text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { Address, BlendFactor, BlendOp, ColorMask, ComparisonFunc, CullMode, DynamicStateFlagBit, Filter, Format, FormatInfos, FormatType, GetTypeSize, PolygonMode, PrimitiveMode, ShadeModel, ShaderStageFlagBit, StencilOp, Type, DescriptorType, SamplerInfo, MemoryAccessBit, } from '../../cocos/core/gfx/base/define'; import { RenderPassStage, RenderPriority, SetIndex } from '../../cocos/core/pipeline/define'; import { murmurhash2_32_gc } from '../../cocos/core/utils/murmurhash2_gc'; import { Sampler } from '../../cocos/core/gfx/base/states/sampler'; const typeMap: Record<string, Type | string> = {}; typeMap[typeMap.bool = Type.BOOL] = 'bool'; typeMap[typeMap.bvec2 = Type.BOOL2] = 'bvec2'; typeMap[typeMap.bvec3 = Type.BOOL3] = 'bvec3'; typeMap[typeMap.bvec4 = Type.BOOL4] = 'bvec4'; typeMap[typeMap.int = Type.INT] = 'int'; typeMap[typeMap.ivec2 = Type.INT2] = 'ivec2'; typeMap[typeMap.ivec3 = Type.INT3] = 'ivec3'; typeMap[typeMap.ivec4 = Type.INT4] = 'ivec4'; typeMap[typeMap.uint = Type.UINT] = 'uint'; typeMap[typeMap.uvec2 = Type.UINT2] = 'uvec2'; typeMap[typeMap.uvec3 = Type.UINT3] = 'uvec3'; typeMap[typeMap.uvec4 = Type.UINT4] = 'uvec4'; typeMap[typeMap.float = Type.FLOAT] = 'float'; typeMap[typeMap.vec2 = Type.FLOAT2] = 'vec2'; typeMap[typeMap.vec3 = Type.FLOAT3] = 'vec3'; typeMap[typeMap.vec4 = Type.FLOAT4] = 'vec4'; typeMap[typeMap.mat2 = Type.MAT2] = 'mat2'; typeMap[typeMap.mat3 = Type.MAT3] = 'mat3'; typeMap[typeMap.mat4 = Type.MAT4] = 'mat4'; typeMap[typeMap.mat2x3 = Type.MAT2X3] = 'mat2x3'; typeMap[typeMap.mat2x4 = Type.MAT2X4] = 'mat2x4'; typeMap[typeMap.mat3x2 = Type.MAT3X2] = 'mat3x2'; typeMap[typeMap.mat3x4 = Type.MAT3X4] = 'mat3x4'; typeMap[typeMap.mat4x2 = Type.MAT4X2] = 'mat4x2'; typeMap[typeMap.mat4x3 = Type.MAT4X3] = 'mat4x3'; typeMap[typeMap.sampler1D = Type.SAMPLER1D] = 'sampler1D'; typeMap[typeMap.sampler1DArray = Type.SAMPLER1D_ARRAY] = 'sampler1DArray'; typeMap[typeMap.sampler2D = Type.SAMPLER2D] = 'sampler2D'; typeMap[typeMap.sampler2DArray = Type.SAMPLER2D_ARRAY] = 'sampler2DArray'; typeMap[typeMap.sampler3D = Type.SAMPLER3D] = 'sampler3D'; typeMap[typeMap.samplerCube = Type.SAMPLER_CUBE] = 'samplerCube'; typeMap[typeMap.sampler = Type.SAMPLER] = 'sampler'; typeMap[typeMap.texture1D = Type.TEXTURE1D] = 'texture1D'; typeMap[typeMap.texture1DArray = Type.TEXTURE1D_ARRAY] = 'texture1DArray'; typeMap[typeMap.texture2D = Type.TEXTURE2D] = 'texture2D'; typeMap[typeMap.texture2DArray = Type.TEXTURE2D_ARRAY] = 'texture2DArray'; typeMap[typeMap.texture3D = Type.TEXTURE3D] = 'texture3D'; typeMap[typeMap.textureCube = Type.TEXTURE_CUBE] = 'textureCube'; typeMap[typeMap.image1D = Type.IMAGE1D] = 'image1D'; typeMap[typeMap.image1DArray = Type.IMAGE1D_ARRAY] = 'image1DArray'; typeMap[typeMap.image2D = Type.IMAGE2D] = 'image2D'; typeMap[typeMap.image2DArray = Type.IMAGE2D_ARRAY] = 'image2DArray'; typeMap[typeMap.image3D = Type.IMAGE3D] = 'image3D'; typeMap[typeMap.imageCube = Type.IMAGE_CUBE] = 'imageCube'; typeMap[typeMap.subpassInput = Type.SUBPASS_INPUT] = 'subpassInput'; // variations typeMap.int8_t = Type.INT; typeMap.i8vec2 = Type.INT2; typeMap.i8vec3 = Type.INT3; typeMap.i8vec4 = Type.INT4; typeMap.uint8_t = Type.UINT; typeMap.u8vec2 = Type.UINT2; typeMap.u8vec3 = Type.UINT3; typeMap.u8vec4 = Type.UINT4; typeMap.int16_t = Type.INT; typeMap.i16vec2 = Type.INT2; typeMap.i16vec3 = Type.INT3; typeMap.i16vec4 = Type.INT4; typeMap.uint16_t = Type.INT; typeMap.u16vec2 = Type.UINT2; typeMap.u16vec3 = Type.UINT3; typeMap.u16vec4 = Type.UINT4; typeMap.float16_t = Type.FLOAT; typeMap.f16vec2 = Type.FLOAT2; typeMap.f16vec3 = Type.FLOAT3; typeMap.f16vec4 = Type.FLOAT4; typeMap.mat2x2 = Type.MAT2; typeMap.mat3x3 = Type.MAT3; typeMap.mat4x4 = Type.MAT4; typeMap.isampler1D = Type.SAMPLER1D; typeMap.usampler1D = Type.SAMPLER1D; typeMap.sampler1DShadow = Type.SAMPLER1D; typeMap.isampler1DArray = Type.SAMPLER1D_ARRAY; typeMap.usampler1DArray = Type.SAMPLER1D_ARRAY; typeMap.sampler1DArrayShadow = Type.SAMPLER1D_ARRAY; typeMap.isampler2D = Type.SAMPLER2D; typeMap.usampler2D = Type.SAMPLER2D; typeMap.sampler2DShadow = Type.SAMPLER2D; typeMap.isampler2DArray = Type.SAMPLER2D_ARRAY; typeMap.usampler2DArray = Type.SAMPLER2D_ARRAY; typeMap.sampler2DArrayShadow = Type.SAMPLER2D_ARRAY; typeMap.isampler3D = Type.SAMPLER3D; typeMap.usampler3D = Type.SAMPLER3D; typeMap.isamplerCube = Type.SAMPLER_CUBE; typeMap.usamplerCube = Type.SAMPLER_CUBE; typeMap.samplerCubeShadow = Type.SAMPLER_CUBE; const isSampler = (type) => type >= Type.SAMPLER1D; const isPaddedMatrix = (type) => type >= Type.MAT2 && type < Type.MAT4; const formatMap = { bool: Format.R8, bvec2: Format.RG8, bvec3: Format.RGB8, bvec4: Format.RGBA8, int: Format.R32I, ivec2: Format.RG32I, ivec3: Format.RGB32I, ivec4: Format.RGBA32I, uint: Format.R32UI, uvec2: Format.RG32UI, uvec3: Format.RGB32UI, uvec4: Format.RGBA32UI, float: Format.R32F, vec2: Format.RG32F, vec3: Format.RGB32F, vec4: Format.RGBA32F, int8_t: Format.R8I, i8vec2: Format.RG8I, i8vec3: Format.RGB8I, i8vec4: Format.RGBA8I, uint8_t: Format.R8UI, u8vec2: Format.RG8UI, u8vec3: Format.RGB8UI, u8vec4: Format.RGBA8UI, int16_t: Format.R16I, i16vec2: Format.RG16I, i16vec3: Format.RGB16I, i16vec4: Format.RGBA16I, uint16_t: Format.R16UI, u16vec2: Format.RG16UI, u16vec3: Format.RGB16UI, u16vec4: Format.RGBA16UI, float16_t: Format.R16F, f16vec2: Format.RG16F, f16vec3: Format.RGB16F, f16vec4: Format.RGBA16F, // no suitable conversions: mat2: Format.RGBA32F, mat3: Format.RGBA32F, mat4: Format.RGBA32F, mat2x2: Format.RGBA32F, mat3x3: Format.RGBA32F, mat4x4: Format.RGBA32F, mat2x3: Format.RGBA32F, mat2x4: Format.RGBA32F, mat3x2: Format.RGBA32F, mat3x4: Format.RGBA32F, mat4x2: Format.RGBA32F, mat4x3: Format.RGBA32F, }; const getFormat = (name: string) => Format[name.toUpperCase()]; const getShaderStage = (name: string) => ShaderStageFlagBit[name.toUpperCase()]; const getDescriptorType = (name: string) => DescriptorType[name.toUpperCase()]; const isNormalized = (format: string) => { const type = FormatInfos[format] && FormatInfos[format].type; return type === FormatType.UNORM || type === FormatType.SNORM; }; const getMemoryAccessFlag = (access: string) => { if (access === 'writeonly') { return MemoryAccessBit.WRITE_ONLY; } if (access === 'readonly') { return MemoryAccessBit.READ_ONLY; } return MemoryAccessBit.READ_WRITE; }; const passParams = { // color mask NONE: ColorMask.NONE, R: ColorMask.R, G: ColorMask.G, B: ColorMask.B, A: ColorMask.A, RG: ColorMask.R | ColorMask.G, RB: ColorMask.R | ColorMask.B, RA: ColorMask.R | ColorMask.A, GB: ColorMask.G | ColorMask.B, GA: ColorMask.G | ColorMask.A, BA: ColorMask.B | ColorMask.A, RGB: ColorMask.R | ColorMask.G | ColorMask.B, RGA: ColorMask.R | ColorMask.G | ColorMask.A, RBA: ColorMask.R | ColorMask.B | ColorMask.A, GBA: ColorMask.G | ColorMask.B | ColorMask.A, ALL: ColorMask.ALL, // blend operation ADD: BlendOp.ADD, SUB: BlendOp.SUB, REV_SUB: BlendOp.REV_SUB, MIN: BlendOp.MIN, MAX: BlendOp.MAX, // blend factor ZERO: BlendFactor.ZERO, ONE: BlendFactor.ONE, SRC_ALPHA: BlendFactor.SRC_ALPHA, DST_ALPHA: BlendFactor.DST_ALPHA, ONE_MINUS_SRC_ALPHA: BlendFactor.ONE_MINUS_SRC_ALPHA, ONE_MINUS_DST_ALPHA: BlendFactor.ONE_MINUS_DST_ALPHA, SRC_COLOR: BlendFactor.SRC_COLOR, DST_COLOR: BlendFactor.DST_COLOR, ONE_MINUS_SRC_COLOR: BlendFactor.ONE_MINUS_SRC_COLOR, ONE_MINUS_DST_COLOR: BlendFactor.ONE_MINUS_DST_COLOR, SRC_ALPHA_SATURATE: BlendFactor.SRC_ALPHA_SATURATE, CONSTANT_COLOR: BlendFactor.CONSTANT_COLOR, ONE_MINUS_CONSTANT_COLOR: BlendFactor.ONE_MINUS_CONSTANT_COLOR, CONSTANT_ALPHA: BlendFactor.CONSTANT_ALPHA, ONE_MINUS_CONSTANT_ALPHA: BlendFactor.ONE_MINUS_CONSTANT_ALPHA, // stencil operation // ZERO: StencilOp.ZERO, // duplicate, safely removed because enum value is(and always will be) the same KEEP: StencilOp.KEEP, REPLACE: StencilOp.REPLACE, INCR: StencilOp.INCR, DECR: StencilOp.DECR, INVERT: StencilOp.INVERT, INCR_WRAP: StencilOp.INCR_WRAP, DECR_WRAP: StencilOp.DECR_WRAP, // comparison function NEVER: ComparisonFunc.NEVER, LESS: ComparisonFunc.LESS, EQUAL: ComparisonFunc.EQUAL, LESS_EQUAL: ComparisonFunc.LESS_EQUAL, GREATER: ComparisonFunc.GREATER, NOT_EQUAL: ComparisonFunc.NOT_EQUAL, GREATER_EQUAL: ComparisonFunc.GREATER_EQUAL, ALWAYS: ComparisonFunc.ALWAYS, // cull mode // NONE: CullMode.NONE, // duplicate, safely removed because enum value is(and always will be) the same FRONT: CullMode.FRONT, BACK: CullMode.BACK, // shade mode GOURAND: ShadeModel.GOURAND, FLAT: ShadeModel.FLAT, // polygon mode FILL: PolygonMode.FILL, LINE: PolygonMode.LINE, POINT: PolygonMode.POINT, // primitive mode POINT_LIST: PrimitiveMode.POINT_LIST, LINE_LIST: PrimitiveMode.LINE_LIST, LINE_STRIP: PrimitiveMode.LINE_STRIP, LINE_LOOP: PrimitiveMode.LINE_LOOP, TRIANGLE_LIST: PrimitiveMode.TRIANGLE_LIST, TRIANGLE_STRIP: PrimitiveMode.TRIANGLE_STRIP, TRIANGLE_FAN: PrimitiveMode.TRIANGLE_FAN, LINE_LIST_ADJACENCY: PrimitiveMode.LINE_LIST_ADJACENCY, LINE_STRIP_ADJACENCY: PrimitiveMode.LINE_STRIP_ADJACENCY, TRIANGLE_LIST_ADJACENCY: PrimitiveMode.TRIANGLE_LIST_ADJACENCY, TRIANGLE_STRIP_ADJACENCY: PrimitiveMode.TRIANGLE_STRIP_ADJACENCY, TRIANGLE_PATCH_ADJACENCY: PrimitiveMode.TRIANGLE_PATCH_ADJACENCY, QUAD_PATCH_LIST: PrimitiveMode.QUAD_PATCH_LIST, ISO_LINE_LIST: PrimitiveMode.ISO_LINE_LIST, // POINT: Filter.POINT, // duplicate, safely removed because enum value is(and always will be) the same LINEAR: Filter.LINEAR, ANISOTROPIC: Filter.ANISOTROPIC, WRAP: Address.WRAP, MIRROR: Address.MIRROR, CLAMP: Address.CLAMP, BORDER: Address.BORDER, LINE_WIDTH: DynamicStateFlagBit.LINE_WIDTH, DEPTH_BIAS: DynamicStateFlagBit.DEPTH_BIAS, BLEND_CONSTANTS: DynamicStateFlagBit.BLEND_CONSTANTS, DEPTH_BOUNDS: DynamicStateFlagBit.DEPTH_BOUNDS, STENCIL_WRITE_MASK: DynamicStateFlagBit.STENCIL_WRITE_MASK, STENCIL_COMPARE_MASK: DynamicStateFlagBit.STENCIL_COMPARE_MASK, TRUE: true, FALSE: false, }; Object.assign(passParams, RenderPassStage); // for structural type checking // an 'any' key will check against all elements defined in that object // a key start with '$' means its essential, and can't be undefined const effectStructure = { $techniques: [ { $passes: [ { depthStencilState: {}, rasterizerState: {}, blendState: { targets: [{}] }, properties: { any: { sampler: {}, editor: {} } }, migrations: { properties: { any: {} }, macros: { any: {} } }, embeddedMacros: {}, }, ], }, ], }; export { murmurhash2_32_gc, Sampler, SamplerInfo, effectStructure, isSampler, typeMap, formatMap, getFormat, getShaderStage, getDescriptorType, isNormalized, isPaddedMatrix, getMemoryAccessFlag, passParams, SetIndex, RenderPriority, GetTypeSize, };
the_stack
import { VirtualCell, VirtualData, VirtualNode } from '../virtual-util'; import { adjustRendered, estimateHeight, getVirtualHeight, initReadNodes, populateNodeData, processRecords } from '../virtual-util'; import { mockPlatform } from '../../../util/mock-providers'; describe('VirtualScroll', () => { beforeEach(() => { records = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; cells = []; nodes = []; headerFn = null; footerFn = null; var viewportWidth = 300; data = { viewWidth: viewportWidth, viewHeight: 600, itmWidth: viewportWidth, itmHeight: HEIGHT_ITEM, hdrWidth: viewportWidth, hdrHeight: HEIGHT_HEADER, ftrWidth: viewportWidth, ftrHeight: HEIGHT_FOOTER }; window.getComputedStyle = function () { var styles: any = { marginTop: '0px', marginRight: '0px', marginBottom: '0px', marginLeft: '0px' }; return styles; }; }); describe('estimateHeight', () => { it('should return zero when no records', () => { const h = estimateHeight(0, undefined, 100, .25); expect(h).toEqual(0); }); }); describe('processRecords', () => { it('should load data for 100% width items', () => { records = [0, 1, 2, 3, 4]; let stopAtHeight = 200; processRecords(stopAtHeight, records, cells, headerFn, footerFn, data); expect(cells.length).toBe(4); expect(cells[0].record).toBe(0); expect(cells[0].row).toBe(0); expect(cells[0].top).toBe(HEIGHT_ITEM * 0); expect(cells[0].height).toBe(HEIGHT_ITEM); expect(cells[0].data).toBeUndefined(); expect(cells[0].tmpl).toBe(TEMPLATE_ITEM); expect(cells[1].row).toBe(1); expect(cells[1].top).toBe(HEIGHT_ITEM * 1); expect(cells[1].height).toBe(HEIGHT_ITEM); expect(cells[2].row).toBe(2); expect(cells[2].top).toBe(HEIGHT_ITEM * 2); expect(cells[2].height).toBe(HEIGHT_ITEM); expect(cells[3].row).toBe(3); expect(cells[3].top).toBe(HEIGHT_ITEM * 3); expect(cells[3].height).toBe(HEIGHT_ITEM); }); it('should load data for 30% width items', () => { records = [0, 1, 2, 3, 4]; let stopAtHeight = 1000; data.viewWidth = 300; data.itmWidth = 90; // 30%, 3 per row data.hdrWidth = data.viewWidth; // 100%, 1 per row data.ftrWidth = data.viewWidth; // 100%, 1 per row headerFn = function (record: any) { return (record === 0) ? 'Header' : null; }; footerFn = function (record: any) { return (record === 4) ? 'Footer' : null; }; processRecords(stopAtHeight, records, cells, headerFn, footerFn, data); expect(cells.length).toBe(7); expect(cells[0].row).toBe(0); expect(cells[0].width).toBe(data.viewWidth); expect(cells[0].height).toBe(HEIGHT_HEADER); expect(cells[0].top).toBe(0); expect(cells[0].left).toBe(0); expect(cells[0].tmpl).toBe(TEMPLATE_HEADER); expect(cells[0].data).toBe('Header'); expect(cells[0].record).toBe(0); expect(cells[1].row).toBe(1); expect(cells[1].width).toBe(data.itmWidth); expect(cells[1].height).toBe(HEIGHT_ITEM); expect(cells[1].top).toBe(HEIGHT_HEADER); expect(cells[1].left).toBe(data.itmWidth * 0); expect(cells[1].tmpl).toBe(TEMPLATE_ITEM); expect(cells[1].data).toBeUndefined(); expect(cells[1].record).toBe(0); expect(cells[2].row).toBe(1); expect(cells[2].width).toBe(data.itmWidth); expect(cells[2].height).toBe(HEIGHT_ITEM); expect(cells[2].top).toBe(HEIGHT_HEADER); expect(cells[2].left).toBe(data.itmWidth * 1); expect(cells[2].tmpl).toBe(TEMPLATE_ITEM); expect(cells[2].data).toBeUndefined(); expect(cells[2].record).toBe(1); expect(cells[3].row).toBe(1); expect(cells[3].width).toBe(data.itmWidth); expect(cells[3].height).toBe(HEIGHT_ITEM); expect(cells[3].top).toBe(HEIGHT_HEADER); expect(cells[3].left).toBe(data.itmWidth * 2); expect(cells[3].tmpl).toBe(TEMPLATE_ITEM); expect(cells[3].data).toBeUndefined(); expect(cells[3].record).toBe(2); expect(cells[4].row).toBe(2); expect(cells[4].width).toBe(data.itmWidth); expect(cells[4].height).toBe(HEIGHT_ITEM); expect(cells[4].top).toBe(HEIGHT_HEADER + HEIGHT_ITEM); expect(cells[4].left).toBe(data.itmWidth * 0); expect(cells[4].tmpl).toBe(TEMPLATE_ITEM); expect(cells[4].data).toBeUndefined(); expect(cells[4].record).toBe(3); expect(cells[5].row).toBe(2); expect(cells[5].width).toBe(data.itmWidth); expect(cells[5].height).toBe(HEIGHT_ITEM); expect(cells[5].top).toBe(HEIGHT_HEADER + HEIGHT_ITEM); expect(cells[5].left).toBe(data.itmWidth * 1); expect(cells[5].tmpl).toBe(TEMPLATE_ITEM); expect(cells[5].data).toBeUndefined(); expect(cells[5].record).toBe(4); expect(cells[6].row).toBe(3); expect(cells[6].width).toBe(data.ftrWidth); expect(cells[6].height).toBe(HEIGHT_FOOTER); expect(cells[6].top).toBe(HEIGHT_HEADER + HEIGHT_ITEM + HEIGHT_ITEM); expect(cells[6].left).toBe(0); expect(cells[6].tmpl).toBe(TEMPLATE_FOOTER); expect(cells[6].data).toBe('Footer'); expect(cells[6].record).toBe(4); }); it('should process more data', () => { records = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let stopAtHeight = 100; data.viewWidth = 200; data.itmWidth = 90; // 2 per row data.hdrWidth = data.viewWidth; // 100%, 1 per row headerFn = function (record: any) { return (record === 0) ? 'Header' : null; }; processRecords(stopAtHeight, records, cells, headerFn, footerFn, data); expect(cells.length).toBe(5); expect(cells[0].row).toBe(0); expect(cells[0].top).toBe(0); expect(cells[0].left).toBe(0); expect(cells[0].tmpl).toBe(TEMPLATE_HEADER); expect(cells[0].record).toBe(0); expect(cells[1].row).toBe(1); expect(cells[1].top).toBe(HEIGHT_HEADER); expect(cells[1].left).toBe(data.itmWidth * 0); expect(cells[1].tmpl).toBe(TEMPLATE_ITEM); expect(cells[1].record).toBe(0); stopAtHeight = 150; processRecords(stopAtHeight, records, cells, headerFn, footerFn, data); expect(cells[2].row).toBe(1); expect(cells[2].top).toBe(HEIGHT_HEADER); expect(cells[2].left).toBe(data.itmWidth * 1); expect(cells[2].tmpl).toBe(TEMPLATE_ITEM); expect(cells[2].record).toBe(1); expect(cells.length).toBe(9); expect(cells[3].row).toBe(2); expect(cells[3].top).toBe(HEIGHT_HEADER + HEIGHT_ITEM); expect(cells[3].left).toBe(data.itmWidth * 0); expect(cells[3].tmpl).toBe(TEMPLATE_ITEM); expect(cells[3].record).toBe(2); stopAtHeight = 20000; processRecords(stopAtHeight, records, cells, headerFn, footerFn, data); expect(cells.length).toBe(11); expect(cells[5].row).toBe(3); expect(cells[5].top).toBe(HEIGHT_HEADER + HEIGHT_ITEM + HEIGHT_ITEM); expect(cells[5].left).toBe(data.itmWidth * 0); expect(cells[5].tmpl).toBe(TEMPLATE_ITEM); expect(cells[5].record).toBe(4); }); }); describe('populateNodeData', () => { it('should set no nodes when no records', () => { nodes = []; records = []; let startCellIndex = 0; let endCellIndex = 0; populateNodeData(startCellIndex, endCellIndex, true, cells, records, nodes, viewContainer, itmTmp, hdrTmp, ftrTmp); expect(nodes.length).toBe(0); }); // it('should skip already rendered, and create nodes', () => { // cells = [ // { row: 0, tmpl: TEMPLATE_ITEM }, // { row: 1, tmpl: TEMPLATE_ITEM }, // { row: 2, tmpl: TEMPLATE_HEADER }, // { row: 3, tmpl: TEMPLATE_ITEM }, // { row: 4, tmpl: TEMPLATE_FOOTER }, // { row: 5, tmpl: TEMPLATE_ITEM }, // { row: 6, tmpl: TEMPLATE_ITEM, reads: 0 } // ]; // nodes = [ // { cell: 0, tmpl: TEMPLATE_ITEM, view: getView() }, // { cell: 1, tmpl: TEMPLATE_ITEM, view: getView() }, // { cell: 2, tmpl: TEMPLATE_HEADER, view: getView() }, // { cell: 3, tmpl: TEMPLATE_ITEM, view: getView() }, // ]; // let startCellIndex = 2; // let endCellIndex = 5; // populateNodeData(startCellIndex, endCellIndex, true, // cells, records, nodes, viewContainer, // itmTmp, hdrTmp, ftrTmp); // expect(nodes.length).toBe(5); // // first stays unchanged // expect(nodes[0].cell).toBe(0); // expect(nodes[1].cell).toBe(5); // expect(nodes[2].cell).toBe(2); // expect(nodes[3].cell).toBe(3); // expect(nodes[4].cell).toBe(4); // }); it('should create nodes', () => { cells = [ { row: 0, tmpl: TEMPLATE_ITEM }, { row: 1, tmpl: TEMPLATE_ITEM }, { row: 2, tmpl: TEMPLATE_HEADER }, { row: 3, tmpl: TEMPLATE_ITEM }, { row: 4, tmpl: TEMPLATE_FOOTER }, { row: 5, tmpl: TEMPLATE_ITEM }, { row: 6, tmpl: TEMPLATE_ITEM } ]; let startCellIndex = 2; let endCellIndex = 4; populateNodeData(startCellIndex, endCellIndex, true, cells, records, nodes, viewContainer, itmTmp, hdrTmp, ftrTmp); expect(nodes.length).toBe(3); expect(nodes[0].cell).toBe(2); expect(nodes[1].cell).toBe(3); expect(nodes[2].cell).toBe(4); expect(nodes[0].tmpl).toBe(TEMPLATE_HEADER); expect(nodes[1].tmpl).toBe(TEMPLATE_ITEM); expect(nodes[2].tmpl).toBe(TEMPLATE_FOOTER); }); }); describe('initReadNodes', () => { it('should get all the row heights w/ 30% width rows', () => { let firstTop = 13; nodes = [ { cell: 0, tmpl: TEMPLATE_HEADER, view: getView(data.viewWidth, HEIGHT_HEADER, firstTop, 0) }, { cell: 1, tmpl: TEMPLATE_ITEM, view: getView(90, HEIGHT_ITEM, HEIGHT_HEADER + firstTop, 0) }, { cell: 2, tmpl: TEMPLATE_ITEM, view: getView(90, HEIGHT_ITEM, HEIGHT_HEADER + firstTop, 90) }, { cell: 3, tmpl: TEMPLATE_ITEM, view: getView(90, HEIGHT_ITEM, HEIGHT_HEADER + firstTop, 180) }, { cell: 4, tmpl: TEMPLATE_ITEM, view: getView(90, HEIGHT_ITEM, HEIGHT_HEADER + HEIGHT_ITEM + firstTop, 0) }, { cell: 5, tmpl: TEMPLATE_FOOTER, view: getView(data.viewWidth, HEIGHT_FOOTER, HEIGHT_HEADER + HEIGHT_ITEM + HEIGHT_ITEM + firstTop, 0) }, ]; cells = [ { row: 0, tmpl: TEMPLATE_HEADER, reads: 0 }, { row: 0, tmpl: TEMPLATE_ITEM, reads: 0 }, { row: 0, tmpl: TEMPLATE_ITEM, reads: 0 }, { row: 0, tmpl: TEMPLATE_ITEM, reads: 0 }, { row: 0, tmpl: TEMPLATE_ITEM, reads: 0 }, { row: 0, tmpl: TEMPLATE_FOOTER, reads: 0 }, ]; initReadNodes(mockPlatform(), nodes, cells, data); expect(cells[0].top).toBe(firstTop); expect(cells[0].left).toBe(0); expect(cells[0].width).toBe(data.viewWidth); expect(cells[0].height).toBe(HEIGHT_HEADER); expect(cells[1].top).toBe(firstTop + HEIGHT_HEADER); expect(cells[1].left).toBe(0); expect(cells[1].width).toBe(90); expect(cells[1].height).toBe(HEIGHT_ITEM); expect(cells[2].top).toBe(firstTop + HEIGHT_HEADER); expect(cells[2].left).toBe(data.itmWidth); expect(cells[2].width).toBe(90); expect(cells[2].height).toBe(HEIGHT_ITEM); expect(cells[3].top).toBe(firstTop + HEIGHT_HEADER); expect(cells[3].left).toBe(data.itmWidth * 2); expect(cells[3].width).toBe(90); expect(cells[3].height).toBe(HEIGHT_ITEM); expect(cells[4].top).toBe(firstTop + HEIGHT_HEADER + HEIGHT_ITEM); expect(cells[4].left).toBe(0); expect(cells[4].width).toBe(90); expect(cells[4].height).toBe(HEIGHT_ITEM); expect(cells[5].top).toBe(firstTop + HEIGHT_HEADER + HEIGHT_ITEM + HEIGHT_ITEM); expect(cells[5].left).toBe(0); expect(cells[5].width).toBe(data.viewWidth); expect(cells[5].height).toBe(HEIGHT_FOOTER); }); it('should get all the row heights w/ all 100% width rows', () => { nodes = [ { cell: 0, tmpl: TEMPLATE_HEADER, view: getView(data.viewWidth, HEIGHT_HEADER, 0, 0) }, { cell: 1, tmpl: TEMPLATE_ITEM, view: getView(data.viewWidth, HEIGHT_ITEM, HEIGHT_HEADER, 0) }, { cell: 2, tmpl: TEMPLATE_ITEM, view: getView(data.viewWidth, HEIGHT_ITEM, HEIGHT_HEADER + HEIGHT_ITEM, 0) }, { cell: 3, tmpl: TEMPLATE_ITEM, view: getView(data.viewWidth, HEIGHT_ITEM, HEIGHT_HEADER + HEIGHT_ITEM + HEIGHT_ITEM, 0) }, { cell: 4, tmpl: TEMPLATE_FOOTER, view: getView(data.viewWidth, HEIGHT_FOOTER, HEIGHT_HEADER + HEIGHT_ITEM + HEIGHT_ITEM + HEIGHT_ITEM, 0) }, ]; cells = [ { row: 0, tmpl: TEMPLATE_HEADER, reads: 0 }, { row: 1, tmpl: TEMPLATE_ITEM, reads: 0 }, { row: 2, tmpl: TEMPLATE_ITEM, reads: 0 }, { row: 3, tmpl: TEMPLATE_ITEM, reads: 0 }, { row: 4, tmpl: TEMPLATE_FOOTER, reads: 0 }, ]; initReadNodes(mockPlatform(), nodes, cells, data); expect(cells[0].top).toBe(0); expect(cells[0].height).toBe(HEIGHT_HEADER); expect(cells[0].reads).toBe(1); expect(cells[1].top).toBe(HEIGHT_HEADER); expect(cells[1].height).toBe(HEIGHT_ITEM); expect(cells[2].top).toBe(HEIGHT_HEADER + HEIGHT_ITEM); expect(cells[2].height).toBe(HEIGHT_ITEM); expect(cells[3].top).toBe(HEIGHT_HEADER + HEIGHT_ITEM + HEIGHT_ITEM); expect(cells[3].height).toBe(HEIGHT_ITEM); expect(cells[4].top).toBe(HEIGHT_HEADER + HEIGHT_ITEM + HEIGHT_ITEM + HEIGHT_ITEM); expect(cells[4].height).toBe(HEIGHT_FOOTER); }); }); describe('adjustRendered', () => { it('should adjust when all the way to the top, scrolling down', () => { for (var i = 0; i < 100; i++) { cells.push({ top: i, height: 1, row: i }); } data.scrollDiff = 1; data.viewHeight = 20; data.itmHeight = 1; data.renderHeight = 40; data.topViewCell = 0; data.bottomViewCell = 19; adjustRendered(cells, data); expect(data.topCell).toBe(0); expect(data.bottomCell).toBe(38); }); it('should adjust when in the middle, scrolling down', () => { for (var i = 0; i < 100; i++) { cells.push({ top: i, height: 1, row: i }); } data.scrollDiff = 1; data.viewHeight = 20; data.itmHeight = 1; data.renderHeight = 40; data.topViewCell = 30; data.bottomViewCell = 49; adjustRendered(cells, data); expect(data.topCell).toBe(27); expect(data.bottomCell).toBe(65); }); it('should adjust when all the way to the bottom, scrolling down', () => { for (var i = 0; i < 100; i++) { cells.push({ top: i, height: 1, row: i }); } data.scrollDiff = 1; data.viewHeight = 20; data.itmHeight = 1; data.renderHeight = 40; data.topViewCell = 80; data.bottomViewCell = 99; adjustRendered(cells, data); expect(data.topCell).toBe(61); expect(data.bottomCell).toBe(99); }); it('should adjust when all the way to the bottom, scrolling up', () => { for (var i = 0; i < 100; i++) { cells.push({ top: i, height: 1, row: i }); } data.scrollDiff = -1; data.viewHeight = 20; data.itmHeight = 1; data.renderHeight = 40; data.topViewCell = 80; data.bottomViewCell = 99; adjustRendered(cells, data); expect(data.topCell).toBe(61); expect(data.bottomCell).toBe(99); }); }); describe('getVirtualHeight', () => { it('should return known height from last cell/record', () => { let totalRecords = 1000; let lastCell: VirtualCell = { record: 999, tmpl: TEMPLATE_ITEM, row: 800, top: 900, height: 45 }; let virtualHeight = getVirtualHeight(totalRecords, lastCell); expect(virtualHeight).toBe(945); }); it('should guess the height from 1 known cell', () => { let totalRecords = 100; let lastCell: VirtualCell = { record: 0, tmpl: TEMPLATE_ITEM, row: 0, top: 0, height: 50 }; let virtualHeight = getVirtualHeight(totalRecords, lastCell); expect(virtualHeight).toBe(5000); }); it('should guess the height from 1/2 known cells', () => { let totalRecords = 100; let lastCell: VirtualCell = { record: 49, tmpl: TEMPLATE_ITEM, row: 0, top: 2450, height: 50 }; let virtualHeight = getVirtualHeight(totalRecords, lastCell); expect(virtualHeight).toBe(5000); }); it('should guess the height from 99/100 known cells', () => { let totalRecords = 100; let lastCell: VirtualCell = { record: 98, tmpl: TEMPLATE_ITEM, row: 0, top: 4900, height: 50 }; let virtualHeight = getVirtualHeight(totalRecords, lastCell); expect(virtualHeight).toBe(5000); }); }); let records: any[]; let cells: VirtualCell[]; let nodes: VirtualNode[]; let headerFn: Function; let footerFn: Function; let data: VirtualData; let itmTmp: any = {}; let hdrTmp: any = {}; let ftrTmp: any = {}; let viewContainer: any = { createEmbeddedView: function () { return getView(); }, indexOf: function () { return 0; }, clear: function () { }, remove: function () { }, }; function getView(width?: number, height?: number, top?: number, left?: number): any { return { context: {}, rootNodes: [{ nodeType: 1, offsetWidth: width, offsetHeight: height, offsetTop: top, offsetLeft: left, clientTop: top, clientLeft: left, style: { top: '', left: '' }, classList: { add: function () { }, remove: function () { } }, setAttribute: function () { }, innerHTML: '', }] }; } }); const TEMPLATE_ITEM = 0; const TEMPLATE_HEADER = 1; const TEMPLATE_FOOTER = 2; const HEIGHT_HEADER = 50; const HEIGHT_ITEM = 45; const HEIGHT_FOOTER = 32;
the_stack
import {context} from '@actions/github'; import {GitHub} from '@actions/github/lib/utils'; import type {GraphQlQueryResponseData} from '@octokit/graphql'; import {GraphqlResponseError} from '@octokit/graphql'; import type {RequestParameters} from '@octokit/graphql/dist-types/types'; // eslint-disable-next-line import/named import {GetResponseTypeFromEndpointMethod} from '@octokit/types'; import {groupConsoleLog, info} from '../logger'; const octokit = new GitHub(); type IssuesCreateCommentResponse = GetResponseTypeFromEndpointMethod< typeof octokit.rest.issues.createComment >; type IssuesUpdateResponse = GetResponseTypeFromEndpointMethod<typeof octokit.rest.issues.update>; type IssuesLockResponse = GetResponseTypeFromEndpointMethod<typeof octokit.rest.issues.lock>; type IssuesUnlockResponse = GetResponseTypeFromEndpointMethod<typeof octokit.rest.issues.unlock>; type IssueState = 'open' | 'closed'; type LockReason = 'off-topic' | 'too heated' | 'resolved' | 'spam' | undefined; const snakeCase = (str: string) => { return str.replace(/-/g, '_').replace(/ /g, '_'); }; interface IIssue { readonly githubClient: InstanceType<typeof GitHub>; readonly id: string; readonly number: number; } interface IIssueProcessor extends IIssue { createComment(body: string): Promise<void>; updateState(state: IssueState): Promise<void>; lock(reason: LockReason): Promise<void>; unlock(): Promise<void>; markPullRequestReadyForReview(): Promise<void>; convertPullRequestToDraft(): Promise<void>; addDiscussionComment(body: string): Promise<string>; lockLockable(reason: LockReason): Promise<void>; unlockLockable(): Promise<void>; markDiscussionCommentAsAnswer(id: string): Promise<void>; } class Issue implements IIssueProcessor { readonly githubClient: InstanceType<typeof GitHub>; readonly id: string; readonly number: number; constructor(githubClient: InstanceType<typeof GitHub>, id: string, number: number) { this.githubClient = githubClient; this.id = id; this.number = number; } async createComment(body: string): Promise<void> { try { const res: IssuesCreateCommentResponse = await this.githubClient.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: body }); groupConsoleLog('IssuesCreateCommentResponse', res); if (res.status === 201) { info(`New comment has been created in issue #${this.number}, ${res.data.html_url}`); return; } else { throw new Error(`IssuesCreateCommentResponse.status: ${res.status}`); } } catch (error) { if (error instanceof Error) { groupConsoleLog('Dump error.stack', error.stack); throw new Error(error.message); } throw new Error('unexpected error'); } } async updateState(state: IssueState): Promise<void> { try { const res: IssuesUpdateResponse = await this.githubClient.rest.issues.update({ owner: context.repo.owner, repo: context.repo.repo, issue_number: this.number, state: state }); groupConsoleLog('IssuesUpdateResponse', res); if (res.status === 200) { if (state === 'closed') { info(`#${this.number} has been closed`); return; } info(`#${this.number} has been reopened`); } else { throw new Error(`IssuesUpdateResponse.status: ${res.status}`); } } catch (error) { if (error instanceof Error) { groupConsoleLog('Dump error.stack', error.stack); throw new Error(error.message); } throw new Error('unexpected error'); } } async lock(reason: LockReason): Promise<void> { try { const res: IssuesLockResponse = await this.githubClient.rest.issues.lock({ owner: context.repo.owner, repo: context.repo.repo, issue_number: this.number, lock_reason: reason || 'resolved' }); groupConsoleLog('IssuesLockResponse', res); if (res.status === 204) { info(`#${this.number} has been locked`); return; } else { throw new Error(`IssuesLockResponse.status: ${res.status}`); } } catch (error) { if (error instanceof Error) { groupConsoleLog('Dump error.stack', error.stack); throw new Error(error.message); } throw new Error('unexpected error'); } } async unlock(): Promise<void> { try { const res: IssuesUnlockResponse = await this.githubClient.rest.issues.unlock({ owner: context.repo.owner, repo: context.repo.repo, issue_number: this.number }); groupConsoleLog('IssuesUnlockResponse', res); if (res.status === 204) { info(`#${this.number} has been unlocked`); return; } else { throw new Error(`IssuesUnlockResponse.status: ${res.status}`); } } catch (error) { if (error instanceof Error) { groupConsoleLog('Dump error.stack', error.stack); throw new Error(error.message); } throw new Error('unexpected error'); } } async markPullRequestReadyForReview(): Promise<void> { const query = ` mutation MarkPullRequestReadyForReview($input: MarkPullRequestReadyForReviewInput!) { __typename markPullRequestReadyForReview(input: $input) { pullRequest { isDraft } } } `; const variables: RequestParameters = { input: { pullRequestId: this.id } }; try { const res: GraphQlQueryResponseData = await this.githubClient.graphql(query, variables); info(`#${this.number} has been marked as ready for review`); groupConsoleLog('GraphQlQueryResponseData', res); } catch (error) { if (error instanceof GraphqlResponseError) { // eslint-disable-next-line @typescript-eslint/no-explicit-any groupConsoleLog('Request failed', error.request as any); throw new Error(error.message); } else { if (error instanceof Error) { groupConsoleLog('Dump error.stack', error.stack); throw new Error(error.message); } throw new Error('unexpected error'); } } } async convertPullRequestToDraft(): Promise<void> { const query = ` mutation ConvertPullRequestToDraft($input: ConvertPullRequestToDraftInput!) { __typename convertPullRequestToDraft(input: $input) { pullRequest { isDraft } } } `; const variables: RequestParameters = { input: { pullRequestId: this.id } }; try { const res: GraphQlQueryResponseData = await this.githubClient.graphql(query, variables); info(`#${this.number} has been converted to draft`); groupConsoleLog('GraphQlQueryResponseData', res); } catch (error) { if (error instanceof GraphqlResponseError) { // eslint-disable-next-line @typescript-eslint/no-explicit-any groupConsoleLog('Request failed', error.request as any); throw new Error(error.message); } else { if (error instanceof Error) { groupConsoleLog('Dump error.stack', error.stack); throw new Error(error.message); } throw new Error('unexpected error'); } } } async addDiscussionComment(body: string): Promise<string> { const query = ` mutation AddDiscussionComment($input: AddDiscussionCommentInput!) { __typename addDiscussionComment(input: $input) { comment { body id url } } } `; const variables: RequestParameters = { input: { discussionId: this.id, body: body } }; try { const res: GraphQlQueryResponseData = await this.githubClient.graphql(query, variables); info(`Add comment to #${this.number}, ${res.addDiscussionComment.comment.url}`); groupConsoleLog('GraphQlQueryResponseData', res); return res.addDiscussionComment.comment.id; } catch (error) { if (error instanceof GraphqlResponseError) { // eslint-disable-next-line @typescript-eslint/no-explicit-any groupConsoleLog('Request failed', error.request as any); throw new Error(error.message); } else { if (error instanceof Error) { groupConsoleLog('Dump error.stack', error.stack); throw new Error(error.message); } throw new Error('unexpected error'); } } } async lockLockable(reason: LockReason): Promise<void> { const query = ` mutation LockLockable($input: LockLockableInput!) { __typename lockLockable(input: $input) { lockedRecord { locked activeLockReason } } } `; const variables: RequestParameters = { input: { lockableId: this.id, lockReason: snakeCase(reason || 'RESOLVED').toUpperCase() } }; try { const res: GraphQlQueryResponseData = await this.githubClient.graphql(query, variables); info(`#${this.number} has been locked`); groupConsoleLog('GraphQlQueryResponseData', res); } catch (error) { if (error instanceof GraphqlResponseError) { // eslint-disable-next-line @typescript-eslint/no-explicit-any groupConsoleLog('Request failed', error.request as any); throw new Error(error.message); } else { if (error instanceof Error) { groupConsoleLog('Dump error.stack', error.stack); throw new Error(error.message); } throw new Error('unexpected error'); } } } async unlockLockable(): Promise<void> { const query = ` mutation UnlockLockable($input: UnlockLockableInput!) { __typename unlockLockable(input: $input) { unlockedRecord { locked } } } `; const variables: RequestParameters = { input: { lockableId: this.id } }; try { const res: GraphQlQueryResponseData = await this.githubClient.graphql(query, variables); info(`#${this.number} has been unlocked`); groupConsoleLog('GraphQlQueryResponseData', res); } catch (error) { if (error instanceof GraphqlResponseError) { // eslint-disable-next-line @typescript-eslint/no-explicit-any groupConsoleLog('Request failed', error.request as any); throw new Error(error.message); } else { if (error instanceof Error) { groupConsoleLog('Dump error.stack', error.stack); throw new Error(error.message); } throw new Error('unexpected error'); } } } async markDiscussionCommentAsAnswer(id: string): Promise<void> { const query = ` mutation MarkDiscussionCommentAsAnswer($input: MarkDiscussionCommentAsAnswerInput!) { __typename markDiscussionCommentAsAnswer(input: $input) { discussion { id } } } `; const variables: RequestParameters = { input: { id: id } }; try { const res: GraphQlQueryResponseData = await this.githubClient.graphql(query, variables); info(`Mark the discussion comment as answer`); groupConsoleLog('GraphQlQueryResponseData', res); } catch (error) { if (error instanceof GraphqlResponseError) { // eslint-disable-next-line @typescript-eslint/no-explicit-any groupConsoleLog('Request failed', error.request as any); throw new Error(error.message); } else { if (error instanceof Error) { groupConsoleLog('Dump error.stack', error.stack); throw new Error(error.message); } throw new Error('unexpected error'); } } } } export {LockReason, IIssueProcessor, Issue};
the_stack
import { describe, it, expect } from "@jest/globals"; import { dataset } from "@rdfjs/dataset"; import { DataFactory } from "n3"; import { IriString, Thing, ThingPersisted, UrlString } from "../interfaces"; import { removeAll, removeUrl, removeBoolean, removeDatetime, removeDate, removeTime, removeDecimal, removeInteger, removeStringEnglish, removeStringWithLocale, removeStringNoLocale, removeLiteral, removeNamedNode, } from "./remove"; import { mockThingFrom } from "./mock"; import { ValidPropertyUrlExpectedError, ValidValueUrlExpectedError, } from "./thing"; import { localNodeSkolemPrefix } from "../rdf.internal"; function getMockThingWithLiteralFor( predicate: IriString, literalValue: string, literalType: | "string" | "integer" | "decimal" | "boolean" | "dateTime" | "date" | "time" ): Thing { return { type: "Subject", url: "https://arbitrary.vocab/subject", predicates: { [predicate]: { literals: { [`http://www.w3.org/2001/XMLSchema#${literalType}`]: [literalValue], }, }, }, }; } function getMockThingWithNamedNode( predicate: IriString, object: IriString ): Thing { return { type: "Subject", url: "https://arbitrary.vocab/subject", predicates: { [predicate]: { namedNodes: [object], }, }, }; } describe("removeAll", () => { it("removes all values for the given Predicate", () => { const thingWithStringAndIri = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Arbitrary string value", "string" ); (thingWithStringAndIri.predicates["https://some.vocab/predicate"] .namedNodes as UrlString[]) = ["https://arbitrary.vocab/predicate"]; const updatedThing = removeAll( thingWithStringAndIri, "https://some.vocab/predicate" ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toBeUndefined(); }); it("accepts Properties as Named Nodes", () => { const thingWithString = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Arbitrary string value", "string" ); const updatedThing = removeAll( thingWithString, DataFactory.namedNode("https://some.vocab/predicate") ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toBeUndefined(); }); it("does not modify the input Thing", () => { const thingWithString = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Arbitrary string value", "string" ); const updatedThing = removeAll( thingWithString, DataFactory.namedNode("https://some.vocab/predicate") ); expect(thingWithString).not.toStrictEqual(updatedThing); expect( thingWithString.predicates["https://some.vocab/predicate"] ).toBeDefined(); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toBeUndefined(); }); it("does nothing if there was nothing to remove", () => { const thingWithString = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Arbitrary string value", "string" ); const updatedThing = removeAll( thingWithString, DataFactory.namedNode("https://some.vocab/other-predicate") ); expect(thingWithString).toStrictEqual(updatedThing); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toBeDefined(); }); it("also works on ThingLocals", () => { const thingLocal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Arbitrary string value", "string" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = removeAll(thingLocal, "https://some.vocab/predicate"); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toBeUndefined(); }); it("removes multiple instances of the same value for the same Predicate", () => { const thingWithDuplicateIri = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://arbitrary.pod/resource#name" ); ( thingWithDuplicateIri.predicates["https://some.vocab/predicate"] .namedNodes as UrlString[] ).push("https://arbitrary.pod/resource#name"); const updatedThing = removeAll( thingWithDuplicateIri, "https://some.vocab/predicate" ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toBeUndefined(); }); it("does not remove Quads with different Predicates", () => { const thingWithIri = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://arbitrary.pod/resource#name" ); (thingWithIri.predicates["https://some-other.vocab/predicate"] as { namedNodes: UrlString[]; }) = { namedNodes: ["https://arbitrary.pod/resource#name"], }; const updatedThing = removeAll( thingWithIri, "https://some.vocab/predicate" ); expect( updatedThing.predicates["https://some-other.vocab/predicate"] ).toBeDefined(); }); it("throws an error when passed something other than a Thing", () => { expect(() => removeAll(null as unknown as Thing, "https://arbitrary.vocab/predicate") ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => removeAll( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url" ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeAll( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url" ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("removeIri", () => { it("removes the given IRI value for the given Predicate", () => { const thingWithIri = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.pod/resource#name" ); const updatedThing = removeUrl( thingWithIri, "https://some.vocab/predicate", "https://some.pod/resource#name" ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual([]); }); it("accepts Properties as Named Nodes", () => { const thingWithIri = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.pod/resource#name" ); const updatedThing = removeUrl( thingWithIri, DataFactory.namedNode("https://some.vocab/predicate"), "https://some.pod/resource#name" ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual([]); }); it("accepts IRI's as Named Nodes", () => { const thingWithIri = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.pod/resource#name" ); const updatedThing = removeUrl( thingWithIri, "https://some.vocab/predicate", DataFactory.namedNode("https://some.pod/resource#name") ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual([]); }); it("does not modify the input Thing", () => { const thingWithIri = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.pod/resource#name" ); const updatedThing = removeUrl( thingWithIri, "https://some.vocab/predicate", "https://some.pod/resource#name" ); expect(thingWithIri).not.toStrictEqual(updatedThing); expect( thingWithIri.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual(["https://some.pod/resource#name"]); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual([]); }); it("does nothing if the URL to remove was not found", () => { const thingWithIri = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.pod/resource#name" ); const updatedThing = removeUrl( thingWithIri, "https://some.vocab/other-predicate", "https://some.pod/other-resource#name" ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toEqual(["https://some.pod/resource#name"]); }); it("also works on ThingLocals", () => { const thingLocal = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.pod/resource#name" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = removeUrl( thingLocal, "https://some.vocab/predicate", "https://some.pod/resource#name" ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual([]); }); it("removes multiple instances of the same IRI for the same Predicate", () => { const thingWithIri = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.pod/resource#name" ); ( thingWithIri.predicates["https://some.vocab/predicate"] .namedNodes as UrlString[] ).push("https://some.pod/resource#name"); const updatedThing = removeUrl( thingWithIri, "https://some.vocab/predicate", "https://some.pod/resource#name" ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual([]); }); it("does not remove Quads with different Predicates or Objects", () => { const thingWithIri = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.pod/resource#name" ); ( thingWithIri.predicates["https://some.vocab/predicate"] .namedNodes as UrlString[] ).push("https://some-other.pod/resource#name"); (thingWithIri.predicates["https://some-other.vocab/predicate"] as { namedNodes: UrlString[]; }) = { namedNodes: ["https://arbitrary.pod/resource#name"], }; const updatedThing = removeUrl( thingWithIri, "https://some.vocab/predicate", "https://some.pod/resource#name" ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual(["https://some-other.pod/resource#name"]); expect( updatedThing.predicates["https://some-other.vocab/predicate"].namedNodes ).toStrictEqual(["https://arbitrary.pod/resource#name"]); }); it("does not remove Quads with non-IRI Objects", () => { const thingWithIri = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Some non-IRI Object", "string" ); (thingWithIri.predicates["https://some.vocab/predicate"] .namedNodes as UrlString[]) = ["https://some.pod/resource#name"]; const updatedThing = removeUrl( thingWithIri, "https://some.vocab/predicate", "https://some.pod/resource#name" ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some non-IRI Object"], }, namedNodes: [], }); }); it("resolves ThingPersisteds", () => { const thingPersisted: ThingPersisted = { type: "Subject", url: "https://some.pod/resource#thing", predicates: {}, }; const thingWithThingPersistedIri = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.pod/resource#thing" ); const updatedThing = removeUrl( thingWithThingPersistedIri, "https://some.vocab/predicate", thingPersisted ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual([]); }); it("throws an error when passed something other than a Thing", () => { expect(() => removeUrl( null as unknown as Thing, "https://arbitrary.vocab/predicate", "https://arbitrary.url" ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => removeUrl( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", "https://arbitrary.url" ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeUrl( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", "https://arbitrary.url" ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); it("throws an error when passed an invalid URL value", () => { expect(() => removeUrl( mockThingFrom("https://arbitrary.pod/resource#thing"), "https://arbitrary.vocab/predicate", "not-a-url" ) ).toThrow("Expected a valid URL value, but received: [not-a-url]."); }); it("throws an instance of ValidValueUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeUrl( mockThingFrom("https://arbitrary.pod/resource#thing"), "https://arbitrary.vocab/predicate", "not-a-url" ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidValueUrlExpectedError); }); }); describe("removeBoolean", () => { it("removes the given boolean value for the given Predicate", () => { const thingWithBoolean = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1", "boolean" ); const updatedThing = removeBoolean( thingWithBoolean, "https://some.vocab/predicate", true ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": [], }); }); it("removes equivalent booleans with different serialisations", () => { const thingWithSerialised1 = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1", "boolean" ); const thingWithSerialised0 = getMockThingWithLiteralFor( "https://some.vocab/predicate", "0", "boolean" ); const thingWithSerialisedTrue = getMockThingWithLiteralFor( "https://some.vocab/predicate", "true", "boolean" ); const thingWithSerialisedFalse = getMockThingWithLiteralFor( "https://some.vocab/predicate", "false", "boolean" ); const updatedThingWithoutSerialised1 = removeBoolean( thingWithSerialised1, "https://some.vocab/predicate", true ); const updatedThingWithoutSerialised0 = removeBoolean( thingWithSerialised0, "https://some.vocab/predicate", false ); const updatedThingWithoutSerialisedTrue = removeBoolean( thingWithSerialisedTrue, "https://some.vocab/predicate", true ); const updatedThingWithoutSerialisedFalse = removeBoolean( thingWithSerialisedFalse, "https://some.vocab/predicate", false ); expect( updatedThingWithoutSerialised1.predicates["https://some.vocab/predicate"] .literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": [], }); expect( updatedThingWithoutSerialised0.predicates["https://some.vocab/predicate"] .literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": [], }); expect( updatedThingWithoutSerialisedTrue.predicates[ "https://some.vocab/predicate" ].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": [], }); expect( updatedThingWithoutSerialisedFalse.predicates[ "https://some.vocab/predicate" ].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": [], }); }); it("accepts Properties as Named Nodes", () => { const thingWithBoolean = getMockThingWithLiteralFor( "https://some.vocab/predicate", "0", "boolean" ); const updatedThing = removeBoolean( thingWithBoolean, DataFactory.namedNode("https://some.vocab/predicate"), false ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": [], }); }); it("does not modify the input Thing", () => { const thingWithBoolean = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1", "boolean" ); const updatedThing = removeBoolean( thingWithBoolean, "https://some.vocab/predicate", true ); expect(thingWithBoolean).not.toStrictEqual(updatedThing); expect( thingWithBoolean.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": ["1"], }); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": [], }); }); it("does nothing if the boolean to remove was not found", () => { const thingWithBoolean = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1", "boolean" ); const updatedThing = removeBoolean( thingWithBoolean, "https://some.vocab/other-predicate", false ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toEqual({ "http://www.w3.org/2001/XMLSchema#boolean": ["1"], }); }); it("also works on ThingLocals", () => { const thingLocal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1", "boolean" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = removeBoolean( thingLocal, "https://some.vocab/predicate", true ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": [], }); }); it("removes multiple instances of the same boolean for the same Predicate", () => { const thingWithDuplicateBoolean = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1", "boolean" ); ( thingWithDuplicateBoolean.predicates["https://some.vocab/predicate"] .literals!["http://www.w3.org/2001/XMLSchema#boolean"] as string[] ).push("1"); const updatedThing = removeBoolean( thingWithDuplicateBoolean, "https://some.vocab/predicate", true ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": [], }); }); it("does not remove Quads with different Predicates or Objects", () => { const thingWithOtherQuads = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1", "boolean" ); ( thingWithOtherQuads.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#boolean" ] as string[] ).push("0"); (thingWithOtherQuads.predicates[ "https://some-other.vocab/predicate" ] as any) = { literals: { "http://www.w3.org/2001/XMLSchema#boolean": ["1"], }, }; const updatedThing = removeBoolean( thingWithOtherQuads, "https://some.vocab/predicate", true ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": ["0"] }); expect( updatedThing.predicates["https://some-other.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": ["1"] }); }); it("does not remove Quads with non-boolean Objects", () => { const thingWithIri = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1", "boolean" ); (thingWithIri.predicates["https://some.vocab/predicate"] .namedNodes as UrlString[]) = ["1"]; const updatedThing = removeBoolean( thingWithIri, "https://some.vocab/predicate", true ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual(["1"]); }); it("throws an error when passed something other than a Thing", () => { expect(() => removeBoolean( null as unknown as Thing, "https://arbitrary.vocab/predicate", true ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => removeBoolean( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", true ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeBoolean( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", true ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("removeDatetime", () => { it("removes the given datetime value for the given Predicate", () => { const thingWithDatetime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12T13:37:42Z", "dateTime" ); const updatedThing = removeDatetime( thingWithDatetime, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#dateTime": [], }); }); it("removes equivalent Datetimes with different serialisations", () => { const thingWithRoundedDatetime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12T13:37:42Z", "dateTime" ); const thingWithSpecificDatetime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12T12:37:42.000+01:00", "dateTime" ); const updatedThingWithoutRoundedDatetime = removeDatetime( thingWithRoundedDatetime, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); const updatedThingWithoutSpecificDatetime = removeDatetime( thingWithSpecificDatetime, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect( updatedThingWithoutRoundedDatetime.predicates[ "https://some.vocab/predicate" ].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#dateTime": [], }); expect( updatedThingWithoutSpecificDatetime.predicates[ "https://some.vocab/predicate" ].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#dateTime": [], }); }); it("accepts Properties as Named Nodes", () => { const thingWithDatetime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12T13:37:42Z", "dateTime" ); const updatedThing = removeDatetime( thingWithDatetime, DataFactory.namedNode("https://some.vocab/predicate"), new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#dateTime": [], }); }); it("does not modify the input Thing", () => { const thingWithDatetime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12T13:37:42Z", "dateTime" ); const updatedThing = removeDatetime( thingWithDatetime, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect(thingWithDatetime).not.toStrictEqual(updatedThing); expect( thingWithDatetime.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#dateTime": ["1990-11-12T13:37:42Z"], }); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#dateTime": [], }); }); it("also works on ThingLocals", () => { const thingLocal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12T13:37:42Z", "dateTime" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = removeDatetime( thingLocal, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#dateTime": [], }); }); it("removes multiple instances of the same datetime for the same Predicate", () => { const thingWithDuplicateDatetime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12T13:37:42Z", "dateTime" ); ( thingWithDuplicateDatetime.predicates["https://some.vocab/predicate"] .literals!["http://www.w3.org/2001/XMLSchema#dateTime"] as string[] ).push("1990-11-12T13:37:42Z"); const updatedThing = removeDatetime( thingWithDuplicateDatetime, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#dateTime": [], }); }); it("does not remove Quads with different Predicates or Objects", () => { const thingWithOtherQuads = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12T13:37:42Z", "dateTime" ); // A different Object: ( thingWithOtherQuads.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#dateTime" ] as string[] ).push("1955-06-08T13:37:42Z"); // An invalid object ( thingWithOtherQuads.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#dateTime" ] as string[] ).push("not-a-datetime"); // A different predicate (thingWithOtherQuads.predicates[ "https://some-other.vocab/predicate" ] as any) = { literals: { "http://www.w3.org/2001/XMLSchema#dateTime": ["1990-11-12T13:37:42Z"], }, }; const updatedThing = removeDatetime( thingWithOtherQuads, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect(updatedThing.predicates).toStrictEqual({ "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#dateTime": [ "1955-06-08T13:37:42Z", "not-a-datetime", ], }, }, "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#dateTime": ["1990-11-12T13:37:42Z"], }, }, }); }); it("does not remove Quads with non-datetime Objects", () => { const thingWithString = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12T13:37:42Z", "dateTime" ); (thingWithString.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] as string[]) = ["Some string value"]; const updatedThing = removeDatetime( thingWithString, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#dateTime": [], "http://www.w3.org/2001/XMLSchema#string": ["Some string value"], }); }); it("throws an error when passed something other than a Thing", () => { expect(() => removeDatetime( null as unknown as Thing, "https://arbitrary.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => removeDatetime( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeDatetime( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("removeDate", () => { it("removes the given date value for the given Predicate", () => { const thingWithDate = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12Z", "date" ); const updatedThing = removeDate( thingWithDate, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#date": [], }); }); it("removes the given date value for the given Predicate regardless of the time value set", () => { const thingWithDate = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12Z", "date" ); const updatedThing = removeDate( thingWithDate, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#date": [], }); }); it("accepts Properties as Named Nodes", () => { const thingWithDate = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12Z", "date" ); const updatedThing = removeDate( thingWithDate, DataFactory.namedNode("https://some.vocab/predicate"), new Date(Date.UTC(1990, 10, 12)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#date": [], }); }); it("does not modify the input Thing", () => { const thingWithDate = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12Z", "date" ); const updatedThing = removeDate( thingWithDate, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ); expect(thingWithDate).not.toStrictEqual(updatedThing); expect( thingWithDate.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#date": ["1990-11-12Z"], }); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#date": [], }); }); it("also works on ThingLocals", () => { const thingLocal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12Z", "date" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = removeDate( thingLocal, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#date": [], }); }); it("removes multiple instances of the same date for the same Predicate", () => { const thingWithDuplicateDate = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12Z", "date" ); ( thingWithDuplicateDate.predicates["https://some.vocab/predicate"] .literals!["http://www.w3.org/2001/XMLSchema#date"] as string[] ).push("1990-11-12Z"); const updatedThing = removeDate( thingWithDuplicateDate, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#date": [], }); }); it("does not remove Quads with different Predicates or Objects", () => { const thingWithOtherQuads = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12Z", "date" ); // A different Object: ( thingWithOtherQuads.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#date" ] as string[] ).push("1955-06-08Z"); // An invalid object ( thingWithOtherQuads.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#date" ] as string[] ).push("not-a-date"); // A different predicate (thingWithOtherQuads.predicates[ "https://some-other.vocab/predicate" ] as any) = { literals: { "http://www.w3.org/2001/XMLSchema#date": ["1990-11-12Z"], }, }; const updatedThing = removeDate( thingWithOtherQuads, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ); expect(updatedThing.predicates).toStrictEqual({ "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#date": [ "1955-06-08Z", "not-a-date", ], }, }, "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#date": ["1990-11-12Z"], }, }, }); }); it("does not remove Quads with non-date Objects", () => { const thingWithString = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12Z", "date" ); (thingWithString.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] as string[]) = ["Some string value"]; const updatedThing = removeDate( thingWithString, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#date": [], "http://www.w3.org/2001/XMLSchema#string": ["Some string value"], }); }); it("throws an error when passed something other than a Thing", () => { expect(() => removeDate( null as unknown as Thing, "https://arbitrary.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => removeDate( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", new Date(Date.UTC(1990, 10, 12)) ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeDate( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", new Date(Date.UTC(1990, 10, 12)) ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("removeTime", () => { it("removes the given time value for the given Predicate", () => { const thingWithTime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13:37:42", "time" ); const updatedThing = removeTime( thingWithTime, "https://some.vocab/predicate", { hour: 13, minute: 37, second: 42, } ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#time": [], }); }); it("removes equivalent times with different serialisations", () => { const thingWithRoundedTime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13:37:42", "time" ); const thingWithSpecificTime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "12:37:42+01:00", "time" ); const updatedThingWithoutRoundedTime = removeTime( thingWithRoundedTime, "https://some.vocab/predicate", { hour: 13, minute: 37, second: 42, } ); const updatedThingWithoutSpecificTime = removeTime( thingWithSpecificTime, "https://some.vocab/predicate", { hour: 12, minute: 37, second: 42, timezoneHourOffset: 1, timezoneMinuteOffset: 0, } ); expect( updatedThingWithoutRoundedTime.predicates["https://some.vocab/predicate"] .literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#time": [], }); expect( updatedThingWithoutSpecificTime.predicates["https://some.vocab/predicate"] .literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#time": [], }); }); it("accepts Properties as Named Nodes", () => { const thingWithTime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13:37:42", "time" ); const updatedThing = removeTime( thingWithTime, DataFactory.namedNode("https://some.vocab/predicate"), { hour: 13, minute: 37, second: 42, } ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#time": [], }); }); it("does not modify the input Thing", () => { const thingWithTime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13:37:42", "time" ); const updatedThing = removeTime( thingWithTime, "https://some.vocab/predicate", { hour: 13, minute: 37, second: 42, } ); expect(thingWithTime).not.toStrictEqual(updatedThing); expect( thingWithTime.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#time": ["13:37:42"], }); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#time": [], }); }); it("also works on ThingLocals", () => { const thingLocal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13:37:42", "time" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = removeTime( thingLocal, "https://some.vocab/predicate", { hour: 13, minute: 37, second: 42, } ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#time": [], }); }); it("removes multiple instances of the same time for the same Predicate", () => { const thingWithDuplicateTime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13:37:42", "time" ); ( thingWithDuplicateTime.predicates["https://some.vocab/predicate"] .literals!["http://www.w3.org/2001/XMLSchema#time"] as string[] ).push("13:37:42"); const updatedThing = removeTime( thingWithDuplicateTime, "https://some.vocab/predicate", { hour: 13, minute: 37, second: 42, } ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#time": [], }); }); it("does not remove Quads with different Predicates or Objects", () => { const thingWithOtherQuads = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13:37:42", "time" ); // A different Object: ( thingWithOtherQuads.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#time" ] as string[] ).push("14:37:42"); // An invalid object ( thingWithOtherQuads.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#time" ] as string[] ).push("not-a-time"); // A different predicate (thingWithOtherQuads.predicates[ "https://some-other.vocab/predicate" ] as any) = { literals: { "http://www.w3.org/2001/XMLSchema#time": ["13:37:42"], }, }; const updatedThing = removeTime( thingWithOtherQuads, "https://some.vocab/predicate", { hour: 13, minute: 37, second: 42, } ); expect(updatedThing.predicates).toStrictEqual({ "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#time": ["14:37:42", "not-a-time"], }, }, "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#time": ["13:37:42"], }, }, }); }); it("does not remove Quads with non-time Objects", () => { const thingWithString = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13:37:42", "time" ); (thingWithString.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] as string[]) = ["Some string value"]; const updatedThing = removeTime( thingWithString, "https://some.vocab/predicate", { hour: 13, minute: 37, second: 42, } ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#time": [], "http://www.w3.org/2001/XMLSchema#string": ["Some string value"], }); }); it("throws an error when passed something other than a Thing", () => { expect(() => removeTime( null as unknown as Thing, "https://arbitrary.vocab/predicate", { hour: 13, minute: 37, second: 42, } ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => removeTime( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", { hour: 13, minute: 37, second: 42, } ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeTime( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", { hour: 13, minute: 37, second: 42, } ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("removeDecimal", () => { it("removes the given decimal value for the given Predicate", () => { const thingWithDecimal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13.37", "decimal" ); const updatedThing = removeDecimal( thingWithDecimal, "https://some.vocab/predicate", 13.37 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#decimal": [], }); }); it("removes equivalent Decimals with different serialisations", () => { const thingWithPlainDecimal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1337", "decimal" ); const thingWithSignedDecimal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "+1337", "decimal" ); const thingWithZeroedDecimal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "01337.0", "decimal" ); const updatedThingWithoutPlainDecimal = removeDecimal( thingWithPlainDecimal, "https://some.vocab/predicate", 1337 ); const updatedThingWithoutSignedDecimal = removeDecimal( thingWithSignedDecimal, "https://some.vocab/predicate", 1337 ); const updatedThingWithoutZeroedDecimal = removeDecimal( thingWithZeroedDecimal, "https://some.vocab/predicate", 1337 ); expect( updatedThingWithoutPlainDecimal.predicates["https://some.vocab/predicate"] .literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#decimal": [], }); expect( updatedThingWithoutSignedDecimal.predicates[ "https://some.vocab/predicate" ].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#decimal": [], }); expect( updatedThingWithoutZeroedDecimal.predicates[ "https://some.vocab/predicate" ].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#decimal": [], }); }); it("accepts Properties as Named Nodes", () => { const thingWithDecimal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13.37", "decimal" ); const updatedThing = removeDecimal( thingWithDecimal, DataFactory.namedNode("https://some.vocab/predicate"), 13.37 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#decimal": [], }); }); it("does not modify the input Thing", () => { const thingWithDecimal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13.37", "decimal" ); const updatedThing = removeDecimal( thingWithDecimal, "https://some.vocab/predicate", 13.37 ); expect(thingWithDecimal).not.toStrictEqual(updatedThing); expect( thingWithDecimal.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#decimal": ["13.37"], }); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#decimal": [], }); }); it("does nothing if the decimal to remove could not be found", () => { const thingWithDecimal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13.37", "decimal" ); const updatedThing = removeDecimal( thingWithDecimal, "https://some.vocab/other-predicate", 4.2 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toEqual({ "http://www.w3.org/2001/XMLSchema#decimal": ["13.37"], }); }); it("also works on ThingLocals", () => { const thingLocal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13.37", "decimal" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = removeDecimal( thingLocal, "https://some.vocab/predicate", 13.37 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#decimal": [], }); }); it("removes multiple instances of the same decimal for the same Predicate", () => { const thingWithDuplicateDecimal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13.37", "decimal" ); ( thingWithDuplicateDecimal.predicates["https://some.vocab/predicate"] .literals!["http://www.w3.org/2001/XMLSchema#decimal"] as string[] ).push("13.37"); const updatedThing = removeDecimal( thingWithDuplicateDecimal, "https://some.vocab/predicate", 13.37 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#decimal": [], }); }); it("does not remove Quads with different Predicates or Objects", () => { const thingWithOtherQuads = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13.37", "decimal" ); // A different Object: ( thingWithOtherQuads.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#decimal" ] as string[] ).push("4.2"); // A different predicate (thingWithOtherQuads.predicates[ "https://some-other.vocab/predicate" ] as any) = { literals: { "http://www.w3.org/2001/XMLSchema#decimal": ["13.37"], }, }; const updatedThing = removeDecimal( thingWithOtherQuads, "https://some.vocab/predicate", 13.37 ); expect(updatedThing.predicates).toStrictEqual({ "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#decimal": ["4.2"], }, }, "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#decimal": ["13.37"], }, }, }); }); it("does not remove Quads with non-decimal Objects", () => { const thingWithString = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13.37", "decimal" ); (thingWithString.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] as string[]) = ["13.37"]; const updatedThing = removeDecimal( thingWithString, "https://some.vocab/predicate", 13.37 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#decimal": [], "http://www.w3.org/2001/XMLSchema#string": ["13.37"], }); }); it("throws an error when passed something other than a Thing", () => { expect(() => removeDecimal( null as unknown as Thing, "https://arbitrary.vocab/predicate", 13.37 ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => removeDecimal( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", 13.37 ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeDecimal( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", 13.37 ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("removeInteger", () => { it("removes the given integer value for the given Predicate", () => { const thingWithInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); const updatedThing = removeInteger( thingWithInteger, "https://some.vocab/predicate", 42 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], }); }); it("removes equivalent integers with different serialisations", () => { const thingWithUnsignedInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); const thingWithSignedInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "+42", "integer" ); const updatedThingWithoutUnsignedInteger = removeInteger( thingWithUnsignedInteger, "https://some.vocab/predicate", 42 ); const updatedThingWithoutSignedInteger = removeInteger( thingWithSignedInteger, "https://some.vocab/predicate", 42 ); expect( updatedThingWithoutUnsignedInteger.predicates[ "https://some.vocab/predicate" ].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], }); expect( updatedThingWithoutSignedInteger.predicates[ "https://some.vocab/predicate" ].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], }); }); it("accepts Properties as Named Nodes", () => { const thingWithInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); const updatedThing = removeInteger( thingWithInteger, DataFactory.namedNode("https://some.vocab/predicate"), 42 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], }); }); it("does not modify the input Thing", () => { const thingWithInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); const updatedThing = removeInteger( thingWithInteger, "https://some.vocab/predicate", 42 ); expect(thingWithInteger).not.toStrictEqual(updatedThing); expect( thingWithInteger.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": ["42"], }); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], }); }); it("does nothing if the integer to remove could not be found", () => { const thingWithInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); const updatedThing = removeInteger( thingWithInteger, "https://some.vocab/other-predicate", 1337 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toEqual({ "http://www.w3.org/2001/XMLSchema#integer": ["42"], }); }); it("also works on ThingLocals", () => { const thingLocal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = removeInteger( thingLocal, "https://some.vocab/predicate", 42 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], }); }); it("removes multiple instances of the same integer for the same Predicate", () => { const thingWithDuplicateInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); ( thingWithDuplicateInteger.predicates["https://some.vocab/predicate"] .literals!["http://www.w3.org/2001/XMLSchema#integer"] as string[] ).push("42"); const updatedThing = removeInteger( thingWithDuplicateInteger, "https://some.vocab/predicate", 42 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], }); }); it("does not remove Quads with different Predicates or Objects", () => { const thingWithOtherQuads = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); // A different Object: ( thingWithOtherQuads.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#integer" ] as string[] ).push("1337"); // A different predicate (thingWithOtherQuads.predicates[ "https://some-other.vocab/predicate" ] as any) = { literals: { "http://www.w3.org/2001/XMLSchema#integer": ["42"], }, }; const updatedThing = removeInteger( thingWithOtherQuads, "https://some.vocab/predicate", 42 ); expect(updatedThing.predicates).toStrictEqual({ "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#integer": ["1337"], }, }, "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#integer": ["42"], }, }, }); }); it("does not remove Quads with non-integer Objects", () => { const thingWithString = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); (thingWithString.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] as string[]) = ["42"]; const updatedThing = removeInteger( thingWithString, "https://some.vocab/predicate", 42 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], "http://www.w3.org/2001/XMLSchema#string": ["42"], }); }); it("throws an error when passed something other than a Thing", () => { expect(() => removeInteger( null as unknown as Thing, "https://arbitrary.vocab/predicate", 42 ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => removeInteger( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", 42 ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeInteger( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", 42 ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("removeStringEnglish", () => { function getMockThingWithEnglishString( predicate: IriString, literalValue: string ): Thing { return { type: "Subject", url: "https://arbitrary.vocab/subject", predicates: { [predicate]: { langStrings: { en: [literalValue], }, }, }, }; } it("removes the given English string for the given Predicate", () => { const thingWithStringWithLocale = getMockThingWithEnglishString( "https://some.vocab/predicate", "Some value in English..." ); const updatedThing = removeStringEnglish( thingWithStringWithLocale, "https://some.vocab/predicate", "Some value in English..." ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ en: [], }); }); }); describe("removeStringWithLocale", () => { function getMockThingWithStringWithLocaleFor( predicate: IriString, literalValue: string, locale: string ): Thing { return { type: "Subject", url: "https://arbitrary.vocab/subject", predicates: { [predicate]: { langStrings: { [locale]: [literalValue], }, }, }, }; } it("removes the given localised string for the given Predicate", () => { const thingWithStringWithLocale = getMockThingWithStringWithLocaleFor( "https://some.vocab/predicate", "Une chaîne de caractères quelconque", "fr-fr" ); const updatedThing = removeStringWithLocale( thingWithStringWithLocale, "https://some.vocab/predicate", "Une chaîne de caractères quelconque", "fr-fr" ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "fr-fr": [], }); }); it("accepts Properties as Named Nodes", () => { const thingWithStringWithLocale = getMockThingWithStringWithLocaleFor( "https://some.vocab/predicate", "Some arbitrary string", "en-us" ); const updatedThing = removeStringWithLocale( thingWithStringWithLocale, DataFactory.namedNode("https://some.vocab/predicate"), "Some arbitrary string", "en-us" ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-us": [], }); }); it("does not modify the input Thing", () => { const thingWithStringWithLocale = getMockThingWithStringWithLocaleFor( "https://some.vocab/predicate", "Some arbitrary string", "en-us" ); const updatedThing = removeStringWithLocale( thingWithStringWithLocale, "https://some.vocab/predicate", "Some arbitrary string", "en-us" ); expect(thingWithStringWithLocale).not.toStrictEqual(updatedThing); expect( thingWithStringWithLocale.predicates["https://some.vocab/predicate"] .langStrings ).toStrictEqual({ "en-us": ["Some arbitrary string"], }); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-us": [], }); }); it("does nothing if the given string could not be found", () => { const thingWithStringWithLocale = getMockThingWithStringWithLocaleFor( "https://some.vocab/predicate", "Some arbitrary string", "en-us" ); const updatedThing = removeStringWithLocale( thingWithStringWithLocale, "https://some.vocab/other-predicate", "Some other arbitrary string", "nl-nl" ); expect(thingWithStringWithLocale).toStrictEqual(updatedThing); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-us": ["Some arbitrary string"], }); }); it("also works on ThingLocals", () => { const thingLocal = getMockThingWithStringWithLocaleFor( "https://some.vocab/predicate", "Some arbitrary string", "en-us" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = removeStringWithLocale( thingLocal, "https://some.vocab/predicate", "Some arbitrary string", "en-us" ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-us": [], }); }); it("removes multiple instances of the same localised string for the same Predicate", () => { const thingWithDuplicateStringWithLocale = getMockThingWithStringWithLocaleFor( "https://some.vocab/predicate", "Some arbitrary string", "en-us" ); ( thingWithDuplicateStringWithLocale.predicates[ "https://some.vocab/predicate" ].langStrings!["en-us"] as string[] ).push("Some arbitrary string"); const updatedThing = removeStringWithLocale( thingWithDuplicateStringWithLocale, "https://some.vocab/predicate", "Some arbitrary string", "en-us" ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-us": [], }); }); it("does not remove Quads with different Predicates or Objects", () => { const thingWithStringWithLocale = getMockThingWithStringWithLocaleFor( "https://some.vocab/predicate", "Some arbitrary string", "en-us" ); // A different Object: ( thingWithStringWithLocale.predicates["https://some.vocab/predicate"] .langStrings!["en-us"] as string[] ).push("Some other arbitrary string"); // A different locale (thingWithStringWithLocale.predicates["https://some.vocab/predicate"] .langStrings!["en-uk"] as string[]) = ["Some arbitrary string"]; // A different predicate (thingWithStringWithLocale.predicates[ "https://some-other.vocab/predicate" ] as any) = { langStrings: { "en-us": ["Some arbitrary string"], }, }; const updatedThing = removeStringWithLocale( thingWithStringWithLocale, "https://some.vocab/predicate", "Some arbitrary string", "en-US" ); expect(updatedThing.predicates).toStrictEqual({ "https://some.vocab/predicate": { langStrings: { "en-us": ["Some other arbitrary string"], "en-uk": ["Some arbitrary string"], }, }, "https://some-other.vocab/predicate": { langStrings: { "en-us": ["Some arbitrary string"], }, }, }); }); it("removes Quads when the locale casing mismatch", () => { const thingWithStringWithLocale = getMockThingWithStringWithLocaleFor( "https://some.vocab/predicate", "Some arbitrary string", "en-us" ); const updatedThing = removeStringWithLocale( thingWithStringWithLocale, "https://some.vocab/predicate", "Some arbitrary string", "en-US" ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-us": [], }); }); it("does not remove Quads with non-string Objects", () => { const thingWithInteger = getMockThingWithStringWithLocaleFor( "https://some.vocab/predicate", "Some arbitrary string", "en-us" ); (thingWithInteger.predicates["https://some.vocab/predicate"] .literals as any) = { "http://www.w3.org/2001/XMLSchema#integer": ["Some arbitrary string"], }; const updatedThing = removeStringWithLocale( thingWithInteger, "https://some.vocab/predicate", "Some arbitrary string", "en-us" ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": ["Some arbitrary string"], }); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-us": [], }); }); it("throws an error when passed something other than a Thing", () => { expect(() => removeStringWithLocale( null as unknown as Thing, "https://arbitrary.vocab/predicate", "Arbitrary string", "nl-NL" ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => removeStringWithLocale( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", "Arbitrary string", "nl-NL" ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeStringWithLocale( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", "Arbitrary string", "nl-NL" ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("removeStringNoLocale", () => { it("removes the given string value for the given Predicate", () => { const thingWithStringNoLocale = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Some arbitrary string", "string" ); const updatedThing = removeStringNoLocale( thingWithStringNoLocale, "https://some.vocab/predicate", "Some arbitrary string" ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#string": [], }); }); it("accepts Properties as Named Nodes", () => { const thingWithStringNoLocale = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Some arbitrary string", "string" ); const updatedThing = removeStringNoLocale( thingWithStringNoLocale, DataFactory.namedNode("https://some.vocab/predicate"), "Some arbitrary string" ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#string": [], }); }); it("does not modify the input Thing", () => { const thingWithStringNoLocale = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Some arbitrary string", "string" ); const updatedThing = removeStringNoLocale( thingWithStringNoLocale, "https://some.vocab/predicate", "Some arbitrary string" ); expect(thingWithStringNoLocale).not.toStrictEqual(updatedThing); expect( thingWithStringNoLocale.predicates["https://some.vocab/predicate"] .literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#string": ["Some arbitrary string"], }); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#string": [], }); }); it("does nothing if the string to remove could not be found", () => { const thingWithStringNoLocale = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Some arbitrary string", "string" ); const updatedThing = removeStringNoLocale( thingWithStringNoLocale, "https://some.vocab/other-predicate", "Some arbitrary other string" ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toEqual({ "http://www.w3.org/2001/XMLSchema#string": ["Some arbitrary string"], }); }); it("also works on ThingLocals", () => { const thingLocal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Some arbitrary string", "string" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = removeStringNoLocale( thingLocal, "https://some.vocab/predicate", "Some arbitrary string" ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#string": [], }); }); it("removes multiple instances of the same string for the same Predicate", () => { const thingWithDuplicateString = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Some arbitrary string", "string" ); ( thingWithDuplicateString.predicates["https://some.vocab/predicate"] .literals!["http://www.w3.org/2001/XMLSchema#string"] as string[] ).push("Some arbitrary string"); const updatedThing = removeStringNoLocale( thingWithDuplicateString, "https://some.vocab/predicate", "Some arbitrary string" ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#string": [], }); }); it("does not remove Quads with different Predicates or Objects", () => { const thingWithOtherQuads = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Some arbitrary string", "string" ); // A different Object: ( thingWithOtherQuads.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] as string[] ).push("Some other arbitrary string"); // A different predicate (thingWithOtherQuads.predicates[ "https://some-other.vocab/predicate" ] as any) = { literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some arbitrary string"], }, }; const updatedThing = removeStringNoLocale( thingWithOtherQuads, "https://some.vocab/predicate", "Some arbitrary string" ); expect(updatedThing.predicates).toStrictEqual({ "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#string": [ "Some other arbitrary string", ], }, }, "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some arbitrary string"], }, }, }); }); it("does not remove Quads with non-string Objects", () => { const thingWithInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Some arbitrary string", "string" ); (thingWithInteger.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#integer" ] as string[]) = ["Some arbitrary string"]; const updatedThing = removeStringNoLocale( thingWithInteger, "https://some.vocab/predicate", "Some arbitrary string" ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#string": [], "http://www.w3.org/2001/XMLSchema#integer": ["Some arbitrary string"], }); }); it("throws an error when passed something other than a Thing", () => { expect(() => removeStringNoLocale( null as unknown as Thing, "https://arbitrary.vocab/predicate", "Arbitrary string" ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => removeStringNoLocale( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", "Arbitrary string" ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeStringNoLocale( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", "Arbitrary string" ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("removeLiteral", () => { it("accepts unlocalised strings as Literal", () => { const thingWithStringNoLocale = getMockThingWithLiteralFor( "https://some.vocab/predicate", "Some arbitrary string", "string" ); const updatedThing = removeLiteral( thingWithStringNoLocale, "https://some.vocab/predicate", DataFactory.literal( "Some arbitrary string", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#string") ) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#string": [], }); }); it("accepts localised strings as Literal", () => { const quad = DataFactory.quad( DataFactory.namedNode("https://arbitrary.vocab/subject"), DataFactory.namedNode("https://some.vocab/predicate"), DataFactory.literal("Some arbitrary string", "en-US") ); const thing = dataset(); thing.add(quad); const thingWithStringWithLocale: Thing = { type: "Subject", url: "https://arbitrary.vocab/subject", predicates: { "https://some.vocab/predicate": { langStrings: { "en-US": ["Some arbitrary string"], }, }, }, }; const updatedThing = removeLiteral( thingWithStringWithLocale, "https://some.vocab/predicate", DataFactory.literal("Some arbitrary string", "en-US") ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-US": [], }); }); it("accepts integers as Literal", () => { const thingWithInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); const updatedThing = removeLiteral( thingWithInteger, "https://some.vocab/predicate", DataFactory.literal( "42", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#integer") ) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], }); }); it("accepts decimal as Literal", () => { const thingWithDecimal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13.37", "decimal" ); const updatedThing = removeLiteral( thingWithDecimal, "https://some.vocab/predicate", DataFactory.literal( "13.37", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#decimal") ) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#decimal": [], }); }); it("accepts boolean as Literal", () => { const thingWithBoolean = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1", "boolean" ); const updatedThing = removeLiteral( thingWithBoolean, "https://some.vocab/predicate", DataFactory.literal( "1", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#boolean") ) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#boolean": [], }); }); it("accepts time as Literal", () => { const thingWithTime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "13:37:42", "time" ); const updatedThing = removeLiteral( thingWithTime, "https://some.vocab/predicate", DataFactory.literal( "13:37:42", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#time") ) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#time": [], }); }); it("accepts datetime as Literal", () => { const thingWithDatetime = getMockThingWithLiteralFor( "https://some.vocab/predicate", "1990-11-12T13:37:42Z", "dateTime" ); const updatedThing = removeLiteral( thingWithDatetime, "https://some.vocab/predicate", DataFactory.literal( "1990-11-12T13:37:42Z", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#dateTime") ) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#dateTime": [], }); }); it("accepts Properties as Named Nodes", () => { const thingWithInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); const updatedThing = removeLiteral( thingWithInteger, DataFactory.namedNode("https://some.vocab/predicate"), DataFactory.literal( "42", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#integer") ) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], }); }); it("does not modify the input Thing", () => { const thingWithInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); const updatedThing = removeLiteral( thingWithInteger, DataFactory.namedNode("https://some.vocab/predicate"), DataFactory.literal( "42", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#integer") ) ); expect(thingWithInteger).not.toStrictEqual(updatedThing); expect( thingWithInteger.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": ["42"], }); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], }); }); it("does nothing if the given Literal could not be found", () => { const thingWithInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); const updatedThing = removeLiteral( thingWithInteger, DataFactory.namedNode("https://some.vocab/other-predicate"), DataFactory.literal( "13.37", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#decimal") ) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toEqual({ "http://www.w3.org/2001/XMLSchema#integer": ["42"], }); }); it("also works on ThingLocals", () => { const thingLocal = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = removeLiteral( thingLocal, "https://some.vocab/predicate", DataFactory.literal( "42", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#integer") ) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], }); }); it("removes multiple instances of the same Literal for the same Predicate", () => { const thingWithDuplicateInteger = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); ( thingWithDuplicateInteger.predicates["https://some.vocab/predicate"] .literals!["http://www.w3.org/2001/XMLSchema#integer"] as string[] ).push("42"); const updatedThing = removeLiteral( thingWithDuplicateInteger, "https://some.vocab/predicate", DataFactory.literal( "42", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#integer") ) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], }); }); it("does not remove Quads with different Predicates or Objects", () => { const thingWithOtherQuads = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); // A different Object: ( thingWithOtherQuads.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#integer" ] as string[] ).push("1337"); // A different predicate (thingWithOtherQuads.predicates[ "https://some-other.vocab/predicate" ] as any) = { literals: { "http://www.w3.org/2001/XMLSchema#integer": ["42"], }, }; const updatedThing = removeLiteral( thingWithOtherQuads, "https://some.vocab/predicate", DataFactory.literal( "42", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#integer") ) ); expect(updatedThing.predicates).toStrictEqual({ "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#integer": ["1337"], }, }, "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#integer": ["42"], }, }, }); }); it("does not remove Quads with Literal Objects with different types", () => { const thingWithString = getMockThingWithLiteralFor( "https://some.vocab/predicate", "42", "integer" ); (thingWithString.predicates["https://some.vocab/predicate"] as any) = { literals: { "http://www.w3.org/2001/XMLSchema#string": ["42"], }, }; const updatedThing = removeLiteral( thingWithString, "https://some.vocab/predicate", DataFactory.literal( "42", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#integer") ) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals ).toStrictEqual({ "http://www.w3.org/2001/XMLSchema#integer": [], "http://www.w3.org/2001/XMLSchema#string": ["42"], }); }); it("throws an error when passed something other than a Thing", () => { expect(() => removeLiteral( null as unknown as Thing, "https://arbitrary.vocab/predicate", DataFactory.literal( "42", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#integer") ) ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => removeLiteral( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", DataFactory.literal("Arbitrary string value") ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeLiteral( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", DataFactory.literal("Arbitrary string value") ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("removeNamedNode", () => { it("removes the given NamedNode value for the given Predicate", () => { const thingWithNamedNode = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.vocab/object" ); const updatedThing = removeNamedNode( thingWithNamedNode, "https://some.vocab/predicate", DataFactory.namedNode("https://some.vocab/object") ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual([]); }); it("accepts Properties as Named Nodes", () => { const thingWithNamedNode = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.vocab/object" ); const updatedThing = removeNamedNode( thingWithNamedNode, DataFactory.namedNode("https://some.vocab/predicate"), DataFactory.namedNode("https://some.vocab/object") ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual([]); }); it("does not modify the input Thing", () => { const thingWithNamedNode = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.vocab/object" ); const updatedThing = removeNamedNode( thingWithNamedNode, DataFactory.namedNode("https://some.vocab/predicate"), DataFactory.namedNode("https://some.vocab/object") ); expect(thingWithNamedNode).not.toStrictEqual(updatedThing); expect( thingWithNamedNode.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual(["https://some.vocab/object"]); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual([]); }); it("also works on ThingLocals", () => { const thingLocal = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.vocab/object" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = removeNamedNode( thingLocal, "https://some.vocab/predicate", DataFactory.namedNode("https://some.vocab/object") ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual([]); }); it("removes multiple instances of the same NamedNode for the same Predicate", () => { const thingWithDuplicateNamedNode = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.vocab/object" ); ( thingWithDuplicateNamedNode.predicates["https://some.vocab/predicate"] .namedNodes as UrlString[] ).push("https://some.vocab/object"); const updatedThing = removeNamedNode( thingWithDuplicateNamedNode, "https://some.vocab/predicate", DataFactory.namedNode("https://some.vocab/object") ); expect( updatedThing.predicates["https://some.vocab/predicate"].namedNodes ).toStrictEqual([]); }); it("does not remove Quads with different Predicates or Objects", () => { const thingWithOtherQuads = getMockThingWithNamedNode( "https://some.vocab/predicate", "https://some.vocab/object" ); ( thingWithOtherQuads.predicates["https://some.vocab/predicate"] .namedNodes as UrlString[] ).push("https://some-other.vocab/object"); (thingWithOtherQuads.predicates["https://some-other.vocab/predicate"] as { namedNodes: UrlString[]; }) = { namedNodes: ["https://some.vocab/object"], }; const updatedThing = removeNamedNode( thingWithOtherQuads, "https://some.vocab/predicate", DataFactory.namedNode("https://some.vocab/object") ); expect(updatedThing.predicates).toStrictEqual({ "https://some.vocab/predicate": { namedNodes: ["https://some-other.vocab/object"], }, "https://some-other.vocab/predicate": { namedNodes: ["https://some.vocab/object"], }, }); }); it("throws an error when passed something other than a Thing", () => { expect(() => removeNamedNode( null as unknown as Thing, "https://arbitrary.vocab/predicate", DataFactory.namedNode("https://arbitrary.vocab/object") ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => removeNamedNode( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", DataFactory.namedNode("https://arbitrary.vocab/object") ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { removeNamedNode( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", DataFactory.namedNode("https://arbitrary.vocab/object") ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); });
the_stack
interface RestEntities {} /** * @internal */ declare namespace SDK { namespace REST { function createRecord(object: any, type: string, successCallback: (result: any) => any, errorCallback: (err: Error) => any): void; function deleteRecord(id: string, type: string, successCallBack: () => any, errorCallback: (err: Error) => any): void; function retrieveRecord(id: string, type: string, select: string | null, expand: string | null, successCallback: (result: any) => any, errorCallback: (err: Error) => any): void; function updateRecord(id: string, object: any, type: string, successCallBack: () => any, errorCallback: (err: Error) => any): void; function retrieveMultipleRecords(type: string, options: string | null, successCallback: (result: any[]) => any, errorCallback: (err: Error) => any, onComplete: any): void; } } interface RestMapping<O, S, E, F, R> { __RestMapping: O; } interface RestAttribute<T> { __RestAttribute: T; } interface RestExpand<T, U> extends RestAttribute<T> { __RestExpandable: U; } interface RestFilter { __RestFilter: any; } namespace Filter.REST { export function equals<T>(v1: T, v2: T): RestFilter { return Comp(v1, "eq", v2); } export function notEquals<T>(v1: T, v2: T): RestFilter { return Comp(v1, "ne", v2); } export function greaterThan<T extends Number | Date>(v1: T, v2: T): RestFilter { return Comp(v1, "gt", v2); } export function greaterThanOrEqual<T extends Number | Date>(v1: T, v2: T): RestFilter { return Comp(v1, "ge", v2); } export function lessThan<T extends Number | Date>(v1: T, v2: T): RestFilter { return Comp(v1, "lt", v2); } export function lessThanOrEqual<T extends Number | Date>(v1: T, v2: T): RestFilter { return Comp(v1, "le", v2); } export function and(f1: RestFilter, f2: RestFilter): RestFilter { return BiFilter(f1, "and", f2); } export function or(f1: RestFilter, f2: RestFilter): RestFilter { return BiFilter(f1, "or", f2); } export function not(f1: RestFilter): RestFilter { return <RestFilter><any>("not " + f1); } export function ands(fs: RestFilter[]): RestFilter { return NestedFilter(fs, "and"); } export function ors(fs: RestFilter[]): RestFilter { return NestedFilter(fs, "or"); } export function startsWith(v1: string, v2: string): RestFilter { return DataFunc("startswith", v1, v2); } export function substringOf(v1: string, v2: string): RestFilter { return DataFunc("substringof", v1, v2); } export function endsWith(v1: string, v2: string): RestFilter { return DataFunc("endswith", v1, v2); } /** * Makes a string into a GUID that can be sent to the OData source */ export function makeGuid(id: string): XQR.Guid { return <XQR.Guid><any>XQR.makeTag(`(guid'${id}')`); } /** * @internal */ function getVal(v: any) { if (v == null) return "null"; if (typeof v === "string") return `'${v}'`; if (Object.prototype.toString.call(v) === "[object Date]") return `DateTime'${v.format("yyyy-MM-ddTHH:mm:ss")}'`; return v.toString(); } /** * @internal */ function Comp<T>(val1: T, op: string, val2: T): RestFilter { return <RestFilter><any>(`${getVal(val1)} ${op} ${getVal(val2)}`); } /** * @internal */ function DataFunc<T>(funcName: string, val1: T, val2: T): RestFilter { return <RestFilter><any>(`${funcName}(${getVal(val1)}, ${getVal(val2)})`); } /** * @internal */ function BiFilter(f1: RestFilter, conj: string, f2: RestFilter): RestFilter { return <RestFilter><any>(`(${f1} ${conj} ${f2})`); } /** * @internal */ function NestedFilter(fs: RestFilter[], conj: string): RestFilter { var last = fs.pop(); if (last === undefined) { return <RestFilter><any>(""); } return fs.reduceRight((acc, c) => BiFilter(c, conj, acc), last); } } namespace XrmQuery.REST { export function stripGUID(guid: string) { if (guid.startsWith("{") && guid.endsWith("}")) return guid.substring(1, guid.length - 1); else return guid; } export function retrieveRecord<O, S, E, R>(entityPicker: (x: RestEntities) => RestMapping<O, S, E, any, R>, id: string) { return new XQR.RetrieveRecord(entityPicker, stripGUID(id)); } export function retrieveMultipleRecords<O, S, E, F, R>(entityPicker: (x: RestEntities) => RestMapping<O, S, E, F, R>) { return new XQR.RetrieveMultipleRecords(entityPicker); } export function createRecord<O, R>(entityPicker: (x: RestEntities) => RestMapping<O, any, any, any, R>, record: O) { return new XQR.CreateRecord(entityPicker, record); } export function updateRecord<O>(entityPicker: (x: RestEntities) => RestMapping<O, any, any, any, any>, id: string, record: O) { return new XQR.UpdateRecord(entityPicker, stripGUID(id), record); } export function deleteRecord<O>(entityPicker: (x: RestEntities) => RestMapping<O, any, any, any, any>, id: string) { return new XQR.DeleteRecord(entityPicker, stripGUID(id)); } } namespace XQR { export interface Guid { __XqrGuid: any; } export interface ValueContainerFilter<T> { Value: T; } export interface EntityReferenceFilter { Id: Guid; Name: string; LogicalName: string; } /** * @internal */ export function makeTag(name: string) { return { __str: name, toString: function () { return this.__str; } }; } /** * @internal */ function taggedExec<T>(f: (x: any) => T): T { var tagged = tagMatches(f); return f(tagged); } /** * @internal */ var fPatt = /function[^\(]*\(([a-zA-Z0-9_]+)[^\{]*\{([\s\S]*)\}$/m; /** * @internal */ function objRegex(oName: string) { return new RegExp("\\b" + oName + "\\.([a-zA-Z_$][0-9a-zA-Z_$]*)(\\.([a-zA-Z_$][0-9a-zA-Z_$]*))?", "g"); } /** * @internal */ function analyzeFunc(f: (x: any) => any) { var m = f.toString().match(fPatt); if (!m) throw new Error(`XrmQuery: Unable to properly parse function: ${f.toString()}`); return { arg: m[1], body: m[2] }; } /** * @internal */ function tagMatches(f: (x: any) => any) { var funcInfo = analyzeFunc(f); var regex = objRegex(funcInfo.arg); var obj: { [k: string]: any } = {}; var match: any; while ((match = regex.exec(funcInfo.body)) != null) { if (!obj[match[1]]) { obj[match[1]] = makeTag(match[1]); } if (match[3]) { obj[match[1]][match[3]] = makeTag(match[1] + "/" + match[3]); } } return obj; } /** * @internal */ var NoOp = () => {}; /** * Contains information about a Retrieve query */ export class RetrieveRecord<S, E, R> { /** * @internal */ private logicalName: string; /** * @internal */ private selects: string[] = []; /** * @internal */ private expands: string[] = []; /** * @internal */ private id: string; constructor(entityPicker: (x: RestEntities) => RestMapping<any, S, E, any, R>, id: string) { this.logicalName = taggedExec(entityPicker).toString(); this.id = id; } select(vars: (x: S) => RestAttribute<S>[]) { this.selects = this.selects.concat(<string[]><any>taggedExec(vars)); return this; } expand<S2>(exps: (x: E) => RestExpand<S, S2>, vars?: (x: S2) => RestAttribute<S2>[]) { var expName = taggedExec(exps).toString(); this.expands.push(expName); if (vars) this.selects = this.selects.concat(taggedExec(vars).map(a => expName + "." + a)); return this; } execute(successCallback: (record: R) => any, errorCallback?: (err: Error) => any) { SDK.REST.retrieveRecord( this.id, this.logicalName, this.selects.length > 0 ? this.selects.join(",") : null, this.expands.length > 0 ? this.expands.join(",") : null, successCallback, errorCallback ? errorCallback : NoOp); } } /** * Contains information about a RetrieveMultiple query */ export class RetrieveMultipleRecords<S, E, F, R> { /** * @internal */ private logicalName: string; /** * @internal */ private selects: string[] = []; /** * @internal */ private expands: string[] = []; /** * @internal */ private ordering: string[] = []; /** * @internal */ private filters: RestFilter; /** * @internal */ private skipAmount: number | null = null; /** * @internal */ private topAmount: number | null = null; constructor(entityPicker: (x: RestEntities) => RestMapping<any, S, E, F, R>) { this.logicalName = taggedExec(entityPicker).toString(); } select(vars: (x: S) => RestAttribute<S>[]) { this.selects = this.selects.concat(<string[]><any>taggedExec(vars)); return this; } expand<T2>(exps: (x: E) => RestExpand<S, T2>, vars?: (x: T2) => RestAttribute<T2>[]) { var expName = taggedExec(exps).toString(); this.expands.push(expName); if (vars) this.selects = this.selects.concat(taggedExec(vars).map(a => `${expName}/${a}`)); return this; } filter(filter: (x: F) => RestFilter) { this.filters = taggedExec(filter); return this; } orFilter(filter: (x: F) => RestFilter) { if (this.filters) this.filters = Filter.REST.or(this.filters, taggedExec(filter)); else this.filter(filter); return this; } andFilter(filter: (x: F) => RestFilter) { if (this.filters) this.filters = Filter.REST.and(this.filters, taggedExec(filter)); else this.filter(filter); return this; } /** * @internal */ private order(vars: (x: S) => RestAttribute<S>, by: string) { this.ordering.push(taggedExec(vars) + " " + by); return this; } orderAsc(vars: (x: S) => RestAttribute<S>) { return this.order(vars, "asc"); } orderDesc(vars: (x: S) => RestAttribute<S>) { return this.order(vars, "desc"); } skip(amount: number) { this.skipAmount = amount; return this; } top(amount: number) { this.topAmount = amount; return this; } /** * Executes the RetrieveMultiple. Note that the first function passed as an argument is called once per page returned from CRM. * @param pageSuccessCallback Called once per page returned from CRM * @param errorCallback Called if an error occurs during the retrieval * @param onComplete Called when all pages have been successfully retrieved from CRM */ execute(pageSuccessCallback: (records: R[]) => any, errorCallback: (err: Error) => any, onComplete: () => any) { SDK.REST.retrieveMultipleRecords( this.logicalName, this.getOptionString(), pageSuccessCallback, errorCallback, onComplete); } /** * Executes the RetrieveMultiple and concatenates all the pages to a single array that is delivered to the success callback function. * @param successCallback Called with all records returned from the query * @param errorCallback Called if an error occures during the retrieval */ getAll(successCallback: (records: R[]) => any, errorCallback?: (err: Error) => any) { let pages: any[][] = []; SDK.REST.retrieveMultipleRecords( this.logicalName, this.getOptionString(), page => { pages.push(page); }, errorCallback ? errorCallback : NoOp, () => { successCallback([].concat.apply([], pages)); }); } /** * Executes the RetrieveMultiple, but only returns the first result (or null, if no record was found). * @param successCallback Called with the first result of the query (or null, if no record was found) * @param errorCallback Called if an error occures during the retrieval */ getFirst(successCallback: (record: R | null) => any, errorCallback?: (err: Error) => any) { this.top(1); this.execute(recs => successCallback((recs.length > 0) ? recs[0] : null), errorCallback ? errorCallback : NoOp, NoOp); } getOptionString(): string { var options: string[] = []; if (this.selects.length > 0) { options.push("$select=" + this.selects.join(",")); } if (this.expands.length > 0) { options.push("$expand=" + this.expands.join(",")); } if (this.filters) { options.push("$filter=" + this.filters); } if (this.ordering.length > 0) { options.push("$orderby=" + this.ordering.join(",")); } if (this.skipAmount != null) { options.push("$skip=" + this.skipAmount); } if (this.topAmount != null) { options.push("$top=" + this.topAmount); } return options.join("&"); } } /** * Contains information about a Create query */ export class CreateRecord<O, R> { /** * @internal */ private logicalName: string; /** * @internal */ private record: O; constructor(entityPicker: (x: RestEntities) => RestMapping<O, any, any, any, R>, record: O) { this.logicalName = taggedExec(entityPicker).toString(); this.record = record; } execute(successCallback?: (record: R) => any, errorCallback?: (err: Error) => any) { SDK.REST.createRecord( this.record, this.logicalName, successCallback ? successCallback : NoOp, errorCallback ? errorCallback : NoOp); } } /** * Contains information about an Update query */ export class UpdateRecord<O> { /** * @internal */ private logicalName: string; /** * @internal */ private id: string; /** * @internal */ private record: O; constructor(entityPicker: (x: RestEntities) => RestMapping<O, any, any, any, any>, id: string, record: O) { this.logicalName = taggedExec(entityPicker).toString(); this.id = id; this.record = record; } execute(successCallback?: () => any, errorCallback?: (err: Error) => any) { SDK.REST.updateRecord( this.id, this.record, this.logicalName, successCallback ? successCallback : NoOp, errorCallback ? errorCallback : NoOp); } } /** * Contains information about a Delete query */ export class DeleteRecord<O> { /** * @internal */ private logicalName: string; /** * @internal */ private id: string; constructor(entityPicker: (x: RestEntities) => RestMapping<O, any, any, any, any>, id: string) { this.logicalName = taggedExec(entityPicker).toString(); this.id = id; } execute(successCallback?: () => any, errorCallback?: (err: Error) => any) { SDK.REST.deleteRecord( this.id, this.logicalName, successCallback ? successCallback : NoOp, errorCallback ? errorCallback : NoOp); } } }
the_stack
import { expect } from '../expect' import { fancy } from 'fancy-test' import { restore, replace, fake } from 'sinon' import Prompter from '../../src/services/user-prompt' import { ProviderLibrary, Logger, BoosterConfig } from '@boostercloud/framework-types' import * as Nuke from '../../src/commands/nuke' import * as providerService from '../../src/services/provider-service' import { oraLogger } from '../../src/services/logger' import { IConfig } from '@oclif/config' import { test } from '@oclif/test' import * as environment from '../../src/services/environment' import * as configService from '../../src/services/config-service' import * as projectChecker from '../../src/services/project-checker' const rewire = require('rewire') const nuke = rewire('../../src/commands/nuke') const runTasks = nuke.__get__('runTasks') const loader = nuke.__get__('askToConfirmRemoval') describe('nuke', () => { beforeEach(() => { delete process.env.BOOSTER_ENV }) afterEach(() => { restore() }) describe('runTasks function', () => { context('when an unexpected problem happens', () => { fancy.stdout().it('fails gracefully showing the error message', async () => { const msg = 'weird exception' const fakeLoader = Promise.reject(new Error(msg)) const fakeNuke = fake() replace(environment, 'currentEnvironment', fake.returns('test-env')) await expect(runTasks(fakeLoader, fakeNuke)).to.eventually.be.rejectedWith(msg) expect(fakeNuke).not.to.have.been.called }) }) context('when a wrong application name is provided', () => { fancy.stdout().it('fails gracefully showing the error message', async () => { const fakeProvider = {} as ProviderLibrary const fakeConfig = Promise.resolve({ provider: fakeProvider, appName: 'fake app', region: 'tunte', entities: {}, }) const prompter = new Prompter() const fakePrompter = fake.resolves('fake app 2') // The user entered wrong app name replace(prompter, 'defaultOrPrompt', fakePrompter) const fakeNuke = fake() const errorMsg = 'Wrong app name, stopping nuke!' replace(environment, 'currentEnvironment', fake.returns('test-env')) await expect(runTasks(loader(prompter, false, fakeConfig), fakeNuke)).to.eventually.be.rejectedWith(errorMsg) expect(fakeNuke).not.to.have.been.called }) }) context('when the --force flag is provided', () => { fancy.stdout().it('continues without asking for the application name', async () => { const fakeProvider = {} as ProviderLibrary const fakeConfig = Promise.resolve({ provider: fakeProvider, appName: 'fake app', region: 'tunte', entities: {}, }) const prompter = new Prompter() const fakePrompter = fake.resolves('fake app 2') // The user entered wrong app name replace(prompter, 'defaultOrPrompt', fakePrompter) const fakeNuke = fake() replace(environment, 'currentEnvironment', fake.returns('test-env')) await expect(runTasks(loader(prompter, true, fakeConfig), fakeNuke)).to.eventually.be.fulfilled expect(prompter.defaultOrPrompt).not.to.have.been.called expect(fakeNuke).to.have.been.calledOnce }) }) context('when a valid application name is provided', () => { fancy.stdout().it('starts removal', async (ctx) => { const fakeProvider = {} as ProviderLibrary const fakeConfig = Promise.resolve({ provider: fakeProvider, appName: 'fake app', region: 'tunte', entities: {}, }) const prompter = new Prompter() const fakePrompter = fake.resolves('fake app') replace(prompter, 'defaultOrPrompt', fakePrompter) const fakeNuke = fake((_config: unknown, logger: Logger) => { logger.info('this is a progress update') }) replace(environment, 'currentEnvironment', fake.returns('test-env')) await runTasks(loader(prompter, false, fakeConfig), fakeNuke) expect(ctx.stdout).to.include('Removal complete!') expect(fakeNuke).to.have.been.calledOnce }) }) }) describe('run', () => { context('when no environment provided', async () => { test .stdout() .command(['nuke']) .it('shows no environment provided error', (ctx) => { expect(ctx.stdout).to.match(/No environment set/) }) }) }) describe('command class', () => { beforeEach(() => { const config = new BoosterConfig('fake_environment') replace(configService, 'compileProjectAndLoadConfig', fake.resolves(config)) replace(providerService, 'nukeCloudProviderResources', fake.resolves({})) replace(projectChecker, 'checkCurrentDirBoosterVersion', fake.resolves({})) replace(oraLogger, 'fail', fake.resolves({})) replace(oraLogger, 'info', fake.resolves({})) replace(oraLogger, 'start', fake.resolves({})) replace(oraLogger, 'succeed', fake.resolves({})) }) it('init calls checkCurrentDirBoosterVersion', async () => { await new Nuke.default([], {} as IConfig).init() expect(projectChecker.checkCurrentDirBoosterVersion).to.have.been.called }) it('without flags', async () => { await new Nuke.default([], {} as IConfig).run() expect(configService.compileProjectAndLoadConfig).to.have.not.been.called expect(providerService.nukeCloudProviderResources).to.have.not.been.called expect(oraLogger.fail).to.have.been.calledWithMatch(/No environment set/) }) it('with -e flag incomplete', async () => { let exceptionThrown = false let exceptionMessage = '' try { await new Nuke.default(['-e'], {} as IConfig).run() } catch (e) { exceptionThrown = true exceptionMessage = e.message } expect(exceptionThrown).to.be.equal(true) expect(exceptionMessage).to.to.contain('--environment expects a value') expect(configService.compileProjectAndLoadConfig).to.have.not.been.called expect(providerService.nukeCloudProviderResources).to.have.not.been.called }) it('with --environment flag incomplete', async () => { let exceptionThrown = false let exceptionMessage = '' try { await new Nuke.default(['--environment'], {} as IConfig).run() } catch (e) { exceptionThrown = true exceptionMessage = e.message } expect(exceptionThrown).to.be.equal(true) expect(exceptionMessage).to.to.contain('--environment expects a value') expect(configService.compileProjectAndLoadConfig).to.have.not.been.called expect(providerService.nukeCloudProviderResources).to.have.not.been.called }) describe('inside a booster project', () => { it('entering correct environment and application name', async () => { replace(Prompter.prototype, 'defaultOrPrompt', fake.resolves('new-booster-app')) await new Nuke.default(['-e', 'fake_environment'], {} as IConfig).run() expect(configService.compileProjectAndLoadConfig).to.have.been.called expect(providerService.nukeCloudProviderResources).to.have.been.called expect(oraLogger.info).to.have.been.calledWithMatch('Removal complete!') }) it('entering correct environment and --force flag', async () => { await new Nuke.default(['-e', 'fake_environment', '--force'], {} as IConfig).run() expect(configService.compileProjectAndLoadConfig).to.have.been.called expect(providerService.nukeCloudProviderResources).to.have.been.called expect(oraLogger.info).to.have.been.calledWithMatch('Removal complete!') }) it('entering correct environment and -f flag', async () => { await new Nuke.default(['-e', 'fake_environment', '-f'], {} as IConfig).run() expect(configService.compileProjectAndLoadConfig).to.have.been.called expect(providerService.nukeCloudProviderResources).to.have.been.called expect(oraLogger.info).to.have.been.calledWithMatch('Removal complete!') }) it('entering correct environment but a wrong application name', async () => { replace(Prompter.prototype, 'defaultOrPrompt', fake.resolves('fake app 2')) let exceptionThrown = false let exceptionMessage = '' try { await new Nuke.default(['-e', 'fake_environment'], {} as IConfig).run() } catch (e) { exceptionThrown = true exceptionMessage = e.message } expect(exceptionThrown).to.be.equal(true) expect(exceptionMessage).to.contain('Wrong app name, stopping nuke!') expect(configService.compileProjectAndLoadConfig).to.have.been.called expect(providerService.nukeCloudProviderResources).to.have.not.been.called expect(oraLogger.info).to.have.not.been.calledWithMatch('Removal complete!') }) it('entering correct environment and nonexisting flag', async () => { let exceptionThrown = false let exceptionMessage = '' try { await new Nuke.default(['-e', 'fake_environment', '--nonexistingoption'], {} as IConfig).run() } catch (e) { exceptionThrown = true exceptionMessage = e.message } expect(exceptionThrown).to.be.equal(true) expect(exceptionMessage).to.contain('Unexpected argument: --nonexistingoption') expect(providerService.nukeCloudProviderResources).to.have.not.been.called expect(oraLogger.info).to.have.not.been.calledWithMatch('Removal complete!') }) it('without defining environment and --force', async () => { await new Nuke.default(['--force'], {} as IConfig).run() expect(providerService.nukeCloudProviderResources).to.have.not.been.called expect(oraLogger.fail).to.have.been.calledWithMatch(/No environment set/) }) }) }) })
the_stack
import { GraphQLQueryGenerator } from '../../../src/services/graphql/graphql-query-generator' import { SinonStub, stub, replace, SinonStubbedInstance, restore, fake } from 'sinon' import { expect } from '../../expect' import { GraphQLTypeInformer } from '../../../src/services/graphql/graphql-type-informer' import sinon = require('sinon') import { GraphQLResolverContext, TargetTypesMap } from '../../../src/services/graphql/common' import { GraphQLBoolean, GraphQLEnumType, GraphQLFloat, GraphQLID, GraphQLInt, GraphQLNonNull, GraphQLOutputType, GraphQLString, GraphQLFieldConfigMap, GraphQLList, GraphQLObjectType, } from 'graphql' import { random } from 'faker' import GraphQLJSON, { GraphQLJSONObject } from 'graphql-type-json' import { BoosterConfig, UUID, TimeKey } from '@boostercloud/framework-types' function buildFakeGraphQLFielConfigMap(name: string): GraphQLFieldConfigMap<unknown, GraphQLResolverContext> { return { [name]: { type: GraphQLString, args: {}, resolve: fake(), }, } } describe('GraphQLQueryGenerator', () => { afterEach(() => { restore() }) describe('the `generate` public method', () => { const simpleConfig = new BoosterConfig('test') class SomeReadModel {} const fakeReadModelsMetadata = { SomeReadModel: { class: SomeReadModel, properties: [], }, } const typeInformer = new GraphQLTypeInformer({ ...fakeReadModelsMetadata, }) const graphQLQueryGenerator = new GraphQLQueryGenerator( simpleConfig, fakeReadModelsMetadata, typeInformer, () => fake(), () => fake(), fake() ) it('generates by Key queries', () => { const fakegenerateByKeysQueries = fake() replace(graphQLQueryGenerator as any, 'generateByKeysQueries', fakegenerateByKeysQueries) replace(graphQLQueryGenerator as any, 'generateFilterQueries', fake()) replace(graphQLQueryGenerator as any, 'generateListedQueries', fake()) replace(graphQLQueryGenerator as any, 'generateEventQueries', fake()) graphQLQueryGenerator.generate() expect(fakegenerateByKeysQueries).to.have.been.calledOnce }) it('generates filter queries', () => { replace(graphQLQueryGenerator as any, 'generateByKeysQueries', fake()) const fakeGenerateFilterQueries = fake() replace(graphQLQueryGenerator as any, 'generateFilterQueries', fakeGenerateFilterQueries) replace(graphQLQueryGenerator as any, 'generateListedQueries', fake()) replace(graphQLQueryGenerator as any, 'generateEventQueries', fake()) graphQLQueryGenerator.generate() expect(fakeGenerateFilterQueries).to.have.been.calledOnce }) it('generates listed queries', () => { replace(graphQLQueryGenerator as any, 'generateByKeysQueries', fake()) replace(graphQLQueryGenerator as any, 'generateFilterQueries', fake()) const fakeGenerateListedQueries = fake() replace(graphQLQueryGenerator as any, 'generateListedQueries', fakeGenerateListedQueries) replace(graphQLQueryGenerator as any, 'generateEventQueries', fake()) graphQLQueryGenerator.generate() expect(fakeGenerateListedQueries).to.have.been.calledOnce }) it('generates event queries', () => { replace(graphQLQueryGenerator as any, 'generateByKeysQueries', fake()) replace(graphQLQueryGenerator as any, 'generateFilterQueries', fake()) replace(graphQLQueryGenerator as any, 'generateListedQueries', fake()) const fakeGenerateEventQueries = fake() replace(graphQLQueryGenerator as any, 'generateEventQueries', fakeGenerateEventQueries) graphQLQueryGenerator.generate() expect(fakeGenerateEventQueries).to.have.been.calledOnce }) it('returns a well-formed GraphQL Query Object Type', () => { const fakeIDQueries = buildFakeGraphQLFielConfigMap('IDQuery') replace(graphQLQueryGenerator as any, 'generateByKeysQueries', fake.returns(fakeIDQueries)) const fakeFilterQueries = buildFakeGraphQLFielConfigMap('FilterQuery') replace(graphQLQueryGenerator as any, 'generateFilterQueries', fake.returns(fakeFilterQueries)) const fakeListedQueries = buildFakeGraphQLFielConfigMap('ListedQuery') replace(graphQLQueryGenerator as any, 'generateListedQueries', fake.returns(fakeListedQueries)) const fakeEventQueries = buildFakeGraphQLFielConfigMap('EventQuery') replace(graphQLQueryGenerator as any, 'generateEventQueries', fake.returns(fakeEventQueries)) const result = graphQLQueryGenerator.generate() expect(result).to.have.property('name', 'Query') const fieldNames = Object.keys(result.getFields()) expect(fieldNames).to.include('IDQuery') expect(fieldNames).to.include('FilterQuery') expect(fieldNames).to.include('ListedQuery') expect(fieldNames).to.include('EventQuery') }) context('black box tests', () => { let mockTargetTypes: TargetTypesMap let mockGraphQLType: any let mockTypeInformer: SinonStubbedInstance<GraphQLTypeInformer> let mockByIdResolverBuilder: SinonStub let mockFilterResolverBuilder: SinonStub let mockEventsResolver: SinonStub let getGraphQLTypeForStub: SinonStub let isGraphQLScalarTypeStub: SinonStub beforeEach(() => { mockTargetTypes = {} mockGraphQLType = random.arrayElement([ GraphQLBoolean, GraphQLID, GraphQLString, GraphQLFloat, GraphQLInt, GraphQLJSON, ]) mockTypeInformer = sinon.createStubInstance(GraphQLTypeInformer) mockByIdResolverBuilder = stub() mockFilterResolverBuilder = stub() mockEventsResolver = stub() getGraphQLTypeForStub = stub().returns(mockGraphQLType) replace(mockTypeInformer, 'getGraphQLTypeFor', getGraphQLTypeForStub as any) isGraphQLScalarTypeStub = stub().returns(mockGraphQLType) replace(mockTypeInformer, 'isGraphQLScalarType', isGraphQLScalarTypeStub as any) }) context('with target types', () => { context('1 target type', () => { let mockTargetTypeClass: BooleanConstructor | StringConstructor | NumberConstructor let mockTargetTypeName: string let sut: GraphQLQueryGenerator beforeEach(() => { mockTargetTypeClass = random.arrayElement([Boolean, String, Number]) mockTargetTypeName = mockTargetTypeClass.name.toLowerCase() // Provision target types mockTargetTypes = {} mockTargetTypes[mockTargetTypeName] = { class: mockTargetTypeClass, properties: [], } sut = new GraphQLQueryGenerator( simpleConfig, mockTargetTypes, mockTypeInformer as any, mockByIdResolverBuilder, mockFilterResolverBuilder, mockEventsResolver ) }) it('should call typeInformer.getGraphQLTypeFor thrice', () => { sut.generate() expect(getGraphQLTypeForStub).calledThrice.and.calledWith(mockTargetTypeClass) }) it('should call filterResolverBuilder once with expected argument', () => { sut.generate() expect(mockByIdResolverBuilder).calledOnce.and.calledWith(mockTargetTypeClass) // @ts-ignore expect(mockByIdResolverBuilder).to.be.calledAfter(getGraphQLTypeForStub) }) it('should return expected result', () => { const result = sut.generate() expect(result.name).to.be.equal('Query') expect(result.description).to.be.undefined expect(result.extensions).to.be.undefined expect(result.astNode).to.be.undefined expect(result.extensionASTNodes).to.be.undefined const config: any = result.toConfig() expect(config.fields[mockTargetTypeName].description).to.be.undefined expect(config.fields[mockTargetTypeName].type).to.be.equal(mockGraphQLType) expect(config.fields[mockTargetTypeName].resolve).to.be.undefined expect(config.fields[mockTargetTypeName].subscribe).to.be.undefined expect(config.fields[mockTargetTypeName].deprecationReason).to.be.undefined expect(config.fields[mockTargetTypeName].extensions).to.be.undefined expect(config.fields[mockTargetTypeName].astNode).to.be.undefined expect(config.fields[`${mockTargetTypeName}s`].description).to.be.undefined expect(config.fields[`${mockTargetTypeName}s`].type.toString()).to.be.equal(`[${mockGraphQLType}]`) expect(config.fields[`${mockTargetTypeName}s`].resolve).to.be.undefined expect(config.fields[`${mockTargetTypeName}s`].subscribe).to.be.undefined expect(config.fields[`${mockTargetTypeName}s`].deprecationReason).to.be.undefined expect(config.fields[`${mockTargetTypeName}s`].extensions).to.be.undefined expect(config.fields[`${mockTargetTypeName}s`].astNode).to.be.undefined }) describe('Array with properties', () => { let mockPropertyName: string let mockTargetType: any let mockPropertyType: any beforeEach(() => { // Provision target types mockPropertyName = random.alphaNumeric(10) mockTargetType = Array mockPropertyType = Boolean mockTargetTypes = {} mockTargetTypes[mockTargetTypeName] = { class: mockTargetType, properties: [ { name: mockPropertyName, typeInfo: { name: mockPropertyType.name, type: mockPropertyType, parameters: [], }, }, ], } replace(mockTypeInformer, 'getOriginalAncestor', stub().returnsArg(0) as any) }) context('Property GraphQL Type is scalar', () => { beforeEach(() => { sut = new GraphQLQueryGenerator( simpleConfig, mockTargetTypes, mockTypeInformer as any, mockByIdResolverBuilder, mockFilterResolverBuilder, mockEventsResolver ) }) it('should call typeInformer.getGraphQLTypeFor 4 times', () => { sut.generate() expect(getGraphQLTypeForStub) .callCount(4) .and.calledWith(mockTargetType) .and.calledWith(mockPropertyType) }) it('should call filterResolverBuilder once with expected arguments', () => { sut.generate() expect(mockByIdResolverBuilder).to.be.calledOnce.and.calledWith(mockTargetType) // @ts-ignore expect(mockByIdResolverBuilder).to.be.calledAfter(getGraphQLTypeForStub) }) context('should have expected args', () => { it('When Boolean', () => { const result = sut.generate() const config: any = result.toConfig() expect(config.fields[mockTargetTypeName].args['id'].type.toString()).to.be.equal('ID!') expect(config.fields[mockTargetTypeName].args['id'].astNode).to.be.undefined expect(config.fields[mockTargetTypeName].args['id'].defaultValue).to.be.undefined expect(config.fields[mockTargetTypeName].args['id'].description).to.be.undefined expect(config.fields[mockTargetTypeName].args['id'].extensions).to.be.undefined const booleansTypeFilterConfig = config.fields[`${mockTargetTypeName}s`].args.filter.type.getFields()[mockPropertyName] expect(booleansTypeFilterConfig.type.toString()).to.be.equal('BooleanPropertyFilter') const fieldsKeys = Object.keys(booleansTypeFilterConfig.type.getFields()) expect(fieldsKeys).to.be.deep.equal(['eq', 'ne']) expect(fieldsKeys.length).to.equal(2) fieldsKeys.forEach((fieldKey) => { expect(booleansTypeFilterConfig.type.getFields()[fieldKey].description).to.be.undefined expect(booleansTypeFilterConfig.type.getFields()[fieldKey].type.toString()).to.be.equal('Boolean') expect(booleansTypeFilterConfig.type.getFields()[fieldKey].defaultValue).to.be.undefined expect(booleansTypeFilterConfig.type.getFields()[fieldKey].extensions).to.be.undefined expect(booleansTypeFilterConfig.type.getFields()[fieldKey].astNode).to.be.undefined }) }) it('When Number', () => { mockPropertyName = random.alphaNumeric(10) mockTargetType = Array mockPropertyType = Number mockTargetTypes = {} mockTargetTypes[mockTargetTypeName] = { class: mockTargetType, properties: [ { name: mockPropertyName, typeInfo: { name: mockPropertyType.name, type: mockPropertyType, parameters: [], }, }, ], } sut = new GraphQLQueryGenerator( simpleConfig, mockTargetTypes, mockTypeInformer as any, mockByIdResolverBuilder, mockFilterResolverBuilder, mockEventsResolver ) const result = sut.generate() const config: any = result.toConfig() expect(config.fields[mockTargetTypeName].args['id'].type.toString()).to.be.equal('ID!') expect(config.fields[mockTargetTypeName].args['id'].astNode).to.be.undefined expect(config.fields[mockTargetTypeName].args['id'].defaultValue).to.be.undefined expect(config.fields[mockTargetTypeName].args['id'].description).to.be.undefined expect(config.fields[mockTargetTypeName].args['id'].extensions).to.be.undefined const TypeFilterConfig = config.fields[`${mockTargetTypeName}s`].args.filter.type.getFields()[mockPropertyName] expect(TypeFilterConfig.type.toString()).to.be.equal('NumberPropertyFilter') const fieldsKeys = Object.keys(TypeFilterConfig.type.getFields()) expect(fieldsKeys).to.be.deep.equal(['eq', 'ne', 'lte', 'lt', 'gte', 'gt', 'in']) expect(fieldsKeys.length).to.equal(7) fieldsKeys.forEach((fieldKey) => { expect(TypeFilterConfig.type.getFields()[fieldKey].description).to.be.undefined const type = fieldKey === 'in' ? '[Float]' : 'Float' // The in filter expects an array of the element expect(TypeFilterConfig.type.getFields()[fieldKey].type.toString()).to.be.equal(type) expect(TypeFilterConfig.type.getFields()[fieldKey].defaultValue).to.be.undefined expect(TypeFilterConfig.type.getFields()[fieldKey].extensions).to.be.undefined expect(TypeFilterConfig.type.getFields()[fieldKey].astNode).to.be.undefined }) }) it('When String', () => { mockPropertyName = random.alphaNumeric(10) mockTargetType = Array mockPropertyType = String mockTargetTypes = {} mockTargetTypes[mockTargetTypeName] = { class: mockTargetType, properties: [ { name: mockPropertyName, typeInfo: { name: mockPropertyType.name, type: mockPropertyType, parameters: [], }, }, ], } sut = new GraphQLQueryGenerator( simpleConfig, mockTargetTypes, mockTypeInformer as any, mockByIdResolverBuilder, mockFilterResolverBuilder, mockEventsResolver ) const result = sut.generate() const config: any = result.toConfig() expect(config.fields[mockTargetTypeName].args['id'].type.toString()).to.be.equal('ID!') expect(config.fields[mockTargetTypeName].args['id'].astNode).to.be.undefined expect(config.fields[mockTargetTypeName].args['id'].defaultValue).to.be.undefined expect(config.fields[mockTargetTypeName].args['id'].description).to.be.undefined expect(config.fields[mockTargetTypeName].args['id'].extensions).to.be.undefined const TypeFilterConfig = config.fields[`${mockTargetTypeName}s`].args.filter.type.getFields()[mockPropertyName] expect(TypeFilterConfig.type.toString()).to.be.equal('StringPropertyFilter') const fieldsKeys = Object.keys(TypeFilterConfig.type.getFields()) expect(fieldsKeys).to.be.deep.equal([ 'eq', 'ne', 'lte', 'lt', 'gte', 'gt', 'in', 'beginsWith', 'contains', ]) expect(fieldsKeys.length).to.equal(9) fieldsKeys.forEach((fieldKey) => { expect(TypeFilterConfig.type.getFields()[fieldKey].description).to.be.undefined const type = fieldKey === 'in' ? '[String]' : 'String' // The in filter expects an array of the element expect(TypeFilterConfig.type.getFields()[fieldKey].type.toString()).to.be.equal(type) expect(TypeFilterConfig.type.getFields()[fieldKey].defaultValue).to.be.undefined expect(TypeFilterConfig.type.getFields()[fieldKey].extensions).to.be.undefined expect(TypeFilterConfig.type.getFields()[fieldKey].astNode).to.be.undefined }) }) }) }) context('Property GraphQL Type is GraphQLJSONObject', () => { beforeEach(() => { class MockedClass {} getGraphQLTypeForStub.returns(GraphQLJSONObject) isGraphQLScalarTypeStub.returns(false) mockPropertyName = random.alphaNumeric(10) mockTargetType = Array mockPropertyType = MockedClass mockTargetTypes = {} mockTargetTypes[mockTargetTypeName] = { class: mockTargetType, properties: [ { name: mockPropertyName, typeInfo: { name: mockPropertyType.name, type: mockPropertyType, parameters: [], }, }, ], } sut = new GraphQLQueryGenerator( simpleConfig, mockTargetTypes, mockTypeInformer as any, mockByIdResolverBuilder, mockFilterResolverBuilder, mockEventsResolver ) }) it('should call typeInformer.getGraphQLTypeFor 5 times', () => { sut.generate() expect(getGraphQLTypeForStub) .callCount(5) .and.calledWith(mockTargetType) .and.calledWith(mockPropertyType) }) it('should call filterResolverBuilder once with expected arguments', () => { sut.generate() expect(mockByIdResolverBuilder).to.be.calledOnce.and.calledWith(mockTargetType) // @ts-ignore expect(mockByIdResolverBuilder).to.be.calledAfter(getGraphQLTypeForStub) }) }) context('Property GraphQL Type is GraphQLString', () => { beforeEach(() => { getGraphQLTypeForStub.returns(GraphQLString) mockPropertyName = random.alphaNumeric(10) mockTargetType = Array mockPropertyType = String mockTargetTypes = {} mockTargetTypes[mockTargetTypeName] = { class: mockTargetType, properties: [ { name: mockPropertyName, typeInfo: { name: mockPropertyType.name, type: mockPropertyType, parameters: [], }, }, ], } sut = new GraphQLQueryGenerator( simpleConfig, mockTargetTypes, mockTypeInformer as any, mockByIdResolverBuilder, mockFilterResolverBuilder, mockEventsResolver ) }) it('should call typeInformer.getGraphQLTypeFor 4 times', () => { sut.generate() expect(getGraphQLTypeForStub) .callCount(4) .and.calledWith(mockTargetType) .and.calledWith(mockPropertyType) }) it('should call filterResolverBuilder once with expected arguments', () => { sut.generate() expect(mockByIdResolverBuilder).to.be.calledOnce.and.calledWith(mockTargetType) // @ts-ignore expect(mockByIdResolverBuilder).to.be.calledAfter(getGraphQLTypeForStub) }) }) }) }) context('several target types', () => { let sut: GraphQLQueryGenerator beforeEach(() => { // Provision target types mockTargetTypes = {} mockTargetTypes['boolean'] = { class: Boolean, properties: [], } mockTargetTypes['string'] = { class: String, properties: [], } sut = new GraphQLQueryGenerator( simpleConfig, mockTargetTypes, mockTypeInformer as any, mockByIdResolverBuilder, mockFilterResolverBuilder, mockEventsResolver ) }) it('should call typeInformer.getGraphQLTypeFor n of target types * 2', () => { sut.generate() expect(getGraphQLTypeForStub).callCount(6).and.calledWith(Boolean).and.calledWith(String) }) it('should call filterResolverBuilder twice with expected arguments', () => { sut.generate() expect(mockByIdResolverBuilder).to.be.calledTwice.and.calledWith(Boolean).and.calledWith(String) // @ts-ignore expect(mockByIdResolverBuilder).to.be.calledAfter(getGraphQLTypeForStub) }) describe('repeated type', () => { beforeEach(() => { // Provision target types mockTargetTypes = {} mockTargetTypes['boolean'] = { class: Boolean, properties: [], } mockTargetTypes['string'] = { class: String, properties: [], } mockTargetTypes['string'] = { class: String, properties: [], } sut = new GraphQLQueryGenerator( simpleConfig, mockTargetTypes, mockTypeInformer as any, mockByIdResolverBuilder, mockFilterResolverBuilder, mockEventsResolver ) }) it('should call typeInformer.getGraphQLTypeFor (number of types * 2) - (2 * (repeated types))', () => { sut.generate() expect(getGraphQLTypeForStub).to.be.callCount(6).and.calledWith(Boolean).and.calledWith(String) }) it('should call filterResolverBuilder twice with expected arguments', () => { sut.generate() expect(mockByIdResolverBuilder).to.be.calledTwice.and.calledWith(Boolean).and.calledWith(String) // @ts-ignore expect(mockByIdResolverBuilder).to.be.calledAfter(getGraphQLTypeForStub) }) }) }) context('Cannot filter type', () => { // TODO: Currently it is not possible to filter complex properties }) }) context('with a config with events and entities', () => { let sut: GraphQLQueryGenerator const entityNames = ['TestEntity1', 'TestEntity2', 'TestEntity3'] const eventTypeNames = ['EventType1', 'EventType2', 'EventType3'] beforeEach(() => { const configWithEventsAndEntities = new BoosterConfig('test') for (const entityName of entityNames) { configWithEventsAndEntities.entities[entityName] = {} as never } for (const eventTypeName of eventTypeNames) { configWithEventsAndEntities.reducers[eventTypeName] = {} as never } sut = new GraphQLQueryGenerator( configWithEventsAndEntities, mockTargetTypes, mockTypeInformer as any, mockByIdResolverBuilder, mockFilterResolverBuilder, mockEventsResolver ) }) it('should return expected result', () => { const result = sut.generate().toConfig() expect(result.name).to.be.equal('Query') expect(new Set(Object.keys(result.fields))).to.be.deep.equal(new Set(['eventsByEntity', 'eventsByType'])) const eventsByEntityField = result.fields['eventsByEntity'] expect(new Set(Object.keys(eventsByEntityField.args!))).to.be.deep.equal( new Set(['entity', 'entityID', 'from', 'to']) ) const entityEnumType = (eventsByEntityField.args!['entity'].type as GraphQLNonNull<GraphQLEnumType>).ofType expect(new Set(entityEnumType.getValues().map((v) => v.value))).to.be.deep.equal(new Set(entityNames)) assertEventSearchQueryReturnType(eventsByEntityField.type) const eventsByType = result.fields['eventsByType'] expect(new Set(Object.keys(eventsByType.args!))).to.be.deep.equal(new Set(['type', 'from', 'to'])) const eventTypeEnumType = (eventsByType.args!['type'].type as GraphQLNonNull<GraphQLEnumType>).ofType expect(new Set(eventTypeEnumType.getValues().map((v) => v.value))).to.be.deep.equal(new Set(eventTypeNames)) assertEventSearchQueryReturnType(eventsByType.type) }) function assertEventSearchQueryReturnType(queryReturnType: GraphQLOutputType): void { expect(queryReturnType).to.be.instanceOf(GraphQLList) const returnElementType = (queryReturnType as GraphQLList<GraphQLObjectType>).ofType expect(returnElementType.name).to.be.equal('EventQueryResponse') expect(new Set(Object.keys(returnElementType.getFields()))).to.be.deep.equal( new Set(['type', 'entity', 'requestID', 'entityID', 'user', 'createdAt', 'value']) ) const userType = returnElementType.getFields()['user'].type as GraphQLObjectType expect(new Set(Object.keys(userType.getFields()))).to.be.deep.equal(new Set(['id', 'username', 'role'])) } }) context('without target types', () => { let sut: GraphQLQueryGenerator beforeEach(() => { sut = new GraphQLQueryGenerator( simpleConfig, mockTargetTypes, mockTypeInformer as any, mockByIdResolverBuilder, mockFilterResolverBuilder, mockEventsResolver ) }) it('should not call typeInformer.getGraphQLTypeFor', () => { sut.generate() expect(getGraphQLTypeForStub).to.not.be.called }) it('should return only the event queries', () => { const result = sut.generate() expect(result.name).to.be.equal('Query') const config = result.toConfig() expect(Object.keys(config.fields).length).to.eq(2) expect(config.fields).to.include.keys('eventsByEntity', 'eventsByType') }) }) }) }) describe('the `generateByKeysQueries` private method', () => { class AnotherReadModel { public constructor(readonly id: UUID, readonly otherField: string) {} } class ASequencedReadModel { public constructor(readonly id: UUID, readonly timestamp: TimeKey) {} } const fakeReadModelsMetadata: TargetTypesMap = { AnotherReadModel: { class: AnotherReadModel, properties: [], }, ASequencedReadModel: { class: ASequencedReadModel, properties: [], }, } const typeInformer = new GraphQLTypeInformer({ ...fakeReadModelsMetadata, }) const config = new BoosterConfig('test') config.readModelSequenceKeys['ASequencedReadModel'] = 'timestamp' const graphQLQueryGenerator = new GraphQLQueryGenerator( config, fakeReadModelsMetadata, typeInformer, () => fake(), () => fake(), fake() ) as any // So we can see private methods it('generates by ID and sequenced queries', () => { const fakeGenerateByIdQuery = fake() replace(graphQLQueryGenerator, 'generateByIdQuery', fakeGenerateByIdQuery) const fakeGenerateByIdAndSequenceKeyQuery = fake() replace(graphQLQueryGenerator, 'generateByIdAndSequenceKeyQuery', fakeGenerateByIdAndSequenceKeyQuery) graphQLQueryGenerator.generateByKeysQueries() expect(fakeGenerateByIdQuery).to.have.been.calledOnceWith('AnotherReadModel') expect(fakeGenerateByIdAndSequenceKeyQuery).to.have.been.calledOnceWith('ASequencedReadModel', 'timestamp') }) }) describe('the `generateByIdQuery` private method', () => { class ARegularReadModel { readonly id: string = '∫' } const fakeReadModelsMetadata: TargetTypesMap = { ARegularReadModel: { class: ARegularReadModel, properties: [], }, } const typeInformer = new GraphQLTypeInformer({ ...fakeReadModelsMetadata, }) const config = new BoosterConfig('test') const graphQLQueryGenerator = new GraphQLQueryGenerator( config, fakeReadModelsMetadata, typeInformer, () => fake(), () => fake(), fake() ) as any // So we can see private methods it('generates a query named after the read model class that accepts a unique ID', () => { const fakeByIdResolverBuilder = fake.returns(fake()) replace(graphQLQueryGenerator, 'byIDResolverBuilder', fakeByIdResolverBuilder) const query = graphQLQueryGenerator.generateByIdQuery('ARegularReadModel') expect(query.type).to.has.a.property('name', 'ARegularReadModel') expect(query.args).to.have.a.property('id') expect(query.resolve).to.be.a('Function') expect(fakeByIdResolverBuilder).to.have.been.calledWith(ARegularReadModel) }) }) describe('the `generateByIdAndSequenceKeyQuery` private method', () => { class AnotherSequencedReadModel { readonly id: string = 'µ' readonly timestamp: string = '™' } const fakeReadModelsMetadata: TargetTypesMap = { AnotherSequencedReadModel: { class: AnotherSequencedReadModel, properties: [], }, } const typeInformer = new GraphQLTypeInformer({ ...fakeReadModelsMetadata, }) const config = new BoosterConfig('test') const graphQLQueryGenerator = new GraphQLQueryGenerator( config, fakeReadModelsMetadata, typeInformer, () => fake(), () => fake(), fake() ) as any // So we can see private methods it('generates a query named after the read model class that accepts an ID and a sequence key', () => { const fakeByIdResolverBuilder = fake.returns(fake()) replace(graphQLQueryGenerator, 'byIDResolverBuilder', fakeByIdResolverBuilder) const query = graphQLQueryGenerator.generateByIdAndSequenceKeyQuery('AnotherSequencedReadModel', 'timestamp') expect(query.type).to.be.a('GraphQLList') expect(query.type.ofType).to.have.a.property('name', 'AnotherSequencedReadModel') expect(query.args).to.have.a.property('id') expect(query.args).to.have.a.property('timestamp') expect(query.resolve).to.be.a('Function') expect(fakeByIdResolverBuilder).to.have.been.calledWith(AnotherSequencedReadModel) }) }) describe('the `generateFilterQueries` private method', () => { it( 'generates a query named after the plural version of the read model name that responds with a list of read model instances' ) // TODO }) describe('the `generateListedQueries` private method', () => { it( 'generates a query named List<PluralizedNameOfReadModel> that responds with a paginated list of read model instances' ) // TODO }) describe('the `generateEventsQueries` private method', () => { it('generates event queries for specific entities') // TODO }) })
the_stack
import { module, test } from 'qunit'; import { click, currentURL, fillIn, settled, visit, waitFor, waitUntil, } from '@ember/test-helpers'; import { setupApplicationTest } from 'ember-qunit'; import percySnapshot from '@percy/ember'; import Layer2TestWeb3Strategy from '@cardstack/web-client/utils/web3-strategies/test-layer2'; import WorkflowPersistence from '@cardstack/web-client/services/workflow-persistence'; import { currentNetworkDisplayInfo as c } from '@cardstack/web-client/utils/web3-strategies/network-display-info'; import { setupMirage } from 'ember-cli-mirage/test-support'; import { convertAmountToNativeDisplay, spendToUsd, } from '@cardstack/cardpay-sdk'; import { setupHubAuthenticationToken } from '../helpers/setup'; import { MirageTestContext } from 'ember-cli-mirage/test-support'; import { formatAmount } from '@cardstack/web-client/helpers/format-amount'; import { createDepotSafe, createPrepaidCardSafe, createSafeToken, } from '@cardstack/web-client/utils/test-factories'; interface Context extends MirageTestContext {} function postableSel(milestoneIndex: number, postableIndex: number): string { return `[data-test-milestone="${milestoneIndex}"][data-test-postable="${postableIndex}"]`; } function epiloguePostableSel(postableIndex: number): string { return `[data-test-epilogue][data-test-postable="${postableIndex}"]`; } function milestoneCompletedSel(milestoneIndex: number): string { return `[data-test-milestone-completed][data-test-milestone="${milestoneIndex}"]`; } async function selectPrepaidCard(cardAddress: string) { await click(`[data-test-card-picker-dropdown] > [role="button"]`); await waitFor(`[data-test-card-picker-dropdown-option="${cardAddress}"]`); await click(`[data-test-card-picker-dropdown-option="${cardAddress}"]`); } let layer2AccountAddress = '0x182619c6Ea074C053eF3f1e1eF81Ec8De6Eb6E44'; let prepaidCardAddress = '0x123400000000000000000000000000000000abcd'; let secondLayer2AccountAddress = '0x5416C61193C3393B46C2774ac4717C252031c0bE'; let secondPrepaidCardAddress = '0x123400000000000000000000000000000000defa'; let merchantAddress = '0x1234000000000000000000000000000000004321'; function createMockPrepaidCard( eoaAddress: string, prepaidCardAddress: string, amount: number ) { return createPrepaidCardSafe({ address: prepaidCardAddress, owners: [eoaAddress], spendFaceValue: amount, prepaidCardOwner: eoaAddress, issuer: eoaAddress, }); } module('Acceptance | create merchant', function (hooks) { setupApplicationTest(hooks); setupMirage(hooks); let merchantRegistrationFee: number; hooks.beforeEach(async function () { merchantRegistrationFee = await this.owner .lookup('service:layer2-network') .strategy.fetchMerchantRegistrationFee(); }); test('initiating workflow without wallet connections', async function (assert) { await visit('/card-pay'); await click('[data-test-card-pay-header-tab][href="/card-pay/payments"]'); assert.equal(currentURL(), '/card-pay/payments'); await click('[data-test-workflow-button="create-business"]'); let post = postableSel(0, 0); assert.dom(`${postableSel(0, 0)} img`).exists(); assert.dom(postableSel(0, 0)).containsText('Hello, nice to see you!'); assert.dom(postableSel(0, 1)).containsText('create a business account'); assert .dom(postableSel(0, 2)) .containsText('connect your L2 test chain wallet'); assert .dom(postableSel(0, 3)) .containsText( 'Once you have installed the app, open the app and add an existing wallet/account' ); assert .dom(`${postableSel(0, 4)} [data-test-wallet-connect-loading-qr-code]`) .exists(); let layer2Service = this.owner.lookup('service:layer2-network') .strategy as Layer2TestWeb3Strategy; layer2Service.test__simulateWalletConnectUri(); await waitFor('[data-test-wallet-connect-qr-code]'); assert.dom('[data-test-wallet-connect-qr-code]').exists(); // Simulate the user scanning the QR code and connecting their mobile wallet layer2Service.test__simulateRemoteAccountSafes(layer2AccountAddress, [ createDepotSafe({ owners: [layer2AccountAddress], tokens: [createSafeToken('DAI.CPXD', '0')], }), createMockPrepaidCard( layer2AccountAddress, prepaidCardAddress, merchantRegistrationFee ), ]); await layer2Service.test__simulateAccountsChanged([layer2AccountAddress]); await waitUntil( () => !document.querySelector('[data-test-wallet-connect-qr-code]') ); assert .dom( '[data-test-card-pay-layer-2-connect] [data-test-card-pay-connect-button]' ) .hasText('0x1826...6E44'); await waitFor(milestoneCompletedSel(0)); assert .dom(milestoneCompletedSel(0)) .containsText('L2 test chain wallet connected'); post = postableSel(1, 0); await waitFor(post); assert .dom(post) .containsText( 'To store data in the Cardstack Hub, you need to authenticate using your Card Wallet' ); post = postableSel(1, 1); await waitFor(post); await click( `${post} [data-test-boxel-action-chin] [data-test-boxel-button]` ); layer2Service.test__simulateHubAuthentication('abc123--def456--ghi789'); await waitFor(postableSel(1, 2)); assert .dom(postableSel(1, 2)) .containsText('Let’s create a new business account.'); post = postableSel(1, 3); await waitFor(post); assert.dom(post).containsText('Choose a name and ID for the business'); // // merchant-customization card // TODO verify and interact with merchant customization card default state await fillIn( `[data-test-merchant-customization-merchant-name-field] input`, 'Mandello' ); await fillIn( `[data-test-merchant-customization-merchant-id-field] input`, 'mandello1' ); await waitUntil( () => ( document.querySelector( '[data-test-validation-state-input]' ) as HTMLElement ).dataset.testValidationStateInput === 'valid' ); await click(`[data-test-merchant-customization-save-details]`); await waitFor(milestoneCompletedSel(1)); assert.dom(milestoneCompletedSel(1)).containsText('Business details saved'); // prepaid-card-choice card post = postableSel(2, 2); await waitFor(post); await click(`${post} [data-test-card-picker-dropdown] > [role="button"]`); await waitFor( `${post} [data-test-card-picker-dropdown-option="${prepaidCardAddress}"]` ); await click( `${post} [data-test-card-picker-dropdown-option="${prepaidCardAddress}"]` ); await click( `${post} [data-test-boxel-action-chin] [data-test-boxel-button]` ); // need wait for Hub POST /api/merchant-infos // eslint-disable-next-line ember/no-settled-after-test-helper await settled(); layer2Service.test__simulateRegisterMerchantForAddress( prepaidCardAddress, merchantAddress, {} ); await waitFor('[data-test-prepaid-card-choice-is-complete]'); assert.dom(`[data-test-card-picker-dropdown]`).doesNotExist(); assert .dom('[data-test-prepaid-card-choice-merchant-address]') .containsText(merchantAddress); await waitFor(milestoneCompletedSel(2)); assert .dom(milestoneCompletedSel(2)) .containsText('Business account created'); assert .dom(epiloguePostableSel(0)) .containsText('You have created a business account.'); await waitFor(epiloguePostableSel(1)); await percySnapshot(assert); await click( `${epiloguePostableSel( 1 )} [data-test-create-merchant-next-step="dashboard"]` ); assert.dom('[data-test-workflow-thread]').doesNotExist(); await visit('/card-pay/wallet'); assert .dom('[data-test-card-balances]') .containsText('§0', 'expected card balance to have updated'); }); module('Tests with the layer 2 wallet already connected', function (hooks) { setupHubAuthenticationToken(hooks); let layer2Service: Layer2TestWeb3Strategy; hooks.beforeEach(async function () { layer2Service = this.owner.lookup('service:layer2-network') .strategy as Layer2TestWeb3Strategy; layer2Service.test__simulateRemoteAccountSafes(layer2AccountAddress, [ createDepotSafe({ owners: [layer2AccountAddress], tokens: [createSafeToken('DAI.CPXD', '0')], }), createMockPrepaidCard( layer2AccountAddress, prepaidCardAddress, merchantRegistrationFee ), ]); await layer2Service.test__simulateAccountsChanged([layer2AccountAddress]); }); test('initiating workflow with layer 2 wallet already connected', async function (assert) { await visit('/card-pay/payments?flow=create-business'); const flowId = new URL( 'http://domain.test/' + currentURL() ).searchParams.get('flow-id'); assert.equal( currentURL(), `/card-pay/payments?flow=create-business&flow-id=${flowId}` ); assert .dom(postableSel(0, 2)) .containsText( `Looks like you’ve already connected your ${c.layer2.fullName} wallet` ); assert .dom( '[data-test-layer-2-wallet-card] [data-test-layer-2-wallet-connected-status]' ) .containsText('Connected'); assert .dom( '[data-test-layer-2-wallet-card] [data-test-wallet-connect-qr-code]' ) .doesNotExist(); assert .dom(milestoneCompletedSel(0)) .containsText(`${c.layer2.fullName} wallet connected`); let workflowPersistenceService = this.owner.lookup( 'service:workflow-persistence' ) as WorkflowPersistence; let workflowPersistenceId = new URL( 'http://domain.test/' + currentURL() ).searchParams.get('flow-id')!; let persistedData = workflowPersistenceService.getPersistedData( workflowPersistenceId ); assert.ok( persistedData.state.layer2WalletAddress.includes(layer2AccountAddress), 'expected the layer 2 address to have been persisted when the wallet was already connected' ); }); test('changed merchant details after canceling the merchant creation request are persisted', async function (this: Context, assert) { await visit('/card-pay/payments?flow=create-business'); await waitFor('[data-test-merchant-customization-merchant-name-field]'); await fillIn( `[data-test-merchant-customization-merchant-name-field] input`, 'HELLO!' ); await fillIn( `[data-test-merchant-customization-merchant-id-field] input`, 'abc123' ); await waitUntil( () => ( document.querySelector( '[data-test-validation-state-input]' ) as HTMLElement ).dataset.testValidationStateInput === 'valid' ); await click(`[data-test-merchant-customization-save-details]`); let prepaidCardChoice = postableSel(2, 2); await waitFor(prepaidCardChoice); await selectPrepaidCard(prepaidCardAddress); await click( `${prepaidCardChoice} [data-test-boxel-action-chin] [data-test-boxel-button]` ); // need wait for Hub POST /api/merchant-infos // eslint-disable-next-line ember/no-settled-after-test-helper await settled(); layer2Service.test__simulateRegisterMerchantRejectionForAddress( prepaidCardAddress ); await click('[data-test-merchant-customization-edit]'); await fillIn( '[data-test-merchant-customization-merchant-name-field] input', 'changed' ); await click('[data-test-merchant-customization-save-details]'); await waitFor(prepaidCardChoice); await selectPrepaidCard(prepaidCardAddress); await click( `${prepaidCardChoice} [data-test-boxel-action-chin] [data-test-boxel-button]` ); // wait for another Hub POST /api/merchant-infos // eslint-disable-next-line ember/no-settled-after-test-helper await settled(); layer2Service.test__simulateRegisterMerchantForAddress( prepaidCardAddress, merchantAddress, {} ); let secondMerchantInfo = this.server.schema.findBy('merchant-info', { name: 'changed', }); assert.ok( secondMerchantInfo, 'expected a second merchant-info to have been persisted' ); }); test('disconnecting Layer 2 after proceeding beyond it', async function (assert) { await visit('/card-pay/payments?flow=create-business'); let flowId = new URL( 'http://domain.test/' + currentURL() ).searchParams.get('flow-id'); assert.equal( currentURL(), `/card-pay/payments?flow=create-business&flow-id=${flowId}` ); assert .dom( '[data-test-postable] [data-test-layer-2-wallet-card] [data-test-address-field]' ) .containsText(layer2AccountAddress) .isVisible(); assert .dom(milestoneCompletedSel(0)) .containsText(`${c.layer2.fullName} wallet connected`); layer2Service.test__simulateDisconnectFromWallet(); await settled(); assert .dom('[data-test-postable="0"][data-test-cancelation]') .containsText( `It looks like your ${c.layer2.fullName} wallet got disconnected. If you still want to create a business account, please start again by connecting your wallet.` ); assert .dom('[data-test-workflow-default-cancelation-cta="create-business"]') .containsText('Workflow canceled'); await click( '[data-test-workflow-default-cancelation-restart="create-business"]' ); flowId = new URL('http://domain.test/' + currentURL()).searchParams.get( 'flow-id' ); assert.equal( currentURL(), `/card-pay/payments?flow=create-business&flow-id=${flowId}` ); layer2Service.test__simulateWalletConnectUri(); await waitFor('[data-test-wallet-connect-qr-code]'); assert .dom( '[data-test-layer-2-wallet-card] [data-test-wallet-connect-qr-code]' ) .exists(); assert .dom('[data-test-workflow-default-cancelation-cta="create-business"]') .doesNotExist(); }); test('changing Layer 2 account should cancel the workflow', async function (assert) { await visit('/card-pay/payments?flow=create-business'); let flowId = new URL( 'http://domain.test/' + currentURL() ).searchParams.get('flow-id'); assert.equal( currentURL(), `/card-pay/payments?flow=create-business&flow-id=${flowId}` ); assert .dom( '[data-test-postable] [data-test-layer-2-wallet-card] [data-test-address-field]' ) .containsText(layer2AccountAddress) .isVisible(); assert .dom(milestoneCompletedSel(0)) .containsText(`${c.layer2.fullName} wallet connected`); await layer2Service.test__simulateAccountsChanged([ secondLayer2AccountAddress, ]); layer2Service.test__simulateRemoteAccountSafes( secondLayer2AccountAddress, [ createMockPrepaidCard( secondLayer2AccountAddress, secondPrepaidCardAddress, merchantRegistrationFee ), ] ); await settled(); assert .dom('[data-test-postable="0"][data-test-cancelation]') .containsText( 'It looks like you changed accounts in the middle of this workflow. If you still want to create a business account, please restart the workflow.' ); assert .dom('[data-test-workflow-default-cancelation-cta="create-business"]') .containsText('Workflow canceled'); await click( '[data-test-workflow-default-cancelation-restart="create-business"]' ); flowId = new URL('http://domain.test/' + currentURL()).searchParams.get( 'flow-id' ); assert.equal( currentURL(), `/card-pay/payments?flow=create-business&flow-id=${flowId}` ); }); }); test('it cancels the workflow if there are no prepaid cards associated with the EOA', async function (assert) { let layer2Service = this.owner.lookup('service:layer2-network') .strategy as Layer2TestWeb3Strategy; layer2Service.test__simulateRemoteAccountSafes(layer2AccountAddress, [ createDepotSafe({ owners: [layer2AccountAddress], tokens: [createSafeToken('DAI.CPXD', '0')], }), ]); await layer2Service.test__simulateAccountsChanged([layer2AccountAddress]); await visit('/card-pay/payments?flow=create-business'); assert .dom( '[data-test-postable] [data-test-layer-2-wallet-card] [data-test-address-field]' ) .containsText(layer2AccountAddress) .isVisible(); await settled(); assert .dom('[data-test-postable="0"][data-test-cancelation]') .containsText( `It looks like you don’t have a prepaid card in your wallet. You will need one to pay the ${formatAmount( merchantRegistrationFee )} SPEND (${convertAmountToNativeDisplay( spendToUsd(merchantRegistrationFee)!, 'USD' )}) business account creation fee. Please buy a prepaid card in your Card Wallet mobile app before you continue with this workflow.` ); assert .dom('[data-test-workflow-default-cancelation-cta="create-business"]') .containsText('Workflow canceled'); }); test('it cancels the workflow if prepaid cards associated with the EOA do not have enough balance', async function (assert) { let layer2Service = this.owner.lookup('service:layer2-network') .strategy as Layer2TestWeb3Strategy; layer2Service.test__simulateRemoteAccountSafes(layer2AccountAddress, [ createDepotSafe({ owners: [layer2AccountAddress], tokens: [createSafeToken('DAI.CPXD', '0')], }), createMockPrepaidCard( layer2AccountAddress, prepaidCardAddress, merchantRegistrationFee - 1 ), ]); await layer2Service.test__simulateAccountsChanged([layer2AccountAddress]); await visit('/card-pay/payments?flow=create-business'); assert .dom( '[data-test-postable] [data-test-layer-2-wallet-card] [data-test-address-field]' ) .containsText(layer2AccountAddress) .isVisible(); await settled(); assert .dom('[data-test-postable="0"][data-test-cancelation]') .containsText( `It looks like you don’t have a prepaid card with enough funds to pay the ${formatAmount( merchantRegistrationFee )} SPEND (${convertAmountToNativeDisplay( spendToUsd(merchantRegistrationFee)!, 'USD' )}) business account creation fee. Please buy a prepaid card in your Card Wallet mobile app before you continue with this workflow.` ); assert .dom('[data-test-workflow-default-cancelation-cta="create-business"]') .containsText('Workflow canceled'); }); });
the_stack
import { createApi } from '@reduxjs/toolkit/query/react' import { setupApiStore, waitMs } from './helpers' import React from 'react' import { render, screen, getByTestId, waitFor } from '@testing-library/react' describe('fixedCacheKey', () => { const api = createApi({ async baseQuery(arg: string | Promise<string>) { return { data: await arg } }, endpoints: (build) => ({ send: build.mutation<string, string | Promise<string>>({ query: (arg) => arg, }), }), }) const storeRef = setupApiStore(api) function Component({ name, fixedCacheKey, value = name, }: { name: string fixedCacheKey?: string value?: string | Promise<string> }) { const [trigger, result] = api.endpoints.send.useMutation({ fixedCacheKey }) return ( <div data-testid={name}> <div data-testid="status">{result.status}</div> <div data-testid="data">{result.data}</div> <div data-testid="originalArgs">{String(result.originalArgs)}</div> <button data-testid="trigger" onClick={() => trigger(value)}> trigger </button> <button data-testid="reset" onClick={result.reset}> reset </button> </div> ) } test('two mutations without `fixedCacheKey` do not influence each other', async () => { render( <> <Component name="C1" /> <Component name="C2" /> </>, { wrapper: storeRef.wrapper } ) const c1 = screen.getByTestId('C1') const c2 = screen.getByTestId('C2') expect(getByTestId(c1, 'status').textContent).toBe('uninitialized') expect(getByTestId(c2, 'status').textContent).toBe('uninitialized') getByTestId(c1, 'trigger').click() await waitFor(() => expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') ) expect(getByTestId(c1, 'data').textContent).toBe('C1') expect(getByTestId(c2, 'status').textContent).toBe('uninitialized') }) test('two mutations with the same `fixedCacheKey` do influence each other', async () => { render( <> <Component name="C1" fixedCacheKey="test" /> <Component name="C2" fixedCacheKey="test" /> </>, { wrapper: storeRef.wrapper } ) const c1 = screen.getByTestId('C1') const c2 = screen.getByTestId('C2') expect(getByTestId(c1, 'status').textContent).toBe('uninitialized') expect(getByTestId(c2, 'status').textContent).toBe('uninitialized') getByTestId(c1, 'trigger').click() await waitFor(() => expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') ) expect(getByTestId(c1, 'data').textContent).toBe('C1') expect(getByTestId(c2, 'status').textContent).toBe('fulfilled') expect(getByTestId(c2, 'data').textContent).toBe('C1') // test reset from the other component getByTestId(c2, 'reset').click() expect(getByTestId(c1, 'status').textContent).toBe('uninitialized') expect(getByTestId(c1, 'data').textContent).toBe('') expect(getByTestId(c2, 'status').textContent).toBe('uninitialized') expect(getByTestId(c2, 'data').textContent).toBe('') }) test('resetting from the component that triggered the mutation resets for each shared result', async () => { render( <> <Component name="C1" fixedCacheKey="test-A" /> <Component name="C2" fixedCacheKey="test-A" /> <Component name="C3" fixedCacheKey="test-B" /> <Component name="C4" fixedCacheKey="test-B" /> </>, { wrapper: storeRef.wrapper } ) const c1 = screen.getByTestId('C1') const c2 = screen.getByTestId('C2') const c3 = screen.getByTestId('C3') const c4 = screen.getByTestId('C4') expect(getByTestId(c1, 'status').textContent).toBe('uninitialized') expect(getByTestId(c2, 'status').textContent).toBe('uninitialized') expect(getByTestId(c3, 'status').textContent).toBe('uninitialized') expect(getByTestId(c4, 'status').textContent).toBe('uninitialized') // trigger with a component using the first cache key getByTestId(c1, 'trigger').click() await waitFor(() => expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') ) // the components with the first cache key should be affected expect(getByTestId(c1, 'data').textContent).toBe('C1') expect(getByTestId(c2, 'status').textContent).toBe('fulfilled') expect(getByTestId(c2, 'data').textContent).toBe('C1') expect(getByTestId(c2, 'status').textContent).toBe('fulfilled') // the components with the second cache key should be unaffected expect(getByTestId(c3, 'data').textContent).toBe('') expect(getByTestId(c3, 'status').textContent).toBe('uninitialized') expect(getByTestId(c4, 'data').textContent).toBe('') expect(getByTestId(c4, 'status').textContent).toBe('uninitialized') // trigger with a component using the second cache key getByTestId(c3, 'trigger').click() await waitFor(() => expect(getByTestId(c3, 'status').textContent).toBe('fulfilled') ) // the components with the first cache key should be unaffected expect(getByTestId(c1, 'data').textContent).toBe('C1') expect(getByTestId(c2, 'status').textContent).toBe('fulfilled') expect(getByTestId(c2, 'data').textContent).toBe('C1') expect(getByTestId(c2, 'status').textContent).toBe('fulfilled') // the component with the second cache key should be affected expect(getByTestId(c3, 'data').textContent).toBe('C3') expect(getByTestId(c3, 'status').textContent).toBe('fulfilled') expect(getByTestId(c4, 'data').textContent).toBe('C3') expect(getByTestId(c4, 'status').textContent).toBe('fulfilled') // test reset from the component that triggered the mutation for the first cache key getByTestId(c1, 'reset').click() // the components with the first cache key should be affected expect(getByTestId(c1, 'data').textContent).toBe('') expect(getByTestId(c1, 'status').textContent).toBe('uninitialized') expect(getByTestId(c2, 'data').textContent).toBe('') expect(getByTestId(c2, 'status').textContent).toBe('uninitialized') // the components with the second cache key should be unaffected expect(getByTestId(c3, 'data').textContent).toBe('C3') expect(getByTestId(c3, 'status').textContent).toBe('fulfilled') expect(getByTestId(c4, 'data').textContent).toBe('C3') expect(getByTestId(c4, 'status').textContent).toBe('fulfilled') }) test('two mutations with different `fixedCacheKey` do not influence each other', async () => { render( <> <Component name="C1" fixedCacheKey="test" /> <Component name="C2" fixedCacheKey="toast" /> </>, { wrapper: storeRef.wrapper } ) const c1 = screen.getByTestId('C1') const c2 = screen.getByTestId('C2') expect(getByTestId(c1, 'status').textContent).toBe('uninitialized') expect(getByTestId(c2, 'status').textContent).toBe('uninitialized') getByTestId(c1, 'trigger').click() await waitFor(() => expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') ) expect(getByTestId(c1, 'data').textContent).toBe('C1') expect(getByTestId(c2, 'status').textContent).toBe('uninitialized') }) test('unmounting and remounting keeps data intact', async () => { const { rerender } = render(<Component name="C1" fixedCacheKey="test" />, { wrapper: storeRef.wrapper, }) let c1 = screen.getByTestId('C1') expect(getByTestId(c1, 'status').textContent).toBe('uninitialized') getByTestId(c1, 'trigger').click() await waitFor(() => expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') ) expect(getByTestId(c1, 'data').textContent).toBe('C1') rerender(<div />) expect(screen.queryByTestId('C1')).toBe(null) rerender(<Component name="C1" fixedCacheKey="test" />) c1 = screen.getByTestId('C1') expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') expect(getByTestId(c1, 'data').textContent).toBe('C1') }) test('(limitation) mutations using `fixedCacheKey` do not return `originalArgs`', async () => { render( <> <Component name="C1" fixedCacheKey="test" /> <Component name="C2" fixedCacheKey="test" /> </>, { wrapper: storeRef.wrapper } ) const c1 = screen.getByTestId('C1') const c2 = screen.getByTestId('C2') expect(getByTestId(c1, 'status').textContent).toBe('uninitialized') expect(getByTestId(c2, 'status').textContent).toBe('uninitialized') getByTestId(c1, 'trigger').click() await waitFor(() => expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') ) expect(getByTestId(c1, 'data').textContent).toBe('C1') expect(getByTestId(c2, 'status').textContent).toBe('fulfilled') expect(getByTestId(c2, 'data').textContent).toBe('C1') }) test('a component without `fixedCacheKey` has `originalArgs`', async () => { render(<Component name="C1" />, { wrapper: storeRef.wrapper }) let c1 = screen.getByTestId('C1') expect(getByTestId(c1, 'status').textContent).toBe('uninitialized') expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined') getByTestId(c1, 'trigger').click() expect(getByTestId(c1, 'originalArgs').textContent).toBe('C1') }) test('a component with `fixedCacheKey` does never have `originalArgs`', async () => { render(<Component name="C1" fixedCacheKey="test" />, { wrapper: storeRef.wrapper, }) let c1 = screen.getByTestId('C1') expect(getByTestId(c1, 'status').textContent).toBe('uninitialized') expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined') getByTestId(c1, 'trigger').click() expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined') }) test('using `fixedCacheKey` will always use the latest dispatched thunk, prevent races', async () => { let resolve1: (str: string) => void, resolve2: (str: string) => void const p1 = new Promise<string>((resolve) => { resolve1 = resolve }) const p2 = new Promise<string>((resolve) => { resolve2 = resolve }) render( <> <Component name="C1" fixedCacheKey="test" value={p1} /> <Component name="C2" fixedCacheKey="test" value={p2} /> </>, { wrapper: storeRef.wrapper } ) const c1 = screen.getByTestId('C1') const c2 = screen.getByTestId('C2') expect(getByTestId(c1, 'status').textContent).toBe('uninitialized') expect(getByTestId(c2, 'status').textContent).toBe('uninitialized') getByTestId(c1, 'trigger').click() expect(getByTestId(c1, 'status').textContent).toBe('pending') expect(getByTestId(c1, 'data').textContent).toBe('') getByTestId(c2, 'trigger').click() expect(getByTestId(c1, 'status').textContent).toBe('pending') expect(getByTestId(c1, 'data').textContent).toBe('') resolve1!('this should not show up any more') await waitMs() expect(getByTestId(c1, 'status').textContent).toBe('pending') expect(getByTestId(c1, 'data').textContent).toBe('') resolve2!('this should be visible') await waitMs() expect(getByTestId(c1, 'status').textContent).toBe('fulfilled') expect(getByTestId(c1, 'data').textContent).toBe('this should be visible') }) })
the_stack
import { Filter, ComparisonFilter, Rule, CombinationFilter, NegationFilter } from 'geostyler-style'; import { isCombinationFilter, isComparisonFilter, isNegationFilter } from 'geostyler-style/dist/typeguards'; import { VectorData } from 'geostyler-data'; import _get from 'lodash/get'; import _set from 'lodash/set'; import _cloneDeep from 'lodash/cloneDeep'; import _isString from 'lodash/isString'; export type CountResult = { counts?: number[]; duplicates?: number[]; }; /** * @class FilterUtil */ class FilterUtil { static nestingOperators = ['&&', '||', '!']; /** * Handle nested filters. */ static handleNestedFilter = (filter: CombinationFilter | NegationFilter, feature: any): boolean => { switch (filter[0]) { case '&&': let intermediate = true; let restFilter = filter.slice(1); restFilter.forEach((f: Filter) => { if (!FilterUtil.featureMatchesFilter(f, feature)) { intermediate = false; } }); return intermediate; case '||': intermediate = false; restFilter = filter.slice(1); restFilter.forEach((f: Filter) => { if (FilterUtil.featureMatchesFilter(f, feature)) { intermediate = true; } }); return intermediate; case '!': return !FilterUtil.featureMatchesFilter(filter[1], feature); default: throw new Error('Cannot parse Filter. Unknown combination or negation operator.'); } }; /** * Handle simple filters, i.e. non-nested filters. */ static handleSimpleFilter = (filter: ComparisonFilter, feature: any): boolean => { const featureValue = _get(feature, 'properties[' + filter[1] + ']'); let filterValue = filter[2]; switch (filter[0]) { case '==': return (('' + featureValue) === ('' + filterValue)); case '*=': filterValue = filterValue as string; if (featureValue && filterValue.length > featureValue.length) { return false; } else if (featureValue) { return (featureValue.indexOf(filterValue) !== -1); } else { return false; } case '!=': return (('' + featureValue) !== ('' + filterValue)); case '<': return (parseFloat(featureValue) < Number(filterValue)); case '<=': return (parseFloat(featureValue) <= Number(filterValue)); case '>': return (parseFloat(featureValue) > Number(filterValue)); case '>=': return (parseFloat(featureValue) >= Number(filterValue)); default: throw new Error('Cannot parse Filter. Unknown comparison operator.'); } }; /** * Checks if a feature matches the specified filter. * Returns true if it matches, otherwise returns false. */ static featureMatchesFilter = (filter: Filter, feature: any): boolean => { if (filter.length === 0) { return true; } let matchesFilter: boolean = true; if (isComparisonFilter(filter)) { matchesFilter = FilterUtil.handleSimpleFilter(filter, feature); } else if (isCombinationFilter(filter) || isNegationFilter(filter)) { matchesFilter = FilterUtil.handleNestedFilter(filter, feature); } return matchesFilter; }; /** * Returns those features that match a given filter. * If no feature matches, returns an empty array. * * @param {Filter} filter A geostyler filter object. * @param {VectorData} data A geostyler data object. * @return {Feature[]} An Array of geojson feature objects. */ static getMatches = (filter: Filter, data: VectorData): any[] => { const matches: any[] = []; data.exampleFeatures.features.forEach(feature => { const match = FilterUtil.featureMatchesFilter(filter, feature); if (match) { matches.push(feature); } }); return matches; }; /** * Calculates the number of features that are covered by more then one rule per * rule. * * @param {object} matches An object containing the count of matches for every * filter. Seperate by scales. * @returns {number[]} An array containing the number of duplicates for each * rule. */ static calculateDuplicates(matches: any): number[] { const duplicates: number[] = []; const ids: any[] = []; matches.forEach((features: any, index: number) => { const idMap = {}; features.forEach((feat: any) => idMap[feat.id] = true); ids[index] = idMap; }); matches.forEach((features: any, index: number) => { let counter = 0; ids.forEach((idMap, idIndex) => { if (index !== idIndex) { features.forEach((feat: any) => { if (idMap[feat.id]) { ++counter; } }); } }); duplicates[index] = counter; }); return duplicates; } /** * Calculates the amount of matched and duplicate matched features for the rules. * * @param {Rule[]} rules An array of GeoStyler rule objects. * @param {VectorData} data A geostyler data object. * @returns {CountResult} An object containing array with the amount of matched * and duplicate matched features reachable through keys'counts' and 'duplicates'. */ static calculateCountAndDuplicates(rules: Rule[], data: VectorData): CountResult { if (!rules || !data) { return {}; } const result: CountResult = { counts: [], duplicates: [] }; // Add id to feature if missing data.exampleFeatures.features = data.exampleFeatures.features.map((feature, idx) => { if (!feature.id) { feature.id = idx; } return feature; }); const matches: any = []; rules.forEach((rule, index) => { const currentMatches = rule.filter ? FilterUtil.getMatches(rule.filter, data) : data.exampleFeatures.features; result.counts.push(currentMatches.length); matches[index] = currentMatches; }); result.duplicates = FilterUtil.calculateDuplicates(matches); return result; } /** * Transforms a position String like '[2][3]' to an positionArray like [2, 3]. */ static positionStringAsArray(positionString: string) { return positionString .replace(/\]\[/g, ',') .replace(/\]/g, '') .replace(/\[/g, '') .split(',') .map(i => parseInt(i, 10)); }; /** * Transforms am positionArray like [2, 3] to a string like '[2][3]'. */ static positionArrayAsString(positionArray: number[] | string[]) { return `[${positionArray.toString().replace(/,/g, '][')}]`; }; /** * Returns the filter at a specific position. */ static getFilterAtPosition(rootFilter: Filter, position: string) { if (position === '') { return rootFilter; } else { return _get(rootFilter, position); } }; /** * Removes a subfilter from a given filter at the given position. */ static removeAtPosition(filter: Filter, position: string): Filter { let newFilter = [...filter] as Filter; const dragNodeSubPosition = position.substr(position.length - 3); const dragNodeIndex = parseInt(dragNodeSubPosition.slice(1, 2), 10); const parentPosition = position.substring(0, position.length - 3); let parentFilter = newFilter; if (parentPosition !== '') { parentFilter = _get(newFilter, parentPosition); } parentFilter.splice(dragNodeIndex, 1); return newFilter; }; /** * Inserts a given subfilter to a given parentfilter by its position and its * dropPosition. */ static insertAtPosition( baseFilter: Filter, insertFilter: Filter, position: string, dropPosition: number ): Filter { const dropTargetParentPosition = position.substring(0, position.length - 3); const dropTargetSubPosition = position.substr(position.length - 3); const dropTargetSubIndex = dropTargetParentPosition === '' ? 1 : parseInt(dropTargetSubPosition.slice(1, 2), 10); const dropTargetIsComparison = !['&', '||', '!'].includes(insertFilter[0]); let newFilter: Filter = [...baseFilter]; const newSubFilter = dropTargetParentPosition === '' ? newFilter : _get(newFilter, dropTargetParentPosition); // Add to new position switch (dropPosition) { // before case 0: newSubFilter.splice(dropTargetSubIndex, 0, insertFilter); break; // on case 1: if (dropTargetIsComparison) { newSubFilter.splice(dropTargetSubIndex + 1, 0, insertFilter); } else { newSubFilter.push(insertFilter); } break; // after case 2: newSubFilter.splice(dropTargetSubIndex + 1, 0, insertFilter); break; default: break; } return newFilter; }; /** * Handler for the add button. * Adds a filter of a given type at the given position. * */ static addFilter(rootFilter: Filter, position: string, type: string) { let addedFilter: Filter ; let newFilter: Filter = _cloneDeep(rootFilter); switch (type) { case 'and': addedFilter = ['&&', ['==', '', ''], ['==', '', '']] as CombinationFilter; break; case 'or': addedFilter = ['||', ['==', '', ''], ['==', '', '']] as CombinationFilter; break; case 'not': addedFilter = ['!', ['==', '', '']] as NegationFilter; break; case 'comparison': default: addedFilter = ['==', '', ''] as ComparisonFilter; break; } if (position === '') { newFilter = newFilter as CombinationFilter; newFilter.push(addedFilter); } else { const previousFilter: CombinationFilter = _get(newFilter, position); previousFilter.push(addedFilter); _set(newFilter, position, previousFilter); } return newFilter; }; /** * Changes a filter at a position to a given typ. * */ static changeFilter(rootFilter: Filter, position: string, type: string) { let addedFilter: Filter ; const newFilter: Filter = _cloneDeep(rootFilter); const previousFilter = position === '' ? newFilter : _get(newFilter, position); switch (type) { case 'and': if (previousFilter && (previousFilter[0] === '&&' || previousFilter[0] === '||' )) { addedFilter = previousFilter; addedFilter[0] = '&&'; } else { addedFilter = ['&&', ['==', '', ''], ['==', '', '']]; } break; case 'or': if (previousFilter && (previousFilter[0] === '&&' || previousFilter[0] === '||' )) { addedFilter = previousFilter; addedFilter[0] = '||'; } else { addedFilter = ['||', ['==', '', ''], ['==', '', '']]; } break; case 'not': addedFilter = ['!', ['==', '', '']]; break; case 'comparison': default: addedFilter = ['==', '', '']; break; } if (position === '') { return addedFilter; } else { _set(newFilter, position, addedFilter); return newFilter; } }; /** * Removes a filter at a given position. * */ static removeFilter = (rootFilter: Filter, position: string) => { const parentPosition = position.substring(0, position.length - 3); const parentFilter: Filter = FilterUtil.getFilterAtPosition(rootFilter, parentPosition); let newFilter: Filter; if (position === '') { newFilter = undefined; } else if (parentFilter.length <= 2) { newFilter = FilterUtil.removeAtPosition(rootFilter, parentPosition); } else { newFilter = FilterUtil.removeAtPosition(rootFilter, position); } return newFilter; }; } export default FilterUtil;
the_stack
import Image from './image/ImageBox'; import EventObject from './event/EventObject'; import EventSource from './event/EventSource'; import InternalEvent from './event/InternalEvent'; import Rectangle from './geometry/Rectangle'; import TooltipHandler from './tooltip/TooltipHandler'; import mxClient from '../mxClient'; import SelectionCellsHandler from './selection/SelectionCellsHandler'; import ConnectionHandler from './connection/ConnectionHandler'; import GraphHandler from './GraphHandler'; import PanningHandler from './panning/PanningHandler'; import PopupMenuHandler from './popups_menus/PopupMenuHandler'; import GraphView from './view/GraphView'; import CellRenderer from './cell/CellRenderer'; import CellEditor from './editing/CellEditor'; import Point from './geometry/Point'; import { getCurrentStyle, hasScrollbars, parseCssNumber } from '../util/Utils'; import Cell from './cell/datatypes/Cell'; import Model from './model/Model'; import Stylesheet from './style/Stylesheet'; import { PAGE_FORMAT_A4_PORTRAIT } from '../util/Constants'; import ChildChange from './model/ChildChange'; import GeometryChange from './geometry/GeometryChange'; import RootChange from './model/RootChange'; import StyleChange from './style/StyleChange'; import TerminalChange from './cell/edge/TerminalChange'; import ValueChange from './cell/ValueChange'; import CellState from './cell/datatypes/CellState'; import { isNode } from '../util/DomUtils'; import EdgeStyle from './style/EdgeStyle'; import EdgeHandler from './cell/edge/EdgeHandler'; import VertexHandler from './cell/vertex/VertexHandler'; import EdgeSegmentHandler from './cell/edge/EdgeSegmentHandler'; import ElbowEdgeHandler from './cell/edge/ElbowEdgeHandler'; import type { GraphPlugin, GraphPluginConstructor } from '../types'; const defaultPlugins: GraphPluginConstructor[] = [ CellEditor, TooltipHandler, SelectionCellsHandler, PopupMenuHandler, ConnectionHandler, GraphHandler, PanningHandler, ]; /** * Extends {@link EventSource} to implement a graph component for * the browser. This is the main class of the package. To activate * panning and connections use {@link setPanning} and {@link setConnectable}. * For rubberband selection you must create a new instance of * {@link rubberband}. The following listeners are added to * {@link mouseListeners} by default: * * - tooltipHandler: {@link TooltipHandler} that displays tooltips * - panningHandler: {@link PanningHandler} for panning and popup menus * - connectionHandler: {@link ConnectionHandler} for creating connections * - graphHandler: {@link GraphHandler} for moving and cloning cells * * These listeners will be called in the above order if they are enabled. * @class graph * @extends {EventSource} */ class Graph extends EventSource { container: HTMLElement; destroyed: boolean = false; graphModelChangeListener: Function | null = null; paintBackground: Function | null = null; /***************************************************************************** * Group: Variables *****************************************************************************/ /** * Holds the {@link Model} that contains the cells to be displayed. */ model: Model; plugins: GraphPluginConstructor[]; pluginsMap: Record<string, GraphPlugin> = {}; /** * Holds the {@link GraphView} that caches the {@link CellState}s for the cells. */ view: GraphView; /** * Holds the {@link Stylesheet} that defines the appearance of the cells. * * Use the following code to read a stylesheet into an existing graph. * * @example * ```javascript * var req = mxUtils.load('stylesheet.xml'); * var root = req.getDocumentElement(); * var dec = new mxCodec(root.ownerDocument); * dec.decode(root, graph.stylesheet); * ``` */ // @ts-ignore stylesheet: Stylesheet; /** * Holds the {@link CellRenderer} for rendering the cells in the graph. */ cellRenderer: CellRenderer; /** * RenderHint as it was passed to the constructor. */ renderHint: string | null = null; /** * Dialect to be used for drawing the graph. Possible values are all * constants in {@link mxConstants} with a DIALECT-prefix. */ dialect: 'svg' | 'mixedHtml' | 'preferHtml' | 'strictHtml' = 'svg'; /** * Value returned by {@link getOverlap} if {@link isAllowOverlapParent} returns * `true` for the given cell. {@link getOverlap} is used in {@link constrainChild} if * {@link isConstrainChild} returns `true`. The value specifies the * portion of the child which is allowed to overlap the parent. */ defaultOverlap: number = 0.5; /** * Specifies the default parent to be used to insert new cells. * This is used in {@link getDefaultParent}. * @default null */ defaultParent: Cell | null = null; /** * Specifies the {@link Image} to be returned by {@link getBackgroundImage}. * @default null * * @example * ```javascript * var img = new mxImage('http://www.example.com/maps/examplemap.jpg', 1024, 768); * graph.setBackgroundImage(img); * graph.view.validate(); * ``` */ backgroundImage: Image | null = null; /** * Specifies if the background page should be visible. * Not yet implemented. * @default false */ pageVisible = false; /** * Specifies if a dashed line should be drawn between multiple pages. * If you change this value while a graph is being displayed then you * should call {@link sizeDidChange} to force an update of the display. * @default false */ pageBreaksVisible = false; /** * Specifies the color for page breaks. * @default gray */ pageBreakColor = 'gray'; /** * Specifies the page breaks should be dashed. * @default true */ pageBreakDashed = true; /** * Specifies the minimum distance in pixels for page breaks to be visible. * @default 20 */ minPageBreakDist = 20; /** * Specifies if the graph size should be rounded to the next page number in * {@link sizeDidChange}. This is only used if the graph container has scrollbars. * @default false */ preferPageSize = false; /** * Specifies the page format for the background page. * This is used as the default in {@link printPreview} and for painting the background page * if {@link pageVisible} is `true` and the page breaks if {@link pageBreaksVisible} is `true`. * @default {@link mxConstants.PAGE_FORMAT_A4_PORTRAIT} */ pageFormat = new Rectangle(...PAGE_FORMAT_A4_PORTRAIT); /** * Specifies the scale of the background page. * Not yet implemented. * @default 1.5 */ pageScale = 1.5; /** * Specifies the return value for {@link isEnabled}. * @default true */ enabled = true; /** * Specifies the return value for {@link canExportCell}. * @default true */ exportEnabled = true; /** * Specifies the return value for {@link canImportCell}. * @default true */ importEnabled = true; /** * Specifies if the graph should automatically scroll regardless of the * scrollbars. This will scroll the container using positive values for * scroll positions (ie usually only rightwards and downwards). To avoid * possible conflicts with panning, set {@link translateToScrollPosition} to `true`. */ ignoreScrollbars = false; /** * Specifies if the graph should automatically convert the current scroll * position to a translate in the graph view when a mouseUp event is received. * This can be used to avoid conflicts when using {@link autoScroll} and * {@link ignoreScrollbars} with no scrollbars in the container. */ translateToScrollPosition = false; /** * {@link Rectangle} that specifies the area in which all cells in the diagram * should be placed. Uses in {@link getMaximumGraphBounds}. Use a width or height of * `0` if you only want to give a upper, left corner. */ maximumGraphBounds: Rectangle | null = null; /** * {@link Rectangle} that specifies the minimum size of the graph. This is ignored * if the graph container has no scrollbars. * @default null */ minimumGraphSize: Rectangle | null = null; /** * {@link Rectangle} that specifies the minimum size of the {@link container} if * {@link resizeContainer} is `true`. */ minimumContainerSize: Rectangle | null = null; /** * {@link Rectangle} that specifies the maximum size of the container if * {@link resizeContainer} is `true`. */ maximumContainerSize: Rectangle | null = null; /** * Specifies if the container should be resized to the graph size when * the graph size has changed. * @default false */ resizeContainer = false; /** * Border to be added to the bottom and right side when the container is * being resized after the graph has been changed. * @default 0 */ border: number = 0; /** * Specifies if edges should appear in the foreground regardless of their order * in the model. If {@link keepEdgesInForeground} and {@link keepEdgesInBackground} are * both `true` then the normal order is applied. * @default false */ keepEdgesInForeground: boolean = false; /** * Specifies if edges should appear in the background regardless of their order * in the model. If {@link keepEdgesInForeground} and {@link keepEdgesInBackground} are * both `true` then the normal order is applied. * @default false */ keepEdgesInBackground: boolean = false; /** * Specifies the return value for {@link isRecursiveResize}. * @default false (for backwards compatibility) */ recursiveResize: boolean = false; /** * Specifies if the scale and translate should be reset if the root changes in * the model. * @default true */ resetViewOnRootChange: boolean = true; /** * Specifies if loops (aka self-references) are allowed. * @default false */ allowLoops: boolean = false; /** * {@link EdgeStyle} to be used for loops. This is a fallback for loops if the * {@link mxConstants.STYLE_LOOP} is undefined. * @default {@link EdgeStyle.Loop} */ defaultLoopStyle = EdgeStyle.Loop; /** * Specifies if multiple edges in the same direction between the same pair of * vertices are allowed. * @default true */ multigraph: boolean = true; /** * Specifies the minimum scale to be applied in {@link fit}. Set this to `null` to allow any value. * @default 0.1 */ minFitScale: number = 0.1; /** * Specifies the maximum scale to be applied in {@link fit}. Set this to `null` to allow any value. * @default 8 */ maxFitScale: number = 8; /** * Specifies the {@link Image} for the image to be used to display a warning * overlay. See {@link setCellWarning}. Default value is mxClient.imageBasePath + * '/warning'. The extension for the image depends on the platform. It is * '.png' on the Mac and '.gif' on all other platforms. */ warningImage: Image = new Image( `${mxClient.imageBasePath}/warning${mxClient.IS_MAC ? '.png' : '.gif'}`, 16, 16 ); /** * Specifies the resource key for the error message to be displayed in * non-multigraphs when two vertices are already connected. If the resource * for this key does not exist then the value is used as the error message. * @default 'alreadyConnected' */ alreadyConnectedResource: string = mxClient.language != 'none' ? 'alreadyConnected' : ''; /** * Specifies the resource key for the warning message to be displayed when * a collapsed cell contains validation errors. If the resource for this * key does not exist then the value is used as the warning message. * @default 'containsValidationErrors' */ containsValidationErrorsResource: string = mxClient.language != 'none' ? 'containsValidationErrors' : ''; constructor( container: HTMLElement, model?: Model, plugins: GraphPluginConstructor[] = defaultPlugins, stylesheet: Stylesheet | null = null ) { super(); this.container = container ?? document.createElement('div'); this.model = model ?? new Model(); this.plugins = plugins; this.cellRenderer = this.createCellRenderer(); this.setStylesheet(stylesheet != null ? stylesheet : this.createStylesheet()); this.view = this.createGraphView(); // Adds a graph model listener to update the view this.graphModelChangeListener = (sender: any, evt: EventObject) => { this.graphModelChanged(evt.getProperty('edit').changes); }; this.getModel().addListener(InternalEvent.CHANGE, this.graphModelChangeListener); // Initializes the container using the view this.view.init(); // Updates the size of the container for the current graph this.sizeDidChange(); // Initiailzes plugins this.plugins.forEach((p: GraphPluginConstructor) => { this.pluginsMap[p.pluginId] = new p(this); }); this.view.revalidate(); } getContainer = () => this.container; getPlugin = (id: string) => this.pluginsMap[id] as unknown; getCellRenderer() { return this.cellRenderer; } getDialect = () => this.dialect; isPageVisible = () => this.pageVisible; isPageBreaksVisible = () => this.pageBreaksVisible; getPageBreakColor = () => this.pageBreakColor; isPageBreakDashed = () => this.pageBreakDashed; getMinPageBreakDist = () => this.minPageBreakDist; isPreferPageSize = () => this.preferPageSize; getPageFormat = () => this.pageFormat; getPageScale = () => this.pageScale; isExportEnabled = () => this.exportEnabled; isImportEnabled = () => this.importEnabled; isIgnoreScrollbars = () => this.ignoreScrollbars; isTranslateToScrollPosition = () => this.translateToScrollPosition; getMinimumGraphSize = () => this.minimumGraphSize; setMinimumGraphSize = (size: Rectangle | null) => (this.minimumGraphSize = size); getMinimumContainerSize = () => this.minimumContainerSize; setMinimumContainerSize = (size: Rectangle | null) => (this.minimumContainerSize = size); getWarningImage() { return this.warningImage; } getAlreadyConnectedResource = () => this.alreadyConnectedResource; getContainsValidationErrorsResource = () => this.containsValidationErrorsResource; // TODO: Document me!! batchUpdate(fn: Function) { this.getModel().beginUpdate(); try { fn(); } finally { this.getModel().endUpdate(); } } /** * Creates a new {@link mxGraphSelectionModel} to be used in this graph. */ createStylesheet(): Stylesheet { return new Stylesheet(); } /** * Creates a new {@link GraphView} to be used in this graph. */ createGraphView() { return new GraphView(this); } /** * Creates a new {@link CellRenderer} to be used in this graph. */ createCellRenderer(): CellRenderer { return new CellRenderer(); } /** * Returns the {@link Model} that contains the cells. */ getModel() { return this.model; } /** * Returns the {@link GraphView} that contains the {@link mxCellStates}. */ getView() { return this.view; } /** * Returns the {@link Stylesheet} that defines the style. */ getStylesheet() { return this.stylesheet; } /** * Sets the {@link Stylesheet} that defines the style. */ setStylesheet(stylesheet: Stylesheet) { this.stylesheet = stylesheet; } /** * Called when the graph model changes. Invokes {@link processChange} on each * item of the given array to update the view accordingly. * * @param changes Array that contains the individual changes. */ graphModelChanged(changes: any[]) { for (const change of changes) { this.processChange(change); } this.updateSelection(); this.view.validate(); this.sizeDidChange(); } /** * Processes the given change and invalidates the respective cached data * in {@link GraphView}. This fires a {@link root} event if the root has changed in the * model. * * @param {(RootChange|ChildChange|TerminalChange|GeometryChange|ValueChange|StyleChange)} change - Object that represents the change on the model. */ processChange(change: any): void { // Resets the view settings, removes all cells and clears // the selection if the root changes. if (change instanceof RootChange) { this.clearSelection(); this.setDefaultParent(null); if (change.previous) this.removeStateForCell(change.previous); if (this.resetViewOnRootChange) { this.view.scale = 1; this.view.translate.x = 0; this.view.translate.y = 0; } this.fireEvent(new EventObject(InternalEvent.ROOT)); } // Adds or removes a child to the view by online invaliding // the minimal required portions of the cache, namely, the // old and new parent and the child. else if (change instanceof ChildChange) { const newParent = change.child.getParent(); this.view.invalidate(change.child, true, true); if ( newParent && (!this.getModel().contains(newParent) || newParent.isCollapsed()) ) { this.view.invalidate(change.child, true, true); this.removeStateForCell(change.child); // Handles special case of current root of view being removed if (this.view.currentRoot == change.child) { this.home(); } } if (newParent != change.previous) { // Refreshes the collapse/expand icons on the parents if (newParent != null) { this.view.invalidate(newParent, false, false); } if (change.previous != null) { this.view.invalidate(change.previous, false, false); } } } // Handles two special cases where the shape does not need to be // recreated from scratch, it only needs to be invalidated. else if (change instanceof TerminalChange || change instanceof GeometryChange) { // Checks if the geometry has changed to avoid unnessecary revalidation if ( change instanceof TerminalChange || (change.previous == null && change.geometry != null) || (change.previous != null && !change.previous.equals(change.geometry)) ) { this.view.invalidate(change.cell); } } // Handles two special cases where only the shape, but no // descendants need to be recreated else if (change instanceof ValueChange) { this.view.invalidate(change.cell, false, false); } // Requires a new mxShape in JavaScript else if (change instanceof StyleChange) { this.view.invalidate(change.cell, true, true); const state = this.view.getState(change.cell); if (state != null) { state.invalidStyle = true; } } // Removes the state from the cache by default else if (change.cell != null && change.cell instanceof Cell) { this.removeStateForCell(change.cell); } } /** * Scrolls the graph to the given point, extending the graph container if * specified. */ scrollPointToVisible( x: number, y: number, extend: boolean = false, border: number = 20 ) { const panningHandler = this.getPlugin('PanningHandler') as PanningHandler; if ( !this.isTimerAutoScroll() && (this.ignoreScrollbars || hasScrollbars(this.container)) ) { const c = <HTMLElement>this.container; if ( x >= c.scrollLeft && y >= c.scrollTop && x <= c.scrollLeft + c.clientWidth && y <= c.scrollTop + c.clientHeight ) { let dx = c.scrollLeft + c.clientWidth - x; if (dx < border) { const old = c.scrollLeft; c.scrollLeft += border - dx; // Automatically extends the canvas size to the bottom, right // if the event is outside of the canvas and the edge of the // canvas has been reached. Notes: Needs fix for IE. if (extend && old === c.scrollLeft) { // @ts-ignore const root = this.view.getDrawPane().ownerSVGElement; const width = c.scrollWidth + border - dx; // Updates the clipping region. This is an expensive // operation that should not be executed too often. // @ts-ignore root.style.width = `${width}px`; c.scrollLeft += border - dx; } } else { dx = x - c.scrollLeft; if (dx < border) { c.scrollLeft -= border - dx; } } let dy = c.scrollTop + c.clientHeight - y; if (dy < border) { const old = c.scrollTop; c.scrollTop += border - dy; if (old == c.scrollTop && extend) { // @ts-ignore const root = this.view.getDrawPane().ownerSVGElement; const height = c.scrollHeight + border - dy; // Updates the clipping region. This is an expensive // operation that should not be executed too often. // @ts-ignore root.style.height = `${height}px`; c.scrollTop += border - dy; } } else { dy = y - c.scrollTop; if (dy < border) { c.scrollTop -= border - dy; } } } } else if (this.isAllowAutoPanning() && !panningHandler.isActive()) { panningHandler.getPanningManager().panTo(x + this.getPanDx(), y + this.getPanDy()); } } /** * Returns the size of the border and padding on all four sides of the * container. The left, top, right and bottom borders are stored in the x, y, * width and height of the returned {@link Rectangle}, respectively. */ getBorderSizes(): Rectangle { const css = <CSSStyleDeclaration>getCurrentStyle(this.container); return new Rectangle( parseCssNumber(css.paddingLeft) + (css.borderLeftStyle != 'none' ? parseCssNumber(css.borderLeftWidth) : 0), parseCssNumber(css.paddingTop) + (css.borderTopStyle != 'none' ? parseCssNumber(css.borderTopWidth) : 0), parseCssNumber(css.paddingRight) + (css.borderRightStyle != 'none' ? parseCssNumber(css.borderRightWidth) : 0), parseCssNumber(css.paddingBottom) + (css.borderBottomStyle != 'none' ? parseCssNumber(css.borderBottomWidth) : 0) ); } /** * Returns the preferred size of the background page if {@link preferPageSize} is true. */ getPreferredPageSize(bounds: Rectangle, width: number, height: number) { const tr = this.view.translate; const fmt = this.pageFormat; const ps = this.pageScale; const page = new Rectangle( 0, 0, Math.ceil(fmt.width * ps), Math.ceil(fmt.height * ps) ); const hCount = this.pageBreaksVisible ? Math.ceil(width / page.width) : 1; const vCount = this.pageBreaksVisible ? Math.ceil(height / page.height) : 1; return new Rectangle( 0, 0, hCount * page.width + 2 + tr.x, vCount * page.height + 2 + tr.y ); } /** * Function: fit * * Scales the graph such that the complete diagram fits into <container> and * returns the current scale in the view. To fit an initial graph prior to * rendering, set <mxGraphView.rendering> to false prior to changing the model * and execute the following after changing the model. * * (code) * graph.fit(); * graph.view.rendering = true; * graph.refresh(); * (end) * * To fit and center the graph, the following code can be used. * * (code) * let margin = 2; * let max = 3; * * let bounds = graph.getGraphBounds(); * let cw = graph.container.clientWidth - margin; * let ch = graph.container.clientHeight - margin; * let w = bounds.width / graph.view.scale; * let h = bounds.height / graph.view.scale; * let s = Math.min(max, Math.min(cw / w, ch / h)); * * graph.view.scaleAndTranslate(s, * (margin + cw - w * s) / (2 * s) - bounds.x / graph.view.scale, * (margin + ch - h * s) / (2 * s) - bounds.y / graph.view.scale); * (end) * * Parameters: * * border - Optional number that specifies the border. Default is <border>. * keepOrigin - Optional boolean that specifies if the translate should be * changed. Default is false. * margin - Optional margin in pixels. Default is 0. * enabled - Optional boolean that specifies if the scale should be set or * just returned. Default is true. * ignoreWidth - Optional boolean that specifies if the width should be * ignored. Default is false. * ignoreHeight - Optional boolean that specifies if the height should be * ignored. Default is false. * maxHeight - Optional maximum height. */ fit( border: number = this.getBorder(), keepOrigin: boolean = false, margin: number = 0, enabled: boolean = true, ignoreWidth: boolean = false, ignoreHeight: boolean = false, maxHeight: number | null = null ): number { if (this.container != null) { // Adds spacing and border from css const cssBorder = this.getBorderSizes(); let w1: number = this.container.offsetWidth - cssBorder.x - cssBorder.width - 1; let h1: number = maxHeight != null ? maxHeight : this.container.offsetHeight - cssBorder.y - cssBorder.height - 1; let bounds = this.view.getGraphBounds(); if (bounds.width > 0 && bounds.height > 0) { if (keepOrigin && bounds.x != null && bounds.y != null) { bounds = bounds.clone(); bounds.width += bounds.x; bounds.height += bounds.y; bounds.x = 0; bounds.y = 0; } // LATER: Use unscaled bounding boxes to fix rounding errors const s = this.view.scale; let w2 = bounds.width / s; let h2 = bounds.height / s; // Fits to the size of the background image if required if (this.backgroundImage != null) { w2 = Math.max(w2, this.backgroundImage.width - bounds.x / s); h2 = Math.max(h2, this.backgroundImage.height - bounds.y / s); } const b: number = (keepOrigin ? border : 2 * border) + margin + 1; w1 -= b; h1 -= b; let s2 = ignoreWidth ? h1 / h2 : ignoreHeight ? w1 / w2 : Math.min(w1 / w2, h1 / h2); if (this.minFitScale != null) { s2 = Math.max(s2, this.minFitScale); } if (this.maxFitScale != null) { s2 = Math.min(s2, this.maxFitScale); } if (enabled) { if (!keepOrigin) { if (!hasScrollbars(this.container)) { const x0 = bounds.x != null ? Math.floor( this.view.translate.x - bounds.x / s + border / s2 + margin / 2 ) : border; const y0 = bounds.y != null ? Math.floor( this.view.translate.y - bounds.y / s + border / s2 + margin / 2 ) : border; this.view.scaleAndTranslate(s2, x0, y0); } else { this.view.setScale(s2); const b2 = this.getGraphBounds(); if (b2.x != null) { this.container.scrollLeft = b2.x; } if (b2.y != null) { this.container.scrollTop = b2.y; } } } else if (this.view.scale != s2) { this.view.setScale(s2); } } else { return s2; } } } return this.view.scale; } /** * Resizes the container for the given graph width and height. */ doResizeContainer(width: number, height: number): void { if (this.maximumContainerSize != null) { width = Math.min(this.maximumContainerSize.width, width); height = Math.min(this.maximumContainerSize.height, height); } const container = <HTMLElement>this.container; container.style.width = `${Math.ceil(width)}px`; container.style.height = `${Math.ceil(height)}px`; } /***************************************************************************** * Group: UNCLASSIFIED *****************************************************************************/ /** * Creates a new handler for the given cell state. This implementation * returns a new {@link EdgeHandler} of the corresponding cell is an edge, * otherwise it returns an {@link VertexHandler}. * * @param state {@link mxCellState} whose handler should be created. */ createHandler(state: CellState) { let result: EdgeHandler | VertexHandler | null = null; if (state.cell.isEdge()) { const source = state.getVisibleTerminalState(true); const target = state.getVisibleTerminalState(false); const geo = state.cell.getGeometry(); const edgeStyle = this.getView().getEdgeStyle( state, geo ? geo.points : undefined, source, target ); result = this.createEdgeHandler(state, edgeStyle); } else { result = this.createVertexHandler(state); } return result; } /** * Hooks to create a new {@link VertexHandler} for the given {@link CellState}. * * @param state {@link mxCellState} to create the handler for. */ createVertexHandler(state: CellState): VertexHandler { return new VertexHandler(state); } /** * Hooks to create a new {@link EdgeHandler} for the given {@link CellState}. * * @param state {@link mxCellState} to create the handler for. */ createEdgeHandler(state: CellState, edgeStyle: any) { let result = null; if ( edgeStyle == EdgeStyle.Loop || edgeStyle == EdgeStyle.ElbowConnector || edgeStyle == EdgeStyle.SideToSide || edgeStyle == EdgeStyle.TopToBottom ) { result = this.createElbowEdgeHandler(state); } else if ( edgeStyle == EdgeStyle.SegmentConnector || edgeStyle == EdgeStyle.OrthConnector ) { result = this.createEdgeSegmentHandler(state); } else { result = new EdgeHandler(state); } return result as EdgeHandler; } /** * Hooks to create a new {@link EdgeSegmentHandler} for the given {@link CellState}. * * @param state {@link mxCellState} to create the handler for. */ createEdgeSegmentHandler(state: CellState) { return new EdgeSegmentHandler(state); } /** * Hooks to create a new {@link ElbowEdgeHandler} for the given {@link CellState}. * * @param state {@link mxCellState} to create the handler for. */ createElbowEdgeHandler(state: CellState) { return new ElbowEdgeHandler(state); } /***************************************************************************** * Group: Drilldown *****************************************************************************/ /** * Returns the current root of the displayed cell hierarchy. This is a * shortcut to {@link GraphView.currentRoot} in {@link GraphView}. */ getCurrentRoot() { return this.view.currentRoot; } /** * Returns the translation to be used if the given cell is the root cell as * an {@link Point}. This implementation returns null. * * To keep the children at their absolute position while stepping into groups, * this function can be overridden as follows. * * @example * ```javascript * var offset = new mxPoint(0, 0); * * while (cell != null) * { * var geo = this.model.getGeometry(cell); * * if (geo != null) * { * offset.x -= geo.x; * offset.y -= geo.y; * } * * cell = this.model.getParent(cell); * } * * return offset; * ``` * * @param cell {@link mxCell} that represents the root. */ getTranslateForRoot(cell: Cell | null): Point | null { return null; } /** * Returns the offset to be used for the cells inside the given cell. The * root and layer cells may be identified using {@link Model.isRoot} and * {@link Model.isLayer}. For all other current roots, the * {@link GraphView.currentRoot} field points to the respective cell, so that * the following holds: cell == this.view.currentRoot. This implementation * returns null. * * @param cell {@link mxCell} whose offset should be returned. */ getChildOffsetForCell(cell: Cell): Point | null { return null; } /** * Uses the root of the model as the root of the displayed cell hierarchy * and selects the previous root. */ home() { const current = this.getCurrentRoot(); if (current != null) { this.view.setCurrentRoot(null); const state = this.view.getState(current); if (state != null) { this.setSelectionCell(current); } } } /** * Returns true if the given cell is a valid root for the cell display * hierarchy. This implementation returns true for all non-null values. * * @param cell {@link mxCell} which should be checked as a possible root. */ isValidRoot(cell: Cell) { return !!cell; } /***************************************************************************** * Group: Graph display *****************************************************************************/ /** * Returns the bounds of the visible graph. Shortcut to * {@link GraphView.getGraphBounds}. See also: {@link getBoundingBoxFromGeometry}. */ getGraphBounds(): Rectangle { return this.view.getGraphBounds(); } /** * Returns the bounds inside which the diagram should be kept as an * {@link Rectangle}. */ getMaximumGraphBounds(): Rectangle | null { return this.maximumGraphBounds; } /** * Clears all cell states or the states for the hierarchy starting at the * given cell and validates the graph. This fires a refresh event as the * last step. * * @param cell Optional {@link Cell} for which the cell states should be cleared. */ refresh(cell: Cell | null = null): void { if (cell) { this.view.clear(cell, false); } else { this.view.clear(undefined, true); } this.view.validate(); this.sizeDidChange(); this.fireEvent(new EventObject(InternalEvent.REFRESH)); } /** * Centers the graph in the container. * * @param horizontal Optional boolean that specifies if the graph should be centered * horizontally. Default is `true`. * @param vertical Optional boolean that specifies if the graph should be centered * vertically. Default is `true`. * @param cx Optional float that specifies the horizontal center. Default is `0.5`. * @param cy Optional float that specifies the vertical center. Default is `0.5`. */ center( horizontal: boolean = true, vertical: boolean = true, cx: number = 0.5, cy: number = 0.5 ): void { const container = <HTMLElement>this.container; const _hasScrollbars = hasScrollbars(this.container); const padding = 2 * this.getBorder(); const cw = container.clientWidth - padding; const ch = container.clientHeight - padding; const bounds = this.getGraphBounds(); const t = this.view.translate; const s = this.view.scale; let dx = horizontal ? cw - bounds.width : 0; let dy = vertical ? ch - bounds.height : 0; if (!_hasScrollbars) { this.view.setTranslate( horizontal ? Math.floor(t.x - bounds.x / s + (dx * cx) / s) : t.x, vertical ? Math.floor(t.y - bounds.y / s + (dy * cy) / s) : t.y ); } else { bounds.x -= t.x; bounds.y -= t.y; const sw = container.scrollWidth; const sh = container.scrollHeight; if (sw > cw) { dx = 0; } if (sh > ch) { dy = 0; } this.view.setTranslate( Math.floor(dx / 2 - bounds.x), Math.floor(dy / 2 - bounds.y) ); container.scrollLeft = (sw - cw) / 2; container.scrollTop = (sh - ch) / 2; } } /** * Returns true if perimeter points should be computed such that the * resulting edge has only horizontal or vertical segments. * * @param edge {@link mxCellState} that represents the edge. */ isOrthogonal(edge: CellState): boolean { /* 'orthogonal' defines if the connection points on either end of the edge should be computed so that the edge is vertical or horizontal if possible and if the point is not at a fixed location. Default is false. This also returns true if the edgeStyle of the edge is an elbow or entity. */ const orthogonal = edge.style.orthogonal; if (orthogonal !== null) { return orthogonal; } const tmp = this.view.getEdgeStyle(edge); return ( tmp === EdgeStyle.SegmentConnector || tmp === EdgeStyle.ElbowConnector || tmp === EdgeStyle.SideToSide || tmp === EdgeStyle.TopToBottom || tmp === EdgeStyle.EntityRelation || tmp === EdgeStyle.OrthConnector ); } /***************************************************************************** * Group: Graph appearance *****************************************************************************/ /** * Returns the {@link backgroundImage} as an {@link Image}. */ getBackgroundImage(): Image | null { return this.backgroundImage; } /** * Sets the new {@link backgroundImage}. * * @param image New {@link Image} to be used for the background. */ setBackgroundImage(image: Image | null): void { this.backgroundImage = image; } /** * Returns the textual representation for the given cell. This * implementation returns the nodename or string-representation of the user * object. * * * The following returns the label attribute from the cells user * object if it is an XML node. * * @example * ```javascript * graph.convertValueToString = function(cell) * { * return cell.getAttribute('label'); * } * ``` * * See also: {@link cellLabelChanged}. * * @param cell {@link mxCell} whose textual representation should be returned. */ convertValueToString(cell: Cell): string { const value = cell.getValue(); if (value != null) { if (isNode(value)) { return value.nodeName; } if (typeof value.toString === 'function') { return value.toString(); } } return ''; } /** * Returns the string to be used as the link for the given cell. This * implementation returns null. * * @param cell {@link mxCell} whose tooltip should be returned. */ getLinkForCell(cell: Cell): string | null { return null; } /** * Returns the value of {@link border}. */ getBorder(): number { return this.border; } /** * Sets the value of {@link border}. * * @param value Positive integer that represents the border to be used. */ setBorder(value: number): void { this.border = value; } /***************************************************************************** * Group: Graph behaviour *****************************************************************************/ /** * Returns {@link resizeContainer}. */ isResizeContainer() { return this.resizeContainer; } /** * Sets {@link resizeContainer}. * * @param value Boolean indicating if the container should be resized. */ setResizeContainer(value: boolean) { this.resizeContainer = value; } /** * Returns true if the graph is {@link enabled}. */ isEnabled() { return this.enabled; } /** * Specifies if the graph should allow any interactions. This * implementation updates {@link enabled}. * * @param value Boolean indicating if the graph should be enabled. */ setEnabled(value: boolean) { this.enabled = value; } /** * Returns {@link multigraph} as a boolean. */ isMultigraph() { return this.multigraph; } /** * Specifies if the graph should allow multiple connections between the * same pair of vertices. * * @param value Boolean indicating if the graph allows multiple connections * between the same pair of vertices. */ setMultigraph(value: boolean) { this.multigraph = value; } /** * Returns {@link allowLoops} as a boolean. */ isAllowLoops() { return this.allowLoops; } /** * Specifies if loops are allowed. * * @param value Boolean indicating if loops are allowed. */ setAllowLoops(value: boolean) { this.allowLoops = value; } /** * Returns {@link recursiveResize}. * * @param state {@link mxCellState} that is being resized. */ isRecursiveResize(state: CellState | null = null) { return this.recursiveResize; } /** * Sets {@link recursiveResize}. * * @param value New boolean value for {@link recursiveResize}. */ setRecursiveResize(value: boolean) { this.recursiveResize = value; } /** * Returns a decimal number representing the amount of the width and height * of the given cell that is allowed to overlap its parent. A value of 0 * means all children must stay inside the parent, 1 means the child is * allowed to be placed outside of the parent such that it touches one of * the parents sides. If {@link isAllowOverlapParent} returns false for the given * cell, then this method returns 0. * * @param cell {@link mxCell} for which the overlap ratio should be returned. */ getOverlap(cell: Cell) { return this.isAllowOverlapParent(cell) ? this.defaultOverlap : 0; } /** * Returns true if the given cell is allowed to be placed outside of the * parents area. * * @param cell {@link mxCell} that represents the child to be checked. */ isAllowOverlapParent(cell: Cell): boolean { return false; } /***************************************************************************** * Group: Cell retrieval *****************************************************************************/ /** * Returns {@link defaultParent} or {@link GraphView.currentRoot} or the first child * child of {@link Model.root} if both are null. The value returned by * this function should be used as the parent for new cells (aka default * layer). */ getDefaultParent() { let parent = this.getCurrentRoot(); if (!parent) { parent = this.defaultParent; if (!parent) { const root = <Cell>this.getModel().getRoot(); parent = root.getChildAt(0); } } return <Cell>parent; } /** * Sets the {@link defaultParent} to the given cell. Set this to null to return * the first child of the root in getDefaultParent. */ setDefaultParent(cell: Cell | null) { this.defaultParent = cell; } /** * Destroys the graph and all its resources. */ destroy() { if (!this.destroyed) { this.destroyed = true; Object.values(this.pluginsMap).forEach((p) => p.onDestroy()); this.view.destroy(); if (this.model && this.graphModelChangeListener) { this.getModel().removeListener(this.graphModelChangeListener); this.graphModelChangeListener = null; } } } } export { Graph };
the_stack
import { FocusMonitor } from '@angular/cdk/a11y'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { SelectionModel } from '@angular/cdk/collections'; import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, Directive, ElementRef, EventEmitter, forwardRef, Input, OnDestroy, OnInit, Optional, Output, QueryList, ViewEncapsulation, ViewChild } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { McButton } from '@ptsecurity/mosaic/button'; /** Acceptable types for a button toggle. */ export type ToggleType = 'checkbox' | 'radio'; /** * Provider Expression that allows mc-button-toggle-group to register as a ControlValueAccessor. * This allows it to support [(ngModel)]. * @docs-private */ export const MC_BUTTON_TOGGLE_GROUP_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => McButtonToggleGroup), multi: true }; /** Change event object emitted by MсButtonToggle. */ export class McButtonToggleChange { constructor( /** The MсButtonToggle that emits the event. */ public source: McButtonToggle, /** The value assigned to the MсButtonToggle. */ public value: any ) {} } /** Exclusive selection button toggle group that behaves like a radio-button group. */ @Directive({ selector: 'mc-button-toggle-group', providers: [MC_BUTTON_TOGGLE_GROUP_VALUE_ACCESSOR], host: { role: 'group', class: 'mc-button-toggle-group', '[class.mc-button-toggle_vertical]': 'vertical' }, exportAs: 'mcButtonToggleGroup' }) export class McButtonToggleGroup implements ControlValueAccessor, OnInit, AfterContentInit { /** Whether the toggle group is vertical. */ @Input() get vertical(): boolean { return this._vertical; } set vertical(value: boolean) { this._vertical = coerceBooleanProperty(value); } /** Value of the toggle group. */ @Input() get value(): any { const selected = this.selectionModel ? this.selectionModel.selected : []; if (this.multiple) { return selected.map((toggle) => toggle.value); } return selected[0] ? selected[0].value : undefined; } set value(newValue: any) { this.setSelectionByValue(newValue); this.valueChange.emit(this.value); } /** Selected button toggles in the group. */ get selected(): any { const selected = this.selectionModel.selected; return this.multiple ? selected : (selected[0] || null); } /** Whether multiple button toggles can be selected. */ @Input() get multiple(): boolean { return this._multiple; } set multiple(value: boolean) { this._multiple = coerceBooleanProperty(value); } /** Child button toggle buttons. */ @ContentChildren(forwardRef(() => McButtonToggle)) buttonToggles: QueryList<McButtonToggle>; /** Whether multiple button toggle group is disabled. */ @Input() get disabled(): boolean { return this._disabled; } set disabled(value: boolean) { this._disabled = coerceBooleanProperty(value); if (!this.buttonToggles) { return; } this.buttonToggles.forEach((toggle) => toggle.markForCheck()); } /** * Event that emits whenever the value of the group changes. * Used to facilitate two-way data binding. * @docs-private */ @Output() readonly valueChange = new EventEmitter<any>(); /** Event emitted when the group's value changes. */ @Output() readonly change: EventEmitter<McButtonToggleChange> = new EventEmitter<McButtonToggleChange>(); private _vertical = false; private _multiple = false; private _disabled = false; private selectionModel: SelectionModel<McButtonToggle>; /** * Reference to the raw value that the consumer tried to assign. The real * value will exclude any values from this one that don't correspond to a * toggle. Useful for the cases where the value is assigned before the toggles * have been initialized or at the same that they're being swapped out. */ private rawValue: any; constructor(private _changeDetector: ChangeDetectorRef) {} /** * The method to be called in order to update ngModel. * Now `ngModel` binding is not supported in multiple selection mode. */ // tslint:disable-next-line:no-empty controlValueAccessorChangeFn: (value: any) => void = () => {}; /** onTouch function registered via registerOnTouch (ControlValueAccessor). */ // tslint:disable-next-line:no-empty onTouched: () => any = () => {}; ngOnInit() { this.selectionModel = new SelectionModel<McButtonToggle>(this.multiple, undefined, false); } ngAfterContentInit() { this.selectionModel.select(...this.buttonToggles.filter((toggle) => toggle.checked)); this.disabled = this._disabled; } /** * Sets the model value. Implemented as part of ControlValueAccessor. * @param value Value to be set to the model. */ writeValue(value: any) { this.value = value; this._changeDetector.markForCheck(); } // Implemented as part of ControlValueAccessor. registerOnChange(fn: (value: any) => void) { this.controlValueAccessorChangeFn = fn; } // Implemented as part of ControlValueAccessor. registerOnTouched(fn: any) { this.onTouched = fn; } // Implemented as part of ControlValueAccessor. setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; } /** Dispatch change event with current selection and group value. */ emitChangeEvent(): void { const selected = this.selected; const source = Array.isArray(selected) ? selected[selected.length - 1] : selected; const event = new McButtonToggleChange(source, this.value); this.controlValueAccessorChangeFn(event.value); this.change.emit(event); } /** * Syncs a button toggle's selected state with the model value. * @param toggle Toggle to be synced. * @param select Whether the toggle should be selected. * @param isUserInput Whether the change was a result of a user interaction. */ syncButtonToggle(toggle: McButtonToggle, select: boolean, isUserInput = false) { // Deselect the currently-selected toggle, if we're in single-selection // mode and the button being toggled isn't selected at the moment. if (!this.multiple && this.selected && !toggle.checked) { (this.selected as McButtonToggle).checked = false; } if (select) { this.selectionModel.select(toggle); } else { this.selectionModel.deselect(toggle); } // Only emit the change event for user input. if (isUserInput) { this.emitChangeEvent(); } // Note: we emit this one no matter whether it was a user interaction, because // it is used by Angular to sync up the two-way data binding. this.valueChange.emit(this.value); } /** Checks whether a button toggle is selected. */ isSelected(toggle: McButtonToggle) { return this.selectionModel.isSelected(toggle); } /** Determines whether a button toggle should be checked on init. */ isPrechecked(toggle: McButtonToggle) { if (this.rawValue === undefined) { return false; } if (this.multiple && Array.isArray(this.rawValue)) { return this.rawValue.some((value) => toggle.value != null && value === toggle.value); } return toggle.value === this.rawValue; } /** Updates the selection state of the toggles in the group based on a value. */ private setSelectionByValue(value: any | any[]) { this.rawValue = value; if (!this.buttonToggles) { return; } if (this.multiple && value) { if (!Array.isArray(value)) { throw Error('Value must be an array in multiple-selection mode.'); } this.clearSelection(); value.forEach((currentValue: any) => this.selectValue(currentValue)); } else { this.clearSelection(); this.selectValue(value); } } /** Clears the selected toggles. */ private clearSelection() { this.selectionModel.clear(); this.buttonToggles.forEach((toggle) => toggle.checked = false); } /** Selects a value if there's a toggle that corresponds to it. */ private selectValue(value: any) { const correspondingOption = this.buttonToggles.find((toggle) => { return toggle.value != null && toggle.value === value; }); if (correspondingOption) { correspondingOption.checked = true; this.selectionModel.select(correspondingOption); } } } /** Single button inside of a toggle group. */ @Component({ selector: 'mc-button-toggle', exportAs: 'mcButtonToggle', template: ` <button mc-button type="button" [class.mc-active]="checked" [disabled]="disabled" [tabIndex]="tabIndex" (click)="onToggleClick()"> <ng-content></ng-content> </button> `, styleUrls: ['button-toggle.scss'], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, host: { class: 'mc-button-toggle', '[class.mc-button-toggle-standalone]': '!buttonToggleGroup' } }) export class McButtonToggle implements OnInit, OnDestroy { /** Whether the button is checked. */ @Input() get checked(): boolean { return this.buttonToggleGroup ? this.buttonToggleGroup.isSelected(this) : this._checked; } set checked(value: boolean) { const newValue = coerceBooleanProperty(value); if (newValue !== this._checked) { this._checked = newValue; if (this.buttonToggleGroup) { this.buttonToggleGroup.syncButtonToggle(this, this._checked); } this.changeDetectorRef.markForCheck(); } } // tslint:disable-next-line:no-reserved-keywords type: ToggleType; @ViewChild(McButton, { static: false }) mcButton: McButton; /** McButtonToggleGroup reads this to assign its own value. */ @Input() value: any; /** Tabindex for the toggle. */ @Input() tabIndex: number | null; @Input() get disabled(): boolean { return this._disabled || (this.buttonToggleGroup && this.buttonToggleGroup.disabled); } set disabled(value: boolean) { this._disabled = coerceBooleanProperty(value); } /** Event emitted when the group value changes. */ @Output() readonly change: EventEmitter<McButtonToggleChange> = new EventEmitter<McButtonToggleChange>(); private isSingleSelector = false; private _checked = false; private _disabled: boolean = false; constructor( @Optional() public buttonToggleGroup: McButtonToggleGroup, private changeDetectorRef: ChangeDetectorRef, private focusMonitor: FocusMonitor, private element: ElementRef ) {} ngOnInit() { this.isSingleSelector = this.buttonToggleGroup && !this.buttonToggleGroup.multiple; this.type = this.isSingleSelector ? 'radio' : 'checkbox'; if (this.buttonToggleGroup && this.buttonToggleGroup.isPrechecked(this)) { this.checked = true; } this.focusMonitor.monitor(this.element.nativeElement, true); } ngOnDestroy() { const group = this.buttonToggleGroup; this.focusMonitor.stopMonitoring(this.element.nativeElement); // Remove the toggle from the selection once it's destroyed. Needs to happen // on the next tick in order to avoid "changed after checked" errors. if (group && group.isSelected(this)) { Promise.resolve().then(() => group.syncButtonToggle(this, false)); } } /** Focuses the button. */ focus(): void { this.element.nativeElement.focus(); } /** Checks the button toggle due to an interaction with the underlying native button. */ onToggleClick() { if (this.disabled) { return; } const newChecked = this.isSingleSelector ? true : !this._checked; if (newChecked !== this._checked) { this._checked = newChecked; if (this.buttonToggleGroup) { this.buttonToggleGroup.syncButtonToggle(this, this._checked, true); this.buttonToggleGroup.onTouched(); } } // Emit a change event when it's the single selector this.change.emit(new McButtonToggleChange(this, this.value)); } /** * Marks the button toggle as needing checking for change detection. * This method is exposed because the parent button toggle group will directly * update bound properties of the radio button. */ markForCheck() { // When the group value changes, the button will not be notified. // Use `markForCheck` to explicit update button toggle's status. this.changeDetectorRef.markForCheck(); } }
the_stack
import tv4 from 'tv4'; import Types from './types'; import SchemaNotFound from './schema-not-found-error'; import EventHandling from './eventhandling'; import config from './config'; import { applyMixins, cleanPath } from './util'; import RemoteStorage from './remotestorage'; /** * Provides a high-level interface to access data below a given root path. */ class BaseClient { /** * The <RemoteStorage> instance this <BaseClient> operates on. */ storage: RemoteStorage; /** * Base path, which this <BaseClient> operates on. * * For the module's privateClient this would be /<moduleName>/, for the * corresponding publicClient /public/<moduleName>/. */ base: string; moduleName: string; constructor(storage: RemoteStorage, base: string) { if (base[base.length - 1] !== '/') { throw "Not a folder: " + base; } if (base === '/') { // allow absolute and relative paths for the root scope. this.makePath = (path: string): string => { return (path[0] === '/' ? '' : '/') + path; }; } this.storage = storage; this.base = base; /** * TODO: document */ const parts = this.base.split('/'); if (parts.length > 2) { this.moduleName = parts[1]; } else { this.moduleName = 'root'; } this.addEvents(['change']); this.on = this.on.bind(this); storage.onChange(this.base, this._fireChange.bind(this)); } /** * Instantiate a new client, scoped to a subpath of the current client's * path. * * @param path - The path to scope the new client to * * @returns A new client operating on a subpath of the current base path */ scope (path: string): BaseClient { return new BaseClient(this.storage, this.makePath(path)); } /** * Get a list of child nodes below a given path. * * @param {string} path - The path to query. It MUST end with a forward slash. * @param {number} maxAge - (optional) Either ``false`` or the maximum age of * cached listing in milliseconds. See :ref:`max-age`. * * @returns {Promise} A promise for an object representing child nodes */ // TODO add real return type getListing (path: string, maxAge?: false | number): Promise<unknown> { if (typeof (path) !== 'string') { path = ''; } else if (path.length > 0 && path[path.length - 1] !== '/') { return Promise.reject("Not a folder: " + path); } return this.storage.get(this.makePath(path), maxAge).then( function (r) { return (r.statusCode === 404) ? {} : r.body; } ); } /** * Get all objects directly below a given path. * * @param {string} path - Path to the folder. Must end in a forward slash. * @param {number} maxAge - (optional) Either ``false`` or the maximum age of * cached objects in milliseconds. See :ref:`max-age`. * * @returns {Promise} A promise for an object */ // TODO add real return type getAll (path: string, maxAge?: false | number): Promise<unknown> { if (typeof (path) !== 'string') { path = ''; } else if (path.length > 0 && path[path.length - 1] !== '/') { return Promise.reject("Not a folder: " + path); } return this.storage.get(this.makePath(path), maxAge).then((r) => { if (r.statusCode === 404) { return {}; } if (typeof (r.body) === 'object') { const keys = Object.keys(r.body); if (keys.length === 0) { // treat this like 404. it probably means a folder listing that // has changes that haven't been pushed out yet. return {}; } const calls = keys.map((key: string) => { return this.storage.get(this.makePath(path + key), maxAge) .then(function (o) { if (typeof (o.body) === 'string') { try { o.body = JSON.parse(o.body); } catch (e) { // empty } } if (typeof (o.body) === 'object') { r.body[key] = o.body; } }); }); return Promise.all(calls).then(function () { return r.body; }); } }); } /** * Get the file at the given path. A file is raw data, as opposed to * a JSON object (use :func:`getObject` for that). * * @param {string} path - Relative path from the module root (without leading * slash). * @param {number} maxAge - (optional) Either ``false`` or the maximum age of * the cached file in milliseconds. See :ref:`max-age`. * * @returns {Promise} A promise for an object */ // TODO add real return type getFile (path: string, maxAge?: false | number): Promise<unknown> { if (typeof (path) !== 'string') { return Promise.reject('Argument \'path\' of baseClient.getFile must be a string'); } return this.storage.get(this.makePath(path), maxAge).then(function (r) { return { data: r.body, contentType: r.contentType, revision: r.revision // (this is new) }; }); } /** * Store raw data at a given path. * * @param {string} mimeType - MIME media type of the data being stored * @param {string} path - Path relative to the module root * @param {string|ArrayBuffer|ArrayBufferView} body - Raw data to store * * @returns {Promise} A promise for the created/updated revision (ETag) */ storeFile (mimeType: string, path: string, body: string | ArrayBuffer | ArrayBufferView): Promise<string> { if (typeof (mimeType) !== 'string') { return Promise.reject('Argument \'mimeType\' of baseClient.storeFile must be a string'); } if (typeof (path) !== 'string') { return Promise.reject('Argument \'path\' of baseClient.storeFile must be a string'); } if (typeof (body) !== 'string' && typeof (body) !== 'object') { return Promise.reject('Argument \'body\' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView'); } if (!this.storage.access.checkPathPermission(this.makePath(path), 'rw')) { console.warn('WARNING: Editing a document to which only read access (\'r\') was claimed'); } return this.storage.put(this.makePath(path), body, mimeType).then((r) => { if (r.statusCode === 200 || r.statusCode === 201) { return r.revision; } else { return Promise.reject("Request (PUT " + this.makePath(path) + ") failed with status: " + r.statusCode); } }); } /** * Get a JSON object from the given path. * * @param {string} path - Relative path from the module root (without leading * slash). * @param {number} maxAge - (optional) Either ``false`` or the maximum age of * cached object in milliseconds. See :ref:`max-age`. * * @returns {Promise} A promise, which resolves with the requested object (or ``null`` * if non-existent) */ // TODO add real return type getObject (path: string, maxAge?: false | number): Promise<unknown> { if (typeof (path) !== 'string') { return Promise.reject('Argument \'path\' of baseClient.getObject must be a string'); } return this.storage.get(this.makePath(path), maxAge).then((r) => { if (typeof (r.body) === 'object') { // will be the case for documents stored with rs.js <= 0.10.0-beta2 return r.body; } else if (typeof (r.body) === 'string') { try { return JSON.parse(r.body); } catch (e) { throw new Error("Not valid JSON: " + this.makePath(path)); } } else if (typeof (r.body) !== 'undefined' && r.statusCode === 200) { return Promise.reject("Not an object: " + this.makePath(path)); } }); } /** * Store object at given path. Triggers synchronization. * * See ``declareType()`` and :doc:`data types </data-modules/defining-data-types>` * for an explanation of types * * @param {string} typeAlias - Unique type of this object within this module. * @param {string} path - Path relative to the module root. * @param {object} object - A JavaScript object to be stored at the given * path. Must be serializable as JSON. * * @returns {Promise} Resolves with revision on success. Rejects with * a ValidationError, if validations fail. */ // TODO add real return type storeObject (typeAlias: string, path: string, object: object): Promise<unknown> { if (typeof (typeAlias) !== 'string') { return Promise.reject('Argument \'typeAlias\' of baseClient.storeObject must be a string'); } if (typeof (path) !== 'string') { return Promise.reject('Argument \'path\' of baseClient.storeObject must be a string'); } if (typeof (object) !== 'object') { return Promise.reject('Argument \'object\' of baseClient.storeObject must be an object'); } this._attachType(object, typeAlias); try { const validationResult = this.validate(object); if (!validationResult.valid) { return Promise.reject(validationResult); } } catch (exc) { return Promise.reject(exc); } return this.storage.put(this.makePath(path), JSON.stringify(object), 'application/json; charset=UTF-8').then((r) => { if (r.statusCode === 200 || r.statusCode === 201) { return r.revision; } else { return Promise.reject("Request (PUT " + this.makePath(path) + ") failed with status: " + r.statusCode); } }); } /** * Remove node at given path from storage. Triggers synchronization. * * @param {string} path - Path relative to the module root. * @returns {Promise} */ // TODO add real return type remove (path: string): Promise<unknown> { if (typeof (path) !== 'string') { return Promise.reject('Argument \'path\' of baseClient.remove must be a string'); } if (!this.storage.access.checkPathPermission(this.makePath(path), 'rw')) { console.warn('WARNING: Removing a document to which only read access (\'r\') was claimed'); } return this.storage.delete(this.makePath(path)); } /** * Retrieve full URL of a document. Useful for example for sharing the public * URL of an item in the ``/public`` folder. * * @param {string} path - Path relative to the module root. * @returns {string} The full URL of the item, including the storage origin */ getItemURL (path: string): string { if (typeof (path) !== 'string') { throw 'Argument \'path\' of baseClient.getItemURL must be a string'; } if (this.storage.connected) { path = cleanPath(this.makePath(path)); return this.storage.remote.href + path; } else { return undefined; } } /** * Set caching strategy for a given path and its children. * * See :ref:`caching-strategies` for a detailed description of the available * strategies. * * @param {string} path - Path to cache * @param {string} strategy - Caching strategy. One of 'ALL', 'SEEN', or * 'FLUSH'. Defaults to 'ALL'. * * @returns {BaseClient} The same instance this is called on to allow for method chaining */ cache (path: string, strategy: 'ALL' | 'SEEN' | 'FLUSH' = 'ALL') { if (typeof path !== 'string') { throw 'Argument \'path\' of baseClient.cache must be a string'; } if (typeof strategy !== 'string') { throw 'Argument \'strategy\' of baseClient.cache must be a string or undefined'; } if (strategy !== 'FLUSH' && strategy !== 'SEEN' && strategy !== 'ALL') { throw 'Argument \'strategy\' of baseclient.cache must be one of ' + '["FLUSH", "SEEN", "ALL"]'; } this.storage.caching.set(this.makePath(path), strategy); return this; } /** * TODO: document * * @param {string} path */ // TODO add return type once known flush (path: string): unknown { return this.storage.local.flush(path); } /** * Declare a remoteStorage object type using a JSON schema. * * See :doc:`Defining data types </data-modules/defining-data-types>` for more info. * * @param {string} alias - A type alias/shortname * @param {uri} uri - (optional) JSON-LD URI of the schema. Automatically generated if none given * @param {object} schema - A JSON Schema object describing the object type **/ declareType (alias: any, uriOrSchema: any, schema?: any): void { let uri: string; if (!schema) { schema = uriOrSchema; uri = this._defaultTypeURI(alias); } else { uri = uriOrSchema; } BaseClient.Types.declare(this.moduleName, alias, uri, schema); } /** * Validate an object against the associated schema. * * @param {Object} object - JS object to validate. Must have a ``@context`` property. * * @returns {Object} An object containing information about validation errors **/ validate (object: {[key: string]: any}): {[key: string]: any} { const schema = BaseClient.Types.getSchema(object['@context']); if (schema) { return tv4.validateResult(object, schema); } else { throw new SchemaNotFound(object['@context']); } } /** * TODO document * * @private */ schemas = { configurable: true, get: function () { return BaseClient.Types.inScope(this.moduleName); } }; /** * The default JSON-LD @context URL for RS types/objects/documents * * @private */ _defaultTypeURI (alias: string): string { return 'http://remotestorage.io/spec/modules/' + encodeURIComponent(this.moduleName) + '/' + encodeURIComponent(alias); } /** * Attaches the JSON-LD @content to an object * * @private */ _attachType (object: object, alias: string): void { object['@context'] = BaseClient.Types.resolveAlias(this.moduleName + '/' + alias) || this._defaultTypeURI(alias); } /** * TODO: document * * @private */ makePath (path: string): string { return this.base + (path || ''); } /** * TODO: document * * @private */ _fireChange (event: ChangeObj) { if (config.changeEvents[event.origin]) { ['new', 'old', 'lastCommon'].forEach(function (fieldNamePrefix) { if ((!event[fieldNamePrefix + 'ContentType']) || (/^application\/(.*)json(.*)/.exec(event[fieldNamePrefix + 'ContentType']))) { if (typeof (event[fieldNamePrefix + 'Value']) === 'string') { try { event[fieldNamePrefix + 'Value'] = JSON.parse(event[fieldNamePrefix + 'Value']); } catch (e) { // empty } } } }); this._emit('change', event); } } static Types = Types; static _rs_init (): void { return; } } interface BaseClient extends EventHandling {}; applyMixins(BaseClient, [EventHandling]); export = BaseClient;
the_stack
import setupLogger from '@/config/logger'; import { IExplorer } from '@/services/datastores/base/datastore'; import { ICassandraAccessDef, IClusterSchemaColumn, ICreateTableOptions, IDatacenter, IKeyResult, IKeyspace, IKeyspaceReplication, IStatementResult, ITableSchema, ITableSummary, IUserDefinedType, IClusterInfo, IKeyQuery, CassEncoding, IRowDetails, IStatementExecuteOptions, } from '@/services/datastores/cassandra/typings/cassandra'; import { Client } from 'cassandra-driver'; import { getBinaryValue } from './modules/blob'; import { getClusterSchema } from './modules/columns'; import { deleteKey, generateInsertStatement, getKeys, insertKey, updateKey, } from './modules/keys'; import { getKeyspace, getKeyspaces } from './modules/keyspaces'; import { createKeyspace, createTable, createTableAdvanced, dropTable, generateCreateStatement, truncateTable, } from './modules/schema'; import { execute } from './modules/statement'; import { getTable, getTables } from './modules/tables'; import { getTypes } from './modules/types'; import { getVersion } from './utils/cluster-utils'; const logger = setupLogger(module); export default class CassandraExplorer implements IExplorer { /** * Create an instance of the CassandraExplorer by wrapping an existing cassandra driver client instance. * @param client */ constructor(readonly client: Client) {} /** * Fetches the list of datacenters (regions) this cluster spans. Each datacenter returned will * include the list of racks (AZs). * @returns Returns an array of datacenters. */ public async getDatacenters(): Promise<IDatacenter[]> { logger.info('fetching cluster regions'); await this.client.connect(); const datacenters = this.client.metadata.datacenters; return Object.keys(datacenters) .sort() .map((datacenter) => ({ name: datacenter, racks: datacenters[datacenter].racks.toArray(), })); } /** * Creates a new Keyspace. * @param keyspaceName Name of the new keyspace. * @param datacenters Map of datacenter names to az count (e.g. { "us-east": 1 }). * @returns Returns a Promise that will be resolved with the value of * true if successful. Rejects with error if the request fails. */ public async createKeyspace( keyspaceName: string, datacenters: IKeyspaceReplication, ): Promise<boolean> { return createKeyspace(this.client, keyspaceName, datacenters); } /** * Permanently and irreversibly destroys a table schema and all data. * @param keyspaceName Keyspace containing the table to drop. * @param tableName Name of the table to drop. */ public async dropTable( keyspaceName: string, tableName: string, ): Promise<IStatementResult> { return dropTable(this.client, keyspaceName, tableName); } /** * Permanently and irreversibly destroys all data in a table. * @param keyspaceName Keyspace containing the table to truncate. * @param tableName Name of the table to truncate. */ public async truncateTable( keyspaceName: string, tableName: string, ): Promise<IStatementResult> { return truncateTable(this.client, keyspaceName, tableName); } /** * Generates a CREATE TABLE statement which can be passed to the driver to execute. * @param tableOptions The table options. * @return Returns a Promise that will resolve with the generated CREATE TABLE statement. */ public async generateCreateStatement( tableOptions: ICreateTableOptions, ): Promise<string> { return generateCreateStatement(this.client, tableOptions); } /** * Executes a CREATE TABLE statement using the given table options. * @param options The creation options * @return Returns a Promise containing the result of the table creation operation. */ public async createTable( options: ICreateTableOptions, clusterAcccess: ICassandraAccessDef, ): Promise<any> { return createTable(this.client, options, clusterAcccess); } /** * Executes a CREATE TABLE statement using the given table options. * @param options The creation options * @return Returns a Promise containing the result of the table creation operation. */ public async createTableAdvanced( keyspace: string, table: string, createStatement: string, clusterAcccess: ICassandraAccessDef, ): Promise<any> { return createTableAdvanced( this.client, keyspace, table, createStatement, clusterAcccess, ); } public async getClusterInfo(): Promise<IClusterInfo> { return { version: getVersion(this.client), }; } /** * Fetches the complete list of defined keyspaces. * @returns Returns a Promise that resolves with the list of keyspaces. */ public async getKeyspaces(): Promise<IKeyspace[]> { return getKeyspaces(this.client); } /** * Fetches a given keyspace by name. * @param keyspaceName Keyspace name. * @returns Returns a Promise that resolves with the keyspace if found. */ public async getKeyspace(keyspaceName: string): Promise<IKeyspace> { return getKeyspace(this.client, keyspaceName); } /** * Fetches the list of tables for the current cluster. Can be optionally scoped by keyspace. * @param keyspace Optionally can be used to scope the results to a specific keyspace. * @returns Returns a promise that resolves with the list of tables. */ public async getTables( keyspace: string | undefined, ): Promise<ITableSummary[]> { return getTables(this.client, keyspace); } /** * A batch style query for fetching the entire schema for the current cluster. This will return a mapping * of keyspaces to tables and from tables to columns. Includes column type information. * * This is a fairly expensive operation and is intended for clients to cache the data and call this API * infrequently in order to refresh the cache. * * @param keyspace Optional keyspace to filter by. * @returns Returns a flat array of column definitions per table, per keyspace. */ public async getClusterSchema( keyspace?: string, ): Promise<IClusterSchemaColumn[]> { return getClusterSchema(this.client, keyspace); } /** * Fetches the schema definition for a given table. * @param keyspace The name of the keyspace that contains the table. * @param table The name of the table. * @returns Returns a promise that will be resolved with the table metadata. */ public async getTable( keyspace: string, table: string, ): Promise<ITableSchema> { return getTable(this.client, keyspace, table); } /** * The data types supported by a C* cluster varies depending on the version and keyspace (since UDTs are scoped * by keyspace). * @param keyspaceName The name of the keyspace. * @return {Promise.<{standard: Array.<*>, user}>} Returns a Promise that will be resolved with an object * containing the standard and user types. */ public async getTypes( keyspaceName: string, ): Promise<{ standard: string[]; user: IUserDefinedType[] }> { return getTypes(this.client, keyspaceName); } /** * Executes a freeform query. Expects the query to include the fully qualified table name (i.e. <keyspace>.<table>). * @param query The query string to submit. * @param clusterAccess * @param logMetadata Optional object to include in logger messages. * @returns Returns a Promise that will resolve with the statement result. */ public async execute( query: string, clusterAccess: ICassandraAccessDef, logMetadata: any, options?: IStatementExecuteOptions, ): Promise<IStatementResult> { return execute(this.client, query, clusterAccess, logMetadata, options); } /** * Fetches results by keys. * @param {String} keyspace The keyspace name. * @param {String} table The table name. * @param {Object} params Parameterized object containing the fields to filter by. * @param {String} pageState An optional existing cursor. * @param {Object} logMetadata Optional object to include in logger messages. * @returns {Promise.<TResult>|*} */ public async getKeys( keyspace: string, table: string, params: IKeyQuery, pageState: string | undefined, logMetadata: any, ): Promise<IKeyResult> { return getKeys( this.client, keyspace, table, params, pageState, logMetadata, ); } public generateInsertStatement( schema: ITableSchema, fields: { [columnName: string]: any }, encoding: CassEncoding, ): string { return generateInsertStatement(schema, fields, encoding); } public async getBinaryValue( keyspace: string, table: string, keyQuery: IKeyQuery, binaryColumnName: string, ): Promise<Buffer | null> { return getBinaryValue( this.client, keyspace, table, keyQuery, binaryColumnName, ); } /** * Updates an existing record. * * @param keyspace The name of the keyspace the table belongs to. * @param table The name of the table to perform the UPDATE on. * @param key A map of primary key pairs where the keys are the name of the primary key fields * and the values are the primary key values. This is used to locate the record to * update. * @param updateFields A map of the fields to update. The keys are the names of the columns and the * values are the values for each of the columns. Must be non-empty. * @param logMetadata Additional log metadata to include (optional). * @returns Returns true if the record was updated. False indicates ta */ public async updateKey( keyspace: string, table: string, key: IKeyQuery, updateFields: { [columnName: string]: any }, logMetadata: any, ): Promise<boolean> { return updateKey( this.client, keyspace, table, key, updateFields, logMetadata, ); } /** * Inserts a new record. * @param keyspace The keyspace name. * @param table The table to insert into. * @param fields The map of fields to values. * @param logMetadata Additional log metadata to include (optional). */ public async insertKey( keyspace: string, table: string, row: IRowDetails, logMetadata: any, ): Promise<boolean> { return insertKey(this.client, keyspace, table, row, logMetadata); } /** * Deletes an existing record. * * @param keyspace The name of the keyspace the table belongs to. * @param table The name of the table to perform the UPDATE on. * @param key A map of primary key pairs where the keys are the name of the primary key fields * and the values are the primary key values. This is used to locate the record to * delete. * @param logMetadata Additional log metadata to include (optional). * @return Returns true if the record was deleted successfully. */ public async deleteKey( keyspace: string, table: string, key: IKeyQuery, logMetadata: any, ): Promise<boolean> { return deleteKey(this.client, keyspace, table, key, logMetadata); } public shutdown(): Promise<void> { return this.client.shutdown(); } }
the_stack
import { Fn } from './cfn-fn'; import { Stack } from './stack'; import { Token } from './token'; import { filterUndefined } from './util'; /** * An enum representing the various ARN formats that different services use. */ export enum ArnFormat { /** * This represents a format where there is no 'resourceName' part. * This format is used for S3 resources, * like 'arn:aws:s3:::bucket'. * Everything after the last colon is considered the 'resource', * even if it contains slashes, * like in 'arn:aws:s3:::bucket/object.zip'. */ NO_RESOURCE_NAME = 'arn:aws:service:region:account:resource', /** * This represents a format where the 'resource' and 'resourceName' * parts are separated with a colon. * Like in: 'arn:aws:service:region:account:resource:resourceName'. * Everything after the last colon is considered the 'resourceName', * even if it contains slashes, * like in 'arn:aws:apigateway:region:account:resource:/test/mydemoresource/*'. */ COLON_RESOURCE_NAME = 'arn:aws:service:region:account:resource:resourceName', /** * This represents a format where the 'resource' and 'resourceName' * parts are separated with a slash. * Like in: 'arn:aws:service:region:account:resource/resourceName'. * Everything after the separating slash is considered the 'resourceName', * even if it contains colons, * like in 'arn:aws:cognito-sync:region:account:identitypool/us-east-1:1a1a1a1a-ffff-1111-9999-12345678:bla'. */ SLASH_RESOURCE_NAME = 'arn:aws:service:region:account:resource/resourceName', /** * This represents a format where the 'resource' and 'resourceName' * parts are seperated with a slash, * but there is also an additional slash after the colon separating 'account' from 'resource'. * Like in: 'arn:aws:service:region:account:/resource/resourceName'. * Note that the leading slash is _not_ included in the parsed 'resource' part. */ SLASH_RESOURCE_SLASH_RESOURCE_NAME = 'arn:aws:service:region:account:/resource/resourceName', } export interface ArnComponents { /** * The partition that the resource is in. For standard AWS regions, the * partition is aws. If you have resources in other partitions, the * partition is aws-partitionname. For example, the partition for resources * in the China (Beijing) region is aws-cn. * * @default The AWS partition the stack is deployed to. */ readonly partition?: string; /** * The service namespace that identifies the AWS product (for example, * 's3', 'iam', 'codepipline'). */ readonly service: string; /** * The region the resource resides in. Note that the ARNs for some resources * do not require a region, so this component might be omitted. * * @default The region the stack is deployed to. */ readonly region?: string; /** * The ID of the AWS account that owns the resource, without the hyphens. * For example, 123456789012. Note that the ARNs for some resources don't * require an account number, so this component might be omitted. * * @default The account the stack is deployed to. */ readonly account?: string; /** * Resource type (e.g. "table", "autoScalingGroup", "certificate"). * For some resource types, e.g. S3 buckets, this field defines the bucket name. */ readonly resource: string; /** * Separator between resource type and the resource. * * Can be either '/', ':' or an empty string. Will only be used if resourceName is defined. * @default '/' * * @deprecated use arnFormat instead */ readonly sep?: string; /** * Resource name or path within the resource (i.e. S3 bucket object key) or * a wildcard such as ``"*"``. This is service-dependent. */ readonly resourceName?: string; /** * The specific ARN format to use for this ARN value. * * @default - uses value of `sep` as the separator for formatting, * `ArnFormat.SLASH_RESOURCE_NAME` if that property was also not provided */ readonly arnFormat?: ArnFormat; } export class Arn { /** * Creates an ARN from components. * * If `partition`, `region` or `account` are not specified, the stack's * partition, region and account will be used. * * If any component is the empty string, an empty string will be inserted * into the generated ARN at the location that component corresponds to. * * The ARN will be formatted as follows: * * arn:{partition}:{service}:{region}:{account}:{resource}{sep}{resource-name} * * The required ARN pieces that are omitted will be taken from the stack that * the 'scope' is attached to. If all ARN pieces are supplied, the supplied scope * can be 'undefined'. */ public static format(components: ArnComponents, stack?: Stack): string { const partition = components.partition ?? stack?.partition; const region = components.region ?? stack?.region; const account = components.account ?? stack?.account; // Catch both 'null' and 'undefined' if (partition == null || region == null || account == null) { throw new Error(`Arn.format: partition (${partition}), region (${region}), and account (${account}) must all be passed if stack is not passed.`); } const sep = components.sep ?? (components.arnFormat === ArnFormat.COLON_RESOURCE_NAME ? ':' : '/'); const values = [ 'arn', ':', partition, ':', components.service, ':', region, ':', account, ':', ...(components.arnFormat === ArnFormat.SLASH_RESOURCE_SLASH_RESOURCE_NAME ? ['/'] : []), components.resource, ]; if (sep !== '/' && sep !== ':' && sep !== '') { throw new Error('resourcePathSep may only be ":", "/" or an empty string'); } if (components.resourceName != null) { values.push(sep); values.push(components.resourceName); } return values.join(''); } /** * Given an ARN, parses it and returns components. * * IF THE ARN IS A CONCRETE STRING... * * ...it will be parsed and validated. The separator (`sep`) will be set to '/' * if the 6th component includes a '/', in which case, `resource` will be set * to the value before the '/' and `resourceName` will be the rest. In case * there is no '/', `resource` will be set to the 6th components and * `resourceName` will be set to the rest of the string. * * IF THE ARN IS A TOKEN... * * ...it cannot be validated, since we don't have the actual value yet at the * time of this function call. You will have to supply `sepIfToken` and * whether or not ARNs of the expected format usually have resource names * in order to parse it properly. The resulting `ArnComponents` object will * contain tokens for the subexpressions of the ARN, not string literals. * * If the resource name could possibly contain the separator char, the actual * resource name cannot be properly parsed. This only occurs if the separator * char is '/', and happens for example for S3 object ARNs, IAM Role ARNs, * IAM OIDC Provider ARNs, etc. To properly extract the resource name from a * Tokenized ARN, you must know the resource type and call * `Arn.extractResourceName`. * * @param arn The ARN to parse * @param sepIfToken The separator used to separate resource from resourceName * @param hasName Whether there is a name component in the ARN at all. For * example, SNS Topics ARNs have the 'resource' component contain the topic * name, and no 'resourceName' component. * * @returns an ArnComponents object which allows access to the various * components of the ARN. * * @returns an ArnComponents object which allows access to the various * components of the ARN. * * @deprecated use split instead */ public static parse(arn: string, sepIfToken: string = '/', hasName: boolean = true): ArnComponents { let arnFormat: ArnFormat; if (!hasName) { arnFormat = ArnFormat.NO_RESOURCE_NAME; } else { arnFormat = sepIfToken === '/' ? ArnFormat.SLASH_RESOURCE_NAME : ArnFormat.COLON_RESOURCE_NAME; } return this.split(arn, arnFormat); } /** * Splits the provided ARN into its components. * Works both if 'arn' is a string like 'arn:aws:s3:::bucket', * and a Token representing a dynamic CloudFormation expression * (in which case the returned components will also be dynamic CloudFormation expressions, * encoded as Tokens). * * @param arn the ARN to split into its components * @param arnFormat the expected format of 'arn' - depends on what format the service 'arn' represents uses */ public static split(arn: string, arnFormat: ArnFormat): ArnComponents { const components = parseArnShape(arn); if (components === 'token') { return parseTokenArn(arn, arnFormat); } const [, partition, service, region, account, resourceTypeOrName, ...rest] = components; let resource: string; let resourceName: string | undefined; let sep: string | undefined; let resourcePartStartIndex = 0; let detectedArnFormat: ArnFormat; let slashIndex = resourceTypeOrName.indexOf('/'); if (slashIndex === 0) { // new-style ARNs are of the form 'arn:aws:s4:us-west-1:12345:/resource-type/resource-name' slashIndex = resourceTypeOrName.indexOf('/', 1); resourcePartStartIndex = 1; detectedArnFormat = ArnFormat.SLASH_RESOURCE_SLASH_RESOURCE_NAME; } if (slashIndex !== -1) { // the slash is only a separator if ArnFormat is not NO_RESOURCE_NAME if (arnFormat === ArnFormat.NO_RESOURCE_NAME) { sep = undefined; slashIndex = -1; detectedArnFormat = ArnFormat.NO_RESOURCE_NAME; } else { sep = '/'; detectedArnFormat = resourcePartStartIndex === 0 ? ArnFormat.SLASH_RESOURCE_NAME // need to repeat this here, as otherwise the compiler thinks 'detectedArnFormat' is not initialized in all paths : ArnFormat.SLASH_RESOURCE_SLASH_RESOURCE_NAME; } } else if (rest.length > 0) { sep = ':'; slashIndex = -1; detectedArnFormat = ArnFormat.COLON_RESOURCE_NAME; } else { sep = undefined; detectedArnFormat = ArnFormat.NO_RESOURCE_NAME; } if (slashIndex !== -1) { resource = resourceTypeOrName.substring(resourcePartStartIndex, slashIndex); resourceName = resourceTypeOrName.substring(slashIndex + 1); } else { resource = resourceTypeOrName; } if (rest.length > 0) { if (!resourceName) { resourceName = ''; } else { resourceName += ':'; } resourceName += rest.join(':'); } // "|| undefined" will cause empty strings to be treated as "undefined". // Optional ARN attributes (e.g. region, account) should return as empty string // if they are provided as such. return filterUndefined({ service: service || undefined, resource: resource || undefined, partition: partition || undefined, region, account, resourceName, sep, arnFormat: detectedArnFormat, }); } /** * Extract the full resource name from an ARN * * Necessary for resource names (paths) that may contain the separator, like * `arn:aws:iam::111111111111:role/path/to/role/name`. * * Only works if we statically know the expected `resourceType` beforehand, since we're going * to use that to split the string on ':<resourceType>/' (and take the right-hand side). * * We can't extract the 'resourceType' from the ARN at hand, because CloudFormation Expressions * only allow literals in the 'separator' argument to `{ Fn::Split }`, and so it can't be * `{ Fn::Select: [5, { Fn::Split: [':', ARN] }}`. * * Only necessary for ARN formats for which the type-name separator is `/`. */ public static extractResourceName(arn: string, resourceType: string): string { const components = parseArnShape(arn); if (components === 'token') { return Fn.select(1, Fn.split(`:${resourceType}/`, arn)); } // Apparently we could just parse this right away. Validate that we got the right // resource type (to notify authors of incorrect assumptions right away). const parsed = Arn.split(arn, ArnFormat.SLASH_RESOURCE_NAME); if (!Token.isUnresolved(parsed.resource) && parsed.resource !== resourceType) { throw new Error(`Expected resource type '${resourceType}' in ARN, got '${parsed.resource}' in '${arn}'`); } if (!parsed.resourceName) { throw new Error(`Expected resource name in ARN, didn't find one: '${arn}'`); } return parsed.resourceName; } private constructor() { } } /** * Given a Token evaluating to ARN, parses it and returns components. * * The ARN cannot be validated, since we don't have the actual value yet * at the time of this function call. You will have to know the separator * and the type of ARN. * * The resulting `ArnComponents` object will contain tokens for the * subexpressions of the ARN, not string literals. * * WARNING: this function cannot properly parse the complete final * 'resourceName' part if it contains colons, * like 'arn:aws:cognito-sync:region:account:identitypool/us-east-1:1a1a1a1a-ffff-1111-9999-12345678:bla'. * * @param arnToken The input token that contains an ARN * @param arnFormat the expected format of 'arn' - depends on what format the service the ARN represents uses */ function parseTokenArn(arnToken: string, arnFormat: ArnFormat): ArnComponents { // ARN looks like: // arn:partition:service:region:account:resource // arn:partition:service:region:account:resource:resourceName // arn:partition:service:region:account:resource/resourceName // arn:partition:service:region:account:/resource/resourceName const components = Fn.split(':', arnToken); const partition = Fn.select(1, components).toString(); const service = Fn.select(2, components).toString(); const region = Fn.select(3, components).toString(); const account = Fn.select(4, components).toString(); let resource: string; let resourceName: string | undefined; let sep: string | undefined; if (arnFormat === ArnFormat.NO_RESOURCE_NAME || arnFormat === ArnFormat.COLON_RESOURCE_NAME) { // we know that the 'resource' part will always be the 6th segment in this case resource = Fn.select(5, components); if (arnFormat === ArnFormat.COLON_RESOURCE_NAME) { resourceName = Fn.select(6, components); sep = ':'; } else { resourceName = undefined; sep = undefined; } } else { // we know that the 'resource' and 'resourceName' parts are separated by slash here, // so we split the 6th segment from the colon-separated ones with a slash const lastComponents = Fn.split('/', Fn.select(5, components)); if (arnFormat === ArnFormat.SLASH_RESOURCE_NAME) { resource = Fn.select(0, lastComponents); resourceName = Fn.select(1, lastComponents); } else { // arnFormat is ArnFormat.SLASH_RESOURCE_SLASH_RESOURCE_NAME, // which means there's an extra slash there at the beginning that we need to skip resource = Fn.select(1, lastComponents); resourceName = Fn.select(2, lastComponents); } sep = '/'; } return { partition, service, region, account, resource, resourceName, sep, arnFormat }; } /** * Validate that a string is either unparseable or looks mostly like an ARN */ function parseArnShape(arn: string): 'token' | string[] { // assume anything that starts with 'arn:' is an ARN, // so we can report better errors const looksLikeArn = arn.startsWith('arn:'); if (!looksLikeArn) { if (Token.isUnresolved(arn)) { return 'token'; } else { throw new Error(`ARNs must start with "arn:" and have at least 6 components: ${arn}`); } } // If the ARN merely contains Tokens, but otherwise *looks* mostly like an ARN, // it's a string of the form 'arn:${partition}:service:${region}:${account}:resource/xyz'. // Parse fields out to the best of our ability. // Tokens won't contain ":", so this won't break them. const components = arn.split(':'); const partition = components.length > 1 ? components[1] : undefined; if (!partition) { throw new Error('The `partition` component (2nd component) of an ARN is required: ' + arn); } const service = components.length > 2 ? components[2] : undefined; if (!service) { throw new Error('The `service` component (3rd component) of an ARN is required: ' + arn); } const resource = components.length > 5 ? components[5] : undefined; if (!resource) { throw new Error('The `resource` component (6th component) of an ARN is required: ' + arn); } // Region can be missing in global ARNs (such as used by IAM) // Account can be missing in some ARN types (such as used for S3 buckets) return components; }
the_stack
import { toAsyncIterable } from '@esfx/async-iter-fromsync'; import { Equaler } from "@esfx/equatable"; import { identity, tuple } from '@esfx/fn'; import * as assert from "@esfx/internal-assert"; import { defaultIfEmpty, empty, map, union } from "@esfx/iter-fn"; import { Grouping } from "@esfx/iter-grouping"; import { Lookup } from "@esfx/iter-lookup"; import { createGroupingsAsync } from './internal/utils'; class AsyncGroupJoinIterable<O, I, K, R> implements AsyncIterable<R> { private _outer: AsyncIterable<O> | Iterable<PromiseLike<O> | O>; private _inner: AsyncIterable<I> | Iterable<PromiseLike<I> | I>; private _outerKeySelector: (element: O) => K; private _innerKeySelector: (element: I) => K; private _resultSelector: (outer: O, inner: Iterable<I>) => PromiseLike<R> | R; private _keyEqualer?: Equaler<K> constructor(outer: AsyncIterable<O> | Iterable<PromiseLike<O> | O>, inner: AsyncIterable<I> | Iterable<PromiseLike<I> | I>, outerKeySelector: (element: O) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: O, inner: Iterable<I>) => PromiseLike<R> | R, keyEqualer?: Equaler<K>) { this._outer = outer; this._inner = inner; this._outerKeySelector = outerKeySelector; this._innerKeySelector = innerKeySelector; this._resultSelector = resultSelector; this._keyEqualer = keyEqualer; } async *[Symbol.asyncIterator](): AsyncIterator<R> { const outerKeySelector = this._outerKeySelector; const resultSelector = this._resultSelector; const map = await createGroupingsAsync(this._inner, this._innerKeySelector, identity, this._keyEqualer); for await (const outerElement of this._outer) { const outerKey = outerKeySelector(outerElement); const innerElements = map.get(outerKey) || empty<I>(); yield resultSelector(outerElement, innerElements); } } } /** * Creates a grouped [[AsyncIterable]] for the correlated elements between an outer [[AsyncQueryable]] object and an inner [[AsyncQueryable]] object. * * @param outer An [[AsyncQueryable]] object. * @param inner An [[AsyncQueryable]] object. * @param outerKeySelector A callback used to select the key for an element in `outer`. * @param innerKeySelector A callback used to select the key for an element in `inner`. * @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 */ export function groupJoinAsync<O, I, K, R>(outer: AsyncIterable<O> | Iterable<PromiseLike<O> | O>, inner: AsyncIterable<I> | Iterable<PromiseLike<I> | I>, outerKeySelector: (element: O) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: O, inner: Iterable<I>) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncIterable<R> { assert.mustBeAsyncOrSyncIterableObject(outer, "outer"); assert.mustBeAsyncOrSyncIterableObject(inner, "inner"); assert.mustBeFunction(outerKeySelector, "outerKeySelector"); assert.mustBeFunction(innerKeySelector, "innerKeySelector"); assert.mustBeFunction(resultSelector, "resultSelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return new AsyncGroupJoinIterable(outer, inner, outerKeySelector, innerKeySelector, resultSelector, keyEqualer); } class AsyncJoinIterable<O, I, K, R> implements AsyncIterable<R> { private _outer: AsyncIterable<O> | Iterable<PromiseLike<O> | O>; private _inner: AsyncIterable<I> | Iterable<PromiseLike<I> | I>; private _outerKeySelector: (element: O) => K; private _innerKeySelector: (element: I) => K; private _resultSelector: (outer: O, inner: I) => PromiseLike<R> | R; private _keyEqualer?: Equaler<K> constructor(outer: AsyncIterable<O> | Iterable<PromiseLike<O> | O>, inner: AsyncIterable<I> | Iterable<PromiseLike<I> | I>, outerKeySelector: (element: O) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: O, inner: I) => PromiseLike<R> | R, keyEqualer?: Equaler<K>) { this._outer = outer; this._inner = inner; this._outerKeySelector = outerKeySelector; this._innerKeySelector = innerKeySelector; this._resultSelector = resultSelector; this._keyEqualer = keyEqualer; } async *[Symbol.asyncIterator](): AsyncIterator<R> { const outerKeySelector = this._outerKeySelector; const resultSelector = this._resultSelector; const map = await createGroupingsAsync(this._inner, this._innerKeySelector, identity, this._keyEqualer); for await (const outerElement of this._outer) { const outerKey = outerKeySelector(outerElement); const innerElements = map.get(outerKey); if (innerElements != undefined) { for (const innerElement of innerElements) { yield resultSelector(outerElement, innerElement); } } } } } /** * Creates an [[AsyncIterable]] for the correlated elements of two [[AsyncQueryable]] objects. * * @param outer An [[AsyncQueryable]]. * @param inner An [[AsyncQueryable]]. * @param outerKeySelector A callback used to select the key for an element in `outer`. * @param innerKeySelector A callback used to select the key for an element in `inner`. * @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 */ export function joinAsync<O, I, K, R>(outer: AsyncIterable<O> | Iterable<PromiseLike<O> | O>, inner: AsyncIterable<I> | Iterable<PromiseLike<I> | I>, outerKeySelector: (element: O) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: O, inner: I) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncIterable<R> { assert.mustBeAsyncOrSyncIterableObject(outer, "outer"); assert.mustBeAsyncOrSyncIterableObject(inner, "inner"); assert.mustBeFunction(outerKeySelector, "outerKeySelector"); assert.mustBeFunction(innerKeySelector, "innerKeySelector"); assert.mustBeFunction(resultSelector, "resultSelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return new AsyncJoinIterable(outer, inner, outerKeySelector, innerKeySelector, resultSelector, keyEqualer); } function selectGroupingKey<K, V>(grouping: Grouping<K, V>) { return grouping.key; } class AsyncFullJoinIterable<O, I, K, R> implements AsyncIterable<R> { private _outer: AsyncIterable<O> | Iterable<PromiseLike<O> | O>; private _inner: AsyncIterable<I> | Iterable<PromiseLike<I> | I>; private _outerKeySelector: (element: O) => K; private _innerKeySelector: (element: I) => K; private _resultSelector: (outer: O | undefined, inner: I | undefined) => PromiseLike<R> | R; private _keyEqualer?: Equaler<K> constructor(outer: AsyncIterable<O> | Iterable<PromiseLike<O> | O>, inner: AsyncIterable<I> | Iterable<PromiseLike<I> | I>, outerKeySelector: (element: O) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: O | undefined, inner: I | undefined) => PromiseLike<R> | R, keyEqualer?: Equaler<K>) { this._outer = outer; this._inner = inner; this._outerKeySelector = outerKeySelector; this._innerKeySelector = innerKeySelector; this._resultSelector = resultSelector; this._keyEqualer = keyEqualer; } async *[Symbol.asyncIterator](): AsyncIterator<R> { const resultSelector = this._resultSelector; const outerLookup = new Lookup<K, O>(await createGroupingsAsync(this._outer, this._outerKeySelector, identity, this._keyEqualer)); const innerLookup = new Lookup<K, I>(await createGroupingsAsync(this._inner, this._innerKeySelector, identity, this._keyEqualer)); const keys = union(map(outerLookup, selectGroupingKey), map(innerLookup, selectGroupingKey), this._keyEqualer); for (const key of keys) { const outer = defaultIfEmpty<O | undefined>(outerLookup.get(key), undefined); const inner = defaultIfEmpty<I | undefined>(innerLookup.get(key), undefined); for (const outerElement of outer) { for (const innerElement of inner) { yield resultSelector(outerElement, innerElement); } } } } } /** * Creates an [[AsyncIterable]] for the correlated elements between an outer [[AsyncQueryable]] object and an inner * [[AsyncQueryable]] object. * * @param outer An [[AsyncQueryable]] object. * @param inner An [[AsyncQueryable]] object. * @param outerKeySelector A callback used to select the key for an element in `outer`. * @param innerKeySelector A callback used to select the key for an element in `inner`. * @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 */ export function fullJoinAsync<O, I, K, R>(outer: AsyncIterable<O> | Iterable<PromiseLike<O> | O>, inner: AsyncIterable<I> | Iterable<PromiseLike<I> | I>, outerKeySelector: (element: O) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: O | undefined, inner: I | undefined) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncIterable<R> { assert.mustBeAsyncOrSyncIterableObject(outer, "outer"); assert.mustBeAsyncOrSyncIterableObject(inner, "inner"); assert.mustBeFunction(outerKeySelector, "outerKeySelector"); assert.mustBeFunction(innerKeySelector, "innerKeySelector"); assert.mustBeFunction(resultSelector, "resultSelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return new AsyncFullJoinIterable(outer, inner, outerKeySelector, innerKeySelector, resultSelector, keyEqualer); } class AsyncZipIterable<T, U, R> implements AsyncIterable<R> { private _left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>; private _selector: (left: T, right: U) => PromiseLike<R> | R; constructor(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, selector: (left: T, right: U) => PromiseLike<R> | R) { this._left = left; this._right = right; this._selector = selector; } async *[Symbol.asyncIterator](): AsyncIterator<R> { const selector = this._selector; const leftIterator: AsyncIterator<T> = toAsyncIterable(this._left)[Symbol.asyncIterator](); let leftDone: boolean | undefined = false; let leftValue: T; try { const rightIterator: AsyncIterator<U> = toAsyncIterable(this._right)[Symbol.asyncIterator](); let rightDone: boolean | undefined = false; let rightValue: U; try { for (;;) { ({ done: leftDone, value: leftValue } = await leftIterator.next()); ({ done: rightDone, value: rightValue } = await rightIterator.next()); if (leftDone || rightDone) break; yield selector(leftValue, rightValue); } } finally { if (!rightDone) await rightIterator.return?.(); } } finally { if (!leftDone) await leftIterator.return?.(); } } } /** * Creates a subquery that combines two [[AsyncQueryable]] objects by combining elements * in tuples. * * @param left An [[AsyncQueryable]] object. * @param right An [[AsyncQueryable]] object. * @category Join */ export function zipAsync<T, U>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>): AsyncIterable<[T, U]>; /** * Creates a subquery that combines two [[AsyncQueryable]] objects by combining elements * using the supplied callback. * * @param left An [[AsyncQueryable]] object. * @param right An [[AsyncQueryable]] object. * @param selector A callback used to combine two elements. * @category Join */ export function zipAsync<T, U, R>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, selector: (left: T, right: U) => PromiseLike<R> | R): AsyncIterable<R>; export function zipAsync<T, U, R>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, selector: (left: T, right: U) => PromiseLike<[T, U] | R> | [T, U] | R = tuple): AsyncIterable<[T, U] | R> { assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeFunction(selector, "selector"); return new AsyncZipIterable(left, right, selector); }
the_stack
import { util } from "protobufjs/minimal"; import { BatchingLayerMessage } from "../../generated/proto_compiled"; import { Collab, CollabEvent, CollabEventsRecord, InitToken, ICollabParent, MessageMeta, Pre, Message, serializeMessage, } from "../core"; import { Optional } from "../util"; import { BatchingStrategy } from "./batching_strategy"; export interface BatchingLayerEventsRecord extends CollabEventsRecord { /** * Emitted each time the child's state is changed * (including changes to its descendants) and * is in a reasonable user-facing state * (so not in the middle of a transaction). * * A [[Runtime]] using this [[BatchingLayer]] should listen * on this event and emit its own "Change" events in response. * * More specifically, a "Change" event is emitted: * - For messages sent by the local child, once per * transaction, in a microtask scheduled after the first * sent message. Note that this may happen more than once per * batch or after the batch is committed, if it is * committed synchronously with the transaction. * - For received messages, once per batch. */ Change: CollabEvent; /** * Emitted when a batch is pending, i.e., there is * a complete transaction waiting to be sent. * [[commitBatch]] can be be called to send it immediately, * or you (or the [[BatchingStrategy]]) can wait to send it later. * * Specifically, this event is emitted in a microtask after * the child sends a message, unless that message's batch * is already committed by the time of the microtask. */ BatchPending: CollabEvent; /** * Event for debugging and testing purposes only. * Emitted each time a message is sent by the child, * at the end of [[BatchingLayer.childSend]]. By calling [[BatchingLayer.commitBatch]] * each time this event is emitted, you can effectively * disable batching. Doing so in a real application is * not recommended because it will break up transactions. */ DebugSend: CollabEvent; } /** * Info about a pending batch. * * The sent messagePath's are interpreted as paths to the root in * a tree (last element is closest to the root), with the elements labelling * edges. We apply suffix compression (prefix compression but * reversed) to these paths. * * Edge labels are compared using ===, so you will only get * reasonable equality for (1) strings and (2) Uint8Arrays * that are stored by the sender and reused (e.g. collection * elements stored in serialized form). * * Vertices are labelled with numbers sequentially. The root * (messagePath = []) is 0. */ interface BatchInfo { /** * For each edge, maps from (child vertex - 1) to its label * and parent vertex. */ edges: { label: Message; parent: number }[]; /** * Maps each vertex with at least one child to a map * from edge labels to the corresponding child. */ children: Map<number, Map<Message, number>>; /** * The vertices corresponding to actual complete messagePaths, * in order of sending. */ messages: number[]; /** * Type guard. */ isBatchInfo: true; } function isBatchInfo( pendingBatch: BatchInfo | Message[] ): pendingBatch is BatchInfo { return (<BatchInfo>pendingBatch).isBatchInfo === true; } /** * Collab that batches message sent by its descendants. * * Batching serves a few purposes: * - Enforces transactional * behavior ([transactions docs](../../transactions.md)): * messages sent in the same event loop iteration are * delivered atomically on each replica. * - Reduce the number and size of messages sent on the * network, by delivering multiple transactions together * with some compression applied. Specifically, path * prefix compression is applied to sent `messagePath`s, * so in particular, multiple messages from the same [[Collab]] * end up only sending that [[Collab]]'s name path once. * - Rate-limit the rate of message sending. * * Typically, [[BatchingLayer]] should either be the * root Collab, or the sole child of the root, or the * sole child of a sole child, etc. Otherwise, * the current [[MessageMeta]] may change during a batch, * causing a sending replica to see different [[MessageMeta]]'s * than recipients. * * See the note on [[save]] about calling [[commitBatch]] * before saving---ideally before saving starts at the * [[Runtime]]/root level, to prevent confusion due to sending * messages partway through an ancestor's save. * * As an optimization, descendants of a [[BatchingLayer]] should reuse * [[Uint8Array]] objects (treated as immutable) when sending * identical messages, possibly within the same batch. That * allows [[BatchingLayer]] to deduplicate the messages. */ export class BatchingLayer extends Collab<BatchingLayerEventsRecord> implements ICollabParent { private child!: Collab; /** * The first message is stored as a plain Message[]; if another message * appears, it is converted to BatchInfo. null when no send batch is pending. */ private pendingBatch: BatchInfo | Message[] | null = null; constructor( initToken: InitToken, private batchingStrategy: BatchingStrategy ) { super(initToken); this.batchingStrategy.start(this); } setChild<C extends Collab>(preChild: Pre<C>): C { const child = preChild(new InitToken("", this)); this.child = child; return child; } /** * Replaces the current [[BatchingStrategy]] with * `batchingStrategy`. * * @param batchingStrategy [description] */ setBatchingStrategy(batchingStrategy: BatchingStrategy): void { this.batchingStrategy.stop(); this.batchingStrategy = batchingStrategy; this.batchingStrategy.start(this); } isBatchPending(): boolean { return this.pendingBatch !== null; } /** * [[MessageMeta]] extra metadata that gives the number of messages * in the current batch. */ static BATCH_SIZE_KEY = Symbol(); private inChildReceive = false; private batchEventPending = false; childSend(child: Collab<CollabEventsRecord>, messagePath: Message[]): void { if (child !== this.child) { throw new Error(`childSend called by non-child: ${child}`); } // Local echo. if (this.inChildReceive) { // send inside a receive call; not allowed (might break things). throw new Error( "BatchingLayer.childSend called during another message's receive;" + " did you try to perform an operation in an event handler?" ); } const meta = this.getMessageMeta(); this.inChildReceive = true; try { // Need to copy messagePath since receive mutates it but // we still need to store it. this.child.receive(messagePath.slice(), meta); } finally { this.inChildReceive = false; } if (this.pendingBatch === null) { this.pendingBatch = messagePath; } else if (isBatchInfo(this.pendingBatch)) { this.addToPendingBatch(messagePath); } else { // pendingBatch is a single messagePath. Creating a new BatchInfo // with both messages. const previousMessagePath = this.pendingBatch; this.pendingBatch = { edges: [], children: new Map(), messages: [], isBatchInfo: true, }; this.addToPendingBatch(previousMessagePath); this.addToPendingBatch(messagePath); } // Schedule a BatchPending event as a microtask, if there // is not one pending already. // This notifies BatchingStrategy and also emits a Change event. if (!this.batchEventPending) { this.batchEventPending = true; void Promise.resolve().then(() => { this.batchEventPending = false; if (this.isBatchPending()) { // Only emit if the batch is still pending. this.emit("BatchPending", { meta }); } this.emit("Change", { meta }); }); } this.emit("DebugSend", { meta }, false); } private getMessageMeta(): MessageMeta { return ( <MessageMeta>this.getContext(MessageMeta.NEXT_MESSAGE_META) ?? { sender: this.runtime.replicaID, isLocalEcho: true, } ); } /** * Assumes this.pendingBatch has type BatchInfo. */ private addToPendingBatch(messagePath: Message[]) { const pendingBatch = <BatchInfo>this.pendingBatch; // Find the vertex corresponding to messagePathResolved, creating // it if necessary. let vertex = 0; for (let i = messagePath.length - 1; i >= 0; i--) { const message = messagePath[i]; let nextVertex: number | undefined = undefined; let vertexChildren = pendingBatch.children.get(vertex); if (vertexChildren !== undefined) { nextVertex = vertexChildren.get(message); } else { vertexChildren = new Map(); pendingBatch.children.set(vertex, vertexChildren); } if (nextVertex === undefined) { // Create a new vertex for it. nextVertex = pendingBatch.edges.length + 1; pendingBatch.edges.push({ label: message, parent: vertex }); vertexChildren.set(message, nextVertex); } vertex = nextVertex; } pendingBatch.messages.push(vertex); } /** * [commitBatch description] * @return [description] */ commitBatch() { if (this.pendingBatch === null) return; const batch = this.pendingBatch; // Clear this.pendingBatch now so that this.isBatchPending() // is false when we call send at the end of this method, // in case someone consults it during send. this.pendingBatch = null; // Serialize the batch and send it. let batchMessage: BatchingLayerMessage; if (isBatchInfo(batch)) { // We only need to serialize batch.edges and batch.messages; // batch.children is redundant with batch.edges. // Note that we serialize the individual labels and store // them back in batch.edges[i].label, so that can later // be assumed to have type Uint8Array | string. const edgeLabelLengths = new Array<number>(batch.edges.length); let totalLength = 0; const edgeParents = new Array<number>(batch.edges.length); for (let i = 0; i < batch.edges.length; i++) { const label = serializeMessage(batch.edges[i].label); batch.edges[i].label = label; // Store serialized form. if (typeof label === "string") { const length = util.utf8.length(label); edgeLabelLengths[i] = ~length; totalLength += length; } else { edgeLabelLengths[i] = label.length; totalLength += label.length; } edgeParents[i] = batch.edges[i].parent; } const edgeLabelsPacked = new Uint8Array(totalLength); let offset = 0; for (let i = 0; i < batch.edges.length; i++) { const label = batch.edges[i].label; if (typeof label === "string") { util.utf8.write(label, edgeLabelsPacked, offset); offset += ~edgeLabelLengths[i]; } else { // Use assumption that label is already serialized, // hence must be Uint8Array here. edgeLabelsPacked.set(<Uint8Array>label, offset); offset += edgeLabelLengths[i]; } } batchMessage = BatchingLayerMessage.create({ edgeLabelsPacked, edgeLabelLengths, edgeParents, messages: batch.messages, }); } else { // batch is a single messagePath. Store it using edgeLabelsPacked // and edgeLabelLengths like before, but just in order, and leave // out edgeParents & messages. const messageLengths = new Array<number>(batch.length); let totalLength = 0; for (let i = 0; i < batch.length; i++) { const message = serializeMessage(batch[i]); batch[i] = message; // Store serialized form. if (typeof message === "string") { const length = util.utf8.length(message); messageLengths[i] = ~length; totalLength += length; } else { messageLengths[i] = message.length; totalLength += message.length; } } const messagesPacked = new Uint8Array(totalLength); let offset = 0; for (let i = 0; i < batch.length; i++) { const message = batch[i]; if (typeof message === "string") { util.utf8.write(message, messagesPacked, offset); offset += ~messageLengths[i]; } else { // Use assumption that message is already serialized, // hence must be Uint8Array here. messagesPacked.set(<Uint8Array>message, offset); offset += messageLengths[i]; } } batchMessage = BatchingLayerMessage.create({ edgeLabelsPacked: messagesPacked, edgeLabelLengths: messageLengths, }); } const serialized = BatchingLayerMessage.encode(batchMessage).finish(); this.send([serialized]); } /** * Added context: [[MessageMeta.NEXT_MESSAGE_META]]. */ getAddedContext(key: symbol): unknown { if (key === MessageMeta.NEXT_MESSAGE_META) { return this.getMessageMeta(); } return undefined; } receive(messagePath: Message[], meta: MessageMeta): void { // We do our own local echo. if (meta.isLocalEcho) return; if (messagePath.length !== 1) { throw new Error( `messagePath.length is not 1: ${JSON.stringify(messagePath)}` ); } const deserialized = BatchingLayerMessage.decode( <Uint8Array>messagePath[0] ); const edgeLabels = new Array<string | Uint8Array>( deserialized.edgeLabelLengths.length ); let offset = 0; for (let i = 0; i < edgeLabels.length; i++) { const signedLengthI = deserialized.edgeLabelLengths[i]; if (signedLengthI < 0) { // string, actual length is ~signedLengthI. const lengthI = ~signedLengthI; edgeLabels[i] = util.utf8.read( deserialized.edgeLabelsPacked, offset, offset + lengthI ); offset += lengthI; } else { // Uint8Array, actual length is signedLengthI. edgeLabels[i] = new Uint8Array( deserialized.edgeLabelsPacked.buffer, offset + deserialized.edgeLabelsPacked.byteOffset, signedLengthI ); offset += signedLengthI; } } if (deserialized.messages.length === 0) { // Single message case. edgeLabels is the literal single message. meta[BatchingLayer.BATCH_SIZE_KEY] = 1; this.deliver(edgeLabels, meta); } else { // BatchInfo case. Use full deserialized message. meta[BatchingLayer.BATCH_SIZE_KEY] = deserialized.messages.length; for (const messageVertex of deserialized.messages) { // Reconstruct vertex's messagePath. const childMessagePath: (Uint8Array | string)[] = []; let vertex = messageVertex; while (vertex !== 0) { childMessagePath.push(edgeLabels[vertex - 1]); vertex = deserialized.edgeParents[vertex - 1]; } this.deliver(childMessagePath, meta); } } this.emit("Change", { meta }); } private deliver( childMessagePath: (Uint8Array | string)[], meta: MessageMeta ): void { if (this.inChildReceive) { // nested receive calls; not allowed (might break things). throw new Error( "BatchingLayer.receive called during another message's receive;" + " did you try to deliver a message in an event handler?" ); } this.inChildReceive = true; try { this.child.receive(childMessagePath, meta); } catch (err) { // Don't let the error block other messages' delivery // or affect the deliverer, // but still make it print // its error like it was unhandled. // Note we know the message is not a local echo. void Promise.resolve().then(() => { throw err; }); } finally { this.inChildReceive = false; } } /** * Usage note: there must not be a pending batch when this * is called. I.e., you should call [[commitBatch]] first, * then call `save` before any new messages might get queued. * * Saving with a pending batch does not make sense because * the pending messages are authored by the current replica, * not some future replica who might load this state * (possibly none or several concurrently). We can't just * ignore the pending batch or wait to commit it until * after saving, since the BatchingLayer's descendants * have already processed the pending messages, hence * their save state will reflect those messages. * * @throws is [[isBatchPending]]() */ save(): Uint8Array { // Need to flush before saving. if (this.isBatchPending()) { throw new Error( "Cannot save during pending batch (call commitBatch() first)" ); } return this.child.save(); } load(saveData: Optional<Uint8Array>): void { this.child.load(saveData); } getDescendant(namePath: string[]): Collab | undefined { if (namePath.length === 0) return this; if (namePath[namePath.length - 1] !== "") { throw new Error("Unrecognized child: " + namePath[namePath.length - 1]); } namePath.length--; return this.child.getDescendant(namePath); } canGC(): boolean { return !this.isBatchPending() && this.child.canGC(); } }
the_stack
import * as PrismaSchemaDSL from "prisma-schema-dsl"; import { camelCase } from "camel-case"; import { pascalCase } from "pascal-case"; import { types } from "@amplication/data"; import countBy from "lodash.countby"; import { Entity, EntityField, EnumDataType, LookupResolvedProperties, } from "../../types"; import { getEnumFields } from "../../util/entity"; export const CLIENT_GENERATOR = PrismaSchemaDSL.createGenerator( "client", "prisma-client-js" ); export const DATA_SOURCE = { name: "postgres", provider: PrismaSchemaDSL.DataSourceProvider.PostgreSQL, url: new PrismaSchemaDSL.DataSourceURLEnv("POSTGRESQL_URL"), }; export const CUID_CALL_EXPRESSION = new PrismaSchemaDSL.CallExpression( PrismaSchemaDSL.CUID ); export const NOW_CALL_EXPRESSION = new PrismaSchemaDSL.CallExpression( PrismaSchemaDSL.NOW ); export async function createPrismaSchema(entities: Entity[]): Promise<string> { const fieldNamesCount = countBy( entities.flatMap((entity) => entity.fields), "name" ); const models = entities.map((entity) => createPrismaModel(entity, fieldNamesCount) ); const enums = entities.flatMap((entity) => { const enumFields = getEnumFields(entity); return enumFields.map((field) => createPrismaEnum(field, entity)); }); const schema = PrismaSchemaDSL.createSchema(models, enums, DATA_SOURCE, [ CLIENT_GENERATOR, ]); return PrismaSchemaDSL.print(schema); } export function createPrismaEnum( field: EntityField, entity: Entity ): PrismaSchemaDSL.Enum { const { options } = field.properties as types.OptionSet; return PrismaSchemaDSL.createEnum( createEnumName(field, entity), options.map((option) => option.value) ); } export function createEnumName(field: EntityField, entity: Entity): string { return `Enum${pascalCase(entity.name)}${pascalCase(field.name)}`; } export function createPrismaModel( entity: Entity, fieldNamesCount: Record<string, number> ): PrismaSchemaDSL.Model { return PrismaSchemaDSL.createModel( entity.name, entity.fields.flatMap((field) => createPrismaFields(field, entity, fieldNamesCount) ) ); } export function createPrismaFields( field: EntityField, entity: Entity, fieldNamesCount: Record<string, number> = {} ): | [PrismaSchemaDSL.ScalarField] | [PrismaSchemaDSL.ObjectField] | [PrismaSchemaDSL.ObjectField, PrismaSchemaDSL.ScalarField] { const { dataType, name, properties } = field; switch (dataType) { case EnumDataType.SingleLineText: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.String, false, field.required, field.unique ), ]; } case EnumDataType.MultiLineText: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.String, false, field.required, field.unique ), ]; } case EnumDataType.Email: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.String, false, field.required, field.unique ), ]; } case EnumDataType.WholeNumber: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.Int, false, field.required, field.unique ), ]; } case EnumDataType.DateTime: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.DateTime, false, field.required, field.unique ), ]; } case EnumDataType.DecimalNumber: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.Float, false, field.required, field.unique ), ]; } case EnumDataType.Boolean: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.Boolean, false, field.required, field.unique ), ]; } case EnumDataType.GeographicLocation: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.String, false, field.required, field.unique ), ]; } case EnumDataType.Json: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.Json, false, field.required, field.unique ), ]; } case EnumDataType.Lookup: { const { relatedEntity, relatedField, allowMultipleSelection, isOneToOneWithoutForeignKey, } = properties as LookupResolvedProperties; const hasAnotherRelation = entity.fields.some( (entityField) => entityField.id !== field.id && entityField.dataType === EnumDataType.Lookup && entityField.properties.relatedEntity.name === relatedEntity.name ); const relationName = !hasAnotherRelation ? null : createRelationName( entity, field, relatedEntity, relatedField, fieldNamesCount[field.name] === 1, fieldNamesCount[relatedField.name] === 1 ); if (allowMultipleSelection || isOneToOneWithoutForeignKey) { return [ PrismaSchemaDSL.createObjectField( name, relatedEntity.name, !isOneToOneWithoutForeignKey, true, relationName ), ]; } const scalarRelationFieldName = `${name}Id`; return [ PrismaSchemaDSL.createObjectField( name, relatedEntity.name, false, field.required, relationName, [scalarRelationFieldName], [ "id", ] /**@todo: calculate the referenced field on the related entity (currently it is always 'id') */ ), // Prisma Scalar Relation Field PrismaSchemaDSL.createScalarField( scalarRelationFieldName, PrismaSchemaDSL.ScalarType.String, false, field.required, field.unique ), ]; } case EnumDataType.MultiSelectOptionSet: { return [ PrismaSchemaDSL.createObjectField( name, createEnumName(field, entity), true, true ), ]; } case EnumDataType.OptionSet: { return [ PrismaSchemaDSL.createObjectField( name, createEnumName(field, entity), false, field.required ), ]; } case EnumDataType.Id: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.String, false, field.required, false, true, false, CUID_CALL_EXPRESSION ), ]; } case EnumDataType.CreatedAt: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.DateTime, false, field.required, false, false, false, NOW_CALL_EXPRESSION ), ]; } case EnumDataType.UpdatedAt: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.DateTime, false, field.required, false, false, true ), ]; } case EnumDataType.Roles: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.String, true, true ), ]; } case EnumDataType.Username: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.String, false, field.required, true ), ]; } case EnumDataType.Password: { return [ PrismaSchemaDSL.createScalarField( name, PrismaSchemaDSL.ScalarType.String, false, field.required ), ]; } default: { throw new Error(`Unfamiliar data type: ${dataType}`); } } } /** * Creates Prisma Schema relation name according to the names of the entity, * field, relatedEntity and relatedField. * This function is assumed to be used when a relation name is necessary * @param entity * @param field * @param relatedEntity * @param relatedField * @param fieldHasUniqueName * @returns Prisma Schema relation name * @todo use unique name of one of the fields deterministically (VIPCustomers or VIPOrganizations) */ export function createRelationName( entity: Entity, field: EntityField, relatedEntity: Entity, relatedField: EntityField, fieldHasUniqueName: boolean, relatedFieldHasUniqueName: boolean ): string { const relatedEntityNames = [ relatedEntity.name, relatedEntity.pluralDisplayName, ]; const entityNames = [entity.name, entity.pluralDisplayName]; const matchingRelatedEntityName = relatedEntityNames.find( (name) => field.name === camelCase(name) ); const matchingEntityName = entityNames.find( (name) => relatedField.name === camelCase(name) ); if (matchingRelatedEntityName && matchingEntityName) { const names = [matchingRelatedEntityName, matchingEntityName]; // Sort names for deterministic results regardless of entity and related order names.sort(); return names.join("On"); } if (fieldHasUniqueName || relatedFieldHasUniqueName) { const names = []; if (fieldHasUniqueName) { names.push(field.name); } if (relatedFieldHasUniqueName) { names.push(relatedField.name); } // Sort names for deterministic results regardless of entity and related order names.sort(); return names[0]; } const entityAndField = [entity.name, field.name].join(" "); const relatedEntityAndField = [relatedEntity.name, relatedField.name].join( " " ); const parts = [entityAndField, relatedEntityAndField]; // Sort parts for deterministic results regardless of entity and related order parts.sort(); return pascalCase(parts.join(" ")); }
the_stack
import { defaultConfig, getCurrTime } from './Utils'; import { StorageCache } from './StorageCache'; import { ICache, CacheConfig, CacheItem, CacheItemOptions } from './types'; import { ConsoleLogger as Logger } from '@aws-amplify/core'; const logger = new Logger('Cache'); /** * Customized storage based on the SessionStorage or LocalStorage with LRU implemented */ export class BrowserStorageCacheClass extends StorageCache implements ICache { /** * initialize the cache * @param config - the configuration of the cache */ constructor(config?: CacheConfig) { const cacheConfig = config ? Object.assign({}, defaultConfig, config) : defaultConfig; super(cacheConfig); this.config.storage = cacheConfig.storage; this.getItem = this.getItem.bind(this); this.setItem = this.setItem.bind(this); this.removeItem = this.removeItem.bind(this); } /** * decrease current size of the cache * * @private * @param amount - the amount of the cache size which needs to be decreased */ private _decreaseCurSizeInBytes(amount: number): void { const curSize: number = this.getCacheCurSize(); this.config.storage.setItem( this.cacheCurSizeKey, (curSize - amount).toString() ); } /** * increase current size of the cache * * @private * @param amount - the amount of the cache szie which need to be increased */ private _increaseCurSizeInBytes(amount: number): void { const curSize: number = this.getCacheCurSize(); this.config.storage.setItem( this.cacheCurSizeKey, (curSize + amount).toString() ); } /** * update the visited time if item has been visited * * @private * @param item - the item which need to be refreshed * @param prefixedKey - the key of the item * * @return the refreshed item */ private _refreshItem(item: CacheItem, prefixedKey: string): CacheItem { item.visitedTime = getCurrTime(); this.config.storage.setItem(prefixedKey, JSON.stringify(item)); return item; } /** * check wether item is expired * * @private * @param key - the key of the item * * @return true if the item is expired. */ private _isExpired(key: string): boolean { const text: string | null = this.config.storage.getItem(key); const item: CacheItem = JSON.parse(text); if (getCurrTime() >= item.expires) { return true; } return false; } /** * delete item from cache * * @private * @param prefixedKey - the key of the item * @param size - optional, the byte size of the item */ private _removeItem(prefixedKey: string, size?: number): void { const itemSize: number = size ? size : JSON.parse(this.config.storage.getItem(prefixedKey)).byteSize; this._decreaseCurSizeInBytes(itemSize); // remove the cache item this.config.storage.removeItem(prefixedKey); } /** * put item into cache * * @private * @param prefixedKey - the key of the item * @param itemData - the value of the item * @param itemSizeInBytes - the byte size of the item */ private _setItem(prefixedKey: string, item: CacheItem): void { // update the cache size this._increaseCurSizeInBytes(item.byteSize); try { this.config.storage.setItem(prefixedKey, JSON.stringify(item)); } catch (setItemErr) { // if failed, we need to rollback the cache size this._decreaseCurSizeInBytes(item.byteSize); logger.error(`Failed to set item ${setItemErr}`); } } /** * total space needed when poping out items * * @private * @param itemSize * * @return total space needed */ private _sizeToPop(itemSize: number): number { const spaceItemNeed = this.getCacheCurSize() + itemSize - this.config.capacityInBytes; const cacheThresholdSpace = (1 - this.config.warningThreshold) * this.config.capacityInBytes; return spaceItemNeed > cacheThresholdSpace ? spaceItemNeed : cacheThresholdSpace; } /** * see whether cache is full * * @private * @param itemSize * * @return true if cache is full */ private _isCacheFull(itemSize: number): boolean { return itemSize + this.getCacheCurSize() > this.config.capacityInBytes; } /** * scan the storage and find out all the keys owned by this cache * also clean the expired keys while scanning * * @private * * @return array of keys */ private _findValidKeys(): string[] { const keys: string[] = []; const keyInCache: string[] = []; // get all keys in Storage for (let i = 0; i < this.config.storage.length; i += 1) { keyInCache.push(this.config.storage.key(i)); } // find those items which belong to our cache and also clean those expired items for (let i = 0; i < keyInCache.length; i += 1) { const key: string = keyInCache[i]; if ( key.indexOf(this.config.keyPrefix) === 0 && key !== this.cacheCurSizeKey ) { if (this._isExpired(key)) { this._removeItem(key); } else { keys.push(key); } } } return keys; } /** * get all the items we have, sort them by their priority, * if priority is same, sort them by their last visited time * pop out items from the low priority (5 is the lowest) * * @private * @param keys - all the keys in this cache * @param sizeToPop - the total size of the items which needed to be poped out */ private _popOutItems(keys: string[], sizeToPop: number): void { const items: CacheItem[] = []; let remainedSize: number = sizeToPop; // get the items from Storage for (let i = 0; i < keys.length; i += 1) { const val: string | null = this.config.storage.getItem(keys[i]); if (val != null) { const item: CacheItem = JSON.parse(val); items.push(item); } } // first compare priority // then compare visited time items.sort((a, b) => { if (a.priority > b.priority) { return -1; } else if (a.priority < b.priority) { return 1; } else { if (a.visitedTime < b.visitedTime) { return -1; } else return 1; } }); for (let i = 0; i < items.length; i += 1) { // pop out items until we have enough room for new item this._removeItem(items[i].key, items[i].byteSize); remainedSize -= items[i].byteSize; if (remainedSize <= 0) { return; } } } /** * Set item into cache. You can put number, string, boolean or object. * The cache will first check whether has the same key. * If it has, it will delete the old item and then put the new item in * The cache will pop out items if it is full * You can specify the cache item options. The cache will abort and output a warning: * If the key is invalid * If the size of the item exceeds itemMaxSize. * If the value is undefined * If incorrect cache item configuration * If error happened with browser storage * * @param key - the key of the item * @param value - the value of the item * @param {Object} [options] - optional, the specified meta-data */ public setItem( key: string, value: object | number | string | boolean, options?: CacheItemOptions ): void { logger.log( `Set item: key is ${key}, value is ${value} with options: ${options}` ); const prefixedKey: string = this.config.keyPrefix + key; // invalid keys if ( prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey ) { logger.warn(`Invalid key: should not be empty or 'CurSize'`); return; } if (typeof value === 'undefined') { logger.warn(`The value of item should not be undefined!`); return; } const cacheItemOptions: CacheItemOptions = { priority: options && options.priority !== undefined ? options.priority : this.config.defaultPriority, expires: options && options.expires !== undefined ? options.expires : this.config.defaultTTL + getCurrTime(), }; if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) { logger.warn( `Invalid parameter: priority due to out or range. It should be within 1 and 5.` ); return; } const item: CacheItem = this.fillCacheItem( prefixedKey, value, cacheItemOptions ); // check wether this item is too big; if (item.byteSize > this.config.itemMaxSize) { logger.warn( `Item with key: ${key} you are trying to put into is too big!` ); return; } try { // first look into the storage, if it exists, delete it. const val: string | null = this.config.storage.getItem(prefixedKey); if (val) { this._removeItem(prefixedKey, JSON.parse(val).byteSize); } // check whether the cache is full if (this._isCacheFull(item.byteSize)) { const validKeys: string[] = this._findValidKeys(); // check again and then pop out items if (this._isCacheFull(item.byteSize)) { const sizeToPop: number = this._sizeToPop(item.byteSize); this._popOutItems(validKeys, sizeToPop); } } // put item in the cache // may failed due to storage full this._setItem(prefixedKey, item); } catch (e) { logger.warn(`setItem failed! ${e}`); } } /** * Get item from cache. It will return null if item doesn’t exist or it has been expired. * If you specified callback function in the options, * then the function will be executed if no such item in the cache * and finally put the return value into cache. * Please make sure the callback function will return the value you want to put into the cache. * The cache will abort output a warning: * If the key is invalid * If error happened with browser storage * * @param key - the key of the item * @param {Object} [options] - the options of callback function * * @return - return the value of the item */ public getItem(key: string, options?: CacheItemOptions): any { logger.log(`Get item: key is ${key} with options ${options}`); let ret: string | null = null; const prefixedKey: string = this.config.keyPrefix + key; if ( prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey ) { logger.warn(`Invalid key: should not be empty or 'CurSize'`); return null; } try { ret = this.config.storage.getItem(prefixedKey); if (ret != null) { if (this._isExpired(prefixedKey)) { // if expired, remove that item and return null this._removeItem(prefixedKey, JSON.parse(ret).byteSize); ret = null; } else { // if not expired, great, return the value and refresh it let item: CacheItem = JSON.parse(ret); item = this._refreshItem(item, prefixedKey); return item.data; } } if (options && options.callback !== undefined) { const val: object | string | number | boolean = options.callback(); if (val !== null) { this.setItem(key, val, options); } return val; } return null; } catch (e) { logger.warn(`getItem failed! ${e}`); return null; } } /** * remove item from the cache * The cache will abort output a warning: * If error happened with browser storage * @param key - the key of the item */ public removeItem(key: string): void { logger.log(`Remove item: key is ${key}`); const prefixedKey: string = this.config.keyPrefix + key; if ( prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey ) { return; } try { const val: string | null = this.config.storage.getItem(prefixedKey); if (val) { this._removeItem(prefixedKey, JSON.parse(val).byteSize); } } catch (e) { logger.warn(`removeItem failed! ${e}`); } } /** * clear the entire cache * The cache will abort output a warning: * If error happened with browser storage */ public clear(): void { logger.log(`Clear Cache`); const keysToRemove: string[] = []; for (let i = 0; i < this.config.storage.length; i += 1) { const key = this.config.storage.key(i); if (key.indexOf(this.config.keyPrefix) === 0) { keysToRemove.push(key); } } try { for (let i = 0; i < keysToRemove.length; i += 1) { this.config.storage.removeItem(keysToRemove[i]); } } catch (e) { logger.warn(`clear failed! ${e}`); } } /** * Return all the keys in the cache. * * @return - all keys in the cache */ public getAllKeys(): string[] { const keys: string[] = []; for (let i = 0; i < this.config.storage.length; i += 1) { const key = this.config.storage.key(i); if ( key.indexOf(this.config.keyPrefix) === 0 && key !== this.cacheCurSizeKey ) { keys.push(key.substring(this.config.keyPrefix.length)); } } return keys; } /** * return the current size of the cache * * @return - current size of the cache */ public getCacheCurSize(): number { let ret: string | null = this.config.storage.getItem(this.cacheCurSizeKey); if (!ret) { this.config.storage.setItem(this.cacheCurSizeKey, '0'); ret = '0'; } return Number(ret); } /** * Return a new instance of cache with customized configuration. * @param config - the customized configuration * * @return - new instance of Cache */ public createInstance(config: CacheConfig): ICache { if (!config.keyPrefix || config.keyPrefix === defaultConfig.keyPrefix) { logger.error('invalid keyPrefix, setting keyPrefix with timeStamp'); config.keyPrefix = getCurrTime.toString(); } return new BrowserStorageCacheClass(config); } } export const BrowserStorageCache: ICache = new BrowserStorageCacheClass(); /** * @deprecated use named import */ export default BrowserStorageCache;
the_stack
module android.widget{ import Gravity = android.view.Gravity; import View = android.view.View; import MeasureSpec = View.MeasureSpec; import ViewGroup = android.view.ViewGroup; import Drawable = android.graphics.drawable.Drawable; import Canvas = android.graphics.Canvas; import Rect = android.graphics.Rect; import Context = android.content.Context; export class LinearLayout extends ViewGroup{ static HORIZONTAL = 0; static VERTICAL = 1; /** * Don't show any dividers. */ static SHOW_DIVIDER_NONE = 0; /** * Show a divider at the beginning of the group. */ static SHOW_DIVIDER_BEGINNING = 1; /** * Show dividers between each item in the group. */ static SHOW_DIVIDER_MIDDLE = 2; /** * Show a divider at the end of the group. */ static SHOW_DIVIDER_END = 4; /** * Whether the children of this layout are baseline aligned. Only applicable * if {@link #mOrientation} is horizontal. */ private mBaselineAligned = true; /** * If this layout is part of another layout that is baseline aligned, * use the child at this index as the baseline. * * Note: this is orthogonal to {@link #mBaselineAligned}, which is concerned * with whether the children of this layout are baseline aligned. */ private mBaselineAlignedChildIndex = -1; /** * The additional offset to the child's baseline. * We'll calculate the baseline of this layout as we measure vertically; for * horizontal linear layouts, the offset of 0 is appropriate. */ private mBaselineChildTop = 0; private mOrientation = 0; private mGravity = Gravity.LEFT | Gravity.TOP; private mTotalLength = 0; private mWeightSum = -1; private mUseLargestChild = false; private mMaxAscent : Array<number>; private mMaxDescent : Array<number>; private static VERTICAL_GRAVITY_COUNT = 4; private static INDEX_CENTER_VERTICAL = 0; private static INDEX_TOP = 1; private static INDEX_BOTTOM = 2; private static INDEX_FILL = 3; private mDivider:Drawable; private mDividerWidth:number = 0; private mDividerHeight:number = 0; private mShowDividers:number = LinearLayout.SHOW_DIVIDER_NONE; private mDividerPadding:number = 0; constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle?:Map<string, string>) { super(context, bindElement, defStyle); const a = context.obtainStyledAttributes(bindElement, defStyle); const orientationS = a.getAttrValue('orientation'); if (orientationS) { const orientation = LinearLayout[orientationS.toUpperCase()]; if (Number.isInteger(orientation)) { this.setOrientation(orientation); } } const gravityS = a.getAttrValue('gravity'); if (gravityS) { this.setGravity(Gravity.parseGravity(gravityS)); } let baselineAligned = a.getBoolean('baselineAligned', true); if (!baselineAligned) { this.setBaselineAligned(baselineAligned); } this.mWeightSum = a.getFloat('weightSum', -1.0); this.mBaselineAlignedChildIndex = a.getInt('baselineAlignedChildIndex', -1); this.mUseLargestChild = a.getBoolean('measureWithLargestChild', false); this.setDividerDrawable(a.getDrawable('divider')); let fieldName = ('SHOW_DIVIDER_' + a.getAttrValue('showDividers')).toUpperCase(); if(Number.isInteger(LinearLayout[fieldName])){ this.mShowDividers = LinearLayout[fieldName]; } this.mDividerPadding = a.getDimensionPixelSize('dividerPadding', 0); a.recycle(); } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('orientation', { setter(v:LinearLayout, value:any, attrBinder:androidui.attr.AttrBinder) { if((value+"").toUpperCase() === 'VERTICAL' || LinearLayout.VERTICAL == value){ v.setOrientation(LinearLayout.VERTICAL); }else if((value+"").toUpperCase() === 'HORIZONTAL' || LinearLayout.HORIZONTAL == value) { v.setOrientation(LinearLayout.HORIZONTAL); } }, getter(v:LinearLayout) { return v.mOrientation; } }).set('gravity', { setter(v:LinearLayout, value:any, attrBinder:androidui.attr.AttrBinder) { v.setGravity(attrBinder.parseGravity(value, v.mGravity)); }, getter(v:LinearLayout) { return v.mGravity; } }).set('baselineAligned', { setter(v:LinearLayout, value:any, attrBinder:androidui.attr.AttrBinder) { if(!attrBinder.parseBoolean(value)) v.setBaselineAligned(false); }, getter(v:LinearLayout) { return v.mBaselineAligned; } }).set('weightSum', { setter(v:LinearLayout, value:any, attrBinder:androidui.attr.AttrBinder) { v.setWeightSum(attrBinder.parseFloat(value, v.mWeightSum)); }, getter(v:LinearLayout) { return v.mWeightSum; } }).set('baselineAlignedChildIndex', { setter(v:LinearLayout, value:any, attrBinder:androidui.attr.AttrBinder) { v.setBaselineAlignedChildIndex(attrBinder.parseInt(value, v.mBaselineAlignedChildIndex)); }, getter(v:LinearLayout) { return v.mBaselineAlignedChildIndex; } }).set('measureWithLargestChild', { setter(v:LinearLayout, value:any, attrBinder:androidui.attr.AttrBinder) { v.setMeasureWithLargestChildEnabled(attrBinder.parseBoolean(value, v.mUseLargestChild)); }, getter(v:LinearLayout) { return v.mUseLargestChild; } }).set('divider', { setter(v:LinearLayout, value:any, attrBinder:androidui.attr.AttrBinder) { v.setDividerDrawable(attrBinder.parseDrawable(value)); }, getter(v:LinearLayout) { return v.mDivider; } }).set('showDividers', { setter(v:LinearLayout, value:any, attrBinder:androidui.attr.AttrBinder) { if (Number.isInteger(parseInt(value))) { this.setShowDividers(parseInt(value)) } else { let fieldName = ('SHOW_DIVIDER_' + value).toUpperCase(); if(Number.isInteger(LinearLayout[fieldName])){ this.setShowDividers(LinearLayout[fieldName]) } } }, getter(v:LinearLayout) { return v.getShowDividers(); } }).set('dividerPadding', { setter(v:LinearLayout, value:any, attrBinder:androidui.attr.AttrBinder) { v.setDividerPadding(attrBinder.parseInt(value, v.mDividerPadding)); }, getter(v:LinearLayout) { return v.getDividerPadding(); } }); } setShowDividers(showDividers:number) { if (showDividers != this.mShowDividers) { this.requestLayout(); } this.mShowDividers = showDividers; } shouldDelayChildPressedState():boolean { return false; } getShowDividers():number { return this.mShowDividers; } getDividerDrawable():Drawable { return this.mDivider; } setDividerDrawable(divider:Drawable) { if (divider == this.mDivider) { return; } this.mDivider = divider; if (divider != null) { this.mDividerWidth = divider.getIntrinsicWidth(); this.mDividerHeight = divider.getIntrinsicHeight(); } else { this.mDividerWidth = 0; this.mDividerHeight = 0; } this.setWillNotDraw(divider == null); this.requestLayout(); } setDividerPadding(padding:number) { this.mDividerPadding = padding; } getDividerPadding() { return this.mDividerPadding; } getDividerWidth() { return this.mDividerWidth; } protected onDraw(canvas:Canvas) { if (this.mDivider == null) { return; } if (this.mOrientation == LinearLayout.VERTICAL) { this.drawDividersVertical(canvas); } else { this.drawDividersHorizontal(canvas); } } drawDividersVertical(canvas:Canvas) { const count = this.getVirtualChildCount(); for (let i = 0; i < count; i++) { const child = this.getVirtualChildAt(i); if (child != null && child.getVisibility() != View.GONE) { if (this.hasDividerBeforeChildAt(i)) { const lp = <LinearLayout.LayoutParams>child.getLayoutParams(); const top = child.getTop() - lp.topMargin - this.mDividerHeight; this.drawHorizontalDivider(canvas, top); } } } if (this.hasDividerBeforeChildAt(count)) { const child = this.getVirtualChildAt(count - 1); let bottom = 0; if (child == null) { bottom = this.getHeight() - this.getPaddingBottom() - this.mDividerHeight; } else { const lp = <LinearLayout.LayoutParams>child.getLayoutParams(); bottom = child.getBottom() + lp.bottomMargin; } this.drawHorizontalDivider(canvas, bottom); } } drawDividersHorizontal(canvas:Canvas) { const count = this.getVirtualChildCount(); const isLayoutRtl = this.isLayoutRtl(); for (let i = 0; i < count; i++) { const child = this.getVirtualChildAt(i); if (child != null && child.getVisibility() != View.GONE) { if (this.hasDividerBeforeChildAt(i)) { const lp = <LinearLayout.LayoutParams>child.getLayoutParams(); let position; if (isLayoutRtl) { position = child.getRight() + lp.rightMargin; } else { position = child.getLeft() - lp.leftMargin - this.mDividerWidth; } this.drawVerticalDivider(canvas, position); } } } if (this.hasDividerBeforeChildAt(count)) { const child = this.getVirtualChildAt(count - 1); let position; if (child == null) { if (isLayoutRtl) { position = this.getPaddingLeft(); } else { position = this.getWidth() - this.getPaddingRight() - this.mDividerWidth; } } else { const lp = <LinearLayout.LayoutParams>child.getLayoutParams(); if (isLayoutRtl) { position = child.getLeft() - lp.leftMargin - this.mDividerWidth; } else { position = child.getRight() + lp.rightMargin; } } this.drawVerticalDivider(canvas, position); } } drawHorizontalDivider(canvas:Canvas, top:number) { this.mDivider.setBounds(this.getPaddingLeft() + this.mDividerPadding, top, this.getWidth() - this.getPaddingRight() - this.mDividerPadding, top + this.mDividerHeight); this.mDivider.draw(canvas); } drawVerticalDivider(canvas:Canvas, left:number) { this.mDivider.setBounds(left, this.getPaddingTop() + this.mDividerPadding, left + this.mDividerWidth, this.getHeight() - this.getPaddingBottom() - this.mDividerPadding); this.mDivider.draw(canvas); } isBaselineAligned():boolean { return this.mBaselineAligned; } setBaselineAligned(baselineAligned:boolean) { this.mBaselineAligned = baselineAligned; } isMeasureWithLargestChildEnabled():boolean { return this.mUseLargestChild; } setMeasureWithLargestChildEnabled(enabled:boolean) { this.mUseLargestChild = enabled; } getBaseline():number { if (this.mBaselineAlignedChildIndex < 0) { return super.getBaseline(); } if (this.getChildCount() <= this.mBaselineAlignedChildIndex) { throw new Error("mBaselineAlignedChildIndex of LinearLayout " + "set to an index that is out of bounds."); } const child = this.getChildAt(this.mBaselineAlignedChildIndex); const childBaseline = child.getBaseline(); if (childBaseline == -1) { if (this.mBaselineAlignedChildIndex == 0) { // this is just the default case, safe to return -1 return -1; } // the user picked an index that points to something that doesn't // know how to calculate its baseline. throw new Error("mBaselineAlignedChildIndex of LinearLayout " + "points to a View that doesn't know how to get its baseline."); } // TODO: This should try to take into account the virtual offsets // (See getNextLocationOffset and getLocationOffset) // We should add to childTop: // sum([getNextLocationOffset(getChildAt(i)) / i < mBaselineAlignedChildIndex]) // and also add: // getLocationOffset(child) let childTop = this.mBaselineChildTop; if (this.mOrientation == LinearLayout.VERTICAL) { const majorGravity = this.mGravity & Gravity.VERTICAL_GRAVITY_MASK; if (majorGravity != Gravity.TOP) { switch (majorGravity) { case Gravity.BOTTOM: childTop = this.mBottom - this.mTop - this.mPaddingBottom - this.mTotalLength; break; case Gravity.CENTER_VERTICAL: childTop += ((this.mBottom - this.mTop - this.mPaddingTop - this.mPaddingBottom) - this.mTotalLength) / 2; break; } } } let lp = <LinearLayout.LayoutParams>child.getLayoutParams(); return childTop + lp.topMargin + childBaseline; } getBaselineAlignedChildIndex():number { return this.mBaselineAlignedChildIndex; } setBaselineAlignedChildIndex(i:number) { if ((i < 0) || (i >= this.getChildCount())) { throw new Error("base aligned child index out " + "of range (0, " + this.getChildCount() + ")"); } this.mBaselineAlignedChildIndex = i; } getVirtualChildAt(index:number) { return this.getChildAt(index); } getVirtualChildCount():number { return this.getChildCount(); } getWeightSum():number { return this.mWeightSum; } setWeightSum(weightSum:number){ this.mWeightSum = Math.max(0, weightSum); } protected onMeasure(widthMeasureSpec, heightMeasureSpec) { if (this.mOrientation == LinearLayout.VERTICAL) { this.measureVertical(widthMeasureSpec, heightMeasureSpec); } else { this.measureHorizontal(widthMeasureSpec, heightMeasureSpec); } } hasDividerBeforeChildAt(childIndex:number) { if (childIndex == 0) { return (this.mShowDividers & LinearLayout.SHOW_DIVIDER_BEGINNING) != 0; } else if (childIndex == this.getChildCount()) { return (this.mShowDividers & LinearLayout.SHOW_DIVIDER_END) != 0; } else if ((this.mShowDividers & LinearLayout.SHOW_DIVIDER_MIDDLE) != 0) { let hasVisibleViewBefore = false; for (let i = childIndex - 1; i >= 0; i--) { if (this.getChildAt(i).getVisibility() != LinearLayout.GONE) { hasVisibleViewBefore = true; break; } } return hasVisibleViewBefore; } return false; } measureVertical(widthMeasureSpec:number, heightMeasureSpec:number) { this.mTotalLength = 0; let maxWidth = 0; let childState = 0; let alternativeMaxWidth = 0; let weightedMaxWidth = 0; let allFillParent = true; let totalWeight = 0; const count = this.getVirtualChildCount(); const widthMode = MeasureSpec.getMode(widthMeasureSpec); const heightMode = MeasureSpec.getMode(heightMeasureSpec); let matchWidth = false; const baselineChildIndex = this.mBaselineAlignedChildIndex; const useLargestChild = this.mUseLargestChild; let largestChildHeight = Number.MIN_SAFE_INTEGER; // See how tall everyone is. Also remember max width. for (let i = 0; i < count; ++i) { const child = this.getVirtualChildAt(i); if (child == null) { this.mTotalLength += this.measureNullChild(i); continue; } if (child.getVisibility() == View.GONE) { i += this.getChildrenSkipCount(child, i); continue; } if (this.hasDividerBeforeChildAt(i)) { this.mTotalLength += this.mDividerHeight; } let lp = <LinearLayout.LayoutParams>child.getLayoutParams(); totalWeight += lp.weight; if (heightMode == MeasureSpec.EXACTLY && lp.height == 0 && lp.weight > 0) { // Optimization: don't bother measuring children who are going to use // leftover space. These views will get measured again down below if // there is any leftover space. const totalLength = this.mTotalLength; this.mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin); } else { let oldHeight = Number.MIN_SAFE_INTEGER; if (lp.height == 0 && lp.weight > 0) { // heightMode is either UNSPECIFIED or AT_MOST, and this // child wanted to stretch to fill available space. // Translate that to WRAP_CONTENT so that it does not end up // with a height of 0 oldHeight = 0; lp.height = LinearLayout.LayoutParams.WRAP_CONTENT; } // Determine how big this child would like to be. If this or // previous children have given a weight, then we allow it to // use all available space (and we will shrink things later // if needed). this.measureChildBeforeLayout( child, i, widthMeasureSpec, 0, heightMeasureSpec, totalWeight == 0 ? this.mTotalLength : 0); if (oldHeight != Number.MIN_SAFE_INTEGER) { lp.height = oldHeight; } const childHeight = child.getMeasuredHeight(); const totalLength = this.mTotalLength; this.mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin + lp.bottomMargin + this.getNextLocationOffset(child)); if (useLargestChild) { largestChildHeight = Math.max(childHeight, largestChildHeight); } } /** * If applicable, compute the additional offset to the child's baseline * we'll need later when asked {@link #getBaseline}. */ if ((baselineChildIndex >= 0) && (baselineChildIndex == i + 1)) { this.mBaselineChildTop = this.mTotalLength; } // if we are trying to use a child index for our baseline, the above // book keeping only works if there are no children above it with // weight. fail fast to aid the developer. if (i < baselineChildIndex && lp.weight > 0) { throw new Error("A child of LinearLayout with index " + "less than mBaselineAlignedChildIndex has weight > 0, which " + "won't work. Either remove the weight, or don't set " + "mBaselineAlignedChildIndex."); } let matchWidthLocally = false; if (widthMode != MeasureSpec.EXACTLY && lp.width == LinearLayout.LayoutParams.MATCH_PARENT) { // The width of the linear layout will scale, and at least one // child said it wanted to match our width. Set a flag // indicating that we need to remeasure at least that view when // we know our width. matchWidth = true; matchWidthLocally = true; } const margin = lp.leftMargin + lp.rightMargin; const measuredWidth = child.getMeasuredWidth() + margin; maxWidth = Math.max(maxWidth, measuredWidth); childState = LinearLayout.combineMeasuredStates(childState, child.getMeasuredState()); allFillParent = allFillParent && lp.width == LinearLayout.LayoutParams.MATCH_PARENT; if (lp.weight > 0) { /* * Widths of weighted Views are bogus if we end up * remeasuring, so keep them separate. */ weightedMaxWidth = Math.max(weightedMaxWidth, matchWidthLocally ? margin : measuredWidth); } else { alternativeMaxWidth = Math.max(alternativeMaxWidth, matchWidthLocally ? margin : measuredWidth); } i += this.getChildrenSkipCount(child, i); } if (this.mTotalLength > 0 && this.hasDividerBeforeChildAt(count)) { this.mTotalLength += this.mDividerHeight; } if (useLargestChild && (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED)) { this.mTotalLength = 0; for (let i = 0; i < count; ++i) { const child = this.getVirtualChildAt(i); if (child == null) { this.mTotalLength += this.measureNullChild(i); continue; } if (child.getVisibility() == View.GONE) { i += this.getChildrenSkipCount(child, i); continue; } const lp = <LinearLayout.LayoutParams>child.getLayoutParams(); // Account for negative margins const totalLength = this.mTotalLength; this.mTotalLength = Math.max(totalLength, totalLength + largestChildHeight + lp.topMargin + lp.bottomMargin + this.getNextLocationOffset(child)); } } // Add in our padding this.mTotalLength += this.mPaddingTop + this.mPaddingBottom; let heightSize = this.mTotalLength; // Check against our minimum height heightSize = Math.max(heightSize, this.getSuggestedMinimumHeight()); // Reconcile our calculated size with the heightMeasureSpec let heightSizeAndState = LinearLayout.resolveSizeAndState(heightSize, heightMeasureSpec, 0); heightSize = heightSizeAndState & View.MEASURED_SIZE_MASK; // Either expand children with weight to take up available space or // shrink them if they extend beyond our current bounds let delta = heightSize - this.mTotalLength; if (delta != 0 && totalWeight > 0) { let weightSum = this.mWeightSum > 0 ? this.mWeightSum : totalWeight; this.mTotalLength = 0; for (let i = 0; i < count; ++i) { const child = this.getVirtualChildAt(i); if (child.getVisibility() == View.GONE) { continue; } let lp = <LinearLayout.LayoutParams>child.getLayoutParams(); let childExtra = lp.weight; if (childExtra > 0) { // Child said it could absorb extra space -- give him his share let share = (childExtra * delta / weightSum); weightSum -= childExtra; delta -= share; const childWidthMeasureSpec = LinearLayout.getChildMeasureSpec(widthMeasureSpec, this.mPaddingLeft + this.mPaddingRight + lp.leftMargin + lp.rightMargin, lp.width); // TODO: Use a field like lp.isMeasured to figure out if this // child has been previously measured if ((lp.height != 0) || (heightMode != MeasureSpec.EXACTLY)) { // child was measured once already above... // base new measurement on stored values let childHeight = child.getMeasuredHeight() + share; if (childHeight < 0) { childHeight = 0; } child.measure(childWidthMeasureSpec, MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY)); } else { // child was skipped in the loop above. // Measure for this first time here child.measure(childWidthMeasureSpec, MeasureSpec.makeMeasureSpec(share > 0 ? share : 0, MeasureSpec.EXACTLY)); } // Child may now not fit in vertical dimension. childState = LinearLayout.combineMeasuredStates(childState, child.getMeasuredState() & (View.MEASURED_STATE_MASK>>View.MEASURED_HEIGHT_STATE_SHIFT)); } const margin = lp.leftMargin + lp.rightMargin; const measuredWidth = child.getMeasuredWidth() + margin; maxWidth = Math.max(maxWidth, measuredWidth); let matchWidthLocally = widthMode != MeasureSpec.EXACTLY && lp.width == LinearLayout.LayoutParams.MATCH_PARENT; alternativeMaxWidth = Math.max(alternativeMaxWidth, matchWidthLocally ? margin : measuredWidth); allFillParent = allFillParent && lp.width == LinearLayout.LayoutParams.MATCH_PARENT; const totalLength = this.mTotalLength; this.mTotalLength = Math.max(totalLength, totalLength + child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin + this.getNextLocationOffset(child)); } // Add in our padding this.mTotalLength += this.mPaddingTop + this.mPaddingBottom; // TODO: Should we recompute the heightSpec based on the new total length? } else { alternativeMaxWidth = Math.max(alternativeMaxWidth, weightedMaxWidth); // We have no limit, so make all weighted views as tall as the largest child. // Children will have already been measured once. if (useLargestChild && heightMode != MeasureSpec.EXACTLY) { for (let i = 0; i < count; i++) { const child = this.getVirtualChildAt(i); if (child == null || child.getVisibility() == View.GONE) { continue; } const lp = <LinearLayout.LayoutParams>child.getLayoutParams(); let childExtra = lp.weight; if (childExtra > 0) { child.measure( MeasureSpec.makeMeasureSpec(child.getMeasuredWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(largestChildHeight, MeasureSpec.EXACTLY)); } } } } if (!allFillParent && widthMode != MeasureSpec.EXACTLY) { maxWidth = alternativeMaxWidth; } maxWidth += this.mPaddingLeft + this.mPaddingRight; // Check against our minimum width maxWidth = Math.max(maxWidth, this.getSuggestedMinimumWidth()); this.setMeasuredDimension(LinearLayout.resolveSizeAndState(maxWidth, widthMeasureSpec, childState), heightSizeAndState); if (matchWidth) { this.forceUniformWidth(count, heightMeasureSpec); } } forceUniformWidth(count:number, heightMeasureSpec:number) { // Pretend that the linear layout has an exact size. let uniformMeasureSpec = MeasureSpec.makeMeasureSpec(this.getMeasuredWidth(), MeasureSpec.EXACTLY); for (let i = 0; i< count; ++i) { const child = this.getVirtualChildAt(i); if (child.getVisibility() != View.GONE) { let lp = <LinearLayout.LayoutParams>child.getLayoutParams(); if (lp.width == LinearLayout.LayoutParams.MATCH_PARENT) { // Temporarily force children to reuse their old measured height // FIXME: this may not be right for something like wrapping text? let oldHeight = lp.height; lp.height = child.getMeasuredHeight(); // Remeasue with new dimensions this.measureChildWithMargins(child, uniformMeasureSpec, 0, heightMeasureSpec, 0); lp.height = oldHeight; } } } } measureHorizontal(widthMeasureSpec:number, heightMeasureSpec:number) { this.mTotalLength = 0; let maxHeight = 0; let childState = 0; let alternativeMaxHeight = 0; let weightedMaxHeight = 0; let allFillParent = true; let totalWeight = 0; const count = this.getVirtualChildCount(); const widthMode = MeasureSpec.getMode(widthMeasureSpec); const heightMode = MeasureSpec.getMode(heightMeasureSpec); let matchHeight = false; if (this.mMaxAscent == null || this.mMaxDescent == null) { this.mMaxAscent = androidui.util.ArrayCreator.newNumberArray(LinearLayout.VERTICAL_GRAVITY_COUNT); this.mMaxDescent = androidui.util.ArrayCreator.newNumberArray(LinearLayout.VERTICAL_GRAVITY_COUNT); } let maxAscent = this.mMaxAscent; let maxDescent = this.mMaxDescent; maxAscent[0] = maxAscent[1] = maxAscent[2] = maxAscent[3] = -1; maxDescent[0] = maxDescent[1] = maxDescent[2] = maxDescent[3] = -1; const baselineAligned = this.mBaselineAligned; const useLargestChild = this.mUseLargestChild; const isExactly = widthMode == MeasureSpec.EXACTLY; let largestChildWidth = Number.MAX_SAFE_INTEGER; // See how wide everyone is. Also remember max height. for (let i = 0; i < count; ++i) { const child = this.getVirtualChildAt(i); if (child == null) { this.mTotalLength += this.measureNullChild(i); continue; } if (child.getVisibility() == View.GONE) { i += this.getChildrenSkipCount(child, i); continue; } if (this.hasDividerBeforeChildAt(i)) { this.mTotalLength += this.mDividerWidth; } const lp = <LinearLayout.LayoutParams>child.getLayoutParams(); totalWeight += lp.weight; if (widthMode == MeasureSpec.EXACTLY && lp.width == 0 && lp.weight > 0) { // Optimization: don't bother measuring children who are going to use // leftover space. These views will get measured again down below if // there is any leftover space. if (isExactly) { this.mTotalLength += lp.leftMargin + lp.rightMargin; } else { const totalLength = this.mTotalLength; this.mTotalLength = Math.max(totalLength, totalLength + lp.leftMargin + lp.rightMargin); } // Baseline alignment requires to measure widgets to obtain the // baseline offset (in particular for TextViews). The following // defeats the optimization mentioned above. Allow the child to // use as much space as it wants because we can shrink things // later (and re-measure). if (baselineAligned) { const freeSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); child.measure(freeSpec, freeSpec); } } else { let oldWidth = Number.MIN_SAFE_INTEGER; if (lp.width == 0 && lp.weight > 0) { // widthMode is either UNSPECIFIED or AT_MOST, and this // child // wanted to stretch to fill available space. Translate that to // WRAP_CONTENT so that it does not end up with a width of 0 oldWidth = 0; lp.width = LinearLayout.LayoutParams.WRAP_CONTENT; } // Determine how big this child would like to be. If this or // previous children have given a weight, then we allow it to // use all available space (and we will shrink things later // if needed). this.measureChildBeforeLayout(child, i, widthMeasureSpec, totalWeight == 0 ? this.mTotalLength : 0, heightMeasureSpec, 0); if (oldWidth != Number.MIN_SAFE_INTEGER) { lp.width = oldWidth; } const childWidth = child.getMeasuredWidth(); if (isExactly) { this.mTotalLength += childWidth + lp.leftMargin + lp.rightMargin + this.getNextLocationOffset(child); } else { const totalLength = this.mTotalLength; this.mTotalLength = Math.max(totalLength, totalLength + childWidth + lp.leftMargin + lp.rightMargin + this.getNextLocationOffset(child)); } if (useLargestChild) { largestChildWidth = Math.max(childWidth, largestChildWidth); } } let matchHeightLocally = false; if (heightMode != MeasureSpec.EXACTLY && lp.height == LinearLayout.LayoutParams.MATCH_PARENT) { // The height of the linear layout will scale, and at least one // child said it wanted to match our height. Set a flag indicating that // we need to remeasure at least that view when we know our height. matchHeight = true; matchHeightLocally = true; } const margin = lp.topMargin + lp.bottomMargin; const childHeight = child.getMeasuredHeight() + margin; childState = LinearLayout.combineMeasuredStates(childState, child.getMeasuredState()); if (baselineAligned) { const childBaseline = child.getBaseline(); if (childBaseline != -1) { // Translates the child's vertical gravity into an index // in the range 0..VERTICAL_GRAVITY_COUNT const gravity = (lp.gravity < 0 ? this.mGravity : lp.gravity) & Gravity.VERTICAL_GRAVITY_MASK; const index = ((gravity >> Gravity.AXIS_Y_SHIFT) & ~Gravity.AXIS_SPECIFIED) >> 1; maxAscent[index] = Math.max(maxAscent[index], childBaseline); maxDescent[index] = Math.max(maxDescent[index], childHeight - childBaseline); } } maxHeight = Math.max(maxHeight, childHeight); allFillParent = allFillParent && lp.height == LinearLayout.LayoutParams.MATCH_PARENT; if (lp.weight > 0) { /* * Heights of weighted Views are bogus if we end up * remeasuring, so keep them separate. */ weightedMaxHeight = Math.max(weightedMaxHeight, matchHeightLocally ? margin : childHeight); } else { alternativeMaxHeight = Math.max(alternativeMaxHeight, matchHeightLocally ? margin : childHeight); } i += this.getChildrenSkipCount(child, i); } if (this.mTotalLength > 0 && this.hasDividerBeforeChildAt(count)) { this.mTotalLength += this.mDividerWidth; } // Check mMaxAscent[INDEX_TOP] first because it maps to Gravity.TOP, // the most common case if (maxAscent[LinearLayout.INDEX_TOP] != -1 || maxAscent[LinearLayout.INDEX_CENTER_VERTICAL] != -1 || maxAscent[LinearLayout.INDEX_BOTTOM] != -1 || maxAscent[LinearLayout.INDEX_FILL] != -1) { const ascent = Math.max(maxAscent[LinearLayout.INDEX_FILL], Math.max(maxAscent[LinearLayout.INDEX_CENTER_VERTICAL], Math.max(maxAscent[LinearLayout.INDEX_TOP], maxAscent[LinearLayout.INDEX_BOTTOM]))); const descent = Math.max(maxDescent[LinearLayout.INDEX_FILL], Math.max(maxDescent[LinearLayout.INDEX_CENTER_VERTICAL], Math.max(maxDescent[LinearLayout.INDEX_TOP], maxDescent[LinearLayout.INDEX_BOTTOM]))); maxHeight = Math.max(maxHeight, ascent + descent); } if (useLargestChild && (widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED)) { this.mTotalLength = 0; for (let i = 0; i < count; ++i) { const child = this.getVirtualChildAt(i); if (child == null) { this.mTotalLength += this.measureNullChild(i); continue; } if (child.getVisibility() == View.GONE) { i += this.getChildrenSkipCount(child, i); continue; } const lp = <LinearLayout.LayoutParams>child.getLayoutParams(); if (isExactly) { this.mTotalLength += largestChildWidth + lp.leftMargin + lp.rightMargin + this.getNextLocationOffset(child); } else { const totalLength = this.mTotalLength; this.mTotalLength = Math.max(totalLength, totalLength + largestChildWidth + lp.leftMargin + lp.rightMargin + this.getNextLocationOffset(child)); } } } // Add in our padding this.mTotalLength += this.mPaddingLeft + this.mPaddingRight; let widthSize = this.mTotalLength; // Check against our minimum width widthSize = Math.max(widthSize, this.getSuggestedMinimumWidth()); // Reconcile our calculated size with the widthMeasureSpec let widthSizeAndState = LinearLayout.resolveSizeAndState(widthSize, widthMeasureSpec, 0); widthSize = widthSizeAndState & View.MEASURED_SIZE_MASK; // Either expand children with weight to take up available space or // shrink them if they extend beyond our current bounds let delta = widthSize - this.mTotalLength; if (delta != 0 && totalWeight > 0) { let weightSum = this.mWeightSum > 0 ? this.mWeightSum : totalWeight; maxAscent[0] = maxAscent[1] = maxAscent[2] = maxAscent[3] = -1; maxDescent[0] = maxDescent[1] = maxDescent[2] = maxDescent[3] = -1; maxHeight = -1; this.mTotalLength = 0; for (let i = 0; i < count; ++i) { const child = this.getVirtualChildAt(i); if (child == null || child.getVisibility() == View.GONE) { continue; } const lp = <LinearLayout.LayoutParams>child.getLayoutParams(); let childExtra = lp.weight; if (childExtra > 0) { // Child said it could absorb extra space -- give him his share let share = (childExtra * delta / weightSum); weightSum -= childExtra; delta -= share; const childHeightMeasureSpec = LinearLayout.getChildMeasureSpec( heightMeasureSpec, this.mPaddingTop + this.mPaddingBottom + lp.topMargin + lp.bottomMargin, lp.height); // TODO: Use a field like lp.isMeasured to figure out if this // child has been previously measured if ((lp.width != 0) || (widthMode != MeasureSpec.EXACTLY)) { // child was measured once already above ... base new measurement // on stored values let childWidth = child.getMeasuredWidth() + share; if (childWidth < 0) { childWidth = 0; } child.measure( MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY), childHeightMeasureSpec); } else { // child was skipped in the loop above. Measure for this first time here child.measure(MeasureSpec.makeMeasureSpec( share > 0 ? share : 0, MeasureSpec.EXACTLY), childHeightMeasureSpec); } // Child may now not fit in horizontal dimension. childState = LinearLayout.combineMeasuredStates(childState, child.getMeasuredState() & View.MEASURED_STATE_MASK); } if (isExactly) { this.mTotalLength += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin + this.getNextLocationOffset(child); } else { const totalLength = this.mTotalLength; this.mTotalLength = Math.max(totalLength, totalLength + child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin + this.getNextLocationOffset(child)); } let matchHeightLocally = heightMode != MeasureSpec.EXACTLY && lp.height == LinearLayout.LayoutParams.MATCH_PARENT; const margin = lp.topMargin + lp .bottomMargin; let childHeight = child.getMeasuredHeight() + margin; maxHeight = Math.max(maxHeight, childHeight); alternativeMaxHeight = Math.max(alternativeMaxHeight, matchHeightLocally ? margin : childHeight); allFillParent = allFillParent && lp.height == LinearLayout.LayoutParams.MATCH_PARENT; if (baselineAligned) { const childBaseline = child.getBaseline(); if (childBaseline != -1) { // Translates the child's vertical gravity into an index in the range 0..2 const gravity = (lp.gravity < 0 ? this.mGravity : lp.gravity) & Gravity.VERTICAL_GRAVITY_MASK; const index = ((gravity >> Gravity.AXIS_Y_SHIFT) & ~Gravity.AXIS_SPECIFIED) >> 1; maxAscent[index] = Math.max(maxAscent[index], childBaseline); maxDescent[index] = Math.max(maxDescent[index], childHeight - childBaseline); } } } // Add in our padding this.mTotalLength += this.mPaddingLeft + this.mPaddingRight; // TODO: Should we update widthSize with the new total length? // Check mMaxAscent[INDEX_TOP] first because it maps to Gravity.TOP, // the most common case if (maxAscent[LinearLayout.INDEX_TOP] != -1 || maxAscent[LinearLayout.INDEX_CENTER_VERTICAL] != -1 || maxAscent[LinearLayout.INDEX_BOTTOM] != -1 || maxAscent[LinearLayout.INDEX_FILL] != -1) { const ascent = Math.max(maxAscent[LinearLayout.INDEX_FILL], Math.max(maxAscent[LinearLayout.INDEX_CENTER_VERTICAL], Math.max(maxAscent[LinearLayout.INDEX_TOP], maxAscent[LinearLayout.INDEX_BOTTOM]))); const descent = Math.max(maxDescent[LinearLayout.INDEX_FILL], Math.max(maxDescent[LinearLayout.INDEX_CENTER_VERTICAL], Math.max(maxDescent[LinearLayout.INDEX_TOP], maxDescent[LinearLayout.INDEX_BOTTOM]))); maxHeight = Math.max(maxHeight, ascent + descent); } } else { alternativeMaxHeight = Math.max(alternativeMaxHeight, weightedMaxHeight); // We have no limit, so make all weighted views as wide as the largest child. // Children will have already been measured once. if (useLargestChild && widthMode != MeasureSpec.EXACTLY) { for (let i = 0; i < count; i++) { const child = this.getVirtualChildAt(i); if (child == null || child.getVisibility() == View.GONE) { continue; } const lp = <LinearLayout.LayoutParams>child.getLayoutParams(); let childExtra = lp.weight; if (childExtra > 0) { child.measure( MeasureSpec.makeMeasureSpec(largestChildWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(child.getMeasuredHeight(), MeasureSpec.EXACTLY)); } } } } if (!allFillParent && heightMode != MeasureSpec.EXACTLY) { maxHeight = alternativeMaxHeight; } maxHeight += this.mPaddingTop + this.mPaddingBottom; // Check against our minimum height maxHeight = Math.max(maxHeight, this.getSuggestedMinimumHeight()); this.setMeasuredDimension(widthSizeAndState | (childState&View.MEASURED_STATE_MASK), LinearLayout.resolveSizeAndState(maxHeight, heightMeasureSpec, (childState<<View.MEASURED_HEIGHT_STATE_SHIFT))); if (matchHeight) { this.forceUniformHeight(count, widthMeasureSpec); } } private forceUniformHeight(count:number, widthMeasureSpec:number) { // Pretend that the linear layout has an exact size. This is the measured height of // ourselves. The measured height should be the max height of the children, changed // to accommodate the heightMeasureSpec from the parent let uniformMeasureSpec = MeasureSpec.makeMeasureSpec(this.getMeasuredHeight(), MeasureSpec.EXACTLY); for (let i = 0; i < count; ++i) { const child = this.getVirtualChildAt(i); if (child.getVisibility() != View.GONE) { let lp = <LinearLayout.LayoutParams>child.getLayoutParams(); if (lp.height == LinearLayout.LayoutParams.MATCH_PARENT) { // Temporarily force children to reuse their old measured width // FIXME: this may not be right for something like wrapping text? let oldWidth = lp.width; lp.width = child.getMeasuredWidth(); // Remeasure with new dimensions this.measureChildWithMargins(child, widthMeasureSpec, 0, uniformMeasureSpec, 0); lp.width = oldWidth; } } } } getChildrenSkipCount(child:View, index:number):number { return 0; } measureNullChild(childIndex:number):number { return 0; } measureChildBeforeLayout(child:View, childIndex:number, widthMeasureSpec:number, totalWidth:number, heightMeasureSpec:number, totalHeight:number) { this.measureChildWithMargins(child, widthMeasureSpec, totalWidth, heightMeasureSpec, totalHeight); } getLocationOffset(child:View):number { return 0; } getNextLocationOffset(child:View) { return 0; } protected onLayout(changed:boolean, l:number, t:number, r:number, b:number):void { if (this.mOrientation == LinearLayout.VERTICAL) { this.layoutVertical(l, t, r, b); } else { this.layoutHorizontal(l, t, r, b); } } layoutVertical(left:number, top:number, right:number, bottom:number) { const paddingLeft = this.mPaddingLeft; let childTop; let childLeft; // Where right end of child should go const width = right - left; let childRight = width - this.mPaddingRight; // Space available for child let childSpace = width - paddingLeft - this.mPaddingRight; const count = this.getVirtualChildCount(); const majorGravity = this.mGravity & Gravity.VERTICAL_GRAVITY_MASK; const minorGravity = this.mGravity & Gravity.HORIZONTAL_GRAVITY_MASK; switch (majorGravity) { case Gravity.BOTTOM: // mTotalLength contains the padding already childTop = this.mPaddingTop + bottom - top - this.mTotalLength; break; // mTotalLength contains the padding already case Gravity.CENTER_VERTICAL: childTop = this.mPaddingTop + (bottom - top - this.mTotalLength) / 2; break; case Gravity.TOP: default: childTop = this.mPaddingTop; break; } for (let i = 0; i < count; i++) { const child = this.getVirtualChildAt(i); if (child == null) { childTop += this.measureNullChild(i); } else if (child.getVisibility() != View.GONE) { const childWidth = child.getMeasuredWidth(); const childHeight = child.getMeasuredHeight(); const lp = <LinearLayout.LayoutParams>child.getLayoutParams(); let gravity = lp.gravity; if (gravity < 0) { gravity = minorGravity; } //const layoutDirection = this.getLayoutDirection(); const absoluteGravity = gravity;//Gravity.getAbsoluteGravity(gravity, layoutDirection); switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.CENTER_HORIZONTAL: childLeft = paddingLeft + ((childSpace - childWidth) / 2) + lp.leftMargin - lp.rightMargin; break; case Gravity.RIGHT: childLeft = childRight - childWidth - lp.rightMargin; break; case Gravity.LEFT: default: childLeft = paddingLeft + lp.leftMargin; break; } if (this.hasDividerBeforeChildAt(i)) { childTop += this.mDividerHeight; } childTop += lp.topMargin; this.setChildFrame(child, childLeft, childTop + this.getLocationOffset(child), childWidth, childHeight); childTop += childHeight + lp.bottomMargin + this.getNextLocationOffset(child); i += this.getChildrenSkipCount(child, i); } } } layoutHorizontal(left:number, top:number, right:number, bottom:number) { const isLayoutRtl = this.isLayoutRtl(); const paddingTop = this.mPaddingTop; let childTop; let childLeft; // Where bottom of child should go const height = bottom - top; let childBottom = height - this.mPaddingBottom; // Space available for child let childSpace = height - paddingTop - this.mPaddingBottom; const count = this.getVirtualChildCount(); const majorGravity = this.mGravity & Gravity.HORIZONTAL_GRAVITY_MASK; const minorGravity = this.mGravity & Gravity.VERTICAL_GRAVITY_MASK; const baselineAligned = this.mBaselineAligned; const maxAscent = this.mMaxAscent; const maxDescent = this.mMaxDescent; //const layoutDirection = this.getLayoutDirection(); let absoluteGravity = majorGravity;//Gravity.getAbsoluteGravity(majorGravity, layoutDirection); switch (absoluteGravity) { case Gravity.RIGHT: // mTotalLength contains the padding already childLeft = this.mPaddingLeft + right - left - this.mTotalLength; break; case Gravity.CENTER_HORIZONTAL: // mTotalLength contains the padding already childLeft = this.mPaddingLeft + (right - left - this.mTotalLength) / 2; break; case Gravity.LEFT: default: childLeft = this.mPaddingLeft; break; } let start = 0; let dir = 1; //In case of RTL, start drawing from the last child. if (isLayoutRtl) { start = count - 1; dir = -1; } for (let i = 0; i < count; i++) { let childIndex = start + dir * i; const child = this.getVirtualChildAt(childIndex); if (child == null) { childLeft += this.measureNullChild(childIndex); } else if (child.getVisibility() != View.GONE) { const childWidth = child.getMeasuredWidth(); const childHeight = child.getMeasuredHeight(); let childBaseline = -1; const lp = <LinearLayout.LayoutParams>child.getLayoutParams(); if (baselineAligned && lp.height != LinearLayout.LayoutParams.MATCH_PARENT) { childBaseline = child.getBaseline(); } let gravity = lp.gravity; if (gravity < 0) { gravity = minorGravity; } switch (gravity & Gravity.VERTICAL_GRAVITY_MASK) { case Gravity.TOP: childTop = paddingTop + lp.topMargin; if (childBaseline != -1) { childTop += maxAscent[LinearLayout.INDEX_TOP] - childBaseline; } break; case Gravity.CENTER_VERTICAL: // Removed support for baseline alignment when layout_gravity or // gravity == center_vertical. See bug #1038483. // Keep the code around if we need to re-enable this feature // if (childBaseline != -1) { // // Align baselines vertically only if the child is smaller than us // if (childSpace - childHeight > 0) { // childTop = paddingTop + (childSpace / 2) - childBaseline; // } else { // childTop = paddingTop + (childSpace - childHeight) / 2; // } // } else { childTop = paddingTop + ((childSpace - childHeight) / 2) + lp.topMargin - lp.bottomMargin; break; case Gravity.BOTTOM: childTop = childBottom - childHeight - lp.bottomMargin; if (childBaseline != -1) { let descent = child.getMeasuredHeight() - childBaseline; childTop -= (maxDescent[LinearLayout.INDEX_BOTTOM] - descent); } break; default: childTop = paddingTop; break; } if (this.hasDividerBeforeChildAt(childIndex)) { childLeft += this.mDividerWidth; } childLeft += lp.leftMargin; this.setChildFrame(child, childLeft + this.getLocationOffset(child), childTop, childWidth, childHeight); childLeft += childWidth + lp.rightMargin + this.getNextLocationOffset(child); i += this.getChildrenSkipCount(child, childIndex); } } } private setChildFrame(child:View, left:number, top:number, width:number, height:number){ child.layout(left, top, left + width, top + height); } setOrientation(orientation:number) { if(typeof orientation === 'string'){ if('VERTICAL' === (orientation+'').toUpperCase()) orientation = LinearLayout.VERTICAL; else if('HORIZONTAL' === (orientation+'').toUpperCase()) orientation = LinearLayout.HORIZONTAL; } if (this.mOrientation != orientation) { this.mOrientation = orientation; this.requestLayout(); } } getOrientation() { return this.mOrientation; } setGravity(gravity:number) { if (this.mGravity != gravity) { if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) { gravity |= Gravity.LEFT; } if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { gravity |= Gravity.TOP; } this.mGravity = gravity; this.requestLayout(); } } setHorizontalGravity(horizontalGravity:number) { const gravity = horizontalGravity & Gravity.HORIZONTAL_GRAVITY_MASK; if ((this.mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != gravity) { this.mGravity = (this.mGravity & ~Gravity.HORIZONTAL_GRAVITY_MASK) | gravity; this.requestLayout(); } } setVerticalGravity(verticalGravity:number) { const gravity = verticalGravity & Gravity.VERTICAL_GRAVITY_MASK; if ((this.mGravity & Gravity.VERTICAL_GRAVITY_MASK) != gravity) { this.mGravity = (this.mGravity & ~Gravity.VERTICAL_GRAVITY_MASK) | gravity; this.requestLayout(); } } public generateLayoutParamsFromAttr(attrs: HTMLElement): android.view.ViewGroup.LayoutParams { return new LinearLayout.LayoutParams(this.getContext(), attrs); } protected generateDefaultLayoutParams():android.view.ViewGroup.LayoutParams { let LayoutParams = LinearLayout.LayoutParams; if (this.mOrientation == LinearLayout.HORIZONTAL) { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } else if (this.mOrientation == LinearLayout.VERTICAL) { return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } return super.generateDefaultLayoutParams(); } protected generateLayoutParams(p:android.view.ViewGroup.LayoutParams):android.view.ViewGroup.LayoutParams { return new LinearLayout.LayoutParams(p); } protected checkLayoutParams(p:android.view.ViewGroup.LayoutParams):boolean { return p instanceof LinearLayout.LayoutParams; } } export module LinearLayout{ export class LayoutParams extends android.view.ViewGroup.MarginLayoutParams{ weight = 0; gravity = -1; constructor(context:Context, attrs:HTMLElement); constructor(width:number, height:number); constructor(source:ViewGroup.LayoutParams); constructor(width:number, height:number, weight?:number); constructor(...args) { super(...(() => { if (args[0] instanceof Context && args[1] instanceof HTMLElement) return [args[0], args[1]]; else if (typeof args[0] === 'number' && typeof args[1] === 'number' && typeof args[2] === 'number') return [args[0], args[1]]; else if (typeof args[0] === 'number' && typeof args[1] === 'number') return [args[0], args[1]]; else if (args[0] instanceof LinearLayout.LayoutParams) return [args[0]]; else if (args[0] instanceof ViewGroup.MarginLayoutParams) return [args[0]]; else if (args[0] instanceof ViewGroup.LayoutParams) return [args[0]]; })()); if (args[0] instanceof Context && args[1] instanceof HTMLElement) { const c = <Context>args[0]; const attrs = <HTMLElement>args[1]; const a = c.obtainStyledAttributes(attrs); this.weight = a.getFloat('layout_weight', 0); this.gravity = Gravity.parseGravity(a.getAttrValue('layout_gravity'), -1); a.recycle(); } else if (typeof args[0] === 'number' && typeof args[1] === 'number' && typeof args[2] == 'number') { this.weight = args[2]; } else if (typeof args[0] === 'number' && typeof args[1] === 'number') { this.weight = 0; } else if (args[0] instanceof LinearLayout.LayoutParams) { const source = <LinearLayout.LayoutParams>args[0]; this.weight = source.weight; this.gravity = source.gravity; } else if (args[0] instanceof ViewGroup.MarginLayoutParams) { } else if (args[0] instanceof ViewGroup.LayoutParams) { } } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('layout_gravity', { setter(param:LayoutParams, value:any, attrBinder:androidui.attr.AttrBinder) { param.gravity = attrBinder.parseGravity(value, param.gravity); }, getter(param:LayoutParams) { return param.gravity; } }).set('layout_weight', { setter(param:LayoutParams, value:any, attrBinder:androidui.attr.AttrBinder) { param.weight = attrBinder.parseFloat(value, param.weight); }, getter(param:LayoutParams) { return param.weight; } }); } } } }
the_stack
/*** Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE file in the project root for full license information. */ module Todo { "use strict"; /** A union of the differing promise types from WinJs and Azure */ type Promise = Microsoft.WindowsAzure.asyncPromise | WinJS.Promise<any>; export module Storage { /** * The key for your Azure Mobile Service * TODO: Add your application key */ var AZURE_MOBILE_SERVICES_KEY = ''; /** * The URL for your Azure Mobile Service * TODO: Add your application URL */ var AZURE_MOBILE_SERVICES_URL = ''; /** * Get all items from storage * @return A promise that wraps a list of todo items */ export function getAllToDoItems(): Promise { return storageImplementation.getAll(); } /** * Insert an item into storage * @param toDoItem The item to insert * @return A promise to insert the item wrapping the inserted item */ export function insert(toDoItem: ToDoItem): Promise { return storageImplementation.insert(toDoItem); } /** * Update an item in the backend * @param toDoItem The item to update * @return A promise to update the item wrapping the updated item */ export function update(toDoItem: ToDoItem): Promise { return storageImplementation.update(toDoItem); } /** * Delete an item from the storage backend. * @param toDoItem The item to delete * @return A promise to delete the item wrapping a null value */ export function del(toDoItem: ToDoItem): Promise { return storageImplementation.del(toDoItem); } /** * Defines how to get, save, update, and delete items from storage */ interface IStorageImplementation { getAll(): Promise; insert(item: ToDoItem): Promise; update(item: ToDoItem): Promise; del(item: ToDoItem): Promise; } /** * Provides a localStorage-backed API */ class LocalStorageImplementation implements IStorageImplementation { /** * The key that the array will be stringified and stored under. */ private static _localStorageKey: string = 'toDoItems'; /** * Get all the items from local storage * @return An array of all the items */ getAll(): WinJS.IPromise<ToDoItem[]> { return WinJS.Promise.as(this._loadFromStorage()); } /** * Insert an item to local storage * @param item The item to insert * @return A promise that wraps the inserted item */ insert(item: ToDoItem): WinJS.Promise<ToDoItem> { item.id = LocalStorageImplementation._generateGuid(); var items = this._loadFromStorage(); items.push(item); this._saveToStorage(items); return WinJS.Promise.as(item); } /** * Update an item in local storage * @param item The item to update * @return A promise that wraps the updated item */ update(item: ToDoItem): WinJS.Promise<ToDoItem> { var items = this._loadFromStorage(); for (var i = 0; i < items.length; i++) { // Loop through the array and replace the item that matches if (items[i].id === item.id) { items[i] = item; break; } } this._saveToStorage(items); return WinJS.Promise.as(item); } /** * Delete an item from local storage * @param item The item to delete * @return A WinJS promise that wraps null */ del(item: ToDoItem): WinJS.IPromise<ToDoItem> { var items = this._loadFromStorage(); // Loop through the array of items and remove the item that matches. for (var i = 0; i < items.length; i++) { if (items[i].id === item.id) { items.splice(i, 1); break; } } // Send the updated items array back to local storage this._saveToStorage(items); return WinJS.Promise.as(null); } /** * Get all items from local storage. * @return An array of all items stored in local storage (or an empty array if nothing was stored). */ private _loadFromStorage(): ToDoItem[] { return JSON.parse(window.localStorage.getItem(LocalStorageImplementation._localStorageKey)) || []; } /** * Save items to local storage */ private _saveToStorage(items: ToDoItem[]): void { window.localStorage.setItem(LocalStorageImplementation._localStorageKey, JSON.stringify(items)); } /** * Get a random GUID * @return A string guid with no enclosing punctuation (ex. 5BCC1397-7B39-4860-4A20-7346C492F788) */ private static _generateGuid(): string { return [ this._generateGuidPart(), this._generateGuidPart(), '-', this._generateGuidPart(), '-', this._generateGuidPart(), '-', this._generateGuidPart(), '-', this._generateGuidPart(), this._generateGuidPart(), this._generateGuidPart() ].join(''); } /** * Helper for generating a GUID. * @return A random four character uppercase hex string. */ private static _generateGuidPart(): string { var guidPartNumber = (Math.random() * 0x10000) | 0; return (guidPartNumber + 0x10000).toString(16).substring(1).toUpperCase(); } } /** * Storage wrapper for reading and saving items to the todoitem table. * TODO(adamre): Shouldn't this constructable against any table? */ class WindowsAzureStorageImplementation implements IStorageImplementation { /** * The Mobile Services API client library */ private _client: Microsoft.WindowsAzure.MobileServiceClient; /** * The reference to the Mobile Services table */ private _toDoItemsTable: Microsoft.WindowsAzure.MobileServiceTable; /** * Get 1000 items from the todoitem table * @return An Azure promise for the read operation */ getAll(): Microsoft.WindowsAzure.asyncPromise { this._ensureToDoItemsTable(); return this._toDoItemsTable.take(1000).read(); } /** * Insert an item into the todoitem table * @param item The item to insert into the table * @return An Azure promise for the insert operation */ insert(item: ToDoItem): Microsoft.WindowsAzure.asyncPromise { return this._toDoItemsTable.insert(item); } /** * Update an item in the todoitem table * @param item The item to update it the table * @return An Azure promise for the update operation */ update(item: ToDoItem): Microsoft.WindowsAzure.asyncPromise { return this._toDoItemsTable.update(item); } /** * Delete an item in the todoitem table * @param item The item to remove * @return An Azure promise for the delete operation */ del(item: ToDoItem): Microsoft.WindowsAzure.asyncPromise { return this._toDoItemsTable.del(item); } /** * Make sure we have a table to work against * TODO(adamre): Shouldn't this be done in the constructor? */ private _ensureToDoItemsTable(): void { if (!this._toDoItemsTable) { this._client = new WindowsAzure.MobileServiceClient(AZURE_MOBILE_SERVICES_URL, AZURE_MOBILE_SERVICES_KEY); this._toDoItemsTable = this._client.getTable("todoitem"); } } } var storageImplementation: IStorageImplementation = (AZURE_MOBILE_SERVICES_KEY && AZURE_MOBILE_SERVICES_URL) ? new WindowsAzureStorageImplementation() : new LocalStorageImplementation(); } /** * The Bing Maps API */ export module Maps { var BING_MAPS_KEY = ''; //Add your Bing Maps API key /** * Get the current position as a promise from the window's navigator object. * @return A WinJS promise that resolves the current position. */ export function getCurrentPosition(): WinJS.Promise<Position> { return new WinJS.Promise((completed, error) => { navigator.geolocation.getCurrentPosition(completed, error); }); } /** * Call the Bing Maps API to get an address from a position. * @param position The position to get an address for. * @return A WinJS promise that resolves the address to a string on API call success or the plain coordinates on failure. */ export function getAddressFromPosition(position: Position): WinJS.Promise<string> { var url = [ 'http://dev.virtualearth.net/REST/v1/Locations/', position.coords.latitude, ',', position.coords.longitude, '?key=', BING_MAPS_KEY ].join(""); return WinJS. xhr({ responseType: 'text', url: url }). then( response => parseRestResponse(response).resourceSets[0].resources[0].address.formattedAddress, error => position.coords.latitude + ',' + position.coords.longitude ); } /** * Helper to convert the Bing reponse from the XMLHttpRequest to a RestResponse object. * @param response The response from querying the Bing server. * @return The parsed JSON cast to a RestResponse. */ function parseRestResponse(response: XMLHttpRequest): RestResponse { return <RestResponse>JSON.parse(response.responseText); } /** * Bing Maps' API response */ class RestResponse { /** * A status code that offers additional information about authentication success or failure. */ authenticationResultCode: string; /** * A URL that references a brand image to support contractual branding requirements. */ brandLogoUri: string; /** * A copyright notice. */ copyright: string; /** * A collection of ResourceSet objects. A ResourceSet is a container of Resources returned by the request. */ resourceSets: ResourceSet[]; /** * The HTTP Status code for the request. */ statusCode: number; /** * A description of the HTTP status code. */ statusDescription: string; /** * A unique identifier for the request. */ traceId: string; } /** A container for Resources. */ class ResourceSet { /** An estimate of the total number of resources in the ResourceSet. */ estimatedTotal: number; /** A collection of one or more resources. The resources that are returned depend on the request. */ resources: Resource[]; } /** * A Location resource. See https://msdn.microsoft.com/en-us/library/ff701725.aspx */ class Resource { /** * The name of the resource */ name: string; /** * The latitude and longitude coordinates of the location. */ point: Point; /** * A geographic area that contains the location. A bounding box contains SouthLatitude, * WestLongitude, NorthLatitude, and EastLongitude values in units of degrees. */ bbox: number[]; /** * The classification of the geographic entity returned, such as Address. */ entityType: string; /** * The postal address for the location. */ address: Address; /** * The level of confidence that the geocoded location result is a match. * One of the following values: High, Medium, Low */ confidence: string; /** * One or more match code values that represent the geocoding level for each location in the response. */ matchCodes: string; /** * A collection of geocoded points that differ in how they were calculated and their suggested use. */ geocodePoints: GeocodePoint; } /** * Details about a point on the Earth that has additional location information. */ class Address { /** * The official street line of an address relative to the area, as specified by the Locality, * or PostalCode, properties. Typical use of this element would be to provide a street address * or any official address. */ addressLine: string; /** * A string specifying the populated place for the address. This typically refers to a city, * but may refer to a suburb or a neighborhood in certain countries. */ locality: string; /** * A string specifying the neighborhood for an address. You must specify includeNeighborhood=1 * in your request to return the neighborhood. */ neighborhood: string; /** * A string specifying the subdivision name in the country or region for an address. This * element is typically treated as the first order administrative subdivision, but in some * cases it is the second, third, or fourth order subdivision in a country, dependency, or * region. */ adminDistrict: string; /** A string specifying the subdivision name in the country or region for an address. This * element is used when there is another level of subdivision information for a location, * such as the county. */ adminDistrict2: string; /** * A string specifying the complete address. This address may not include the country or region. */ formattedAddress: string; /** * A string specifying the post code, postal code, or ZIP Code of an address. */ postalCode: string; /** * A string specifying the country or region name of an address. */ countryRegion: string; /** * A string specifying the two-letter ISO country code. You must specify include=ciso2 in your request to return this ISO country code. */ countryRegionIso2: string; /** * A string specifying the name of the landmark when there is a landmark associated with an address. */ landmark: string; } /** * Container for points. See https://msdn.microsoft.com/en-us/library/ff701725.aspx */ class GeocodePoint { /** * The latitude and longitude coordinates of the geocode point. */ point: Point; /** * The method that was used to compute the geocode point. * One of the following: Interpolation, InterpolationOffset, Parcel, Rooftop */ calculationMethod: string; /** * The best use for the geocode point. * One or more of the following: Display, Route */ usageTypes: string[]; } /** A point on the Earth specified by a latitude and longitude. */ class Point { /** * The coordinates are stored in a two element array as double values and are specified in the following order: * Latitude,Longitude * * The following ranges of values are valid: * Latitude (degrees): [-90, +90] * Longitude (degrees): [-180,+180] */ coordinates: number[]; } } }
the_stack
import classnames from 'classnames'; import every from 'lodash/every'; import isEmpty from 'lodash/isEmpty'; import isNull from 'lodash/isNull'; import isUndefined from 'lodash/isUndefined'; import { Dispatch, Fragment, SetStateAction, useContext, useEffect, useState } from 'react'; import { FaFilter } from 'react-icons/fa'; import { IoMdCloseCircleOutline } from 'react-icons/io'; import { useHistory } from 'react-router-dom'; import API from '../../api'; import { AppCtx, updateLimit } from '../../context/AppCtx'; import useScrollRestorationFix from '../../hooks/useScrollRestorationFix'; import { FacetOption, Facets, Package, RepositoryKind, SearchFiltersURL, SearchResults, TsQuery } from '../../types'; import { TS_QUERY } from '../../utils/data'; import getSampleQueries from '../../utils/getSampleQueries'; import { prepareQueryString } from '../../utils/prepareQueryString'; import Loading from '../common/Loading'; import NoData from '../common/NoData'; import PackageCard from '../common/PackageCard'; import Pagination from '../common/Pagination'; import SampleQueries from '../common/SampleQueries'; import Sidebar from '../common/Sidebar'; import Footer from '../navigation/Footer'; import SubNavbar from '../navigation/SubNavbar'; import FilterBadge from './FilterBadge'; import Filters from './Filters'; import MoreActionsButton from './MoreActionsButton'; import PaginationLimit from './PaginationLimit'; import styles from './SearchView.module.css'; import SortOptions from './SortOptions'; interface FiltersProp { [key: string]: string[]; } interface Props { isSearching: boolean; setIsSearching: Dispatch<SetStateAction<boolean>>; scrollPosition?: number; setScrollPosition: Dispatch<SetStateAction<number | undefined>>; tsQueryWeb?: string; tsQuery?: string[]; pageNumber: number; filters?: FiltersProp; deprecated?: boolean | null; operators?: boolean | null; verifiedPublisher?: boolean | null; official?: boolean | null; fromDetail: boolean; visibleModal?: string; sort?: string | null; } const DEFAULT_SORT = 'relevance'; interface FilterLabel { key: string; name: string; } const SearchView = (props: Props) => { const { ctx, dispatch } = useContext(AppCtx); const history = useHistory(); const sampleQueries = getSampleQueries(); const [searchResults, setSearchResults] = useState<SearchResults>({ facets: null, packages: null, paginationTotalCount: '0', }); const { isSearching, setIsSearching, scrollPosition, setScrollPosition } = props; const [apiError, setApiError] = useState<string | null>(null); const [currentTsQueryWeb, setCurrentTsQueryWeb] = useState(props.tsQueryWeb); const calculateOffset = (): number => { return props.pageNumber && ctx.prefs.search.limit ? (props.pageNumber - 1) * ctx.prefs.search.limit : 0; }; const [offset, setOffset] = useState<number>(calculateOffset()); const getFilterName = (key: string, label: string): FilterLabel | null => { const correctKey = ['user', 'org'].includes(key) ? 'publisher' : key; if (searchResults.facets) { const selectedKey = searchResults.facets.find((fac: Facets) => fac.filterKey === correctKey); if (selectedKey) { const selectedOpt = selectedKey.options.find((opt: FacetOption) => opt.id.toString() === label); if (selectedOpt) { return { key: selectedKey.title, name: selectedOpt.name }; } else { return null; } } else { return null; } } return null; }; const getTsQueryName = (ts: string): string | null => { const selectedTsQuery = TS_QUERY.find((query: TsQuery) => query.label === ts); if (selectedTsQuery) { return selectedTsQuery.name; } else { return null; } }; const isEmptyFacets = (): boolean => { if (searchResults.facets) { return every(searchResults.facets, (f: Facets) => { return f.options.length === 0; }); } else { return true; } }; useScrollRestorationFix(); const saveScrollPosition = () => { setScrollPosition(window.scrollY); }; const updateWindowScrollPosition = (newPosition: number) => { window.scrollTo(0, newPosition); }; const prepareSelectedFilters = (name: string, newFilters: string[], prevFilters: FiltersProp): FiltersProp => { let cleanFilters: FiltersProp = {}; switch (name) { case 'kind': // Remove selected chart repositories when some kind different to Chart is selected and Chart is not selected if (newFilters.length > 0 && !newFilters.includes(RepositoryKind.Helm.toString())) { cleanFilters['repo'] = []; } break; } return { ...prevFilters, [name]: newFilters, ...cleanFilters, }; }; const getCurrentFilters = (): SearchFiltersURL => { return { pageNumber: props.pageNumber, tsQueryWeb: props.tsQueryWeb, tsQuery: props.tsQuery, filters: props.filters, deprecated: props.deprecated, operators: props.operators, verifiedPublisher: props.verifiedPublisher, official: props.official, sort: props.sort, }; }; const updateCurrentPage = (searchChanges: any) => { history.push({ pathname: '/packages/search', search: prepareQueryString({ ...getCurrentFilters(), pageNumber: 1, ...searchChanges, }), }); }; const onFiltersChange = (name: string, value: string, checked: boolean): void => { const currentFilters = props.filters || {}; let newFilters = isUndefined(currentFilters[name]) ? [] : currentFilters[name].slice(); if (checked) { newFilters.push(value); } else { newFilters = newFilters.filter((el) => el !== value); } updateCurrentPage({ filters: prepareSelectedFilters(name, newFilters, currentFilters), }); }; const onResetSomeFilters = (filterKeys: string[]): void => { let newFilters: FiltersProp = {}; filterKeys.forEach((fKey: string) => { newFilters[fKey] = []; }); updateCurrentPage({ filters: { ...props.filters, ...newFilters }, }); }; const onTsQueryChange = (value: string, checked: boolean): void => { let query = isUndefined(props.tsQuery) ? [] : props.tsQuery.slice(); if (checked) { query.push(value); } else { query = query.filter((el) => el !== value); } updateCurrentPage({ tsQuery: query, }); }; const onDeprecatedChange = (): void => { updateCurrentPage({ deprecated: !isUndefined(props.deprecated) && !isNull(props.deprecated) ? !props.deprecated : true, }); }; const onOperatorsChange = (): void => { updateCurrentPage({ operators: !isUndefined(props.operators) && !isNull(props.operators) ? !props.operators : true, }); }; const onVerifiedPublisherChange = (): void => { updateCurrentPage({ verifiedPublisher: !isUndefined(props.verifiedPublisher) && !isNull(props.verifiedPublisher) ? !props.verifiedPublisher : true, }); }; const onOfficialChange = (): void => { updateCurrentPage({ official: !isUndefined(props.official) && !isNull(props.official) ? !props.official : true, }); }; const onResetFilters = (): void => { history.push({ pathname: '/packages/search', search: prepareQueryString({ pageNumber: 1, tsQueryWeb: props.tsQueryWeb, tsQuery: [], filters: {}, sort: DEFAULT_SORT, }), }); }; const onPageNumberChange = (pageNumber: number): void => { updateCurrentPage({ pageNumber: pageNumber, }); }; const onSortChange = (sort: string): void => { history.replace({ pathname: '/packages/search', search: prepareQueryString({ ...getCurrentFilters(), sort: sort, pageNumber: 1, }), }); setScrollPosition(0); updateWindowScrollPosition(0); }; const onPaginationLimitChange = (newLimit: number): void => { history.replace({ pathname: '/packages/search', search: prepareQueryString({ ...getCurrentFilters(), pageNumber: 1, }), }); setScrollPosition(0); updateWindowScrollPosition(0); dispatch(updateLimit(newLimit)); }; useEffect(() => { async function fetchSearchResults() { setIsSearching(true); const query = { tsQueryWeb: props.tsQueryWeb, tsQuery: props.tsQuery, filters: props.filters, offset: calculateOffset(), limit: ctx.prefs.search.limit, deprecated: props.deprecated, operators: props.operators, verifiedPublisher: props.verifiedPublisher, official: props.official, sort: props.sort || DEFAULT_SORT, }; try { let newSearchResults = await API.searchPackages(query); if ( newSearchResults.paginationTotalCount === '0' && searchResults.facets && !isEmpty(searchResults.facets) && currentTsQueryWeb === props.tsQueryWeb // When some filters have changed, but not ts_query_web ) { newSearchResults = { ...newSearchResults, facets: searchResults.facets, }; } setSearchResults(newSearchResults); setOffset(query.offset); setCurrentTsQueryWeb(props.tsQueryWeb); setApiError(null); } catch { setSearchResults({ facets: [], packages: [], paginationTotalCount: '0', }); setApiError('An error occurred searching packages, please try again later.'); } finally { setIsSearching(false); // Update scroll position if (history.action === 'PUSH') { // When search page is open from detail page if (props.fromDetail && !isUndefined(scrollPosition)) { updateWindowScrollPosition(scrollPosition); // When search has changed } else { updateWindowScrollPosition(0); } // On pop action and when scroll position has been previously saved } else if (!isUndefined(scrollPosition)) { updateWindowScrollPosition(scrollPosition); } } } fetchSearchResults(); // prettier-ignore /* eslint-disable react-hooks/exhaustive-deps */ }, [ props.tsQueryWeb, JSON.stringify(props.tsQuery), props.pageNumber, JSON.stringify(props.filters), // https://twitter.com/dan_abramov/status/1104414272753487872 props.deprecated, props.operators, props.verifiedPublisher, props.official, ctx.prefs.search.limit, props.sort, ]); /* eslint-enable react-hooks/exhaustive-deps */ const activeFilters = props.deprecated || props.operators || props.verifiedPublisher || props.official || !isUndefined(props.tsQuery) || !isEmpty(props.filters); return ( <> <SubNavbar className={`h-auto ${styles.subnavbar}`}> <div className="d-flex flex-column w-100"> <div className="d-flex align-items-center justify-content-between flex-nowrap"> <div className="d-flex align-items-center text-truncate w-100"> {!isNull(searchResults.packages) && ( <> {/* Mobile filters */} {!isEmptyFacets() && ( <Sidebar label="Filters" className="d-inline-block d-md-none me-2" wrapperClassName="px-4" buttonType={classnames('btn-sm rounded-circle position-relative', styles.btnMobileFilters, { [styles.filtersBadge]: activeFilters, })} buttonIcon={<FaFilter />} closeButton={ <> {isSearching ? ( <> <span className="spinner-grow spinner-grow-sm" role="status" aria-hidden="true" /> <span className="ms-2">Loading...</span> </> ) : ( <>See {searchResults.paginationTotalCount} results</> )} </> } leftButton={ <> <div className="d-flex align-items-center"> <IoMdCloseCircleOutline className={`text-dark ${styles.resetBtnDecorator}`} /> <button className="btn btn-link btn-sm p-0 ps-1 text-dark" onClick={onResetFilters} aria-label="Reset filters" > Reset </button> </div> </> } header={<div className="h6 text-uppercase mb-0 flex-grow-1">Filters</div>} > <div role="menu"> <Filters forceCollapseList={props.tsQueryWeb !== currentTsQueryWeb} facets={searchResults.facets} activeFilters={props.filters || {}} activeTsQuery={props.tsQuery} onChange={onFiltersChange} onResetSomeFilters={onResetSomeFilters} onTsQueryChange={onTsQueryChange} deprecated={props.deprecated} operators={props.operators} verifiedPublisher={props.verifiedPublisher} official={props.official} onDeprecatedChange={onDeprecatedChange} onOperatorsChange={onOperatorsChange} onVerifiedPublisherChange={onVerifiedPublisherChange} onOfficialChange={onOfficialChange} onResetFilters={onResetFilters} visibleTitle={false} device="mobile" /> </div> </Sidebar> )} {!isSearching && ( <div className="d-flex flex-column w-100 text-truncate"> <div className={`text-truncate ${styles.searchText}`} role="status"> {parseInt(searchResults.paginationTotalCount) > 0 && ( <span className="pe-1"> {offset + 1} -{' '} {parseInt(searchResults.paginationTotalCount) < ctx.prefs.search.limit * props.pageNumber ? searchResults.paginationTotalCount : ctx.prefs.search.limit * props.pageNumber}{' '} <span className="ms-1">of</span>{' '} </span> )} {searchResults.paginationTotalCount} <span className="ps-1"> results </span> {props.tsQueryWeb && props.tsQueryWeb !== '' && ( <span className="d-none d-sm-inline ps-1"> for "<span className="fw-bold">{props.tsQueryWeb}</span>" </span> )} {activeFilters && ( <small className="d-inline d-lg-none fst-italic ms-1"> (some filters applied)</small> )} </div> </div> )} </> )} </div> <div className="ms-3"> <div className="d-flex flex-row"> {/* Only display sort options when ts_query_web is defined */} {props.tsQueryWeb && props.tsQueryWeb !== '' && ( <SortOptions activeSort={props.sort || DEFAULT_SORT} updateSort={onSortChange} disabled={isNull(searchResults.packages) || searchResults.packages.length === 0} /> )} <div className="d-none d-sm-flex"> <PaginationLimit limit={ctx.prefs.search.limit} updateLimit={onPaginationLimitChange} disabled={isNull(searchResults.packages) || searchResults.packages.length === 0} /> </div> <MoreActionsButton /> </div> </div> </div> {activeFilters && ( <div className="d-none d-lg-inline"> <div className="d-flex flex-row flex-wrap align-items-center pt-2"> <span className="me-2 pe-1 mb-2">Filters:</span> {props.official && <FilterBadge name="Only official" onClick={onOfficialChange} />} {props.verifiedPublisher && ( <FilterBadge name="Only verified publishers" onClick={onVerifiedPublisherChange} /> )} {!isUndefined(props.filters) && ( <> {Object.keys(props.filters).map((type: string) => { const opts = props.filters![type]; return ( <Fragment key={`opts_${type}`}> {opts.map((opt: string) => { const filter = getFilterName(type, opt); if (isNull(filter)) return null; return ( <FilterBadge key={`btn_${type}_${opt}`} type={filter.key} name={filter.name} onClick={() => onFiltersChange(type, opt, false)} /> ); })} </Fragment> ); })} </> )} {props.tsQuery && ( <> {props.tsQuery.map((ts: string) => { const value = getTsQueryName(ts); if (isNull(value)) return null; return ( <FilterBadge key={`btn_${ts}`} type="Category" name={value} onClick={() => onTsQueryChange(ts, false)} /> ); })} </> )} {props.operators && <FilterBadge name="Only operators" onClick={onOperatorsChange} />} {props.deprecated && <FilterBadge name="Include deprecated" onClick={onDeprecatedChange} />} </div> </div> )} </div> </SubNavbar> <div className="d-flex position-relative pt-3 pb-3 flex-grow-1"> {(isSearching || isNull(searchResults.packages)) && <Loading spinnerClassName="position-fixed top-50" />} <main role="main" className="container-lg px-sm-4 px-lg-0 d-flex flex-row justify-content-between"> {!isEmptyFacets() && ( <aside className={`px-xs-0 px-sm-3 px-lg-0 d-none d-md-block position-relative ${styles.sidebar}`} aria-label="Filters" > <div className="me-5" role="menu"> <Filters forceCollapseList={props.tsQueryWeb !== currentTsQueryWeb} facets={searchResults.facets} activeFilters={props.filters || {}} activeTsQuery={props.tsQuery} onChange={onFiltersChange} onResetSomeFilters={onResetSomeFilters} onTsQueryChange={onTsQueryChange} deprecated={props.deprecated} operators={props.operators} verifiedPublisher={props.verifiedPublisher} official={props.official} onDeprecatedChange={onDeprecatedChange} onOperatorsChange={onOperatorsChange} onVerifiedPublisherChange={onVerifiedPublisherChange} onOfficialChange={onOfficialChange} onResetFilters={onResetFilters} visibleTitle device="desktop" /> </div> </aside> )} <div className={classnames('flex-grow-1 mt-3 px-xs-0 px-sm-3 px-lg-0', styles.list, { [styles.emptyList]: isNull(searchResults.packages) || searchResults.packages.length === 0, })} > {!isNull(searchResults.packages) && ( <> {searchResults.packages.length === 0 ? ( <NoData issuesLinkVisible={!isNull(apiError)}> {isNull(apiError) ? ( <> We're sorry! <p className="h6 mb-0 mt-3 lh-base"> <span> We can't seem to find any packages that match your search </span> {props.tsQueryWeb && ( <span className="ps-1"> for "<span className="fw-bold">{props.tsQueryWeb}</span>" </span> )} {!isEmpty(props.filters) && <span className="ps-1">with the selected filters</span>} </p> <p className="h6 mb-0 mt-5 lh-base"> You can{' '} {!isEmpty(props.filters) ? ( <button className="btn btn-link text-dark fw-bold py-0 pb-1 px-0" onClick={onResetFilters} aria-label="Reset filters" > <u>reset the filters</u> </button> ) : ( <button className="btn btn-link text-dark fw-bold py-0 pb-1 px-0" onClick={() => { history.push({ pathname: '/packages/search', search: prepareQueryString({ pageNumber: 1, tsQueryWeb: '', tsQuery: [], filters: {}, }), }); }} aria-label="Browse all packages" > <u>browse all packages</u> </button> )} {sampleQueries.length > 0 ? ( <>, try a new search or start with one of the sample queries:</> ) : ( <> or try a new search.</> )} </p> <div className="h5 d-flex flex-row align-items-end justify-content-center flex-wrap"> <SampleQueries className="bg-light text-dark border-secondary text-dark" /> </div> </> ) : ( <>{apiError}</> )} </NoData> ) : ( <> <div className="mb-2 noFocus" id="content" tabIndex={-1} aria-label="Packages list"> <div className="row" role="list"> {searchResults.packages.map((item: Package) => ( <PackageCard key={item.packageId} package={item} searchUrlReferer={{ tsQueryWeb: props.tsQueryWeb, tsQuery: props.tsQuery, pageNumber: props.pageNumber, filters: props.filters, deprecated: props.deprecated, operators: props.operators, verifiedPublisher: props.verifiedPublisher, official: props.official, sort: props.sort, }} saveScrollPosition={saveScrollPosition} /> ))} </div> </div> <Pagination limit={ctx.prefs.search.limit} offset={offset} total={parseInt(searchResults.paginationTotalCount)} active={props.pageNumber} className="my-5" onChange={onPageNumberChange} /> </> )} </> )} </div> </main> </div> <Footer isHidden={isSearching || isNull(searchResults.packages)} /> </> ); }; export default SearchView;
the_stack
import { developMachine } from "../develop" import { interpret } from "xstate" import { IProgram } from "../../commands/types" const actions = { assignStoreAndWorkerPool: jest.fn(), assignServiceResult: jest.fn(), callApi: jest.fn(), finishParentSpan: jest.fn(), saveDbState: jest.fn(), logError: jest.fn(), panic: jest.fn(), panicBecauseOfInfiniteLoop: jest.fn(), } const services = { initialize: jest.fn(), initializeData: jest.fn(), reloadData: jest.fn(), runQueries: jest.fn(), startWebpackServer: jest.fn(), recompile: jest.fn(), waitForMutations: jest.fn(), recreatePages: jest.fn(), } const throwService = async (): Promise<void> => { throw new Error(`fail`) } const rejectService = async (): Promise<void> => Promise.reject(`fail`) const machine = developMachine.withConfig( { actions, services, }, { program: {} as IProgram, } ) const tick = (): Promise<void> => new Promise(resolve => setTimeout(resolve, 0)) const resetMocks = (mocks: Record<string, jest.Mock>): void => Object.values(mocks).forEach(mock => mock.mockReset()) const resetAllMocks = (): void => { resetMocks(services) resetMocks(actions) } describe(`the top-level develop state machine`, () => { beforeEach(() => { resetAllMocks() }) it(`initialises`, async () => { const service = interpret(machine) service.start() expect(service.state.value).toBe(`initializing`) }) it(`runs node mutation during initialising data state`, () => { const payload = { foo: 1 } const service = interpret(machine) service.start() service.send(`done.invoke.initialize`) expect(service.state.value).toBe(`initializingData`) service.send(`ADD_NODE_MUTATION`, payload) expect(actions.callApi).toHaveBeenCalledWith( expect.anything(), expect.objectContaining({ type: `ADD_NODE_MUTATION`, ...payload }), expect.anything() ) }) it(`marks source file as dirty during node sourcing`, () => { const service = interpret(machine) service.start() expect(service.state.value).toBe(`initializing`) service.send(`done.invoke.initialize`) expect(service.state.value).toBe(`initializingData`) expect(service.state.context.sourceFilesDirty).toBeFalsy() service.send(`SOURCE_FILE_CHANGED`) expect(service.state.context.sourceFilesDirty).toBeTruthy() }) // This is current behaviour, but it will be queued in future it(`handles a webhook during node sourcing`, () => { const webhookBody = { foo: 1 } const service = interpret(machine) service.start() expect(service.state.value).toBe(`initializing`) service.send(`done.invoke.initialize`) expect(service.state.value).toBe(`initializingData`) expect(service.state.context.webhookBody).toBeUndefined() service.send(`WEBHOOK_RECEIVED`, { payload: { webhookBody } }) expect(service.state.context.webhookBody).toEqual(webhookBody) expect(services.reloadData).toHaveBeenCalled() }) it(`runs a node mutation during query running and marks node as dirty`, () => { const payload = { foo: 1 } const service = interpret(machine) service.start() service.send(`done.invoke.initialize`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) expect(service.state.context.nodeMutationBatch).toBeUndefined() expect(service.state.context.nodesMutatedDuringQueryRun).toBeFalsy() service.send(`ADD_NODE_MUTATION`, { payload }) expect(service.state.context.nodesMutatedDuringQueryRun).toBeTruthy() expect(actions.callApi).toHaveBeenCalled() }) it(`increments the recompile count if nodes were mutated during query running`, () => { const payload = { foo: 1 } const service = interpret(machine) service.start() service.send(`done.invoke.initialize`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) service.send(`ADD_NODE_MUTATION`, { payload }) service.send(`done.invoke.run-queries`) expect( service.state.context.nodesMutatedDuringQueryRunRecompileCount ).toEqual(1) expect(service.state.context.nodesMutatedDuringQueryRun).toBeFalsy() }) it(`resets the recompile count if nodes were not mutated during query running`, () => { const service = interpret(machine) service.start() service.send(`done.invoke.initialize`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) service.state.context.compiler = {} as any service.state.context.nodesMutatedDuringQueryRunRecompileCount = 1 service.send(`done.invoke.run-queries`) expect( service.state.context.nodesMutatedDuringQueryRunRecompileCount ).toEqual(0) expect(service.state.context.nodesMutatedDuringQueryRun).toBeFalsy() }) it(`panics if the recompile count is above the limit`, () => { const payload = { foo: 1 } const service = interpret(machine) service.start() service.send(`done.invoke.initialize`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) service.send(`ADD_NODE_MUTATION`, { payload }) service.send(`done.invoke.run-queries`) for (let index = 0; index < 6; index++) { service.send(`done.invoke.recreate-pages`) service.send(`ADD_NODE_MUTATION`, { payload }) service.send(`done.invoke.run-queries`) } expect(actions.panicBecauseOfInfiniteLoop).toHaveBeenCalled() }) it(`starts webpack if there is no compiler`, () => { const service = interpret(machine) service.start() service.send(`done.invoke.initialize`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) expect(service.state.context.compiler).toBeUndefined() services.startWebpackServer.mockReset() service.send(`done.invoke.run-queries`) expect(services.startWebpackServer).toHaveBeenCalled() }) it(`recompiles if source files have changed`, () => { const service = interpret(machine) service.start() service.send(`done.invoke.initialize`) service.send(`SOURCE_FILE_CHANGED`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) // So we don't start webpack instead service.state.context.compiler = {} as any services.recompile.mockReset() service.send(`done.invoke.run-queries`) expect(services.startWebpackServer).not.toHaveBeenCalled() expect(services.recompile).toHaveBeenCalled() }) it(`skips compilation if source files are unchanged`, () => { const service = interpret(machine) service.start() service.send(`done.invoke.initialize`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) service.state.context.compiler = {} as any services.recompile.mockReset() service.send(`done.invoke.run-queries`) expect(services.startWebpackServer).not.toHaveBeenCalled() expect(services.recompile).not.toHaveBeenCalled() }) it(`recreates pages when waiting is complete`, () => { const service = interpret(machine) service.start() service.send(`done.invoke.initialize`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) service.state.context.compiler = {} as any service.send(`done.invoke.run-queries`) service.send(`done.invoke.waiting`) expect(services.recreatePages).toHaveBeenCalled() }) it(`extracts queries when waiting requests it`, () => { const service = interpret(machine) service.start() service.send(`done.invoke.initialize`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) service.state.context.compiler = {} as any service.send(`done.invoke.run-queries`) service.send(`EXTRACT_QUERIES_NOW`) expect(services.runQueries).toHaveBeenCalled() }) it(`panics on error during initialisation`, async () => { const service = interpret(machine) services.initialize.mockImplementationOnce(throwService) service.start() await tick() expect(actions.panic).toHaveBeenCalled() }) it(`panics on rejection during initialisation`, async () => { const service = interpret(machine) services.initialize.mockImplementationOnce(rejectService) service.start() await tick() expect(actions.panic).toHaveBeenCalled() }) it(`logs errors during sourcing and transitions to waiting`, async () => { const service = interpret(machine) services.initializeData.mockImplementationOnce(throwService) service.start() service.send(`done.invoke.initialize`) await tick() expect(actions.logError).toHaveBeenCalled() expect(service.state.value).toEqual(`waiting`) }) it(`logs errors during query running and transitions to waiting`, async () => { const service = interpret(machine) services.runQueries.mockImplementationOnce(throwService) service.start() service.send(`done.invoke.initialize`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) await tick() expect(actions.logError).toHaveBeenCalled() expect(service.state.value).toEqual(`waiting`) }) it(`panics on errors when launching webpack`, async () => { const service = interpret(machine) services.startWebpackServer.mockImplementationOnce(throwService) service.start() service.send(`done.invoke.initialize`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) service.send(`done.invoke.run-queries`) await tick() expect(actions.panic).toHaveBeenCalled() }) it(`logs errors during compilation and transitions to waiting`, async () => { const service = interpret(machine) services.recompile.mockImplementationOnce(throwService) service.start() service.send(`done.invoke.initialize`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) service.state.context.compiler = {} as any service.state.context.sourceFilesDirty = true service.send(`done.invoke.run-queries`) await tick() expect(actions.logError).toHaveBeenCalled() expect(service.state.value).toEqual(`waiting`) }) it(`panics on errors while waiting`, async () => { const service = interpret(machine) services.waitForMutations.mockImplementationOnce(throwService) service.start() service.send(`done.invoke.initialize`) service.send(`done.invoke.initialize-data`) service.send(`done.invoke.post-bootstrap`) service.state.context.compiler = {} as any service.send(`done.invoke.run-queries`) await tick() expect(actions.panic).toHaveBeenCalled() }) })
the_stack
import {normalizeUnit} from './conversions'; import {ExpressionNode, ExpressionTerm, FunctionNode, IdentNode, NumberNode, numberNode, OperatorNode, Percentage, Unit, ZERO} from './parsers'; export type Evaluatable<T> = Evaluator<T>|T; /** * A NumberNodeSequence is a vector of NumberNodes with a specified * sequence of units. */ export type NumberNodeSequence<T extends Array<Unit>, U = never> = { [I in keyof T]: NumberNode&{ unit: T[I]|U; }; }; export type Sparse<T> = { [I in keyof T]: null|T[I]; }; /** * Intrinsics describe the metadata required to do four things for any given * type of number-based CSS expression: * * 1. Establish the expected units of a final, evaluated result * 2. Provide a foundational value that percentages should scale against * 3. Describe the analog number values that correspond to various keywords * 4. Have an available concrete value to fallback to when needed * * Intrinsics must always specify a basis and the substitute values for the * keyword 'auto'. * * Intrinsics may optionally specify the substitute values for any additional * number of keywords. */ export interface Intrinsics<T extends Array<Unit> = []> { basis: NumberNodeSequence<T>; keywords: { auto: Sparse<NumberNodeSequence<T, Percentage>>; [index: string]: Sparse<NumberNodeSequence<T, Percentage>>; }; } const $evaluate = Symbol('evaluate'); const $lastValue = Symbol('lastValue'); /** * An Evaluator is used to derive a computed style from part (or all) of a CSS * expression AST. This construct is particularly useful for complex ASTs * containing function calls such as calc, var and env. Such styles could be * costly to re-evaluate on every frame (and in some cases we may try to do * that). The Evaluator construct allows us to mark sub-trees of the AST as * constant, so that only the dynamic parts are re-evaluated. It also separates * one-time AST preparation work from work that necessarily has to happen upon * each evaluation. */ export abstract class Evaluator<T> { /** * An Evaluatable is a NumberNode or an Evaluator that evaluates a NumberNode * as the result of invoking its evaluate method. This is mainly used to * ensure that CSS function nodes are cast to the corresponding Evaluators * that will resolve the result of the function, but is also used to ensure * that a percentage nested at arbitrary depth in the expression will always * be evaluated against the correct basis. */ static evaluatableFor( node: ExpressionTerm|Evaluator<NumberNode>, basis: NumberNode = ZERO): Evaluatable<NumberNode> { if (node instanceof Evaluator) { return node; } if (node.type === 'number') { if (node.unit === '%') { return new PercentageEvaluator(node as NumberNode<'%'>, basis); } return node; } switch ((node as FunctionNode).name.value) { case 'calc': return new CalcEvaluator(node as FunctionNode, basis); case 'env': return new EnvEvaluator(node as FunctionNode); } return ZERO; } /** * If the input is an Evaluator, returns the result of evaluating it. * Otherwise, returns the input. * * This is a helper to aide in resolving a NumberNode without conditionally * checking if the Evaluatable is an Evaluator everywhere. */ static evaluate<T extends NumberNode|IdentNode>(evaluatable: Evaluatable<T>): T { if (evaluatable instanceof Evaluator) { return evaluatable.evaluate(); } return evaluatable; } /** * If the input is an Evaluator, returns the value of its isConstant property. * Returns true for all other input values. */ static isConstant<T>(evaluatable: Evaluatable<T>): boolean { if (evaluatable instanceof Evaluator) { return evaluatable.isConstant; } return true; } /** * This method applies a set of structured intrinsic metadata to an evaluated * result from a parsed CSS-like string of expressions. Intrinsics provide * sufficient metadata (e.g., basis values, analogs for keywords) such that * omitted values in the input string can be backfilled, and keywords can be * converted to concrete numbers. * * The result of applying intrinsics is a tuple of NumberNode values whose * units match the units used by the basis of the intrinsics. * * The following is a high-level description of how intrinsics are applied: * * 1. Determine the value of 'auto' for the current term * 2. If there is no corresponding input value for this term, substitute the * 'auto' value. * 3. If the term is an IdentNode, treat it as a keyword and perform the * appropriate substitution. * 4. If the term is still null, fallback to the 'auto' value * 5. If the term is a percentage, apply it to the basis and return that * value * 6. Normalize the unit of the term * 7. If the term's unit does not match the basis unit, return the basis * value * 8. Return the term as is */ static applyIntrinsics<T extends Array<Unit>>( evaluated: Array<any>, intrinsics: Intrinsics<T>): NumberNodeSequence<T> { const {basis, keywords} = intrinsics; const {auto} = keywords; return basis.map<NumberNode>((basisNode, index) => { // Use an auto value if we have it, otherwise the auto value is the basis: const autoSubstituteNode = auto[index] == null ? basisNode : auto[index]; // If the evaluated nodes do not have a node at the current // index, fallback to the "auto" substitute right away: let evaluatedNode = evaluated[index] ? evaluated[index] : autoSubstituteNode; // Any ident node is considered a keyword: if (evaluatedNode.type === 'ident') { const keyword = evaluatedNode.value; // Substitute any keywords for concrete values first: if (keyword in keywords) { evaluatedNode = keywords[keyword][index]; } } // If we don't have a NumberNode at this point, fall back to whatever // is specified for auto: if (evaluatedNode == null || evaluatedNode.type === 'ident') { evaluatedNode = autoSubstituteNode; } // For percentages, we always apply the percentage to the basis value: if (evaluatedNode.unit === '%') { return numberNode( evaluatedNode.number / 100 * basisNode.number, basisNode.unit); } // Otherwise, normalize whatever we have: evaluatedNode = normalizeUnit(evaluatedNode, basisNode); // If the normalized units do not match, return the basis as a fallback: if (evaluatedNode.unit !== basisNode.unit) { return basisNode; } // Finally, return the evaluated node with intrinsics applied: return evaluatedNode; }) as NumberNodeSequence<T>; } /** * If true, the Evaluator will only evaluate its AST one time. If false, the * Evaluator will re-evaluate the AST each time that the public evaluate * method is invoked. */ get isConstant(): boolean { return false; } protected[$lastValue]: T|null = null; /** * This method must be implemented by subclasses. Its implementation should be * the actual steps to evaluate the AST, and should return the evaluated * result. */ protected abstract[$evaluate](): T; /** * Evaluate the Evaluator and return the result. If the Evaluator is constant, * the corresponding AST will only be evaluated once, and the result of * evaluating it the first time will be returned on all subsequent * evaluations. */ evaluate(): T { if (!this.isConstant || this[$lastValue] == null) { this[$lastValue] = this[$evaluate](); } return this[$lastValue]!; } } const $percentage = Symbol('percentage'); const $basis = Symbol('basis'); /** * A PercentageEvaluator scales a given basis value by a given percentage value. * The evaluated result is always considered to be constant. */ export class PercentageEvaluator extends Evaluator<NumberNode> { protected[$percentage]: NumberNode<'%'>; protected[$basis]: NumberNode; constructor(percentage: NumberNode<'%'>, basis: NumberNode) { super(); this[$percentage] = percentage; this[$basis] = basis; } get isConstant() { return true; } [$evaluate]() { return numberNode( this[$percentage].number / 100 * this[$basis].number, this[$basis].unit); } } const $identNode = Symbol('identNode'); /** * Evaluator for CSS-like env() functions. Currently, only one environment * variable is accepted as an argument for such functions: window-scroll-y. * * The env() Evaluator is explicitly dynamic because it always refers to * external state that changes as the user scrolls, so it should always be * re-evaluated to ensure we get the most recent value. * * Some important notes about this feature include: * * - There is no such thing as a "window-scroll-y" CSS environment variable in * any stable browser at the time that this comment is being written. * - The actual CSS env() function accepts a second argument as a fallback for * the case that the specified first argument isn't set; our syntax does not * support this second argument. * * @see https://developer.mozilla.org/en-US/docs/Web/CSS/env */ export class EnvEvaluator extends Evaluator<NumberNode> { protected[$identNode]: IdentNode|null = null; constructor(envFunction: FunctionNode) { super(); const identNode = envFunction.arguments.length ? envFunction.arguments[0].terms[0] : null; if (identNode != null && identNode.type === 'ident') { this[$identNode] = identNode; } } get isConstant(): boolean { return false; }; [$evaluate](): NumberNode { if (this[$identNode] != null) { switch (this[$identNode]!.value) { case 'window-scroll-y': const verticalScrollPosition = window.pageYOffset; const verticalScrollMax = Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight); const scrollY = verticalScrollPosition / (verticalScrollMax - window.innerHeight) || 0; return {type: 'number', number: scrollY, unit: null}; } } return ZERO; } } const IS_MULTIPLICATION_RE = /[\*\/]/; const $evaluator = Symbol('evalutor'); /** * Evaluator for CSS-like calc() functions. Our implementation of calc() * evaluation currently support nested function calls, an unlimited number of * terms, and all four algebraic operators (+, -, * and /). * * The Evaluator is marked as constant unless the calc expression contains an * internal env expression at any depth, in which case it will be marked as * dynamic. * * @see https://www.w3.org/TR/css-values-3/#calc-syntax * @see https://developer.mozilla.org/en-US/docs/Web/CSS/calc */ export class CalcEvaluator extends Evaluator<NumberNode> { protected[$evaluator]: Evaluator<NumberNode>|null = null; constructor(calcFunction: FunctionNode, basis: NumberNode = ZERO) { super(); if (calcFunction.arguments.length !== 1) { return; } const terms: Array<ExpressionTerm> = calcFunction.arguments[0].terms.slice(); const secondOrderTerms: Array<ExpressionTerm|Evaluator<NumberNode>> = []; while (terms.length) { const term: ExpressionTerm = terms.shift()!; if (secondOrderTerms.length > 0) { const previousTerm = secondOrderTerms[secondOrderTerms.length - 1] as ExpressionTerm; if (previousTerm.type === 'operator' && IS_MULTIPLICATION_RE.test(previousTerm.value)) { const operator = secondOrderTerms.pop() as OperatorNode; const leftValue = secondOrderTerms.pop(); if (leftValue == null) { return; } secondOrderTerms.push(new OperatorEvaluator( operator, Evaluator.evaluatableFor(leftValue, basis), Evaluator.evaluatableFor(term, basis))); continue; } } secondOrderTerms.push( term.type === 'operator' ? term : Evaluator.evaluatableFor(term, basis)); } while (secondOrderTerms.length > 2) { const [left, operator, right] = secondOrderTerms.splice(0, 3); if ((operator as ExpressionTerm).type !== 'operator') { return; } secondOrderTerms.unshift(new OperatorEvaluator( operator as OperatorNode, Evaluator.evaluatableFor(left, basis), Evaluator.evaluatableFor(right, basis))); } // There should only be one combined evaluator at this point: if (secondOrderTerms.length === 1) { this[$evaluator] = secondOrderTerms[0] as Evaluator<NumberNode>; } } get isConstant() { return this[$evaluator] == null || Evaluator.isConstant(this[$evaluator]!); } [$evaluate]() { return this[$evaluator] != null ? Evaluator.evaluate(this[$evaluator]!) : ZERO; } } const $operator = Symbol('operator'); const $left = Symbol('left'); const $right = Symbol('right'); /** * An Evaluator for the operators found inside CSS calc() functions. * The evaluator accepts an operator and left/right operands. The operands can * be any valid expression term typically allowed inside a CSS calc function. * * As detail of this implementation, the only supported unit types are angles * expressed as radians or degrees, and lengths expressed as meters, centimeters * or millimeters. * * @see https://developer.mozilla.org/en-US/docs/Web/CSS/calc */ export class OperatorEvaluator extends Evaluator<NumberNode> { protected[$operator]: OperatorNode; protected[$left]: Evaluatable<NumberNode>; protected[$right]: Evaluatable<NumberNode>; constructor( operator: OperatorNode, left: Evaluatable<NumberNode>, right: Evaluatable<NumberNode>) { super(); this[$operator] = operator; this[$left] = left; this[$right] = right; } get isConstant() { return Evaluator.isConstant(this[$left]) && Evaluator.isConstant(this[$right]); } [$evaluate](): NumberNode { const leftNode = normalizeUnit(Evaluator.evaluate(this[$left])); const rightNode = normalizeUnit(Evaluator.evaluate(this[$right])); const {number: leftValue, unit: leftUnit} = leftNode; const {number: rightValue, unit: rightUnit} = rightNode; // Disallow operations for mismatched normalized units e.g., m and rad: if (rightUnit != null && leftUnit != null && rightUnit != leftUnit) { return ZERO; } // NOTE(cdata): rules for calc type checking are defined here // https://drafts.csswg.org/css-values-3/#calc-type-checking // This is a simplification and may not hold up once we begin to support // additional unit types: const unit = leftUnit || rightUnit; let value; switch (this[$operator].value) { case '+': value = leftValue + rightValue; break; case '-': value = leftValue - rightValue; break; case '/': value = leftValue / rightValue; break; case '*': value = leftValue * rightValue; break; default: return ZERO; } return {type: 'number', number: value, unit}; } } export type EvaluatedStyle<T extends Intrinsics<Array<Unit>>> = { [I in keyof T['basis']]: number; }&Array<never>; const $evaluatables = Symbol('evaluatables'); const $intrinsics = Symbol('intrinsics'); /** * A VectorEvaluator evaluates a series of numeric terms that usually represent * a data structure such as a multi-dimensional vector or a spherical * * The form of the evaluator's result is determined by the Intrinsics that are * given to it when it is constructed. For example, spherical intrinsics would * establish two angle terms and a length term, so the result of evaluating the * evaluator that is configured with spherical intrinsics is a three element * array where the first two elements represent angles in radians and the third * element representing a length in meters. */ export class StyleEvaluator<T extends Intrinsics<Array<any>>> extends Evaluator<EvaluatedStyle<T>> { protected[$intrinsics]: T; protected[$evaluatables]: Array<Evaluatable<NumberNode|IdentNode>>; constructor(expressions: Array<ExpressionNode>, intrinsics: T) { super(); this[$intrinsics] = intrinsics; const firstExpression = expressions[0]; const terms = firstExpression != null ? firstExpression.terms : []; this[$evaluatables] = intrinsics.basis.map<Evaluatable<NumberNode|IdentNode>>( (basisNode, index) => { const term = terms[index]; if (term == null) { return {type: 'ident', value: 'auto'}; } if (term.type === 'ident') { return term; } return Evaluator.evaluatableFor(term, basisNode); }); } get isConstant(): boolean { for (const evaluatable of this[$evaluatables]) { if (!Evaluator.isConstant(evaluatable)) { return false; } } return true; } [$evaluate]() { const evaluated = this[$evaluatables].map<NumberNode|IdentNode>( evaluatable => Evaluator.evaluate(evaluatable)); return Evaluator.applyIntrinsics(evaluated, this[$intrinsics]) .map<number>(numberNode => numberNode.number) as EvaluatedStyle<T>; } } // SphericalIntrinsics are Intrinsics that expect two angle terms // and one length term export type SphericalIntrinsics = Intrinsics<['rad', 'rad', 'm']>; // Vector3Intrinsics expect three length terms export type Vector3Intrinsics = Intrinsics<['m', 'm', 'm']>;
the_stack
import * as assert from 'assert'; import * as fs from 'fs-extra'; import * as path from 'path'; import * as sinon from 'sinon'; import { Constants } from '../src/Constants'; import { TruffleConfiguration } from '../src/helpers'; import * as helpers from '../src/helpers'; import * as commands from '../src/helpers/command'; import { ICommandResult } from '../src/helpers/command'; import * as testData from './testData/truffleConfigTestdata'; describe('TruffleConfiguration helper', () => { afterEach(() => { sinon.restore(); }); it('generateMnemonic should return correct sequence', async () => { // Act const result = TruffleConfiguration.generateMnemonic(); // Assert // 11 spaces + 12 words, 1 word = at least 1 char assert.strictEqual(result.length > 23, true, 'result length should be greater than 23'); assert.strictEqual(result.split(' ').length, 12, 'number of words should be equal to 12'); }); it('getTruffleConfigUri returns correct value and check path for existence', async () => { // Arrange const referencePath = path.normalize('w:/temp/truffle-config.js'); sinon.stub(helpers, 'getWorkspaceRoot').returns(path.normalize('w:/temp')); const pathExistsStub = sinon.stub(fs, 'pathExistsSync').returns(true); // Act const result = TruffleConfiguration.getTruffleConfigUri(); // Assert assert.strictEqual(result, referencePath, 'result should be correct uri'); assert.strictEqual(pathExistsStub.calledOnce, true, 'pathExists should called once'); }); it('getTruffleConfigUri throw an exception if path is not existed', async () => { // Arrange sinon.stub(helpers, 'getWorkspaceRoot').returns(''); sinon.stub(fs, 'pathExistsSync').returns(false); // Act and Assert assert.throws(TruffleConfiguration.getTruffleConfigUri); }); }); describe('class TruffleConfig', () => { const configPathStub = path.normalize('w:/temp/truffle-config.js'); let readFileStub: sinon.SinonStub<any, any>; let writeFileStub: sinon.SinonStub<any, any>; before(() => { readFileStub = sinon.stub(fs, 'readFileSync'); writeFileStub = sinon.stub(fs, 'writeFileSync'); readFileStub.withArgs(configPathStub).returns(testData.referenceCfgContent); readFileStub.withArgs('path').returns(testData.referenceMnemonic); readFileStub.withArgs('path', 'encoding').returns(testData.referenceMnemonic); }); after(() => { sinon.restore(); }); afterEach(() => { sinon.resetHistory(); }); it('getAST should load correct AST', async () => { // Arrange // Act const result = (new TruffleConfiguration.TruffleConfig(configPathStub)).getAST(); // Assert assert.deepEqual(result, testData.referenceAstObject, 'result should be equal to expected result'); assert.strictEqual(readFileStub.callCount > 0, true, 'readFile should called more then 0 times'); assert.strictEqual( readFileStub.getCall(0).args[0], configPathStub, 'readFile should called with correct arguments'); }); it('writeAST should write ast content to file', async () => { // Arrange // Act const truffleConfig = new TruffleConfiguration.TruffleConfig(configPathStub); truffleConfig.getAST(); truffleConfig.writeAST(); // Assert assert.strictEqual(writeFileStub.callCount > 0, true, 'writeFile should called more then 0 times'); assert.strictEqual( writeFileStub.getCall(0).args[0], configPathStub, 'writeFile should called with correct arguments'); assert.strictEqual(// 60 - first line, to avoid EOL differences writeFileStub.getCall(0).args[1].substring(0, 60), testData.referenceCfgContent.substring(0, 60), 'writeFile should called with correct arguments', ); }); it('getNetworks should returns correct networks', async () => { // Arrange const truffleConfig = new TruffleConfiguration.TruffleConfig(configPathStub); // Act const result = truffleConfig.getNetworks(); // Assert assert.deepStrictEqual( result[0], testData.referenceConfiguration.networks[0], 'result first item should be equal to expected network'); assert.deepStrictEqual( result[1], testData.referenceConfiguration.networks[1], 'result second item should be equal to expected network'); }); it('setNetworks should add a network item', async () => { // Arrange const truffleConfig = new TruffleConfiguration.TruffleConfig(configPathStub); const newNetwork = { name: 'newNetworkName', options: { network_id: 'ntwrk', }, }; // Act const resultBefore = truffleConfig.getNetworks(); truffleConfig.setNetworks(newNetwork); const resultAfter = truffleConfig.getNetworks(); // Assert assert.strictEqual(resultBefore.length, 2, 'before execution should be 2 networks'); assert.strictEqual(resultAfter.length, 3, 'after execution should be 2 networks'); assert.deepStrictEqual(resultAfter[2], newNetwork, 'last network should be equal to test network'); }); it('setNetworks should threw an exception if network already existed', async () => { // Arrange const truffleConfig = new TruffleConfiguration.TruffleConfig(configPathStub); const newNetwork = { name: 'development', options: { network_id: 'ntwrk', }, }; const action = () => { truffleConfig.setNetworks(newNetwork); }; // Act and Assert assert.throws(action); }); it('importFs should add correct import line', async () => { // Arrange const truffleConfig = new TruffleConfiguration.TruffleConfig(configPathStub); // Act truffleConfig.importPackage('fs', 'fs'); // Assert const configContent = writeFileStub.getCall(0).args[1]; assert.strictEqual( configContent.includes('fs = require(\'fs\');'), true, 'configContent should include test string'); }); }); describe('getConfiguration() in class TruffleConfig', () => { const configPathStub = path.normalize('w:/temp/truffle-config.js'); let readFileStub: sinon.SinonStub<any, any>; beforeEach(() => { sinon.stub(helpers, 'getWorkspaceRoot').returns(path.normalize('w:/temp')); readFileStub = sinon.stub(fs, 'readFileSync'); readFileStub.withArgs('path').returns(testData.referenceMnemonic); readFileStub.withArgs('path, encoding').returns(testData.referenceMnemonic); }); afterEach(() => { sinon.restore(); }); it('getConfiguration returns configurations without directories and networks', async () => { // Arrange const { contracts_directory, contracts_build_directory, migrations_directory } = Constants.truffleConfigDefaultDirectory; const commandResult: ICommandResult = { cmdOutput: '', cmdOutputIncludingStderr: '', code: 0, messages: [{command: 'truffleConfig', message: '{}'}], }; sinon.stub(commands, 'tryExecuteCommandInFork').returns(Promise.resolve(commandResult)); readFileStub.returns(''); const truffleConfig = new TruffleConfiguration.TruffleConfig(configPathStub); // Act const result = await truffleConfig.getConfiguration(); // Assert assert.strictEqual( result.contracts_build_directory, path.normalize(contracts_build_directory), 'result should contain contracts build directory'); assert.strictEqual( result.contracts_directory, contracts_directory, 'result should contain contracts directory'); assert.strictEqual( result.migrations_directory, migrations_directory, 'result should contain migration build directory'); assert.strictEqual(result.networks?.length, 0, 'result.networks should be empty array'); }); it('getConfiguration returns configurations with directories and without networks', async () => { // Arrange const expectedContractsBuildDirectory = '123'; const expectedContractsDirectory = '234'; const expectedMigrationsDirector = '345'; const commandResult: ICommandResult = { cmdOutput: '', cmdOutputIncludingStderr: '', code: 0, messages: [{command: 'truffleConfig', message: `{"contracts_build_directory": "${expectedContractsBuildDirectory}", ` + `"contracts_directory": "${expectedContractsDirectory}", ` + `"migrations_directory": "${expectedMigrationsDirector}"}`}], }; sinon.stub(commands, 'tryExecuteCommandInFork').returns(Promise.resolve(commandResult)); readFileStub.returns(''); const truffleConfig = new TruffleConfiguration.TruffleConfig(configPathStub); // Act const result = await truffleConfig.getConfiguration(); // Assert assert.strictEqual( result.contracts_build_directory, expectedContractsBuildDirectory, 'result should contain contracts build directory'); assert.strictEqual( result.contracts_directory, expectedContractsDirectory, 'result should contain contracts directory'); assert.strictEqual( result.migrations_directory, expectedMigrationsDirector, 'result should contain migration build directory'); assert.strictEqual(result.networks?.length, 0, 'result.networks should be empty array'); }); it('getConfiguration returns configurations with networks', async () => { // Arrange const testNetworkOptions = '{"development":{"host":"127.0.0.1","port":8545,"network_id":"*"}}'; const testNetwork = `{"networks": ${testNetworkOptions}}`; const parseTestNetworkOptions = JSON.parse(testNetworkOptions); const commandResult: ICommandResult = { cmdOutput: '', cmdOutputIncludingStderr: '', code: 0, messages: [{command: 'truffleConfig', message: testNetwork}], }; sinon.stub(commands, 'tryExecuteCommandInFork').returns(Promise.resolve(commandResult)); readFileStub.returns(''); const truffleConfig = new TruffleConfiguration.TruffleConfig(configPathStub); // Act const result = await truffleConfig.getConfiguration(); // Assert const networkKey = Object.keys(parseTestNetworkOptions)[0]; assert.strictEqual(result.networks?.length, 1, 'result.networks should not be empty array'); assert.strictEqual( result.networks && result.networks[0].name, networkKey, 'networks should have specific name'); assert.deepStrictEqual( result.networks && result.networks[0].options, parseTestNetworkOptions[networkKey], 'networks should have specific options'); }); it('getConfiguration throws error when truffle-config.js has incorrect format', async () => { // Arrange const commandResult: ICommandResult = { cmdOutput: '', cmdOutputIncludingStderr: '', code: 0, messages: [{command: 'truffleConfig', message: undefined}], }; sinon.stub(commands, 'tryExecuteCommandInFork').returns(Promise.resolve(commandResult)); readFileStub.returns(''); const truffleConfig = new TruffleConfiguration.TruffleConfig(configPathStub); // Act, Assert try { await truffleConfig.getConfiguration(); } catch (error) { assert.strictEqual(error.message, Constants.errorMessageStrings.TruffleConfigHasIncorrectFormat, 'getConfiguration should throw error'); } }); });
the_stack
import React from 'react'; import Conversations from './collections/conversations/collection'; import { Posts } from './collections/posts'; import { postGetAuthorName } from './collections/posts/helpers'; import { Comments } from './collections/comments/collection'; import { commentGetAuthorName } from './collections/comments/helpers'; import { TagRels } from './collections/tagRels/collection'; import { Tags } from './collections/tags/collection'; import Messages from './collections/messages/collection'; import Localgroups from './collections/localgroups/collection'; import Users from './collections/users/collection'; import AllIcon from '@material-ui/icons/Notifications'; import PostsIcon from '@material-ui/icons/Description'; import CommentsIcon from '@material-ui/icons/ModeComment'; import EventIcon from '@material-ui/icons/Event'; import MailIcon from '@material-ui/icons/Mail'; import StarIcon from '@material-ui/icons/Star'; import { responseToText } from '../components/posts/PostsPage/RSVPForm'; import sortBy from 'lodash/sortBy'; import { REVIEW_NAME_IN_SITU } from './reviewUtils'; import SupervisedUserCircleIcon from '@material-ui/icons/SupervisedUserCircle'; import GroupAddIcon from '@material-ui/icons/GroupAdd'; import DoneIcon from '@material-ui/icons/Done'; interface NotificationType { name: string userSettingField: keyof DbUser|null mustBeEnabled?: boolean, getMessage: (args: {documentType: string|null, documentId: string|null})=>Promise<string> getIcon: ()=>React.ReactNode } const notificationTypes: Record<string,NotificationType> = {}; const notificationTypesByUserSetting: Partial<Record<keyof DbUser, NotificationType>> = {}; export const getNotificationTypes = () => { return Object.keys(notificationTypes); } export const getNotificationTypeByName = (name: string) => { if (name in notificationTypes) return notificationTypes[name]; else throw new Error(`Invalid notification type: ${name}`); } export const getNotificationTypeByUserSetting = (settingName: keyof DbUser): NotificationType => { const result = notificationTypesByUserSetting[settingName]; if (!result) throw new Error("Setting does not correspond to a notification type"); return result; } const registerNotificationType = (notificationTypeClass: NotificationType) => { const name = notificationTypeClass.name; notificationTypes[name] = notificationTypeClass; if (notificationTypeClass.userSettingField) notificationTypesByUserSetting[notificationTypeClass.userSettingField] = notificationTypeClass; return notificationTypeClass; } const getDocument = async (documentType: string|null, documentId: string|null) => { if (!documentId) return null; switch(documentType) { case "post": return await Posts.findOne(documentId); case "comment": return await Comments.findOne(documentId); case "user": return await Users.findOne(documentId); case "message": return await Messages.findOne(documentId); case "tagRel": return await TagRels.findOne(documentId); default: //eslint-disable-next-line no-console console.error(`Invalid documentType type: ${documentType}`); } } const iconStyles = { margin: 16, fontSize: 20, } export const NewPostNotification = registerNotificationType({ name: "newPost", userSettingField: "notificationSubscribedUserPost", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document: DbPost = await getDocument(documentType, documentId) as DbPost; return await postGetAuthorName(document) + ' has created a new post: ' + document.title; }, getIcon() { return <PostsIcon style={iconStyles}/> }, }); // Vulcan notification that we don't really use export const PostApprovedNotification = registerNotificationType({ name: "postApproved", userSettingField: null, //TODO async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document: DbPost = await getDocument(documentType, documentId) as DbPost; return 'Your post "' + document.title + '" has been approved'; }, getIcon() { return <AllIcon style={iconStyles} /> }, }); export const PostNominatedNotification = registerNotificationType({ name: "postNominated", userSettingField: "notificationPostsNominatedReview", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let post: DbPost = await getDocument(documentType, documentId) as DbPost; return `Your post is nominated for the ${REVIEW_NAME_IN_SITU}: "${post.title}"` }, getIcon() { return <StarIcon style={iconStyles} /> } }) export const NewEventNotification = registerNotificationType({ name: "newEvent", userSettingField: "notificationPostsInGroups", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document = await getDocument(documentType, documentId); let group: DbLocalgroup|null = null if (documentType == "post") { const post = document as DbPost if (post.groupId) { group = await Localgroups.findOne(post.groupId); } } if (group) return `${group.name} posted a new event`; else return await postGetAuthorName(document as DbPost) + ' has created a new event'; }, getIcon() { return <AllIcon style={iconStyles} /> }, }); export const NewGroupPostNotification = registerNotificationType({ name: "newGroupPost", userSettingField: "notificationPostsInGroups", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document = await getDocument(documentType, documentId); let group: DbLocalgroup|null = null if (documentType == "post") { const post = document as DbPost if (post.groupId) { group = await Localgroups.findOne(post.groupId); } } if (group) return await postGetAuthorName(document as DbPost) + ' has created a new post in the group "' + group.name + '"'; else return await postGetAuthorName(document as DbPost) + ' has created a new post in a group'; }, getIcon() { return <AllIcon style={iconStyles} /> }, }); // New comment on a post you're subscribed to. export const NewCommentNotification = registerNotificationType({ name: "newComment", userSettingField: "notificationCommentsOnSubscribedPost", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document = await getDocument(documentType, documentId) as DbComment; return await commentGetAuthorName(document) + ' left a new comment on "' + await getCommentParentTitle(document) + '"'; }, getIcon() { return <CommentsIcon style={iconStyles}/> }, }); export const NewShortformNotification = registerNotificationType({ name: "newShortform", userSettingField: "notificationShortformContent", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document = await getDocument(documentType, documentId) as DbComment; return 'New comment on "' + await getCommentParentTitle(document) + '"'; }, getIcon() { return <CommentsIcon style={iconStyles}/> }, }); export const taggedPostMessage = async ({documentType, documentId}: {documentType: string|null, documentId: string|null}) => { const tagRel = await getDocument(documentType, documentId) as DbTagRel; const tag = await Tags.findOne({_id: tagRel.tagId}) const post = await Posts.findOne({_id: tagRel.postId}) return `New post tagged '${tag?.name}: ${post?.title}'` } export const NewTagPostsNotification = registerNotificationType({ name: "newTagPosts", userSettingField: "notificationSubscribedTagPost", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { return await taggedPostMessage({documentType, documentId}) }, getIcon() { return <PostsIcon style={iconStyles}/> }, }); export async function getCommentParentTitle(comment: DbComment) { if (comment.postId) return (await Posts.findOne(comment.postId))?.title if (comment.tagId) return (await Tags.findOne(comment.tagId))?.name return "Unknown Parent" } // Reply to a comment you're subscribed to. export const NewReplyNotification = registerNotificationType({ name: "newReply", userSettingField: "notificationRepliesToSubscribedComments", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document = await getDocument(documentType, documentId) as DbComment; return await commentGetAuthorName(document) + ' replied to a comment on "' + await getCommentParentTitle(document) + '"'; }, getIcon() { return <CommentsIcon style={iconStyles}/> }, }); // Reply to a comment you are the author of. export const NewReplyToYouNotification = registerNotificationType({ name: "newReplyToYou", userSettingField: "notificationRepliesToMyComments", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document = await getDocument(documentType, documentId) as DbComment; return await commentGetAuthorName(document) + ' replied to your comment on "' + await getCommentParentTitle(document) + '"'; }, getIcon() { return <CommentsIcon style={iconStyles}/> }, }); // Vulcan notification that we don't really use export const NewUserNotification = registerNotificationType({ name: "newUser", userSettingField: null, async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document = await getDocument(documentType, documentId) as DbUser; return document.displayName + ' just signed up!'; }, getIcon() { return <AllIcon style={iconStyles} /> }, }); export const NewMessageNotification = registerNotificationType({ name: "newMessage", userSettingField: "notificationPrivateMessage", mustBeEnabled: true, async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document = await getDocument(documentType, documentId) as DbMessage; let conversation = await Conversations.findOne(document.conversationId); return (await Users.findOne(document.userId))?.displayName + ' sent you a new message' + (conversation?.title ? (' in the conversation ' + conversation.title) : "") + '!'; }, getIcon() { return <MailIcon style={iconStyles}/> }, }); // TODO(EA): Fix notificationCallbacks getLink, or the associated component to // be EA-compatible. Currently we just disable it in the new user callback. export const EmailVerificationRequiredNotification = registerNotificationType({ name: "emailVerificationRequired", userSettingField: null, async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { return "Verify your email address to activate email subscriptions."; }, getIcon() { return <AllIcon style={iconStyles} /> }, }); export const PostSharedWithUserNotification = registerNotificationType({ name: "postSharedWithUser", userSettingField: "notificationSharedWithMe", mustBeEnabled: true, async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document = await getDocument(documentType, documentId) as DbPost; return `You have been shared on the ${document.draft ? "draft" : "post"} ${document.title}`; }, getIcon() { return <AllIcon style={iconStyles} /> }, }); export const AlignmentSubmissionApprovalNotification = registerNotificationType({ name: "alignmentSubmissionApproved", userSettingField: "notificationAlignmentSubmissionApproved", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { if (documentType==='comment') { return "Your comment has been accepted to the Alignment Forum"; } else if (documentType==='post') { let post = await getDocument(documentType, documentId) as DbPost return `Your post has been accepted to the Alignment Forum: ${post.title}` } else throw new Error("documentType must be post or comment!") }, getIcon() { return <AllIcon style={iconStyles} /> }, }); export const NewEventInNotificationRadiusNotification = registerNotificationType({ name: "newEventInRadius", userSettingField: "notificationEventInRadius", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document = await getDocument(documentType, documentId) as DbPost return `New event in your area: ${document.title}` }, getIcon() { return <EventIcon style={iconStyles} /> } }) export const EditedEventInNotificationRadiusNotification = registerNotificationType({ name: "editedEventInRadius", userSettingField: "notificationEventInRadius", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { let document = await getDocument(documentType, documentId) as DbPost return `Event in your area updated: ${document.title}` }, getIcon() { return <EventIcon style={iconStyles} /> } }) export const NewRSVPNotification = registerNotificationType({ name: "newRSVP", userSettingField: "notificationRSVPs", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { const document = await getDocument(documentType, documentId) as DbPost const rsvps = document.rsvps || [] const lastRSVP = sortBy(rsvps, r => r.createdAt)[rsvps.length - 1] return `${lastRSVP.name} responded "${responseToText[lastRSVP.response]}" to your event ${document.title}` }, getIcon() { return <EventIcon style={iconStyles} /> } }) export const NewGroupOrganizerNotification = registerNotificationType({ name: "newGroupOrganizer", userSettingField: "notificationGroupAdministration", async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { if (documentType !== 'localgroup') throw new Error("documentType must be localgroup") const localGroup = await Localgroups.findOne(documentId) if (!localGroup) throw new Error("Cannot find local group for which this notification is being sent") return `You've been added as an organizer of ${localGroup.name}` }, getIcon() { return <SupervisedUserCircleIcon style={iconStyles} /> } }) export const CoauthorRequestNotification = registerNotificationType({ name: 'coauthorRequestNotification', userSettingField: 'notificationSharedWithMe', async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { const document = await getDocument(documentType, documentId) as DbPost; const name = await postGetAuthorName(document); return `${name} requested that you co-author their post: ${document.title}`; }, getIcon() { return <GroupAddIcon style={iconStyles} /> }, }) export const CoauthorAcceptNotification = registerNotificationType({ name: 'coauthorAcceptNotification', userSettingField: 'notificationSharedWithMe', async getMessage({documentType, documentId}: {documentType: string|null, documentId: string|null}) { const document = await getDocument(documentType, documentId) as DbPost; return `Your co-author request for '${document.title}' was accepted`; }, getIcon() { return <DoneIcon style={iconStyles} /> }, })
the_stack
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { CustomValidators } from './../shared/validation/validators'; import { ShopEventBus, PricingService, UserEventBus, Util } from './../shared/services/index'; import { PromotionTestConfigComponent } from './components/index'; import { ModalComponent, ModalResult, ModalAction } from './../shared/modal/index'; import { ProductSkuSelectComponent } from './../shared/catalog/index'; import { CarrierSlaSelectComponent } from './../shared/shipping/index'; import { CountrySelectComponent, CountryStateSelectComponent } from './../shared/shipping/index'; import { TaxSelectComponent } from './../shared/price/index'; import { TaxVO, ShopVO, TaxConfigVO, PromotionTestVO, CartVO, ProductSkuVO, CarrierSlaInfoVO, CountryInfoVO, StateVO, Pair, SearchResultVO } from './../shared/model/index'; import { FormValidationEvent, Futures, Future } from './../shared/event/index'; import { Config } from './../../environments/environment'; import { UiUtil } from './../shared/ui/index'; import { LogUtil } from './../shared/log/index'; import { StorageUtil } from './../shared/storage/index'; @Component({ selector: 'cw-shop-taxconfigs', templateUrl: 'shop-taxconfigs.component.html', }) export class ShopTaxConfigsComponent implements OnInit, OnDestroy { private static COOKIE_SHOP:string = 'ADM_UI_TAX_SHOP'; private static COOKIE_CURRENCY:string = 'ADM_UI_TAX_CURR'; private static _selectedShopCode:string; private static _selectedShop:ShopVO; private static _selectedCurrency:string; private static CONFIGS:string = 'taxconfigs'; private static PRICELIST_TEST:string = 'pricelisttest'; public searchHelpTaxConfigShow:boolean = false; public forceShowAll:boolean = false; public viewMode:string = ShopTaxConfigsComponent.CONFIGS; public taxconfigs:SearchResultVO<TaxConfigVO>; public taxconfigsFilter:string; public taxconfigsFilterRequired:boolean = true; private delayedFilteringTaxConfig:Future; private delayedFilteringMs:number = Config.UI_INPUT_DELAY; public selectedTaxconfig:TaxConfigVO; public taxconfigEdit:TaxConfigVO; public taxconfigEditForm:any; public validForSaveTaxconfig:boolean = true; @ViewChild('deleteConfirmationModalDialog') private deleteConfirmationModalDialog:ModalComponent; @ViewChild('editTaxconfigModalDialog') private editTaxconfigModalDialog:ModalComponent; @ViewChild('selectShopModalDialog') private selectShopModalDialog:ModalComponent; @ViewChild('selectCurrencyModalDialog') private selectCurrencyModalDialog:ModalComponent; @ViewChild('selectProductModalSkuDialog') private selectProductModalSkuDialog:ProductSkuSelectComponent; @ViewChild('carrierSlaSelectDialog') private carrierSlaSelectDialog:CarrierSlaSelectComponent; @ViewChild('selectCountryModalDialog') private selectCountryModalDialog:CountrySelectComponent; @ViewChild('selectStateModalDialog') private selectStateModalDialog:CountryStateSelectComponent; @ViewChild('selectTaxModalDialog') private selectTaxModalDialog:TaxSelectComponent; @ViewChild('runTestModalDialog') private runTestModalDialog:PromotionTestConfigComponent; public deleteValue:String; public loading:boolean = false; public testCart:CartVO; private userSub:any; constructor(private _taxService:PricingService, fb: FormBuilder) { LogUtil.debug('ShopTaxConfigsComponent constructed'); this.taxconfigEditForm = fb.group({ 'productCode': ['', CustomValidators.validCode], 'stateCode': ['', CustomValidators.nonBlankTrimmed64], 'countryCode': ['', CustomValidators.validCountryCode], 'tax': ['', Validators.required], }); this.taxconfigs = this.newSearchResultInstance(); } get selectedShop():ShopVO { return ShopTaxConfigsComponent._selectedShop; } set selectedShop(selectedShop:ShopVO) { ShopTaxConfigsComponent._selectedShop = selectedShop; } get selectedShopCode(): string { return ShopTaxConfigsComponent._selectedShopCode; } set selectedShopCode(value: string) { ShopTaxConfigsComponent._selectedShopCode = value; } get selectedCurrency():string { return ShopTaxConfigsComponent._selectedCurrency; } set selectedCurrency(selectedCurrency:string) { ShopTaxConfigsComponent._selectedCurrency = selectedCurrency; } newInstance():TaxConfigVO { return { taxConfigId: 0, tax: null, productCode: null, stateCode: null, countryCode: null, guid: null}; //return { taxConfigId: 0, taxId: this.selectedTax, productCode: null, stateCode: null, countryCode: null, guid: null}; } newSearchResultInstance():SearchResultVO<TaxConfigVO> { return { searchContext: { parameters: { filter: [] }, start: 0, size: Config.UI_TABLE_PAGE_SIZE, sortBy: null, sortDesc: false }, items: [], total: 0 }; } ngOnInit() { LogUtil.debug('ShopTaxConfigsComponent ngOnInit'); this.onRefreshHandler(); this.userSub = UserEventBus.getUserEventBus().userUpdated$.subscribe(user => { this.presetFromCookie(); }); let that = this; this.delayedFilteringTaxConfig = Futures.perpetual(function() { that.getFilteredTaxConfig(); }, this.delayedFilteringMs); this.formBind(); } ngOnDestroy() { LogUtil.debug('ShopTaxConfigsComponent ngOnDestroy'); this.formUnbind(); if (this.userSub) { this.userSub.unsubscribe(); } } formBind():void { UiUtil.formBind(this, 'taxconfigEditForm', 'formChangeTaxconfig', false); } formUnbind():void { UiUtil.formUnbind(this, 'taxconfigEditForm'); } formChangeTaxconfig():void { LogUtil.debug('ShopTaxConfigsComponent formChangeTaxconfig', this.taxconfigEditForm.valid, this.taxconfigEdit); this.validForSaveTaxconfig = this.taxconfigEditForm.valid; } presetFromCookie() { if (this.selectedShop == null) { let shopCode = StorageUtil.readValue(ShopTaxConfigsComponent.COOKIE_SHOP, null); if (shopCode != null) { let shops = ShopEventBus.getShopEventBus().currentAll(); if (shops != null) { shops.forEach(shop => { if (shop.code == shopCode) { this.selectedShop = shop; this.selectedShopCode = shop.code; LogUtil.debug('ShopTaxConfigsComponent ngOnInit presetting shop from cookie', shop); } }); } } } if (this.selectedCurrency == null) { let curr = StorageUtil.readValue(ShopTaxConfigsComponent.COOKIE_CURRENCY, null); if (curr != null) { this.selectedCurrency = curr; LogUtil.debug('ShopTaxConfigsComponent ngOnInit presetting currency from cookie', curr); } } } onShopSelect() { LogUtil.debug('ShopTaxConfigsComponent onShopSelect'); this.selectShopModalDialog.show(); } onShopSelected(event:ShopVO) { LogUtil.debug('ShopTaxConfigsComponent onShopSelected'); this.selectedShop = event; if (this.selectedShop != null) { this.selectedShopCode = event.code; StorageUtil.saveValue(ShopTaxConfigsComponent.COOKIE_SHOP, this.selectedShop.code); } else { this.selectedShopCode = null; } } onSelectShopResult(modalresult: ModalResult) { LogUtil.debug('ShopTaxConfigsComponent onSelectShopResult modal result is ', modalresult); if (this.selectedShop == null) { this.selectShopModalDialog.show(); } else if (this.selectedCurrency == null) { this.selectCurrencyModalDialog.show(); } else { this.getFilteredTaxConfig(); } } onCurrencySelect() { LogUtil.debug('ShopTaxConfigsComponent onCurrencySelect'); this.selectCurrencyModalDialog.show(); } onCurrencySelected(event:string) { LogUtil.debug('ShopTaxConfigsComponent onCurrencySelected'); this.selectedCurrency = event; if (this.selectedCurrency != null) { StorageUtil.saveValue(ShopTaxConfigsComponent.COOKIE_CURRENCY, this.selectedCurrency); } } onSelectCurrencyResult(modalresult: ModalResult) { LogUtil.debug('ShopTaxConfigsComponent onSelectCurrencyResult modal result is ', modalresult); if (this.selectedCurrency == null) { this.selectCurrencyModalDialog.show(); } else { this.getFilteredTaxConfig(); } } onTestRules() { LogUtil.debug('ShopTaxConfigsComponent onTestRules'); this.runTestModalDialog.showDialog(); } onRunTestResult(event:PromotionTestVO) { LogUtil.debug('ShopTaxConfigsComponent onRunTestResult', event); if (event != null && this.selectedShop != null) { this.loading = true; event.shopCode = this.selectedShop.code; event.currency = this.selectedCurrency; this._taxService.testPromotions(event).subscribe( cart => { this.loading = false; LogUtil.debug('ShopTaxConfigsComponent onTestRules', cart); this.viewMode = ShopTaxConfigsComponent.PRICELIST_TEST; this.testCart = cart; } ); } } onTaxConfigFilterChange(event:any) { this.taxconfigs.searchContext.start = 0; // changing filter means we need to start from first page this.delayedFilteringTaxConfig.delay(); } onRefreshHandler() { LogUtil.debug('ShopTaxConfigsComponent refresh handler'); if (UserEventBus.getUserEventBus().current() != null) { this.presetFromCookie(); if (this.viewMode == ShopTaxConfigsComponent.CONFIGS) { this.getFilteredTaxConfig(); } } } onPageSelected(page:number) { LogUtil.debug('ShopTaxConfigsComponent onPageSelected', page); this.taxconfigs.searchContext.start = page; this.delayedFilteringTaxConfig.delay(); } onSortSelected(sort:Pair<string, boolean>) { LogUtil.debug('ShopTaxConfigsComponent ononSortSelected', sort); if (sort == null) { this.taxconfigs.searchContext.sortBy = null; this.taxconfigs.searchContext.sortDesc = false; } else { this.taxconfigs.searchContext.sortBy = sort.first; this.taxconfigs.searchContext.sortDesc = sort.second; } this.delayedFilteringTaxConfig.delay(); } onTaxconfigSelected(data:TaxConfigVO) { LogUtil.debug('ShopTaxConfigsComponent onTaxconfigSelected', data); this.selectedTaxconfig = data; } onSearchHelpToggleTaxConfig() { this.searchHelpTaxConfigShow = !this.searchHelpTaxConfigShow; } onSearchSKU() { this.taxconfigsFilter = '#!'; this.searchHelpTaxConfigShow = false; this.getFilteredTaxConfig(); } onSearchSKUExact() { this.selectProductModalSkuDialog.showDialog(); } onProductSkuSelected(event:FormValidationEvent<ProductSkuVO>) { LogUtil.debug('ShopTaxConfigsComponent onProductSkuSelected', event); if (event.valid) { if (this.taxconfigEdit != null) { this.taxconfigEdit.productCode = event.source.code; } else { this.taxconfigsFilter = '!' + event.source.code; this.searchHelpTaxConfigShow = false; this.getFilteredTaxConfig(); } } } onSearchSLAExact() { this.carrierSlaSelectDialog.showDialog(); } onCarrierSlaSelected(event:FormValidationEvent<CarrierSlaInfoVO>) { LogUtil.debug('ShopTaxConfigsComponent onCarrierSlaSelected', event); if (this.taxconfigEdit != null) { this.taxconfigEdit.productCode = event.source.code; } else { this.taxconfigsFilter = '!' + event.source.code; this.searchHelpTaxConfigShow = false; this.getFilteredTaxConfig(); } } onCountryExact() { this.selectCountryModalDialog.showDialog(); } onCountrySelected(event:FormValidationEvent<CountryInfoVO>) { LogUtil.debug('ShopTaxConfigsComponent onCountrySelected', event); if (event.valid) { if (this.taxconfigEdit != null) { this.taxconfigEdit.stateCode = null; this.taxconfigEdit.countryCode = event.source.countryCode; } else { this.taxconfigsFilter = '@' + event.source.countryCode; this.searchHelpTaxConfigShow = false; this.getFilteredTaxConfig(); } } } onStateExact() { this.selectStateModalDialog.showDialog(); } onStateSelected(event:FormValidationEvent<StateVO>) { LogUtil.debug('ShopTaxConfigsComponent onCountrySelected', event); if (event.valid) { if (this.taxconfigEdit != null) { this.taxconfigEdit.stateCode = event.source.stateCode; this.taxconfigEdit.countryCode = event.source.countryCode; } else { this.taxconfigsFilter = '@' + event.source.stateCode; this.searchHelpTaxConfigShow = false; this.getFilteredTaxConfig(); } } } onTaxExact() { this.selectTaxModalDialog.showDialog(); } onTaxSelected(event:FormValidationEvent<TaxVO>) { LogUtil.debug('ShopTaxConfigsComponent onTaxSelected', event); if (event.valid) { if (this.taxconfigEdit != null) { this.taxconfigEdit.tax = event.source; } else { this.taxconfigsFilter = '^' + event.source.code; this.searchHelpTaxConfigShow = false; this.getFilteredTaxConfig(); } } } onForceShowAll() { this.forceShowAll = !this.forceShowAll; if (this.viewMode == ShopTaxConfigsComponent.CONFIGS) { this.getFilteredTaxConfig(); } } onRowNew() { LogUtil.debug('ShopTaxConfigsComponent onRowNew handler'); UiUtil.formInitialise(this, 'taxconfigEditForm', 'taxconfigEdit', this.newInstance()); this.editTaxconfigModalDialog.show(); } onRowTaxConfigDelete(row:TaxConfigVO) { LogUtil.debug('ShopTaxConfigsComponent onRowTaxConfigDelete handler', row); this.deleteValue = (row.countryCode ? row.countryCode + '/' : '-') + (row.stateCode ? row.stateCode + '/' : '-') + (row.productCode ? row.productCode : '-'); this.deleteConfirmationModalDialog.show(); } onRowDeleteSelected() { if (this.selectedTaxconfig != null) { this.onRowTaxConfigDelete(this.selectedTaxconfig); } } onRowEditTaxconfig(row:TaxConfigVO) { LogUtil.debug('ShopTaxConfigsComponent onRowEditTaxconfig handler', row); this.validForSaveTaxconfig = true; UiUtil.formInitialise(this, 'taxconfigEditForm', 'taxconfigEdit', Util.clone(row)); this.editTaxconfigModalDialog.show(); } onRowCopySelected() { if (this.selectedTaxconfig != null) { let copyCfg:TaxConfigVO = Util.clone(this.selectedTaxconfig); copyCfg.taxConfigId = 0; this.onRowEditTaxconfig(copyCfg); } } onBackToList() { LogUtil.debug('ShopTaxConfigsComponent onBackToList handler'); if (this.viewMode === ShopTaxConfigsComponent.PRICELIST_TEST) { this.viewMode = ShopTaxConfigsComponent.CONFIGS; } } onSaveHandler() { if (this.taxconfigEdit != null) { if (this.validForSaveTaxconfig) { LogUtil.debug('ShopTaxConfigsComponent Save handler config', this.taxconfigEdit); this.loading = true; this._taxService.createTaxConfig(this.taxconfigEdit).subscribe( rez => { LogUtil.debug('ShopTaxConfigsComponent config changed', rez); this.selectedTaxconfig = rez; this.taxconfigEdit = null; this.validForSaveTaxconfig = false; this.loading = false; this.getFilteredTaxConfig(); } ); } } } onDiscardEventHandler() { LogUtil.debug('ShopTaxConfigsComponent discard handler'); this.onRowNew(); } onEditTaxResult(modalresult: ModalResult) { LogUtil.debug('ShopTaxConfigsComponent onEditTaxResult modal result is ', modalresult); if (ModalAction.POSITIVE === modalresult.action) { this.onSaveHandler(); } else { if (this.taxconfigEdit != null) { this.taxconfigEdit = null; } } } onDeleteConfirmationResult(modalresult: ModalResult) { LogUtil.debug('ShopTaxConfigsComponent onDeleteConfirmationResult modal result is ', modalresult); if (ModalAction.POSITIVE === modalresult.action) { if (this.selectedTaxconfig != null) { LogUtil.debug('ShopTaxConfigsComponent onDeleteConfirmationResult', this.selectedTaxconfig); this.loading = true; this._taxService.removeTaxConfig(this.selectedTaxconfig).subscribe(res => { LogUtil.debug('ShopTaxConfigsComponent removeTax', this.selectedTaxconfig); this.selectedTaxconfig = null; this.loading = false; this.getFilteredTaxConfig(); }); } } } onClearFilterTaxConfig() { this.taxconfigsFilter = ''; this.delayedFilteringTaxConfig.delay(); } private getFilteredTaxConfig() { this.taxconfigsFilterRequired = !this.forceShowAll && (this.taxconfigsFilter == null || this.taxconfigsFilter.length < 2); LogUtil.debug('ShopTaxConfigsComponent getFilteredTaxConfig' + (this.forceShowAll ? ' forcefully': '')); if (this.selectedShop != null && this.selectedCurrency != null && !this.taxconfigsFilterRequired) { this.loading = true; this.taxconfigs.searchContext.parameters.filter = [ this.taxconfigsFilter ]; this.taxconfigs.searchContext.parameters.shopCode = [ this.selectedShop.code ]; this.taxconfigs.searchContext.parameters.currency = [ this.selectedCurrency ]; this.taxconfigs.searchContext.size = Config.UI_TABLE_PAGE_SIZE; this._taxService.getFilteredTaxConfig(this.taxconfigs.searchContext).subscribe( alltaxes => { LogUtil.debug('ShopTaxConfigsComponent getFilteredTaxConfig', alltaxes); this.taxconfigs = alltaxes; this.selectedTaxconfig = null; this.taxconfigEdit = null; this.validForSaveTaxconfig = true; this.viewMode = ShopTaxConfigsComponent.CONFIGS; this.loading = false; }); } else { this.taxconfigs = this.newSearchResultInstance(); this.selectedTaxconfig = null; this.taxconfigEdit = null; this.validForSaveTaxconfig = true; this.viewMode = ShopTaxConfigsComponent.CONFIGS; } } }
the_stack
declare const mhtml2html const InitKeyPair = function () { const keyPair: keypair = { publicKey: null, privateKey: null, keyLength: null, nikeName: null, createDate: null, email: null, passwordOK: false, verified: false, publicKeyID: null, _password: null } return keyPair } const makeKeyPairData = function ( view: view_layout.view, keypair: keypair ) { const length = keypair.publicKeyID.length keypair.publicKeyID = keypair.publicKeyID.substr ( length - 16 ) let keyPairPasswordClass = new keyPairPassword ( keypair.privateKey, function ( passwd: string ) { // password OK keypair.keyPairPassword ( keyPairPasswordClass = null ) keypair.passwordOK = true view.password = passwd keypair.showLoginPasswordField ( false ) return view.keyPairCalss = new encryptoClass ( keypair, view.password, view.connectInformationMessage, err => { view.showKeyPair ( false ) if ( view.keyPairCalss.imapData && view.keyPairCalss.imapData.imapTestResult ) { return view.imapSetupClassExit ( view.keyPairCalss.imapData ) } let uu = null return view.imapSetup ( uu = new imapForm ( keypair.email, view.keyPairCalss.imapData, function ( imapData: IinputData ) { view.imapSetup ( uu = null ) view.keyPairCalss.imapData = imapData return view.keyPairCalss.saveImapIInputData ( err => { return view.imapSetupClassExit ( imapData ) }) })) }) }) keypair.keyPairPassword = ko.observable( keyPairPasswordClass ) keypair.showLoginPasswordField = ko.observable ( false ) keypair.delete_btn_view = ko.observable ( true ) keypair.showConform = ko.observable ( false ) keypair['showDeleteKeyPairNoite'] = ko.observable ( false ) keypair.delete_btn_click = function () { keypair.delete_btn_view ( false ) return keypair.showConform ( true ) } keypair.deleteKeyPairNext = function () { localStorage.setItem ( "config", JSON.stringify ({})) view.localServerConfig ( null ) view.showIconBar ( false ) view.connectedCoNET ( false ) view.connectToCoNET ( false ) view.CoNETConnect ( view.CoNETConnectClass = null ) view.imapSetup ( view.imapFormClass = null ) keypair.showDeleteKeyPairNoite ( false ) keypair.delete_btn_view ( false ) localStorage.clear() return view.reFreshLocalServer() } } const initPopupArea = function () { const popItem = $( '.activating.element' ).popup('hide') const inline = popItem.hasClass ('inline') return popItem.popup({ on: 'focus', movePopup: false, position: 'top left', inline: inline }) } class showWebPageClass { public showLoading = ko.observable ( true ) public htmlIframe = ko.observable ( null ) public showErrorMessage = ko.observable ( false ) public showHtmlCodePage = ko.observable ( false ) public showImgPage = ko.observable ( true ) public showErrorMessageProcess () { this.showLoading ( false ) this.showErrorMessage ( true ) } public png = ko.observable ('') public mHtml = ko.observable ('') private urlBlobList = [] public close () { this.showImgPage ( false ) this.showHtmlCodePage ( false ) this.png ( null ) this.htmlIframe ( null ) this.urlBlobList.forEach ( n => { ( URL || webkitURL ).revokeObjectURL ( n ) }) this.exit () } public imgClick () { this.showHtmlCodePage ( false ) this.showImgPage ( true ) } public htmlClick () { this.showHtmlCodePage ( true ) this.showImgPage ( false ) const docu = this.mHtml() if ( docu ) { $('iframe').contents().find( "head" ).html ( docu["window"].document.head.outerHTML ) $('iframe').contents().find( "body" ).html ( docu["window"].document.body.outerHTML ) } } constructor ( public showUrl: string, private zipBase64Stream: string, private zipBase64StreamUuid: string, private exit: ()=> void ) { const self = this _view.showIconBar ( false ) showHTMLComplete ( zipBase64StreamUuid, zipBase64Stream, ( err, data: { mhtml: string, img: string, html: string, folder: [ { filename: string, data: string }]} ) => { if ( err ) { return self.showErrorMessageProcess () } _view.bodyBlue ( false ) let html = data.html // support HTMLComplete if ( html ) { html = html.replace ( / srcset="[^"]+" /ig, ' ').replace ( / srcset='[^']+' /ig, ' ') let det = data.folder.shift() const getData = ( filename: string, _data: string, CallBack ) => { const pointStart = html.indexOf ( `${ filename }` ) const doCallBack = () => { det = data.folder.shift() if ( ! det ) { return CallBack () } return getData ( det.filename, det.data, CallBack ) } if ( pointStart > -1 ) { return getFilenameMime ( filename, ( err, mime ) => { if ( mime && ! /javascript/.test( mime ) ) { /** * * css link tag format support * */ const _filename = filename.replace(/\-/g,'\\-').replace(/\//g,'\\/').replace(/\./g,'\\.').replace(/\(/g,'\\(').replace(/\)/g,'\\)') const regex = new RegExp (` src=("|')\.\/${ _filename }("|')`, 'g') const regex1 = new RegExp (` href=("|')\.\/${ _filename }("|')`, 'g') /* if ( /^ src/i.test( hrefTest )) { const data1 = `data:${ mime };base64,` + _data html = html.replace ( regex, data1 ).replace ( regex, data1 ) return doCallBack () } */ const blob = new Blob ([ /^image/.test( mime ) ? Buffer.from ( _data,'base64' ) : Buffer.from ( _data,'base64' ).toString()], { type: mime }) const link = ( URL || webkitURL ).createObjectURL( blob ) html = html.replace ( regex, ` src="${ link }"` ).replace ( regex1, ` href="${ link }"` ) this.urlBlobList.push ( link ) } doCallBack () }) } doCallBack () } return getData ( det.filename, det.data, err => { self.png ( data.img ) const htmlBolb = new Blob ([ html ], { type: 'text/html'}) const _url = ( URL || webkitURL ).createObjectURL ( htmlBolb ) self.showLoading ( false ) self.htmlIframe ( _url ) self.urlBlobList.push ( _url ) }) } html = mhtml2html.convert( data.mhtml ) self.png ( data.img ) self.showLoading ( false ) self.mHtml ( html ) }) } } class workerManager { public workers: Map<string, Worker > = new Map() private callbackPool: Map< string, any > = new Map () private doEvent ( evt: MessageEvent ) { const jsonData = Buffer.from ( Buffer.from ( evt.data ).toString(), 'base64').toString() let data: workerDataEvent = null try { data = JSON.parse ( jsonData ) } catch ( ex ) { return new EvalError ( `workerManager JSON.parse error [${ ex.message }]`) } const callBack = this.callbackPool.get ( data.uuid ) if ( !callBack ) { return console.log (`workerManager: [${ new Date().toLocaleTimeString()}] have not callback about message from [${ data.workerName }] content = [${ data.data }]`) } return callBack ( null, data ) } constructor ( list: string[] ) { list.forEach ( n => { const work = new Worker(`scripts/${ n }.js`) work.onmessage = evt => { return this.doEvent ( evt ) } return this.workers.set ( n, work ) }) } /** * * */ public postFun ( workerName: string, data: any, CallBack ) { const worker = this.workers.get ( workerName ) if ( !worker ) { return CallBack ( new Error ('no worker')) } const callback: workerDataEvent = { data: data, uuid: uuid_generate (), workerName: workerName } const kk = Buffer.from ( Buffer.from ( JSON.stringify( callback )).toString ('base64')) this.callbackPool.set ( callback.uuid, CallBack ) return worker.postMessage ( kk, [ kk.buffer ] ) } } module view_layout { export class view { public connectInformationMessage = new connectInformationMessage( '/' ) public sectionLogin = ko.observable ( false ) public sectionAgreement = ko.observable ( false ) public sectionWelcome = ko.observable ( true ) public isFreeUser = ko.observable ( true ) public QTTransferData = ko.observable ( false ) public LocalLanguage = 'up' public menu = Menu public modalContent = ko.observable ('') public keyPairGenerateForm: KnockoutObservable< keyPairGenerateForm> = ko.observable () public tLang = ko.observable ( initLanguageCookie ()) public languageIndex = ko.observable ( lang [ this.tLang() ]) public localServerConfig = ko.observable () public keyPair: KnockoutObservable < keypair > = ko.observable ( InitKeyPair ()) public hacked = ko.observable ( false ) public imapSetup: KnockoutObservable < imapForm > = ko.observable () public showIconBar = ko.observable ( false ) public connectToCoNET = ko.observable ( false ) public connectedCoNET = ko.observable ( false ) public showKeyPair = ko.observable ( false ) public CoNETConnectClass: CoNETConnect = null public imapFormClass: imapForm = null public CoNETConnect: KnockoutObservable < CoNETConnect > = ko.observable ( null ) public bodyBlue = ko.observable ( true ) public CanadaBackground = ko.observable ( false ) public password = null /* public worker = new workerManager ([ 'mHtml2Html' ]) */ public keyPairCalss: encryptoClass = null public appsManager: KnockoutObservable< appsManager > = ko.observable ( null ) public AppList = ko.observable ( false ) public imapData: IinputData = null public newVersion = ko.observable ( null ) public showLanguageSelect = ko.observable ( true ) private demoTimeout private demoMainElm /************************************* * * for New York Times */ public nytSection = ko.observable ( false ) public nytloader = ko.observable ( true ) public iframShow = ko.observable ( false ) public nyt_news = ko.observable ( false ) public nyt_detail = ko.observable ( false ) public nyt_menu = ko.observable ( false ) /*** */ private afterInitConfig ( ) { this.keyPair ( this.localServerConfig ().keypair ) if ( this.keyPair() && this.keyPair().keyPairPassword() && typeof this.keyPair().keyPairPassword().inputFocus ==='function' ) { this.keyPair().keyPairPassword().inputFocus ( true ) this.sectionLogin ( false ) } } private initConfig ( config ) { const self = this this.showKeyPair ( true ) if ( config && config.keypair && config.keypair.publicKeyID ) { /** * * Key pair ready * */ makeKeyPairData ( this, config.keypair ) if ( ! config.keypair.passwordOK ) { config.keypair.showLoginPasswordField ( true ) } this.localServerConfig ( config ) return this.afterInitConfig () //this.keyPairGenerateForm ( _keyPairGenerateForm ) } /** * * No key pair * */ this.svgDemo_showLanguage () config["account"] = config["keypair"] = null let _keyPairGenerateForm = new keyPairGenerateForm (( _keyPair: keypair ) => { self.keyPairGenerateForm ( _keyPairGenerateForm = null ) /** * key pair ready */ self.showKeyPair ( false ) self.password = _keyPair._password _keyPair._password = null config.account = _keyPair.email config.keypair = _keyPair localStorage.setItem ( "config", JSON.stringify ( config )) _keyPair.passwordOK = true //self.localServerConfig ( config ) self.keyPair ( _keyPair ) return self.keyPairCalss = new encryptoClass ( _keyPair, self.password, self.connectInformationMessage, err => { self.showKeyPair ( false ) let uu = null return self.imapSetup ( uu = new imapForm ( _keyPair.email, self.keyPairCalss.imapData, function ( imapData: IinputData ) { self.imapSetup ( uu = null ) self.keyPairCalss.imapData = imapData return self.keyPairCalss.saveImapIInputData ( err => { return self.imapSetupClassExit ( imapData ) }) })) }) //initPopupArea () }) this.localServerConfig ( config ) this.afterInitConfig () this.keyPairGenerateForm ( _keyPairGenerateForm ) } private getConfigFromLocalStorage () { const configStr = localStorage.getItem ( "config" ) if (!configStr ) { return this.initConfig ( {} ) } let config = null try { config = JSON.parse ( configStr ) } catch ( ex ) { return this.initConfig ( {} ) } return this.initConfig ( config ) } private socketListen () { let self = this return this.getConfigFromLocalStorage () } constructor () { this.socketListen () this.CanadaBackground.subscribe ( val => { if ( val ) { $.ajax ({ url:'/scripts/CanadaSvg.js' }).done ( data => { eval ( data ) }) } }) } // change language public selectItem ( that?: any, site?: () => number ) { const tindex = lang [ this.tLang ()] let index = tindex + 1 if ( index > 3 ) { index = 0 } this.languageIndex ( index ) this.tLang( lang [ index ]) $.cookie ( 'langEH', this.tLang(), { expires: 180, path: '/' }) const obj = $( "span[ve-data-bind]" ) obj.each ( function ( index, element ) { const ele = $( element ) const data = ele.attr ( 've-data-bind' ) if ( data && data.length ) { ele.text ( eval ( data )) } }) $('.languageText').shape (`flip ${ this.LocalLanguage }`) $('.KnockoutAnimation').transition('jiggle') return initPopupArea() } // start click public openClick () { clearTimeout ( this.demoTimeout ) if ( this.demoMainElm && typeof this.demoMainElm.remove === 'function' ) { this.demoMainElm.remove() this.demoMainElm = null } if ( !this.connectInformationMessage.socketIoOnline ) { return this.connectInformationMessage.showSystemError () } this.sectionWelcome ( false ) /* if ( this.localServerConfig().firstRun ) { return this.sectionAgreement ( true ) } */ this.sectionLogin ( true ) return initPopupArea () /* setTimeout (() => { this.nytloader ( false ) }, 3000 ) new Date().toDateString this.nyt_menu ( true ) return this.nytSection ( true ) */ } public deletedKeypairResetView () { this.imapSetup (null) } public agreeClick () { this.connectInformationMessage.sockEmit ( 'agreeClick' ) this.sectionAgreement ( false ) this.localServerConfig().firstRun = false return this.openClick() } public refresh () { if ( typeof require === 'undefined' ) { this.modalContent ( infoDefine[ this.languageIndex() ].emailConform.formatError [ 11 ] ) return this.hacked ( true ) } const { remote } = require ('electron') if ( remote && remote.app && typeof remote.app.quit === 'function' ) { return remote.app.quit() } } public showKeyInfoClick () { this.sectionLogin ( true ) this.showKeyPair ( true ) this.AppList ( false ) this.appsManager ( null ) } public imapSetupClassExit ( _imapData: IinputData ) { const self = this this.imapData = _imapData return this.CoNETConnect ( this.CoNETConnectClass = new CoNETConnect ( this, this.keyPair().verified, ( err ) => { if ( typeof err ==='number' && err > -1 ) { self.CoNETConnect ( this.CoNETConnectClass = null ) return self.imapSetup ( this.imapFormClass = new imapForm ( _imapData.account, null, function ( imapData: IinputData ) { self.imapSetup ( this.imapFormClass = null ) return self.imapSetupClassExit ( imapData ) })) } self.connectedCoNET ( true ) self.homeClick () })) } public reFreshLocalServer () { location.reload() } public homeClick () { this.AppList ( true ) this.sectionLogin ( false ) const connectMainMenu = () => { let am = null this.appsManager ( am = new appsManager (() => { am = null return connectMainMenu () })) } connectMainMenu () this.showKeyPair ( false ) $('.dimmable').dimmer ({ on: 'hover' }) $('.comeSoon').popup ({ on: 'focus', movePopup: false, position: 'top left', inline: true }) _view.connectInformationMessage.socketIo.removeEventListener ('tryConnectCoNETStage', this.CoNETConnectClass.listenFun ) } /** * * T/t = Translate (t is relative, T is absolute) R/r = rotate(r is relative, R is absolute) S/s = scale(s is relative, S is absolute) */ private svgDemo_showLanguage () { if ( !this.sectionWelcome()) { return } let i = 0 const changeLanguage = () => { if ( ++i === 1 ) { backGround_mask_circle.attr ({ stroke: "#FF000090", }) return setTimeout (() => { changeLanguage() }, 1000 ) } if ( i > 5 || !this.sectionWelcome() ) { main.remove() return this.demoMainElm = main = null } this.selectItem () this.demoTimeout = setTimeout (() => { changeLanguage () }, 2000 ) } const width = window.innerWidth const height = window.outerHeight let main = this.demoMainElm = Snap( width, height ) const backGround_mask_circle = main.circle( width / 2, height / 2, width / 1.7 ).attr({ fill:'#00000000', stroke: "#FF000020", strokeWidth: 5, }) const wT = width/2 - 35 const wY = 30 - height / 2 backGround_mask_circle.animate ({ transform: `t${ wT } ${ wY }`, r: 60 }, 3000, mina.easeout, changeLanguage ) } } } const _view = new view_layout.view () ko.applyBindings ( _view , document.getElementById ( 'body' )) $(`.${ _view.tLang()}`).addClass ('active') openpgp.config.indutny_elliptic_path = 'lightweight/elliptic.min.js' window[`${ "indexedDB" }`] = window.indexedDB || window["mozIndexedDB"] || window["webkitIndexedDB"] || window["msIndexedDB"] const CoNET_version = "0.1.10"
the_stack
namespace annie { /** * 动态文本类,有时需要在canvas里有一个动态文本,能根据我们的显示内容来改变 * @class annie.TextField * @extends annie.Bitmap * @since 1.0.0 * @public */ export class TextField extends DisplayObject { public constructor() { super(); this._instanceType = "annie.TextField"; } /** * 文本的对齐方式 * @property textAlign * @public * @since 1.0.0 * @type {string} * @default left */ public set textAlign(value: string) { let s = this; if (value != s._textAlign) { s._textAlign = value; s.a2x_ut = true; } } public get textAlign(): string { return this._textAlign; } private _textAlign = "left"; /** * @property textAlpha * @since 2.0.0 * @public */ public set textAlpha(value: number) { let s = this; if (value != s._textAlpha) { s._textAlpha = value; s.a2x_ut = true; } } public get textAlpha(): number { return this._textAlpha; } private _textAlpha: number = 1; /** * 文本的行高 * @property textHeight * @public * @since 1.0.0 * @type {number} * @default 0 */ public set textHeight(value: number) { let s = this; if (value != s._textHeight) { s._textHeight = value; s.a2x_ut = true; } } public get textHeight(): number { return this._textHeight; } private _textHeight: number = 0; /** * @property lineHeight * @public * @since 1.0.0 * @param {number} value */ public set lineHeight(value: number) { let s = this; if (value != s._lineHeight) { s._lineHeight = value; s.a2x_ut = true; } } public get lineHeight(): number { return this._lineHeight; } private _lineHeight: number = 14; /** * 文本的宽 * @property textWidth * @public * @since 1.0.0 * @type {number} * @default 0 */ public set textWidth(value: number) { let s = this; if (value != s._textWidth) { s._textWidth = value; s.a2x_ut = true; } } public get textWidth(): number { return this._textWidth; } private _textWidth: number = 120; /** * 文本类型,单行还是多行 single multi * @property lineType * @public * @since 1.0.0 * @type {string} 两种 single和multi * @default single */ public set lineType(value: string) { let s = this; if (value != s._lineType) { s._lineType = value; s.a2x_ut = true; } } public get lineType(): string { return this._lineType; } private _lineType: string = "single"; /** * 文本内容 * @property text * @type {string} * @public * @default "" * @since 1.0.0 */ public set text(value: string) { let s = this; value+=""; if (value != s._text) { s._text = value; if(s._text==""){ s.a2x_ut = false; s.clearBounds(); }else{ s.a2x_ut = true; } } } public get text(): string { return this._text; } private _text: string = ""; /** * 文本的css字体样式 * @property font * @public * @since 1.0.0 * @type {string} * @default 12px Arial */ public set font(value: string) { let s = this; if (value != s._font) { s._font = value; s.a2x_ut = true; } } public get font(): string { return this._font; } private _font: string = "Arial"; /** * 文本的size * @property size * @public * @since 1.0.0 * @type {number} * @default 12 */ public set size(value: number) { let s = this; if (value != s._size) { s._size = value; s.a2x_ut = true; } } public get size(): number { return this._size; } private _size: number = 12; /** * 文本的颜色值 * @property color * @type {string} * @public * @since 1.0.0 * @default #fff */ public set color(value: string) { let s = this; if (value != s._color) { s._color = value; s.a2x_ut = true; } } public get color(): string { return this._color; } public _color: string = "#fff"; /** * 文本是否倾斜 * @property italic * @public * @since * @default false * @type {boolean} */ public set italic(value: boolean) { let s = this; if (value != s._italic) { s._italic = value; s.a2x_ut = true; } } public get italic(): boolean { return this._italic; } private _italic: boolean = false; /** * 文本是否加粗 * @property bold * @public * @since * @default false * @type {boolean} */ public set bold(value: boolean) { let s = this; if (value != s._bold) { s._bold = value; s.a2x_ut = true; } } public get bold(): boolean { return this._bold; } public _bold: boolean = false; /** * 设置或获取是否有边框 * @property property * @param {boolean} show true或false * @public * @since 1.0.6 */ public set border(value: boolean) { let s = this; if (value != s._border) { s._border = value; s.a2x_ut = true; } } public get border(): boolean { return this._border; } private _border: boolean = false; /** * 描边宽度 默认为0,不显示. 值为正数则是外描边,值为负数则是内描边 * @property stroke * @param {number} value * @since 2.0.2 */ public set stroke(value: number) { let s = this; if (value != s._stroke) { s._stroke = value; s.a2x_ut = true; } } public get stroke(): number { return this._stroke; } private _stroke: number = 0; /** * 描边颜色 默认黑色 * @property strokeColor * @param {string} value * @since 2.0.2 */ public set strokeColor(value: string) { let s = this; if (value != s._strokeColor) { s._strokeColor = value; s.a2x_ut = true; } } public get strokeColor(): string { return this._strokeColor; } private _strokeColor: string = "#000"; //设置文本在canvas里的渲染样式 private _prepContext(ctx: any): void { let s = this; let font: any = s.size || 12; font += "px "; font += s.font; //font-weight:bold;font-style:italic; if (s._bold) { font = "bold " + font; } if (s._italic) { font = "italic " + font; } ctx.font = font; ctx.textAlign = s._textAlign || "left"; ctx.textBaseline = "top"; ctx.lineJoin = "miter"; ctx.miterLimit = 2.5; ctx.fillStyle = Shape.getRGBA(s._color, s._textAlpha); //实线文字 ctx.strokeStyle = s.strokeColor; ctx.lineWidth = Math.abs(s._stroke); } /** * 获取当前文本行数 * @property lines * @type {number} * @public * @readonly * @since 2.0.0 */ get lines(): number { return this.realLines.length; } // 获取文本宽 private _getMeasuredWidth(text: string): number { let ctx = CanvasRender._ctx; //ctx.save(); let w = ctx.measureText(text).width; //ctx.restore(); return w; } private realLines: any = []; public a2x_ut: boolean = true; protected _updateMatrix(isOffCanvas: boolean = false): void { let s: any = this; super._updateMatrix(); if (s.a2x_ut) { let ctx = CanvasRender._ctx; s.a2x_ut = false; let hardLines: any = s._text.toString().split(/(?:\r\n|\r|\n)/); s.realLines.length=0; let realLines=s.realLines; s._prepContext(ctx); let wordW = 0; let lineH = s._lineHeight; if (s._text.indexOf("\n") < 0 && s.lineType == "single") { realLines[realLines.length] = hardLines[0]; let str = hardLines[0]; let lineW = s._getMeasuredWidth(str); if (lineW > s._textWidth) { let w = s._getMeasuredWidth(str[0]); let lineStr = str[0]; let strLen = str.length; for (let j = 1; j < strLen; j++) { wordW = ctx.measureText(str[j]).width; w += wordW; if (w > s._textWidth) { realLines[0] = lineStr; break; } else { lineStr += str[j]; } } } } else { for (let i = 0, l = hardLines.length; i < l; i++) { let str = hardLines[i]; if (!str) continue; let w = s._getMeasuredWidth(str[0]); let lineStr = str[0]; let strLen = str.length; for (let j = 1; j < strLen; j++) { wordW = ctx.measureText(str[j]).width; w += wordW; if (w > s._textWidth) { realLines[realLines.length] = lineStr; lineStr = str[j]; w = wordW; } else { lineStr += str[j]; } } realLines[realLines.length] = lineStr; } } let maxH = lineH * realLines.length+4 >> 0; let maxW = s._textWidth >> 0; s._offsetX = 2; if (s._textAlign == "center") { s._offsetX += maxW * 0.5; } else if (s._textAlign == "right") { s._offsetX += maxW; } s._bounds.width = maxW; s._bounds.height = maxH; s.a2x_um=true; } if( s.a2x_um){ s._checkDrawBounds(); } s.a2x_um = false; s.a2x_ua = false; } public _draw(ctx: any, isMask: boolean = false): void { let s=this; let realLines=s.realLines; let lineHeight=s._lineHeight; let w=s._bounds.width; s._prepContext(ctx); ctx.translate(s._offsetX, s._offsetY); for (let i = 0; i < realLines.length; i++) { if (s._stroke > 0) { ctx.strokeText(realLines[i], 0, i * lineHeight, w); } ctx.fillText(realLines[i], 0, i * lineHeight, w); if (s._stroke < 0) { ctx.strokeText(realLines[i], 0, i * lineHeight, w); } } } } }
the_stack
import { CoinPretty } from "./coin-pretty"; import { Dec } from "./decimal"; import { Int } from "./int"; import { CoinUtils } from "./coin-utils"; import { DecUtils } from "./dec-utils"; describe("Test CoinPretty", () => { it("Test creation of CoinPretty", () => { expect( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int(1234) ) .toDec() .equals(new Dec("0.001234")) ).toBe(true); expect( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int(1234) ).toString() ).toBe("0.001234 ATOM"); expect( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, 1234 ) .toDec() .equals(new Dec("0.001234")) ).toBe(true); expect( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, 1234 ).toString() ).toBe("0.001234 ATOM"); expect( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, "1234.5" ) .toDec() .equals(new Dec("0.0012345")) ).toBe(true); expect( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, "1234.5" ).toString() ).toBe("0.001234 ATOM"); expect( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Dec("1234.5") ) .toDec() .equals(new Dec("0.0012345")) ).toBe(true); expect( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Dec("1234.5") ).toString() ).toBe("0.001234 ATOM"); }); it("Basic test for CoinPretty", () => { const pretty = new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int(1234) ); expect(pretty.toDec().equals(new Dec("0.001234"))).toBeTruthy(); expect(pretty.toString()).toBe("0.001234 ATOM"); expect(pretty.separator("").toString()).toBe("0.001234ATOM"); expect(pretty.increasePrecision(1).toString()).toBe("0.000123 ATOM"); expect(pretty.decreasePrecision(1).toString()).toBe("0.012340 ATOM"); expect(pretty.decreasePrecision(1).trim(true).toString()).toBe( "0.01234 ATOM" ); expect(pretty.moveDecimalPointLeft(1).toString()).toBe("0.000123 ATOM"); expect(pretty.moveDecimalPointRight(1).toString()).toBe("0.012340 ATOM"); expect(pretty.moveDecimalPointRight(1).trim(true).toString()).toBe( "0.01234 ATOM" ); expect(pretty.maxDecimals(7).add(new Dec("0.1")).toString()).toBe( "0.0012341 ATOM" ); expect(pretty.maxDecimals(7).sub(new Dec("0.1")).toString()).toBe( "0.0012339 ATOM" ); expect(pretty.maxDecimals(7).mul(new Dec("0.1")).toString()).toBe( "0.0001234 ATOM" ); expect(pretty.maxDecimals(7).quo(new Dec("0.1")).toString()).toBe( "0.0123400 ATOM" ); expect( pretty .add( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int(1200000) ) ) .toString() ).toBe("1.201234 ATOM"); expect( pretty .sub( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int(1200000) ) ) .toString() ).toBe("-1.198766 ATOM"); // If target is `CoinPretty` and it has different denom, do nothing. expect( pretty .add( new CoinPretty( { coinDenom: "SCRT", coinMinimalDenom: "uscrt", coinDecimals: 6, }, new Int(1200000) ) ) .toString() ).toBe("0.001234 ATOM"); // If target is `CoinPretty` and it has different denom, do nothing. expect( pretty .sub( new CoinPretty( { coinDenom: "SCRT", coinMinimalDenom: "uscrt", coinDecimals: 6, }, new Int(1200000) ) ) .toString() ).toBe("0.001234 ATOM"); }); it("Basic test for CoinPretty 2", () => { const pretty = new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Dec("12.1234") ); expect(pretty.toString()).toBe("0.000012 ATOM"); expect(pretty.maxDecimals(10).toString()).toBe("0.0000121234 ATOM"); expect(pretty.increasePrecision(1).toString()).toBe("0.000001 ATOM"); expect(pretty.decreasePrecision(1).toString()).toBe("0.000121 ATOM"); expect(pretty.moveDecimalPointLeft(1).toString()).toBe("0.000001 ATOM"); expect(pretty.moveDecimalPointRight(1).toString()).toBe("0.000121 ATOM"); expect(pretty.maxDecimals(7).add(new Dec("0.1")).toString()).toBe( "0.0000122 ATOM" ); expect(pretty.maxDecimals(7).sub(new Dec("0.1")).toString()).toBe( "0.0000120 ATOM" ); expect(pretty.maxDecimals(7).mul(new Dec("0.1")).toString()).toBe( "0.0000012 ATOM" ); expect(pretty.maxDecimals(7).quo(new Dec("0.1")).toString()).toBe( "0.0001212 ATOM" ); expect( pretty .add( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int(1200000) ) ) .toString() ).toBe("1.200012 ATOM"); expect( pretty .sub( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int(1200000) ) ) .toString() ).toBe("-1.199987 ATOM"); }); it("Test toCoin() for CoinPretty", () => { expect( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Dec("0.1234") ).toCoin() ).toStrictEqual({ denom: "uatom", amount: "0", }); expect( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Dec("12.1234") ).toCoin() ).toStrictEqual({ denom: "uatom", amount: "12", }); expect( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Dec("123456.1234") ).toCoin() ).toStrictEqual({ denom: "uatom", amount: "123456", }); expect( new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("12345600") ).toCoin() ).toStrictEqual({ denom: "uatom", amount: "12345600", }); }); it("Test CoinPretty's setCurrency", () => { const pretty = new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("123456") ); expect( pretty .setCurrency({ coinDenom: "TEST", coinMinimalDenom: "utest", coinDecimals: 6, }) .toString() ).toBe("0.123456 TEST"); expect( pretty .setCurrency({ coinDenom: "TEST", coinMinimalDenom: "utest", coinDecimals: 3, }) .toString() ).toBe("123.456000 TEST"); expect( pretty .setCurrency({ coinDenom: "TEST", coinMinimalDenom: "utest", coinDecimals: 3, }) .moveDecimalPointLeft(2) .moveDecimalPointRight(1) .trim(true) .toString() ).toBe("12.3456 TEST"); }); it("Test CoinPretty's toString()", () => { const tests: { base: CoinPretty; pre: (pretty: CoinPretty) => CoinPretty; res: string; }[] = [ { base: new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("12345600") ), pre: (pretty) => pretty, res: "12.345600 ATOM", }, { base: new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("12345600") ), pre: (pretty) => pretty.hideDenom(true), res: "12.345600", }, { base: new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("12345600") ), pre: (pretty) => pretty.separator(""), res: "12.345600ATOM", }, { base: new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("12345600") ), pre: (pretty) => pretty.maxDecimals(3), res: "12.345 ATOM", }, { base: new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("12345600") ), pre: (pretty) => pretty.maxDecimals(3).separator(""), res: "12.345ATOM", }, { base: new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("12345600") ), pre: (pretty) => pretty.lowerCase(true), res: "12.345600 atom", }, { base: new CoinPretty( { coinDenom: "AtoM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("12345600") ), pre: (pretty) => pretty.upperCase(true), res: "12.345600 ATOM", }, { base: new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("1234560000") ), pre: (pretty) => pretty, res: "1,234.560000 ATOM", }, { base: new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("1234560000") ), pre: (pretty) => pretty.locale(false), res: "1234.560000 ATOM", }, { base: new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("1234560000") ), pre: (pretty) => pretty.shrink(true), res: CoinUtils.shrinkDecimals( new Dec("1234560000").mul(DecUtils.getTenExponentN(-6)), 0, 6, true ) + " ATOM", }, { base: new CoinPretty( { coinDenom: "ATOM", coinMinimalDenom: "uatom", coinDecimals: 6, }, new Int("1234560000") ), pre: (pretty) => pretty.locale(false).shrink(true), res: CoinUtils.shrinkDecimals( new Dec("1234560000").mul(DecUtils.getTenExponentN(-6)), 0, 6, false ) + " ATOM", }, ]; for (const test of tests) { expect(test.pre(test.base).toString()).toBe(test.res); } }); });
the_stack
import {IApp} from '../../IApp'; import IDisplayContext = etch.drawing.IDisplayContext; import Point = etch.primitives.Point; import {SamplerBase} from './SamplerBase'; import {WaveVoice} from '../../WaveVoice'; declare var App: IApp; export class SampleGen extends SamplerBase { //private WaveForm: number[]; private _FirstRelease: boolean = true; public Sources: Tone.Simpler[]; //private PrimaryBuffer: any; private _LoadFromShare: boolean = false; private _BufferData: Float32Array; private _WaveVoices: WaveVoice[]; private _SeedLoad: boolean; public Params: SampleGenParams; public Defaults: SampleGenParams; Init(drawTo: IDisplayContext): void { this.BlockName = App.L10n.Blocks.Source.Blocks.SampleGen.name; if (this.Params) { this._LoadFromShare = true; var me = this; setTimeout(function() { me.FirstSetup(); },100); } this.Defaults = { playbackRate: 0, detune: 0, reverse: false, startPosition: 0, endPosition: null, loop: true, loopStart: 0, loopEnd: 0, volume: 11, generate: null, seed: {} }; this.PopulateParams(); this.WaveForm = []; this._WaveVoices = []; this._SeedLoad = true; super.Init(drawTo); // Define Outline for HitTest this.Outline.push(new Point(-1, -1),new Point(0, -1),new Point(1, 0),new Point(1, 2),new Point(0, 2),new Point(-1, 1)); } Arp(mode,notes,octave,range,length) { var seq = []; switch (mode) { case 1: for (var j=0; j<length; j++) { seq.push( this.Sources[0].noteToFrequency("" + notes[0] + (octave + Math.floor(Math.random()*range))) ); } return seq; break; case 2: for (var j=0; j<length; j++) { seq.push( this.Sources[0].noteToFrequency("" + notes[Math.floor(Math.random()*notes.length)] + (octave + Math.floor(Math.random()*range))) ); } return seq; break; case 3: var dir = 1; if (this.Dice(2)) {dir = -1;} var change = 3 + Math.round(Math.random()*5); var note = Math.floor(Math.random()*notes.length); var thisOctave = Math.floor(Math.random()*range); for (var j=0; j<length; j++) { seq.push( this.Sources[0].noteToFrequency("" + notes[note] + (octave + thisOctave)) ); if (this.Dice(change)) {dir = -dir;} note += dir; if (note < 0) { if (thisOctave > 0) { note = (notes.length-1); thisOctave -= 1; } else { note += 2; dir = 1; } } if (note > (notes.length-1)) { if (thisOctave < range) { note = 0; thisOctave += 1; } else { note -= 2; dir = -1; } } } return seq; break; } } Dice(sides) { return ((Math.floor(Math.random()*sides))==0); } //------------------------------------------------------------------------------------------- // GENERATION //------------------------------------------------------------------------------------------- DataToBuffer() { // SETTINGS // var seconds = 2; var sampleRate = App.Audio.sampleRate; var gain = 1; var noise = 0; if (this.Dice(2)) { noise = Math.random()*0.5; } var waveType = Math.floor(Math.random()*3); var octaving = 0; var organise = false; if (this.Dice(8)) { if (this.Dice(3)) { octaving = 2; } else { octaving = 1; } if (this.Dice(3)) { organise = true; } } var following = false; if (this.Dice(4)) { following = true; } var glide = 1 + Math.round(Math.random()*20); var noGlide = false; if (this.Dice(2)) { noGlide = true; } // ARPEGGIO SEQUENCER // var notes = ['c','d','e','f','g','a','b']; var wonder = ['c','e','f','a']; var minor = ['c','d#','g','g#']; var jpent = ['c','c#','f','g','a#']; var second = ['c','f','g','g#']; var jazz = ['c','d','d#','g','a','a#']; var scales = [wonder,minor,jpent,second,jazz]; var scale; var sequenceLength = Math.pow(2,1 + Math.round(Math.random()*6)); if (sequenceLength==2) { if (this.Dice(2)) { sequenceLength = 4; } } var octave = 4; var range = 1; var arpMode; switch (Math.floor(Math.random()*10)) { case 0: arpMode = 1; break; case 1: case 2: case 3: case 4: case 5: case 6: arpMode = 2; break; case 7: case 8: case 9: arpMode = 3; break; } var octaveLower = 0; if (this.Dice(2)) { octaveLower = Math.ceil(Math.random()*2); } if (arpMode==1) { octave = 2 + Math.round(Math.random()*(3 - octaveLower)); range = 2 + Math.round(Math.random()*(4 - (octave-2))); if (sequenceLength<8) { if (this.Dice(2)) { sequenceLength = 8; } } scale = notes; } if (arpMode==2) { octave = 1 + Math.round(Math.random()*(6 - octaveLower)); range = 1 + Math.floor(Math.random()*(6 - (octave-1))); scale = notes; if (this.Dice(4)) { scale = scales[Math.floor(Math.random()*scales.length)]; } } if (arpMode==3) { octave = 1 + Math.round(Math.random()*(5 - octaveLower)); range = 1 + Math.floor(Math.random()*(6 - (octave-1))); if (sequenceLength<8) { sequenceLength = 8; } scale = scales[Math.floor(Math.random()*scales.length)]; } /*console.log("mode: "+arpMode); console.log("range: "+range); console.log("octave: "+octave);*/ // CREATE DATA ARRAY // this._BufferData = new Float32Array(sampleRate*seconds); var data = this._BufferData; // SETUP VOICES // var voices, harmonics, lfo; this._WaveVoices = []; voices = 1 + Math.round(Math.random()*3); harmonics = Math.round(Math.random()*13); lfo = Math.round(Math.random()); if (this.Dice(8)) { voices = 1 + Math.round(Math.random()*20); harmonics = 3 + Math.round(Math.random()*6); //console.log("DENSE"); } if (this.Dice(8)) { voices = 10 + Math.round(Math.random()*10); harmonics = 3; lfo = 0; //console.log("DENSE2"); } // VOICE LOOP // var totalGain = 0; for (var i=0; i<(voices + harmonics + lfo); i++) { var t,w,f,vol,d,s,sl; // defaults // vol = 0.05 + (Math.random()*30); f = 440; d = 1; s = []; sl = false; w = waveType; // type // if (i<voices) { // voice t = 0; // ARPEGGIATION // if (arpMode>0) { if (i==0) { s = this.Arp(arpMode,scale,octave,range,sequenceLength); } else { if (this.Dice(3)) { s = this.Arp(arpMode,scale,octave,range,sequenceLength); } } } // SAW // if (w==1) { // half frequencies f *= 0.5; if (s.length>0) { for (j=0; j<s.length; j++) { s[j] *= 0.5; } } } // ORGANISE // if (organise && i>0) { vol = this._WaveVoices[0].Volume; } // FREQUENCY DRIFT // if (this.Dice(3)) { d = 0.9999 + (Math.random()*0.0002); } if (following && i>0) { d = this._WaveVoices[0].Drift; } // SLIDE // if (this.Dice(4) && !noGlide) { sl = true; } } else if (i>=voices && i< (voices + harmonics)) { // harmonic t = 1; // SLIDE // if (this.Dice(4) && !noGlide) { sl = true; } } else { // lfo t = 2; vol = 10 + (Math.random()*100); f = 1 + Math.round(Math.random()*15); } this._WaveVoices.push(new WaveVoice(t,w,f,vol,d,s,sl)); totalGain += vol; } var amp = 1 / totalGain; // get seed // if (this.Params.seed.waveVoices && this._SeedLoad && this._LoadFromShare) { var seed = this.Params.seed; sequenceLength = seed.sequenceLength; seconds = seed.seconds; gain = seed.gain; noise = seed.noise; octaving = seed.octaving; glide = seed.glide; this._WaveVoices = seed.waveVoices; voices = seed.voices; harmonics = seed.harmonics; amp = seed.amp; this._SeedLoad = false; } //set seed // this.Params.seed = { sequenceLength: sequenceLength, seconds: seconds, gain: gain, noise: noise, octaving: octaving, glide: glide, waveVoices: this._WaveVoices, voices: voices, harmonics: harmonics, amp: amp }; //console.log(this.Params.seed); // GENERATE BUFFER DATA // var waveVoices = this._WaveVoices; var overflow = 800; var dataLength = data.length; for (var i=0; i<(dataLength + overflow); i++) { // FOR EACH VOICE // var totalVal = 0; for (var j=0; j<waveVoices.length; j++) { var v = waveVoices[j]; // voice type // switch (v.VoiceType) { case 0: if (i == (Math.round(dataLength/sequenceLength) * Math.round((sequenceLength/dataLength)*i)) && i<dataLength) { // if at a step point, update the sequence frequency // if (v.Sequence.length==0) { if (octaving==1) { v.FDest = (waveVoices[0].Frequency * (2*j)); } else if (octaving==2) { v.FDest = (waveVoices[0].Frequency / (2*j)); } else { v.FDest = (waveVoices[0].Frequency + (5*j)); } if (!v.Slide) { v.Frequency = v.FDest; } } else { v.FDest = v.Sequence[Math.floor((sequenceLength/dataLength)*i)]; if (!v.Slide) { v.Frequency = v.FDest; } } } if (v.Slide) { v.Frequency += (((v.FDest - v.Frequency)/10000))*glide; } v.Frequency *= v.Drift; break; case 1: v.FDest = (waveVoices[0].Frequency * j); if (v.Slide) { v.Frequency += (((v.FDest - v.Frequency)/10000))*glide; } else { v.Frequency = v.FDest; } break; } // cap freq range // var maxFreq = 20000; if (v.Frequency>maxFreq) { v.Frequency = maxFreq; } if (v.Frequency<1) { v.Frequency = 1; } // update total amplitude for this sample // totalVal += (v.Value * v.Volume); if (v.WaveType<2) { // TRIANGLE & SAW // update voice value // var step = (v.Frequency * ((amp*4)/sampleRate)); v.Value += (step * v.Polarity); // stay within amplitude bounds // if (v.Value > amp) { var spill = v.Value - amp; if (v.WaveType==1 && j<(voices + harmonics)) { v.Value = -(amp - spill); } else { v.Value = amp - spill; v.Polarity = - v.Polarity; } } if (v.Value < -amp) { var spill = (v.Value - (-amp)); v.Value = (-amp) - spill; v.Polarity = - v.Polarity; } } else { // SINE var a1 = v.Frequency * i*Math.PI*2/sampleRate; v.Value = Math.sin(a1) * amp; } } // write to 32 bit array var roam = (1 - (noise*0.5)) + (Math.random()*noise); var totalTotal = (totalVal * roam) * gain; if (i < (dataLength-1)) { data[i] = totalTotal; } // CROSSFADE // else { var ni = i - (dataLength-1); var gainA = 1 - ((1/overflow) * ni); var gainB = (1/overflow) * ni; data[ni] = (totalTotal*gainA) + (data[ni]*gainB); } } // POPULATE BUFFER // this.PopulateBuffer(sampleRate); } //------------------------------------------------------------------------------------------- // SETUP BUFFERS //------------------------------------------------------------------------------------------- PopulateBuffer(sampleRate) { if (!this.PrimaryBuffer) { this.PrimaryBuffer = App.Audio.ctx.createBuffer(1, this._BufferData.length, sampleRate); } this.PrimaryBuffer.copyToChannel(this._BufferData,0,0); this.WaveForm = App.Audio.Waveform.GetWaveformFromBuffer(this.PrimaryBuffer,200,5,95); var duration = this.GetDuration(this.PrimaryBuffer); if (!this._LoadFromShare) { this.Params.startPosition = 0; this.Params.loopStart = 0; this.Params.loopEnd = this.Params.endPosition = duration; this.Params.reverse = false; } // update options panel // this.RefreshOptionsPanel(); // update sources // this.Sources.forEach((s: Tone.Simpler)=> { s.player.buffer = this.PrimaryBuffer; s.player.loopStart = this.Params.loopStart; s.player.loopEnd = this.Params.loopEnd; //s.player.reverse = this.Params.reverse; }); // Reset reverse buffer // if (this.ReverseBuffer) { this.ReverseBuffer = null; } // if loaded from save & reverse // if (this._LoadFromShare && this.Params.reverse) { this.ReverseTrack(); } // IF POWERED ON LOAD - TRIGGER // if (this.IsPowered() && this._LoadFromShare) { // STOP SOUND // this.Sources.forEach((s: any)=> { s.triggerRelease(); }); // RETRIGGER // var that = this; setTimeout(function(){ that.TriggerAttack(); },1000); } this._LoadFromShare = false; } FirstSetup() { if (this._FirstRelease) { this.DataToBuffer(); this.Envelopes.forEach((e: Tone.AmplitudeEnvelope, i: number)=> { e = this.Sources[i].envelope; }); this.Sources.forEach((s: Tone.Simpler) => { s.connect(this.AudioInput); }); this._FirstRelease = false; } } Draw() { super.Draw(); this.DrawSprite(this.BlockName); } MouseUp() { this.FirstSetup(); super.MouseUp(); } UpdateOptionsForm() { super.UpdateOptionsForm(); this.OptionsForm = { "name" : App.L10n.Blocks.Source.Blocks.SampleGen.name, "parameters" : [ { "type" : "waveregion", "name" : "Wave", "setting" :"region", "props" : { "value" : 5, "min" : 0, "max" : this.GetDuration(this.PrimaryBuffer), "quantised" : false, "centered" : false, "wavearray" : this.WaveForm, "mode" : this.Params.loop, "emptystring" : "Generating Wave" },"nodes": [ { "setting": "startPosition", "value": this.Params.startPosition }, { "setting": "endPosition", "value": this.Params.endPosition }, { "setting": "loopStart", "value": this.Params.loopStart }, { "setting": "loopEnd", "value": this.Params.loopEnd } ] }, { "type" : "actionbutton", "name" : "Generate", "setting" :"generate", "props" : { "text" : "Generate Wave" } }, { "type" : "switches", "name" : "Loop", "setting" :"loop", "switches": [ { "name": "Reverse", "setting": "reverse", "value": this.Params.reverse, "lit" : true, "mode": "offOn" }, { "name": "Looping", "setting": "loop", "value": this.Params.loop, "lit" : true, "mode": "offOn" } ] }, { "type" : "slider", "name" : "playback", "setting" :"playbackRate", "props" : { "value" : this.Params.playbackRate, "min" : -App.Config.PlaybackRange, "max" : App.Config.PlaybackRange, "quantised" : false, "centered" : true } } ] }; } SetParam(param: string,value: any) { super.SetParam(param,value); var val = value; switch(param) { case "playbackRate": /*if ((<any>Tone).isSafari) { this.Sources[0].player.playbackRate = value; } else { this.Sources[0].player.playbackRate.value = value; }*/ this.Params.playbackRate = value; this.NoteUpdate(); break; case "generate": this.WaveForm = []; this.RefreshOptionsPanel(); // TODO - look into web workers for performance heavy executions like DataToBuffer var me = this; setTimeout(function() { me.DataToBuffer(); },16); break; case "reverse": value = value? true : false; this.Params[param] = val; this.ReverseTrack(); /*value = value? true : false; this._BufferData = this.ReverseTheBuffer(this._BufferData); this.PrimaryBuffer.copyToChannel(this._BufferData,0,0); this.Sources.forEach((s: Tone.Simpler)=> { s.player.buffer = this.PrimaryBuffer; }); this.Params[param] = val; // Update waveform this.WaveForm = App.Audio.Waveform.GetWaveformFromBuffer(this.PrimaryBuffer,200,5,95); this.RefreshOptionsPanel();*/ break; case "loop": value = value? true : false; this.Sources.forEach((s: Tone.Simpler)=> { s.player.loop = value; }); if (value === true && this.IsPowered()) { this.Sources.forEach((s: Tone.Simpler) => { s.player.stop(); s.player.start(s.player.startPosition); }); } // update display of loop sliders this.Params[param] = value; this.RefreshOptionsPanel(); break; case "loopStart": this.Sources.forEach((s: Tone.Simpler)=> { s.player.loopStart = value; }); break; case "loopEnd": this.Sources.forEach((s:Tone.Simpler)=> { s.player.loopEnd = value; }); break; } this.Params[param] = value; } Dispose(){ super.Dispose(); //TODO: Set everything to null } ReverseTheBuffer(buffer) { var newBuffer = new Float32Array(buffer.length); for (var i=0; i<buffer.length; i++) { newBuffer[i] = buffer[(buffer.length-1)-i]; } return newBuffer; } }
the_stack
import { Element } from "@siteimprove/alfa-dom"; import { Equatable } from "@siteimprove/alfa-equatable"; import { Hashable, Hash } from "@siteimprove/alfa-hash"; import { Iterable } from "@siteimprove/alfa-iterable"; import { Serializable } from "@siteimprove/alfa-json"; import { Option, None } from "@siteimprove/alfa-option"; import { Predicate } from "@siteimprove/alfa-predicate"; import { Sequence } from "@siteimprove/alfa-sequence"; import * as json from "@siteimprove/alfa-json"; import { Attribute } from "./attribute"; import { Feature } from "./feature"; import { Roles } from "./role/data"; import * as predicate from "./role/predicate"; const { and, not, nor } = Predicate; const roles = new Map<string, Role>(); /** * @public */ export class Role<N extends Role.Name = Role.Name> implements Equatable, Hashable, Serializable { public static of<N extends Role.Name>(name: N): Role<N> { let role = roles.get(name); if (role === undefined) { const { inherited } = Roles[name]; const attributes = new Set( [...Roles[name].attributes].map(([attribute]) => attribute) ); for (const parent of inherited) { for (const attribute of Role.of(parent).attributes) { attributes.add(attribute); } } role = new Role(name, [...attributes]); roles.set(name, role); } return role as Role<N>; } private readonly _name: N; private readonly _attributes: Array<Attribute.Name>; private constructor(name: N, attributes: Array<Attribute.Name>) { this._name = name; this._attributes = attributes; } public get name(): N { return this._name; } /** * Get all attributes supported by this role and its inherited roles. */ public get attributes(): ReadonlyArray<Attribute.Name> { return this._attributes; } /** * Get the required parent of this role. */ public get requiredParent(): ReadonlyArray<ReadonlyArray<Role.Name>> { return Roles[this._name].parent.required; } /** * Get the required children of this role. */ public get requiredChildren(): ReadonlyArray<ReadonlyArray<Role.Name>> { return Roles[this._name].children.required; } /** * Check if this role has the specified name. */ public hasName<N extends Role.Name>(name: N): this is Role<N> { return this._name === (name as Role.Name); } /** * Check if this role is a superclass of the role with the specified name. */ public isSuperclassOf<N extends Role.Name>( name: N ): this is Role<Role.SuperclassOf<N>> { const { inherited } = Roles[name]; for (const parent of inherited) { if (parent === this._name || this.isSuperclassOf(parent)) { return true; } } return false; } /** * Check if this role is a subclass of the role with the specified name. */ public isSubclassOf<N extends Role.Name>( name: N ): this is Role<Role.SubclassOf<N>> { return Role.of(name).isSuperclassOf(this._name); } /** * Check if this role either is, or is a subclass of, the role with the * specified name. */ public is<N extends Role.Name>( name: N ): this is Role<N | Role.SubclassOf<N>> { return this.hasName(name) || this.isSubclassOf(name); } /** * Check if this role is abstract. */ public isAbstract(): this is Role<Role.Abstract> { return Roles[this._name].abstract; } /** * Check if this role is non-abstract. */ public isConcrete(): this is Role<Role.Concrete> { return !this.isAbstract(); } /** * Check if this role is presentational. */ public isPresentational(): this is Role<Role.Presentational> { return this.hasName("presentation") || this.hasName("none"); } /** * Check if this role is a widget. */ public isWidget(): this is Role<Role.Widget> { return this.is("widget"); } /** * Check if this role is a landmark. */ public isLandmark(): this is Role<Role.Landmark> { return this.is("landmark"); } /** * Check if this role supports naming by the specified method. */ public isNamedBy(method: Role.NamedBy): boolean { for (const found of Roles[this._name].name.from) { if (found === method) { return true; } } return false; } /** * Check if this role prohibits naming. */ public isNameProhibited(): boolean { return Roles[this._name].name.prohibited; } /** * Check if this role has a required parent. */ public hasRequiredParent(): boolean { return Roles[this._name].parent.required.length > 0; } /** * Check if this role has presentational children. */ public hasPresentationalChildren(): boolean { return Roles[this._name].children.presentational; } /** * Check if this role has required children. */ public hasRequiredChildren(): boolean { return Roles[this._name].children.required.length > 0; } /** * Check if this role supports the specified attribute. */ public isAttributeSupported(name: Attribute.Name): boolean { const { inherited, attributes } = Roles[this._name]; for (const [found] of attributes) { if (name === found) { return true; } } for (const parent of inherited) { if (Role.of(parent).isAttributeSupported(name)) { return true; } } return false; } /** * Check if this role requires the specified attribute. */ public isAttributeRequired(name: Attribute.Name): boolean { const { inherited, attributes } = Roles[this._name]; for (const [found, { required }] of attributes) { if (name === found && required) { return true; } } for (const parent of inherited) { if (Role.of(parent).isAttributeRequired(name)) { return true; } } return false; } /** * Get the implicit value of the specified attribute, if any. */ public implicitAttributeValue(name: Attribute.Name): Option<string> { const { inherited, attributes } = Roles[this._name]; for (const [found, { value }] of attributes) { if (name === found && value !== null) { return Option.from(value); } } for (const parent of inherited) { for (const value of Role.of(parent).implicitAttributeValue(name)) { return Option.of(value); } } return None; } public equals(value: unknown): value is this { return value instanceof Role && value._name === this._name; } public hash(hash: Hash): void { hash.writeString(this._name); } public toJSON(): Role.JSON { return { name: this._name, }; } } /** * @public */ export namespace Role { export interface JSON { [key: string]: json.JSON; name: Name; } export type Name = keyof Roles; export function isName(value: string): value is Name { return value in Roles; } /** * The names of all abstract roles. */ export type Abstract = { [N in Name]: Roles[N]["abstract"] extends true ? N : never; }[Name]; /** * The names of all non-abstract roles. */ export type Concrete = Exclude<Name, Abstract>; /** * The names of all presentational roles. * * @remarks * In WAI-ARIA, the role `none` is defined to be synonymous with the role * `presentation`. We therefore refer collectively to the two roles as the * presentational roles. */ export type Presentational = "presentation" | "none"; /** * The names of all widget roles. */ export type Widget = SubclassOf<"widget">; /** * The names of all landmark roles. */ export type Landmark = SubclassOf<"landmark">; /** * The inherited roles for the specified role. */ export type Inherited<N extends Name> = N extends "roletype" | "none" ? never : Members<Roles[N]["inherited"]>; /** * All roles that are subclasses of the specified role. */ export type SubclassOf<N extends Name> = { [M in Name]: N extends SuperclassOf<M> ? M : never; }[Name]; /** * All roles that are superclasses of the specified role. * * @remarks * The super roles `roletype` and `none` act as base conditions of the * recursive type construction in order to avoid the TypeScript compiler * infinitely recursing while instantiating the type. */ export type SuperclassOf<N extends Name> = N extends "roletype" | "none" ? never : Inherited<N> | { [M in Inherited<N>]: SuperclassOf<M> }[Inherited<N>]; /** * The methods by which the element assigned to the specified role may receive * its name. */ export type NamedBy<N extends Name = Name> = Members< Roles[N]["name"]["from"] >; export function isRole<N extends Name>( value: unknown, name?: N ): value is Role<Name> { return value instanceof Role && (name === undefined || value.name === name); } /** * Get the role assigned either explicitly or implicitly to an element, if * any. */ export function from(element: Element): Option<Role> { return fromExplicit(element).orElse(() => fromImplicit(element)); } /** * Get the role explicitly assigned to an element, if any. */ export function fromExplicit(element: Element): Option<Role> { const roles: Sequence<string> = element .attribute("role") .map((attribute) => attribute.tokens()) .getOrElse(() => Sequence.empty()); return ( roles .map((role) => role.toLowerCase()) .filter(isName) .map(Role.of) // Abstract roles are only used for ontological purposes and are not // allowed to be used by authors; we therefore filter them out. .reject((role) => role.isAbstract()) // If the element is not allowed to be presentational, reject all // presentational roles. .reject((role) => isAllowedPresentational(element) ? false : role.isPresentational() ) .first() ); } /** * Get the role implicitly assigned to an element, if any. */ export function fromImplicit(element: Element): Option<Role> { return element.namespace.flatMap((namespace) => Feature.from(namespace, element.name).flatMap((feature) => Sequence.from(feature.role(element)) // If the element is not allowed to be presentational, reject all // presentational roles. .reject((role) => isAllowedPresentational(element) ? false : role.isPresentational() ) .first() ) ); } export const { hasName } = predicate; } type Members<T> = T extends Iterable<infer T> ? T : never; /** * Check if an element has one or more global `aria-*` attributes. */ const hasGlobalAttributes: Predicate<Element> = (element) => Iterable.some(Role.of("roletype").attributes, (attribute) => element.attribute(attribute).isSome() ); /** * Check if an element is potentially focusable, not accounting for whether or * not the element is rendered. */ const isPotentiallyFocusable: Predicate<Element> = and( Element.hasTabIndex(), not(Element.isDisabled) ); /** * Check if an element is allowed to be assigned a presentational role. */ const isAllowedPresentational: Predicate<Element> = nor( hasGlobalAttributes, isPotentiallyFocusable );
the_stack
import { FilterOutlined } from "@ant-design/icons"; import { AutoComplete, Button, Checkbox, Input, Modal, Popover, Typography } from "antd"; import Item from "antd/lib/list/Item"; import Paragraph from "antd/lib/typography/Paragraph"; import arrayMove from "array-move"; import { AnimatePresence, motion } from "framer-motion"; import { computed, makeObservable, observable } from "mobx"; import { observer } from "mobx-react"; import React from "react"; import { Component } from "react"; import { DragDropContext, Draggable, Droppable, DropResult, ResponderProvided } from "react-beautiful-dnd"; import { api } from "../../../../state/backendApi"; import { PreviewTagV2 } from "../../../../state/ui"; import { uiState } from "../../../../state/uiState"; import { MotionDiv } from "../../../../utils/animationProps"; import { IsDev } from "../../../../utils/env"; import { clone, toJson } from "../../../../utils/jsonUtils"; import { Code, Label, OptionGroup, QuickTable, toSafeString } from "../../../../utils/tsxUtils"; import { getAllMessageKeys, randomId, collectElements2, CollectedProperty } from "../../../../utils/utils"; import globExampleImg from '../../../../assets/globExample.png'; import { InfoIcon, ThreeBarsIcon, GearIcon, XIcon } from "@primer/octicons-react"; const { Text } = Typography; const globHelp = <div> {/* Examples + Image */} <div style={{ display: 'flex', gap: '2em', minWidth: '900px' }}> <div style={{ flexGrow: 1 }}> <h3>Glob Pattern Examples</h3> <div className="globHelpGrid"> <div className='h'>Pattern</div> <div className='h'>Result</div> <div className='h'>Reason / Explanation</div> <div className='titleRowSeparator' /> {/* Example */} <div className="c1"><Code>id</Code></div> <div className="c2">id: 1111</div> <div className="c3">There is only one 'id' property at the root of the object</div> <div className='rowSeparator' /> {/* Example */} <div className="c1 "><Code>*.id</Code></div> <div className="c2"> <div>customer.id: 2222</div> <div>key.with.dots.id: 3333</div> </div > <div className="c3">Star only seraches in direct children. Here, only 2 children contain an 'id' prop</div> <div className='rowSeparator' /> {/* Example */} <div className="c1"><Code>**.id</Code></div> <div className="c2"> (all ID properties) </div > <div className="c3">Double-star searches everywhere</div> <div className='rowSeparator' /> {/* Example */} <div className="c1"><Code>customer.*Na*</Code></div> <div className="c2"> <div>customer.firstName: John</div> <div>customer.lastName: Example</div> </div > <div className="c3">In the direct child named 'customer', find all properties that contain 'Na'</div> <div className='rowSeparator' /> {/* Example */} <div className="c1"><Code>key.with.dots.id</Code></div> <div className="c2">(no results!)</div> <div className="c3">There is no property named 'key'!</div> <div className='rowSeparator' /> {/* Example */} <div className="c1"><Code>"key.with.dots".id</Code></div> <div className="c2">key.with.dots.id: 3333</div> <div className="c3">To find properties with special characters in their name, use single or double-quotes</div> <div className='rowSeparator' /> </div> </div> <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}> <div style={{ opacity: 0.5, fontSize: 'smaller', textAlign: 'center' }}>Example Data</div> <img src={globExampleImg} alt="Examples for glob patterns" /> </div> </div> {/* Details */} <div> <h3>Details</h3> <div> A glob pattern is just a list of property names seperated by dots. In addition to simple property names you can use: </div> <ul style={{ paddingLeft: '2em', marginTop: '.5em' }}> <li><Code>*</Code> Star to match all current properties</li> <li><Code>**</Code> Double-Star to matches all current and nested properties</li> <li><Code>"</Code>/<Code>'</Code> Quotes for when a property-name contains dots</li> <li><Code>abc*</Code> One or more stars within a name. Depending on where you place the star, you can check if a name starts with, ends with, or contains some string.</li> </ul> </div> </div>; @observer export class PreviewSettings extends Component<{ getShowDialog: () => boolean, setShowDialog: (show: boolean) => void }> { @computed.struct get allCurrentKeys() { const unused = api.messages.length; // console.log("get all current keys: " + unused); return getAllMessageKeys(api.messages).map(p => p.propertyName).distinct(); } constructor(p: any) { super(p); makeObservable(this); } render() { const currentKeys = this.props.getShowDialog() ? this.allCurrentKeys : []; const tags = uiState.topicSettings.previewTags; // add ids to elements that don't have any const getFreeId = function (): string { let i = 1; // eslint-disable-next-line no-loop-func while (tags.any(t => t.id == String(i))) i++; return String(i); }; tags.filter(t => !t.id).forEach(t => t.id = getFreeId()); const onDragEnd = function (result: DropResult, provided: ResponderProvided) { if (!result.destination) return; arrayMove.mutate(tags, result.source.index, result.destination.index); }; const content = <> <div> <span style={{ display: 'inline-flex' }}> When viewing large messages we're often only interested in a few specific fields. Add <Popover trigger={['click']} placement='bottom' content={globHelp}> <span style={{ display: 'inline-flex', gap: '2px', margin: '0 0.6ch', color: 'hsl(205deg, 100%, 50%)', textDecoration: 'underline dotted', cursor: 'pointer' }}><InfoIcon size={15} />glob patterns</span> </Popover> to this list to show found values as previews. </span> </div> <div className="previewTagsList"> <DragDropContext onDragEnd={onDragEnd} > <Droppable droppableId="droppable"> {(droppableProvided, droppableSnapshot) => ( <div ref={droppableProvided.innerRef} style={{ display: 'flex', flexDirection: 'column' }} > {tags.map((tag, index) => ( <Draggable key={tag.id} draggableId={tag.id} index={index}> {(draggableProvided, draggableSnapshot) => ( <div ref={draggableProvided.innerRef} {...draggableProvided.draggableProps} {...draggableProvided.dragHandleProps} > <PreviewTagSettings tag={tag} index={index} onRemove={() => tags.removeAll(t => t.id == tag.id)} allCurrentKeys={currentKeys} /> </div> )} </Draggable> ))} {droppableProvided.placeholder} <Button onClick={() => { const newTag: PreviewTagV2 = { id: getFreeId(), isActive: true, pattern: '', searchInMessageHeaders: false, searchInMessageKey: false, searchInMessageValue: true, }; tags.push(newTag); }}>Add entry...</Button> </div> )} </Droppable> </DragDropContext> {/* <CustomTagList tags={uiState.topicSettings.previewTags} allCurrentKeys={this.props.allCurrentKeys} /> */} </div> <div style={{ marginTop: '1em' }}> <h3 style={{ marginBottom: '0.5em' }}>Settings</h3> <div className="previewTagsSettings" > <OptionGroup label='Matching' options={{ 'Ignore Case': false, 'Case Sensitive': true }} size='small' value={uiState.topicSettings.previewTagsCaseSensitive} onChange={e => uiState.topicSettings.previewTagsCaseSensitive = e} /> <OptionGroup label='Multiple Results' options={{ 'First result': 'showOnlyFirst', 'Show All': 'showAll' }} value={uiState.topicSettings.previewMultiResultMode} onChange={e => uiState.topicSettings.previewMultiResultMode = e} /> <OptionGroup label='Wrapping' options={{ 'Single Line': 'single', 'Wrap': 'wrap', 'Rows': 'rows' }} value={uiState.topicSettings.previewDisplayMode} onChange={e => uiState.topicSettings.previewDisplayMode = e} /> </div> </div> </>; return <Modal title={<span><FilterOutlined style={{ fontSize: '22px', verticalAlign: 'bottom', marginRight: '16px', color: 'hsla(209, 20%, 35%, 1)' }} />Preview Fields</span>} visible={this.props.getShowDialog()} style={{ minWidth: '750px', maxWidth: '1000px', top: '26px' }} width={'auto'} bodyStyle={{ paddingTop: '12px' }} centered={false} okText='Close' cancelButtonProps={{ style: { display: 'none' } }} onOk={() => this.props.setShowDialog(false)} onCancel={() => this.props.setShowDialog(false)} closable={false} maskClosable={true} > {content} </Modal>; } } /* todo: - mark patterns red when they are invalid - better auto-complete: get suggestions from current pattern (except for last segment) - */ @observer class PreviewTagSettings extends Component<{ tag: PreviewTagV2, index: number, onRemove: () => void, allCurrentKeys: string[] }>{ render() { const { tag, index, onRemove, allCurrentKeys } = this.props; return <div style={{ display: 'flex', placeItems: 'center', gap: '4px', background: 'hsl(0deg, 0%, 91%)', padding: '4px', borderRadius: '4px', marginBottom: '6px' }}> {/* Move Handle */} <span className="moveHandle"><ThreeBarsIcon /></span> {/* Enabled */} <Checkbox checked={tag.isActive} onChange={e => tag.isActive = e.target.checked} /> {/* Settings */} <Popover trigger={['click']} placement='bottomLeft' arrowPointAtCenter={true} content={<div style={{ display: 'flex', flexDirection: 'column', gap: '.3em' }} > <Label text="Display Name" style={{ marginBottom: '.5em' }}> <Input size='small' style={{ flexGrow: 1, flexBasis: '50px' }} value={tag.customName} onChange={e => tag.customName = e.target.value} autoComplete={randomId()} spellCheck={false} placeholder="Enter a display name..." /> </Label> <span><Checkbox checked={tag.searchInMessageKey} onChange={e => tag.searchInMessageKey = e.target.checked}>Search in message key</Checkbox></span> <span><Checkbox checked={tag.searchInMessageValue} onChange={e => tag.searchInMessageValue = e.target.checked}>Search in message value</Checkbox></span> </div>}> <span className="inlineButton" ><GearIcon /></span> </Popover> {/* Pattern */} <AutoComplete options={allCurrentKeys.map(t => ({ label: t, value: t }))} size="small" style={{ flexGrow: 1, flexBasis: '400px' }} defaultActiveFirstOption={true} onSearch={(value) => { // console.log('onSearch ', value); }} value={tag.pattern} onChange={e => tag.pattern = e} placeholder="Pattern..." filterOption={(inputValue, option) => option?.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1} notFoundContent="None" {...{ spellCheck: "false" }} /> {/* Remove */} <span className="inlineButton" onClick={onRemove} ><XIcon /></span> </div>; } } /* todo: - support regex patterns as path elements - `data./pattern/.email` - in order to match `/pattern/` our 'parseJsonPath' must support escaping forward slashes: "\/" */ export function getPreviewTags(targetObject: any, tags: PreviewTagV2[]): React.ReactNode[] { const ar: React.ReactNode[] = []; const results: { prop: CollectedProperty, tag: PreviewTagV2, fullPath: string }[] = []; const caseSensitive = uiState.topicSettings.previewTagsCaseSensitive; for (const t of tags) { if (t.pattern.length == 0) continue; const trimmed = t.pattern.trim(); const searchPath = parseJsonPath(trimmed); if (searchPath == null) continue; if (typeof searchPath == 'string') continue; // todo: show error to user const foundProperties = collectElements2(targetObject, searchPath, (pathElement, propertyName, value) => { // We'll never get called for '*' or '**' patterns // So we can be sure that the pattern is not just '*' const segmentRegex = caseSensitive ? wildcardToRegex(pathElement) : new RegExp(wildcardToRegex(pathElement), 'i'); return segmentRegex.test(propertyName); }); for (const p of foundProperties) results.push({ tag: t, prop: p, fullPath: p.path.join('.'), }); } // order results by their path results.sort((a, b) => { // first sort by path length const pathLengthDiff = a.prop.path.length - b.prop.path.length; if (pathLengthDiff != 0) return pathLengthDiff; // then alphabetically const pathA = a.fullPath; const pathB = b.fullPath; return pathA.localeCompare(pathB, undefined, // no locales { numeric: true, ignorePunctuation: false, sensitivity: 'base', }); }); // found some properties, create JSX for them for (const r of results) { const tag = r.tag; const displayName = tag.customName && tag.customName.length > 0 ? tag.customName : r.fullPath; ar.push(<span className='previewTag'> <span className='path'>{displayName}</span> <span>{toSafeString(r.prop.value)}</span> </span >); } return ar; } const splitChars = ["'", "\"", "."]; // Splits a given path into its path segments. // Path segments are seperated by the dot-character. // This function also supports quotes, so that the dot can still be used (the path segment just needs to be wrapped in quotes then). // Returns: // - String array when the path was parsed correctly // - Single string as error reason why the path couldn't be parsed function parseJsonPath(str: string): string[] | string { // Collect symbols until we find a dot, single-quote, or double-quote const result: string[] = []; let pos = 0; while (pos < str.length) { let c = str[pos]; let start: number; let end: number; let match: string; switch (c) { case "'": case "\"": // A quote is opened // Find the closing quote and collect everything in-between start = pos + 1; // start just after the quote end = str.indexOf(c, start); // and collect until the closing quote if (end == -1) return "missing closing quote, quote was opened at index " + (start - 1); match = str.slice(start, end); if (match.length > 0) result.push(match); pos = end == -1 ? str.length : end + 1; // continue after the end of our string and the closing quote break; case ".": // A dot, skip over it if (pos == 0) return "pattern cannot start with a dot"; pos++; if (pos >= str.length) return "pattern can not end with a dot"; c = str[pos]; if (c == '.') return "pattern cannot contain more than one dot in a row"; break; default: // We're at a simple character, just collect everything until the next dot or quote start = pos; // start here end = indexOfMany(str, splitChars, pos); // collect until dot or quote match = end >= 0 ? str.slice(start, end) : str.slice(start, str.length); if (match.length > 0) result.push(match); pos = end == -1 ? str.length : end; // continue after the end break; } } // While we do support the '**' pattern, it must always appear alone. // In other words, a path segment is valid if it is exactly equal to '**', // but it is invalid if it contains '**' // // Valid example paths: can appear anywhere as long as it is // **.a.b.c // a.b.**.c.** // a.b.** // // Invalid example paths: // b**c.d // a.b** // a.**b // for (const segment of result) { if (segment != "**" && segment.includes("**")) return "path segment '**' must not have anything before or after it (except for dots of course)"; } return result; } function indexOfMany(str: string, matches: string[], position: number): number { const indices: number[] = matches.map(_ => -1); // for every string we want to find, record the index of its first occurance for (let i = 0; i < matches.length; i++) indices[i] = str.indexOf(matches[i], position); // find the first match (smallest value in our results) // but skip over -1, because that means the string didn't contain that match let smallest = -1; for (const i of indices) { if (smallest == -1 || i < smallest) smallest = i; } return smallest; } if (IsDev) { const tests = [ // simple case { input: `abc`, output: [`abc`] }, // single quotes, double quotes { input: `"xx"."yy"`, output: [`xx`, `yy`] }, { input: `'xx'.'yy'`, output: [`xx`, `yy`] }, { input: `".".'.'`, output: [`.`, `.`] }, // keys with split-characters inside them { input: `"'a.'b".asdf`, output: [`'a.'b`, `asdf`] }, { input: `"x.y.z".firstName`, output: [`x.y.z`, `firstName`] }, { input: `a.".b"`, output: [`a`, `.b`] }, { input: `a.'.b'`, output: [`a`, `.b`] }, { input: `a.'""".b"'`, output: [`a`, `""".b"`] }, { input: `a.'""".b'`, output: [`a`, `""".b`] }, // empty { input: ``, output: [] }, { input: `''`, output: [] }, { input: `""`, output: [] }, // invalid inputs // missing closing quotes { input: `"`, output: null }, { input: `."`, output: null }, { input: `".`, output: null }, { input: `'`, output: null }, { input: `.'`, output: null }, { input: `'.`, output: null }, // dots at the wrong location { input: `.`, output: null }, { input: `'a'.`, output: null }, { input: `.a`, output: null }, { input: `.'a'`, output: null }, { input: `a..b`, output: null }, ]; for (const test of tests) { const expected = test.output; let result = parseJsonPath(test.input); if (typeof result == 'string') result = null as unknown as string[]; // string means error message if (result === null && expected === null) continue; let hasError = false; if (result === null && expected !== null) hasError = true; // didn't match when it should have if (result !== null && expected === null) hasError = true; // matched something we don't want if (!hasError && result && expected) { if (result.length != expected.length) hasError = true; // wrong length for (let i = 0; i < result.length && !hasError; i++) if (result[i] != expected[i]) hasError = true; // wrong array entry } if (hasError) throw new Error(`Error in parseJsonPath test:\nTest: ${JSON.stringify(test)}\nActual Result: ${JSON.stringify(result)}`); } } function wildcardToRegex(pattern: string): RegExp { const components = pattern.split('*'); // split by '*' symbol const escapedComponents = components.map(regexEscape); // ensure the components don't contain regex special characters const joined = escapedComponents.join('.*'); // join components, adding back the wildcard return new RegExp('^' + joined + '$'); } function regexEscape(regexPattern: string): string { return regexPattern.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); }
the_stack
import { API, ASTPath, FileInfo, Identifier, ImportDeclaration, MemberExpression, Property, } from 'jscodeshift'; const legacyTypeLevelsMap = { dataViz1: 'levels.title.large', dataViz2: 'levels.heading.large', h1: 'levels.heading.medium', h2: 'levels.heading.small', h3: 'levels.body.large', h4: 'levels.body.small', h5: 'levels.body.small', body: 'levels.subtext.large', body2: 'levels.subtext.medium', small: 'levels.subtext.medium', }; const legacyTypeFontSizesMap = { dataViz1: 56, dataViz2: 32, h1: 28, h2: 24, h3: 20, h4: 16, h5: 16, body: 14, body2: 12, small: 12, }; const betaTypeLevelsMap = { brand1: 'levels.title.large', brand2: 'levels.title.medium', h1: 'levels.title.small', h2: 'levels.heading.large', h3: 'levels.heading.small', h4: 'levels.body.large', h5: 'levels.body.large', body: 'levels.body.small', body2: 'levels.subtext.large', small: 'levels.subtext.medium', }; const betaTypeFontSizesMap = { brand1: 56, brand2: 48, h1: 40, h2: 32, h3: 24, h4: 20, h5: 20, body: 16, body2: 14, small: 12, }; const fontWeightsMap = { brand1: 'bold', brand2: 'bold', dataViz1: 'bold', dataViz2: 'bold', h1: 'bold', h2: 'bold', h3: 'bold', h4: 'bold', h5: 'bold', body: 'regular', body2: 'regular', small: 'regular', }; export default function transformer(file: FileInfo, api: API) { const j = api.jscodeshift; const root = j(file.source); // Find all legacy `type` import statements from react/tokens const legacyTypeImportSpecifiers = root .find(j.ImportSpecifier, {imported: {name: 'type'}}) .filter(nodePath => { const parent = nodePath.parent.value as ImportDeclaration; // This extra filter ensures we aren't improperly transforming other variables return parent.source.value === '@workday/canvas-kit-react/tokens'; }); // Find all beta `type` import statements from preview-react/tokens labs-react/tokens const betaTypeImportSpecifiers = root .find(j.ImportSpecifier, {imported: {name: 'type'}}) .filter(nodePath => { const parent = nodePath.parent.value as ImportDeclaration; // This extra filter ensures we aren't improperly transforming other variables return ( parent.source.value === '@workday/canvas-kit-preview-react/tokens' || parent.source.value === '@workday/canvas-kit-labs-react/tokens' ); }); // Find all canvas import statements from react/tokens const canvasImportDefaultSpecifiers = root .find(j.ImportDefaultSpecifier, {local: {name: 'canvas'}}) .filter(nodePath => { const parent = nodePath.parent.value as ImportDeclaration; // This extra filter ensures we aren't improperly transforming other variables return parent.source.value === '@workday/canvas-kit-react/tokens'; }); function updateFontFamily( nodePath: ASTPath<MemberExpression>, identifierName: string, isDefaultImport?: boolean ) { const updatedProperty = j.memberExpression( j.identifier(identifierName), j.memberExpression( j.identifier('properties'), j.memberExpression(j.identifier('fontFamilies'), j.identifier('default'), false), false ), false ); if (isDefaultImport) { return nodePath.parent.replace( j.memberExpression(j.identifier('canvas'), updatedProperty, false) ); } nodePath.parent.replace(updatedProperty); } function updateFontSize( nodePath: ASTPath<MemberExpression>, importSpecifierName: string, identifierName: string, typeMap: 'legacy' | 'beta', isDefaultImport?: boolean ) { const updatedFontSizeValue = typeMap === 'legacy' ? legacyTypeFontSizesMap[identifierName as keyof typeof legacyTypeFontSizesMap] : betaTypeFontSizesMap[identifierName as keyof typeof betaTypeFontSizesMap]; const updatedProperty = j.memberExpression( j.identifier(importSpecifierName), j.memberExpression( j.identifier('properties'), j.memberExpression(j.identifier('fontSizes'), j.literal(updatedFontSizeValue), true), false ), false ); if (isDefaultImport) { return nodePath.parent.replace( j.memberExpression(j.identifier('canvas'), updatedProperty, false) ); } nodePath.parent.replace(updatedProperty); } function updateFontWeight( nodePath: ASTPath<MemberExpression>, importSpecifierName: string, identifierName: string, isDefaultImport?: boolean ) { const updatedFontWeight = fontWeightsMap[identifierName as keyof typeof fontWeightsMap]; const updatedProperty = j.memberExpression( j.identifier(importSpecifierName), j.memberExpression( j.identifier('properties'), j.memberExpression(j.identifier('fontWeights'), j.identifier(updatedFontWeight)), false ), false ); if (isDefaultImport) { return nodePath.parent.replace( j.memberExpression(j.identifier('canvas'), updatedProperty, false) ); } nodePath.parent.replace(updatedProperty); } function replaceVariantProperties(nodePath: ASTPath<MemberExpression>, properties: Property[]) { const grandParentNodeType = nodePath.parent.parent.value.type; // This covers variant object styles and variants in styled components />` if ( grandParentNodeType === 'JSXExpressionContainer' || grandParentNodeType === 'CallExpression' ) { return nodePath.parent.replace(j.objectExpression(properties)); } // And this covers all other variant transformations properties.forEach((property, index) => { if (index === 0) { // Replace the first property provided nodePath.parent.parent.replace(property); } else { // Insert any additional properties after nodePath.parent.parent.insertAfter(property); } }); } function updateVariant( nodePath: ASTPath<MemberExpression>, importSpecifierName: string, variantName: string, isDefaultImport?: boolean ) { switch (variantName) { case 'error': case 'hint': case 'inverse': { // Update the node property name from 'variant' to 'variants' nodePath.value.property = j.identifier('variants'); break; } case 'button': { const newFontWeightProperty = j.property( 'init', j.identifier('fontWeight'), j.memberExpression( j.identifier(importSpecifierName), j.memberExpression( j.identifier('properties'), j.memberExpression(j.identifier('fontWeights'), j.identifier('bold'), false), false ), false ) ); const newFontWeightMemberExpression = j.memberExpression( j.identifier('canvas'), j.memberExpression( j.identifier(importSpecifierName), j.memberExpression( j.identifier('properties'), j.memberExpression(j.identifier('fontWeights'), j.identifier('bold'), false), false ), false ), false ); if (isDefaultImport) { const newCanvasProperty = j.property( 'init', j.identifier('fontWeight'), newFontWeightMemberExpression ); return replaceVariantProperties(nodePath, [newCanvasProperty]); } // Replace the target node with the new fontWeight property replaceVariantProperties(nodePath, [newFontWeightProperty]); break; } case 'caps': { // Create a new property: `fontWeight: {importSpecifierName}.properties.fontWeights.medium` const newFontWeightProperty = j.property( 'init', j.identifier('fontWeight'), j.memberExpression( j.identifier(importSpecifierName), j.memberExpression( j.identifier('properties'), j.memberExpression(j.identifier('fontWeights'), j.identifier('medium'), false), false ), false ) ); const newFontWeightMemberExpression = j.memberExpression( j.identifier('canvas'), j.memberExpression( j.identifier(importSpecifierName), j.memberExpression( j.identifier('properties'), j.memberExpression(j.identifier('fontWeights'), j.identifier('medium'), false), false ), false ), false ); // Create a new property: `textTransform: 'uppercase'` const newTextTransformProperty = j.property( 'init', j.identifier('textTransform'), j.literal('uppercase') ); if (isDefaultImport) { const newCanvasProperty = j.property( 'init', j.identifier('fontWeight'), newFontWeightMemberExpression ); return replaceVariantProperties(nodePath, [newCanvasProperty, newTextTransformProperty]); } // Replace the target node with the new fontWeight and text transform properties replaceVariantProperties(nodePath, [newFontWeightProperty, newTextTransformProperty]); break; } case 'label': { // Create a new property: `fontWeight: {importSpecifierName}.properties.fontWeights.medium` const newFontWeightProperty = j.property( 'init', j.identifier('fontWeight'), j.memberExpression( j.identifier(importSpecifierName), j.memberExpression( j.identifier('properties'), j.memberExpression(j.identifier('fontWeights'), j.identifier('medium'), false), false ), false ) ); const newFontWeightMemberExpression = j.memberExpression( j.identifier('canvas'), j.memberExpression( j.identifier(importSpecifierName), j.memberExpression( j.identifier('properties'), j.memberExpression(j.identifier('fontWeights'), j.identifier('medium'), false), false ), false ), false ); if (isDefaultImport) { const newCanvasProperty = j.property( 'init', j.identifier('fontWeight'), newFontWeightMemberExpression ); return replaceVariantProperties(nodePath, [newCanvasProperty]); } // Replace the target node with the new fontWeight property replaceVariantProperties(nodePath, [newFontWeightProperty]); break; } case 'mono': { const newFontProperty = j.property( 'init', j.identifier('fontFamily'), j.memberExpression( j.identifier(importSpecifierName), j.memberExpression( j.identifier('properties'), j.memberExpression(j.identifier('fontFamilies'), j.identifier('monospace'), false), false ), false ) ); const newFontMemberExpression = j.memberExpression( j.identifier('canvas'), j.memberExpression( j.identifier(importSpecifierName), j.memberExpression( j.identifier('properties'), j.memberExpression(j.identifier('fontFamilies'), j.identifier('monospace'), false), false ), false ), false ); if (isDefaultImport) { const newCanvasProperty = j.property( 'init', j.identifier('fontFamily'), newFontMemberExpression ); return replaceVariantProperties(nodePath, [newCanvasProperty]); } replaceVariantProperties(nodePath, [newFontProperty]); break; } default: { break; } } } function updateTypeHierarchy( nodePath: ASTPath<MemberExpression>, identifierName: string, typeMap: 'legacy' | 'beta' ) { const updatedTypeLevelProperty = typeMap === 'legacy' ? legacyTypeLevelsMap[identifierName as keyof typeof legacyTypeLevelsMap] : betaTypeLevelsMap[identifierName as keyof typeof betaTypeLevelsMap]; nodePath.value.property = j.identifier(updatedTypeLevelProperty); } function updateHeadingFontWeight( nodePath: ASTPath<MemberExpression>, importSpecifierName: string, legacy?: boolean ) { const newFontWeightMemberExpression = j.memberExpression( j.identifier(importSpecifierName), j.memberExpression( j.identifier('properties'), j.memberExpression(j.identifier('fontWeights'), j.identifier('bold'), false), false ), false ); const fontWeightProperty = j.property( 'init', j.identifier('fontWeight'), legacy ? j.memberExpression(j.identifier('canvas'), newFontWeightMemberExpression, false) : newFontWeightMemberExpression ); if (nodePath.parent.parent.value.type === 'ObjectExpression') { return nodePath.parent.parent.value.properties.push(fontWeightProperty); } else if (nodePath.parent.value.type === 'CallExpression') { const typeArgIndex = nodePath.parent.value.arguments.indexOf(nodePath.value); return nodePath.parent.value.arguments.splice(typeArgIndex + 1, 0, fontWeightProperty); } else if (nodePath.parent.value.type === 'JSXExpressionContainer') { return nodePath.replace( j.objectExpression([j.spreadElement(nodePath.value), fontWeightProperty]) ); } } // Run only if there are type imports from react/tokens if (legacyTypeImportSpecifiers.paths().length) { // Iterate over all type import specifiers and transform their corresponding member expressions legacyTypeImportSpecifiers.forEach(importSpecifier => { // Use either the local or imported name for the import specifier // e.g. `import { type as typeTokens } from '@workday/canvas-kit-react/tokens';` // 'type' is the imported name, and 'typeTokens' is the local name const importSpecifierName = importSpecifier.value.local?.name || importSpecifier.value.imported.name; // Find all member expressions using the specifier name root .find(j.MemberExpression, {object: {type: 'Identifier', name: importSpecifierName}}) .forEach(nodePath => { const parentProperty = nodePath.parent.value.property; const propertyIdentifier = nodePath.value.property as Identifier; const identifierName = propertyIdentifier.name; // Handle font-family transformations if (parentProperty && parentProperty.name === 'fontFamily') { return updateFontFamily(nodePath, importSpecifierName); } // Handle font-size transformations if (parentProperty && parentProperty.name === 'fontSize') { return updateFontSize(nodePath, importSpecifierName, identifierName, 'legacy'); } // Handle font-weight transformations if (parentProperty && parentProperty.name === 'fontWeight') { return updateFontWeight(nodePath, importSpecifierName, identifierName); } // Handle variant transformations if (parentProperty && propertyIdentifier.name === 'variant') { const variantName = parentProperty.name; return updateVariant(nodePath, importSpecifierName, variantName); } // Handle type hierarchy transformations if (identifierName in legacyTypeLevelsMap) { updateTypeHierarchy(nodePath, identifierName, 'legacy'); if (identifierName === 'h3' || identifierName === 'h4') { updateHeadingFontWeight(nodePath, importSpecifierName); } return; } return nodePath; }); }); } if (canvasImportDefaultSpecifiers.paths().length) { // Only run if there are canvas default imports from react/tokens or labs-react/tokens canvasImportDefaultSpecifiers.forEach(importDefaultSpecifier => { root .find(j.MemberExpression, {object: {type: 'Identifier', name: 'canvas'}}) .forEach(nodePath => { const grandParentProperty = nodePath.parent.parent.value.property; const parentProperty = nodePath.parent.value.property; const parentIdentifierName = parentProperty.name; const propertyIdentifier = nodePath.value.property as Identifier; const identifierName = propertyIdentifier.name; if (identifierName === 'type') { // Handle font-family transformations if (grandParentProperty && grandParentProperty.name === 'fontFamily') { updateFontFamily(nodePath.parent, 'type', true); } // Handle font-family transformations if (grandParentProperty && grandParentProperty.name === 'fontSize') { updateFontSize(nodePath.parent, 'type', parentIdentifierName, 'legacy', true); } // Handle font-weight transformations if (grandParentProperty && grandParentProperty.name === 'fontWeight') { return updateFontWeight(nodePath.parent, 'type', parentIdentifierName, true); } // Handle variant transformations if (parentProperty && parentProperty.name === 'variant') { const variantName = grandParentProperty.name; return updateVariant(nodePath.parent, 'type', variantName, true); } // Handle type hierarchy transformations if (parentProperty.name in legacyTypeLevelsMap) { updateTypeHierarchy(nodePath.parent, parentIdentifierName, 'legacy'); if (parentIdentifierName === 'h3' || parentIdentifierName === 'h4') { updateHeadingFontWeight(nodePath.parent, 'type', true); } return; } } return nodePath; }); }); } // Only run if there are type imports from preview-react/tokens or labs-react/tokens if (betaTypeImportSpecifiers.paths().length) { // Iterate over all type import specifiers and transform their corresponding member expressions betaTypeImportSpecifiers.forEach(importSpecifier => { // Use either the local or imported name for the import specifier // e.g. `import { type as typeTokens } from '@workday/canvas-kit-react/tokens';` // 'type' is the imported name, and 'typeTokens' is the local name const importSpecifierName = importSpecifier.value.local?.name || importSpecifier.value.imported.name; // Find all member expressions using the specifier name root .find(j.MemberExpression, {object: {type: 'Identifier', name: importSpecifierName}}) .forEach(nodePath => { const parentProperty = nodePath.parent.value.property; const propertyIdentifier = nodePath.value.property as Identifier; const identifierName = propertyIdentifier.name; // Handle font-family transformations if (parentProperty && parentProperty.name === 'fontFamily') { return updateFontFamily(nodePath, importSpecifierName); } // Handle font-size transformations if (parentProperty && parentProperty.name === 'fontSize') { return updateFontSize(nodePath, importSpecifierName, identifierName, 'beta'); } // Handle font-weight transformations if (parentProperty && parentProperty.name === 'fontWeight') { return updateFontWeight(nodePath, importSpecifierName, identifierName); } // Handle variant transformations if (parentProperty && propertyIdentifier.name === 'variant') { const variantName = parentProperty.name; return updateVariant(nodePath, importSpecifierName, variantName); } // Handle type hierarchy transformations if (identifierName in betaTypeLevelsMap) { updateTypeHierarchy(nodePath, identifierName, 'beta'); if (identifierName === 'h4') { updateHeadingFontWeight(nodePath, importSpecifierName); } return; } return nodePath; }); }); } return root.toSource(); }
the_stack
import * as builder from 'botbuilder'; import * as msRest from 'ms-rest'; import RemoteQuery = require('./RemoteQuery/teams'); import RestClient = require('./RemoteQuery/RestClient'); import { ChannelAccount, ChannelInfo, ComposeExtensionQuery, IComposeExtensionResponse, ComposeExtensionParameter, ComposeExtensionResponse, IO365ConnectorCardActionQuery, ISigninStateVerificationQuery, TeamInfo, TeamsChannelAccountsResult, IComposeExtensionActionCommandRequest } from './models'; import { IFileConsentCardResponse } from './models/FileConsentCardResponse'; import * as task from './models/TaskModuleResponse'; var WebResource = msRest.WebResource; export type ComposeExtensionHandlerType = (event: builder.IEvent, query: ComposeExtensionQuery, callback: (err: Error, result: IComposeExtensionResponse, statusCode?: number) => void) => void; export type O365ConnectorCardActionHandlerType = (event: builder.IEvent, query: IO365ConnectorCardActionQuery, callback: (err: Error, result: any, statusCode?: number) => void) => void; export type SigninStateVerificationHandlerType = (event: builder.IEvent, query: ISigninStateVerificationQuery, callback: (err: Error, result: any, statusCode?: number) => void) => void; export type FileConsentCardResponseHandlerType = (event: builder.IEvent, response: IFileConsentCardResponse, callback: (err: Error, result: any, statusCode?: number) => void) => void; export type TaskModuleFetchHandlerType = (event: builder.IEvent, request: task.ITaskModuleInvokeRequest, callback: (err: Error, result: task.ITaskModuleResponseOfFetch, statusCode?: number) => void) => void; export type TaskModuleSubmitHandlerType = (event: builder.IEvent, request: task.ITaskModuleInvokeRequest, callback: (err: Error, result: task.ITaskModuleResponseOfSubmit, statusCode?: number) => void) => void; export type ComposeExtensionFetchTaskHandlerType = (event: builder.IEvent, request: IComposeExtensionActionCommandRequest, callback: (err: Error, result: task.ITaskModuleResponseOfFetch | IComposeExtensionResponse, statusCode?: number) => void) => void; export type ComposeExtensionSubmitActionHandlerType = (event: builder.IEvent, request: IComposeExtensionActionCommandRequest, callback: (err: Error, result: task.ITaskModuleResponseOfSubmit | IComposeExtensionResponse, statusCode?: number) => void) => void; export type AppBasedLinkHandlerType = (event: builder.IEvent, query: ComposeExtensionQuery, callback: (err: Error, result: IComposeExtensionResponse, statusCode?: number) => void) => void; export interface IInvokeEvent extends builder.IEvent { name: string; value: any; } export interface ReplyResult { id: string, activityId: string } export class TeamsChatConnector extends builder.ChatConnector { private static o365CardActionInvokeName = 'actionableMessage/executeAction'; private static signinStateVerificationInvokeName = 'signin/verifyState'; private static queryInvokeName = 'composeExtension/query'; private static querySettingUrlInvokeName = 'composeExtension/querySettingUrl'; private static selectItemInvokeName = 'composeExtension/selectItem'; private static settingInvokeName = 'composeExtension/setting'; private static fileConsentInvokeName = 'fileConsent/invoke'; private static taskModuleInvokeNameOfFetch = task.taskModuleInvokeNameOfFetch; private static taskModuleInvokeNameOfSubmit = task.taskModuleInvokeNameOfSubmit; private static composeExtensionInvokeNameofFetchTask = 'composeExtension/fetchTask'; private static composeExtensionInvokeNameofSubmitAction = 'composeExtension/submitAction'; private static appBasedLinkInvokeName = 'composeExtension/queryLink'; private allowedTenants: string[]; private o365CardActionHandler: O365ConnectorCardActionHandlerType; private signinStateVerificationHandler: SigninStateVerificationHandlerType; private queryHandlers: { [id: string]: ComposeExtensionHandlerType } = null; private querySettingsUrlHandler: ComposeExtensionHandlerType; private settingsUpdateHandler: ComposeExtensionHandlerType; private selectItemInvokeHandler: ComposeExtensionHandlerType; private fileConsentCardResponseHandler: FileConsentCardResponseHandlerType; private taskModuleFetchHandler: TaskModuleFetchHandlerType; private taskModuleSubmitHandler: TaskModuleSubmitHandlerType; private composeExtensionFetchTaskHandler: ComposeExtensionFetchTaskHandlerType; private composeExtensionSubmitActionHandler: ComposeExtensionSubmitActionHandlerType; private appBasedLinkHandler: AppBasedLinkHandlerType; constructor(settings: builder.IChatConnectorSettings = {}) { super(settings) this.allowedTenants = null; } /** * Return a list of conversations in a team * @param {string} serverUrl - Server url is composed of baseUrl and cloud name, remember to find your correct cloud name in session or the function will not find the team. * @param {string} teamId - The team id, you can look it up in session object. * @param {function} callback - This callback returns err or result. */ public fetchChannelList(serverUrl: string, teamId: string, callback: (err: Error, result: ChannelInfo[]) => void) : void { var options = {customHeaders: {}, jar: false}; var restClient = new RestClient(serverUrl, null); var remoteQuery = new RemoteQuery(restClient); this.getAccessToken((err, token) => { if (!err && token) { options.customHeaders = { 'Authorization': 'Bearer ' + token }; remoteQuery.fetchChannelList(teamId, options, callback); } else { return callback(new Error('Failed to authorize request'), null); } }); } /** * Return info of a team given team id * @param {string} serverUrl - Server url is composed of baseUrl and cloud name, remember to find your correct cloud name in session or the function will not find the team. * @param {string} teamId - The team id, you can look it up in session object. * @param {function} callback - This callback returns err or result. */ public fetchTeamInfo(serverUrl: string, teamId: string, callback: (err: Error, result: TeamInfo) => void) : void { var options = {customHeaders: {}, jar: false}; var restClient = new RestClient(serverUrl, null); var remoteQuery = new RemoteQuery(restClient); this.getAccessToken((err, token) => { if (!err && token) { options.customHeaders = { 'Authorization': 'Bearer ' + token }; remoteQuery.fetchTeamInfo(teamId, options, callback); } else { return callback(new Error('Failed to authorize request'), null); } }); } /** * Return a list of members in a team or channel * @param {string} serverUrl - Server url is composed of baseUrl and cloud name, remember to find your correct cloud name in session or the function will not find the team. * @param {string} conversationId - The conversation id or channel id, you can look it up in session object. * @param {function} callback - This callback returns err or result. */ public fetchMembers(serverUrl: string, conversationId: string, callback: (err: Error, result: ChannelAccount[]) => void) : void { var options = {customHeaders: {}, jar: false}; var restClient = new RestClient(serverUrl, null); var remoteQuery = new RemoteQuery(restClient); this.getAccessToken((err, token) => { if (!err && token) { options.customHeaders = { 'Authorization': 'Bearer ' + token }; remoteQuery.fetchMemberList(conversationId, options, callback); } else { return callback(new Error('Failed to authorize request'), null); } }); } /** * Return a specific member from a team or a chat. * @param {string} serviceUrl - The service url for the team or chat, which should be taken from a previous message received from that team or chat. If the wrong service url is used, the method wil fail. * @param {string} conversationId - The team id or chat conversation id. * @param {string} memberId - Member Id * @param {function} callback - This callback returns err or result. */ public fetchMember(serverUrl: string, conversationId: string, memberId: string, callback: (err: Error, result: ChannelAccount) => void) : void { var options = {customHeaders: {}, jar: false}; var restClient = new RestClient(serverUrl, null); var remoteQuery = new RemoteQuery(restClient); this.getAccessToken((err, token) => { if (!err && token) { options.customHeaders = { 'Authorization': 'Bearer ' + token }; remoteQuery.fetchMember(conversationId, memberId, options, callback); } else { return callback(new Error('Failed to authorize request'), null); } }); } /** * Return members in a team or channel with pagination * @param {string} serverUrl - Server url is composed of baseUrl and cloud name, remember to find your correct cloud name in session or the function will not find the team. * @param {string} conversationId - The conversation id or channel id, you can look it up in session object. * @param {number} pageSize - optional. If exists, it specifies how many members to fetch per page, if it's not passed, default is 200 * @param {string} continuationToken - optional. If exists, callers can make a subsequent call to fetch more members * @param {function} callback - This callback returns err or result. */ public fetchMembersWithPaging( serverUrl: string, conversationId: string, ...args: any[]): void { let pageSize: number = undefined; let continuationToken: string = undefined; let callback: (err: Error, result: TeamsChannelAccountsResult) => void; let throwInvalidParameter = () => { throw new Error('Invalid parameters: ' + JSON.stringify(args)); }; if (!args) { throwInvalidParameter(); } switch (args.length) { case 1: callback = args[0]; break; case 2: if (typeof args[0] === 'string') { continuationToken = args[0]; } else if (typeof args[0] === 'number') { pageSize = args[0]; } else { throwInvalidParameter(); } callback = args[1]; break; case 3: pageSize = args[0]; continuationToken = args[1]; callback = args[2]; break; default: throwInvalidParameter(); } let options = { pageSize: pageSize, continuationToken: continuationToken, customHeaders: {}, jar: false }; var restClient = new RestClient(serverUrl, null); var remoteQuery = new RemoteQuery(restClient); this.getAccessToken((err, token) => { if (!err && token) { options.customHeaders = { "Authorization": "Bearer " + token }; remoteQuery.fetchMemberListWithPaging(conversationId, options, callback); } else { return callback(new Error("Failed to authorize request"), null); } }); } /** * Return a newly started reply chain address in channel * @param {string} serverUrl - Server url is composed of baseUrl and cloud name, remember to find your correct cloud name in session or the function will not find the team. * @param {string} channelId - The channel id, will post in the channel. * @param {builder.IMessage|builder.IIsMessage} message - The message to post in the channel. * @param {function} callback - This callback returns err or result. */ public startReplyChain(serverUrl: string, channelId: string, message: builder.IMessage|builder.IIsMessage, callback?: (err: Error, address: builder.IChatConnectorAddress) => void) : void { var options = {customHeaders: {}, jar: false}; var restClient = new RestClient(serverUrl, null); var remoteQuery = new RemoteQuery(restClient); this.getAccessToken((err, token) => { if (!err && token) { options.customHeaders = { 'Authorization': 'Bearer ' + token }; var iMessage: builder.IMessage = null; if ((<builder.IIsMessage>message).toMessage) { iMessage = (<builder.IIsMessage>message).toMessage(); } else if ((<builder.IMessage>message).address) { iMessage = <builder.IMessage>message; } else { throw new Error("Message type is wrong. Need either IMessage or IIsMessage"); } var innerCallback = function (err: Error, result: ReplyResult) { if (!callback) { return; } if (result && result.hasOwnProperty("id") && result.hasOwnProperty("activityId")) { var messageAddress = <builder.IChatConnectorAddress>iMessage.address; var address: builder.IChatConnectorAddress = <builder.IChatConnectorAddress>{ ... messageAddress, channelId : 'msteams', conversation: { id: result.id }, id : result.activityId }; if (address.user) { delete address.user; } return callback(null, address); } else { let error = new Error("Failed to start reply chain: no conversation ID and activity ID returned."); return callback(error, null); } } remoteQuery.beginReplyChainInChannel(channelId, iMessage, options, innerCallback); } else { if (callback) { return callback(new Error('Failed to authorize request'), null); } } }); } /** * @override * * Change default implementation to ignore endOfCoversation message types * */ public send(messages: builder.IMessage[], done: (err: Error, addresses?: builder.IAddress[]) => void): void { return super.send(messages.filter((m) => m.type !== "endOfConversation"), done) } /** * Set the list of allowed tenants. Messages from tenants not on the list will be dropped silently. * @param {array} tenants - Ids of allowed tenants. */ public setAllowedTenants(tenants: string[]) : void { if (tenants != null) { this.allowedTenants = tenants; } } /** * Reset allowed tenants, ask connector to receive every message sent from any source. */ public resetAllowedTenants() : void { this.allowedTenants = null; } public onO365ConnectorCardAction(handler: O365ConnectorCardActionHandlerType): void { this.o365CardActionHandler = handler; } public onSigninStateVerification(handler: SigninStateVerificationHandlerType): void { this.signinStateVerificationHandler = handler; } public onQuery(commandId: string, handler: ComposeExtensionHandlerType): void { if (!this.queryHandlers) { this.queryHandlers = {}; } this.queryHandlers[commandId] = handler; } public onQuerySettingsUrl(handler: ComposeExtensionHandlerType) { this.querySettingsUrlHandler = handler; } public onSettingsUpdate(handler: ComposeExtensionHandlerType) { this.settingsUpdateHandler = handler; } public onSelectItem(handler: ComposeExtensionHandlerType) { this.selectItemInvokeHandler = handler; } public onFileConsentCardResponse(handler: FileConsentCardResponseHandlerType) { this.fileConsentCardResponseHandler = handler; } public onTaskModuleFetch(handler: TaskModuleFetchHandlerType): void { this.taskModuleFetchHandler = handler; } public onTaskModuleSubmit(handler: TaskModuleSubmitHandlerType): void { this.taskModuleSubmitHandler = handler; } public onComposeExtensionFetchTask(handler:ComposeExtensionFetchTaskHandlerType): void { this.composeExtensionFetchTaskHandler = handler; } public onComposeExtensionSubmitAction(handler: ComposeExtensionSubmitActionHandlerType): void { this.composeExtensionSubmitActionHandler = handler; } public onAppBasedLinkQuery(handler: AppBasedLinkHandlerType): void { this.appBasedLinkHandler = handler; } protected onDispatchEvents(events: builder.IEvent[], callback: (err: Error, body: any, status?: number) => void): void { if (this.allowedTenants) { var filteredEvents: builder.IEvent[] = []; for (var event of events) { if (event.sourceEvent.tenant && this.allowedTenants.indexOf(event.sourceEvent.tenant.id) > -1) { filteredEvents.push(event); } } this.dispatchEventOrQuery(filteredEvents, callback); } else { this.dispatchEventOrQuery(events, callback); } } private dispatchEventOrQuery(events: builder.IEvent[], callback: (err: Error, body: any, status?: number) => void): void { var realEvents: builder.IEvent[] = []; // Events to be dispatched by ChatConnector for (var event of events) { if (event.type === 'invoke') { let invoke = <IInvokeEvent>event; let invokeHandler: (event: builder.IEvent, value: any, callback: (err: Error, body: any, status?: number) => void) => void; switch (invoke.name) { case TeamsChatConnector.queryInvokeName: if (this.queryHandlers) { invokeHandler = this.dispatchQuery.bind(this); } break; case TeamsChatConnector.querySettingUrlInvokeName: if (this.querySettingsUrlHandler) { invokeHandler = this.querySettingsUrlHandler.bind(this); } break; case TeamsChatConnector.settingInvokeName: if (this.settingsUpdateHandler) { invokeHandler = this.settingsUpdateHandler.bind(this); } break; case TeamsChatConnector.selectItemInvokeName: if (this.selectItemInvokeHandler) { invokeHandler = this.selectItemInvokeHandler.bind(this); } break; case TeamsChatConnector.o365CardActionInvokeName: if (this.o365CardActionHandler) { invokeHandler = this.o365CardActionHandler.bind(this); } break; case TeamsChatConnector.signinStateVerificationInvokeName: if (this.signinStateVerificationHandler) { invokeHandler = this.signinStateVerificationHandler.bind(this); } break; case TeamsChatConnector.fileConsentInvokeName: if (this.fileConsentCardResponseHandler) { invokeHandler = this.fileConsentCardResponseHandler.bind(this); } break; case TeamsChatConnector.taskModuleInvokeNameOfFetch: if (this.taskModuleFetchHandler) { invokeHandler = this.taskModuleFetchHandler.bind(this); } break; case TeamsChatConnector.taskModuleInvokeNameOfSubmit: if (this.taskModuleSubmitHandler) { invokeHandler = this.taskModuleSubmitHandler.bind(this); } break; case TeamsChatConnector.composeExtensionInvokeNameofFetchTask: if (this.composeExtensionFetchTaskHandler) { invokeHandler = this.composeExtensionFetchTaskHandler.bind(this); } break; case TeamsChatConnector.composeExtensionInvokeNameofSubmitAction: if (this.composeExtensionSubmitActionHandler) { invokeHandler = this.composeExtensionSubmitActionHandler.bind(this); } break; case TeamsChatConnector.appBasedLinkInvokeName: if (this.appBasedLinkHandler) { invokeHandler = this.appBasedLinkHandler.bind(this); } break; default: // Generic invoke activity, defer to default handling of invoke activities realEvents.push(event); break; } if (invokeHandler) { try { invokeHandler(invoke, invoke.value, callback); } catch (e) { return callback(e, null, 500); } } else { // No handler registered, defer to default handling of invoke activities realEvents.push(event); } } else { // Use default handling for all other activities realEvents.push(event); } } if (realEvents.length > 0) { super.onDispatchEvents(realEvents, callback); } } private dispatchQuery(event: builder.IEvent, query: ComposeExtensionQuery, callback: (err: Error, body: IComposeExtensionResponse, status?: number) => void): void { let handler = this.queryHandlers[query.commandId]; if (handler) { handler(event, query, callback); } else { return callback(new Error("Query handler [" + query.commandId + "] not found."), null, 500); } } }
the_stack
import * as util from './util' import { Angle } from './angle' import { Geometry } from './geometry' import { Rectangle } from './rectangle' export class Point extends Geometry implements Point.PointLike { public x: number public y: number protected get [Symbol.toStringTag]() { return Point.toStringTag } constructor(x?: number, y?: number) { super() this.x = x == null ? 0 : x this.y = y == null ? 0 : y } /** * Rounds the point to the given precision. */ round(precision = 0) { this.x = util.round(this.x, precision) this.y = util.round(this.y, precision) return this } add(x: number, y: number): this add(p: Point.PointLike | Point.PointData): this add(x: number | Point.PointLike | Point.PointData, y?: number): this { const p = Point.create(x, y) this.x += p.x this.y += p.y return this } /** * Update the point's `x` and `y` coordinates with new values and return the * point itself. Useful for chaining. */ update(x: number, y: number): this update(p: Point.PointLike | Point.PointData): this update(x: number | Point.PointLike | Point.PointData, y?: number): this { const p = Point.create(x, y) this.x = p.x this.y = p.y return this } translate(dx: number, dy: number): this translate(p: Point.PointLike | Point.PointData): this translate(dx: number | Point.PointLike | Point.PointData, dy?: number): this { const t = Point.create(dx, dy) this.x += t.x this.y += t.y return this } /** * Rotate the point by `degree` around `center`. */ rotate(degree: number, center?: Point.PointLike | Point.PointData): this { const p = Point.rotate(this, degree, center) this.x = p.x this.y = p.y return this } /** * Scale point by `sx` and `sy` around the given `origin`. If origin is not * specified, the point is scaled around `0,0`. */ scale( sx: number, sy: number, origin: Point.PointLike | Point.PointData = new Point(), ) { const ref = Point.create(origin) this.x = ref.x + sx * (this.x - ref.x) this.y = ref.y + sy * (this.y - ref.y) return this } /** * Chooses the point closest to this point from among `points`. If `points` * is an empty array, `null` is returned. */ closest(points: (Point.PointLike | Point.PointData)[]) { if (points.length === 1) { return Point.create(points[0]) } let ret: Point.PointLike | Point.PointData | null = null let min = Infinity points.forEach((p) => { const dist = this.squaredDistance(p) if (dist < min) { ret = p min = dist } }) return ret ? Point.create(ret) : null } /** * Returns the distance between the point and another point `p`. */ distance(p: Point.PointLike | Point.PointData) { return Math.sqrt(this.squaredDistance(p)) } /** * Returns the squared distance between the point and another point `p`. * * Useful for distance comparisons in which real distance is not necessary * (saves one `Math.sqrt()` operation). */ squaredDistance(p: Point.PointLike | Point.PointData) { const ref = Point.create(p) const dx = this.x - ref.x const dy = this.y - ref.y return dx * dx + dy * dy } manhattanDistance(p: Point.PointLike | Point.PointData) { const ref = Point.create(p) return Math.abs(ref.x - this.x) + Math.abs(ref.y - this.y) } /** * Returns the magnitude of the point vector. * * @see http://en.wikipedia.org/wiki/Magnitude_(mathematics) */ magnitude() { return Math.sqrt(this.x * this.x + this.y * this.y) || 0.01 } /** * Returns the angle(in degrees) between vector from this point to `p` and * the x-axis. */ theta(p: Point.PointLike | Point.PointData = new Point()): number { const ref = Point.create(p) const y = -(ref.y - this.y) // invert the y-axis. const x = ref.x - this.x let rad = Math.atan2(y, x) // Correction for III. and IV. quadrant. if (rad < 0) { rad = 2 * Math.PI + rad } return (180 * rad) / Math.PI } /** * Returns the angle(in degrees) between vector from this point to `p1` and * the vector from this point to `p2`. * * The ordering of points `p1` and `p2` is important. * * The function returns a value between `0` and `180` when the angle (in the * direction from `p1` to `p2`) is clockwise, and a value between `180` and * `360` when the angle is counterclockwise. * * Returns `NaN` if either of the points `p1` and `p2` is equal with this point. */ angleBetween( p1: Point.PointLike | Point.PointData, p2: Point.PointLike | Point.PointData, ) { if (this.equals(p1) || this.equals(p2)) { return NaN } let angle = this.theta(p2) - this.theta(p1) if (angle < 0) { angle += 360 } return angle } /** * Returns the angle(in degrees) between the line from `(0,0)` and this point * and the line from `(0,0)` to `p`. * * The function returns a value between `0` and `180` when the angle (in the * direction from this point to `p`) is clockwise, and a value between `180` * and `360` when the angle is counterclockwise. Returns `NaN` if called from * point `(0,0)` or if `p` is `(0,0)`. */ vectorAngle(p: Point.PointLike | Point.PointData) { const zero = new Point(0, 0) return zero.angleBetween(this, p) } /** * Converts rectangular to polar coordinates. */ toPolar(origin?: Point.PointLike | Point.PointData) { this.update(Point.toPolar(this, origin)) return this } /** * Returns the change in angle(in degrees) that is the result of moving the * point from its previous position to its current position. * * More specifically, this function computes the angle between the line from * the ref point to the previous position of this point(i.e. current position * `-dx`, `-dy`) and the line from the `ref` point to the current position of * this point. * * The function returns a positive value between `0` and `180` when the angle * (in the direction from previous position of this point to its current * position) is clockwise, and a negative value between `0` and `-180` when * the angle is counterclockwise. * * The function returns `0` if the previous and current positions of this * point are the same (i.e. both `dx` and `dy` are `0`). */ changeInAngle( dx: number, dy: number, ref: Point.PointLike | Point.PointData = new Point(), ) { // Revert the translation and measure the change in angle around x-axis. return this.clone().translate(-dx, -dy).theta(ref) - this.theta(ref) } /** * If the point lies outside the rectangle `rect`, adjust the point so that * it becomes the nearest point on the boundary of `rect`. */ adhereToRect(rect: Rectangle.RectangleLike) { if (!util.containsPoint(rect, this)) { this.x = Math.min(Math.max(this.x, rect.x), rect.x + rect.width) this.y = Math.min(Math.max(this.y, rect.y), rect.y + rect.height) } return this } /** * Returns the bearing(cardinal direction) between me and the given point. * * @see https://en.wikipedia.org/wiki/Cardinal_direction */ bearing(p: Point.PointLike | Point.PointData) { const ref = Point.create(p) const lat1 = Angle.toRad(this.y) const lat2 = Angle.toRad(ref.y) const lon1 = this.x const lon2 = ref.x const dLon = Angle.toRad(lon2 - lon1) const y = Math.sin(dLon) * Math.cos(lat2) const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon) const brng = Angle.toDeg(Math.atan2(y, x)) const bearings = ['NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N'] let index = brng - 22.5 if (index < 0) { index += 360 } index = parseInt((index / 45) as any, 10) return bearings[index] as Point.Bearing } /** * Returns the cross product of the vector from me to `p1` and the vector * from me to `p2`. * * The left-hand rule is used because the coordinate system is left-handed. */ cross( p1: Point.PointLike | Point.PointData, p2: Point.PointLike | Point.PointData, ) { if (p1 != null && p2 != null) { const a = Point.create(p1) const b = Point.create(p2) return (b.x - this.x) * (a.y - this.y) - (b.y - this.y) * (a.x - this.x) } return NaN } /** * Returns the dot product of this point with given other point. */ dot(p: Point.PointLike | Point.PointData) { const ref = Point.create(p) return this.x * ref.x + this.y * ref.y } /** * Returns a point that has coordinates computed as a difference between the * point and another point with coordinates `dx` and `dy`. * * If only `dx` is specified and is a number, `dy` is considered to be zero. * If only `dx` is specified and is an object, it is considered to be another * point or an object in the form `{ x: [number], y: [number] }` */ diff(dx: number, dy: number): Point diff(p: Point.PointLike | Point.PointData): Point diff(dx: number | Point.PointLike | Point.PointData, dy?: number): Point { if (typeof dx === 'number') { return new Point(this.x - dx, this.y - dy!) } const p = Point.create(dx) return new Point(this.x - p.x, this.y - p.y) } /** * Returns an interpolation between me and point `p` for a parametert in * the closed interval `[0, 1]`. */ lerp(p: Point.PointLike | Point.PointData, t: number) { const ref = Point.create(p) return new Point((1 - t) * this.x + t * ref.x, (1 - t) * this.y + t * ref.y) } /** * Normalize the point vector, scale the line segment between `(0, 0)` * and the point in order for it to have the given length. If length is * not specified, it is considered to be `1`; in that case, a unit vector * is computed. */ normalize(length = 1) { const scale = length / this.magnitude() return this.scale(scale, scale) } /** * Moves this point along the line starting from `ref` to this point by a * certain `distance`. */ move(ref: Point.PointLike | Point.PointData, distance: number) { const p = Point.create(ref) const rad = Angle.toRad(p.theta(this)) return this.translate(Math.cos(rad) * distance, -Math.sin(rad) * distance) } /** * Returns a point that is the reflection of me with the center of inversion * in `ref` point. */ reflection(ref: Point.PointLike | Point.PointData) { return Point.create(ref).move(this, this.distance(ref)) } /** * Snaps the point(change its x and y coordinates) to a grid of size `gridSize` * (or `gridSize` x `gridSizeY` for non-uniform grid). */ snapToGrid(gridSize: number): this snapToGrid(gx: number, gy: number): this snapToGrid(gx: number, gy?: number): this snapToGrid(gx: number, gy?: number): this { this.x = util.snapToGrid(this.x, gx) this.y = util.snapToGrid(this.y, gy == null ? gx : gy) return this } equals(p: Point.PointLike | Point.PointData) { const ref = Point.create(p) return ref != null && ref.x === this.x && ref.y === this.y } clone() { return Point.clone(this) } /** * Returns the point as a simple JSON object. For example: `{ x: 0, y: 0 }`. */ toJSON() { return Point.toJSON(this) } serialize() { return `${this.x} ${this.y}` } } export namespace Point { export const toStringTag = `X6.Geometry.${Point.name}` export function isPoint(instance: any): instance is Point { if (instance == null) { return false } if (instance instanceof Point) { return true } const tag = instance[Symbol.toStringTag] const point = instance as Point if ( (tag == null || tag === toStringTag) && typeof point.x === 'number' && typeof point.y === 'number' && typeof point.toPolar === 'function' ) { return true } return false } } export namespace Point { export interface PointLike { x: number y: number } export type PointData = [number, number] export type Bearing = 'NE' | 'E' | 'SE' | 'S' | 'SW' | 'W' | 'NW' | 'N' export function isPointLike(p: any): p is PointLike { return ( p != null && typeof p === 'object' && typeof p.x === 'number' && typeof p.y === 'number' ) } export function isPointData(p: any): p is PointData { return ( p != null && Array.isArray(p) && p.length === 2 && typeof p[0] === 'number' && typeof p[1] === 'number' ) } } export namespace Point { export function create( x?: number | Point | PointLike | PointData, y?: number, ): Point { if (x == null || typeof x === 'number') { return new Point(x, y) } return clone(x) } export function clone(p: Point | PointLike | PointData) { if (Point.isPoint(p)) { return new Point(p.x, p.y) } if (Array.isArray(p)) { return new Point(p[0], p[1]) } return new Point(p.x, p.y) } export function toJSON(p: Point | PointLike | PointData) { if (Point.isPoint(p)) { return { x: p.x, y: p.y } } if (Array.isArray(p)) { return { x: p[0], y: p[1] } } return { x: p.x, y: p.y } } /** * Returns a new Point object from the given polar coordinates. * @see http://en.wikipedia.org/wiki/Polar_coordinate_system */ export function fromPolar( r: number, rad: number, origin: Point | PointLike | PointData = new Point(), ) { let x = Math.abs(r * Math.cos(rad)) let y = Math.abs(r * Math.sin(rad)) const org = clone(origin) const deg = Angle.normalize(Angle.toDeg(rad)) if (deg < 90) { y = -y } else if (deg < 180) { x = -x y = -y } else if (deg < 270) { x = -x } return new Point(org.x + x, org.y + y) } /** * Converts rectangular to polar coordinates. */ export function toPolar( point: Point | PointLike | PointData, origin: Point | PointLike | PointData = new Point(), ) { const p = clone(point) const o = clone(origin) const dx = p.x - o.x const dy = p.y - o.y return new Point( Math.sqrt(dx * dx + dy * dy), // r Angle.toRad(o.theta(p)), ) } export function equals(p1?: Point.PointLike, p2?: Point.PointLike) { if (p1 === p2) { return true } if (p1 != null && p2 != null) { return p1.x === p2.x && p1.y === p2.y } return false } export function equalPoints(p1: Point.PointLike[], p2: Point.PointLike[]) { if ( (p1 == null && p2 != null) || (p1 != null && p2 == null) || (p1 != null && p2 != null && p1.length !== p2.length) ) { return false } if (p1 != null && p2 != null) { for (let i = 0, ii = p1.length; i < ii; i += 1) { if (!equals(p1[i], p2[i])) { return false } } } return true } /** * Returns a point with random coordinates that fall within the range * `[x1, x2]` and `[y1, y2]`. */ export function random(x1: number, x2: number, y1: number, y2: number) { return new Point(util.random(x1, x2), util.random(y1, y2)) } export function rotate( point: Point | PointLike | PointData, angle: number, center?: Point | PointLike | PointData, ) { const rad = Angle.toRad(Angle.normalize(-angle)) const sin = Math.sin(rad) const cos = Math.cos(rad) return rotateEx(point, cos, sin, center) } export function rotateEx( point: Point | PointLike | PointData, cos: number, sin: number, center: Point | PointLike | PointData = new Point(), ) { const source = clone(point) const origin = clone(center) const dx = source.x - origin.x const dy = source.y - origin.y const x1 = dx * cos - dy * sin const y1 = dy * cos + dx * sin return new Point(x1 + origin.x, y1 + origin.y) } }
the_stack
import { defHttp } from '/@/utils/http/axios'; enum Api { cpuCount = '/actuator/metrics/system.cpu.count', cpuUsage = '/actuator/metrics/system.cpu.usage', processStartTime = '/actuator/metrics/process.start.time', processUptime = '/actuator/metrics/process.uptime', processCpuUsage = '/actuator/metrics/process.cpu.usage', jvmMemoryMax = '/actuator/metrics/jvm.memory.max', jvmMemoryCommitted = '/actuator/metrics/jvm.memory.committed', jvmMemoryUsed = '/actuator/metrics/jvm.memory.used', jvmBufferMemoryUsed = '/actuator/metrics/jvm.buffer.memory.used', jvmBufferCount = '/actuator/metrics/jvm.buffer.count', jvmThreadsDaemon = '/actuator/metrics/jvm.threads.daemon', jvmThreadsLive = '/actuator/metrics/jvm.threads.live', jvmThreadsPeak = '/actuator/metrics/jvm.threads.peak', jvmClassesLoaded = '/actuator/metrics/jvm.classes.loaded', jvmClassesUnloaded = '/actuator/metrics/jvm.classes.unloaded', jvmGcMemoryAllocated = '/actuator/metrics/jvm.gc.memory.allocated', jvmGcMemoryPromoted = '/actuator/metrics/jvm.gc.memory.promoted', jvmGcMaxDataSize = '/actuator/metrics/jvm.gc.max.data.size', jvmGcLiveDataSize = '/actuator/metrics/jvm.gc.live.data.size', jvmGcPause = '/actuator/metrics/jvm.gc.pause', tomcatSessionsCreated = '/actuator/metrics/tomcat.sessions.created', tomcatSessionsExpired = '/actuator/metrics/tomcat.sessions.expired', tomcatSessionsActiveCurrent = '/actuator/metrics/tomcat.sessions.active.current', tomcatSessionsActiveMax = '/actuator/metrics/tomcat.sessions.active.max', tomcatSessionsRejected = '/actuator/metrics/tomcat.sessions.rejected' } /** * 查询cpu数量 */ export const getCpuCount = () => { return defHttp.get({ url: Api.cpuCount }, { isTransformResponse: false }); }; /** * 查询系统 CPU 使用率 */ export const getCpuUsage = () => { return defHttp.get({ url: Api.cpuUsage }, { isTransformResponse: false }); }; /** * 查询应用启动时间点 */ export const getProcessStartTime = () => { return defHttp.get({ url: Api.processStartTime }, { isTransformResponse: false }); }; /** * 查询应用已运行时间 */ export const getProcessUptime = () => { return defHttp.get({ url: Api.processUptime }, { isTransformResponse: false }); }; /** * 查询当前应用 CPU 使用率 */ export const getProcessCpuUsage = () => { return defHttp.get({ url: Api.processCpuUsage }, { isTransformResponse: false }); }; /** * 查询JVM 最大内存 */ export const getJvmMemoryMax = () => { return defHttp.get({ url: Api.jvmMemoryMax }, { isTransformResponse: false }); }; /** * JVM 可用内存 */ export const getJvmMemoryCommitted = () => { return defHttp.get({ url: Api.jvmMemoryCommitted }, { isTransformResponse: false }); }; /** * JVM 已用内存 */ export const getJvmMemoryUsed = () => { return defHttp.get({ url: Api.jvmMemoryUsed }, { isTransformResponse: false }); }; /** * JVM 缓冲区已用内存 */ export const getJvmBufferMemoryUsed = () => { return defHttp.get({ url: Api.jvmBufferMemoryUsed }, { isTransformResponse: false }); }; /** *JVM 当前缓冲区数量 */ export const getJvmBufferCount = () => { return defHttp.get({ url: Api.jvmBufferCount }, { isTransformResponse: false }); }; /** **JVM 守护线程数量 */ export const getJvmThreadsDaemon = () => { return defHttp.get({ url: Api.jvmThreadsDaemon }, { isTransformResponse: false }); }; /** *JVM 当前活跃线程数量 */ export const getJvmThreadsLive = () => { return defHttp.get({ url: Api.jvmThreadsLive }, { isTransformResponse: false }); }; /** *JVM 峰值线程数量 */ export const getJvmThreadsPeak = () => { return defHttp.get({ url: Api.jvmThreadsPeak }, { isTransformResponse: false }); }; /** *JVM 已加载 Class 数量 */ export const getJvmClassesLoaded = () => { return defHttp.get({ url: Api.jvmClassesLoaded }, { isTransformResponse: false }); }; /** *JVM 未加载 Class 数量 */ export const getJvmClassesUnloaded = () => { return defHttp.get({ url: Api.jvmClassesUnloaded }, { isTransformResponse: false }); }; /** **GC 时, 年轻代分配的内存空间 */ export const getJvmGcMemoryAllocated = () => { return defHttp.get({ url: Api.jvmGcMemoryAllocated }, { isTransformResponse: false }); }; /** *GC 时, 老年代分配的内存空间 */ export const getJvmGcMemoryPromoted = () => { return defHttp.get({ url: Api.jvmGcMemoryPromoted }, { isTransformResponse: false }); }; /** *GC 时, 老年代的最大内存空间 */ export const getJvmGcMaxDataSize = () => { return defHttp.get({ url: Api.jvmGcMaxDataSize }, { isTransformResponse: false }); }; /** *FullGC 时, 老年代的内存空间 */ export const getJvmGcLiveDataSize = () => { return defHttp.get({ url: Api.jvmGcLiveDataSize }, { isTransformResponse: false }); }; /** *系统启动以来GC 次数 */ export const getJvmGcPause = () => { return defHttp.get({ url: Api.jvmGcPause }, { isTransformResponse: false }); }; /** *tomcat 已创建 session 数 */ export const getTomcatSessionsCreated = () => { return defHttp.get({ url: Api.tomcatSessionsCreated }, { isTransformResponse: false }); }; /** *tomcat 已过期 session 数 */ export const getTomcatSessionsExpired = () => { return defHttp.get({ url: Api.tomcatSessionsExpired }, { isTransformResponse: false }); }; /** *tomcat 当前活跃 session 数 */ export const getTomcatSessionsActiveCurrent = () => { return defHttp.get({ url: Api.tomcatSessionsActiveCurrent }, { isTransformResponse: false }); }; /** *tomcat 活跃 session 数峰值 */ export const getTomcatSessionsActiveMax = () => { return defHttp.get({ url: Api.tomcatSessionsActiveMax }, { isTransformResponse: false }); }; /** *超过session 最大配置后,拒绝的 session 个数 */ export const getTomcatSessionsRejected = () => { return defHttp.get({ url: Api.tomcatSessionsRejected }, { isTransformResponse: false }); }; export const getMoreInfo = (infoType) => { if (infoType == '1') { return {}; } if (infoType == '2') { return { 'jvm.gc.pause': ['.count', '.totalTime'] }; } if (infoType == '3') { return { 'tomcat.global.request': ['.count', '.totalTime'], 'tomcat.servlet.request': ['.count', '.totalTime'], }; } }; export const getTextInfo = (infoType) => { if (infoType == '1') { return { 'system.cpu.count': { color: 'green', text: 'CPU 数量', unit: '核' }, 'system.cpu.usage': { color: 'green', text: '系统 CPU 使用率', unit: '%', valueType: 'Number' }, 'process.start.time': { color: 'purple', text: '应用启动时间点', unit: '', valueType: 'Date' }, 'process.uptime': { color: 'purple', text: '应用已运行时间', unit: '秒' }, 'process.cpu.usage': { color: 'purple', text: '当前应用 CPU 使用率', unit: '%', valueType: 'Number' }, }; } if (infoType == '2') { return { 'jvm.memory.max': { color: 'purple', text: 'JVM 最大内存', unit: 'MB', valueType: 'RAM' }, 'jvm.memory.committed': { color: 'purple', text: 'JVM 可用内存', unit: 'MB', valueType: 'RAM' }, 'jvm.memory.used': { color: 'purple', text: 'JVM 已用内存', unit: 'MB', valueType: 'RAM' }, 'jvm.buffer.memory.used': { color: 'cyan', text: 'JVM 缓冲区已用内存', unit: 'MB', valueType: 'RAM' }, 'jvm.buffer.count': { color: 'cyan', text: '当前缓冲区数量', unit: '个' }, 'jvm.threads.daemon': { color: 'green', text: 'JVM 守护线程数量', unit: '个' }, 'jvm.threads.live': { color: 'green', text: 'JVM 当前活跃线程数量', unit: '个' }, 'jvm.threads.peak': { color: 'green', text: 'JVM 峰值线程数量', unit: '个' }, 'jvm.classes.loaded': { color: 'orange', text: 'JVM 已加载 Class 数量', unit: '个' }, 'jvm.classes.unloaded': { color: 'orange', text: 'JVM 未加载 Class 数量', unit: '个' }, 'jvm.gc.memory.allocated': { color: 'pink', text: 'GC 时, 年轻代分配的内存空间', unit: 'MB', valueType: 'RAM' }, 'jvm.gc.memory.promoted': { color: 'pink', text: 'GC 时, 老年代分配的内存空间', unit: 'MB', valueType: 'RAM' }, 'jvm.gc.max.data.size': { color: 'pink', text: 'GC 时, 老年代的最大内存空间', unit: 'MB', valueType: 'RAM' }, 'jvm.gc.live.data.size': { color: 'pink', text: 'FullGC 时, 老年代的内存空间', unit: 'MB', valueType: 'RAM' }, 'jvm.gc.pause.count': { color: 'blue', text: '系统启动以来GC 次数', unit: '次' }, 'jvm.gc.pause.totalTime': { color: 'blue', text: '系统启动以来GC 总耗时', unit: '秒' }, }; } if (infoType == '3') { return { 'tomcat.sessions.created': { color: 'green', text: 'tomcat 已创建 session 数', unit: '个' }, 'tomcat.sessions.expired': { color: 'green', text: 'tomcat 已过期 session 数', unit: '个' }, 'tomcat.sessions.active.current': { color: 'green', text: 'tomcat 当前活跃 session 数', unit: '个' }, 'tomcat.sessions.active.max': { color: 'green', text: 'tomcat 活跃 session 数峰值', unit: '个' }, 'tomcat.sessions.rejected': { color: 'green', text: '超过session 最大配置后,拒绝的 session 个数', unit: '个' }, 'tomcat.global.sent': { color: 'purple', text: '发送的字节数', unit: 'bytes' }, 'tomcat.global.request.max': { color: 'purple', text: 'request 请求最长耗时', unit: '秒' }, 'tomcat.global.request.count': { color: 'purple', text: '全局 request 请求次数', unit: '次' }, 'tomcat.global.request.totalTime': { color: 'purple', text: '全局 request 请求总耗时', unit: '秒' }, 'tomcat.servlet.request.max': { color: 'cyan', text: 'servlet 请求最长耗时', unit: '秒' }, 'tomcat.servlet.request.count': { color: 'cyan', text: 'servlet 总请求次数', unit: '次' }, 'tomcat.servlet.request.totalTime': { color: 'cyan', text: 'servlet 请求总耗时', unit: '秒' }, 'tomcat.threads.current': { color: 'pink', text: 'tomcat 当前线程数(包括守护线程)', unit: '个' }, 'tomcat.threads.config.max': { color: 'pink', text: 'tomcat 配置的线程最大数', unit: '个' }, }; } }; /** * 查询cpu数量 * @param params */ export const getServerInfo = (infoType) => { if (infoType == '1') { return Promise.all([ getCpuCount(), getCpuUsage(), getProcessStartTime(), getProcessUptime(), getProcessCpuUsage(), ]); } if (infoType == '2') { return Promise.all([ getJvmMemoryMax(), getJvmMemoryCommitted(), getJvmMemoryUsed(), getJvmBufferCount(), getJvmBufferMemoryUsed(), getJvmThreadsDaemon(), getJvmThreadsLive(), getJvmThreadsPeak(), getJvmClassesLoaded(), getJvmClassesUnloaded(), getJvmGcLiveDataSize(), getJvmGcMaxDataSize(), getJvmGcMemoryAllocated(), getJvmGcMemoryPromoted(), getJvmGcPause(), ]); } if (infoType == '3') { return Promise.all([ getTomcatSessionsActiveCurrent(), getTomcatSessionsActiveMax(), getTomcatSessionsCreated(), getTomcatSessionsExpired(), getTomcatSessionsRejected(), ]); } };
the_stack
import EncodeHintType from './../../EncodeHintType' import BitArray from './../../common/BitArray' import CharacterSetECI from './../../common/CharacterSetECI' import GenericGF from './../../common/reedsolomon/GenericGF' import ReedSolomonEncoder from './../../common/reedsolomon/ReedSolomonEncoder' import ErrorCorrectionLevel from './../decoder/ErrorCorrectionLevel' import Mode from './../decoder/Mode' import Version from './../decoder/Version' import MaskUtil from './MaskUtil' import ByteMatrix from './ByteMatrix' import QRCode from './QRCode' import Exception from './../../Exception' import ECBlocks from './../decoder/ECBlocks' import MatrixUtil from './MatrixUtil' import StringEncoding from './../../util/StringEncoding' import BlockPair from './BlockPair' /*import java.io.UnsupportedEncodingException;*/ /*import java.util.ArrayList;*/ /*import java.util.Collection;*/ /*import java.util.Map;*/ /** * @author satorux@google.com (Satoru Takabayashi) - creator * @author dswitkin@google.com (Daniel Switkin) - ported from C++ */ export default class Encoder { // The original table is defined in the table 5 of JISX0510:2004 (p.19). private static ALPHANUMERIC_TABLE = Int32Array.from([ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f ]) public static DEFAULT_BYTE_MODE_ENCODING = CharacterSetECI.UTF8.getName()//"ISO-8859-1" // TYPESCRIPTPORT: changed to UTF8, the default for js private constructor() {} // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details. // Basically it applies four rules and summate all penalties. private static calculateMaskPenalty(matrix: ByteMatrix): number /*int*/ { return MaskUtil.applyMaskPenaltyRule1(matrix) + MaskUtil.applyMaskPenaltyRule2(matrix) + MaskUtil.applyMaskPenaltyRule3(matrix) + MaskUtil.applyMaskPenaltyRule4(matrix) } /** * @param content text to encode * @param ecLevel error correction level to use * @return {@link QRCode} representing the encoded QR code * @throws WriterException if encoding can't succeed, because of for example invalid content * or configuration */ // public static encode(content: string, ecLevel: ErrorCorrectionLevel): QRCode /*throws WriterException*/ { // return encode(content, ecLevel, null) // } public static encode(content: string, ecLevel: ErrorCorrectionLevel, hints: Map<EncodeHintType, any> = null): QRCode /*throws WriterException*/ { // Determine what character encoding has been specified by the caller, if any let encoding: string = Encoder.DEFAULT_BYTE_MODE_ENCODING const hasEncodingHint: boolean = hints !== null && undefined !== hints.get(EncodeHintType.CHARACTER_SET) if (hasEncodingHint) { encoding = hints.get(EncodeHintType.CHARACTER_SET).toString() } // Pick an encoding mode appropriate for the content. Note that this will not attempt to use // multiple modes / segments even if that were more efficient. Twould be nice. const mode: Mode = this.chooseMode(content, encoding) // This will store the header information, like mode and // length, as well as "header" segments like an ECI segment. const headerBits = new BitArray() // Append ECI segment if applicable if (mode == Mode.BYTE && (hasEncodingHint || Encoder.DEFAULT_BYTE_MODE_ENCODING !== encoding)) { const eci = CharacterSetECI.getCharacterSetECIByName(encoding) if (eci !== undefined) { this.appendECI(eci, headerBits) } } // (With ECI in place,) Write the mode marker this.appendModeInfo(mode, headerBits) // Collect data within the main segment, separately, to count its size if needed. Don't add it to // main payload yet. const dataBits = new BitArray() this.appendBytes(content, mode, dataBits, encoding) let version: Version if (hints !== null && undefined !== hints.get(EncodeHintType.QR_VERSION)) { const versionNumber = Number.parseInt(hints.get(EncodeHintType.QR_VERSION).toString(), 10) version = Version.getVersionForNumber(versionNumber) const bitsNeeded = this.calculateBitsNeeded(mode, headerBits, dataBits, version) if (!this.willFit(bitsNeeded, version, ecLevel)) { throw new Exception(Exception.WriterException, "Data too big for requested version") } } else { version = this.recommendVersion(ecLevel, mode, headerBits, dataBits) } const headerAndDataBits = new BitArray() headerAndDataBits.appendBitArray(headerBits) // Find "length" of main segment and write it const numLetters = mode == Mode.BYTE ? dataBits.getSizeInBytes() : content.length this.appendLengthInfo(numLetters, version, mode, headerAndDataBits) // Put data together into the overall payload headerAndDataBits.appendBitArray(dataBits) const ecBlocks: ECBlocks = version.getECBlocksForLevel(ecLevel) const numDataBytes = version.getTotalCodewords() - ecBlocks.getTotalECCodewords() // Terminate the bits properly. this.terminateBits(numDataBytes, headerAndDataBits) // Interleave data bits with error correction code. const finalBits: BitArray = this.interleaveWithECBytes(headerAndDataBits, version.getTotalCodewords(), numDataBytes, ecBlocks.getNumBlocks()) const qrCode = new QRCode() qrCode.setECLevel(ecLevel) qrCode.setMode(mode) qrCode.setVersion(version) // Choose the mask pattern and set to "qrCode". const dimension = version.getDimensionForVersion() const matrix: ByteMatrix = new ByteMatrix(dimension, dimension) const maskPattern = this.chooseMaskPattern(finalBits, ecLevel, version, matrix) qrCode.setMaskPattern(maskPattern) // Build the matrix and set it to "qrCode". MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix) qrCode.setMatrix(matrix) return qrCode } /** * Decides the smallest version of QR code that will contain all of the provided data. * * @throws WriterException if the data cannot fit in any version */ private static recommendVersion(ecLevel: ErrorCorrectionLevel, mode: Mode, headerBits: BitArray, dataBits: BitArray): Version /*throws WriterException*/ { // Hard part: need to know version to know how many bits length takes. But need to know how many // bits it takes to know version. First we take a guess at version by assuming version will be // the minimum, 1: const provisionalBitsNeeded = this.calculateBitsNeeded(mode, headerBits, dataBits, Version.getVersionForNumber(1)) const provisionalVersion = this.chooseVersion(provisionalBitsNeeded, ecLevel) // Use that guess to calculate the right version. I am still not sure this works in 100% of cases. const bitsNeeded = this.calculateBitsNeeded(mode, headerBits, dataBits, provisionalVersion) return this.chooseVersion(bitsNeeded, ecLevel) } private static calculateBitsNeeded(mode: Mode, headerBits: BitArray, dataBits: BitArray, version: Version): number /*int*/ { return headerBits.getSize() + mode.getCharacterCountBits(version) + dataBits.getSize() } /** * @return the code point of the table used in alphanumeric mode or * -1 if there is no corresponding code in the table. */ public static getAlphanumericCode(code: number /*int*/): number /*int*/ { if (code < Encoder.ALPHANUMERIC_TABLE.length) { return Encoder.ALPHANUMERIC_TABLE[code] } return -1 } // public static chooseMode(content: string): Mode { // return chooseMode(content, null); // } /** * Choose the best mode by examining the content. Note that 'encoding' is used as a hint; * if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}. */ public static chooseMode(content: string, encoding: string = null): Mode { if (CharacterSetECI.SJIS.getName() === encoding && this.isOnlyDoubleByteKanji(content)) { // Choose Kanji mode if all input are double-byte characters return Mode.KANJI } let hasNumeric: boolean = false let hasAlphanumeric: boolean = false for (let i = 0, length = content.length; i < length; ++i) { const c: string = content.charAt(i) if (Encoder.isDigit(c)) { hasNumeric = true } else if (this.getAlphanumericCode(c.charCodeAt(0)) != -1) { hasAlphanumeric = true } else { return Mode.BYTE } } if (hasAlphanumeric) { return Mode.ALPHANUMERIC } if (hasNumeric) { return Mode.NUMERIC } return Mode.BYTE } private static isOnlyDoubleByteKanji(content: string): boolean { let bytes: Uint8Array try { bytes = StringEncoding.encode(content, CharacterSetECI.SJIS.getName())//content.getBytes("Shift_JIS") } catch (ignored/*: UnsupportedEncodingException*/) { return false } const length = bytes.length if (length % 2 != 0) { return false } for (let i = 0; i < length; i += 2) { const byte1 = bytes[i] & 0xFF if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) { return false } } return true } private static chooseMaskPattern(bits: BitArray, ecLevel: ErrorCorrectionLevel, version: Version, matrix: ByteMatrix): number /*int*/ /*throws WriterException*/ { let minPenalty = Number.MAX_SAFE_INTEGER; // Lower penalty is better. let bestMaskPattern = -1 // We try all mask patterns to choose the best one. for (let maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) { MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix) let penalty = this.calculateMaskPenalty(matrix) if (penalty < minPenalty) { minPenalty = penalty bestMaskPattern = maskPattern } } return bestMaskPattern } private static chooseVersion(numInputBits: number /*int*/, ecLevel: ErrorCorrectionLevel): Version /*throws WriterException*/ { for (let versionNum = 1; versionNum <= 40; versionNum++) { const version = Version.getVersionForNumber(versionNum) if (Encoder.willFit(numInputBits, version, ecLevel)) { return version } } throw new Exception(Exception.WriterException, "Data too big") } /** * @return true if the number of input bits will fit in a code with the specified version and * error correction level. */ private static willFit(numInputBits: number /*int*/, version: Version, ecLevel: ErrorCorrectionLevel): boolean { // In the following comments, we use numbers of Version 7-H. // numBytes = 196 const numBytes = version.getTotalCodewords() // getNumECBytes = 130 const ecBlocks = version.getECBlocksForLevel(ecLevel) const numEcBytes = ecBlocks.getTotalECCodewords() // getNumDataBytes = 196 - 130 = 66 const numDataBytes = numBytes - numEcBytes const totalInputBytes = (numInputBits + 7) / 8 return numDataBytes >= totalInputBytes } /** * Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24). */ public static terminateBits(numDataBytes: number /*int*/, bits: BitArray): void /*throws WriterException*/ { const capacity = numDataBytes * 8; if (bits.getSize() > capacity) { throw new Exception(Exception.WriterException, "data bits cannot fit in the QR Code" + bits.getSize() + " > " + capacity) } for (let i = 0; i < 4 && bits.getSize() < capacity; ++i) { bits.appendBit(false) } // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. // If the last byte isn't 8-bit aligned, we'll add padding bits. const numBitsInLastByte = bits.getSize() & 0x07; if (numBitsInLastByte > 0) { for (let i = numBitsInLastByte; i < 8; i++) { bits.appendBit(false) } } // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). const numPaddingBytes = numDataBytes - bits.getSizeInBytes() for (let i = 0; i < numPaddingBytes; ++i) { bits.appendBits((i & 0x01) == 0 ? 0xEC : 0x11, 8) } if (bits.getSize() != capacity) { throw new Exception(Exception.WriterException, "Bits size does not equal capacity") } } /** * Get number of data bytes and number of error correction bytes for block id "blockID". Store * the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of * JISX0510:2004 (p.30) */ public static getNumDataBytesAndNumECBytesForBlockID(numTotalBytes: number /*int*/, numDataBytes: number /*int*/, numRSBlocks: number /*int*/, blockID: number /*int*/, numDataBytesInBlock: Int32Array, numECBytesInBlock: Int32Array): void /*throws WriterException*/ { if (blockID >= numRSBlocks) { throw new Exception(Exception.WriterException, "Block ID too large") } // numRsBlocksInGroup2 = 196 % 5 = 1 const numRsBlocksInGroup2 = numTotalBytes % numRSBlocks // numRsBlocksInGroup1 = 5 - 1 = 4 const numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2 // numTotalBytesInGroup1 = 196 / 5 = 39 const numTotalBytesInGroup1 = Math.floor(numTotalBytes / numRSBlocks) // numTotalBytesInGroup2 = 39 + 1 = 40 const numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1 // numDataBytesInGroup1 = 66 / 5 = 13 const numDataBytesInGroup1 = Math.floor(numDataBytes / numRSBlocks) // numDataBytesInGroup2 = 13 + 1 = 14 const numDataBytesInGroup2 = numDataBytesInGroup1 + 1 // numEcBytesInGroup1 = 39 - 13 = 26 const numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1 // numEcBytesInGroup2 = 40 - 14 = 26 const numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2 // Sanity checks. // 26 = 26 if (numEcBytesInGroup1 !== numEcBytesInGroup2) { throw new Exception(Exception.WriterException, "EC bytes mismatch") } // 5 = 4 + 1. if (numRSBlocks !== numRsBlocksInGroup1 + numRsBlocksInGroup2) { throw new Exception(Exception.WriterException, "RS blocks mismatch") } // 196 = (13 + 26) * 4 + (14 + 26) * 1 if (numTotalBytes !== ((numDataBytesInGroup1 + numEcBytesInGroup1) * numRsBlocksInGroup1) + ((numDataBytesInGroup2 + numEcBytesInGroup2) * numRsBlocksInGroup2)) { throw new Exception(Exception.WriterException, "Total bytes mismatch") } if (blockID < numRsBlocksInGroup1) { numDataBytesInBlock[0] = numDataBytesInGroup1 numECBytesInBlock[0] = numEcBytesInGroup1 } else { numDataBytesInBlock[0] = numDataBytesInGroup2 numECBytesInBlock[0] = numEcBytesInGroup2 } } /** * Interleave "bits" with corresponding error correction bytes. On success, store the result in * "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details. */ public static interleaveWithECBytes(bits: BitArray, numTotalBytes: number /*int*/, numDataBytes: number /*int*/, numRSBlocks: number /*int*/): BitArray /*throws WriterException*/ { // "bits" must have "getNumDataBytes" bytes of data. if (bits.getSizeInBytes() !== numDataBytes) { throw new Exception(Exception.WriterException, "Number of bits and data bytes does not match") } // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll // store the divided data bytes blocks and error correction bytes blocks into "blocks". let dataBytesOffset = 0 let maxNumDataBytes = 0 let maxNumEcBytes = 0 // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. const blocks = new Array<BlockPair>()//new Array<BlockPair>(numRSBlocks) for (let i = 0; i < numRSBlocks; ++i) { const numDataBytesInBlock: Int32Array = new Int32Array(1) const numEcBytesInBlock: Int32Array = new Int32Array(1) Encoder.getNumDataBytesAndNumECBytesForBlockID( numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock) const size = numDataBytesInBlock[0] const dataBytes = new Uint8Array(size) bits.toBytes(8 * dataBytesOffset, dataBytes, 0, size); const ecBytes: Uint8Array = Encoder.generateECBytes(dataBytes, numEcBytesInBlock[0]) blocks.push(new BlockPair(dataBytes, ecBytes)) maxNumDataBytes = Math.max(maxNumDataBytes, size) maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.length) dataBytesOffset += numDataBytesInBlock[0] } if (numDataBytes != dataBytesOffset) { throw new Exception(Exception.WriterException, "Data bytes does not match offset") } const result = new BitArray() // First, place data blocks. for (let i = 0; i < maxNumDataBytes; ++i) { for (const block of blocks) { const dataBytes = block.getDataBytes() if (i < dataBytes.length) { result.appendBits(dataBytes[i], 8) } } } // Then, place error correction blocks. for (let i = 0; i < maxNumEcBytes; ++i) { for (const block of blocks) { const ecBytes = block.getErrorCorrectionBytes() if (i < ecBytes.length) { result.appendBits(ecBytes[i], 8) } } } if (numTotalBytes != result.getSizeInBytes()) { // Should be same. throw new Exception("WriterException", "Interleaving error: " + numTotalBytes + " and " + result.getSizeInBytes() + " differ.") } return result } public static generateECBytes(dataBytes: Uint8Array, numEcBytesInBlock: number /*int*/): Uint8Array { const numDataBytes = dataBytes.length const toEncode: Int32Array = new Int32Array(numDataBytes + numEcBytesInBlock)//int[numDataBytes + numEcBytesInBlock] for (let i = 0; i < numDataBytes; i++) { toEncode[i] = dataBytes[i] & 0xFF } new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256).encode(toEncode, numEcBytesInBlock) const ecBytes = new Uint8Array(numEcBytesInBlock) for (let i = 0; i < numEcBytesInBlock; i++) { ecBytes[i] = /*(byte) */toEncode[numDataBytes + i] } return ecBytes } /** * Append mode info. On success, store the result in "bits". */ public static appendModeInfo(mode: Mode, bits: BitArray): void { bits.appendBits(mode.getBits(), 4) } /** * Append length info. On success, store the result in "bits". */ public static appendLengthInfo(numLetters: number /*int*/, version: Version, mode: Mode, bits: BitArray): void /*throws WriterException*/ { const numBits = mode.getCharacterCountBits(version) if (numLetters >= (1 << numBits)) { throw new Exception(Exception.WriterException, numLetters + " is bigger than " + ((1 << numBits) - 1)) } bits.appendBits(numLetters, numBits) } /** * Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits". */ public static appendBytes(content: string, mode: Mode, bits: BitArray, encoding: string): void /*throws WriterException*/ { switch (mode) { case Mode.NUMERIC: Encoder.appendNumericBytes(content, bits) break case Mode.ALPHANUMERIC: Encoder.appendAlphanumericBytes(content, bits) break case Mode.BYTE: Encoder.append8BitBytes(content, bits, encoding) break case Mode.KANJI: Encoder.appendKanjiBytes(content, bits) break default: throw new Exception(Exception.WriterException, "Invalid mode: " + mode) } } private static getDigit(singleCharacter: string): number { return singleCharacter.charCodeAt(0) - 48 } private static isDigit(singleCharacter: string): boolean { const cn = Encoder.getDigit(singleCharacter) return cn >= 0 && cn <= 9 } public static appendNumericBytes(content: string, bits: BitArray): void { const length = content.length let i = 0 while (i < length) { const num1 = Encoder.getDigit(content.charAt(i)) if (i + 2 < length) { // Encode three numeric letters in ten bits. const num2 = Encoder.getDigit(content.charAt(i + 1)) const num3 = Encoder.getDigit(content.charAt(i + 2)) bits.appendBits(num1 * 100 + num2 * 10 + num3, 10) i += 3 } else if (i + 1 < length) { // Encode two numeric letters in seven bits. const num2 = Encoder.getDigit(content.charAt(i + 1)) bits.appendBits(num1 * 10 + num2, 7); i += 2 } else { // Encode one numeric letter in four bits. bits.appendBits(num1, 4) i++ } } } public static appendAlphanumericBytes(content: string, bits: BitArray): void /*throws WriterException*/ { const length = content.length let i = 0 while (i < length) { const code1 = Encoder.getAlphanumericCode(content.charCodeAt(i)) if (code1 == -1) { throw new Exception(Exception.WriterException) } if (i + 1 < length) { const code2 = Encoder.getAlphanumericCode(content.charCodeAt(i + 1)) if (code2 == -1) { throw new Exception(Exception.WriterException) } // Encode two alphanumeric letters in 11 bits. bits.appendBits(code1 * 45 + code2, 11); i += 2 } else { // Encode one alphanumeric letter in six bits. bits.appendBits(code1, 6) i++ } } } public static append8BitBytes(content: string, bits: BitArray, encoding: string): void /*throws WriterException*/ { let bytes: Uint8Array try { bytes = StringEncoding.encode(content, encoding) } catch (uee/*: UnsupportedEncodingException*/) { throw new Exception(Exception.WriterException, uee) } for (let i = 0, length = bytes.length; i != length; i++) { const b = bytes[i] bits.appendBits(b, 8) } } public static appendKanjiBytes(content: string, bits: BitArray): void /*throws WriterException*/ { let bytes: Uint8Array try { bytes = StringEncoding.encode(content, CharacterSetECI.SJIS.getName()) } catch (uee/*: UnsupportedEncodingException*/) { throw new Exception(Exception.WriterException, uee) } const length = bytes.length for (let i = 0; i < length; i += 2) { const byte1 = bytes[i] & 0xFF const byte2 = bytes[i + 1] & 0xFF const code = ((byte1 << 8) & 0xFFFFFFFF) | byte2 let subtracted = -1 if (code >= 0x8140 && code <= 0x9ffc) { subtracted = code - 0x8140 } else if (code >= 0xe040 && code <= 0xebbf) { subtracted = code - 0xc140 } if (subtracted === -1) { throw new Exception(Exception.WriterException, "Invalid byte sequence") } const encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); bits.appendBits(encoded, 13) } } private static appendECI(eci: CharacterSetECI, bits: BitArray): void { bits.appendBits(Mode.ECI.getBits(), 4) // This is correct for values up to 127, which is all we need now. bits.appendBits(eci.getValue(), 8) } }
the_stack
import { ICarouselConfigProps } from '..'; import { getEle } from '../../../utility/dom/getEle'; import { getAllEle } from '../../../utility/dom/getAllEle'; import { setCss } from '../../../utility/dom/setCss'; import { addClass } from '../../../utility/dom/addClass'; import { removeClass } from '../../../utility/dom/removeClass'; import { getAttr } from '../../../utility/dom/getAttr'; export class Fade { private static defaultConfig = { container: 'body', dataSource: [ { text: '面板一', img: { url: '', target: '', }, }, { text: '面板二', img: { url: '', target: '', }, }, { text: '面板三', img: { url: '', target: '', }, }, { text: '面板四', img: { url: '', target: '', }, }, ], autoPlay: false, showDots: false, showArrows: false, easing: 'ease-in-out', effect: 'scroll', vertical: false, duringTime: 1.5, delayTime: 3000, isHoverPause: true, beforeChange: () => null, afterChange: () => null, }; private oContentItem: any = null; private oArrowWrapper: any = null; private oPrevWrapper: any = null; private oNextWrapper: any = null; private oDotsItem: any = null; private oContentItemLength: number = 0; private timer: any = 0; private count: number = 0; public constructor( config: ICarouselConfigProps, ) { this.init(config); } public init( config: ICarouselConfigProps, ): void { this.initSettings(config); this.initDOM(); } public initSettings( config: ICarouselConfigProps, ): void { for (const key in config) { if (config.hasOwnProperty(key)) { const value = Reflect.get(config, key); Reflect.set(Fade.defaultConfig, key, value); } } } public initDOM(): void { const { container, showArrows, showDots, autoPlay } = Fade.defaultConfig; const oContainer = getEle(container); if (oContainer) { const temp = document.createElement('div'); temp.innerHTML = this.createDOM(); oContainer.appendChild(temp); this.createStyle(); this.initCommonEle(); autoPlay && this.handleAutoPlay(); showArrows && this.handleArrowClick(); showArrows && this.handleImgHover(); showDots && this.handleDotsHover(); } } public createDOM(): string { const dataSource: any[] = Fade.defaultConfig.dataSource; const { showArrows, showDots } = Fade.defaultConfig; let dotsSpan: string = ''; let contentLi: string = ''; dataSource.forEach((item: any, index: number) => { dotsSpan += ` <span class="yyg-dot-item${ index === 0 ? ' yyg-dot-item-active' : '' }" data-id=${index + 1} ></span> `; contentLi += ` <li class="yyg-content-item" data-id=${index + 1}> ${ item.img.url ? `<a href=${item.img.target} ><img src=${item.img.url} alt="图片提示" /></a>` : item.text } </li> `; }); const final: string = ` <div class="yyg-carousel-container"> <div class="yyg-carousel-main"> <div class="yyg-content-wrapper"> <ul class="yyg-content-list">${contentLi}</ul> </div> ${ showArrows ? ` <div class="yyg-arrow-wrapper yyg-arrow-prev-wrapper"> <i class="yyg-arrow yyg-arrow-prev">&lt;</i> </div> <div class="yyg-arrow-wrapper yyg-arrow-next-wrapper"> <i class="yyg-arrow yyg-arrow-next">&gt;</i> </div> ` : '' } ${ showDots ? `<div class="yyg-dots-wrapper">${dotsSpan}</div>` : '' } </div> </div> `; return final; } public createStyle(): void { let oStyle: HTMLElement | null = getEle('style'); const { dataSource, container, } = Fade.defaultConfig; // style标签不存在 if (!oStyle) { oStyle = document.createElement('style'); const oHead = getEle('head') as HTMLHeadElement; oHead.appendChild(oStyle); } oStyle.innerText += ` ${container} ul, p { margin: 0; padding: 0; } ${container} ul { list-style-type: none; } ${container} .yyg-carousel-container { box-sizing: border-box; height: 100%; padding: 10px; border: 5px solid #1890ff; border-radius: 20px; } ${container} .yyg-carousel-main { position: relative; // height: 100%; height: 300px; } ${container} .yyg-arrow-wrapper { display: none; position: absolute; z-index: 999; top: 50%; width: 30px; heigth: 45px; border-top-right-radius: 15px; border-bottom-right-radius: 15px; background-clip: padding-box; background-color: rgba(0,0,0,.5); color: #fff; opacity: 0; line-height: 45px; font-size: 24px; text-align: center; cursor: pointer; user-select: none; transform: translateY(-50%); transition: all .5s ease-in-out; } ${container} .yyg-arrow-prev-wrapper { left: 0; } ${container} .yyg-arrow-next-wrapper { right: 0; } ${container} .yyg-content-wrapper { overflow: hidden; height: 100%; } ${container} .yyg-content-list { position: relative; height: 100%; } ${container} .yyg-content-item { position: absolute; width: 100%; height: 100%; text-align: center; opacity: 0; } ${container} .yyg-content-item:first-child { opacity: 1; z-index: 0; } ${container} .yyg-content-item a img { display: block; max-width: 100%; height: 100%; border-radius: 6px; } ${container} .yyg-dots-wrapper { position: absolute; left: 50%; bottom: 10px; z-index: 888; padding: 2px 0; border: 1px solid #ccc; border-radius: 8px; background-color: rgba(0,0,0,.5); font-size: 0; transform: translateX(-50%); } ${container} .yyg-dot-item { display: inline-block; margin-left: 5px; width: 12px; height: 12px; background-color: #fff; border-radius: 50%; transition: all .5s ease-in-out; } ${container} .yyg-dot-item:last-child { margin-right: 5px; } ${container} .yyg-dot-item-active { background-color: #d50; } ${container} .yyg-prev-wrapper-active { left: 15px; opacity: 1; } ${container} .yyg-next-wrapper-active { right: 15px; opacity: 1; } `; } public initCommonEle(): void { this.oContentItem = getAllEle('.yyg-content-item'); this.oDotsItem = getAllEle('.yyg-dot-item'); this.oArrowWrapper = getAllEle('.yyg-arrow-wrapper'); this.oPrevWrapper = getEle('.yyg-arrow-prev-wrapper'); this.oNextWrapper = getEle('.yyg-arrow-next-wrapper'); this.oContentItemLength = this.oContentItem.length; } /** * 处理 自动轮播 */ public handleAutoPlay(): void { const { delayTime, easing, duringTime, } = Fade.defaultConfig; const oContentItem = this.oContentItem; const oDotsItem = this.oDotsItem; const oContentItemLength = this.oContentItemLength; this.timer = setInterval(() => { oContentItem.forEach((item: any, index: number) => { if (index === this.count) { setCss(item, { transition: `all ${ duringTime }s ${ easing }`, 'z-index': this.count + 1, opacity: 1, }); // dot栏样式改变 oDotsItem.forEach((item: any, inx: number) => { inx === this.count ? addClass(item, 'yyg-dot-item-active') : removeClass(item, 'yyg-dot-item-active'); }); } else { setCss(item, { transition: `all ${ duringTime }s ${ easing }`, 'z-index': 0, opacity: 0, }); } }); this.count++; }, delayTime); oContentItem.forEach((item: any) => { item.addEventListener('transitionend', () => { if (this.count > oContentItemLength - 1) { this.count = 0; } }, false); }); } /** * 处理 鼠标 点击切换 */ public handleArrowClick(): void { const oNextArrow = this.oNextWrapper; const oPrevArrow = this.oPrevWrapper; oNextArrow.addEventListener('click', () => { this.aidedArrowClick('next'); }, false); oPrevArrow.addEventListener('click', () => { this.aidedArrowClick('prev'); }, false); } /** * 处理 dot栏hover */ public handleDotsHover(): void { const { showDots, } = Fade.defaultConfig; const oDotsItem = this.oDotsItem; showDots && oDotsItem.forEach((item: any) => { const oSignId: number = Number(getAttr( item, 'data-id', )); item.addEventListener('mouseenter', () => { clearInterval(this.timer); this.aidedSetDotAndImg(oSignId - 1); }, false); item.addEventListener('mouseleave', () => { // 更新索引 this.count = oSignId - 1; this.handleAutoPlay(); }, false); }); } /** * 处理 图片hover */ public handleImgHover(): void { const oArrowWrapper = this.oArrowWrapper; const oContentItem = this.oContentItem; const oPrevArrow = this.oPrevWrapper; const oNextArrow = this.oNextWrapper; // 箭头hover(处理bug) oArrowWrapper.forEach((item: any) => { setCss(item, { display: 'block', }); item.addEventListener('mouseenter', () => { addClass(oPrevArrow, 'yyg-prev-wrapper-active') addClass(oNextArrow, 'yyg-next-wrapper-active'); }, false); }); oContentItem.forEach((item: any) => { item.addEventListener('mouseenter', () => { clearInterval(this.timer); addClass(oPrevArrow, 'yyg-prev-wrapper-active') addClass(oNextArrow, 'yyg-next-wrapper-active'); }, false); item.addEventListener('mouseleave', () => { removeClass(oPrevArrow, 'yyg-prev-wrapper-active') removeClass(oNextArrow, 'yyg-next-wrapper-active'); this.handleAutoPlay(); }, false); }); } /** * 箭头点击辅助函数 * @param direction 哪个箭头 */ public aidedArrowClick( direction: 'prev' | 'next', ): void { const oContentItemLength = this.oContentItemLength; clearInterval(this.timer); switch (direction) { case 'prev': this.count--; this.count = this.count < 0 ? oContentItemLength - 1 : this.count; break; case 'next': this.count++; this.count = this.count > oContentItemLength - 1 ? 0 : this.count; break; default: break; } this.aidedSetDotAndImg(this.count); this.handleAutoPlay(); } /** * 辅助 设置图片轮播,dot栏对应样式 * @param sign */ public aidedSetDotAndImg( sign: number, ): void { const { duringTime, easing, } = Fade.defaultConfig; const oContentItem = this.oContentItem; const oDotsItem = this.oDotsItem; oContentItem.forEach((item: any, index: number) => { if (sign === index) { setCss(item, { transition: `all ${duringTime}s ${easing}`, opacity: 1, 'z-index': index, }) addClass(oDotsItem[index], 'yyg-dot-item-active') } else { setCss(item, { transition: `all ${duringTime}s ${easing}`, opacity: 0, 'z-index': 0, }) removeClass( oDotsItem[index], 'yyg-dot-item-active' ) } }) } }
the_stack
import { state } from ".."; /** * Combat result for death */ export const COMBATTABLE_DEATH = "D"; /** * The combat table */ export const combatTable = { /** * Combat table results when the combat ratio is <= 0 */ tableBelowOrEqualToEnemy: { // Random table result = 1 1: { 0: [ 3 , 5 ], // Combat ratio 0 => E: 3 / LW: 5 1: [ 2 , 5 ], // Combat ratio -1 / -2 => E: 2 / LW: 5 2: [ 1 , 6 ], // Combat ratio -3 / -4, => E: 1 / LW: 6 3: [ 0 , 6 ], // ... 4: [ 0 , 8 ], 5: [ 0 , COMBATTABLE_DEATH], 6: [ 0 , COMBATTABLE_DEATH ] }, // Random table result = 2 2: { 0: [ 4 , 4 ], 1: [ 3 , 5 ], 2: [ 2 , 5 ], 3: [ 1 , 6 ], 4: [ 0 , 7 ], 5: [ 0 , 8 ], 6: [ 0 , COMBATTABLE_DEATH ] }, // Random table result = 3 3: { 0: [ 5 , 4 ], 1: [ 4 , 4 ], 2: [ 3 , 5 ], 3: [ 2 , 5 ], 4: [ 1 , 6 ], 5: [ 0 , 7 ], 6: [ 0 , 8 ] }, // Random table result = 4 4: { 0: [6 , 3], 1: [5 , 4], 2: [4 , 4], 3: [3 , 5], 4: [2 , 6], 5: [1 , 7], 6: [0 , 8] }, // Random table result = 5 5: { 0: [7 , 2], 1: [6 , 3], 2: [5 , 4], 3: [4 , 4], 4: [3 , 5], 5: [2 , 6], 6: [1 , 7] }, // Random table result = 6 6: { 0: [8 , 2], 1: [7 , 2], 2: [6 , 3], 3: [5 , 4], 4: [4 , 5], 5: [3 , 6], 6: [2 , 6] }, // Random table result = 7 7: { 0: [9 , 1], 1: [8 , 2], 2: [7 , 2], 3: [6 , 3], 4: [5 , 4], 5: [4 , 5], 6: [3 , 5] }, // Random table result = 8 8: { 0: [10 , 0], 1: [9 , 1], 2: [8 , 1], 3: [7 , 2], 4: [6 , 3], 5: [5 , 4], 6: [4 , 4] }, // Random table result = 9 9: { 0: [11 , 0], 1: [10 , 0], 2: [9 , 0], 3: [8 , 0], 4: [7 , 2], 5: [6 , 3], 6: [5 , 3] }, // Random table result = 0 0: { 0: [12 , 0], 1: [11 , 0], 2: [10 , 0], 3: [9 , 0], 4: [8 , 0], 5: [7 , 0], 6: [6 , 0] } }, /** * Combat table results when the combat ratio is > 0 */ tableAboveEnemy: { // Random table result = 1 1: { 1: [4 , 5], // Combat ratio +1 / +2 => E: 4 , LW: 5 2: [5 , 4], // Combat ratio +3 / +4 => E: 5 , LW: 4 3: [6 , 4], // ... 4: [7 , 4], 5: [8 , 3], 6: [9 , 3], // Combat ratio +11 or more if NO extended table (+11 / +12 if extended table) 7: [10, 2], // EXTENDED TABLE STARTS HERE (Combat ratio +13 / +14) 8: [11, 2], 9: [12, 1], 10: [14, 1], 11: [16, 1], 12: [18, 0], 13: [20, 0], 14: [22, 0], 15: [COMBATTABLE_DEATH, 0] }, // Random table result = 2 2: { 1: [5 , 4], 2: [6 , 3], 3: [7 , 3], 4: [8 , 3], 5: [9 , 3], 6: [10 , 2], 7: [11, 2], 8: [12, 1], 9: [14, 1], 10: [16, 1], 11: [18, 0], 12: [20, 0], 13: [22, 0], 14: [COMBATTABLE_DEATH, 0], 15: [COMBATTABLE_DEATH, 0] }, // Random table result = 3 3: { 1: [6 , 3], 2: [7 , 3], 3: [8 , 3], 4: [9 , 2], 5: [10 , 2], 6: [11 , 2], 7: [12, 1], 8: [14, 1], 9: [16, 1], 10: [18, 0], 11: [20, 0], 12: [22, 0], 13: [COMBATTABLE_DEATH, 0], 14: [COMBATTABLE_DEATH, 0], 15: [COMBATTABLE_DEATH, 0] }, // Random table result = 4 4: { 1: [7 , 3], 2: [8 , 2], 3: [9 , 2], 4: [10 , 2], 5: [11 , 2], 6: [12 , 2], 7: [14, 1], 8: [16, 1], 9: [18, 0], 10: [20, 0], 11: [COMBATTABLE_DEATH, 0], 12: [COMBATTABLE_DEATH, 0], 13: [COMBATTABLE_DEATH, 0], 14: [COMBATTABLE_DEATH, 0], 15: [COMBATTABLE_DEATH, 0] }, // Random table result = 5 5: { 1: [8 , 2], 2: [9 , 2], 3: [10 , 2], 4: [11 , 2], 5: [12 , 2], 6: [14 , 1], 7: [16, 1], 8: [18, 0], 9: [20, 0], 10: [COMBATTABLE_DEATH, 0], 11: [COMBATTABLE_DEATH, 0], 12: [COMBATTABLE_DEATH, 0], 13: [COMBATTABLE_DEATH, 0], 14: [COMBATTABLE_DEATH, 0], 15: [COMBATTABLE_DEATH, 0] }, // Random table result = 6 6: { 1: [9, 2], 2: [10, 2], 3: [11, 1], 4: [12, 1], 5: [14, 1], 6: [16, 1], 7: [18, 0], 8: [20, 0], 9: [COMBATTABLE_DEATH, 0], 10: [COMBATTABLE_DEATH, 0], 11: [COMBATTABLE_DEATH, 0], 12: [COMBATTABLE_DEATH, 0], 13: [COMBATTABLE_DEATH, 0], 14: [COMBATTABLE_DEATH, 0], 15: [COMBATTABLE_DEATH, 0] }, // Random table result = 7 7: { 1: [10, 1], 2: [11, 1], 3: [12, 0], 4: [14, 0], 5: [16, 0], 6: [18, 0], 7: [20, 0], 8: [COMBATTABLE_DEATH, 0], 9: [COMBATTABLE_DEATH, 0], 10: [COMBATTABLE_DEATH, 0], 11: [COMBATTABLE_DEATH, 0], 12: [COMBATTABLE_DEATH, 0], 13: [COMBATTABLE_DEATH, 0], 14: [COMBATTABLE_DEATH, 0], 15: [COMBATTABLE_DEATH, 0] }, // Random table result = 8 8: { 1: [11, 0], 2: [12, 0], 3: [14, 0], 4: [16, 0], 5: [18, 0], 6: [COMBATTABLE_DEATH, 0], 7: [COMBATTABLE_DEATH, 0], 8: [COMBATTABLE_DEATH, 0], 9: [COMBATTABLE_DEATH, 0], 10: [COMBATTABLE_DEATH, 0], 11: [COMBATTABLE_DEATH, 0], 12: [COMBATTABLE_DEATH, 0], 13: [COMBATTABLE_DEATH, 0], 14: [COMBATTABLE_DEATH, 0], 15: [COMBATTABLE_DEATH, 0] }, // Random table result = 9 9: { 1: [12, 0], 2: [14, 0], 3: [16, 0], 4: [18, 0], 5: [COMBATTABLE_DEATH, 0], 6: [COMBATTABLE_DEATH, 0], 7: [COMBATTABLE_DEATH, 0], 8: [COMBATTABLE_DEATH, 0], 9: [COMBATTABLE_DEATH, 0], 10: [COMBATTABLE_DEATH, 0], 11: [COMBATTABLE_DEATH, 0], 12: [COMBATTABLE_DEATH, 0], 13: [COMBATTABLE_DEATH, 0], 14: [COMBATTABLE_DEATH, 0], 15: [COMBATTABLE_DEATH, 0] }, // Random table result = 0 0: { 1: [14, 0], 2: [16, 0], 3: [18, 0], 4: [COMBATTABLE_DEATH, 0], 5: [COMBATTABLE_DEATH, 0], 6: [COMBATTABLE_DEATH, 0], 7: [COMBATTABLE_DEATH, 0], 8: [COMBATTABLE_DEATH, 0], 9: [COMBATTABLE_DEATH, 0], 10: [COMBATTABLE_DEATH, 0], 11: [COMBATTABLE_DEATH, 0], 12: [COMBATTABLE_DEATH, 0], 13: [COMBATTABLE_DEATH, 0], 14: [COMBATTABLE_DEATH, 0], 15: [COMBATTABLE_DEATH, 0] }, }, /** * Get a combat table result * @param combatRatio The combat ratio * @param randomTableValue The random table value * @returns Array with endurance points loses, or COMBATTABLE_DEATH. Index 0 is the * EP enemy loss. Index 1 is the Lone Wolf loss */ getCombatTableResult(combatRatio: number, randomTableValue: number): any[] { /* var ponderatedIndex = combatRatio / 2.0; // check if we're using the extended CRT or not and set max column var maxPonderatedIndex = state.actionChart.extendedCRT ? 15 : 6; // Set to the right column if( ponderatedIndex < 0) { // round -4.5 to -5 ponderatedIndex = Math.floor(ponderatedIndex); } else if( ponderatedIndex > 0) { // round 4.5 to 5 ponderatedIndex = Math.ceil(ponderatedIndex); } // stick to min and max columns if( ponderatedIndex < -6 ) { ponderatedIndex = -6; } else if( ponderatedIndex > maxPonderatedIndex ) { ponderatedIndex = maxPonderatedIndex; } var table; if( combatRatio <= 0 ) { table = combatTable.tableBelowOrEqualToEnemy; // flip the sign to select the right column ponderatedIndex = - ponderatedIndex; } else { table = combatTable.tableAboveEnemy; } return table[randomTableValue][ponderatedIndex]; */ let ponderatedIndex = combatRatio / 2.0; let table; if ( combatRatio <= 0 ) { table = combatTable.tableBelowOrEqualToEnemy; ponderatedIndex = - ponderatedIndex; } else { table = combatTable.tableAboveEnemy; } // round 4.5 to 5 ponderatedIndex = Math.ceil(ponderatedIndex); // check if we're using the extended CRT or not and set max column const maxPonderatedIndex = state.actionChart.extendedCRT && combatRatio > 0 ? 15 : 6; if ( ponderatedIndex > maxPonderatedIndex ) { ponderatedIndex = maxPonderatedIndex; } return table[randomTableValue][ponderatedIndex]; } };
the_stack
import { flatten, isEmpty, cloneDeep, uniqBy } from 'lodash'; import { combineGraphs } from '../../utils/graph-utils/utils'; import { getFilterOptions, getGraph, getStyleOptions } from './selectors'; import * as GraphSlices from './slice'; import { importEdgeListCsv, importNodeEdgeCsv, importJson, } from './processors/import'; import * as T from './types'; import { UISlices, UIThunks } from '../ui'; import { aggregateMetadataFields, groupEdgesForImportation, groupEdgesWithConfiguration, } from './processors/group-edges'; import { FileUploadSlices, SingleFileForms, TFileContent, } from '../import/fileUpload'; type ImportAccessors = T.Accessors | null; const processResponse = ( dispatch: any, accessors: T.Accessors, newData: T.GraphData | T.GraphList, ) => { const graphList: T.GraphList = Array.isArray(newData) ? newData : [newData]; const modifiedGraphList = []; const groupedEdgeGraphList: T.GraphList = graphList.map( (graphData: T.GraphData) => { if (graphData.metadata.groupEdges.toggle) { const { graphData: groupedEdgeData, groupEdgeIds } = groupEdgesForImportation(graphData, graphData.metadata.groupEdges); const modData = cloneDeep(graphData); modData.metadata.groupEdges.ids = groupEdgeIds; modifiedGraphList.push(modData); return groupedEdgeData; } modifiedGraphList.push(graphData); return graphData; }, ); dispatch(GraphSlices.addQuery(modifiedGraphList)); const mergedGraph = combineGraphs(groupedEdgeGraphList); // combine new graph data with existing graph data to form graph flattens. dispatch(GraphSlices.processGraphResponse({ data: mergedGraph, accessors })); }; /** * Display Toast Notification based on Filter Options' presence. * 1. Filter Option is not empty, display warning toast. * 2. Filter Option is empty, display success toast. * * @param {any} dispatch * @param {FilterOptions} filterOptions * * @return {void} */ const showImportDataToast = ( dispatch: any, filterOptions: T.FilterOptions, ): void => { const isFilterEmpty: boolean = isEmpty(filterOptions); if (isFilterEmpty) { dispatch(UIThunks.show('Data imported successfully', 'positive')); return; } dispatch(UIThunks.show('Data imported with filters applied', 'warning')); }; /** * Thunk to add data to graph - processes CSV and add to graphList * * @param {ImportFormat[]} importData - array of graphData objects * @param groupEdges - determine whether should group the edges. * @param {ImportAccessors} importAccessors = null * @param {string} metadataKey = null * * @return void */ export const importEdgeListData = ( importData: T.EdgeListCsv[], groupEdges = true, importAccessors: ImportAccessors = null, metadataKey: string = null, ) => (dispatch: any, getState: any) => { const { accessors: mainAccessors } = getGraph(getState()); const accessors = { ...mainAccessors, ...importAccessors }; const filterOptions: T.FilterOptions = getFilterOptions(getState()); const batchDataPromises = importData.map((graphData: T.EdgeListCsv) => { return importEdgeListCsv(graphData, accessors, groupEdges, metadataKey); }); return Promise.all(batchDataPromises) .then((graphData: T.GraphList) => { dispatch(UISlices.fetchBegin()); setTimeout(() => { processResponse(dispatch, mainAccessors, graphData); showImportDataToast(dispatch, filterOptions); dispatch(FileUploadSlices.resetState()); dispatch(UISlices.clearError()); dispatch(UISlices.fetchDone()); dispatch(UISlices.closeModal()); }, 50); }) .catch((err: Error) => { dispatch(UISlices.displayError(err)); dispatch(UISlices.fetchDone()); }); }; /** * * Thunk to add data to graph - processes JSON and add to graphList * 1. apply the latest style options in the import file. * 2. changing layout must occurs before load graph's data * 3. allow original graphin format to import for backward compatibility * * @param {ImportFormat[]} importData - array of graphData objects * @param {boolean} groupEdges - decides whether graph's edges shall be grouped. * @param {ImportAccessors} importAccessors [importAccessors=null] to customize node Id / edge Id / edge source or target * @param {boolean} overwriteStyles - overwrite the existing graph styles * * @return Promise */ export const importJsonData = ( importData: T.JsonImport[], groupEdges = true, importAccessors: Partial<ImportAccessors> = {}, overwriteStyles = false, ) => (dispatch: any, getState: any) => { const isCustomAccessorEmpty = isEmpty(importAccessors); const { accessors: mainAccessors } = getGraph(getState()); const accessors = isCustomAccessorEmpty ? mainAccessors : (importAccessors as ImportAccessors); let filterOptions: T.FilterOptions = getFilterOptions(getState()); let styleOptions: T.StyleOptions = getStyleOptions(getState()); let isDataPossessStyle = false; let isDataPossessFilter = false; const batchDataPromises = importData.map((graphData: T.JsonImport) => { const { data: dataWithStyle } = graphData as T.TLoadFormat; if (dataWithStyle) { const { style: importStyleOption, filter: importFilterOption } = graphData as T.TLoadFormat; if (importStyleOption) { isDataPossessStyle = true; styleOptions = importStyleOption; } if (importFilterOption) { isDataPossessFilter = true; filterOptions = importFilterOption; } return importJson(dataWithStyle as T.GraphList, accessors, groupEdges); } return importJson( graphData as T.GraphList | T.GraphData, accessors, groupEdges, ); }); return Promise.all(batchDataPromises) .then((graphDataArr: T.GraphList[]) => { dispatch(UISlices.fetchBegin()); setTimeout(() => { const graphData: T.GraphList = flatten(graphDataArr); if (isDataPossessStyle && overwriteStyles) { dispatch(GraphSlices.updateStyleOption(styleOptions)); } if (isDataPossessFilter) { dispatch(GraphSlices.updateFilterOption(filterOptions)); } processResponse(dispatch, accessors, graphData); showImportDataToast(dispatch, filterOptions); dispatch(FileUploadSlices.resetState()); dispatch(UISlices.clearError()); dispatch(UISlices.fetchDone()); dispatch(UISlices.closeModal()); }, 50); }) .catch((err: any) => { dispatch(UISlices.displayError(err)); dispatch(UISlices.fetchDone()); }); }; /** * Thunk to add data to graph - processed CSV with node and edge and add to graph List * * @param {SingleFileForms} importData - attachment contains one or more node edge attachments * @param {boolean} groupEdges - group graph's edges * @param {Partial<ImportAccessors>} importAccessors [importAccessors={}] - to customize node Id / edge Id / edge source or target * @param {number} metadataKey [metadataKey=null] * @return {Promise<GraphData>} */ export const importNodeEdgeData = ( importData: SingleFileForms, groupEdges = true, importAccessors: Partial<ImportAccessors> = {}, metadataKey: string = null, ) => (dispatch: any, getState: any) => { const { accessors: mainAccessors } = getGraph(getState()); const accessors = isEmpty(importAccessors) ? mainAccessors : (importAccessors as ImportAccessors); const filterOptions: T.FilterOptions = getFilterOptions(getState()); const { nodeCsv: nodeContents, edgeCsv: edgeContents } = importData; const nodeCsvs: string[] = nodeContents.map( (nodeCsv: TFileContent) => nodeCsv.content as string, ); const edgeCsvs: string[] = edgeContents.map( (edgeCsv: TFileContent) => edgeCsv.content as string, ); const newData: Promise<T.GraphData> = importNodeEdgeCsv( nodeCsvs, edgeCsvs, accessors, groupEdges, metadataKey, ); return newData .then((graphData: T.GraphData) => { dispatch(UISlices.fetchBegin()); setTimeout(() => { processResponse(dispatch, accessors, graphData); showImportDataToast(dispatch, filterOptions); dispatch(FileUploadSlices.resetState()); dispatch(UISlices.fetchDone()); dispatch(UISlices.closeModal()); }, 50); }) .catch((err: any) => { dispatch(UISlices.displayError(err)); dispatch(UISlices.fetchDone()); }); }; /** * Thunk to add sample data into graph * * @param {JsonImport} importData * @param {boolean} groupEdges [groupEdges=true] - group graph's edges * @param {Partial<ImportAccessors>} importAccessors [importAccessors={}] - to customize node Id / edge Id / edge source or target */ export const importSampleData = ( importData: T.JsonImport, importAccessors: Partial<ImportAccessors> = {}, groupEdges = false, ) => async (dispatch: any, getState: any): Promise<void> => { const { accessors: mainAccessors } = getGraph(getState()); const accessors = isEmpty(importAccessors) ? mainAccessors : (importAccessors as ImportAccessors); const filterOptions: T.FilterOptions = getFilterOptions(getState()); const newData: Promise<T.GraphList> = importJson( importData as T.GraphData, accessors, groupEdges, ); return newData .then((graphData: T.GraphList) => { dispatch(UISlices.fetchBegin()); setTimeout(() => { processResponse(dispatch, accessors, graphData); showImportDataToast(dispatch, filterOptions); dispatch(FileUploadSlices.resetState()); dispatch(UISlices.clearError()); dispatch(UISlices.fetchDone()); dispatch(UISlices.closeModal()); }, 50); }) .catch((err: Error) => { const { message } = err; dispatch(UIThunks.show(message, 'negative')); dispatch(UISlices.fetchDone()); }); }; /** * Perform group edges based on preferences and graph edge configurations. * * @param {number} graphIndex - identify specific graph list to perform edge aggregations * @return {void} */ export const groupEdgesWithAggregation = (graphIndex: number) => (dispatch: any, getState: any) => { const { graphList, graphFlatten }: T.GraphState = getGraph(getState()); const selectedGraphList: T.GraphData = graphList[graphIndex]; const { groupEdges } = selectedGraphList.metadata; const { graphData: newGraphData, groupEdgeIds } = groupEdgesWithConfiguration(selectedGraphList, graphFlatten, groupEdges); // obtain the combined aggregated edge fields of entire graph. const combinedAggregatedEdgeFields: T.Field[][] = graphList.reduce( (acc: T.Field[][], graphData: T.GraphData) => { const { metadata } = graphData; const edgeAggregateFields: T.Field[] = aggregateMetadataFields( graphData, metadata.groupEdges.fields, ); const combinedEdgeField = uniqBy( [...metadata.fields.edges, ...edgeAggregateFields], 'name', ) as T.Field[]; acc.push(combinedEdgeField); return acc; }, [], ); // map the aggregated edge fields as edge selections const flattenEdgeFields: T.Field[] = flatten(combinedAggregatedEdgeFields); const uniqueEdgeFields = uniqBy(flattenEdgeFields, 'name') as T.Field[]; const modData = cloneDeep(newGraphData); Object.assign(modData.metadata.fields, { edges: uniqueEdgeFields, }); dispatch(GraphSlices.updateGraphFlatten(modData)); dispatch(GraphSlices.updateGroupEdgeIds({ graphIndex, groupEdgeIds })); }; /** * Update edge selections based on group edge configurations. * * @return {void} */ export const computeEdgeSelection = () => (dispatch: any, getState: any): void => { const { graphFlatten, edgeSelection }: T.GraphState = getGraph(getState()); const { edges: edgeFields } = graphFlatten.metadata.fields; const computedEdgeSelection: T.Selection[] = edgeFields.map( (edgeField: T.Field) => { const { name, type } = edgeField; const existingSelection = edgeSelection.find( (selection: T.Selection) => selection.id === edgeField.name, ); const isSelected: boolean = existingSelection?.selected ?? false; return { id: name, label: name, type, selected: isSelected, }; }, ); dispatch(GraphSlices.overwriteEdgeSelection(computedEdgeSelection)); };
the_stack
import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, ViewChild, } from '@angular/core'; import { debounceTime } from 'rxjs/operators'; @Component({ selector: 'amexio-availability', templateUrl: './availability.component.html', }) export class AvailabilityComponent implements OnInit, AfterViewInit, OnChanges { @Input('start-date') startDate: string; @Input('end-date') endDate: string; @Input('start-time') startTime: number; @Input('end-time') endTime: number; @Input('time-zone-data') zoneData: any; @Input('undo-button') undoFlag = false; @Input('enable-drag') enableDrag = true; _labelData: any; @Input('label-data') set labelData(value: any[]) { this._labelData = value; } get labelData(): any[] { return this._labelData; } @Input('default-radio') defaultRadio = ''; @Input('no-change') nocellchange = false; @ViewChild('datesdiv') elementView: ElementRef; @ViewChild('datesseconddiv') elementView1: ElementRef; @ViewChild('datesfirstdiv') elementView2: ElementRef; @Output() onClick: any = new EventEmitter<any>(); @Output() onRadioClick: any = new EventEmitter<any>(); @Output('onUndoClick') UndoBtnClick: any = new EventEmitter<any>(); @Output('onDragStart') onDragStartEvent: any = new EventEmitter<any>(); @Output('onDragOver') onDragOverEvent: any = new EventEmitter<any>(); @Output('onDragEnd') onDragEndEvent: any = new EventEmitter<any>(); radioValue = ''; selectedIndexArr: any[]; styleVar: any; completeNewArr: any[]; datesArrlen = 0; slotTimeArr: any[]; sDate = new Date(); eDate = new Date(); dateArr: any[]; dateArr1: any[]; completeTimeArr: any[]; dateSpanHt = 18; dateSpanWt = 46; dateSpanlist: any[]; legendArr: any[]; dragStartObj: any; dragEndObj: any = {}; dragFlag = false; legendObj = {}; newTimeArr: any[]; minIndex: number; maxIndex: number; count = 0; newTimeArr2: any = []; constructor(public cdf: ChangeDetectorRef) { } ngOnInit() { this.generateData(); if ((this.defaultRadio.length > 0)) { this.radioValue = this.defaultRadio; // this.styleVar will be initialized this.legendArr.forEach((element: any) => { if (element.label === this.defaultRadio) { this.styleVar = element; this.onRadioClick.emit(element); } }); } const tarr: any = []; this.dateArr1[0].slots.forEach((slele: any, sindex: number) => { if (((sindex % 2) === 0) || (sindex === 0)) { tarr.push(slele); } }); let tcnt = 0; const newttarr2: any = []; let prevt; while (tcnt <= tarr.length - 2) { let obj; if (tcnt === 0) { obj = { starttime: tarr[tcnt].starttime, endtime: tarr[tcnt + 1].starttime }; prevt = obj.endtime; newttarr2.push(obj); } else { obj = { starttime: prevt, endtime: tarr[tcnt + 1].starttime }; prevt = obj.endtime; if (!((obj.starttime.getHours() === obj.endtime.getHours()) && (obj.starttime.getMinutes() === obj.endtime.getMinutes()))) { newttarr2.push(obj); } } tcnt = tcnt + 1; } const prevlastobj = newttarr2[newttarr2.length - 1]; const lastendtime = new Date(newttarr2[newttarr2.length - 1].endtime); lastendtime.setHours(lastendtime.getHours() + 1); const lastobj = { starttime: prevlastobj.endtime, endtime: lastendtime }; newttarr2.push(lastobj); this.newTimeArr2 = newttarr2; } updateComponent() { this.generateData(); } ngOnChanges(changes: SimpleChanges) { if (changes['labelData'] && changes.labelData.currentValue) { this.labelData = changes.labelData.currentValue; } } ngOnchanges() { this.dateSpanWt = 37; this.generateData(); } // generate data structure generateData() { this.selectedIndexArr = []; this.completeNewArr = []; this.slotTimeArr = []; this.dateArr = []; this.dateArr1 = []; this.completeTimeArr = []; this.dateSpanlist = []; this.legendArr = []; this.newTimeArr = []; this.sDate = new Date(this.startDate); this.eDate = new Date(this.endDate); let i = 0; this.dateArr = [{ dates: [], timearr: [] }]; this.dateArr1 = []; let d; // if startdate is less than enddate if (this.sDate < this.eDate) { do { d = new Date(this.sDate.getFullYear(), this.sDate.getMonth(), this.sDate.getDate() + i); const dobj = { date: d }; this.dateArr[0].dates.push(dobj); i++; } while (d < this.eDate); } else if (this.sDate === this.eDate) { // if startdate equals enddate d = new Date(this.sDate.getFullYear(), this.sDate.getMonth(), this.sDate.getDate() + i); const dobj = { date: d }; this.dateArr[0].dates.push(dobj); } i = 0; const arr: any = []; this.sDate = new Date(this.startDate); this.eDate = new Date(this.eDate); if (this.sDate < this.eDate) { do { d = new Date(this.sDate.getFullYear(), this.sDate.getMonth(), this.sDate.getDate() + i); const dobj = { date: d, slots: arr }; dobj.slots = this.setSlots1(d); this.dateArr1.push(dobj); i++; } while (d < this.eDate); } else if (this.sDate === this.eDate) { const arry: any = []; d = new Date(this.sDate.getFullYear(), this.sDate.getMonth(), this.sDate.getDate() + i); const dobj = { date: d, slots: arry }; dobj.slots = this.setSlots1(d); this.dateArr1.push(dobj); } this.initializeTimeArr(); this.generateTimeArr(); this.datesArrlen = this.dateArr[0].dates.length; let j; for (j = 0; j < this.datesArrlen; j++) { this.dateSpanlist.push(j); } this.generateLegendArr(); this.generateSlotTimeArr(); } generateSlotTimeArr() { let i = this.startTime; while (i <= this.endTime) { let j = 0; while (j <= 1) { const d = new Date(); d.setHours(i); if (j === 0) { d.setMinutes(0); } if (j === 1) { d.setMinutes(30); } this.newTimeArr.push(d); j++; } i++; } } setSlots1(d: Date) { const slot: any = []; const etime = this.endTime; let i = this.startTime; let j; while (i <= etime) { let previousendtime; for (j = 0; j <= 1; j++) { const obj = {}; let objstarttime = new Date(d); const objendtime = new Date(d); if (j === 0) { objstarttime.setHours(i); objendtime.setHours(i); objstarttime.setMinutes(0); objendtime.setMinutes(30); previousendtime = objendtime; } if (j === 1) { objstarttime = previousendtime; objendtime.setHours(previousendtime.getHours() + 1); objendtime.setMinutes(0); } obj['starttime'] = objstarttime; obj['endtime'] = objendtime; obj['colorflag'] = false; slot.push(obj); } i++; } return this.chkLabels(d, slot); } chkLabels(d: Date, slotArray: any) { const minindex: any = null; const maxindex: any = null; let minflag = false; let maxflag = false; this.labelData.forEach((labelelement: any) => { if (labelelement.available) { labelelement.available.forEach((availableElement: any) => { if (availableElement.date) { let minmaxarr: any = []; const dt = new Date(availableElement.date); let retflagObj: any; if (availableElement.time) { retflagObj = this.availableTimeTest(availableElement, slotArray, dt, d, minmaxarr); minflag = retflagObj.minFlag; maxflag = retflagObj.maxFlag; minmaxarr = retflagObj.minmaxArr; } this.setRange(minflag, maxflag, slotArray, minmaxarr, labelelement); } }); } }); return slotArray; } setRange(minflag: boolean, maxflag: boolean, slotArray: any, minmaxarr: any, labelelement: any) { if (minflag && maxflag) { this.setColorRangeTest(slotArray, minmaxarr, labelelement); } } availableTimeTest(availableElement: any, slotArray: any, dt: Date, d: Date, minmaxarr: any) { let minindex = null; let maxindex = null; let minflag = false; let maxflag = false; availableElement.time.forEach((timeElement: any) => { minindex = null; maxindex = null; minflag = false; maxflag = false; const retminmaxObj = this.chkMinMaxIndexTest(slotArray, dt, d, timeElement); minflag = retminmaxObj.minFlag; maxflag = retminmaxObj.maxFlag; minindex = retminmaxObj.minIndex; maxindex = retminmaxObj.maxIndex; if (minflag && maxflag) { const minmaxobj = { minIndex: minindex, maxIndex: maxindex }; minmaxarr.push(minmaxobj); } }); return { minFlag: minflag, maxFlag: maxflag, minmaxArr: minmaxarr }; } setColorRangeTest(slotArray: any, minmaxarr: any, labelelement: any) { slotArray.forEach((individualSlot: any, slotindex: any) => { minmaxarr.forEach((minmaxrange: any) => { if ((slotindex >= minmaxrange.minIndex) && (slotindex <= minmaxrange.maxIndex)) { if (individualSlot.label) { individualSlot.label = labelelement.label; individualSlot['color'] = labelelement.colorcode; individualSlot.colorflag = true; } else { individualSlot['label'] = labelelement.label; individualSlot['color'] = labelelement.colorcode; individualSlot.colorflag = true; } } }); }); } chkMinMaxIndexTest(slotArray: any, dt: Date, d: Date, timeElement: any) { let minindex: any = null; let maxindex: any = null; let minflag = false; let maxflag = false; slotArray.forEach((slotElement: any, slotIndex: number) => { if ( (dt.getFullYear() === d.getFullYear()) && (dt.getMonth() === d.getMonth()) && (dt.getDate() === d.getDate())) { // u hav to modify ur condns here const starttimeobj = this.getHourMinuteFormat(timeElement.starttime); if ( ((starttimeobj.hours === slotElement.starttime.getHours()) && (starttimeobj.minutes === slotElement.starttime.getMinutes())) ) { minindex = slotIndex; minflag = true; } } if ((dt.getFullYear() === d.getFullYear()) && (dt.getMonth() === d.getMonth()) && (dt.getDate() === d.getDate())) { const endtimeobj = this.getHourMinuteFormat(timeElement.endtime); if ((endtimeobj.hours === slotElement.endtime.getHours()) && (endtimeobj.minutes === slotElement.endtime.getMinutes())) { maxindex = slotIndex; maxflag = true; } // start end } }); return { minFlag: minflag, maxFlag: maxflag, minIndex: minindex, maxIndex: maxindex }; } getHourMinuteFormat(usertime: number) { let arr = []; arr = usertime.toString().split('.'); return { hours: parseInt((arr[0]), 10), minutes: arr[1] ? (parseInt((arr[1]), 10) * 10) : 0 }; } ngAfterViewInit() { let divHt; let divWt; divHt = this.elementView.nativeElement.offsetHeight; divWt = this.elementView1.nativeElement.offsetWidth; this.dateSpanHt = Math.round(divHt / this.datesArrlen); this.dateSpanWt = Math.round((divWt) / this.newTimeArr.length); this.dateSpanWt = 37; } generateLegendArr() { this.labelData.forEach((element: any) => { this.legendObj[element.label] = false; }); this.labelData.forEach((element: any) => { const obj = { label: element.label, colorcode: element.colorcode, textcolor: element.textcolor ? element.textcolor : 'black' }; this.legendArr.push(obj); }); this.count++; } alterNoChangeFlag() { this.nocellchange = true; } negateNoChangeFlag() { this.nocellchange = false; } initializeTimeArr() { this.completeTimeArr = ['12am', '1am', '2am', '3am', '4am', '5am', '6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm', '9pm', '10pm', '11pm', ]; } generateTimeArr() { let startindex; let endindex; this.completeTimeArr.forEach((element: any, index: number) => { if (element === this.startTime) { startindex = index; } if (element === this.endTime) { endindex = index; } }); this.setTimeArr(startindex, endindex); } setTimeArr(startindex: number, endindex: number) { const tarr: any = []; this.completeTimeArr.forEach((element: any, index: number) => { if ((index >= startindex) && (index <= endindex)) { const tobj = { time: element }; tarr.push(tobj); } }); this.dateArr[0].timearr = tarr; } onSelection(radioData: any) { this.styleVar = ''; const obj = { label: radioData.label, colorcode: radioData.colorcode }; this.styleVar = obj; this.onRadioClick.emit(obj); } clearColorFlag() { this.dateArr1.forEach((element: any) => { if (element.slots) { element.slots.forEach((individualSlot: any) => { individualSlot.colorflag = false; }); } }); } timeBlockWithoutUndo(parentiterateitem: any, parentindex: any, childiterateitem: any, childindex: any) { const flag = false; if (this.radioValue.length > 0) { if ((this.dateArr1[parentindex].slots[childindex].colorflag)) { } else { const newobj = this.dateArr1[parentindex].slots[childindex]; newobj['label'] = this.styleVar.label; newobj['color'] = this.styleVar.colorcode; newobj.colorflag = true; this.dateArr1[parentindex].slots[childindex] = newobj; } } this.onClick.emit({ time: this.dateArr1[parentindex].slots[childindex].time, label: this.dateArr1[parentindex].slots[childindex].label, }); this.generateData(); } timeBlockWithUndo(parentiterateitem: any, parentindex: any, childiterateitem: any, childindex: any) { const flag = false; if (this.radioValue.length > 0) { if ((this.dateArr1[parentindex].slots[childindex].label)) { // overriding logic wrks fr false // overiding logic starts here if (this.dateArr1[parentindex].slots[childindex].label === this.styleVar.label) { // unselect logic // label exist and same label const newobj = { time: this.dateArr1[parentindex].slots[childindex].time, colorflag: false, }; // assignment this.dateArr1[parentindex].slots[childindex] = newobj; // blank } else { // label exist and diff label // blank const newobj2 = { time: this.dateArr1[parentindex].slots[childindex].time, colorflag: false, }; this.dateArr1[parentindex].slots[childindex] = newobj2; } // overiding logic ends here } } this.onClick.emit({ time: this.dateArr1[parentindex].slots[childindex].time, label: this.dateArr1[parentindex].slots[childindex].label, }); this.generateData(); } onTimeBlockClick(parentiterateitem: any, parentindex: any, childiterateitem: any, childindex: any) { this.onClick.emit({ starttime: this.dateArr1[parentindex].slots[childindex].starttime, endtime: this.dateArr1[parentindex].slots[childindex].endtime, label: this.dateArr1[parentindex].slots[childindex].label ? this.dateArr1[parentindex].slots[childindex].label : 'not selected', }); this.generateData(); } onUndoClick() { this.UndoBtnClick.emit(''); this.generateData(); } onDragStart(event: any, iterate: any, parentindex: any, item: any, childindex: any) { debounceTime(1000); const img = document.createElement('img'); event.dataTransfer.setDragImage(img, 0, 0); this.dragFlag = true; this.dragStartObj = { dateObj: iterate, dragparentindex: parentindex, dragcell: item, dragchildindex: childindex, }; this.onDragStartEvent.emit({ starttime: this.dateArr1[parentindex].slots[childindex].starttime, endtime: this.dateArr1[parentindex].slots[childindex].endtime, label: this.dateArr1[parentindex].slots[childindex].label ? this.dateArr1[parentindex].slots[childindex].label : null, }); } ondragover(event: any, iterate: any, parentindex: any, item: any, childindex: any) { debounceTime(1000); this.onDragOverEvent.emit({ starttime: this.dateArr1[parentindex].slots[childindex].starttime, endtime: this.dateArr1[parentindex].slots[childindex].endtime, label: this.dateArr1[parentindex].slots[childindex].label ? this.dateArr1[parentindex].slots[childindex].label : null, }); this.generateData(); this.dragEndObj = { iterate1: iterate, parentindex1: parentindex, item1: item, childindex1: childindex, }; } onDragEnd(event: any, iterate: any, parentindex: any, item: any, childindex: any) { debounceTime(1000); this.onDragEndEvent.emit(''); this.generateData(); } }
the_stack
import {Component, OnInit} from '@angular/core'; import {AlertEnum} from '../../../common/alert-enum.enum'; import {BsModalRef, BsModalService} from 'ngx-bootstrap'; import {RoleVO} from '../../../pojo/RoleVO'; import {RoleService} from '../../../service/role.service'; @Component({ selector: 'app-role-manage', templateUrl: './role-manage.component.html', styleUrls: ['./role-manage.component.css'] }) export class RoleManageComponent implements OnInit { bsModalRef: BsModalRef; // app-alert info alert: AlertEnum = AlertEnum.DANGER; msg: string = '默认提示信息'; // app-content-header info firstName: string = '资源管理'; secondName: string = '角色管理'; detail: string = '角色关联维护'; // modal-page分页 modalPageSize: number = 10; modalTotalItems: number; modalCurrentPage: number = 1; modalSelected: number = 1; // 1 api 2 menu 3 user // ----api---- selectedRoleApi: any; apis: any[]; // api-pagination info apiPageSize: number = 10; apiTotalItems: number; apiCurrentPage: number = 1; // api-modal info modalApis: any[]; modalSelectedApi: any; // ----menu---- selectedRoleMenu: any; menus: any[]; // menu-pagination info menuPageSize: number = 10; menuTotalItems: number; menuCurrentPage: number = 1; // menu-modal info modalMenus: any[]; modalSelectedMenu: any; // ----user---- selectedRoleUser: any; users: any[]; // user-pagination info userPageSize: number = 10; userTotalItems: number; userCurrentPage: number = 1; // user-modal info modalUsers: any[]; modalSelectedUser: any; // ----role---- roles: any[]; selectedRole: any; selectedLinkName: string = '选择角色关联模块'; // role-modal-template info role: RoleVO = new RoleVO(); modalFlag: number = 1; roleModalName: string = '添加角色'; // role-pagination info rolePageSize: number = 10; roleTotalItems: number; roleCurrentPage: number = 1; constructor(private modalService: BsModalService, private roleService: RoleService) { } ngOnInit() { const role$ = this.roleService.getRoles(this.roleCurrentPage, this.rolePageSize).subscribe( data => { if (data.meta.code === 6666) { this.roles = data.data.data.list; this.roleTotalItems = data.data.data.total; } else if (data.meta.code === 1008) { this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '查询失败'; } role$.unsubscribe(); } ); } // ---------------role----------------------- selectLinkName(linkName: string) { this.selectedLinkName = linkName; } selectRole(role: any) { this.selectedRole = role; if (this.selectedLinkName != null && this.selectedLinkName !== undefined && this.selectedRole.id) { if (this.selectedLinkName === '授权API') { this.getRoleApis(this.selectedRole.id, this.apiCurrentPage, this.apiPageSize); } if (this.selectedLinkName === '授权菜单') { this.getRoleMenus(this.selectedRole.id, this.menuCurrentPage, this.menuPageSize); } if (this.selectedLinkName === '关联用户') { this.getRoleUsers(this.selectedRole.id, this.userCurrentPage, this.userPageSize); } } } addRole(template: any) { this.modalFlag = 1; this.roleModalName = '添加角色'; this.role = new RoleVO(); this.bsModalRef = this.modalService.show(template); } editRole(template: any) { if (this.selectedRole === null || this.selectedRole === undefined) { this.msg = '请选择角色'; return; } else { this.roleModalName = '修改角色'; this.modalFlag = 2; this.role = this.selectedRole; this.bsModalRef = this.modalService.show(template); } } deleteRole() { if (this.selectedRole === null || this.selectedRole === undefined || !this.selectedRole.id) { this.msg = '请选择角色'; return; } else { if (!confirm('确认删除?')) { return; } const deleteRole$ = this.roleService.deleteRole(this.selectedRole.id).subscribe( data => { if (data.meta.code === 6666) { this.msg = '删除成功'; deleteRole$.unsubscribe(); this.ngOnInit(); } else if (data.meta.code === 1008) { deleteRole$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { deleteRole$.unsubscribe(); this.msg = '删除失败'; } } ); } } submitRoleModal() { this.bsModalRef.hide(); if (!this.check(this.role)) { return; } // 1 add if (this.modalFlag === 1) { const addRole$ = this.roleService.addRole(this.role).subscribe( data => { if (data.meta.code === 6666) { this.msg = '添加成功'; addRole$.unsubscribe(); this.ngOnInit(); } else if (data.meta.code === 1008) { addRole$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '添加失败'; addRole$.unsubscribe(); } } ); } // 2 update if (this.modalFlag === 2) { const updateRole$ = this.roleService.updateRole(this.role).subscribe( data => { if (data.meta.code === 6666) { this.msg = '修改成功'; updateRole$.unsubscribe(); this.ngOnInit(); } else if (data.meta.code === 1008) { updateRole$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '修改失败'; updateRole$.unsubscribe(); } } ); } } rolePageChanged(event: any) { this.roleCurrentPage = event.page; this.ngOnInit(); } check(role: RoleVO) { if (!role.code) { this.msg = '编码不能为空'; return false; } else if (!role.name) { this.msg = '名称不能为空'; return false; } else if (!role.status) { this.msg = '请选择状态'; return false; } return true; } // ----------------api--------------------- getRoleApis(roleId: number, currentPage: number, pageSize: number) { const roleApi$ = this.roleService.getApiByRoleId(roleId, currentPage, pageSize).subscribe( data => { if (data.meta.code === 6666) { this.apis = data.data.data.list; this.apiTotalItems = data.data.data.total; roleApi$.unsubscribe(); } else if (data.meta.code === 1008) { roleApi$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '获取失败'; roleApi$.unsubscribe(); } } ); } getRoleExtendApis(roleId: number, currentPage: number, pageSize: number) { const roleApi$ = this.roleService.getApiExtendByRoleId(roleId, currentPage, pageSize).subscribe( data => { if (data.meta.code === 6666) { this.modalApis = data.data.data.list; this.modalTotalItems = data.data.data.total; roleApi$.unsubscribe(); } else if (data.meta.code === 1008) { roleApi$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '获取失败'; roleApi$.unsubscribe(); } } ); } selectRoleApi(selectItem: any) { this.selectedRoleApi = selectItem; } selectModalRoleApi(selectItem: any) { this.modalSelectedApi = selectItem; } addRoleApi(template: any) { if (!this.selectedRole) { this.msg = '请选择对应角色'; return; } this.getRoleExtendApis(this.selectedRole.id, this.modalCurrentPage, this.modalPageSize); this.modalSelected = 1; this.bsModalRef = this.modalService.show(template); } deleteRoleApi() { if (this.selectedRoleApi == null || this.selectedRoleApi === undefined) { this.msg = '请选择API'; return; } else { if (!confirm('确认删除?')) { return; } const deleteApi$ = this.roleService.deleteRoleAuthorityApi(this.selectedRole.id, this.selectedRoleApi.id).subscribe( data => { if (data.meta.code === 6666) { this.msg = '删除成功'; deleteApi$.unsubscribe(); this.getRoleApis(this.selectedRole.id, this.apiCurrentPage, this.apiPageSize); } else if (data.meta.code === 1008) { deleteApi$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '删除失败'; } } ); } } apiPageChanged(event: any) { this.apiCurrentPage = event.page; this.getRoleApis(this.selectedRole.id, this.apiCurrentPage, this.apiPageSize); } // ----------------------menu------------------------- getRoleMenus(roleId: number, currentPage: number, pageSize: number) { const roleMenu$ = this.roleService.getMenuByRoleId(roleId, currentPage, pageSize).subscribe( data => { if (data.meta.code === 6666) { this.menus = data.data.data.list; this.menuTotalItems = data.data.data.total; roleMenu$.unsubscribe(); } else if (data.meta.code === 1008) { roleMenu$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '获取失败'; roleMenu$.unsubscribe(); } } ); } getRoleExtendMenus(roleId: number, currentPage: number, pageSize: number) { const roleMenu$ = this.roleService.getMenuExtendByRoleId(roleId, currentPage, pageSize).subscribe( data => { if (data.meta.code === 6666) { this.modalMenus = data.data.data.list; this.modalTotalItems = data.data.data.total; roleMenu$.unsubscribe(); } else if (data.meta.code === 1008) { roleMenu$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '获取失败'; roleMenu$.unsubscribe(); } } ); } selectRoleMenu(selectItem: any) { this.selectedRoleMenu = selectItem; } selectModalRoleMenu(selectItem: any) { this.modalSelectedMenu = selectItem; } addRoleMenu(template: any) { if (!this.selectedRole) { this.msg = '请选择对应角色'; return; } this.getRoleExtendMenus(this.selectedRole.id, this.modalCurrentPage, this.modalPageSize); this.modalSelected = 2; this.bsModalRef = this.modalService.show(template); } deleteRoleMenu() { if (this.selectedRoleMenu == null || this.selectedRoleMenu === undefined) { this.msg = '请选择菜单'; return; } else { if (!confirm('确认删除?')) { return; } const deleteMenu$ = this.roleService.deleteRoleAuthorityMenu(this.selectedRole.id, this.selectedRoleMenu.id).subscribe( data => { if (data.meta.code === 6666) { this.msg = '删除成功'; deleteMenu$.unsubscribe(); this.getRoleMenus(this.selectedRole.id, this.menuCurrentPage, this.menuPageSize); } else if (data.meta.code === 1008) { deleteMenu$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { deleteMenu$.unsubscribe(); this.msg = '删除失败'; } } ); } } menuPageChanged(event: any) { this.menuCurrentPage = event.page; this.getRoleMenus(this.selectedRole.id, this.menuCurrentPage, this.menuPageSize); } // ----------------------user-------------------- getRoleUsers(roleId: number, currentPage: number, pageSize: number) { const roleUser$ = this.roleService.getUserByRoleId(roleId, currentPage, pageSize).subscribe( data => { if (data.meta.code === 6666) { this.users = data.data.data.list; this.userTotalItems = data.data.data.total; roleUser$.unsubscribe(); } else if (data.meta.code === 1008) { roleUser$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '获取失败'; roleUser$.unsubscribe(); } } ); } getRoleExtendUsers(roleId: number, currentPage: number, pageSize: number) { const roleUser$ = this.roleService.getUserExtendByRoleId(roleId, currentPage, pageSize).subscribe( data => { if (data.meta.code === 6666) { this.modalUsers = data.data.data.list; this.modalTotalItems = data.data.data.total; roleUser$.unsubscribe(); } else if (data.meta.code === 1008) { roleUser$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '获取失败'; roleUser$.unsubscribe(); } } ); } selectRoleUser(selectItem: any) { this.selectedRoleUser = selectItem; } selectModalRoleUser(selectItem: any) { this.modalSelectedUser = selectItem; } addRoleUser(template: any) { if (!this.selectedRole) { this.msg = '请选择对应角色'; return; } this.getRoleExtendUsers(this.selectedRole.id, this.modalCurrentPage, this.modalPageSize); this.modalSelected = 3; this.bsModalRef = this.modalService.show(template); } deleteRoleUser() { if (this.selectedRoleUser == null || this.selectedRoleUser === undefined) { this.msg = '请选择用户'; return; } else { if (!confirm('确认删除?')) { return; } const deleteUser$ = this.roleService.deleteUserAuthorityRole(this.selectedRoleUser.uid, this.selectedRole.id).subscribe( data => { if (data.meta.code === 6666) { this.msg = '删除成功'; deleteUser$.unsubscribe(); this.getRoleUsers(this.selectedRole.id, this.userCurrentPage, this.userPageSize); } else if (data.meta.code === 1008) { deleteUser$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '删除失败'; deleteUser$.unsubscribe(); } } ); } } userPageChanged(event: any) { this.userCurrentPage = event.page; this.getRoleUsers(this.selectedRole.id, this.userCurrentPage, this.userPageSize); } // --------------modal------------------ submitAddModal() { this.bsModalRef.hide(); // api add if (this.modalSelected === 1) { if (!this.modalSelectedApi) { this.msg = '请选择要添加的API'; return; } const addApi$ = this.roleService.roleAuthorityApi(this.selectedRole.id, this.modalSelectedApi.id).subscribe( data => { if (data.meta.code === 6666) { this.msg = '授权添加成功'; this.getRoleApis(this.selectedRole.id, this.apiCurrentPage, this.apiPageSize); addApi$.unsubscribe(); } else if (data.meta.code === 1008) { addApi$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '授权添加失败'; addApi$.unsubscribe(); } } ); } // menu add if (this.modalSelected === 2) { if (!this.modalSelectedMenu) { this.msg = '请选择要添加的菜单'; return; } const addMenu$ = this.roleService.roleAuthorityMenu(this.selectedRole.id, this.modalSelectedMenu.id).subscribe( data => { if (data.meta.code === 6666) { this.msg = '授权添加成功'; this.getRoleMenus(this.selectedRole.id, this.menuCurrentPage, this.menuPageSize); addMenu$.unsubscribe(); } else if (data.meta.code === 1008) { addMenu$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '授权添加失败'; addMenu$.unsubscribe(); } } ); } // user add if (this.modalSelected === 3) { if (!this.modalSelectedUser) { this.msg = '请选择要添加的用户'; return; } const addUser$ = this.roleService.userAuthorityRole(this.modalSelectedUser.uid, this.selectedRole.id).subscribe( data => { if (data.meta.code === 6666) { this.msg = '授权添加成功'; this.getRoleUsers(this.selectedRole.id, this.userCurrentPage, this.userPageSize); addUser$.unsubscribe(); } else if (data.meta.code === 1008) { addUser$.unsubscribe(); this.alert = AlertEnum.DANGER; this.msg = '您无此api权限'; } else { this.msg = '授权添加失败'; addUser$.unsubscribe(); } } ); } } modalPageChanged(event: any) { this.modalCurrentPage = event.page; switch (this.modalSelected) { case 1 : this.getRoleExtendApis(this.selectedRole.id, this.modalCurrentPage, this.modalPageSize); break; case 2 : this.getRoleExtendMenus(this.selectedRole.id, this.modalCurrentPage, this.modalPageSize); break; case 3 : this.getRoleExtendUsers(this.selectedRole.id, this.modalCurrentPage, this.modalPageSize); break; default : break; } } // ----------alert---------------- reloadAlertMsg(msg_: string) { this.msg = msg_; } }
the_stack
import GPUHelper from '../common/GPUHelper'; import Convolution1D from './Convolution1D'; import { performance } from 'perf_hooks'; import { Axis, FileParams } from '../common/types'; import { makeG0Kernel, makeG1Kernel, makeG2Kernel } from '../common/kernels'; import { unlinkSync } from 'fs'; import { logTime } from '../common/utils'; export default function run( gpuHelper: GPUHelper, fileParams: FileParams, params: Readonly<{ GAUSS_KERNEL_SIGMA: number, NORMAL_RELAX_GAUSS_SCALE: number, }>, ) { const startTime = performance.now(); const { GAUSS_KERNEL_SIGMA, NORMAL_RELAX_GAUSS_SCALE, } = params; const convolution1D = new Convolution1D(gpuHelper); const G0_KERNEL = makeG0Kernel(GAUSS_KERNEL_SIGMA); const G1_KERNEL = makeG1Kernel(GAUSS_KERNEL_SIGMA); const G2_KERNEL = makeG2Kernel(GAUSS_KERNEL_SIGMA); const G0_KERNEL_3X = makeG0Kernel(GAUSS_KERNEL_SIGMA * NORMAL_RELAX_GAUSS_SCALE); const G1_KERNEL_3X = makeG1Kernel(GAUSS_KERNEL_SIGMA * NORMAL_RELAX_GAUSS_SCALE); const G2_KERNEL_3X = makeG2Kernel(GAUSS_KERNEL_SIGMA * NORMAL_RELAX_GAUSS_SCALE); // Load original (unclipped) tom data as input. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_raw`, gpuHelper); // Do convolutions along z. convolution1D.convolve1D(Axis.Z, G0_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussZ`); convolution1D.convolve1D(Axis.Z, G1_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_dGaussZ`); convolution1D.convolve1D(Axis.Z, G2_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_ddGaussZ`); // Convolve Gz with derivs of y. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussZ`, gpuHelper); convolution1D.convolve1D(Axis.Y, G0_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussYgaussZ`); convolution1D.convolve1D(Axis.Y, G1_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_dGaussYgaussZ`); convolution1D.convolve1D(Axis.Y, G2_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_ddGaussYgaussZ`); // Convolve dGz with derivs of y. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_dGaussZ`, gpuHelper); convolution1D.convolve1D(Axis.Y, G0_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussYdGaussZ`); convolution1D.convolve1D(Axis.Y, G1_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_dGaussYdGaussZ`); // Convolve ddGz with derivs of y. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_ddGaussZ`, gpuHelper); convolution1D.convolve1D(Axis.Y, G0_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussYddGaussZ`); // Convolve GzGy with derivs of x. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussYgaussZ`, gpuHelper); convolution1D.convolve1D(Axis.X, G1_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GX`); convolution1D.convolve1D(Axis.X, G2_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GXX`); // Convolve dGzGy with derivs of x. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussYdGaussZ`, gpuHelper); convolution1D.convolve1D(Axis.X, G0_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GZ`); convolution1D.convolve1D(Axis.X, G1_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GXZ`); // Convolve GzdGy with derivs of x. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_dGaussYgaussZ`, gpuHelper); convolution1D.convolve1D(Axis.X, G0_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GY`); convolution1D.convolve1D(Axis.X, G1_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GXY`); // Convolve dGzdGy with derivs of x. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_dGaussYdGaussZ`, gpuHelper); convolution1D.convolve1D(Axis.X, G0_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GYZ`); // Convolve ddGzGy with derivs of x. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussYddGaussZ`, gpuHelper); convolution1D.convolve1D(Axis.X, G0_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GZZ`); // Convolve GzddGy with derivs of x. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_ddGaussYgaussZ`, gpuHelper); convolution1D.convolve1D(Axis.X, G0_KERNEL, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GYY`); // Delete temp files. unlinkSync(fileParams.OUTPUT_PATH + `${fileParams.FILENAME}_gaussZ.tom`); unlinkSync(fileParams.OUTPUT_PATH + `${fileParams.FILENAME}_dGaussZ.tom`); unlinkSync(fileParams.OUTPUT_PATH + `${fileParams.FILENAME}_ddGaussZ.tom`); unlinkSync(fileParams.OUTPUT_PATH + `${fileParams.FILENAME}_gaussYgaussZ.tom`); unlinkSync(fileParams.OUTPUT_PATH + `${fileParams.FILENAME}_dGaussYgaussZ.tom`); unlinkSync(fileParams.OUTPUT_PATH + `${fileParams.FILENAME}_ddGaussYgaussZ.tom`); unlinkSync(fileParams.OUTPUT_PATH + `${fileParams.FILENAME}_gaussYdGaussZ.tom`); unlinkSync(fileParams.OUTPUT_PATH + `${fileParams.FILENAME}_dGaussYdGaussZ.tom`); unlinkSync(fileParams.OUTPUT_PATH + `${fileParams.FILENAME}_gaussYddGaussZ.tom`); // Repeat blur operations, this time at blur kernel scaled to NORMAL_RELAX_GAUSS_SCALE. // Load clipped tom data as input. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_clipped`, gpuHelper); // Do convolutions along z. convolution1D.convolve1D(Axis.Z, G0_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`); convolution1D.convolve1D(Axis.Z, G1_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_dGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`); convolution1D.convolve1D(Axis.Z, G2_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_ddGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`); // Convolve Gz with derivs of y. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`, gpuHelper); convolution1D.convolve1D(Axis.Y, G0_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussYgaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`); convolution1D.convolve1D(Axis.Y, G1_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_dGaussYgaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`); convolution1D.convolve1D(Axis.Y, G2_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_ddGaussYgaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`); // Convolve dGz with derivs of y. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_dGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`, gpuHelper); convolution1D.convolve1D(Axis.Y, G0_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussYdGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`); convolution1D.convolve1D(Axis.Y, G1_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_dGaussYdGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`); // Convolve ddGz with derivs of y. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_ddGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`, gpuHelper); convolution1D.convolve1D(Axis.Y, G0_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussYddGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`); // Convolve GzGy with derivs of x. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussYgaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`, gpuHelper); convolution1D.convolve1D(Axis.X, G1_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GX_${NORMAL_RELAX_GAUSS_SCALE}X`); convolution1D.convolve1D(Axis.X, G2_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GXX_${NORMAL_RELAX_GAUSS_SCALE}X`); // Convolve dGzGy with derivs of x. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussYdGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`, gpuHelper); convolution1D.convolve1D(Axis.X, G0_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GZ_${NORMAL_RELAX_GAUSS_SCALE}X`); convolution1D.convolve1D(Axis.X, G1_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GXZ_${NORMAL_RELAX_GAUSS_SCALE}X`); // Convolve GzdGy with derivs of x. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_dGaussYgaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`, gpuHelper); convolution1D.convolve1D(Axis.X, G0_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GY_${NORMAL_RELAX_GAUSS_SCALE}X`); convolution1D.convolve1D(Axis.X, G1_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GXY_${NORMAL_RELAX_GAUSS_SCALE}X`); // Convolve dGzdGy with derivs of x. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_dGaussYdGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`, gpuHelper); convolution1D.convolve1D(Axis.X, G0_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GYZ_${NORMAL_RELAX_GAUSS_SCALE}X`); // Convolve ddGzGy with derivs of x. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_gaussYddGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`, gpuHelper); convolution1D.convolve1D(Axis.X, G0_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GZZ_${NORMAL_RELAX_GAUSS_SCALE}X`); // Convolve GzddGy with derivs of x. convolution1D.setInput(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_ddGaussYgaussZ_${NORMAL_RELAX_GAUSS_SCALE}X`, gpuHelper); convolution1D.convolve1D(Axis.X, G0_KERNEL_3X, gpuHelper, fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_GYY_${NORMAL_RELAX_GAUSS_SCALE}X`); // Clear gpu buffers and remove refs. gpuHelper.clear(); // Delete temp files. unlinkSync(`${fileParams.OUTPUT_PATH}${fileParams.FILENAME}_gaussZ_${NORMAL_RELAX_GAUSS_SCALE}X.tom`); unlinkSync(`${fileParams.OUTPUT_PATH}${fileParams.FILENAME}_dGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X.tom`); unlinkSync(`${fileParams.OUTPUT_PATH}${fileParams.FILENAME}_ddGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X.tom`); unlinkSync(`${fileParams.OUTPUT_PATH}${fileParams.FILENAME}_gaussYgaussZ_${NORMAL_RELAX_GAUSS_SCALE}X.tom`); unlinkSync(`${fileParams.OUTPUT_PATH}${fileParams.FILENAME}_dGaussYgaussZ_${NORMAL_RELAX_GAUSS_SCALE}X.tom`); unlinkSync(`${fileParams.OUTPUT_PATH}${fileParams.FILENAME}_ddGaussYgaussZ_${NORMAL_RELAX_GAUSS_SCALE}X.tom`); unlinkSync(`${fileParams.OUTPUT_PATH}${fileParams.FILENAME}_gaussYdGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X.tom`); unlinkSync(`${fileParams.OUTPUT_PATH}${fileParams.FILENAME}_dGaussYdGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X.tom`); unlinkSync(`${fileParams.OUTPUT_PATH}${fileParams.FILENAME}_gaussYddGaussZ_${NORMAL_RELAX_GAUSS_SCALE}X.tom`); logTime('\tgauss convolutions', startTime); };
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type ViewingRoomArtworkQueryVariables = { viewingRoomID: string; artworkID: string; }; export type ViewingRoomArtworkQueryResponse = { readonly artwork: { readonly " $fragmentRefs": FragmentRefs<"ViewingRoomArtwork_selectedArtwork">; } | null; readonly viewingRoom: { readonly " $fragmentRefs": FragmentRefs<"ViewingRoomArtwork_viewingRoomInfo">; } | null; }; export type ViewingRoomArtworkQuery = { readonly response: ViewingRoomArtworkQueryResponse; readonly variables: ViewingRoomArtworkQueryVariables; }; /* query ViewingRoomArtworkQuery( $viewingRoomID: ID! $artworkID: String! ) { artwork(id: $artworkID) { ...ViewingRoomArtwork_selectedArtwork id } viewingRoom(id: $viewingRoomID) { ...ViewingRoomArtwork_viewingRoomInfo } } fragment ViewingRoomArtwork_selectedArtwork on Artwork { title artistNames date additionalInformation saleMessage href slug image { url(version: "larger") aspectRatio } isHangable widthCm heightCm id images { url: imageURL width height imageVersions deepZoom { image: Image { tileSize: TileSize url: Url format: Format size: Size { width: Width height: Height } } } } } fragment ViewingRoomArtwork_viewingRoomInfo on ViewingRoom { title partner { name id } heroImage: image { imageURLs { normalized } } status distanceToOpen distanceToClose internalID slug } */ const node: ConcreteRequest = (function(){ var v0 = { "defaultValue": null, "kind": "LocalArgument", "name": "artworkID" }, v1 = { "defaultValue": null, "kind": "LocalArgument", "name": "viewingRoomID" }, v2 = [ { "kind": "Variable", "name": "id", "variableName": "artworkID" } ], v3 = [ { "kind": "Variable", "name": "id", "variableName": "viewingRoomID" } ], v4 = { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, v5 = { "alias": null, "args": null, "kind": "ScalarField", "name": "slug", "storageKey": null }, v6 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }; return { "fragment": { "argumentDefinitions": [ (v0/*: any*/), (v1/*: any*/) ], "kind": "Fragment", "metadata": null, "name": "ViewingRoomArtworkQuery", "selections": [ { "alias": null, "args": (v2/*: any*/), "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "ViewingRoomArtwork_selectedArtwork" } ], "storageKey": null }, { "alias": null, "args": (v3/*: any*/), "concreteType": "ViewingRoom", "kind": "LinkedField", "name": "viewingRoom", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "ViewingRoomArtwork_viewingRoomInfo" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [ (v1/*: any*/), (v0/*: any*/) ], "kind": "Operation", "name": "ViewingRoomArtworkQuery", "selections": [ { "alias": null, "args": (v2/*: any*/), "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ (v4/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "date", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "additionalInformation", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "saleMessage", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }, (v5/*: any*/), { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "larger" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"larger\")" }, { "alias": null, "args": null, "kind": "ScalarField", "name": "aspectRatio", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "isHangable", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "widthCm", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "heightCm", "storageKey": null }, (v6/*: any*/), { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "images", "plural": true, "selections": [ { "alias": "url", "args": null, "kind": "ScalarField", "name": "imageURL", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "width", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "height", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "imageVersions", "storageKey": null }, { "alias": null, "args": null, "concreteType": "DeepZoom", "kind": "LinkedField", "name": "deepZoom", "plural": false, "selections": [ { "alias": "image", "args": null, "concreteType": "DeepZoomImage", "kind": "LinkedField", "name": "Image", "plural": false, "selections": [ { "alias": "tileSize", "args": null, "kind": "ScalarField", "name": "TileSize", "storageKey": null }, { "alias": "url", "args": null, "kind": "ScalarField", "name": "Url", "storageKey": null }, { "alias": "format", "args": null, "kind": "ScalarField", "name": "Format", "storageKey": null }, { "alias": "size", "args": null, "concreteType": "DeepZoomImageSize", "kind": "LinkedField", "name": "Size", "plural": false, "selections": [ { "alias": "width", "args": null, "kind": "ScalarField", "name": "Width", "storageKey": null }, { "alias": "height", "args": null, "kind": "ScalarField", "name": "Height", "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "storageKey": null }, { "alias": null, "args": (v3/*: any*/), "concreteType": "ViewingRoom", "kind": "LinkedField", "name": "viewingRoom", "plural": false, "selections": [ (v4/*: any*/), { "alias": null, "args": null, "concreteType": "Partner", "kind": "LinkedField", "name": "partner", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, (v6/*: any*/) ], "storageKey": null }, { "alias": "heroImage", "args": null, "concreteType": "ARImage", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "ImageURLs", "kind": "LinkedField", "name": "imageURLs", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "normalized", "storageKey": null } ], "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "status", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "distanceToOpen", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "distanceToClose", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, (v5/*: any*/) ], "storageKey": null } ] }, "params": { "id": "649ba90dbd127d2c0b189ba9d8ccc534", "metadata": {}, "name": "ViewingRoomArtworkQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '4b8b23e69ff8b8a94adb77477d32e87a'; export default node;
the_stack
import * as Async from "../src/async"; import * as Sync from "../src/sync"; import { makeFactory } from "../src/async"; interface ParentType { name: string | null; birthday: Date; children: ChildType[]; spouse: ParentType | null; } interface ChildType { name: string | null; grade: number; } interface WidgetType { name: string; id: number; } describe("async factories build stuff", () => { const childFactory = Async.makeFactory<ChildType>({ name: "Kid", grade: 1 }); const parentFactory = Async.makeFactory<ParentType>( { name: "Parent", birthday: Async.each(i => Promise.resolve(new Date(`2017/05/${i}`))), children: Async.each(() => []), spouse: null }, { startingSequenceNumber: 1 } ); it("makes an object from a factory", async () => { const jimmy = await childFactory.build({ name: "Jimmy" }); expect(jimmy.name).toEqual("Jimmy"); expect(jimmy.grade).toEqual(1); }); it("makes an object with default field from a factory", async () => { const jimmy = await childFactory.build(); expect(jimmy.name).toEqual("Kid"); expect(jimmy.grade).toEqual(1); }); it("makes an object with default field explicitly set to null", async () => { const anon = await childFactory.build({ name: null }); expect(anon.name).toBeNull(); expect(anon.grade).toEqual(1); }); it("can make use of sequence #", async () => { const susan = await parentFactory.build({ name: "Susan" }); const edward = await parentFactory.build({ name: "Edward" }); expect(susan.birthday.getTime()).toEqual(new Date("2017/05/01").getTime()); expect(edward.birthday.getTime()).toEqual(new Date("2017/05/02").getTime()); }); it("can handle has many", async () => { const jimmy = await childFactory.build({ name: "Jimmy" }); const alice = await childFactory.build({ name: "Alice", grade: 3 }); const susan = await parentFactory.build({ name: "Susan", children: [jimmy, alice] }); expect(susan.children.map(c => c.name)).toEqual(["Jimmy", "Alice"]); }); it("can refer to other factories", async () => { const parentWithKidsFactory = Async.makeFactory<ParentType>({ name: "Timothy", birthday: Async.each(i => new Date(`2017/05/${i}`)), children: Async.each(async () => [ await childFactory.build({ name: "Bobby" }), await childFactory.build({ name: "Jane" }) ]), spouse: null }); const tim = await parentWithKidsFactory.build({ birthday: new Date("2017-02-01") }); expect(tim.children.map(c => c.name)).toEqual(["Bobby", "Jane"]); }); it("can extend existing factories", async () => { const geniusFactory = childFactory.extend({ grade: Async.each(i => { return new Promise((res, _rej) => { setTimeout(() => { res((i + 1) * 2); }, 1); }); }) }); const colin = await geniusFactory.build({ name: "Colin" }); expect(colin.grade).toEqual(2); const albert = await geniusFactory.build({ name: "Albert" }); expect(albert.grade).toEqual(4); }); it("can derive one value based on another value", async () => { interface Person { readonly firstName: string; readonly lastName: string; readonly fullName: string; } const personFactory = Async.makeFactory<Person>({ firstName: "Jules", lastName: "Bond", fullName: "" }).withDerivation("fullName", p => `${p.firstName} ${p.lastName}`); //.withDerivation2(['firstName','lastName'],'fullName', (fn, ln) => `${fn} ${ln}`); const bond = await personFactory.build({ firstName: "James" }); expect(bond.fullName).toEqual("James Bond"); const bond2 = await personFactory.build(); expect(bond2.fullName).toEqual("Jules Bond"); }); it("can build a list of items", async () => { const children = await childFactory.buildList(3, { name: "Bruce" }); expect(children.length).toEqual(3); for (let child of children) { expect(child.name).toEqual("Bruce"); expect(child.grade).toEqual(1); } }); it("can combine factories", async () => { const timeStamps = makeFactory({ createdAt: Async.each(async () => new Date()), updatedAt: Async.each(async () => new Date()) }); const softDelete = makeFactory({ isDeleted: false }); interface Post { content: string; createdAt: Date; updatedAt: Date; isDeleted: boolean; } interface User { email: string; createdAt: Date; updatedAt: Date; isDeleted: boolean; } const postFactory: Async.Factory<Post> = makeFactory({ content: "lorem ipsum" }) .combine(timeStamps) .combine(softDelete); const userFactory: Async.Factory<User> = makeFactory({ email: "test@user.com" }) .combine(timeStamps) .combine(softDelete); const post = await postFactory.build({ content: "yadda yadda yadda", isDeleted: true }); expect(post.createdAt.getTime() - new Date().getTime()).toBeLessThan(100); expect(post.isDeleted).toEqual(true); const user = await userFactory.build({ email: "foo@bar.com", createdAt: new Date("2018/01/02") }); expect(user.createdAt.getTime()).toEqual(new Date("2018/01/02").getTime()); expect(post.updatedAt.getTime() - new Date().getTime()).toBeLessThan(100); expect(user.email).toEqual("foo@bar.com"); }); it("supports nested factories", async () => { interface IGroceryStore { aisle: { name: string; typeOfFood: string; budget: number; tags: string[]; }; } const groceryStoreFactory = Async.makeFactory<IGroceryStore>({ aisle: { name: "Junk Food Aisle", typeOfFood: "Junk Food", budget: 3000, tags: ["a", "b", "c"] } }); // Error: Property 'name' is missing in type '{ budget: number; } const aStore = await groceryStoreFactory.build({ aisle: { budget: 9999, tags: ["a", "b"] } }); expect(aStore.aisle.budget).toEqual(9999); expect(aStore.aisle.typeOfFood).toEqual("Junk Food"); expect(aStore.aisle.tags).toEqual(["a", "b"]); }); it("can transform type", async () => { const makeAdult = childFactory.transform<ParentType>(t => { const birthday = `${2018 - t.grade - 25}/05/10`; return { name: t.name, birthday: new Date(birthday), spouse: null, children: [] }; }); const susan = await makeAdult.build({ name: "Susan", grade: 5 }); expect(susan.birthday.getTime()).toEqual(new Date("1988/05/10").getTime()); expect(susan.name).toEqual("Susan"); expect(susan.spouse).toEqual(null); expect(susan.children.length).toEqual(0); }); type Saved<T extends Object> = T & { id: number }; function saveRecord<T extends Object>(t: T): Promise<Saved<T>> { return new Promise<Saved<T>>(res => { setTimeout(() => { const saved: Saved<T> = { ...(t as any), id: Math.random() * 10000 }; res(saved); }, 1); }); } it("can model db factories", async () => { interface SavedParentType { name: string; birthday: Date; children: Saved<ChildType>[]; spouse: Saved<SavedParentType> | null; } const dbChildFactory = childFactory.transform(saveRecord); const savedParentFactory = Async.makeFactory<SavedParentType>({ name: "Parent", birthday: Async.each(i => Promise.resolve(new Date(`2017/05/${i}`))), children: Async.each(() => []), spouse: null }); const dbParentFactory = savedParentFactory.transform(saveRecord); const familyFactory = savedParentFactory .extend({ name: "Ted", children: Promise.all([ await dbChildFactory.build({ name: "Billy" }), await dbChildFactory.build({ name: "Amy" }) ]), spouse: await dbParentFactory.build({ name: "Susan" }) }) .transform(saveRecord); const ted = await familyFactory.build({ birthday: new Date("1980/09/23") }); expect(ted.id).toBeGreaterThan(0); expect(ted.birthday.getTime()).toEqual(new Date("1980/09/23").getTime()); expect(ted.name).toEqual("Ted"); expect(ted.spouse!.id).toBeGreaterThan(0); expect(ted.spouse!.name).toEqual("Susan"); expect(ted.spouse!.id).toBeGreaterThan(0); expect(ted.children[0]!.name).toEqual("Billy"); expect(ted.children[1]!.name).toEqual("Amy"); }); it("can create async factories from sync builders", async () => { const parentFactory = Async.makeFactoryFromSync<ParentType>( { name: "Parent", birthday: Sync.each(i => new Date(`2017/05/${i}`)), children: Sync.each(() => []), spouse: null }, { startingSequenceNumber: 1 } ); const susan = await parentFactory.build({ name: "Susan" }); expect(susan.name).toEqual("Susan"); expect(susan.birthday.getTime()).toEqual(new Date("2017/05/01").getTime()); }); it("seq num works as expected", async () => { interface TypeA { foo: number; bar: string; } const factoryA = Async.makeFactory<TypeA>({ foo: Async.each(n => n), bar: "hello" }); const a = await factoryA.buildList(3); expect(a[0].foo).toEqual(0); expect(a[1].foo).toEqual(1); expect(a[2].foo).toEqual(2); }); it("allows custom seq num start", async () => { interface TypeA { foo: number; bar: string; } const factoryA = Async.makeFactory<TypeA>( { foo: Async.each(n => n + 1), bar: "hello" }, { startingSequenceNumber: 3 } ); const a = await factoryA.build(); expect(a.foo).toEqual(4); }); it("Can reset sequence number back to config default i.e. 0", async () => { const widgetFactory = Async.makeFactory<WidgetType>({ name: "Widget", id: Async.each(i => i) }); const widgets = await widgetFactory.buildList(3); expect(widgets[2].id).toBe(2); widgetFactory.resetSequenceNumber(); const moreWidgets = await widgetFactory.buildList(3); expect(moreWidgets[2].id).toBe(2); }); it("Can reset sequence number back to non-config default", async () => { const widgetFactory = Async.makeFactory<WidgetType>( { name: "Widget", id: Async.each(i => i) }, { startingSequenceNumber: 100 } ); const widgets = await widgetFactory.buildList(3); expect(widgets[2].id).toBe(102); widgetFactory.resetSequenceNumber(); const moreWidgets = await widgetFactory.buildList(3); expect(moreWidgets[2].id).toBe(102); }); it("clones deeply nested values", async () => { interface TypeA { bar: { baz: string; }; } const factoryA = Async.makeFactory<TypeA>({ bar: { baz: "should-be-immutable" } }); const a = await factoryA.build(); const b = await factoryA.build(); a.bar.baz = "is-not-immutable"; expect(b.bar.baz).toEqual("should-be-immutable"); }); describe("required fields", () => { interface DbRecordUnsaved { foreignId: string; name: string; } interface DbRecordSaved extends DbRecordUnsaved { id: number; } function makeFactoryA() { return Async.makeFactoryWithRequired<DbRecordUnsaved, "foreignId">({ name: "hello" }).transform<DbRecordSaved>(t => ({ ...t, name: t.name + t.name, id: t.name.length })); } it("supports build", async () => { const factoryA = makeFactoryA(); // compile failures //const z = await factoryA.build(); //const z = await factoryA.build({ }); //const z = await factoryA.build({ name: "uhoh" }); // data checks const a = await factoryA.build({ foreignId: "fk1" }); expect(a).toEqual({ name: "hellohello", foreignId: "fk1", id: 5 }); const b = await factoryA.build({ foreignId: "fk2", name: "goodbye" }); expect(b).toEqual({ name: "goodbyegoodbye", foreignId: "fk2", id: 7 }); }); it("supports buildList", async () => { const factoryA = makeFactoryA(); // compile failures //const [y,z] = await factoryA.buildList(5); //const [y,z] = await factoryA.buildList(5, {}); //const [y,z] = await factoryA.buildList(5, { name: 'hello' }); // data checks const [c, d] = await factoryA.buildList(2, { foreignId: "fk3" }); expect(c).toEqual({ name: "hellohello", id: 5, foreignId: "fk3" }); expect(d).toEqual({ name: "hellohello", id: 5, foreignId: "fk3" }); }); it("supports build from sync", async () => { interface DbRecord { foreignId: string; name: string; } const factoryA = Sync.makeFactoryWithRequired<DbRecord, "foreignId">({ name: "hello" }); const factoryAPrime = Async.makeFactoryFromSync( factoryA.builder ).transform(v => ({ fk: v.foreignId, name: v.name.toUpperCase() })); // compile failures //const z = await factoryAPrime.build(); //const z = await factoryAPrime.build({}); //const z = await factoryAPrime.build({ name: "hi" }); const a = await factoryAPrime.build({ foreignId: "fk" }); expect(a).toEqual({ fk: "fk", name: "HELLO" }); // compile failures //const [y,z] = await factoryAPrime.buildList(5); //const [y,z] = await factoryAPrime.buildList(5, {}); //const [y,z] = await factoryAPrime.buildList(5, { name: 'hello' }); const [b, c] = await factoryAPrime.buildList(5, { foreignId: "fkmany" }); expect(b).toEqual({ name: "HELLO", fk: "fkmany" }); expect(c).toEqual({ name: "HELLO", fk: "fkmany" }); }); }); });
the_stack
type StateType = IndexType; /** * Action labels can be strings */ export type ActionNameType = IndexType; /** * Represents a state and data and its corresponding data. */ export type State<S extends StateType, D = {}> = Readonly<D> & { readonly stateName: S; } /** * Give Actions to nextState() to (maybe) trigger a transition. */ export type Action<Name extends ActionNameType, Payload> = Readonly<Payload> & { readonly actionName: Name }; /// /// Errors /// /** * Represents a compiler error message. Error brands prevent really clever users from naming their states as one of the error messages * and subverting error checking. Yet, the compiler still displays the string at the end of the failed cast indicating what the * issue is rather than something puzzling like could not assign to never. */ type ErrorBrand<T extends IndexType> = { [k in T]: void }; type IndexType = string | number; /// Validators type AssertStateInMap<StateMap, S extends StateType> = S extends MapKeys<StateMap> ? S : ErrorBrand<`'${S}' is not a state`>; type AssertNewState<S extends StateType, States> = S extends MapKeys<States> ? ErrorBrand<`'${S}' has already been declared`> : S; type AssertNewTransition<S extends StateType, N extends StateType, Transitions> = N extends MapLookup<Transitions, S> ? ErrorBrand<`There already exists a transition from '${S}' to '${N}'`> : N; type AssertActionNotDefined<AN extends ActionNameType, ActionNames extends IndexType> = AN extends ActionNames ? ErrorBrand<`Action '${AN}' already declared`> : AN; type AssertAllNonTerminalStatesHandled<Transitions, HandledStates> = MapKeys<Transitions> extends HandledStates ? void : ErrorBrand<`No handlers declared for ${Exclude<MapKeys<Transitions>, HandledStates>}`>; type StateMachineDefinition<S, A> = { handlers: { [s: string]: { [a: string]: (cur: MapValues<S>, action: MapValues<A>) => MapValues<S> } } }; // Allows us to append multiple values for the same key in a type map. type AddToTypeMap<M, K extends string | number | symbol, V> = M | [K , V]; type MapLookup<Map, K extends string | number | symbol> = Map extends [K, infer V] ? V : never; type MapKeys<Map> = Map extends [infer K, infer _] ? K extends IndexType ? K : never : never; type MapValues<Map> = Map extends [infer _, infer V] ? V : never; /// /// stateMachine() builder /// /** * A builder from calling stateMachine(). */ export type StateMachineBuilder = { /** * Add a state to this state machine. */ readonly state: StateFunc<never>; } type StateMachineFunc = () => StateMachineBuilder; /// /// .state() builder /// /** * A builder from calling .state() */ export type StateBuilder<StateMap> = { /** * Add a state to this state machine. */ readonly state: StateFunc<StateMap>; readonly transition: TransitionFunc<StateMap, never>; } /** * The signature for calling the state function in the builder. */ type StateFunc<StateMap> = <S extends StateType, Data = {}>( state: AssertNewState<S, StateMap> ) => StateBuilder<AddToTypeMap<StateMap, S, State<S, Data>>>; /// /// .transition() builder /// /** * The builder returned by .transition() */ export type TransitionBuilder<StateMap, Transitions> = { /** * Add a transition to this state machine. */ readonly transition: TransitionFunc<StateMap, Transitions>; readonly action: ActionFunc<StateMap, Transitions, never>; } /** * The signature of .transition() */ export type TransitionFunc<StateMap, Transitions> = <S extends StateType, N extends StateType>( curState: AssertStateInMap<StateMap, S>, nextState: N extends MapKeys<StateMap> ? AssertNewTransition<S, N, Transitions> : ErrorBrand<`${S} is not a declared state`> ) => TransitionBuilder<StateMap, AddToTypeMap<Transitions, S, N>>; /// /// .action() builder /// export type ActionBuilder< StateMap, Transitions, ActionsMap > = { readonly action: ActionFunc<StateMap, Transitions, ActionsMap>; readonly actionHandler: ActionHandlerFunc< StateMap, Transitions, ActionsMap, never >; }; export type ActionFunc< StateMap, Transitions, ActionsMap > = <AN extends ActionNameType, AP = {}>(actionName: AssertActionNotDefined<AN, MapKeys<ActionsMap>>) => ActionBuilder<StateMap, Transitions, AddToTypeMap<ActionsMap, AN, Action<AN, AP>>>; /// /// .actionsHandler() builder. /// /** * The builder returned by .actionHandler() */ export type ActionHandlersBuilder<StateMap, Transitions, ActionsMap, HandledStates> = { readonly actionHandler: ActionHandlerFunc<StateMap, Transitions, ActionsMap, HandledStates>; readonly done: DoneFunc<StateMap, ActionsMap, Transitions, HandledStates>, } /** * The Signature of .actionHandler(). */ export type ActionHandlerFunc< States, Transitions, Actions, HandledStates > = < S extends StateType, AN extends ActionNameType, NS extends MapValues<States>, > ( state: S, action: AN, // TODO: Checking that the action and state pair haven't already been declared here causes handler: ActionHandlerCallback<States, Transitions, S, AN, NS, Actions> ) => ActionHandlersBuilder<States, Transitions, Actions, HandledStates | S>; type ActionHandlerCallback< States, Transitions, CS extends StateType, AN extends ActionNameType, NS extends MapValues<States>, Actions, > = (state: MapLookup<States, CS>, action: MapLookup<Actions, AN>) => NS extends State<infer N, infer ND> ? N extends MapKeys<States> ? CS extends MapKeys<Transitions> ? N extends MapLookup<Transitions, CS> ? State<N, ND> : ErrorBrand<`No transition declared between ${CS} and ${N}`> : ErrorBrand<`State ${CS} is terminal and has no transitions`> : ErrorBrand<`${N} is not a state`> : ErrorBrand<'The returned value is not a state'>; /// /// .done() /// type DoneBuilder = <StateMap, ActionMap, Transitions, HandledStates>(definition: StateMachineDefinition<StateMap, ActionMap>) => DoneFunc<StateMap, ActionMap, Transitions, HandledStates>; // Check that the only unhandled states in the handler map are final states (i.e, they have no transitions out of them) type DoneFunc<StateMap, ActionMap, Transitions, HandledStates> = (_: AssertAllNonTerminalStatesHandled<Transitions, HandledStates>) => StateMachine<StateMap, ActionMap>; /** * A state machine */ export type StateMachine<StateMap, ActionMap> = { nextState: (curState: MapValues<StateMap>, action: MapValues<ActionMap>) => MapValues<StateMap>, }; export const stateMachine: StateMachineFunc = (): StateMachineBuilder => { const stateFunc = state<never>(); return { state: stateFunc, }; } const state = <StateMap>(): StateFunc<StateMap> => { return <S extends StateType, D = {}>(_s: AssertNewState<S, StateMap>) => { type NewStateMap = AddToTypeMap<StateMap, S, State<S, D>>; const transitionFunc = transition<NewStateMap, never>(); const stateFunc = state<NewStateMap>() const builder = { state: stateFunc, transition: transitionFunc, }; return builder; } } const transition = <StateMap, Transitions>(): TransitionFunc<StateMap, Transitions> => { return <S extends StateType, N extends StateType>( _curState: AssertStateInMap<StateMap, S>, _next: N extends MapKeys<StateMap> ? AssertNewTransition<S, N, Transitions> : ErrorBrand<`${S} is not a declared state`> ) => { type NewTransitions = AddToTypeMap<Transitions, S, N>; const transitionFunction = transition<StateMap, NewTransitions>(); const actionFunc = action<StateMap, NewTransitions, never>(); return { transition: transitionFunction, action: actionFunc, }; }; } const action = <StateMap, Transitions, ActionMap>(): ActionFunc<StateMap, Transitions, ActionMap> => { return <AN extends ActionNameType, AP = {}>(_actionName: AssertActionNotDefined<AN, MapKeys<ActionMap>>) => { type NewActionMap = AddToTypeMap<ActionMap, AN, Action<AN, AP>>; const actionFunc: any = action<StateMap, Transitions, NewActionMap>() const actionHandlerFunc = actionHandler<StateMap, Transitions, NewActionMap, never>({ handlers: {}}); return { action: actionFunc, actionHandler: actionHandlerFunc, }; } } const actionHandler = <StateMap, Transitions, ActionMap, HandledStates>(definition: StateMachineDefinition<StateMap, ActionMap>): ActionHandlerFunc<StateMap, Transitions, ActionMap, HandledStates> => { const actionHandlerFunc: ActionHandlerFunc<StateMap, Transitions, ActionMap, HandledStates> = <S extends StateType, AN extends ActionNameType, NS extends MapValues<StateMap>>( state: S, action: AN, handler: ActionHandlerCallback<StateMap, Transitions, S, AN, NS, ActionMap> ) => { const newDefinition: StateMachineDefinition<StateMap, ActionMap> = { ...definition, handlers: { ...definition.handlers, [state]: { ...definition.handlers[state as string] ? definition.handlers[state as string] : {}, [action]: handler as any, } } }; type NextHandledStates = HandledStates | S; const doneFunc = done<StateMap, ActionMap, Transitions, NextHandledStates>(newDefinition); const actionHandlerFunc = actionHandler<StateMap, Transitions, ActionMap, NextHandledStates>(newDefinition); return { actionHandler: actionHandlerFunc, done: doneFunc }; }; return actionHandlerFunc; }; const done: DoneBuilder = <StateMap, ActionMap, Transitions, HandledStates>(definition: StateMachineDefinition<StateMap, ActionMap>) => { const doneFunc: DoneFunc<StateMap, ActionMap, Transitions, HandledStates> = ( _: AssertAllNonTerminalStatesHandled<Transitions, HandledStates> ): StateMachine<StateMap, ActionMap> => { const nextStateFunction = (curState: MapValues<StateMap>, action: MapValues<ActionMap>): MapValues<StateMap> => { const curStateAsState = curState as unknown as State<string, {}>; const actionAsAction = action as unknown as Action<string, {}>; // If no handler declared for state, state doesn't change. if (definition.handlers[curStateAsState.stateName] == null) { return curState; } // If no handler declared for action in given state, state doesn't change. return definition.handlers[curStateAsState.stateName][actionAsAction.actionName] != null ? definition.handlers[curStateAsState.stateName][actionAsAction.actionName](curState, action) : curState; }; return { nextState: nextStateFunction }; } return doneFunc }
the_stack
import { Matrix } from './matrix'; import { isNumber } from '@xiao-ai/utils'; export type PointLike = number[] | Point; export type PointInput = PointLike | number; /** 方向 */ export enum Direction { Center, Top, TopLeft, TopRight, Bottom, BottomLeft, BottomRight, Left, Right, } /** 点和向量类 */ export class Point { 0: number; 1: number; readonly length!: 2; /** * 创建一个点或者向量 * @param {PointInput} start * @param {PointInput} end */ constructor(start: number, end: number); constructor(start: PointLike, end: PointLike); constructor(start: PointInput, end: PointInput) { // 输入两个数 -> 点 if (isNumber(start)) { this[0] = start; this[1] = end as number; } // 输入两个点 -> 向量 else { this[0] = end[0] - start[0]; this[1] = end[1] - start[1]; } Object.defineProperty(this, 'length', { writable: false, enumerable: false, configurable: false, value: 2, }); } /** * 从类似 Point 结构的数据中创建 Point */ static from(start: PointInput) { if (isNumber(start)) { return new Point(start, start); } else { return new Point(start[0], start[1]); } } /** * 迭代器函数 * - 用于解构赋值 * * @returns {Generator} */ [Symbol.iterator]() { return Array.prototype[Symbol.iterator].call(this); } /** * 判断`this`与`point`是否相等 * - 此处的相等将会兼容`[number, number]`类型 * * @param {PointLike} point * @returns {boolean} * @memberof Point */ isEqual(point: PointLike): boolean { return ( point.length === 2 && this[0] === point[0] && this[1] === point[1] ); } /** * 加法 * - 第一项将会调用 Point 构造函数生成实例,然后参与运算 * - 第二项输入 -1 表示是减法,且 this 是被减数 * * @param {PointInput} added * @param {number} [label=1] * @returns {Point} */ add(added: PointInput, label = 1): Point { const sum = new Point(0, 0); if (isNumber(added)) { sum[0] = this[0] + added * label; sum[1] = this[1] + added * label; } else { sum[0] = this[0] + added[0] * label; sum[1] = this[1] + added[1] * label; } return (sum); } /** * 乘法 * - 第一项将会调用 Point 构造函数生成实例,然后参与运算 * - 第二项输入 -1 表示是除法,且 this 是被除数 * * @param {PointInput} multiplier * @param {number} [label=1] * @returns {Point} */ mul(multiplier: PointInput, label = 1): Point { const sum = new Point(0, 0); if (isNumber(multiplier)) { sum[0] = this[0] * ((label < 0) ? (1 / multiplier) : multiplier); sum[1] = this[1] * ((label < 0) ? (1 / multiplier) : multiplier); } else { sum[0] = this[0] * ((label < 0) ? (1 / multiplier[0]) : multiplier[0]); sum[1] = this[1] * ((label < 0) ? (1 / multiplier[1]) : multiplier[1]); } return (sum); } /** * 向量乘法 * * @param {PointLike} vector * @returns {number} */ product(vector: PointLike): number { return (this[0] * vector[0] + this[1] * vector[1]); } /** * 点旋转(乘以矩阵) * @param {Matrix} ma * @returns {Point} */ rotate(ma: Matrix) { return new Point( this[0] * ma.get(0, 0) + this[1] * ma.get(1, 0), this[0] * ma.get(0, 1) + this[1] * ma.get(1, 1), ); } /** * 返回对 x, y 坐标分别求绝对值后组成的新 Point 实例 * * @returns {Point} */ abs(): Point { return (new Point( Math.abs(this[0]), Math.abs(this[1]), )); } /** * 返回 x, y 坐标分别单位化后组成的新 Point 实例 * * @returns {Point} */ sign(factor = 1): Point { return (new Point( Math.sign(this[0]) * factor, Math.sign(this[1]) * factor, )); } /** * 求 this 到 point 的几何距离 * * @param {PointLike} [point] * @returns {number} */ distance(point: PointLike = [0, 0]): number { return Math.hypot( (this[0] - point[0]), (this[1] - point[1]), ); } /** * this 在`vector`上的投影向量 * * @param {Point} vector 投影向量 * @returns {Point} */ toProjection(vector: Point) { return vector.mul(this.product(vector) / vector.distance()); } /** * 求与 this 平行且模为 factor 的向量 * * @param {number} [factor=1] * @returns {Point} */ toUnit(factor = 1) { const scale = 1 / this.distance(); return this.mul(scale * factor); } /** * this 顺时针旋转 90° * - x 轴向右为正,y 轴向下为正 * * @param {number} [factor=1] * @returns {Point} */ toVertical() { return new Point(-this[1], this[0]); } /** * 获取点的方向 */ toDirection() { if (this[0] > 0) { if (this[1] > 0) { return Direction.BottomRight; } else if (this[1] < 0) { return Direction.TopRight; } else { return Direction.Right; } } else if (this[0] < 0) { if (this[1] > 0) { return Direction.BottomLeft; } else if (this[1] < 0) { return Direction.TopLeft; } else { return Direction.Left; } } else { if (this[1] > 0) { return Direction.Bottom; } else if (this[1] < 0) { return Direction.Top; } else { return Direction.Center; } } } /** * x, y 分别对 n 的余数四舍五入 * * @param {number} [fixed=20] * @returns {Point} */ round(fixed = 20): Point { return (new Point( Number.parseInt((this[0] / fixed).toFixed(), 10) * fixed, Number.parseInt((this[1] / fixed).toFixed(), 10) * fixed, )); } /** * 对 x, y 分别除以 n, 然后四舍五入 * * @param {number} [fixed=20] * @returns {Point} */ roundToSmall(fixed = 20): Point { return (new Point( Number.parseInt((this[0] / fixed).toFixed(), 10), Number.parseInt((this[1] / fixed).toFixed(), 10), )); } /** * x, y 分别对 n 的余数向下取整 * * @param {number} [fixed=20] * @returns {Point} */ floor(fixed = 20): Point { return (new Point( Math.floor(this[0] / fixed) * fixed, Math.floor(this[1] / fixed) * fixed, )); } /** * 对 x, y 分别除以 n, 然后向下取整 * * @param {number} [fixed=20] * @returns {Point} */ floorToSmall(fixed = 20): Point { return (new Point( Math.floor(this[0] / fixed), Math.floor(this[1] / fixed), )); } /** * 是否是零向量 * * @returns {boolean} */ isZero(): boolean { return (this[0] === 0 && this[1] === 0); } /** * 是否是整数点 * * @returns {boolean} */ isInteger(): boolean { return ( this.length === 2 && Number.isInteger(this[0]) && Number.isInteger(this[1]) ); } /** * 是否和输入向量平行 * * @param {PointLike} vector * @returns {boolean} */ isParallel(vector: PointLike): boolean { return (this[0] * vector[1] === this[1] * vector[0]); } /** * 是否和输入向量垂直 * * @param {PointLike} vector * @returns {boolean} */ isVertical(vector: PointLike): boolean { return ((this[0] * vector[0] + this[1] * vector[1]) === 0); } /** * 是否和输入向量方向相同 * * @param {PointLike} vector * @returns {boolean} */ isSameDirection(vector: PointLike): boolean { return ( // 0 向量与任意向量的方向都相同 this.isZero() || (this.isZero.call(vector) as boolean) || // 非零向量 ( this.isParallel(vector) && (vector[0] * this[0] > 0 || vector[1] * this[1] > 0) ) ); } /** * 是否和输入向量方向相反 * * @param {PointLike} vector * @returns {boolean} */ isOppositeDirection(vector: PointLike): boolean { return ( // 0 向量与任意向量的方向都相反 this.isZero() || (this.isZero.call(vector) as boolean) || // 非零向量 ( this.isParallel(vector) && (vector[0] * this[0] < 0 || vector[1] * this[1] < 0) ) ); } /** * 是否在线段内 * * @param {PointLike[]} segment * @returns {boolean} */ isInLine(segment: PointLike[]): boolean { // 点到线段两端的向量方向相反,即表示其在线段内 const toStart = new Point(this, segment[0]); const toEnd = new Point(this, segment[1]); return ( toEnd.isZero() || toStart.isZero() || toStart.isOppositeDirection(toEnd) ); } /** * 以 this 为中心点,过滤距离中心点距离为 factor 的所有点,返回使 predicate 输出 true 的点的集合 * * @param {(point: Point) => boolean} predicate * @param {number} [factor=1] * @returns {Point[]} */ around(predicate: (point: Point) => boolean, factor = 1): Point[] { const ans: Point[] = predicate(this) ? [Point.from(this)] : []; for (let m = 1; ans.length < 1; m++) { for (let i = 0; i < m; i++) { const x = i * factor, y = (m - i) * factor; const around = (x === 0) ? [[0, y], [0, -y], [y, 0], [-y, 0]] : [[x, y], [x, -y], [-x, y], [-x, -y]]; const points = around.map((n) => this.add(n)); ans.push(...points.filter(predicate)); if (ans.length > 0) { break; } } } return ans; } /** * 求 points 中与 this 距离最近的点 * * @param {PointLike[]} points * @returns {(undefined | Point)} */ closest(points: PointLike[]) { if (points.length === 0) { throw new Error('(point) points can not be a empty array.'); } return Point.from(points.reduce( (pre, next) => this.distance(pre) < this.distance(next) ? pre : next, )); } /** * 求 vectors 中与 this 夹角最小的向量 * * @param {PointLike[]} vectors * @returns {Point} */ minAngle(vectors: PointLike[]) { if (vectors.length === 0) { throw new Error('(point) vectors can not be a empty array.'); } function cosAB(a: PointLike, b: PointLike): number { return ( Point.prototype.product.call(a, b) / Point.prototype.distance.call(a, [0, 0]) / Point.prototype.distance.call(b, [0, 0]) ); } return Point.from(vectors.reduce( (pre, next) => cosAB(this, pre) > cosAB(this, next) ? pre : next, )); } /** * 以当前点为左上角,生成四方格坐标 * * @param {number} [len=20] * @returns {[Point, Point, Point, Point]} */ toGrid(len = 20): [Point, Point, Point, Point] { return ([ new Point(this[0], this[1]), new Point(this[0] + len, this[1]), new Point(this[0], this[1] + len), new Point(this[0] + len, this[1] + len), ]); } /** * 将坐标用 str 连接成字符串 * * @param {string} [str=','] * @returns */ join(str = ',') { return `${this[0]}${str}${this[1]}`; } /** * map 迭代,同`Array.prototype.map` * * @template T * @param {(value: number, index: number) => T} callback * @returns {[T, T]} */ map<T>(callback: (value: number, index: number) => T): [T, T] { return [callback(this[0], 0), callback(this[1], 1)]; } /** 输出数据 */ toData(): [number, number] { return [this[0], this[1]]; } } export const Directions: Readonly<Record<Direction, Point>> = { [Direction.Center]: Point.from([0, 0]), [Direction.Top]: Point.from([0, -1]), [Direction.Bottom]: Point.from([0, 1]), [Direction.Left]: Point.from([-1, 0]), [Direction.Right]: Point.from([1, 0]), [Direction.TopLeft]: Point.from([-1, -1]), [Direction.TopRight]: Point.from([1, -1]), [Direction.BottomLeft]: Point.from([-1, 1]), [Direction.BottomRight]: Point.from([1, 1]), };
the_stack
import { readJSON } from "fs-extra"; import { Nullable, Undefinable } from "../../../../shared/types"; import * as React from "react"; import { ContextMenu, Menu, Classes, Button, MenuDivider } from "@blueprintjs/core"; import { Node, Scene } from "babylonjs"; import { LGraph, LGraphCanvas, LGraphGroup, LiteGraph, LLink } from "litegraph.js"; import { EditableText } from "../../../editor/gui/editable-text"; import { Alert } from "../../../editor/gui/alert"; import { Tools } from "../../../editor/tools/tools"; import { IPCTools } from "../../../editor/tools/ipc"; import { undoRedo } from "../../../editor/tools/undo-redo"; import { INodeResult, IAssetResult, IMaterialResult, IMeshResult } from "../../../editor/scene/utils"; import { GraphCodeGenerator } from "../../../editor/graph/generate"; import { GraphNode, ELinkErrorType } from "../../../editor/graph/node"; import { NodeUtils } from "../../../editor/graph/utils"; import { Mesh } from "../../../editor/graph/mesh/mesh"; import { TransformNode } from "../../../editor/graph/transform-node/transform-node"; import { Camera } from "../../../editor/graph/camera/camera"; import { Light } from "../../../editor/graph/light/light"; import { Sound } from "../../../editor/graph/sound/sound"; import { AnimationGroup } from "../../../editor/graph/animation/animation-group"; import { ParticleSystem } from "../../../editor/graph/particle-system/particle-system"; import { Texture } from "../../../editor/graph/texture/texture"; import { Material } from "../../../editor/graph/material/material"; import { GetMesh } from "../../../editor/graph/mesh/get-mesh"; import { GetCamera } from "../../../editor/graph/camera/get-camera"; import { GetLight } from "../../../editor/graph/light/get-light"; import { TickGameEvent } from "../../../editor/graph/events/tick-game-event"; import { StartGameEvent } from "../../../editor/graph/events/start-game-event"; import { GraphContextMenu } from "../context-menu"; import { NodeCreator } from "../node-creator"; import GraphEditorWindow from "../index"; export interface IGraphProps { /** * Defines the reference to the editor's window main class. */ editor: GraphEditorWindow; } export class Graph extends React.Component<IGraphProps> { /** * Defines the reference to the canvas used to draw the graph. */ public canvas: HTMLCanvasElement; /** * Defines the reference to the graph that contains nodes. */ public graph: Nullable<LGraph> = null; /** * Defines the reference to the graph canvas utility that renders the graph. */ public graphCanvas: Nullable<LGraphCanvas> = null; /** * Defines the path to the JSON file containing the graph. */ public jsonPath: Nullable<string> = null; private _refHandler = { getCanvas: (ref: HTMLCanvasElement) => this.canvas = ref, }; private _editor: GraphEditorWindow; private _canvasFocused: boolean = false; private _pausedNode: Nullable<GraphNode> = null; private _startedGraphInvervals: number[] = []; private _startedGraphs: LGraph[] = []; /** * Constructor. * @param props defines the component's props. */ public constructor(props: IGraphProps) { super(props); this._editor = props.editor; props.editor.graph = this; } /** * Renders the component. */ public render(): React.ReactNode { return <canvas ref={this._refHandler.getCanvas} className="graphcanvas" style={{ width: "100%", height: "100%", position: "absolute", top: "0" }}></canvas>; } /** * Called on the component did mount. */ public componentDidMount(): void { this._bindEvents(); this._updateSceneNodesLists(); } /** * Called on the window or layout is resized. */ public resize(): void { const size = this._editor.getPanelSize("graph"); if (size.width <= 0 || size.height <= 0) { return; } this.graphCanvas?.resize(size.width, size.height); this.graphCanvas?.setDirty(true, true); } /** * Called on the component did mount. */ public async initGraph(jsonPath: string): Promise<void> { this.jsonPath = jsonPath; // Configure graph const json = await readJSON(jsonPath); this.graph = new LGraph(); this.graph.configure(json, false); this.graph.scene = this._editor.preview.getScene(); this.graph.config["align_to_grid"] = true; this._checkGraph(); // Graph events this._handleConnectionChange(this.graph); this._handleNodeAdded(this.graph); // Create graph canvas this.graphCanvas = new LGraphCanvas(this.canvas, this.graph, { autoresize: true, skip_render: false, }); // Preferences const preferences = JSON.parse(localStorage.getItem("babylonjs-editor-graph-preferences") ?? "{ }"); this.graphCanvas.render_canvas_border = false; this.graphCanvas.highquality_render = true; this.graphCanvas.render_execution_order = preferences.render_execution_order ?? true; this.graphCanvas.render_curved_connections = preferences.render_curved_connections ?? true; this.graphCanvas.show_info = preferences.show_info ?? true; // Graph canvas events this._handleShowSearchBox(this.graphCanvas); this._handleLinkError(this.graphCanvas); this._handleGraphCanvasEvents(this.graphCanvas); this._handleProcessContextMenu(this.graphCanvas); this._handleLinkContextMenu(this.graphCanvas); this._handlePrompt(this.graphCanvas); this._handleNodeMoved(this.graphCanvas); this.resize(); // Select first node const firstNode = this.getAllNodes()[0]; if (firstNode) { this.graphCanvas.selectNode(firstNode); this._editor.inspector.setNode(firstNode); } // Clean graph's links this._cleanUselessLinks(this.graph); } /** * Clones all the selected nodes. */ public cloneNode(): void { this.graphCanvas?.copyToClipboard(); this.graphCanvas?.pasteFromClipboard(); } /** * Removes all the selected nodes. */ public removeNode(): void { // node.graph?.remove(node); if (!this.graphCanvas) { return; } const nodes: { node: GraphNode; inputs: LLink[]; outputs: LLink[][]; }[] = []; for (const nodeId in this.graphCanvas.selected_nodes) { const node = this.graphCanvas.selected_nodes[nodeId] as GraphNode; nodes.push({ node, outputs: node.outputs.filter((o) => o.links).map((o) => o.links!.map((l) => this.graph!.links[l])), inputs: node.inputs.filter((o) => o.link).map((o) => this.graph!.links[o.link!]), }); } undoRedo.push({ common: () => { this.graphCanvas?.setDirty(true, true); if (this.graph) { this._cleanUselessLinks(this.graph); } }, undo: () => { nodes.forEach((n) => { this.graph?.add(n.node); n.inputs.forEach((i) => { const originNode = this.graph?.getNodeById(i.origin_id); originNode?.connect(i.origin_slot, n.node, i.target_slot); }); n.outputs.forEach((o) => { o.forEach((o2) => { const targetNode = this.graph?.getNodeById(o2.target_id); if (targetNode) { n.node.connect(o2.origin_slot, targetNode, o2.target_slot); } }); }); }); }, redo: () => { nodes.forEach((n) => this.graph?.remove(n.node)); }, }); } /** * Adds a new node to the graph. * @param event defines the right-click event. */ public async addNode(event: MouseEvent): Promise<void> { const type = await NodeCreator.Show(); if (!type) { return; } const node = LiteGraph.createNode(type) as GraphNode; node.pos = node._lastPosition = this.graphCanvas!.convertEventToCanvasOffset(event); undoRedo.push({ common: () => { this.graphCanvas?.setDirty(true, true); if (this.graph) { this._cleanUselessLinks(this.graph); } }, undo: () => this.graph?.remove(node), redo: () => this.graph?.add(node, false), }); } /** * Removes the given group. * @param group defines the reference to the group to remove. */ public removeGroup(group: LGraphGroup): void { undoRedo.push({ common: () => this.graphCanvas?.setDirty(true, true), undo: () => this.graph?.add(group), redo: () => this.graph?.remove(group), }); } /** * Adds a new group. * @param event defines the right-click event. */ public addGroup(event: MouseEvent): void { const group = new LGraphGroup(); const pos = this.graphCanvas!.convertEventToCanvasOffset(event); group.move(pos[0], pos[1], true); undoRedo.push({ common: () => this.graphCanvas?.setDirty(true, true), undo: () => this.graph?.remove(group), redo: () => this.graph?.add(group), }); } /** * Removes the given link from the graph. * @param link defines the reference to the link to remove. */ public removeLink(link: LLink): void { const originNode = this.graph?.getNodeById(link.origin_id); const targetNode = this.graph?.getNodeById(link.target_id); if (!originNode || !targetNode) { return; } undoRedo.push({ common: () => { this.graphCanvas?.setDirty(true, true); if (this.graph) { this._cleanUselessLinks(this.graph); } }, undo: () => originNode.connect(link.origin_slot, targetNode, link.target_slot), redo: () => this.graph?.removeLink(link.id), }); } /** * Called on the graph is being started. */ public async start(scene: Scene): Promise<void> { if (!this.graph || !this.graphCanvas) { return; } this.startGraph(this.graph, scene); } /** * Starts the given graph with the given scene. * @todo * @param graph defines the reference to the graph to start. * @param scene defines the reference to the scene attached to graph. */ public startGraph(graph: LGraph, scene: Scene): void { graph.hasPaused = false; graph["scene"] = scene; graph.status = LGraph.STATUS_RUNNING; const allNodes = this.getAllNodes(graph); allNodes.forEach((n) => n.onStart()); const sceneNodes: (Node | Scene)[] = [ scene, ...scene.meshes, ...scene.lights, ...scene.cameras, ...scene.transformNodes, ]; const attachedSceneNodes = sceneNodes.filter((n) => { return n.metadata?.script?.name === this._editor.linkPath; }); let running = false; const intervalId = setInterval(async () => { if (NodeUtils.PausedNode !== this._pausedNode) { this._pausedNode = NodeUtils.PausedNode; this._editor.callStack.refresh(); } if (graph.hasPaused) { return; } if (running) { return; } running = true; // Update execution order const executionNodes = graph["_nodes_executable"] ? graph["_nodes_executable"] : graph["_nodes"]; const startNodes: StartGameEvent[] = []; const tickNodes: TickGameEvent[] = []; for (let i = 0; i < executionNodes.length; i++) { const n = executionNodes[i]; if (n instanceof StartGameEvent) { executionNodes.splice(i, 1); startNodes.push(n); i--; } if (n instanceof TickGameEvent) { executionNodes.splice(i, 1); tickNodes.push(n); i--; } } startNodes.forEach((n) => executionNodes.push(n)); tickNodes.forEach((n) => executionNodes.push(n)); if (!attachedSceneNodes.length) { return graph.runStep(); } const promises: Promise<void>[] = []; attachedSceneNodes.forEach((n, i) => { promises.push(new Promise<void>((resolve) => { setTimeout(() => { graph["attachedNode"] = n; graph.runStep(); resolve(); }, i); })); }); await Promise.all(promises); running = false; }, 0) as any; this._startedGraphInvervals.push(intervalId); this._startedGraphs.push(graph); } /** * Stops the graph. */ public stop(): void { this._startedGraphInvervals.forEach((i) => { clearInterval(i); }); this._startedGraphInvervals = []; this._startedGraphs.forEach((graph) => { graph.status = LGraph.STATUS_STOPPED; this.getAllNodes(graph).forEach((n) => n.onStop()); graph.hasPaused = false; }); this._startedGraphs = []; } /** * Refreshes the graph. */ public refresh(): void { this.graphCanvas?.setDirty(true, true); } /** * Returns the list of all available nodes of the given graph. * @param graph defines the optional graph where to get all its nodes. */ public getAllNodes(graph?: LGraph): GraphNode[] { return (graph ?? this.graph!)["_nodes"] as GraphNode[]; } /** * Returns the list of all available groups of the given graph. * @param graph defines the optional graph where to get all its groups. */ public getAllGroups(graph?: LGraph): LGraphGroup[] { return (graph ?? this.graph!)["_groups"] as LGraphGroup[]; } /** * Returns the list of all available links of the given graph. * @param graph defines the optional graph where to get all its links. */ public getAllLinks(graph?: LGraph): LLink[] { return Object.keys((graph ?? this.graph!).links).map((key) => (graph ?? this.graph!).links[key]); } /** * Checks the graph. */ private _checkGraph(): void { const check = GraphCodeGenerator._GenerateCode(this.graph!); if (check.error) { check.error.node.color = "#ff2222"; } else { this.getAllNodes().forEach((n) => NodeUtils.SetColor(n)); } } /** * Binds all the window events. */ private _bindEvents(): void { window.addEventListener("focus", () => this._updateSceneNodesLists()); } /** * Updates the list of nodes in the scene. */ private async _updateSceneNodesLists(): Promise<void> { const meshes = await IPCTools.ExecuteEditorFunction<IMeshResult[]>("sceneUtils.getAllMeshes"); Mesh.Meshes = GetMesh.Meshes = meshes.data.map((d) => ({ name: d.name, type: d.type })); const cameras = await IPCTools.ExecuteEditorFunction<INodeResult[]>("sceneUtils.getAllCameras"); Camera.Cameras = GetCamera.Cameras = cameras.data.map((d) => d.name); const sounds = await IPCTools.ExecuteEditorFunction<string[]>("sceneUtils.getAllSounds"); Sound.Sounds = sounds.data; const lights = await IPCTools.ExecuteEditorFunction<INodeResult[]>("sceneUtils.getAllLights"); Light.Lights = GetLight.Lights = lights.data.map((l) => l.name); const transformNodes = await IPCTools.ExecuteEditorFunction<INodeResult[]>("sceneUtils.getAllTransformNodes"); TransformNode.TransformNodes = transformNodes.data.map((l) => l.name); const animationGroups = await IPCTools.ExecuteEditorFunction<string[]>("sceneUtils.getAllAnimationGroups"); AnimationGroup.Groups = animationGroups.data; const particleSystems = await IPCTools.ExecuteEditorFunction<INodeResult[]>("sceneUtils.getAllParticleSystems"); ParticleSystem.ParticleSystems = particleSystems.data.map((ps) => ps.name); const textures = await IPCTools.ExecuteEditorFunction<IAssetResult[]>("sceneUtils.getAllTextures"); Texture.Textures = textures.data.map((t) => ({ name: t.name, base64: t.base64 })); const materials = await IPCTools.ExecuteEditorFunction<IMaterialResult[]>("sceneUtils.getAllMaterials"); Material.Materials = materials.data.map((m) => ({ name: m.name, base64: m.base64, type: m.type })); } /** * Handles the connection change event. */ private _handleConnectionChange(graph: LGraph): void { const connectionChange = graph.connectionChange; graph.connectionChange = (n) => { connectionChange.call(this.graph, n); this._checkGraph(); } } /** * Handles the node added event. */ private _handleNodeAdded(graph: LGraph): void { graph.onNodeAdded = () => { this._checkGraph(); }; } /** * Handles the show search box event. */ private _handleShowSearchBox(graphCanvas: LGraphCanvas): void { graphCanvas.showSearchBox = (e: MouseEvent) => { setTimeout(() => this.addNode(e), 100); }; } /** * Handles the link error event. */ private _handleLinkError(graphCanvas: LGraphCanvas): void { graphCanvas.notifyLinkError = (errorType: ELinkErrorType) => { switch (errorType) { case ELinkErrorType.MultipleEvent: Alert.Show("Can't connect nodes", "Triggerable links can't be parallelized, they must be linear by chaining actions."); break; default: break; } }; } /** * Handles the graph canvas events. */ private _handleGraphCanvasEvents(graphCanvas: LGraphCanvas): void { graphCanvas.canvas.addEventListener("mousemove", () => { this.graphCanvas!.dirty_bgcanvas = true; this.graphCanvas!.dirty_canvas = true; }); graphCanvas.canvas.addEventListener("mouseover", () => this._canvasFocused = true); graphCanvas.canvas.addEventListener("mouseout", () => this._canvasFocused = false); graphCanvas.canvas.addEventListener("click", (e) => { const pos = this.graphCanvas!.convertEventToCanvasOffset(e); const node = this.graph?.getNodeOnPos(pos[0], pos[1]) as Undefinable<GraphNode>; if (node) { return this._editor.inspector.setNode(node); } const group = this.graph?.getGroupOnPos(pos[0], pos[1]) as Undefinable<LGraphGroup>; if (group) { return this._editor.inspector.setGroup(group); } }); graphCanvas.canvas.addEventListener("dblclick", (e) => { const pos = this.graphCanvas!.convertEventToCanvasOffset(e); const node = this.graph?.getNodeOnPos(pos[0], pos[1]) as Undefinable<GraphNode>; if (node && node instanceof GraphNode) { node.focusOn(); } }); document.addEventListener("keydown", (event) => { if (!this._canvasFocused) { return; } // Copy/paste if (event.key === "c" && event.ctrlKey) { return this.graphCanvas?.copyToClipboard(); } if (event.key === "v" && event.ctrlKey) { return this.graphCanvas?.pasteFromClipboard(); } // Del if (event.keyCode === 46) { return this.removeNode(); } }); } /** * Handles the graph canvas context menu event. */ private _handleProcessContextMenu(graphCanvas: LGraphCanvas): void { graphCanvas.processContextMenu = (n: GraphNode, e: MouseEvent) => { if (n) { const slot = n.getSlotInPosition(e["canvasX"], e["canvasY"]); if (slot?.input?.removable) { return GraphContextMenu.ShowSlotContextMenu(n, slot.slot, e); } return GraphContextMenu.ShowNodeContextMenu(e, this); } const pos = this.graphCanvas!.convertEventToCanvasOffset(e); const group = this.graph?.getGroupOnPos(pos[0], pos[1]); GraphContextMenu.ShowGraphContextMenu(e, this, group!); }; } /** * Handles the graph canvas link contet menu event. */ private _handleLinkContextMenu(graphCanvas: LGraphCanvas): void { graphCanvas.showLinkMenu = (l, e) => { GraphContextMenu.ShowLinkContextMenu(l, e, this); return false; }; } /** * Handles the graph canvas prompt event. */ private _handlePrompt(graphCanvas: LGraphCanvas): void { graphCanvas.prompt = (title, value, callback, event: MouseEvent) => { ContextMenu.show( <Menu className={Classes.DARK}> <Button disabled={true}>{title}</Button> <MenuDivider /> <EditableText disabled={false} value={value.toString()} multiline={true} confirmOnEnterKey={true} selectAllOnFocus={true} className={Classes.FILL} onConfirm={(v) => { const ctor = Tools.GetConstructorName(v).toLowerCase(); switch (ctor) { case "string": callback(v); break; case "number": callback(parseFloat(v)); break; } if (ContextMenu.isOpen()) { ContextMenu.hide(); } }} /> </Menu>, { left: event.clientX, top: event.clientY } ); return document.createElement("div"); }; } /** * Handles the graph canvas node moved event */ private _handleNodeMoved(graphCanvas: LGraphCanvas): void { graphCanvas.onNodeMoved = (n) => { const lastPosition = [n._lastPosition[0], n._lastPosition[1]]; const newPosition = [n.pos[0], n.pos[1]]; undoRedo.push({ common: () => this.graphCanvas?.setDirty(true, true), undo: () => { n.pos[0] = lastPosition[0]; n.pos[1] = lastPosition[1]; }, redo: () => { n.pos[0] = newPosition[0]; n.pos[1] = newPosition[1]; }, }); } } /** * Cleans the useless links of the graph. */ private _cleanUselessLinks(graph: LGraph): void { const oldLinks: string[] = []; for (const linkId in graph.links) { const link = graph.links[linkId]; const origin = graph.getNodeById(link.origin_id); const target = graph.getNodeById(link.target_id); if (!origin || !target) { oldLinks.push(linkId); } } oldLinks.forEach((ol) => delete graph.links[ol]); } }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { AssociateLensesCommand, AssociateLensesCommandInput, AssociateLensesCommandOutput, } from "./commands/AssociateLensesCommand"; import { CreateMilestoneCommand, CreateMilestoneCommandInput, CreateMilestoneCommandOutput, } from "./commands/CreateMilestoneCommand"; import { CreateWorkloadCommand, CreateWorkloadCommandInput, CreateWorkloadCommandOutput, } from "./commands/CreateWorkloadCommand"; import { CreateWorkloadShareCommand, CreateWorkloadShareCommandInput, CreateWorkloadShareCommandOutput, } from "./commands/CreateWorkloadShareCommand"; import { DeleteWorkloadCommand, DeleteWorkloadCommandInput, DeleteWorkloadCommandOutput, } from "./commands/DeleteWorkloadCommand"; import { DeleteWorkloadShareCommand, DeleteWorkloadShareCommandInput, DeleteWorkloadShareCommandOutput, } from "./commands/DeleteWorkloadShareCommand"; import { DisassociateLensesCommand, DisassociateLensesCommandInput, DisassociateLensesCommandOutput, } from "./commands/DisassociateLensesCommand"; import { GetAnswerCommand, GetAnswerCommandInput, GetAnswerCommandOutput } from "./commands/GetAnswerCommand"; import { GetLensReviewCommand, GetLensReviewCommandInput, GetLensReviewCommandOutput, } from "./commands/GetLensReviewCommand"; import { GetLensReviewReportCommand, GetLensReviewReportCommandInput, GetLensReviewReportCommandOutput, } from "./commands/GetLensReviewReportCommand"; import { GetLensVersionDifferenceCommand, GetLensVersionDifferenceCommandInput, GetLensVersionDifferenceCommandOutput, } from "./commands/GetLensVersionDifferenceCommand"; import { GetMilestoneCommand, GetMilestoneCommandInput, GetMilestoneCommandOutput, } from "./commands/GetMilestoneCommand"; import { GetWorkloadCommand, GetWorkloadCommandInput, GetWorkloadCommandOutput } from "./commands/GetWorkloadCommand"; import { ListAnswersCommand, ListAnswersCommandInput, ListAnswersCommandOutput } from "./commands/ListAnswersCommand"; import { ListLensesCommand, ListLensesCommandInput, ListLensesCommandOutput } from "./commands/ListLensesCommand"; import { ListLensReviewImprovementsCommand, ListLensReviewImprovementsCommandInput, ListLensReviewImprovementsCommandOutput, } from "./commands/ListLensReviewImprovementsCommand"; import { ListLensReviewsCommand, ListLensReviewsCommandInput, ListLensReviewsCommandOutput, } from "./commands/ListLensReviewsCommand"; import { ListMilestonesCommand, ListMilestonesCommandInput, ListMilestonesCommandOutput, } from "./commands/ListMilestonesCommand"; import { ListNotificationsCommand, ListNotificationsCommandInput, ListNotificationsCommandOutput, } from "./commands/ListNotificationsCommand"; import { ListShareInvitationsCommand, ListShareInvitationsCommandInput, ListShareInvitationsCommandOutput, } from "./commands/ListShareInvitationsCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { ListWorkloadsCommand, ListWorkloadsCommandInput, ListWorkloadsCommandOutput, } from "./commands/ListWorkloadsCommand"; import { ListWorkloadSharesCommand, ListWorkloadSharesCommandInput, ListWorkloadSharesCommandOutput, } from "./commands/ListWorkloadSharesCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { UpdateAnswerCommand, UpdateAnswerCommandInput, UpdateAnswerCommandOutput, } from "./commands/UpdateAnswerCommand"; import { UpdateLensReviewCommand, UpdateLensReviewCommandInput, UpdateLensReviewCommandOutput, } from "./commands/UpdateLensReviewCommand"; import { UpdateShareInvitationCommand, UpdateShareInvitationCommandInput, UpdateShareInvitationCommandOutput, } from "./commands/UpdateShareInvitationCommand"; import { UpdateWorkloadCommand, UpdateWorkloadCommandInput, UpdateWorkloadCommandOutput, } from "./commands/UpdateWorkloadCommand"; import { UpdateWorkloadShareCommand, UpdateWorkloadShareCommandInput, UpdateWorkloadShareCommandOutput, } from "./commands/UpdateWorkloadShareCommand"; import { UpgradeLensReviewCommand, UpgradeLensReviewCommandInput, UpgradeLensReviewCommandOutput, } from "./commands/UpgradeLensReviewCommand"; import { WellArchitectedClient } from "./WellArchitectedClient"; /** * <fullname>AWS Well-Architected Tool</fullname> * * <p>This is the <i>AWS Well-Architected Tool API Reference</i>. The AWS Well-Architected Tool API provides programmatic access to the * <a href="http://aws.amazon.com/well-architected-tool">AWS Well-Architected Tool</a> in the * <a href="https://console.aws.amazon.com/wellarchitected">AWS Management Console</a>. For information * about the AWS Well-Architected Tool, see the * <a href="https://docs.aws.amazon.com/wellarchitected/latest/userguide/intro.html">AWS Well-Architected Tool User Guide</a>.</p> */ export class WellArchitected extends WellArchitectedClient { /** * <p>Associate a lens to a workload.</p> */ public associateLenses( args: AssociateLensesCommandInput, options?: __HttpHandlerOptions ): Promise<AssociateLensesCommandOutput>; public associateLenses( args: AssociateLensesCommandInput, cb: (err: any, data?: AssociateLensesCommandOutput) => void ): void; public associateLenses( args: AssociateLensesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AssociateLensesCommandOutput) => void ): void; public associateLenses( args: AssociateLensesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AssociateLensesCommandOutput) => void), cb?: (err: any, data?: AssociateLensesCommandOutput) => void ): Promise<AssociateLensesCommandOutput> | void { const command = new AssociateLensesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Create a milestone for an existing workload.</p> */ public createMilestone( args: CreateMilestoneCommandInput, options?: __HttpHandlerOptions ): Promise<CreateMilestoneCommandOutput>; public createMilestone( args: CreateMilestoneCommandInput, cb: (err: any, data?: CreateMilestoneCommandOutput) => void ): void; public createMilestone( args: CreateMilestoneCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateMilestoneCommandOutput) => void ): void; public createMilestone( args: CreateMilestoneCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateMilestoneCommandOutput) => void), cb?: (err: any, data?: CreateMilestoneCommandOutput) => void ): Promise<CreateMilestoneCommandOutput> | void { const command = new CreateMilestoneCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Create a new workload.</p> * <p>The owner of a workload can share the workload with other AWS accounts and IAM users * in the same AWS Region. Only the owner of a workload can delete it.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/wellarchitected/latest/userguide/define-workload.html">Defining a Workload</a> in the * <i>AWS Well-Architected Tool User Guide</i>.</p> */ public createWorkload( args: CreateWorkloadCommandInput, options?: __HttpHandlerOptions ): Promise<CreateWorkloadCommandOutput>; public createWorkload( args: CreateWorkloadCommandInput, cb: (err: any, data?: CreateWorkloadCommandOutput) => void ): void; public createWorkload( args: CreateWorkloadCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateWorkloadCommandOutput) => void ): void; public createWorkload( args: CreateWorkloadCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateWorkloadCommandOutput) => void), cb?: (err: any, data?: CreateWorkloadCommandOutput) => void ): Promise<CreateWorkloadCommandOutput> | void { const command = new CreateWorkloadCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Create a workload share.</p> * <p>The owner of a workload can share it with other AWS accounts and IAM users in the same * AWS Region. Shared access to a workload is not removed until the workload invitation is * deleted.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/wellarchitected/latest/userguide/workloads-sharing.html">Sharing a Workload</a> in the * <i>AWS Well-Architected Tool User Guide</i>.</p> */ public createWorkloadShare( args: CreateWorkloadShareCommandInput, options?: __HttpHandlerOptions ): Promise<CreateWorkloadShareCommandOutput>; public createWorkloadShare( args: CreateWorkloadShareCommandInput, cb: (err: any, data?: CreateWorkloadShareCommandOutput) => void ): void; public createWorkloadShare( args: CreateWorkloadShareCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateWorkloadShareCommandOutput) => void ): void; public createWorkloadShare( args: CreateWorkloadShareCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateWorkloadShareCommandOutput) => void), cb?: (err: any, data?: CreateWorkloadShareCommandOutput) => void ): Promise<CreateWorkloadShareCommandOutput> | void { const command = new CreateWorkloadShareCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Delete an existing workload.</p> */ public deleteWorkload( args: DeleteWorkloadCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteWorkloadCommandOutput>; public deleteWorkload( args: DeleteWorkloadCommandInput, cb: (err: any, data?: DeleteWorkloadCommandOutput) => void ): void; public deleteWorkload( args: DeleteWorkloadCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteWorkloadCommandOutput) => void ): void; public deleteWorkload( args: DeleteWorkloadCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteWorkloadCommandOutput) => void), cb?: (err: any, data?: DeleteWorkloadCommandOutput) => void ): Promise<DeleteWorkloadCommandOutput> | void { const command = new DeleteWorkloadCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Delete a workload share.</p> */ public deleteWorkloadShare( args: DeleteWorkloadShareCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteWorkloadShareCommandOutput>; public deleteWorkloadShare( args: DeleteWorkloadShareCommandInput, cb: (err: any, data?: DeleteWorkloadShareCommandOutput) => void ): void; public deleteWorkloadShare( args: DeleteWorkloadShareCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteWorkloadShareCommandOutput) => void ): void; public deleteWorkloadShare( args: DeleteWorkloadShareCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteWorkloadShareCommandOutput) => void), cb?: (err: any, data?: DeleteWorkloadShareCommandOutput) => void ): Promise<DeleteWorkloadShareCommandOutput> | void { const command = new DeleteWorkloadShareCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Disassociate a lens from a workload.</p> * <note> * <p>The AWS Well-Architected Framework lens (<code>wellarchitected</code>) cannot be * removed from a workload.</p> * </note> */ public disassociateLenses( args: DisassociateLensesCommandInput, options?: __HttpHandlerOptions ): Promise<DisassociateLensesCommandOutput>; public disassociateLenses( args: DisassociateLensesCommandInput, cb: (err: any, data?: DisassociateLensesCommandOutput) => void ): void; public disassociateLenses( args: DisassociateLensesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DisassociateLensesCommandOutput) => void ): void; public disassociateLenses( args: DisassociateLensesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisassociateLensesCommandOutput) => void), cb?: (err: any, data?: DisassociateLensesCommandOutput) => void ): Promise<DisassociateLensesCommandOutput> | void { const command = new DisassociateLensesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Get the answer to a specific question in a workload review.</p> */ public getAnswer(args: GetAnswerCommandInput, options?: __HttpHandlerOptions): Promise<GetAnswerCommandOutput>; public getAnswer(args: GetAnswerCommandInput, cb: (err: any, data?: GetAnswerCommandOutput) => void): void; public getAnswer( args: GetAnswerCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetAnswerCommandOutput) => void ): void; public getAnswer( args: GetAnswerCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAnswerCommandOutput) => void), cb?: (err: any, data?: GetAnswerCommandOutput) => void ): Promise<GetAnswerCommandOutput> | void { const command = new GetAnswerCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Get lens review.</p> */ public getLensReview( args: GetLensReviewCommandInput, options?: __HttpHandlerOptions ): Promise<GetLensReviewCommandOutput>; public getLensReview( args: GetLensReviewCommandInput, cb: (err: any, data?: GetLensReviewCommandOutput) => void ): void; public getLensReview( args: GetLensReviewCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetLensReviewCommandOutput) => void ): void; public getLensReview( args: GetLensReviewCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetLensReviewCommandOutput) => void), cb?: (err: any, data?: GetLensReviewCommandOutput) => void ): Promise<GetLensReviewCommandOutput> | void { const command = new GetLensReviewCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Get lens review report.</p> */ public getLensReviewReport( args: GetLensReviewReportCommandInput, options?: __HttpHandlerOptions ): Promise<GetLensReviewReportCommandOutput>; public getLensReviewReport( args: GetLensReviewReportCommandInput, cb: (err: any, data?: GetLensReviewReportCommandOutput) => void ): void; public getLensReviewReport( args: GetLensReviewReportCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetLensReviewReportCommandOutput) => void ): void; public getLensReviewReport( args: GetLensReviewReportCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetLensReviewReportCommandOutput) => void), cb?: (err: any, data?: GetLensReviewReportCommandOutput) => void ): Promise<GetLensReviewReportCommandOutput> | void { const command = new GetLensReviewReportCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Get lens version differences.</p> */ public getLensVersionDifference( args: GetLensVersionDifferenceCommandInput, options?: __HttpHandlerOptions ): Promise<GetLensVersionDifferenceCommandOutput>; public getLensVersionDifference( args: GetLensVersionDifferenceCommandInput, cb: (err: any, data?: GetLensVersionDifferenceCommandOutput) => void ): void; public getLensVersionDifference( args: GetLensVersionDifferenceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetLensVersionDifferenceCommandOutput) => void ): void; public getLensVersionDifference( args: GetLensVersionDifferenceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetLensVersionDifferenceCommandOutput) => void), cb?: (err: any, data?: GetLensVersionDifferenceCommandOutput) => void ): Promise<GetLensVersionDifferenceCommandOutput> | void { const command = new GetLensVersionDifferenceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Get a milestone for an existing workload.</p> */ public getMilestone( args: GetMilestoneCommandInput, options?: __HttpHandlerOptions ): Promise<GetMilestoneCommandOutput>; public getMilestone(args: GetMilestoneCommandInput, cb: (err: any, data?: GetMilestoneCommandOutput) => void): void; public getMilestone( args: GetMilestoneCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetMilestoneCommandOutput) => void ): void; public getMilestone( args: GetMilestoneCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMilestoneCommandOutput) => void), cb?: (err: any, data?: GetMilestoneCommandOutput) => void ): Promise<GetMilestoneCommandOutput> | void { const command = new GetMilestoneCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Get an existing workload.</p> */ public getWorkload(args: GetWorkloadCommandInput, options?: __HttpHandlerOptions): Promise<GetWorkloadCommandOutput>; public getWorkload(args: GetWorkloadCommandInput, cb: (err: any, data?: GetWorkloadCommandOutput) => void): void; public getWorkload( args: GetWorkloadCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetWorkloadCommandOutput) => void ): void; public getWorkload( args: GetWorkloadCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetWorkloadCommandOutput) => void), cb?: (err: any, data?: GetWorkloadCommandOutput) => void ): Promise<GetWorkloadCommandOutput> | void { const command = new GetWorkloadCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>List of answers.</p> */ public listAnswers(args: ListAnswersCommandInput, options?: __HttpHandlerOptions): Promise<ListAnswersCommandOutput>; public listAnswers(args: ListAnswersCommandInput, cb: (err: any, data?: ListAnswersCommandOutput) => void): void; public listAnswers( args: ListAnswersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListAnswersCommandOutput) => void ): void; public listAnswers( args: ListAnswersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAnswersCommandOutput) => void), cb?: (err: any, data?: ListAnswersCommandOutput) => void ): Promise<ListAnswersCommandOutput> | void { const command = new ListAnswersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>List the available lenses.</p> */ public listLenses(args: ListLensesCommandInput, options?: __HttpHandlerOptions): Promise<ListLensesCommandOutput>; public listLenses(args: ListLensesCommandInput, cb: (err: any, data?: ListLensesCommandOutput) => void): void; public listLenses( args: ListLensesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListLensesCommandOutput) => void ): void; public listLenses( args: ListLensesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListLensesCommandOutput) => void), cb?: (err: any, data?: ListLensesCommandOutput) => void ): Promise<ListLensesCommandOutput> | void { const command = new ListLensesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>List lens review improvements.</p> */ public listLensReviewImprovements( args: ListLensReviewImprovementsCommandInput, options?: __HttpHandlerOptions ): Promise<ListLensReviewImprovementsCommandOutput>; public listLensReviewImprovements( args: ListLensReviewImprovementsCommandInput, cb: (err: any, data?: ListLensReviewImprovementsCommandOutput) => void ): void; public listLensReviewImprovements( args: ListLensReviewImprovementsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListLensReviewImprovementsCommandOutput) => void ): void; public listLensReviewImprovements( args: ListLensReviewImprovementsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListLensReviewImprovementsCommandOutput) => void), cb?: (err: any, data?: ListLensReviewImprovementsCommandOutput) => void ): Promise<ListLensReviewImprovementsCommandOutput> | void { const command = new ListLensReviewImprovementsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>List lens reviews.</p> */ public listLensReviews( args: ListLensReviewsCommandInput, options?: __HttpHandlerOptions ): Promise<ListLensReviewsCommandOutput>; public listLensReviews( args: ListLensReviewsCommandInput, cb: (err: any, data?: ListLensReviewsCommandOutput) => void ): void; public listLensReviews( args: ListLensReviewsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListLensReviewsCommandOutput) => void ): void; public listLensReviews( args: ListLensReviewsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListLensReviewsCommandOutput) => void), cb?: (err: any, data?: ListLensReviewsCommandOutput) => void ): Promise<ListLensReviewsCommandOutput> | void { const command = new ListLensReviewsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>List all milestones for an existing workload.</p> */ public listMilestones( args: ListMilestonesCommandInput, options?: __HttpHandlerOptions ): Promise<ListMilestonesCommandOutput>; public listMilestones( args: ListMilestonesCommandInput, cb: (err: any, data?: ListMilestonesCommandOutput) => void ): void; public listMilestones( args: ListMilestonesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListMilestonesCommandOutput) => void ): void; public listMilestones( args: ListMilestonesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListMilestonesCommandOutput) => void), cb?: (err: any, data?: ListMilestonesCommandOutput) => void ): Promise<ListMilestonesCommandOutput> | void { const command = new ListMilestonesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>List lens notifications.</p> */ public listNotifications( args: ListNotificationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListNotificationsCommandOutput>; public listNotifications( args: ListNotificationsCommandInput, cb: (err: any, data?: ListNotificationsCommandOutput) => void ): void; public listNotifications( args: ListNotificationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListNotificationsCommandOutput) => void ): void; public listNotifications( args: ListNotificationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListNotificationsCommandOutput) => void), cb?: (err: any, data?: ListNotificationsCommandOutput) => void ): Promise<ListNotificationsCommandOutput> | void { const command = new ListNotificationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>List the workload invitations.</p> */ public listShareInvitations( args: ListShareInvitationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListShareInvitationsCommandOutput>; public listShareInvitations( args: ListShareInvitationsCommandInput, cb: (err: any, data?: ListShareInvitationsCommandOutput) => void ): void; public listShareInvitations( args: ListShareInvitationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListShareInvitationsCommandOutput) => void ): void; public listShareInvitations( args: ListShareInvitationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListShareInvitationsCommandOutput) => void), cb?: (err: any, data?: ListShareInvitationsCommandOutput) => void ): Promise<ListShareInvitationsCommandOutput> | void { const command = new ListShareInvitationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>List the tags for a resource.</p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>List workloads. Paginated.</p> */ public listWorkloads( args: ListWorkloadsCommandInput, options?: __HttpHandlerOptions ): Promise<ListWorkloadsCommandOutput>; public listWorkloads( args: ListWorkloadsCommandInput, cb: (err: any, data?: ListWorkloadsCommandOutput) => void ): void; public listWorkloads( args: ListWorkloadsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListWorkloadsCommandOutput) => void ): void; public listWorkloads( args: ListWorkloadsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListWorkloadsCommandOutput) => void), cb?: (err: any, data?: ListWorkloadsCommandOutput) => void ): Promise<ListWorkloadsCommandOutput> | void { const command = new ListWorkloadsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>List the workload shares associated with the workload.</p> */ public listWorkloadShares( args: ListWorkloadSharesCommandInput, options?: __HttpHandlerOptions ): Promise<ListWorkloadSharesCommandOutput>; public listWorkloadShares( args: ListWorkloadSharesCommandInput, cb: (err: any, data?: ListWorkloadSharesCommandOutput) => void ): void; public listWorkloadShares( args: ListWorkloadSharesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListWorkloadSharesCommandOutput) => void ): void; public listWorkloadShares( args: ListWorkloadSharesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListWorkloadSharesCommandOutput) => void), cb?: (err: any, data?: ListWorkloadSharesCommandOutput) => void ): Promise<ListWorkloadSharesCommandOutput> | void { const command = new ListWorkloadSharesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds one or more tags to the specified resource.</p> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes specified tags from a resource.</p> * <p>To specify multiple tags, use separate <b>tagKeys</b> parameters, for example:</p> * <p> * <code>DELETE /tags/WorkloadArn?tagKeys=key1&tagKeys=key2</code> * </p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Update the answer to a specific question in a workload review.</p> */ public updateAnswer( args: UpdateAnswerCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateAnswerCommandOutput>; public updateAnswer(args: UpdateAnswerCommandInput, cb: (err: any, data?: UpdateAnswerCommandOutput) => void): void; public updateAnswer( args: UpdateAnswerCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateAnswerCommandOutput) => void ): void; public updateAnswer( args: UpdateAnswerCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateAnswerCommandOutput) => void), cb?: (err: any, data?: UpdateAnswerCommandOutput) => void ): Promise<UpdateAnswerCommandOutput> | void { const command = new UpdateAnswerCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Update lens review.</p> */ public updateLensReview( args: UpdateLensReviewCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateLensReviewCommandOutput>; public updateLensReview( args: UpdateLensReviewCommandInput, cb: (err: any, data?: UpdateLensReviewCommandOutput) => void ): void; public updateLensReview( args: UpdateLensReviewCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateLensReviewCommandOutput) => void ): void; public updateLensReview( args: UpdateLensReviewCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateLensReviewCommandOutput) => void), cb?: (err: any, data?: UpdateLensReviewCommandOutput) => void ): Promise<UpdateLensReviewCommandOutput> | void { const command = new UpdateLensReviewCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Update a workload invitation.</p> */ public updateShareInvitation( args: UpdateShareInvitationCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateShareInvitationCommandOutput>; public updateShareInvitation( args: UpdateShareInvitationCommandInput, cb: (err: any, data?: UpdateShareInvitationCommandOutput) => void ): void; public updateShareInvitation( args: UpdateShareInvitationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateShareInvitationCommandOutput) => void ): void; public updateShareInvitation( args: UpdateShareInvitationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateShareInvitationCommandOutput) => void), cb?: (err: any, data?: UpdateShareInvitationCommandOutput) => void ): Promise<UpdateShareInvitationCommandOutput> | void { const command = new UpdateShareInvitationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Update an existing workload.</p> */ public updateWorkload( args: UpdateWorkloadCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateWorkloadCommandOutput>; public updateWorkload( args: UpdateWorkloadCommandInput, cb: (err: any, data?: UpdateWorkloadCommandOutput) => void ): void; public updateWorkload( args: UpdateWorkloadCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateWorkloadCommandOutput) => void ): void; public updateWorkload( args: UpdateWorkloadCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateWorkloadCommandOutput) => void), cb?: (err: any, data?: UpdateWorkloadCommandOutput) => void ): Promise<UpdateWorkloadCommandOutput> | void { const command = new UpdateWorkloadCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Update a workload share.</p> */ public updateWorkloadShare( args: UpdateWorkloadShareCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateWorkloadShareCommandOutput>; public updateWorkloadShare( args: UpdateWorkloadShareCommandInput, cb: (err: any, data?: UpdateWorkloadShareCommandOutput) => void ): void; public updateWorkloadShare( args: UpdateWorkloadShareCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateWorkloadShareCommandOutput) => void ): void; public updateWorkloadShare( args: UpdateWorkloadShareCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateWorkloadShareCommandOutput) => void), cb?: (err: any, data?: UpdateWorkloadShareCommandOutput) => void ): Promise<UpdateWorkloadShareCommandOutput> | void { const command = new UpdateWorkloadShareCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Upgrade lens review.</p> */ public upgradeLensReview( args: UpgradeLensReviewCommandInput, options?: __HttpHandlerOptions ): Promise<UpgradeLensReviewCommandOutput>; public upgradeLensReview( args: UpgradeLensReviewCommandInput, cb: (err: any, data?: UpgradeLensReviewCommandOutput) => void ): void; public upgradeLensReview( args: UpgradeLensReviewCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpgradeLensReviewCommandOutput) => void ): void; public upgradeLensReview( args: UpgradeLensReviewCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpgradeLensReviewCommandOutput) => void), cb?: (err: any, data?: UpgradeLensReviewCommandOutput) => void ): Promise<UpgradeLensReviewCommandOutput> | void { const command = new UpgradeLensReviewCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import {describe, it, beforeEach, afterEach} from 'mocha'; import * as assert from 'assert'; import {execSync} from 'child_process'; import * as path from 'path'; import rimraf from 'rimraf'; import {core} from '../src/core'; import {OWL_BOT_IGNORE} from '../src/labels'; import nock from 'nock'; import * as sinon from 'sinon'; import {mkdirSync, writeFileSync} from 'fs'; import * as protos from '@google-cloud/cloudbuild/build/protos/protos'; import {CloudBuildClient} from '@google-cloud/cloudbuild'; import {Octokit} from '@octokit/rest'; import {OctokitType} from '../src/octokit-util'; import {OwlBotLock} from '../src/config-files'; nock.disableNetConnect(); const sandbox = sinon.createSandbox(); /** * Stubs out core.getGitHubShortLivedAccessToken and * core.getAuthenticatedOctokit with test values. */ function initSandbox(prData: unknown) { sandbox.stub(core, 'getGitHubShortLivedAccessToken').resolves({ token: 'abc123', expires_at: '2021-01-13T23:37:43.707Z', permissions: {}, repository_selection: 'included', }); sandbox.stub(core, 'getAuthenticatedOctokit').resolves({ pulls: { get() { return prData; }, }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any as InstanceType<typeof Octokit>); } async function getOwlBotLock( repoFull: string, pullNumber: number, octokit: OctokitType ): Promise<OwlBotLock | undefined> { const lockText = await core.fetchOwlBotLock(repoFull, pullNumber, octokit); return undefined === lockText ? undefined : core.parseOwlBotLock(lockText); } function newPrData(labels: string[] = []): unknown { const prData = { data: { head: { ref: 'my-feature-branch', repo: { full_name: 'bcoe/example', }, }, labels: labels.map(name => { return {name}; }), }, }; return prData; } describe('core', () => { afterEach(() => { sandbox.restore(); }); describe('getAccessTokenURL', () => { it('returns URI for token endpoint', () => { const uri = core.getAccessTokenURL(12345); assert.strictEqual( uri, 'https://api.github.com/app/installations/12345/access_tokens' ); }); }); describe('triggerBuild', () => { it('returns with success if build succeeds', async () => { initSandbox(newPrData()); const successfulBuild = { status: 'SUCCESS', steps: [ { status: 'SUCCESS', name: 'foo step', }, ], }; let triggerRequest: | protos.google.devtools.cloudbuild.v1.IRunBuildTriggerRequest | undefined = undefined; sandbox.stub(core, 'getCloudBuildInstance').returns({ runBuildTrigger( request: protos.google.devtools.cloudbuild.v1.IRunBuildTriggerRequest ) { triggerRequest = request; return [ { metadata: { build: { id: 'abc123', }, }, }, ]; }, getBuild() { return [successfulBuild]; }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any as CloudBuildClient); const build = await core.triggerPostProcessBuild({ image: 'node@abc123', appId: 12345, privateKey: 'abc123', installation: 12345, repo: 'bcoe/example', pr: 99, project: 'fake-project', trigger: 'abc123', }); assert.ok(triggerRequest); assert.strictEqual(build!.conclusion, 'success'); assert.strictEqual(build!.summary, 'successfully ran 1 steps 🎉!'); }); it( "doesn't trigger build when labeled with " + OWL_BOT_IGNORE, async () => { initSandbox(newPrData([OWL_BOT_IGNORE])); const build = await core.triggerPostProcessBuild({ image: 'node@abc123', appId: 12345, privateKey: 'abc123', installation: 12345, repo: 'bcoe/example', pr: 99, project: 'fake-project', trigger: 'abc123', }); assert.strictEqual(build, null); } ); it('returns with failure if build fails', async () => { initSandbox(newPrData()); const successfulBuild = { status: 'FAILURE', steps: [ { status: 'FAILURE', name: 'foo step', }, ], }; let triggerRequest: | protos.google.devtools.cloudbuild.v1.IRunBuildTriggerRequest | undefined = undefined; sandbox.stub(core, 'getCloudBuildInstance').returns({ runBuildTrigger( request: protos.google.devtools.cloudbuild.v1.IRunBuildTriggerRequest ) { triggerRequest = request; return [ { metadata: { build: { id: 'abc123', }, }, }, ]; }, getBuild() { return [successfulBuild]; }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any as CloudBuildClient); const build = await core.triggerPostProcessBuild({ image: 'node@abc123', appId: 12345, privateKey: 'abc123', installation: 12345, repo: 'bcoe/example', pr: 99, project: 'fake-project', trigger: 'abc123', }); assert.ok(triggerRequest); assert.strictEqual(build!.conclusion, 'failure'); assert.strictEqual(build!.summary, '1 steps failed 🙁'); }); }); describe('getOwlBotLock', () => { it('reads .OwlBot.lock.yaml and returns parsed YAML', async () => { const prData = { data: { head: { ref: 'my-feature-branch', repo: { full_name: 'bcoe/example', }, }, }, }; const config = `docker: image: node digest: sha256:9205bb385656cd196f5303b03983282c95c2dfab041d275465c525b501574e5c`; const content = { data: { content: Buffer.from(config, 'utf8').toString('base64'), encoding: 'base64', }, }; const octokit = { pulls: { get() { return prData; }, }, repos: { getContent() { return content; }, }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any as InstanceType<typeof Octokit>; const lock = await getOwlBotLock('bcoe/test', 22, octokit); assert.strictEqual(lock!.docker.image, 'node'); assert.strictEqual( lock!.docker.digest, 'sha256:9205bb385656cd196f5303b03983282c95c2dfab041d275465c525b501574e5c' ); }); it('throws error if config is invalid', async () => { const prData = { data: { head: { ref: 'my-feature-branch', repo: { full_name: 'bcoe/example', }, }, }, }; const config = `no-docker-key: image: node digest: sha256:9205bb385656cd196f5303b03983282c95c2dfab041d275465c525b501574e5c`; const content = { data: { content: Buffer.from(config, 'utf8').toString('base64'), encoding: 'base64', }, }; const octokit = { pulls: { get() { return prData; }, }, repos: { getContent() { return content; }, }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any as InstanceType<typeof Octokit>; assert.rejects(getOwlBotLock('bcoe/test', 22, octokit)); }); it('returns "undefined" if config not found', async () => { const prData = { data: { head: { ref: 'my-feature-branch', repo: { full_name: 'bcoe/example', }, }, }, }; const octokit = { pulls: { get() { return prData; }, }, repos: { getContent() { throw Object.assign(Error('Not Found'), {status: 404}); }, }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any as InstanceType<typeof Octokit>; const config = await getOwlBotLock('bcoe/test', 22, octokit); assert.strictEqual(config, undefined); }); }); describe('getFilesModifiedBySha', () => { const gitFixture = 'tmp'; const testRepo = 'test-repo'; before(() => { // If we're in a CI/CD environment set git username and email: if (process.env.CI) { execSync('git config --global user.email "beepboop@example.com"'); execSync('git config --global user.name "HAL 9000"'); } }); beforeEach(() => { rimraf.sync(gitFixture); mkdirSync(gitFixture, {recursive: true}); }); afterEach(() => { rimraf.sync(gitFixture); }); it('returns files added at sha', async () => { // Initialize git repo: execSync(`git init ${testRepo}`, {cwd: gitFixture}); // Write a couple files: writeFileSync(path.join(gitFixture, testRepo, 'a.txt'), 'hello', 'utf8'); writeFileSync(path.join(gitFixture, testRepo, 'b.txt'), 'hello', 'utf8'); // Commit the changes: const fullRepoPath = path.join(gitFixture, testRepo); execSync('git add .', {cwd: fullRepoPath}); execSync('git commit -a -m "feat: add two files"', { cwd: fullRepoPath, }); // Grab the current sha: const sha = execSync('git rev-parse HEAD', { cwd: fullRepoPath, }).toString('utf8'); const filesModified = await core.getFilesModifiedBySha(fullRepoPath, sha); assert.deepStrictEqual(filesModified, ['b.txt', 'a.txt']); }); it('returns files removed at sha', async () => { // Initialize git repo: execSync(`git init ${testRepo}`, {cwd: gitFixture}); // Write a couple files: writeFileSync(path.join(gitFixture, testRepo, 'a.txt'), 'hello', 'utf8'); writeFileSync(path.join(gitFixture, testRepo, 'b.txt'), 'hello', 'utf8'); // Commit the changes: const fullRepoPath = path.join(gitFixture, testRepo); execSync('git add .', {cwd: fullRepoPath}); execSync('git commit -a -m "feat: add two files"', { cwd: fullRepoPath, }); // Remove a file: rimraf.sync(path.join(gitFixture, testRepo, 'a.txt')); // Commit the change: execSync('git add .', {cwd: fullRepoPath}); execSync('git commit -a -m "fix: removed tricksy file"', { cwd: fullRepoPath, }); // Grab the current sha: const sha = execSync('git rev-parse HEAD', { cwd: fullRepoPath, }).toString('utf8'); const filesModified = await core.getFilesModifiedBySha(fullRepoPath, sha); assert.deepStrictEqual(filesModified, ['a.txt']); }); it('returns files added and removed at same sha', async () => { // Initialize git repo: execSync(`git init ${testRepo}`, {cwd: gitFixture}); // Write a couple files: writeFileSync(path.join(gitFixture, testRepo, 'a.txt'), 'hello', 'utf8'); writeFileSync(path.join(gitFixture, testRepo, 'b.txt'), 'hello', 'utf8'); // Commit the changes: const fullRepoPath = path.join(gitFixture, testRepo); execSync('git add .', {cwd: fullRepoPath}); execSync('git commit -a -m "feat: add two files"', { cwd: fullRepoPath, }); // Remove a file: rimraf.sync(path.join(gitFixture, testRepo, 'a.txt')); // Add a file: writeFileSync( path.join(gitFixture, testRepo, 'c.txt'), 'goodbye', 'utf8' ); // Commit the change: execSync('git add .', {cwd: fullRepoPath}); execSync('git commit -a -m "feat: remove and add file"', { cwd: fullRepoPath, }); // Grab the current sha: const sha = execSync('git rev-parse HEAD', { cwd: fullRepoPath, }).toString('utf8'); const filesModified = await core.getFilesModifiedBySha(fullRepoPath, sha); assert.deepStrictEqual(filesModified, ['c.txt', 'a.txt']); }); }); describe('hasOwlBotLoop', () => { /** A helper function for simulating a date-ordered list of commits */ function generateCommitList(commitOrderByAuthor: string[]) { const commits: { author: { login: string; }; commit: { author: { date: string; }; }; }[] = []; for (let i = 0; i < commitOrderByAuthor.length; i++) { commits.push({ author: { login: commitOrderByAuthor[i], }, commit: { author: { date: new Date(i).toISOString(), }, }, }); } return commits; } it('returns false if post processor not looping', async () => { // Two PRs from gcf-owl-bot[bot] are expected: a PR to // submit files, followed by a commit from the post processor: const commits = generateCommitList([ 'gcf-owl-bot[bot]', 'gcf-owl-bot[bot]', 'bcoe', 'gcf-owl-bot[bot]', 'gcf-owl-bot[bot]', 'gcf-owl-bot[bot]', ]); const githubMock = nock('https://api.github.com') .get('/repos/bcoe/foo/pulls/22/commits?per_page=100') .reply(200, commits); const loop = await core.hasOwlBotLoop('bcoe', 'foo', 22, new Octokit()); assert.strictEqual(loop, false); githubMock.done(); }); it('returns true if post processor looping', async () => { const commits = generateCommitList([ 'bcoe', 'gcf-owl-bot[bot]', 'bcoe', 'gcf-owl-bot[bot]', 'gcf-owl-bot[bot]', 'gcf-owl-bot[bot]', 'gcf-owl-bot[bot]', 'gcf-owl-bot[bot]', // this commit should trigger the breaker ]); const githubMock = nock('https://api.github.com') .get('/repos/bcoe/foo/pulls/22/commits?per_page=100') .reply(200, commits); const loop = await core.hasOwlBotLoop('bcoe', 'foo', 22, new Octokit()); assert.strictEqual(loop, true); githubMock.done(); }); it('returns false if there was a loop in the past, but not within the last few commits', async () => { const commits = generateCommitList([ 'bcoe', 'gcf-owl-bot[bot]', 'bcoe', 'gcf-owl-bot[bot]', 'gcf-owl-bot[bot]', 'gcf-owl-bot[bot]', 'gcf-owl-bot[bot]', 'gcf-owl-bot[bot]', 'bcoe', // this commit should break the loop ]); const githubMock = nock('https://api.github.com') .get('/repos/bcoe/foo/pulls/22/commits?per_page=100') .reply(200, commits); const loop = await core.hasOwlBotLoop('bcoe', 'foo', 22, new Octokit()); assert.strictEqual(loop, false); githubMock.done(); }); it('returns false if there were less than the number of commits from the circuit breaker', async () => { const commits = generateCommitList(['gcf-owl-bot[bot]']); const githubMock = nock('https://api.github.com') .get('/repos/bcoe/foo/pulls/22/commits?per_page=100') .reply(200, commits); const loop = await core.hasOwlBotLoop('bcoe', 'foo', 22, new Octokit()); assert.strictEqual(loop, false); githubMock.done(); }); it('returns false if there were 0 commits in the PR', async () => { const githubMock = nock('https://api.github.com') .get('/repos/bcoe/foo/pulls/22/commits?per_page=100') .reply(200, []); const loop = await core.hasOwlBotLoop('bcoe', 'foo', 22, new Octokit()); assert.strictEqual(loop, false); githubMock.done(); }); }); });
the_stack
module android.support.v4.widget { import Canvas = android.graphics.Canvas; import Paint = android.graphics.Paint; import PixelFormat = android.graphics.PixelFormat; import Rect = android.graphics.Rect; import Drawable = android.graphics.drawable.Drawable; import SystemClock = android.os.SystemClock; import Gravity = android.view.Gravity; import KeyEvent = android.view.KeyEvent; import MotionEvent = android.view.MotionEvent; import View = android.view.View; import ViewGroup = android.view.ViewGroup; import ViewParent = android.view.ViewParent; import Integer = java.lang.Integer; import Runnable = java.lang.Runnable; import ViewDragHelper = android.support.v4.widget.ViewDragHelper; import AttrBinder = androidui.attr.AttrBinder; import Context = android.content.Context; /** * DrawerLayout acts as a top-level container for window content that allows for * interactive "drawer" views to be pulled out from the edge of the window. * * <p>Drawer positioning and layout is controlled using the <code>android:layout_gravity</code> * attribute on child views corresponding to which side of the view you want the drawer * to emerge from: left or right. (Or start/end on platform versions that support layout direction.) * </p> * * <p>To use a DrawerLayout, position your primary content view as the first child with * a width and height of <code>match_parent</code>. Add drawers as child views after the main * content view and set the <code>layout_gravity</code> appropriately. Drawers commonly use * <code>match_parent</code> for height with a fixed width.</p> * * <p>{@link DrawerListener} can be used to monitor the state and motion of drawer views. * Avoid performing expensive operations such as layout during animation as it can cause * stuttering; try to perform expensive operations during the {@link #STATE_IDLE} state. * {@link SimpleDrawerListener} offers default/no-op implementations of each callback method.</p> * * <p>As per the Android Design guide, any drawers positioned to the left/start should * always contain content for navigating around the application, whereas any drawers * positioned to the right/end should always contain actions to take on the current content. * This preserves the same navigation left, actions right structure present in the Action Bar * and elsewhere.</p> */ export class DrawerLayout extends ViewGroup { private static TAG:string = "DrawerLayout"; /** * Indicates that any drawers are in an idle, settled state. No animation is in progress. */ static STATE_IDLE:number = ViewDragHelper.STATE_IDLE; /** * Indicates that a drawer is currently being dragged by the user. */ static STATE_DRAGGING:number = ViewDragHelper.STATE_DRAGGING; /** * Indicates that a drawer is in the process of settling to a final position. */ static STATE_SETTLING:number = ViewDragHelper.STATE_SETTLING; /** * The drawer is unlocked. */ static LOCK_MODE_UNLOCKED:number = 0; /** * The drawer is locked closed. The user may not open it, though * the app may open it programmatically. */ static LOCK_MODE_LOCKED_CLOSED:number = 1; /** * The drawer is locked open. The user may not close it, though the app * may close it programmatically. */ static LOCK_MODE_LOCKED_OPEN:number = 2; // dp private static MIN_DRAWER_MARGIN:number = 64; private static DEFAULT_SCRIM_COLOR:number = 0x99000000; /** * Length of time to delay before peeking the drawer. */ // ms static PEEK_DELAY:number = 160; /** * Minimum velocity that will be detected as a fling */ // dips per second private static MIN_FLING_VELOCITY:number = 400; /** * Experimental feature. */ static ALLOW_EDGE_LOCK:boolean = false; private static CHILDREN_DISALLOW_INTERCEPT:boolean = true; private static TOUCH_SLOP_SENSITIVITY:number = 1.; private mMinDrawerMargin:number = 0; private mScrimColor:number = DrawerLayout.DEFAULT_SCRIM_COLOR; private mScrimOpacity:number = 0; private mScrimPaint:Paint = new Paint(); private mLeftDragger:ViewDragHelper; private mRightDragger:ViewDragHelper; private mLeftCallback:DrawerLayout.ViewDragCallback; private mRightCallback:DrawerLayout.ViewDragCallback; private mDrawerState:number = 0; private mInLayout:boolean; private mFirstLayout:boolean = true; private mLockModeLeft:number = 0; private mLockModeRight:number = 0; private mDisallowInterceptRequested:boolean; private mChildrenCanceledTouch:boolean; private mListener:DrawerLayout.DrawerListener; private mInitialMotionX:number = 0; private mInitialMotionY:number = 0; private mShadowLeft:Drawable; private mShadowRight:Drawable; constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle?:Map<string, string>) { super(context, bindElement, defStyle); const density:number = this.getResources().getDisplayMetrics().density; this.mMinDrawerMargin = Math.floor((DrawerLayout.MIN_DRAWER_MARGIN * density + 0.5)); const minVel:number = DrawerLayout.MIN_FLING_VELOCITY * density; this.mLeftCallback = new DrawerLayout.ViewDragCallback(this, Gravity.LEFT); this.mRightCallback = new DrawerLayout.ViewDragCallback(this, Gravity.RIGHT); this.mLeftDragger = ViewDragHelper.create(this, DrawerLayout.TOUCH_SLOP_SENSITIVITY, this.mLeftCallback); this.mLeftDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT); this.mLeftDragger.setMinVelocity(minVel); this.mLeftCallback.setDragger(this.mLeftDragger); this.mRightDragger = ViewDragHelper.create(this, DrawerLayout.TOUCH_SLOP_SENSITIVITY, this.mRightCallback); this.mRightDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_RIGHT); this.mRightDragger.setMinVelocity(minVel); this.mRightCallback.setDragger(this.mRightDragger); // So that we can catch the back button this.setFocusableInTouchMode(true); //ViewCompat.setAccessibilityDelegate(this, new DrawerLayout.AccessibilityDelegate(this)); this.setMotionEventSplittingEnabled(false); } /** * Set a simple drawable used for the left or right shadow. * The drawable provided must have a nonzero intrinsic width. * * @param shadowDrawable Shadow drawable to use at the edge of a drawer * @param gravity Which drawer the shadow should apply to */ setDrawerShadow(shadowDrawable:Drawable, gravity:number):void { /* * TODO Someone someday might want to set more complex drawables here. * They're probably nuts, but we might want to consider registering callbacks, * setting states, etc. properly. */ const absGravity:number = Gravity.getAbsoluteGravity(gravity, this.getLayoutDirection()); if ((absGravity & Gravity.LEFT) == Gravity.LEFT) { this.mShadowLeft = shadowDrawable; this.invalidate(); } if ((absGravity & Gravity.RIGHT) == Gravity.RIGHT) { this.mShadowRight = shadowDrawable; this.invalidate(); } } ///** // * Set a simple drawable used for the left or right shadow. // * The drawable provided must have a nonzero intrinsic width. // * // * @param resId Resource id of a shadow drawable to use at the edge of a drawer // * @param gravity Which drawer the shadow should apply to // */ //setDrawerShadow(resId:number, gravity:number):void { // this.setDrawerShadow(this.getResources().getDrawable(resId), gravity); //} /** * Set a color to use for the scrim that obscures primary content while a drawer is open. * * @param color Color to use in 0xAARRGGBB format. */ setScrimColor(color:number):void { this.mScrimColor = color; this.invalidate(); } /** * Set a listener to be notified of drawer events. * * @param listener Listener to notify when drawer events occur * @see DrawerListener */ setDrawerListener(listener:DrawerLayout.DrawerListener):void { this.mListener = listener; } ///** // * Enable or disable interaction with all drawers. // * // * <p>This allows the application to restrict the user's ability to open or close // * any drawer within this layout. DrawerLayout will still respond to calls to // * {@link #openDrawer(int)}, {@link #closeDrawer(int)} and friends if a drawer is locked.</p> // * // * <p>Locking drawers open or closed will implicitly open or close // * any drawers as appropriate.</p> // * // * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, // * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. // */ //setDrawerLockMode(lockMode:number):void { // this.setDrawerLockMode(lockMode, Gravity.LEFT); // this.setDrawerLockMode(lockMode, Gravity.RIGHT); //} /** * Enable or disable interaction with the given drawer. * * <p>This allows the application to restrict the user's ability to open or close * the given drawer. DrawerLayout will still respond to calls to {@link #openDrawer(int)}, * {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking a drawer open or closed will implicitly open or close * that drawer as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. * @param edgeGravity Gravity.LEFT, RIGHT, START or END. * Expresses which drawer to change the mode for. * * @see #LOCK_MODE_UNLOCKED * @see #LOCK_MODE_LOCKED_CLOSED * @see #LOCK_MODE_LOCKED_OPEN */ setDrawerLockMode(lockMode:number, edgeGravityOrView?:number|View):void { if(edgeGravityOrView==null){ this.setDrawerLockMode(lockMode, Gravity.LEFT); this.setDrawerLockMode(lockMode, Gravity.RIGHT); return; } if(edgeGravityOrView instanceof View){ if (!this.isDrawerView(edgeGravityOrView)) { throw Error(`new IllegalArgumentException("View " + drawerView + " is not a " + "drawer with appropriate layout_gravity")`); } const gravity:number = (<DrawerLayout.LayoutParams> edgeGravityOrView.getLayoutParams()).gravity; this.setDrawerLockMode(lockMode, gravity); return; } let edgeGravity = <number>edgeGravityOrView; const absGravity:number = Gravity.getAbsoluteGravity(edgeGravity, this.getLayoutDirection()); if (absGravity == Gravity.LEFT) { this.mLockModeLeft = lockMode; } else if (absGravity == Gravity.RIGHT) { this.mLockModeRight = lockMode; } if (lockMode != DrawerLayout.LOCK_MODE_UNLOCKED) { // Cancel interaction in progress const helper:ViewDragHelper = absGravity == Gravity.LEFT ? this.mLeftDragger : this.mRightDragger; helper.cancel(); } switch(lockMode) { case DrawerLayout.LOCK_MODE_LOCKED_OPEN: const toOpen:View = this.findDrawerWithGravity(absGravity); if (toOpen != null) { this.openDrawer(toOpen); } break; case DrawerLayout.LOCK_MODE_LOCKED_CLOSED: const toClose:View = this.findDrawerWithGravity(absGravity); if (toClose != null) { this.closeDrawer(toClose); } break; } } ///** // * Enable or disable interaction with the given drawer. // * // * <p>This allows the application to restrict the user's ability to open or close // * the given drawer. DrawerLayout will still respond to calls to {@link #openDrawer(int)}, // * {@link #closeDrawer(int)} and friends if a drawer is locked.</p> // * // * <p>Locking a drawer open or closed will implicitly open or close // * that drawer as appropriate.</p> // * // * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, // * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. // * @param drawerView The drawer view to change the lock mode for // * // * @see #LOCK_MODE_UNLOCKED // * @see #LOCK_MODE_LOCKED_CLOSED // * @see #LOCK_MODE_LOCKED_OPEN // */ //setDrawerLockMode(lockMode:number, drawerView:View):void { // if (!this.isDrawerView(drawerView)) { // throw Error(`new IllegalArgumentException("View " + drawerView + " is not a " + "drawer with appropriate layout_gravity")`); // } // const gravity:number = (<DrawerLayout.LayoutParams> drawerView.getLayoutParams()).gravity; // this.setDrawerLockMode(lockMode, gravity); //} /** * Check the lock mode of the drawer with the given gravity. * * @param edgeGravityOrView Gravity of the drawer to check / Drawer view to check lock mode * @return one of {@link #LOCK_MODE_UNLOCKED}, {@link #LOCK_MODE_LOCKED_CLOSED} or * {@link #LOCK_MODE_LOCKED_OPEN}. */ getDrawerLockMode(edgeGravityOrView:number|View):number { if(edgeGravityOrView instanceof View){ let drawerView = edgeGravityOrView; const absGravity:number = this.getDrawerViewAbsoluteGravity(drawerView); if (absGravity == Gravity.LEFT) { return this.mLockModeLeft; } else if (absGravity == Gravity.RIGHT) { return this.mLockModeRight; } return DrawerLayout.LOCK_MODE_UNLOCKED; }else{ let edgeGravity = <number>edgeGravityOrView; const absGravity:number = Gravity.getAbsoluteGravity(edgeGravity, this.getLayoutDirection()); if (absGravity == Gravity.LEFT) { return this.mLockModeLeft; } else if (absGravity == Gravity.RIGHT) { return this.mLockModeRight; } return DrawerLayout.LOCK_MODE_UNLOCKED; } } /** * Resolve the shared state of all drawers from the component ViewDragHelpers. * Should be called whenever a ViewDragHelper's state changes. */ updateDrawerState(forGravity:number, activeState:number, activeDrawer:View):void { const leftState:number = this.mLeftDragger.getViewDragState(); const rightState:number = this.mRightDragger.getViewDragState(); let state:number; if (leftState == DrawerLayout.STATE_DRAGGING || rightState == DrawerLayout.STATE_DRAGGING) { state = DrawerLayout.STATE_DRAGGING; } else if (leftState == DrawerLayout.STATE_SETTLING || rightState == DrawerLayout.STATE_SETTLING) { state = DrawerLayout.STATE_SETTLING; } else { state = DrawerLayout.STATE_IDLE; } if (activeDrawer != null && activeState == DrawerLayout.STATE_IDLE) { const lp:DrawerLayout.LayoutParams = <DrawerLayout.LayoutParams> activeDrawer.getLayoutParams(); if (lp.onScreen == 0) { this.dispatchOnDrawerClosed(activeDrawer); } else if (lp.onScreen == 1) { this.dispatchOnDrawerOpened(activeDrawer); } } if (state != this.mDrawerState) { this.mDrawerState = state; if (this.mListener != null) { this.mListener.onDrawerStateChanged(state); } } } dispatchOnDrawerClosed(drawerView:View):void { const lp:DrawerLayout.LayoutParams = <DrawerLayout.LayoutParams> drawerView.getLayoutParams(); if (lp.knownOpen) { lp.knownOpen = false; if (this.mListener != null) { this.mListener.onDrawerClosed(drawerView); } //this.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } } dispatchOnDrawerOpened(drawerView:View):void { const lp:DrawerLayout.LayoutParams = <DrawerLayout.LayoutParams> drawerView.getLayoutParams(); if (!lp.knownOpen) { lp.knownOpen = true; if (this.mListener != null) { this.mListener.onDrawerOpened(drawerView); } //drawerView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } } dispatchOnDrawerSlide(drawerView:View, slideOffset:number):void { if (this.mListener != null) { this.mListener.onDrawerSlide(drawerView, slideOffset); } } setDrawerViewOffset(drawerView:View, slideOffset:number):void { const lp:DrawerLayout.LayoutParams = <DrawerLayout.LayoutParams> drawerView.getLayoutParams(); if (slideOffset == lp.onScreen) { return; } lp.onScreen = slideOffset; this.dispatchOnDrawerSlide(drawerView, slideOffset); } getDrawerViewOffset(drawerView:View):number { return (<DrawerLayout.LayoutParams> drawerView.getLayoutParams()).onScreen; } /** * @return the absolute gravity of the child drawerView, resolved according * to the current layout direction */ getDrawerViewAbsoluteGravity(drawerView:View):number { const gravity:number = (<DrawerLayout.LayoutParams> drawerView.getLayoutParams()).gravity; return Gravity.getAbsoluteGravity(gravity, this.getLayoutDirection()); } checkDrawerViewAbsoluteGravity(drawerView:View, checkFor:number):boolean { const absGravity:number = this.getDrawerViewAbsoluteGravity(drawerView); return (absGravity & checkFor) == checkFor; } findOpenDrawer():View { const childCount:number = this.getChildCount(); for (let i:number = 0; i < childCount; i++) { const child:View = this.getChildAt(i); if ((<DrawerLayout.LayoutParams> child.getLayoutParams()).knownOpen) { return child; } } return null; } moveDrawerToOffset(drawerView:View, slideOffset:number):void { const oldOffset:number = this.getDrawerViewOffset(drawerView); const width:number = drawerView.getWidth(); const oldPos:number = Math.floor((width * oldOffset)); const newPos:number = Math.floor((width * slideOffset)); const dx:number = newPos - oldPos; drawerView.offsetLeftAndRight(this.checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT) ? dx : -dx); this.setDrawerViewOffset(drawerView, slideOffset); } /** * @param gravity the gravity of the child to return. If specified as a * relative value, it will be resolved according to the current * layout direction. * @return the drawer with the specified gravity */ findDrawerWithGravity(gravity:number):View { const absHorizGravity:number = Gravity.getAbsoluteGravity(gravity, this.getLayoutDirection()) & Gravity.HORIZONTAL_GRAVITY_MASK; const childCount:number = this.getChildCount(); for (let i:number = 0; i < childCount; i++) { const child:View = this.getChildAt(i); const childAbsGravity:number = this.getDrawerViewAbsoluteGravity(child); if ((childAbsGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == absHorizGravity) { return child; } } return null; } /** * Simple gravity to string - only supports LEFT and RIGHT for debugging output. * * @param gravity Absolute gravity value * @return LEFT or RIGHT as appropriate, or a hex string */ static gravityToString(gravity:number):string { if ((gravity & Gravity.LEFT) == Gravity.LEFT) { return "LEFT"; } if ((gravity & Gravity.RIGHT) == Gravity.RIGHT) { return "RIGHT"; } return ''+gravity; } protected onDetachedFromWindow():void { super.onDetachedFromWindow(); this.mFirstLayout = true; } protected onAttachedToWindow():void { super.onAttachedToWindow(); this.mFirstLayout = true; } protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void { let widthMode:number = View.MeasureSpec.getMode(widthMeasureSpec); let heightMode:number = View.MeasureSpec.getMode(heightMeasureSpec); let widthSize:number = View.MeasureSpec.getSize(widthMeasureSpec); let heightSize:number = View.MeasureSpec.getSize(heightMeasureSpec); if (widthMode != View.MeasureSpec.EXACTLY || heightMode != View.MeasureSpec.EXACTLY) { if (this.isInEditMode()) { // It will crash on a real device. if (widthMode == View.MeasureSpec.AT_MOST) { widthMode = View.MeasureSpec.EXACTLY; } else if (widthMode == View.MeasureSpec.UNSPECIFIED) { widthMode = View.MeasureSpec.EXACTLY; widthSize = 300; } if (heightMode == View.MeasureSpec.AT_MOST) { heightMode = View.MeasureSpec.EXACTLY; } else if (heightMode == View.MeasureSpec.UNSPECIFIED) { heightMode = View.MeasureSpec.EXACTLY; heightSize = 300; } } else { throw Error(`new IllegalArgumentException("DrawerLayout must be measured with MeasureSpec.EXACTLY.")`); } } this.setMeasuredDimension(widthSize, heightSize); // Gravity value for each drawer we've seen. Only one of each permitted. let foundDrawers:number = 0; const childCount:number = this.getChildCount(); for (let i:number = 0; i < childCount; i++) { const child:View = this.getChildAt(i); if (child.getVisibility() == DrawerLayout.GONE) { continue; } const lp:DrawerLayout.LayoutParams = <DrawerLayout.LayoutParams> child.getLayoutParams(); if (this.isContentView(child)) { // Content views get measured at exactly the layout's size. const contentWidthSpec:number = View.MeasureSpec.makeMeasureSpec(widthSize - lp.leftMargin - lp.rightMargin, View.MeasureSpec.EXACTLY); const contentHeightSpec:number = View.MeasureSpec.makeMeasureSpec(heightSize - lp.topMargin - lp.bottomMargin, View.MeasureSpec.EXACTLY); child.measure(contentWidthSpec, contentHeightSpec); } else if (this.isDrawerView(child)) { const childGravity:number = this.getDrawerViewAbsoluteGravity(child) & Gravity.HORIZONTAL_GRAVITY_MASK; if ((foundDrawers & childGravity) != 0) { throw Error(`new IllegalStateException("Child drawer has absolute gravity " + DrawerLayout.gravityToString(childGravity) + " but this " + DrawerLayout.TAG + " already has a " + "drawer view along that edge")`); } const drawerWidthSpec:number = DrawerLayout.getChildMeasureSpec(widthMeasureSpec, this.mMinDrawerMargin + lp.leftMargin + lp.rightMargin, lp.width); const drawerHeightSpec:number = DrawerLayout.getChildMeasureSpec(heightMeasureSpec, lp.topMargin + lp.bottomMargin, lp.height); child.measure(drawerWidthSpec, drawerHeightSpec); } else { throw Error(`new IllegalStateException("Child " + child + " at index " + i + " does not have a valid layout_gravity - must be Gravity.LEFT, " + "Gravity.RIGHT or Gravity.NO_GRAVITY")`); } } } protected onLayout(changed:boolean, l:number, t:number, r:number, b:number):void { this.mInLayout = true; const width:number = r - l; const childCount:number = this.getChildCount(); for (let i:number = 0; i < childCount; i++) { const child:View = this.getChildAt(i); if (child.getVisibility() == DrawerLayout.GONE) { continue; } const lp:DrawerLayout.LayoutParams = <DrawerLayout.LayoutParams> child.getLayoutParams(); if (this.isContentView(child)) { child.layout(lp.leftMargin, lp.topMargin, lp.leftMargin + child.getMeasuredWidth(), lp.topMargin + child.getMeasuredHeight()); } else { // Drawer, if it wasn't onMeasure would have thrown an exception. const childWidth:number = child.getMeasuredWidth(); const childHeight:number = child.getMeasuredHeight(); let childLeft:number; let newOffset:number; if (this.checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { childLeft = -childWidth + Math.floor((childWidth * lp.onScreen)); newOffset = <number> (childWidth + childLeft) / childWidth; } else { // Right; onMeasure checked for us. childLeft = width - Math.floor((childWidth * lp.onScreen)); newOffset = <number> (width - childLeft) / childWidth; } const changeOffset:boolean = newOffset != lp.onScreen; const vgrav:number = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; switch(vgrav) { default: case Gravity.TOP: { child.layout(childLeft, lp.topMargin, childLeft + childWidth, lp.topMargin + childHeight); break; } case Gravity.BOTTOM: { const height:number = b - t; child.layout(childLeft, height - lp.bottomMargin - child.getMeasuredHeight(), childLeft + childWidth, height - lp.bottomMargin); break; } case Gravity.CENTER_VERTICAL: { const height:number = b - t; let childTop:number = (height - childHeight) / 2; // bad measurement before, oh well. if (childTop < lp.topMargin) { childTop = lp.topMargin; } else if (childTop + childHeight > height - lp.bottomMargin) { childTop = height - lp.bottomMargin - childHeight; } child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); break; } } if (changeOffset) { this.setDrawerViewOffset(child, newOffset); } const newVisibility:number = lp.onScreen > 0 ? DrawerLayout.VISIBLE : DrawerLayout.INVISIBLE; if (child.getVisibility() != newVisibility) { child.setVisibility(newVisibility); } } } this.mInLayout = false; this.mFirstLayout = false; } requestLayout():void { if (!this.mInLayout) { super.requestLayout(); } } computeScroll():void { const childCount:number = this.getChildCount(); let scrimOpacity:number = 0; for (let i:number = 0; i < childCount; i++) { const onscreen:number = (<DrawerLayout.LayoutParams> this.getChildAt(i).getLayoutParams()).onScreen; scrimOpacity = Math.max(scrimOpacity, onscreen); } this.mScrimOpacity = scrimOpacity; let leftContinue = this.mLeftDragger.continueSettling(true); let rightContinue = this.mRightDragger.continueSettling(true); if (leftContinue || rightContinue) { this.postInvalidateOnAnimation(); } } private static hasOpaqueBackground(v:View):boolean { const bg:Drawable = v.getBackground(); if (bg != null) { return bg.getOpacity() == PixelFormat.OPAQUE; } return false; } protected drawChild(canvas:Canvas, child:View, drawingTime:number):boolean { const height:number = this.getHeight(); const drawingContent:boolean = this.isContentView(child); let clipLeft:number = 0, clipRight:number = this.getWidth(); const restoreCount:number = canvas.save(); if (drawingContent) { const childCount:number = this.getChildCount(); for (let i:number = 0; i < childCount; i++) { const v:View = this.getChildAt(i); if (v == child || v.getVisibility() != DrawerLayout.VISIBLE || !DrawerLayout.hasOpaqueBackground(v) || !this.isDrawerView(v) || v.getHeight() < height) { continue; } if (this.checkDrawerViewAbsoluteGravity(v, Gravity.LEFT)) { const vright:number = v.getRight(); if (vright > clipLeft) clipLeft = vright; } else { const vleft:number = v.getLeft(); if (vleft < clipRight) clipRight = vleft; } } canvas.clipRect(clipLeft, 0, clipRight, this.getHeight()); } const result:boolean = super.drawChild(canvas, child, drawingTime); canvas.restoreToCount(restoreCount); if (this.mScrimOpacity > 0 && drawingContent) { const baseAlpha:number = (this.mScrimColor & 0xff000000) >>> 24; const imag:number = Math.floor((baseAlpha * this.mScrimOpacity)); const color:number = imag << 24 | (this.mScrimColor & 0xffffff); this.mScrimPaint.setColor(color); canvas.drawRect(clipLeft, 0, clipRight, this.getHeight(), this.mScrimPaint); } else if (this.mShadowLeft != null && this.checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { const shadowWidth:number = this.mShadowLeft.getIntrinsicWidth(); const childRight:number = child.getRight(); const drawerPeekDistance:number = this.mLeftDragger.getEdgeSize(); const alpha:number = Math.max(0, Math.min(<number> childRight / drawerPeekDistance, 1.)); this.mShadowLeft.setBounds(childRight, child.getTop(), childRight + shadowWidth, child.getBottom()); this.mShadowLeft.setAlpha(Math.floor((0xff * alpha))); this.mShadowLeft.draw(canvas); } else if (this.mShadowRight != null && this.checkDrawerViewAbsoluteGravity(child, Gravity.RIGHT)) { const shadowWidth:number = this.mShadowRight.getIntrinsicWidth(); const childLeft:number = child.getLeft(); const showing:number = this.getWidth() - childLeft; const drawerPeekDistance:number = this.mRightDragger.getEdgeSize(); const alpha:number = Math.max(0, Math.min(<number> showing / drawerPeekDistance, 1.)); this.mShadowRight.setBounds(childLeft - shadowWidth, child.getTop(), childLeft, child.getBottom()); this.mShadowRight.setAlpha(Math.floor((0xff * alpha))); this.mShadowRight.draw(canvas); } return result; } isContentView(child:View):boolean { return (<DrawerLayout.LayoutParams> child.getLayoutParams()).gravity == Gravity.NO_GRAVITY; } isDrawerView(child:View):boolean { const gravity:number = (<DrawerLayout.LayoutParams> child.getLayoutParams()).gravity; const absGravity:number = Gravity.getAbsoluteGravity(gravity, child.getLayoutDirection()); return (absGravity & (Gravity.LEFT | Gravity.RIGHT)) != 0; } onInterceptTouchEvent(ev:MotionEvent):boolean { const action:number = ev.getActionMasked(); const leftIntercept = this.mLeftDragger.shouldInterceptTouchEvent(ev); const rightIntercept = this.mRightDragger.shouldInterceptTouchEvent(ev); const interceptForDrag:boolean = leftIntercept || rightIntercept; let interceptForTap:boolean = false; switch(action) { case MotionEvent.ACTION_DOWN: { const x:number = ev.getX(); const y:number = ev.getY(); this.mInitialMotionX = x; this.mInitialMotionY = y; if (this.mScrimOpacity > 0 && this.isContentView(this.mLeftDragger.findTopChildUnder(Math.floor(x), Math.floor(y)))) { interceptForTap = true; } this.mDisallowInterceptRequested = false; this.mChildrenCanceledTouch = false; break; } case MotionEvent.ACTION_MOVE: { // If we cross the touch slop, don't perform the delayed peek for an edge touch. if (this.mLeftDragger.checkTouchSlop(ViewDragHelper.DIRECTION_ALL)) { this.mLeftCallback.removeCallbacks(); this.mRightCallback.removeCallbacks(); } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: { this.closeDrawers(true); this.mDisallowInterceptRequested = false; this.mChildrenCanceledTouch = false; } } return interceptForDrag || interceptForTap || this.hasPeekingDrawer() || this.mChildrenCanceledTouch; } onTouchEvent(ev:MotionEvent):boolean { this.mLeftDragger.processTouchEvent(ev); this.mRightDragger.processTouchEvent(ev); const action:number = ev.getAction(); let wantTouchEvents:boolean = true; switch(action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { const x:number = ev.getX(); const y:number = ev.getY(); this.mInitialMotionX = x; this.mInitialMotionY = y; this.mDisallowInterceptRequested = false; this.mChildrenCanceledTouch = false; break; } case MotionEvent.ACTION_UP: { const x:number = ev.getX(); const y:number = ev.getY(); let peekingOnly:boolean = true; const touchedView:View = this.mLeftDragger.findTopChildUnder(Math.floor(x), Math.floor(y)); if (touchedView != null && this.isContentView(touchedView)) { const dx:number = x - this.mInitialMotionX; const dy:number = y - this.mInitialMotionY; const slop:number = this.mLeftDragger.getTouchSlop(); if (dx * dx + dy * dy < slop * slop) { // Taps close a dimmed open drawer but only if it isn't locked open. const openDrawer:View = this.findOpenDrawer(); if (openDrawer != null) { peekingOnly = this.getDrawerLockMode(openDrawer) == DrawerLayout.LOCK_MODE_LOCKED_OPEN; } } } this.closeDrawers(peekingOnly); this.mDisallowInterceptRequested = false; break; } case MotionEvent.ACTION_CANCEL: { this.closeDrawers(true); this.mDisallowInterceptRequested = false; this.mChildrenCanceledTouch = false; break; } } return wantTouchEvents; } requestDisallowInterceptTouchEvent(disallowIntercept:boolean):void { if (DrawerLayout.CHILDREN_DISALLOW_INTERCEPT || (!this.mLeftDragger.isEdgeTouched(ViewDragHelper.EDGE_LEFT) && !this.mRightDragger.isEdgeTouched(ViewDragHelper.EDGE_RIGHT))) { // If we have an edge touch we want to skip this and track it for later instead. super.requestDisallowInterceptTouchEvent(disallowIntercept); } this.mDisallowInterceptRequested = disallowIntercept; if (disallowIntercept) { this.closeDrawers(true); } } /** * Close all currently open drawer views by animating them out of view. */ closeDrawers(peekingOnly = false):void { let needsInvalidate:boolean = false; const childCount:number = this.getChildCount(); for (let i:number = 0; i < childCount; i++) { const child:View = this.getChildAt(i); const lp:DrawerLayout.LayoutParams = <DrawerLayout.LayoutParams> child.getLayoutParams(); if (!this.isDrawerView(child) || (peekingOnly && !lp.isPeeking)) { continue; } const childWidth:number = child.getWidth(); if (this.checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { needsInvalidate = this.mLeftDragger.smoothSlideViewTo(child, -childWidth, child.getTop()) || needsInvalidate; } else { needsInvalidate = this.mRightDragger.smoothSlideViewTo(child, this.getWidth(), child.getTop()) || needsInvalidate; } lp.isPeeking = false; } this.mLeftCallback.removeCallbacks(); this.mRightCallback.removeCallbacks(); if (needsInvalidate) { this.invalidate(); } } /** * Open the specified drawer view by animating it into view. * * @param drawerView Drawer view to open */ openDrawer(drawerView:View):void; /** * Open the specified drawer by animating it out of view. * * @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right. * Gravity.START or Gravity.END may also be used. */ openDrawer(gravity:number):void; openDrawer(arg:View|number):void{ if(arg instanceof View){ this._openDrawer_view(<View>arg); }else{ this._openDrawer_gravity(<number>arg); } } private _openDrawer_view(drawerView:View):void { if (!this.isDrawerView(drawerView)) { throw Error(`new IllegalArgumentException("View " + drawerView + " is not a sliding drawer")`); } if (this.mFirstLayout) { const lp:DrawerLayout.LayoutParams = <DrawerLayout.LayoutParams> drawerView.getLayoutParams(); lp.onScreen = 1.; lp.knownOpen = true; } else { if (this.checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT)) { this.mLeftDragger.smoothSlideViewTo(drawerView, 0, drawerView.getTop()); } else { this.mRightDragger.smoothSlideViewTo(drawerView, this.getWidth() - drawerView.getWidth(), drawerView.getTop()); } } this.invalidate(); } private _openDrawer_gravity(gravity:number):void { const drawerView:View = this.findDrawerWithGravity(gravity); if (drawerView == null) { throw Error(`new IllegalArgumentException("No drawer view found with gravity " + DrawerLayout.gravityToString(gravity))`); } this.openDrawer(drawerView); } /** * Close the specified drawer view by animating it into view. * * @param drawerView Drawer view to close */ closeDrawer(drawerView:View):void; /** * Close the specified drawer by animating it out of view. * * @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right. * Gravity.START or Gravity.END may also be used. */ closeDrawer(gravity:number):void; closeDrawer(arg:View|number){ if(arg instanceof View){ this._closeDrawer_view(<View>arg); }else{ this._closeDrawer_gravity(<number>arg); } } private _closeDrawer_view(drawerView:View):void { if (!this.isDrawerView(drawerView)) { throw Error(`new IllegalArgumentException("View " + drawerView + " is not a sliding drawer")`); } if (this.mFirstLayout) { const lp:DrawerLayout.LayoutParams = <DrawerLayout.LayoutParams> drawerView.getLayoutParams(); lp.onScreen = 0.; lp.knownOpen = false; } else { if (this.checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT)) { this.mLeftDragger.smoothSlideViewTo(drawerView, -drawerView.getWidth(), drawerView.getTop()); } else { this.mRightDragger.smoothSlideViewTo(drawerView, this.getWidth(), drawerView.getTop()); } } this.invalidate(); } private _closeDrawer_gravity(gravity:number):void { const drawerView:View = this.findDrawerWithGravity(gravity); if (drawerView == null) { throw Error(`new IllegalArgumentException("No drawer view found with gravity " + DrawerLayout.gravityToString(gravity))`); } this.closeDrawer(drawerView); } /** * Check if the given drawer view is currently in an open state. * To be considered "open" the drawer must have settled into its fully * visible state. To check for partial visibility use * {@link #isDrawerVisible(android.view.View)}. * * @param drawer Drawer view to check * @return true if the given drawer view is in an open state * @see #isDrawerVisible(android.view.View) */ isDrawerOpen(drawer:View):boolean; /** * Check if the given drawer view is currently in an open state. * To be considered "open" the drawer must have settled into its fully * visible state. If there is no drawer with the given gravity this method * will return false. * * @param drawerGravity Gravity of the drawer to check * @return true if the given drawer view is in an open state */ isDrawerOpen(drawerGravity:number):boolean; isDrawerOpen(arg:View|number):boolean{ if(arg instanceof View){ return this._isDrawerOpen_view(<View>arg); }else{ return this._isDrawerOpen_gravity(<number>arg); } } private _isDrawerOpen_view(drawer:View):boolean { if (!this.isDrawerView(drawer)) { throw Error(`new IllegalArgumentException("View " + drawer + " is not a drawer")`); } return (<DrawerLayout.LayoutParams> drawer.getLayoutParams()).knownOpen; } private _isDrawerOpen_gravity(drawerGravity:number):boolean { const drawerView:View = this.findDrawerWithGravity(drawerGravity); if (drawerView != null) { return this.isDrawerOpen(drawerView); } return false; } /** * Check if a given drawer view is currently visible on-screen. The drawer * may be only peeking onto the screen, fully extended, or anywhere inbetween. * * @param drawer Drawer view to check * @return true if the given drawer is visible on-screen * @see #isDrawerOpen(android.view.View) */ isDrawerVisible(drawer:View):boolean; /** * Check if a given drawer view is currently visible on-screen. The drawer * may be only peeking onto the screen, fully extended, or anywhere inbetween. * If there is no drawer with the given gravity this method will return false. * * @param drawerGravity Gravity of the drawer to check * @return true if the given drawer is visible on-screen */ isDrawerVisible(drawerGravity:number):boolean; isDrawerVisible(arg:View|number):boolean{ if(arg instanceof View){ return this._isDrawerVisible_view(<View>arg); }else{ return this._isDrawerVisible_gravity(<number>arg); } } private _isDrawerVisible_view(drawer:View):boolean { if (!this.isDrawerView(drawer)) { throw Error(`new IllegalArgumentException("View " + drawer + " is not a drawer")`); } return (<DrawerLayout.LayoutParams> drawer.getLayoutParams()).onScreen > 0; } private _isDrawerVisible_gravity(drawerGravity:number):boolean { const drawerView:View = this.findDrawerWithGravity(drawerGravity); if (drawerView != null) { return this.isDrawerVisible(drawerView); } return false; } private hasPeekingDrawer():boolean { const childCount:number = this.getChildCount(); for (let i:number = 0; i < childCount; i++) { const lp:DrawerLayout.LayoutParams = <DrawerLayout.LayoutParams> this.getChildAt(i).getLayoutParams(); if (lp.isPeeking) { return true; } } return false; } protected generateDefaultLayoutParams():ViewGroup.LayoutParams { return new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.FILL_PARENT, DrawerLayout.LayoutParams.FILL_PARENT); } protected generateLayoutParams(p:ViewGroup.LayoutParams):ViewGroup.LayoutParams { return p instanceof DrawerLayout.LayoutParams ? new DrawerLayout.LayoutParams(<DrawerLayout.LayoutParams> p) : p instanceof ViewGroup.MarginLayoutParams ? new DrawerLayout.LayoutParams(<ViewGroup.MarginLayoutParams> p) : new DrawerLayout.LayoutParams(p); } protected checkLayoutParams(p:ViewGroup.LayoutParams):boolean { return p instanceof DrawerLayout.LayoutParams && super.checkLayoutParams(p); } public generateLayoutParamsFromAttr(attrs: HTMLElement): android.view.ViewGroup.LayoutParams { return new DrawerLayout.LayoutParams(this.getContext(), attrs); } private hasVisibleDrawer():boolean { return this.findVisibleDrawer() != null; } private findVisibleDrawer():View { const childCount:number = this.getChildCount(); for (let i:number = 0; i < childCount; i++) { const child:View = this.getChildAt(i); if (this.isDrawerView(child) && this.isDrawerVisible(child)) { return child; } } return null; } cancelChildViewTouch():void { // Cancel child touches if (!this.mChildrenCanceledTouch) { const now:number = SystemClock.uptimeMillis(); const cancelEvent:MotionEvent = MotionEvent.obtainWithAction(now, now, MotionEvent.ACTION_CANCEL, 0.0, 0.0, 0); const childCount:number = this.getChildCount(); for (let i:number = 0; i < childCount; i++) { this.getChildAt(i).dispatchTouchEvent(cancelEvent); } cancelEvent.recycle(); this.mChildrenCanceledTouch = true; } } onKeyDown(keyCode:number, event:KeyEvent):boolean { if (keyCode == KeyEvent.KEYCODE_BACK && this.hasVisibleDrawer()) { event.startTracking(); return true; } return super.onKeyDown(keyCode, event); } onKeyUp(keyCode:number, event:KeyEvent):boolean { if (keyCode == KeyEvent.KEYCODE_BACK) { const visibleDrawer:View = this.findVisibleDrawer(); if (visibleDrawer != null && this.getDrawerLockMode(visibleDrawer) == DrawerLayout.LOCK_MODE_UNLOCKED) { this.closeDrawers(); } return visibleDrawer != null; } return super.onKeyUp(keyCode, event); } } export module DrawerLayout{ /** * Listener for monitoring events about drawers. */ export interface DrawerListener { /** * Called when a drawer's position changes. * @param drawerView The child view that was moved * @param slideOffset The new offset of this drawer within its range, from 0-1 */ onDrawerSlide(drawerView:View, slideOffset:number):void ; /** * Called when a drawer has settled in a completely open state. * The drawer is interactive at this point. * * @param drawerView Drawer view that is now open */ onDrawerOpened(drawerView:View):void ; /** * Called when a drawer has settled in a completely closed state. * * @param drawerView Drawer view that is now closed */ onDrawerClosed(drawerView:View):void ; /** * Called when the drawer motion state changes. The new state will * be one of {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}. * * @param newState The new drawer motion state */ onDrawerStateChanged(newState:number):void ; } /** * Stub/no-op implementations of all methods of {@link DrawerListener}. * Override this if you only care about a few of the available callback methods. */ export class SimpleDrawerListener implements DrawerLayout.DrawerListener { onDrawerSlide(drawerView:View, slideOffset:number):void { } onDrawerOpened(drawerView:View):void { } onDrawerClosed(drawerView:View):void { } onDrawerStateChanged(newState:number):void { } } export class ViewDragCallback extends ViewDragHelper.Callback { _DrawerLayout_this:DrawerLayout; constructor(arg:DrawerLayout, gravity:number){ super(); this._DrawerLayout_this = arg; this.mAbsGravity = gravity; } private mAbsGravity:number = 0; private mDragger:ViewDragHelper; private mPeekRunnable:Runnable = (()=>{ const inner_this=this; class _Inner implements Runnable { run():void { inner_this.peekDrawer(); } } return new _Inner(); })(); setDragger(dragger:ViewDragHelper):void { this.mDragger = dragger; } removeCallbacks():void { this._DrawerLayout_this.removeCallbacks(this.mPeekRunnable); } tryCaptureView(child:View, pointerId:number):boolean { // This lets us use two ViewDragHelpers, one for each side drawer. return this._DrawerLayout_this.isDrawerView(child) && this._DrawerLayout_this.checkDrawerViewAbsoluteGravity(child, this.mAbsGravity) && this._DrawerLayout_this.getDrawerLockMode(child) == DrawerLayout.LOCK_MODE_UNLOCKED; } onViewDragStateChanged(state:number):void { this._DrawerLayout_this.updateDrawerState(this.mAbsGravity, state, this.mDragger.getCapturedView()); } onViewPositionChanged(changedView:View, left:number, top:number, dx:number, dy:number):void { let offset:number; const childWidth:number = changedView.getWidth(); // This reverses the positioning shown in onLayout. if (this._DrawerLayout_this.checkDrawerViewAbsoluteGravity(changedView, Gravity.LEFT)) { offset = <number> (childWidth + left) / childWidth; } else { const width:number = this._DrawerLayout_this.getWidth(); offset = <number> (width - left) / childWidth; } this._DrawerLayout_this.setDrawerViewOffset(changedView, offset); changedView.setVisibility(offset == 0 ? DrawerLayout.INVISIBLE : DrawerLayout.VISIBLE); this._DrawerLayout_this.invalidate(); } onViewCaptured(capturedChild:View, activePointerId:number):void { const lp:DrawerLayout.LayoutParams = <DrawerLayout.LayoutParams> capturedChild.getLayoutParams(); lp.isPeeking = false; this.closeOtherDrawer(); } private closeOtherDrawer():void { const otherGrav:number = this.mAbsGravity == Gravity.LEFT ? Gravity.RIGHT : Gravity.LEFT; const toClose:View = this._DrawerLayout_this.findDrawerWithGravity(otherGrav); if (toClose != null) { this._DrawerLayout_this.closeDrawer(toClose); } } onViewReleased(releasedChild:View, xvel:number, yvel:number):void { // Offset is how open the drawer is, therefore left/right values // are reversed from one another. const offset:number = this._DrawerLayout_this.getDrawerViewOffset(releasedChild); const childWidth:number = releasedChild.getWidth(); let left:number; if (this._DrawerLayout_this.checkDrawerViewAbsoluteGravity(releasedChild, Gravity.LEFT)) { left = xvel > 0 || xvel == 0 && offset > 0.5 ? 0 : -childWidth; } else { const width:number = this._DrawerLayout_this.getWidth(); left = xvel < 0 || xvel == 0 && offset > 0.5 ? width - childWidth : width; } this.mDragger.settleCapturedViewAt(left, releasedChild.getTop()); this._DrawerLayout_this.invalidate(); } onEdgeTouched(edgeFlags:number, pointerId:number):void { this._DrawerLayout_this.postDelayed(this.mPeekRunnable, DrawerLayout.PEEK_DELAY); } private peekDrawer():void { let toCapture:View; let childLeft:number; const peekDistance:number = this.mDragger.getEdgeSize(); const leftEdge:boolean = this.mAbsGravity == Gravity.LEFT; if (leftEdge) { toCapture = this._DrawerLayout_this.findDrawerWithGravity(Gravity.LEFT); childLeft = (toCapture != null ? -toCapture.getWidth() : 0) + peekDistance; } else { toCapture = this._DrawerLayout_this.findDrawerWithGravity(Gravity.RIGHT); childLeft = this._DrawerLayout_this.getWidth() - peekDistance; } // Only peek if it would mean making the drawer more visible and the drawer isn't locked if (toCapture != null && ((leftEdge && toCapture.getLeft() < childLeft) || (!leftEdge && toCapture.getLeft() > childLeft)) && this._DrawerLayout_this.getDrawerLockMode(toCapture) == DrawerLayout.LOCK_MODE_UNLOCKED) { const lp:DrawerLayout.LayoutParams = <DrawerLayout.LayoutParams> toCapture.getLayoutParams(); this.mDragger.smoothSlideViewTo(toCapture, childLeft, toCapture.getTop()); lp.isPeeking = true; this._DrawerLayout_this.invalidate(); this.closeOtherDrawer(); this._DrawerLayout_this.cancelChildViewTouch(); } } onEdgeLock(edgeFlags:number):boolean { if (DrawerLayout.ALLOW_EDGE_LOCK) { const drawer:View = this._DrawerLayout_this.findDrawerWithGravity(this.mAbsGravity); if (drawer != null && !this._DrawerLayout_this.isDrawerOpen(drawer)) { this._DrawerLayout_this.closeDrawer(drawer); } return true; } return false; } onEdgeDragStarted(edgeFlags:number, pointerId:number):void { let toCapture:View; if ((edgeFlags & ViewDragHelper.EDGE_LEFT) == ViewDragHelper.EDGE_LEFT) { toCapture = this._DrawerLayout_this.findDrawerWithGravity(Gravity.LEFT); } else { toCapture = this._DrawerLayout_this.findDrawerWithGravity(Gravity.RIGHT); } if (toCapture != null && this._DrawerLayout_this.getDrawerLockMode(toCapture) == DrawerLayout.LOCK_MODE_UNLOCKED) { this.mDragger.captureChildView(toCapture, pointerId); } } getViewHorizontalDragRange(child:View):number { return child.getWidth(); } clampViewPositionHorizontal(child:View, left:number, dx:number):number { if (this._DrawerLayout_this.checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { return Math.max(-child.getWidth(), Math.min(left, 0)); } else { const width:number = this._DrawerLayout_this.getWidth(); return Math.max(width - child.getWidth(), Math.min(left, width)); } } clampViewPositionVertical(child:View, top:number, dy:number):number { return child.getTop(); } } export class LayoutParams extends ViewGroup.MarginLayoutParams { gravity:number = Gravity.NO_GRAVITY; onScreen:number = 0; isPeeking:boolean; knownOpen:boolean; constructor(context:Context, attrs:HTMLElement); constructor(width:number, height:number); constructor(width:number, height:number, gravity:number); constructor(source:ViewGroup.LayoutParams); constructor(source:ViewGroup.MarginLayoutParams); constructor(source:LayoutParams); constructor(...args){ super(...(() => { if (args[0] instanceof android.content.Context && args[1] instanceof HTMLElement) return [args[0], args[1]]; else if (typeof args[0] === 'number' && typeof args[1] === 'number' && typeof args[2] === 'number') return [args[0], args[1]]; else if (typeof args[0] === 'number' && typeof args[1] === 'number') return [args[0], args[1]]; else if (args[0] instanceof DrawerLayout.LayoutParams) return [args[0]]; else if (args[0] instanceof ViewGroup.MarginLayoutParams) return [args[0]]; else if (args[0] instanceof ViewGroup.LayoutParams) return [args[0]]; })()); if (args[0] instanceof Context && args[1] instanceof HTMLElement) { const c = <Context>args[0]; const attrs = <HTMLElement>args[1]; const a = c.obtainStyledAttributes(attrs); this.gravity = Gravity.parseGravity(a.getAttrValue('layout_gravity'), Gravity.NO_GRAVITY); a.recycle(); } else if (typeof args[0] === 'number' && typeof args[1] === 'number' && typeof args[2] == 'number') { this.gravity = args[2]; } else if (typeof args[0] === 'number' && typeof args[1] === 'number') { } else if (args[0] instanceof DrawerLayout.LayoutParams) { const source = <DrawerLayout.LayoutParams>args[0]; this.gravity = source.gravity; } else if (args[0] instanceof ViewGroup.MarginLayoutParams) { } else if (args[0] instanceof ViewGroup.LayoutParams) { } } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('layout_gravity', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { param.gravity = attrBinder.parseGravity(value, param.gravity); }, getter(param:LayoutParams) { return param.gravity; } }); } } } }
the_stack
export default { '-157766400000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: -157766400000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: -157766400000.0, }, { key: ['David'], value: 6820.0, name: ['David'], time: -157766400000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: -157766400000.0, }, { key: ['Michael'], value: 7835.0, name: ['Michael'], time: -157766400000.0, }, ], '-126230400000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: -126230400000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: -126230400000.0, }, { key: ['David'], value: 6757.0, name: ['David'], time: -126230400000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: -126230400000.0, }, { key: ['Michael'], value: 7678.0, name: ['Michael'], time: -126230400000.0, }, ], '-94694400000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: -94694400000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: -94694400000.0, }, { key: ['David'], value: 6923.0, name: ['David'], time: -94694400000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: -94694400000.0, }, { key: ['Michael'], value: 8132.0, name: ['Michael'], time: -94694400000.0, }, ], '-63158400000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: -63158400000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: -63158400000.0, }, { key: ['David'], value: 6490.0, name: ['David'], time: -63158400000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: -63158400000.0, }, { key: ['Michael'], value: 8079.0, name: ['Michael'], time: -63158400000.0, }, ], '-31536000000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: -31536000000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: -31536000000.0, }, { key: ['David'], value: 6563.0, name: ['David'], time: -31536000000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: -31536000000.0, }, { key: ['Michael'], value: 8245.0, name: ['Michael'], time: -31536000000.0, }, ], '0': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 0.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 0.0, }, { key: ['David'], value: 6367.0, name: ['David'], time: 0.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 0.0, }, { key: ['Michael'], value: 8186.0, name: ['Michael'], time: 0.0, }, ], '31536000000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 31536000000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 31536000000.0, }, { key: ['David'], value: 0, name: ['David'], time: 31536000000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 31536000000.0, }, { key: ['Michael'], value: 6825.0, name: ['Michael'], time: 31536000000.0, }, ], '63072000000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 63072000000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 63072000000.0, }, { key: ['David'], value: 0, name: ['David'], time: 63072000000.0, }, { key: ['Jennifer'], value: 6066.0, name: ['Jennifer'], time: 63072000000.0, }, { key: ['Michael'], value: 6337.0, name: ['Michael'], time: 63072000000.0, }, ], '94694400000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 94694400000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 94694400000.0, }, { key: ['David'], value: 0, name: ['David'], time: 94694400000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 94694400000.0, }, { key: ['Michael'], value: 5877.0, name: ['Michael'], time: 94694400000.0, }, ], '126230400000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 126230400000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 126230400000.0, }, { key: ['David'], value: 0, name: ['David'], time: 126230400000.0, }, { key: ['Jennifer'], value: 5672.0, name: ['Jennifer'], time: 126230400000.0, }, { key: ['Michael'], value: 6058.0, name: ['Michael'], time: 126230400000.0, }, ], '157766400000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 157766400000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 157766400000.0, }, { key: ['David'], value: 0, name: ['David'], time: 157766400000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 157766400000.0, }, { key: ['Michael'], value: 6206.0, name: ['Michael'], time: 157766400000.0, }, ], '189302400000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 189302400000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 189302400000.0, }, { key: ['David'], value: 0, name: ['David'], time: 189302400000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 189302400000.0, }, { key: ['Michael'], value: 6178.0, name: ['Michael'], time: 189302400000.0, }, ], '220924800000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 220924800000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 220924800000.0, }, { key: ['David'], value: 0, name: ['David'], time: 220924800000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 220924800000.0, }, { key: ['Michael'], value: 6313.0, name: ['Michael'], time: 220924800000.0, }, ], '252460800000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 252460800000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 252460800000.0, }, { key: ['David'], value: 0, name: ['David'], time: 252460800000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 252460800000.0, }, { key: ['Michael'], value: 6489.0, name: ['Michael'], time: 252460800000.0, }, ], '283996800000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 283996800000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 283996800000.0, }, { key: ['David'], value: 0, name: ['David'], time: 283996800000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 283996800000.0, }, { key: ['Michael'], value: 6580.0, name: ['Michael'], time: 283996800000.0, }, ], '315532800000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 315532800000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 315532800000.0, }, { key: ['David'], value: 0, name: ['David'], time: 315532800000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 315532800000.0, }, { key: ['Michael'], value: 6896.0, name: ['Michael'], time: 315532800000.0, }, ], '347155200000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 347155200000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 347155200000.0, }, { key: ['David'], value: 0, name: ['David'], time: 347155200000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 347155200000.0, }, { key: ['Michael'], value: 7142.0, name: ['Michael'], time: 347155200000.0, }, ], '378691200000000000': [ { key: ['Christopher'], value: 6093.0, name: ['Christopher'], time: 378691200000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 378691200000.0, }, { key: ['David'], value: 0, name: ['David'], time: 378691200000.0, }, { key: ['Jennifer'], value: 5811.0, name: ['Jennifer'], time: 378691200000.0, }, { key: ['Michael'], value: 7155.0, name: ['Michael'], time: 378691200000.0, }, ], '410227200000000000': [ { key: ['Christopher'], value: 6375.0, name: ['Christopher'], time: 410227200000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 410227200000.0, }, { key: ['David'], value: 0, name: ['David'], time: 410227200000.0, }, { key: ['Jennifer'], value: 5829.0, name: ['Jennifer'], time: 410227200000.0, }, { key: ['Michael'], value: 7386.0, name: ['Michael'], time: 410227200000.0, }, ], '441763200000000000': [ { key: ['Christopher'], value: 6509.0, name: ['Christopher'], time: 441763200000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 441763200000.0, }, { key: ['David'], value: 0, name: ['David'], time: 441763200000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 441763200000.0, }, { key: ['Michael'], value: 7478.0, name: ['Michael'], time: 441763200000.0, }, ], '473385600000000000': [ { key: ['Christopher'], value: 6744.0, name: ['Christopher'], time: 473385600000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 473385600000.0, }, { key: ['David'], value: 0, name: ['David'], time: 473385600000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 473385600000.0, }, { key: ['Michael'], value: 7210.0, name: ['Michael'], time: 473385600000.0, }, ], '504921600000000000': [ { key: ['Christopher'], value: 6497.0, name: ['Christopher'], time: 504921600000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 504921600000.0, }, { key: ['David'], value: 0, name: ['David'], time: 504921600000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 504921600000.0, }, { key: ['Michael'], value: 7259.0, name: ['Michael'], time: 504921600000.0, }, ], '536457600000000000': [ { key: ['Christopher'], value: 6549.0, name: ['Christopher'], time: 536457600000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 536457600000.0, }, { key: ['David'], value: 0, name: ['David'], time: 536457600000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 536457600000.0, }, { key: ['Michael'], value: 7448.0, name: ['Michael'], time: 536457600000.0, }, ], '567993600000000000': [ { key: ['Christopher'], value: 6496.0, name: ['Christopher'], time: 567993600000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 567993600000.0, }, { key: ['David'], value: 0, name: ['David'], time: 567993600000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 567993600000.0, }, { key: ['Michael'], value: 7748.0, name: ['Michael'], time: 567993600000.0, }, ], '599616000000000000': [ { key: ['Christopher'], value: 6526.0, name: ['Christopher'], time: 599616000000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 599616000000.0, }, { key: ['David'], value: 0, name: ['David'], time: 599616000000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 599616000000.0, }, { key: ['Michael'], value: 7851.0, name: ['Michael'], time: 599616000000.0, }, ], '631152000000000000': [ { key: ['Christopher'], value: 6641.0, name: ['Christopher'], time: 631152000000.0, }, { key: ['Daniel'], value: 5760.0, name: ['Daniel'], time: 631152000000.0, }, { key: ['David'], value: 0, name: ['David'], time: 631152000000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 631152000000.0, }, { key: ['Michael'], value: 8233.0, name: ['Michael'], time: 631152000000.0, }, ], '662688000000000000': [ { key: ['Christopher'], value: 5784.0, name: ['Christopher'], time: 662688000000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 662688000000.0, }, { key: ['David'], value: 0, name: ['David'], time: 662688000000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 662688000000.0, }, { key: ['Michael'], value: 7579.0, name: ['Michael'], time: 662688000000.0, }, ], '694224000000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 694224000000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 694224000000.0, }, { key: ['David'], value: 0, name: ['David'], time: 694224000000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 694224000000.0, }, { key: ['Michael'], value: 6627.0, name: ['Michael'], time: 694224000000.0, }, ], '725846400000000000': [ { key: ['Christopher'], value: 0, name: ['Christopher'], time: 725846400000.0, }, { key: ['Daniel'], value: 0, name: ['Daniel'], time: 725846400000.0, }, { key: ['David'], value: 0, name: ['David'], time: 725846400000.0, }, { key: ['Jennifer'], value: 0, name: ['Jennifer'], time: 725846400000.0, }, { key: ['Michael'], value: 5839.0, name: ['Michael'], time: 725846400000.0, }, ], };
the_stack
import { options, tasks, domData, triggerEvent, cleanNode } from '@tko/utils' import { observableArray, observable, isWritableObservable } from '@tko/observable' import { MultiProvider } from '@tko/provider.multi' import { DataBindProvider } from '@tko/provider.databind' import { VirtualProvider } from '@tko/provider.virtual' import { ComponentProvider } from '@tko/provider.component' import { NativeProvider } from '@tko/provider.native' import { applyBindings, dataFor } from '@tko/bind' import { bindings as coreBindings } from '@tko/binding.core' import { bindings as templateBindings } from '@tko/binding.template' import { bindings as ifBindings } from '@tko/binding.if' import { JsxObserver } from '@tko/utils.jsx' import { bindings as componentBindings } from '../dist' import components from '@tko/utils.component' import { useMockForTasks } from '@tko/utils/helpers/jasmine-13-helper' describe('Components: Component binding', function () { var testComponentName = 'test-component', testComponentBindingValue, testComponentParams, outerViewModel beforeEach(function () { useMockForTasks(options) jasmine.prepareTestNode() testComponentParams = {} testComponentBindingValue = { name: testComponentName, params: testComponentParams } outerViewModel = { testComponentBindingValue: testComponentBindingValue, isOuterViewModel: true } testNode.innerHTML = '<div data-bind="component: testComponentBindingValue"></div>' var provider = new MultiProvider({ providers: [ new ComponentProvider(), new DataBindProvider(), new VirtualProvider(), new NativeProvider(), ] }) options.bindingProviderInstance = provider provider.bindingHandlers.set(templateBindings) provider.bindingHandlers.set(ifBindings) provider.bindingHandlers.set(coreBindings) provider.bindingHandlers.set(componentBindings) }) afterEach(function () { expect(tasks.resetForTesting()).toEqual(0) jasmine.Clock.reset() components.unregister(testComponentName) }) it('Throws if no name is specified (name provided directly)', function () { testNode.innerHTML = '<div data-bind="component: \'\'"></div>' expect(function () { applyBindings(null, testNode) }) .toThrowContaining('No component name specified') }) it('Throws if no name is specified (using options object)', function () { delete testComponentBindingValue.name expect(function () { applyBindings(outerViewModel, testNode) }) .toThrowContaining('No component name specified') }) it('Throws if the component name is unknown', function () { expect(function () { applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) }).toThrow("Unknown component 'test-component'") }) it('Throws if the component definition has no template', function () { components.register(testComponentName, {}) expect(function () { applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) }).toThrow("Component 'test-component' has no template") }) it('Controls descendant bindings', function () { components.register(testComponentName, { template: 'x' }) testNode.innerHTML = '<div data-bind="if: true, component: $data"></div>' expect(function () { applyBindings(testComponentName, testNode) }) .toThrowContaining('Multiple bindings (if and component) are trying to control descendant bindings of the same element.') // Even though applyBindings threw an exception, the component still gets bound (asynchronously) jasmine.Clock.tick(1) }) it('Replaces the element\'s contents with a clone of the template', function () { var testTemplate = document.createDocumentFragment() testTemplate.appendChild(document.createElement('div')) testTemplate.appendChild(document.createTextNode(' ')) testTemplate.appendChild(document.createElement('span')) testTemplate.childNodes[0].innerHTML = 'hello' testTemplate.childNodes[2].innerHTML = 'world' components.register(testComponentName, { template: testTemplate }) // Bind using just the component name since we're not setting any params applyBindings({ testComponentBindingValue: testComponentName }, testNode) // See the template asynchronously shows up jasmine.Clock.tick(1) expect(testNode.childNodes[0]).toContainHtml('<div>hello</div> <span>world</span>') // Also be sure it's a clone expect(testNode.childNodes[0].childNodes[0]).not.toBe(testTemplate[0]) }) it('Passes params and componentInfo (with prepopulated element and templateNodes) to the component\'s viewmodel factory', function () { var componentConfig = { template: '<div data-bind="text: 123">I have been prepopulated and not bound yet</div>', viewModel: { createViewModel: function (params, componentInfo) { expect(componentInfo.element).toContainText('I have been prepopulated and not bound yet') expect(params).toBe(testComponentParams) expect(componentInfo.templateNodes.length).toEqual(3) expect(componentInfo.templateNodes[0]).toContainText('Here are some ') expect(componentInfo.templateNodes[1]).toContainText('template') expect(componentInfo.templateNodes[2]).toContainText(' nodes') expect(componentInfo.templateNodes[1].tagName.toLowerCase()).toEqual('em') // verify that createViewModel is the same function and was called with the component definition as the context expect(this.createViewModel).toBe(componentConfig.viewModel.createViewModel) expect(this.template).toBeDefined() componentInfo.element.childNodes[0].setAttribute('data-bind', 'text: someValue') return { someValue: 'From the viewmodel' } } } } testNode.innerHTML = '<div data-bind="component: testComponentBindingValue">Here are some <em>template</em> nodes</div>' components.register(testComponentName, componentConfig) applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) expect(testNode).toContainText('From the viewmodel') }) it('Handles absence of viewmodel by using the params', function () { components.register(testComponentName, { template: '<div data-bind="text: myvalue"></div>' }) testComponentParams.myvalue = 'some parameter value' applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) expect(testNode.childNodes[0]).toContainHtml('<div data-bind="text: myvalue">some parameter value</div>') }) it('Injects and binds the component synchronously if it is flagged as synchronous and loads synchronously', function () { components.register(testComponentName, { synchronous: true, template: '<div data-bind="text: myvalue"></div>', viewModel: function () { this.myvalue = 123 } }) // Notice the absence of any 'jasmine.Clock.tick' call here. This is synchronous. applyBindings(outerViewModel, testNode) expect(testNode.childNodes[0]).toContainHtml('<div data-bind="text: myvalue">123</div>') }) it('Injects and binds the component synchronously if it is flagged as synchronous and already cached, even if it previously loaded asynchronously', function () { // Set up a component that loads asynchronously, but is flagged as being injectable synchronously this.restoreAfter(window, 'require') // var requireCallbacks = {}; window.require = function (moduleNames, callback) { expect(moduleNames[0]).toBe('testViewModelModule') setTimeout(function () { var constructor = function (params) { this.viewModelProperty = params } callback(constructor) }, 0) } components.register(testComponentName, { synchronous: true, template: '<div data-bind="text: viewModelProperty"></div>', viewModel: { require: 'testViewModelModule' } }) var testList = observableArray(['first']) testNode.innerHTML = '<div data-bind="foreach: testList">' + '<div data-bind="component: { name: \'test-component\', params: $data }"></div>' + '</div>' // First injection is async, because the loader completes asynchronously applyBindings({ testList: testList }, testNode) expect(testNode.childNodes[0]).toContainText('') jasmine.Clock.tick(0) expect(testNode.childNodes[0]).toContainText('first') // Second (cached) injection is synchronous, because the component config says so. // Notice the absence of any 'jasmine.Clock.tick' call here. This is synchronous. testList.push('second') expect(testNode.childNodes[0]).toContainText('firstsecond', /* ignoreSpaces */ true) // Ignore spaces because old-IE is inconsistent }) it('Creates a binding context with the correct parent', function () { components.register(testComponentName, { template: 'Parent is outer view model: <span data-bind="text: $parent.isOuterViewModel"></span>' }) applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) expect(testNode.childNodes[0]).toContainText('Parent is outer view model: true') }) it('Creates a binding context with $componentTemplateNodes giving the original child nodes', function () { components.register(testComponentName, { template: 'Start<span data-bind="template: { nodes: $componentTemplateNodes }"></span>End' }) testNode.innerHTML = '<div data-bind="component: testComponentBindingValue"><em>original</em> child nodes</div>' applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) expect(testNode.childNodes[0]).toContainHtml('start<span data-bind="template: { nodes: $componenttemplatenodes }"><em>original</em> child nodes</span>end') }) it('Creates a binding context with $component to reference the closest component viewmodel', function () { this.after(function () { components.unregister('sub-component') }) components.register(testComponentName, { template: '<span data-bind="with: { childContext: 123 }">' + 'In child context <!-- ko text: childContext --><!-- /ko -->, ' + 'inside component with property <!-- ko text: $component.componentProp --><!-- /ko -->. ' + '<div data-bind="component: \'sub-component\'"></div>' + '</span>', viewModel: function () { return { componentProp: 456 } } }) // See it works with nesting - $component always refers to the *closest* component root components.register('sub-component', { template: 'Now in sub-component with property <!-- ko text: $component.componentProp --><!-- /ko -->.', viewModel: function () { return { componentProp: 789 } } }) applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) expect(testNode.childNodes[0]).toContainText('In child context 123, inside component with property 456. Now in sub-component with property 789.', /* ignoreSpaces */ true) // Ignore spaces because old-IE is inconsistent }) it('Passes nonobservable params to the component', function () { // Set up a component that logs its constructor params var receivedParams = [] components.register(testComponentName, { viewModel: function (params) { receivedParams.push(params) }, template: 'Ignored' }) testComponentParams.someValue = 123 // Instantiate it applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) // See the params arrived as expected expect(receivedParams).toEqual([testComponentParams]) expect(testComponentParams.someValue).toBe(123) // Just to be sure it doesn't get mutated }) it('Passes through observable params without unwrapping them (so a given component instance can observe them changing)', function () { // Set up a component that logs its constructor params var receivedParams = [] components.register(testComponentName, { viewModel: function (params) { receivedParams.push(params) this.someValue = params.someValue }, template: 'The value is <span data-bind="text: someValue"></span>.' }) testComponentParams.someValue = observable(123) // Instantiate it applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) // See the params arrived as expected expect(receivedParams).toEqual([testComponentParams]) expect(testNode).toContainText('The value is 123.') // Mutating the observable doesn't trigger creation of a new component testComponentParams.someValue(456) expect(receivedParams.length).toBe(1) // i.e., no additional constructor call occurred expect(testNode).toContainText('The value is 456.') }) it('Supports observable component names, rebuilding the component if the name changes, disposing the old viewmodel and nodes', function () { this.after(function () { components.unregister('component-alpha') components.unregister('component-beta') }) function alphaViewModel (params) { this.alphaValue = params.suppliedValue } function betaViewModel (params) { this.betaValue = params.suppliedValue } alphaViewModel.prototype.dispose = function () { expect(arguments.length).toBe(0) this.alphaWasDisposed = true // Disposal happens *before* the DOM is torn down, in case some custom cleanup is required // Note that you'd have to have captured the element via createViewModel, so this is only // for extensibility scenarios - we don't generally recommend that component viewmodels // should interact directly with their DOM, as that breaks MVVM encapsulation. expect(testNode).toContainText('Alpha value is 234.') } components.register('component-alpha', { viewModel: alphaViewModel, template: '<div class="alpha">Alpha value is <span data-bind="text: alphaValue"></span>.</div>' }) components.register('component-beta', { viewModel: betaViewModel, template: '<div class="beta">Beta value is <span data-bind="text: betaValue"></span>.</div>' }) // Instantiate the first component testComponentBindingValue.name = observable('component-alpha') testComponentParams.suppliedValue = observable(123) applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) // See it appeared, and the expected subscriptions were registered var firstAlphaTemplateNode = testNode.firstChild.firstChild, alphaViewModelInstance = dataFor(firstAlphaTemplateNode) expect(firstAlphaTemplateNode.className).toBe('alpha') expect(testNode).toContainText('Alpha value is 123.') expect(testComponentBindingValue.name.getSubscriptionsCount()).toBe(1) expect(testComponentParams.suppliedValue.getSubscriptionsCount()).toBe(1) expect(alphaViewModelInstance.alphaWasDisposed).not.toBe(true) // Store some data on a DOM node so we can check it was cleaned later domData.set(firstAlphaTemplateNode, 'TestValue', 'Hello') // Mutating an observable param doesn't change the set of subscriptions or replace the DOM nodes testComponentParams.suppliedValue(234) expect(testNode).toContainText('Alpha value is 234.') expect(testComponentBindingValue.name.getSubscriptionsCount()).toBe(1) expect(testComponentParams.suppliedValue.getSubscriptionsCount()).toBe(1) expect(testNode.firstChild.firstChild).toBe(firstAlphaTemplateNode) // Same node expect(domData.get(firstAlphaTemplateNode, 'TestValue')).toBe('Hello') // Not cleaned expect(alphaViewModelInstance.alphaWasDisposed).not.toBe(true) // Can switch to the other component by observably changing the component name, // but it happens asynchronously (because the component has to be loaded) testComponentBindingValue.name('component-beta') expect(testNode).toContainText('Alpha value is 234.') jasmine.Clock.tick(1) expect(testNode).toContainText('Beta value is 234.') // Cleans up by disposing obsolete subscriptions, viewmodels, and cleans DOM nodes expect(testComponentBindingValue.name.getSubscriptionsCount()).toBe(1) expect(testComponentParams.suppliedValue.getSubscriptionsCount()).toBe(1) expect(domData.get(firstAlphaTemplateNode, 'TestValue')).toBe(undefined) // Got cleaned expect(alphaViewModelInstance.alphaWasDisposed).toBe(true) }) it('Supports binding to an observable that contains name/params, rebuilding the component if that observable changes, disposing the old viewmodel and nodes', function () { this.after(function () { components.unregister('component-alpha') components.unregister('component-beta') }) function alphaViewModel (params) { this.alphaValue = params.suppliedValue } function betaViewModel (params) { this.betaValue = params.suppliedValue } alphaViewModel.prototype.dispose = function () { expect(arguments.length).toBe(0) this.alphaWasDisposed = true // Disposal happens *before* the DOM is torn down, in case some custom cleanup is required // Note that you'd have to have captured the element via createViewModel, so this is only // for extensibility scenarios - we don't generally recommend that component viewmodels // should interact directly with their DOM, as that breaks MVVM encapsulation. expect(testNode).toContainText('Alpha value is 123.') } components.register('component-alpha', { viewModel: alphaViewModel, template: '<div class="alpha">Alpha value is <span data-bind="text: alphaValue"></span>.</div>' }) components.register('component-beta', { viewModel: betaViewModel, template: '<div class="beta">Beta value is <span data-bind="text: betaValue"></span>.</div>' }) outerViewModel.testComponentBindingValue = observable({ name: 'component-alpha', params: { suppliedValue: 123 } }) // Instantiate the first component applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) // See it appeared, and the expected subscriptions were registered var firstAlphaTemplateNode = testNode.firstChild.firstChild, alphaViewModelInstance = dataFor(firstAlphaTemplateNode) expect(firstAlphaTemplateNode.className).toBe('alpha') expect(testNode).toContainText('Alpha value is 123.') expect(outerViewModel.testComponentBindingValue.getSubscriptionsCount()).toBe(1) expect(alphaViewModelInstance.alphaWasDisposed).not.toBe(true) // Store some data on a DOM node so we can check it was cleaned later domData.set(firstAlphaTemplateNode, 'TestValue', 'Hello') // Can switch to the other component by changing observable, // but it happens asynchronously (because the component has to be loaded) outerViewModel.testComponentBindingValue({ name: 'component-beta', params: { suppliedValue: 456 } }) expect(testNode).toContainText('Alpha value is 123.') jasmine.Clock.tick(1) expect(testNode).toContainText('Beta value is 456.') // Cleans up by disposing obsolete subscriptions, viewmodels, and cleans DOM nodes expect(outerViewModel.testComponentBindingValue.getSubscriptionsCount()).toBe(1) expect(domData.get(firstAlphaTemplateNode, 'TestValue')).toBe(undefined) // Got cleaned expect(alphaViewModelInstance.alphaWasDisposed).toBe(true) }) it('Rebuilds the component if params change in a way that is forced to unwrap inside the binding, disposing the old viewmodel and nodes', function () { function testViewModel (params) { this.myData = params.someData } testViewModel.prototype.dispose = function () { this.wasDisposed = true } components.register(testComponentName, { viewModel: testViewModel, template: '<div>Value is <span data-bind="text: myData"></span>.</div>' }) // Instantiate the first component, via a binding that unwraps an observable before it reaches the component var someObservable = observable('First') testNode.innerHTML = '<div data-bind="component: { name: \'' + testComponentName + '\', params: { someData: someObservable() } }"></div>' applyBindings({ someObservable: someObservable }, testNode) jasmine.Clock.tick(1) var firstTemplateNode = testNode.firstChild.firstChild, firstViewModelInstance = dataFor(firstTemplateNode) expect(firstViewModelInstance instanceof testViewModel).toBe(true) expect(testNode).toContainText('Value is First.') expect(firstViewModelInstance.wasDisposed).not.toBe(true) domData.set(firstTemplateNode, 'TestValue', 'Hello') // Make an observable change that forces the component to rebuild (asynchronously, for consistency) someObservable('Second') expect(testNode).toContainText('Value is First.') expect(firstViewModelInstance.wasDisposed).not.toBe(true) expect(domData.get(firstTemplateNode, 'TestValue')).toBe('Hello') jasmine.Clock.tick(1) expect(testNode).toContainText('Value is Second.') expect(firstViewModelInstance.wasDisposed).toBe(true) expect(domData.get(firstTemplateNode, 'TestValue')).toBe(undefined) // New viewmodel is a new instance var secondViewModelInstance = dataFor(testNode.firstChild.firstChild) expect(secondViewModelInstance instanceof testViewModel).toBe(true) expect(secondViewModelInstance).not.toBe(firstViewModelInstance) }) it('Is possible to pass expressions that can vary observably and evaluate as writable observable instances', function () { // This spec is copied, with small modifications, from customElementBehaviors.js to show that the same component // definition can be used with the component binding and with custom elements. var constructorCallCount = 0 components.register('test-component', { template: '<input data-bind="value: myval"/>', viewModel: function (params) { constructorCallCount++ this.myval = params.somevalue // See we received a writable observable expect(isWritableObservable(this.myval)).toBe(true) } }) // Bind to a viewmodel with nested observables; see the expression is evaluated as expected // The component itself doesn't have to know or care that the supplied value is nested - the // custom element syntax takes care of producing a single computed property that gives the // unwrapped inner value. var innerObservable = observable('inner1'), outerObservable = observable({ inner: innerObservable }) testNode.innerHTML = '<div data-bind="component: { name: \'' + testComponentName + '\', params: { somevalue: outer().inner } }"></div>' applyBindings({ outer: outerObservable }, testNode) jasmine.Clock.tick(1) expect(testNode.childNodes[0].childNodes[0].value).toEqual('inner1') expect(outerObservable.getSubscriptionsCount()).toBe(1) expect(innerObservable.getSubscriptionsCount()).toBe(1) expect(constructorCallCount).toBe(1) // See we can mutate the inner value and see the result show up innerObservable('inner2') expect(testNode.childNodes[0].childNodes[0].value).toEqual('inner2') expect(outerObservable.getSubscriptionsCount()).toBe(1) expect(innerObservable.getSubscriptionsCount()).toBe(1) expect(constructorCallCount).toBe(1) // See that we can mutate the observable from within the component testNode.childNodes[0].childNodes[0].value = 'inner3' triggerEvent(testNode.childNodes[0].childNodes[0], 'change') expect(innerObservable()).toEqual('inner3') // See we can mutate the outer value and see the result show up (cleaning subscriptions to the old inner value) var newInnerObservable = observable('newinner') outerObservable({ inner: newInnerObservable }) jasmine.Clock.tick(1) // modifying the outer observable causes the component to reload, which happens asynchronously expect(testNode.childNodes[0].childNodes[0].value).toEqual('newinner') expect(outerObservable.getSubscriptionsCount()).toBe(1) expect(innerObservable.getSubscriptionsCount()).toBe(0) expect(newInnerObservable.getSubscriptionsCount()).toBe(1) expect(constructorCallCount).toBe(2) // See that we can mutate the new observable from within the component testNode.childNodes[0].childNodes[0].value = 'newinner2' triggerEvent(testNode.childNodes[0].childNodes[0], 'change') expect(newInnerObservable()).toEqual('newinner2') expect(innerObservable()).toEqual('inner3') // original one hasn't changed // See that subscriptions are disposed when the component is cleanNode(testNode) expect(outerObservable.getSubscriptionsCount()).toBe(0) expect(innerObservable.getSubscriptionsCount()).toBe(0) expect(newInnerObservable.getSubscriptionsCount()).toBe(0) }) it('Disposes the viewmodel if the element is cleaned', function () { class TestViewModel { dispose () { this.wasDisposed = true } } components.register(testComponentName, { viewModel: TestViewModel, template: '<div>Ignored</div>' }) // Bind an instance of the component; grab its viewmodel applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) var firstTemplateNode = testNode.firstChild.firstChild, viewModelInstance = dataFor(firstTemplateNode) expect(viewModelInstance instanceof TestViewModel).toBe(true) expect(viewModelInstance.wasDisposed).not.toBe(true) // See that cleaning the associated element automatically disposes the viewmodel cleanNode(testNode.firstChild) expect(viewModelInstance.wasDisposed).toBe(true) }) it('Does not inject the template or instantiate the viewmodel if the element was cleaned before component loading completed', function () { var numConstructorCalls = 0 components.register(testComponentName, { viewModel: function () { numConstructorCalls++ }, template: '<div>Should not be used</div>' }) // Bind an instance of the component; grab its viewmodel applyBindings(outerViewModel, testNode) // Before the component finishes loading, clean the DOM cleanNode(testNode.firstChild) // Now wait and see that, after loading finishes, the component wasn't used jasmine.Clock.tick(1) expect(numConstructorCalls).toBe(0) expect(testNode.firstChild).toContainHtml('') }) it('Disregards component load completions that are no longer relevant', function () { // This spec addresses the possibility of a race condition: if you change the // component name faster than the component loads complete, then we need to // ignore any load completions that don't correspond to the latest name. // Otherwise it's inefficient if the loads complete in order (pointless extra // binding), and broken if they complete out of order (wrong final result). // Set up a mock module loader, so we can control asynchronous load completion this.restoreAfter(window, 'require') var requireCallbacks = {} window.require = function (moduleNames, callback) { expect(moduleNames.length).toBe(1) // In this scenario, it always will be expect(moduleNames[0] in requireCallbacks).toBe(false) // In this scenario, we only require each module once requireCallbacks[moduleNames[0]] = callback } // Define four separate components so we can switch between them var constructorCallLog = [] function testViewModel1 (params) { constructorCallLog.push([1, params]) } function testViewModel2 (params) { constructorCallLog.push([2, params]) } function testViewModel3 (params) { constructorCallLog.push([3, params]) } function testViewModel4 (params) { constructorCallLog.push([4, params]) } testViewModel3.prototype.dispose = function () { this.wasDisposed = true } components.register('component-1', { viewModel: { require: 'module-1' }, template: '<div>Component 1 template</div>' }) components.register('component-2', { viewModel: { require: 'module-2' }, template: '<div>Component 2 template</div>' }) components.register('component-3', { viewModel: { require: 'module-3' }, template: '<div>Component 3 template</div>' }) components.register('component-4', { viewModel: { require: 'module-4' }, template: '<div>Component 4 template</div>' }) this.after(function () { for (var i = 0; i < 4; i++) { components.unregister('component-' + i) } }) // Start by requesting component 1 testComponentBindingValue.name = observable('component-1') applyBindings(outerViewModel, testNode) // Even if we wait a while, it's not yet loaded, because we're still waiting for the module jasmine.Clock.tick(10) expect(constructorCallLog.length).toBe(0) expect(testNode.firstChild.childNodes.length).toBe(0) // In the meantime, switch to requesting component 2 and then 3 testComponentBindingValue.name('component-2') jasmine.Clock.tick(1) testComponentBindingValue.name('component-3') expect(constructorCallLog.length).toBe(0) // Now if component 1 finishes loading, it's irrelevant, so nothing happens requireCallbacks['module-1'](testViewModel1) jasmine.Clock.tick(1) // ... even if we wait a bit longer expect(constructorCallLog.length).toBe(0) expect(testNode.firstChild.childNodes.length).toBe(0) // Now if component 3 finishes loading, it's the current one, so we instantiate and bind to it. // Notice this happens synchronously (at least, relative to the time now), because the completion // is already asynchronous relative to when it began. requireCallbacks['module-3'](testViewModel3) expect(constructorCallLog).toEqual([ [3, testComponentParams] ]) expect(testNode).toContainText('Component 3 template') var viewModelInstance = dataFor(testNode.firstChild.firstChild) expect(viewModelInstance instanceof testViewModel3).toBe(true) expect(viewModelInstance.wasDisposed).not.toBe(true) // Now if component 2 finishes loading, it's irrelevant, so nothing happens. // In particular, the viewmodel isn't disposed. requireCallbacks['module-2'](testViewModel2) jasmine.Clock.tick(1) // ... even if we wait a bit longer expect(constructorCallLog.length).toBe(1) expect(testNode).toContainText('Component 3 template') expect(viewModelInstance.wasDisposed).not.toBe(true) // However, if we now switch to component 2, the old viewmodel is disposed, // and the new component is used without any further module load calls. testComponentBindingValue.name('component-2') jasmine.Clock.tick(1) expect(constructorCallLog.length).toBe(2) expect(testNode).toContainText('Component 2 template') expect(viewModelInstance.wasDisposed).toBe(true) // Show also that we won't leak memory by applying bindings to nodes // after they were disposed (e.g., because they were removed from the document) testComponentBindingValue.name('component-4') jasmine.Clock.tick(1) cleanNode(testNode.firstChild) // Dispose the node before the module loading completes requireCallbacks['module-4'](testViewModel4) expect(constructorCallLog.length).toBe(2) // No extra constructor calls expect(testNode).toContainText('Component 2 template') // No attempt to modify the DOM }) it('Supports virtual elements', function () { testNode.innerHTML = 'Hello! <!-- ko component: testComponentBindingValue -->&nbsp;<!-- /ko --> Goodbye.' components.register(testComponentName, { template: 'Your param is <span data-bind="text: someData">&nbsp;</span>' }) testComponentParams.someData = observable(123) applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) expect(testNode).toContainText('Hello! Your param is 123 Goodbye.') testComponentParams.someData(456) expect(testNode).toContainText('Hello! Your param is 456 Goodbye.') }) it('Should call a childrenComplete callback function', function () { testNode.innerHTML = '<div data-bind="component: testComponentBindingValue, childrenComplete: callback"></div>' components.register(testComponentName, { template: '<div data-bind="text: myvalue"></div>' }) testComponentParams.myvalue = 'some parameter value' var callbacks = 0 outerViewModel.callback = function (nodes, data) { expect(nodes.length).toEqual(1) expect(nodes[0]).toEqual(testNode.childNodes[0].childNodes[0]) expect(data).toEqual(testComponentParams) callbacks++ } applyBindings(outerViewModel, testNode) expect(callbacks).toEqual(0) jasmine.Clock.tick(1) expect(testNode.childNodes[0]).toContainHtml('<div data-bind="text: myvalue">some parameter value</div>') expect(callbacks).toEqual(1) }) describe('Component `bindingHandlers`', function () { it('overloads existing and provides new bindings', function () { const calls = [] testNode.innerHTML = `<with-my-bindings></with-my-bindings>` class ViewModel { getBindingHandler (bindingKey) { return { text: () => calls.push('text'), text2: () => calls.push('text2') }[bindingKey] } } const template = ` <span data-bind='text: "123"'></span> <span data-bind='text2: "123"'></span>` components.register('with-my-bindings', {viewModel: ViewModel, template, synchronous: true}) applyBindings({}, testNode) expect(calls).toEqual(['text', 'text2']) }) }) describe('Does not automatically subscribe to any observables you evaluate during createViewModel or a viewmodel constructor', function () { // This clarifies that, if a developer wants to react when some observable parameter // changes, then it's their responsibility to subscribe to it or use a computed. // We don't rebuild the component just because you evaluated an observable from inside // your viewmodel constructor, just like we don't if you evaluate one elsewhere // in the viewmodel code. it('when loaded asynchronously', function () { components.register(testComponentName, { viewModel: { createViewModel: function (params/*, componentInfo */) { return { someData: params.someData() } } }, template: '<div data-bind="text: someData"></div>' }) // Bind an instance testComponentParams.someData = observable('First') applyBindings(outerViewModel, testNode) jasmine.Clock.tick(1) expect(testNode).toContainText('First') expect(testComponentParams.someData.getSubscriptionsCount()).toBe(0) // See that changing the observable will have no effect testComponentParams.someData('Second') jasmine.Clock.tick(1) expect(testNode).toContainText('First') }) it('when loaded synchronously', function () { components.register(testComponentName, { synchronous: true, viewModel: { createViewModel: function (params/*, componentInfo */) { return { someData: params.someData() } } }, template: '<div data-bind="text: someData"></div>' }) // Bind an instance testComponentParams.someData = observable('First') applyBindings(outerViewModel, testNode) expect(testNode).toContainText('First') expect(testComponentParams.someData.getSubscriptionsCount()).toBe(0) // See that changing the observable will have no effect testComponentParams.someData('Second') expect(testNode).toContainText('First') }) it('when cached component is loaded synchronously', function () { components.register(testComponentName, { synchronous: true, viewModel: { createViewModel: function (params/*, componentInfo */) { return { someData: params.someData() } } }, template: '<div data-bind="text: someData"></div>' }) // Load the component manually so that the next load happens from the cache components.get(testComponentName, function () {}) // Bind an instance testComponentParams.someData = observable('First') applyBindings(outerViewModel, testNode) expect(testNode).toContainText('First') expect(testComponentParams.someData.getSubscriptionsCount()).toBe(0) // See that changing the observable will have no effect testComponentParams.someData('Second') expect(testNode).toContainText('First') }) }) it('uses the template from a view model, if a component template is not defined', function () { class ViewModel extends components.ComponentABC { get template () { return [document.createElement(`inner-bits`)] } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.innerHTML).toContain('<inner-bits></inner-bits>') }) describe('jsx', function () { it('accepts and uses jsx', function () { class ViewModel extends components.ComponentABC { static get template () { return { elementName: 'div', attributes: { attr: '123' }, children: ['téxt'] } } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerHTML).toEqual('<div attr="123">téxt</div>') }) it('updates jsx on changes', function () { const obs = observable('v0') const o2 = observable('text') class ViewModel extends components.ComponentABC { static get template () { // Passing <div attr={obs}>{o2}</div> through // babel-plugin-transform-jsx will yield: return { elementName: 'div', attributes: { attr: obs }, children: [o2] } } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerHTML).toEqual('<div attr="v0">text<!--O--></div>') obs('v1') expect(testNode.children[0].innerHTML).toEqual('<div attr="v1">text<!--O--></div>') obs(undefined) expect(testNode.children[0].innerHTML).toEqual('<div>text<!--O--></div>') o2({ elementName: 'i', children: ['g'], attributes: {} }) expect(testNode.children[0].innerHTML).toEqual('<div><i>g</i><!--O--></div>') o2(undefined) expect(testNode.children[0].innerHTML).toEqual('<div><!--O--></div>') }) it('inserts a partial when the `template` is an array', function () { class ViewModel extends components.ComponentABC { static get template () { return [ { elementName: 'b', attributes: { }, children: ['x'] }, { elementName: 'i', attributes: { }, children: ['y'] }, { elementName: 'em', attributes: { }, children: ['z'] } ] } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerHTML).toEqual('<b>x</b><i>y</i><em>z</em>') expect(testNode.childNodes[0] instanceof HTMLElement).toBeTruthy() expect(testNode.childNodes[0].childNodes[0] instanceof HTMLElement).toBeTruthy() expect(testNode.childNodes[0].childNodes[1] instanceof HTMLElement).toBeTruthy() }) it('inserts partials from `children`', function () { const children = [ 'abc', { elementName: 'c', attributes: {}, children: [['C']] } ] class ViewModel extends components.ComponentABC { static get template () { return [ { elementName: 'b', attributes: { }, children: ['x', children] } ] } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerHTML).toEqual('<b>xabc<c>C</c></b>') }) it('inserts & updates observable partials from `children`', function () { const children = observableArray([ 'abc', { elementName: 'c', attributes: {}, children: [['C']] } ]) class ViewModel extends components.ComponentABC { static get template () { return [ { elementName: 'b', attributes: { }, children: ['x', children] } ] } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerHTML).toEqual('<b>xabc<c>C</c><!--O--></b>') children.pop() expect(testNode.children[0].innerHTML).toEqual('<b>xabc<!--O--></b>') children.unshift('rrr') expect(testNode.children[0].innerHTML).toEqual('<b>xrrrabc<!--O--></b>') }) it('inserts and updates observable template', function () { const t = observable(["abc"]) class ViewModel extends components.ComponentABC { get template () { return t } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerHTML).toEqual('abc<!--O-->') t(["rr", "vv"]) expect(testNode.children[0].innerHTML).toEqual('rrvv<!--O-->') }) it('gets params from the node', function () { const x = {v: 'rrr'} let seen = null class ViewModel extends components.ComponentABC { constructor (params) { super(params) seen = params } static get template () { return { elementName: 'name', attributes: {}, children: [] } } } ViewModel.register('test-component') NativeProvider.addValueToNode(testNode.children[0], 'x', x) NativeProvider.addValueToNode(testNode.children[0], 'y', () => x) applyBindings(outerViewModel, testNode) expect(seen.x).toEqual(x) expect(seen.y()).toEqual(x) expect(testNode.childNodes[0] instanceof HTMLElement).toBeTruthy() expect(testNode.childNodes[0].childNodes[0] instanceof HTMLElement).toBeTruthy() }) it('binds context for ViewModel::template', () => { class ViewModel extends components.ComponentABC { get template () { return { elementName: 'a', children: [], attributes: {} } } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(dataFor(testNode.childNodes[0])).toEqual(outerViewModel) }) it('binds context for ViewModel.template', () => { class ViewModel extends components.ComponentABC { static get template () { return { elementName: 'a', children: [], attributes: {} } } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(dataFor(testNode.childNodes[0])).toEqual(outerViewModel) }) }) // /jsx describe('slots', function () { it('inserts into <slot> content with the named slot template', function () { testNode.innerHTML = ` <test-component> <template slot='alpha'>beep</template> </test-component> ` class ViewModel extends components.ComponentABC { static get template () { return ` <div> <i data-bind='slot: "alpha"'></i> </div> ` } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerText.trim()).toEqual(`beep`) }) it('inserts into virtual element slot with the slot template', function () { testNode.innerHTML = ` <test-component> <template slot='alpha'>beep</template> </test-component> ` class ViewModel extends components.ComponentABC { static get template () { return ` <div> <!-- ko slot: "alpha" --><!-- /ko --> </div> ` } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerText.trim()).toEqual(`beep`) }) it('inserts multiple times into virtual element slot with the slot template', function () { testNode.innerHTML = ` <test-component> <template slot='alpha'>beep</template> </test-component> ` class ViewModel extends components.ComponentABC { static get template () { return ` <div> <!-- ko slot: "alpha" --><!-- /ko --> / <!-- ko slot: "alpha" --><!-- /ko --> </div> ` } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerText.trim()).toEqual(`beep / beep`) }) it('inserts into nested elements', function () { testNode.innerHTML = ` <test-component> <template slot='alpha'>beep</template> </test-component> ` class ViewModel extends components.ComponentABC { static get template () { return ` <div><i><span> <!-- ko slot: "alpha" --><!-- /ko --> </span></i></div> ` } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerText.trim()).toEqual(`beep`) }) it('inserts the node with the slot name', function () { testNode.innerHTML = ` <test-component> <em slot='alpha'>beep</em> </test-component> ` class ViewModel extends components.ComponentABC { static get template () { return ` <div> <!-- ko slot: "alpha" --><!-- /ko --> </div> ` } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerText.trim()).toEqual(`beep`) const em = testNode.children[0].children[0].children[0] expect(em.tagName).toEqual('EM') expect(em.getAttribute('slot')).toEqual('alpha') }) it('ignores missing slots', function () { testNode.innerHTML = ` <test-component> <template slot='beta'>beep</template> </test-component> ` class ViewModel extends components.ComponentABC { static get template () { return ` <div> <!-- ko slot: "alpha" --><!-- /ko --> </div> ` } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerText.trim()).toEqual(``) }) it('preprocesses <slot> nodes', function () { testNode.innerHTML = ` <test-component> <template slot='alpha'>beep</template> </test-component> ` class ViewModel extends components.ComponentABC { static get template () { return ` <div> <slot name='alpha'></slot> </div> ` } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerText.trim()).toEqual(`beep`) }) it('processes default and named slots', function () { testNode.innerHTML = ` <test-component> <template slot='alpha'>beep</template> Gamma <div>Zeta</div> </test-component> ` class ViewModel extends components.ComponentABC { static get template () { return ` <div> X <slot name='alpha'></slot> Y <slot></slot> Q </div> ` } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) const innerText = testNode.children[0].innerText .replace(/\s+/g, ' ').trim() expect(innerText).toEqual(`X beep Y Gamma Zeta Q`) }) it('inserts all component template nodes in an unnamed (default) slot', function () { testNode.innerHTML = ` <test-component> <em>B.</em> </test-component> ` class ViewModel extends components.ComponentABC { static get template () { return ` <div> A. <slot></slot> C. </div> ` } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerText.trim()).toEqual(`A. B. C.`) const em = testNode.children[0].children[0].children[0] expect(em.tagName).toEqual('EM') }) it('inserts multiple nodes from a <template>', function () { testNode.innerHTML = ` <test-component> <em>B.</em> <i>C.</i> <b>E.</b> </test-component> ` class ViewModel extends components.ComponentABC { static get template () { return ` <div> <slot></slot> </div> ` } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.children[0].innerText.trim()).toEqual(`B. C. E.`) const em = testNode.children[0].children[0].children[0] expect(em.tagName).toEqual('EM') }) it('preserves JSX-based slots', function () { testNode.innerHTML = '' new JsxObserver({ elementName: 'test-component', attributes: {}, children: [{ elementName: 'template', attributes: {slot: 'X'}, children: ['t', 'o'] }] }, testNode) class ViewModel extends components.ComponentABC { static get template () { // As-if it's from JSX: return { elementName: 'div', attributes: {}, children: [ 'A', { elementName: 'slot', attributes: {name: 'X'}, children: [] }, 'B' ] } } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) const text = testNode.children[0].innerText.trim().replace(/\s+/, ' ') expect(text).toEqual('AtoB') }) it('preserves native attributes on child nodes', function () { testNode.innerHTML = '' const attrx = {} const jsx = { elementName: 'test-component', attributes: {}, children: [{ elementName: 'template', attributes: {slot: 'X'}, children: [{ elementName: 'em', attributes: {attrx, attry: 'y', attrz: () => 'z'}, children: [] }] }] } new JsxObserver(jsx, testNode) class ViewModel extends components.ComponentABC { static get template () { // As-if it's from JSX: return { elementName: 'div', attributes: {}, children: [ { elementName: 'slot', attributes: {name: 'X'}, children: [] } ] } } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) const em = testNode.querySelector('em') expect(NativeProvider.getNodeValues(em).attry).toEqual('y') expect(NativeProvider.getNodeValues(em).attrz()).toEqual('z') expect(NativeProvider.getNodeValues(em).attrx).toEqual(attrx) }) it('updates observable nodes', function () { const obs = observable('text') class ViewModel extends components.ComponentABC { static get template () { // As-if it's from JSX: return { elementName: 'div', attributes: {}, children: [obs] } } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.innerText).toEqual('text') expect(testNode.childNodes[0] instanceof HTMLElement).toBeTruthy() expect(testNode.childNodes[0].childNodes[0] instanceof HTMLElement).toBeTruthy() obs('téx†') expect(testNode.innerText).toEqual('téx†') }) it('respects observable array changes with text', function () { testNode.innerHTML = '' const arr = observableArray([]) const jsx = { elementName: 'test-component', attributes: {}, children: [{ elementName: 'template', attributes: {slot: 'X'}, children: [arr] }] } new JsxObserver(jsx, testNode) class ViewModel extends components.ComponentABC { static get template () { // As-if it's from JSX: return { elementName: 'div', attributes: {}, children: [ { elementName: 'slot', attributes: {name: 'X'}, children: [] } ] } } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.innerText).toEqual('') expect(testNode.childNodes[0] instanceof HTMLElement).toBeTruthy() expect(testNode.childNodes[0].childNodes[0] instanceof HTMLElement).toBeTruthy() arr(['abcdef']) expect(testNode.innerHTML).toEqual( '<test-component><div><!--ko slot: "X"-->abcdef<!--/ko--></div></test-component>' ) arr([]) expect(testNode.innerHTML).toEqual( `<test-component><div><!--ko slot: "X"--><!--/ko--></div></test-component>` ) }) it('respects observable array changes with JSX', function () { testNode.innerHTML = '' const arr = observableArray([]) // <test-component> // <template slot='X'>{arr}</template> // </test-component> const jsx = { elementName: 'test-component', attributes: {}, children: [{ elementName: 'template', attributes: {slot: 'X'}, children: [arr] }] } const jo = new JsxObserver(jsx, testNode) class ViewModel extends components.ComponentABC { static get template () { // <div><slot name='X'></slot><div> return { elementName: 'div', attributes: {}, children: [ { elementName: 'slot', attributes: {name: 'X'}, children: [] } ] } } } ViewModel.register('test-component') applyBindings(outerViewModel, testNode) expect(testNode.innerText).toEqual('') expect(testNode.childNodes[0] instanceof HTMLElement).toBeTruthy() expect(testNode.childNodes[0].childNodes[0] instanceof HTMLElement).toBeTruthy() // <div x="1">r</div> arr([{elementName: 'div', children: ['r'], attributes: {x: 1}}, 'text']) expect(testNode.innerHTML).toEqual( '<test-component><div><!--ko slot: "X"--><div x="1">r</div>text<!--/ko--></div></test-component>') jo.dispose() }) }) })
the_stack
import { Task } from 'fp-ts/lib/Task'; import { pipe } from 'fp-ts/lib/function'; import { of, merge, firstValueFrom, lastValueFrom } from 'rxjs'; import { mapTo, take, toArray, delay, mergeMap, map } from 'rxjs/operators'; import { createMockEffectContext, createHttpResponse, createHttpRequest, createTestRoute } from '../../+internal/testing.util'; import { HttpEffect, HttpErrorEffect, HttpOutputEffect } from '../../effects/http.effects.interface'; import { Routing } from '../http.router.interface'; import { resolveRouting } from '../http.router.resolver'; import { factorizeRegExpWithParams } from '../http.router.params.factory'; import { HttpError } from '../../error/http.error.model'; import { HttpStatus } from '../../http.interface'; describe('#resolveRouting', () => { test('resolves routes inside collection', async () => { // given const ctx = createMockEffectContext(); const response = createHttpResponse(); const path1 = factorizeRegExpWithParams('/'); const path2 = factorizeRegExpWithParams('/group'); const path3 = factorizeRegExpWithParams('/group/:id/foo'); const e1$: HttpEffect = req$ => req$.pipe(mapTo({ body: 'test_1' })); const e2$: HttpEffect = req$ => req$.pipe(mapTo({ body: 'test_2' })); const e3$: HttpEffect = req$ => req$.pipe(mapTo({ body: 'test_3' })); const e4$: HttpEffect = req$ => req$.pipe(mapTo({ body: 'test_4' })); const req1 = createHttpRequest(({ url: '/', method: 'GET', response })); const req2 = createHttpRequest(({ url: '/', method: 'POST', response })); const req3 = createHttpRequest(({ url: '/group', method: 'GET', response })); const req4 = createHttpRequest(({ url: '/group/123/foo', method: 'POST', response })); const req5 = createHttpRequest(({ url: '/unknown', method: 'GET', response })); const routing: Routing = [ { regExp: path1.regExp, path: path1.path, methods: { GET: { effect: e1$, middlewares: [] }, POST: { effect: e2$, middlewares: [] } }, }, { regExp: path2.regExp, path: path2.path, methods: { GET: { effect: e3$, middlewares: [], parameters: ['id'] } }, }, { regExp: path3.regExp, path: path3.path, methods: { POST: { effect: e4$, middlewares: [] } }, }, ]; // when const { resolve, outputSubject } = resolveRouting({ routing, ctx }); // then const resultPromise = lastValueFrom(pipe( outputSubject, take(4), toArray(), )); resolve(req1); resolve(req2); resolve(req3); resolve(req4); resolve(req5); const result = await resultPromise; expect(result[0]).toEqual({ body: 'test_1', request: req1 }); expect(result[1]).toEqual({ body: 'test_2', request: req2 }); expect(result[2]).toEqual({ body: 'test_3', request: req3 }); expect(result[3]).toEqual({ body: 'test_4', request: req4 }); }); test('resolves `HttpEffect` only once', async () => { // given const effectSpy = jest.fn(); const ctx = createMockEffectContext(); const routes = [createTestRoute({ effectSpy })]; const routing: Routing = routes.map(route => route.item); // when const { resolve, response$ } = resolveRouting({ routing, ctx }); const run: Task<any> = () => { resolve(routes[0].req); // first call resolve(routes[0].req); // second call return pipe(response$, take(2), toArray(), lastValueFrom); }; await run(); // then expect(effectSpy).toHaveBeenCalledTimes(1); }); test('resolves `HttpOutputEffect` only once', async () => { // given const effectSpy = jest.fn(); const ctx = createMockEffectContext(); const routes = [createTestRoute()]; const routing: Routing = routes.map(route => route.item); // given - output effect const output$: HttpOutputEffect = out$ => (effectSpy(), out$); // when const { resolve, response$ } = resolveRouting({ routing, ctx, output$ }); const run: Task<any> = () => { resolve(routes[0].req); // first call resolve(routes[0].req); // second call return pipe(response$, take(2), toArray(), lastValueFrom); }; await run(); // then expect(effectSpy).toHaveBeenCalledTimes(1); }); test('resolves `HttpErrorEffect` only once', async () => { // given const effectSpy = jest.fn(); const ctx = createMockEffectContext(); const routes = [createTestRoute({ throwError: true })]; const routing: Routing = routes.map(route => route.item); // given - error effect const error$: HttpErrorEffect = error$ => { effectSpy(); return error$.pipe(map(({ request }) => ({ request, body: 'ERROR' }))); }; // when const { resolve, response$ } = resolveRouting({ routing, ctx, error$ }); const run: Task<any> = () => { resolve(routes[0].req); // first call resolve(routes[0].req); // second call return pipe(response$, take(2), toArray(), lastValueFrom); }; await run(); // then expect(effectSpy).toHaveBeenCalledTimes(1); }); test(`returns ${HttpStatus.NOT_FOUND} (Not Found) response if route cannot be resolved`, async () => { // given const ctx = createMockEffectContext(); const response = createHttpResponse(); const request = createHttpRequest(({ url: '/unknown', method: 'GET', response })); const path = factorizeRegExpWithParams('/'); const effect$: HttpEffect = req$ => req$.pipe(mapTo({ body: 'test' })); const routing: Routing = [{ regExp: path.regExp, path: path.path, methods: { GET: { effect: effect$, middlewares: [] } }, }]; // when const { resolve, errorSubject } = resolveRouting({ routing, ctx }); const errorPromise = firstValueFrom(errorSubject); resolve(request); // then await expect(errorPromise).resolves.toEqual({ request, error: new HttpError('Route not found', HttpStatus.NOT_FOUND), }); }); test(`returns ${HttpStatus.BAD_REQUEST} (Bad Request) response in case of malformed URL`, async () => { // given const ctx = createMockEffectContext(); const response = createHttpResponse(); const request = createHttpRequest(({ url: '/group/%test', method: 'GET', response })); const path = factorizeRegExpWithParams('/group/:id'); const effect$: HttpEffect = req$ => req$.pipe(mapTo({ body: 'test' })); const routing: Routing = [{ regExp: path.regExp, path: path.path, methods: { GET: { effect: effect$, middlewares: [], parameters: path.parameters } }, }]; // when const { resolve, errorSubject } = resolveRouting({ routing, ctx }); const errorPromise = firstValueFrom(errorSubject); resolve(request); // then await expect(errorPromise).resolves.toEqual({ request, error: new HttpError('URI malformed', HttpStatus.BAD_REQUEST), }); }); test('handles concurrent requests for the same path', done => { // given const delays = [10, 20, 30, 40]; const ctx = createMockEffectContext(); const path = factorizeRegExpWithParams('/delay/:delay'); const testData = delays.map(delay => createHttpRequest(({ url: `/delay/${delay}`, method: 'GET' }))); const effect: HttpEffect = req$ => req$.pipe( map(req => req.params as { delay: number }), mergeMap(params => of({}).pipe( delay(params.delay), mapTo({ body: `delay_${params.delay}` }), )), ); const routing: Routing = [{ regExp: path.regExp, path: path.path, methods: { GET: { effect: effect, middlewares: [], parameters: ['delay'] } }, }]; // when const { resolve, outputSubject } = resolveRouting({ routing, ctx }); const run = () => { resolve(testData[0]); // 10 delay resolve(testData[3]); // 40 delay resolve(testData[2]); // 30 delay resolve(testData[1]); // 20 delay }; // then outputSubject.pipe(take(4), toArray()).subscribe( result => { expect(result[0]).toEqual({ body: 'delay_10', request: testData[0] }); expect(result[1]).toEqual({ body: 'delay_20', request: testData[1] }); expect(result[2]).toEqual({ body: 'delay_30', request: testData[2] }); expect(result[3]).toEqual({ body: 'delay_40', request: testData[3] }); done(); }, ); run(); }); test('handles concurrent requests for different paths', done => { // given const ctx = createMockEffectContext(); const testData = [ createTestRoute({ delay: 10 }), // [0] GET /delay_10 createTestRoute({ delay: 20 }), // [1] GET /delay_20 createTestRoute({ delay: 30 }), // [2] GET /delay_30 createTestRoute({ delay: 40 }), // [3] GET /delay_40 ]; const routing: Routing = testData.map(route => route.item); // when const { resolve, outputSubject } = resolveRouting({ routing, ctx }); const run = () => { resolve(testData[0].req); // 10 delay resolve(testData[3].req); // 40 delay resolve(testData[2].req); // 30 delay resolve(testData[1].req); // 20 delay }; // then outputSubject.pipe(take(4), toArray()).subscribe( result => { expect(result[0]).toEqual({ body: 'delay_10', request: testData[0].req }); expect(result[1]).toEqual({ body: 'delay_20', request: testData[1].req }); expect(result[2]).toEqual({ body: 'delay_30', request: testData[2].req }); expect(result[3]).toEqual({ body: 'delay_40', request: testData[3].req }); done(); }, ); run(); }); test('handles concurrent requests for different paths even if one request throws an error', done => { // given const ctx = createMockEffectContext(); const testData = [ createTestRoute({ delay: 10 }), // [0] GET /delay_10 createTestRoute({ delay: 20, throwError: true }), // [1] GET /delay_20 createTestRoute({ delay: 30 }), // [2] GET /delay_30 createTestRoute({ delay: 40 }), // [3] GET /delay_40 ]; const routing: Routing = testData.map(route => route.item); // when const { resolve, outputSubject, errorSubject } = resolveRouting({ routing, ctx }); const run = () => { resolve(testData[0].req); // 10 delay resolve(testData[1].req); // 20 delay resolve(testData[2].req); // 30 delay resolve(testData[3].req); // 40 delay }; // then merge( outputSubject.pipe(take(3)), errorSubject.pipe(take(1), map(res => res.error)), ).pipe( toArray(), ).subscribe( result => { expect(result[0]).toEqual({ body: 'delay_10', request: testData[0].req }); expect(result[1]).toEqual(new Error()); expect(result[2]).toEqual({ body: 'delay_30', request: testData[2].req }); expect(result[3]).toEqual({ body: 'delay_40', request: testData[3].req }); done(); }, ); run(); }); });
the_stack
import 'core-js/features/set-immediate'; import { attempt, isError, each, includes, compact, map, find, Dictionary, flatten, assign, filter, keys, reverse } from 'lodash'; import { DbIndexFTSFromRangeQueries, getFullTextIndexWordsForItem } from './FullTextSearchHelpers'; import { StoreSchema, DbProvider, DbSchema, DbTransaction, DbIndex, IndexSchema, DbStore, QuerySortOrder, ItemType, KeyPathType, KeyType } from './NoSqlProvider'; import { arrayify, serializeKeyToString, formListOfSerializedKeys, getSerializedKeyForKeypath, getValueForSingleKeypath } from './NoSqlProviderUtils'; import { TransactionLockHelper, TransactionToken } from './TransactionLockHelper'; export interface StoreData { data: Dictionary<ItemType>; schema: StoreSchema; } let asyncCallbacks: Set<() => void> = new Set(); /** * This function will defer callback of the specified callback lambda until the next JS tick, simulating standard A+ promise behavior */ function asyncCallback(callback: () => void): void { asyncCallbacks.add(callback); if (asyncCallbacks.size === 1) { setImmediate(resolveAsyncCallbacks); } } function abortAsyncCallback(callback: () => void): void { asyncCallbacks.delete(callback); } function resolveAsyncCallbacks(): void { const savedCallbacks = asyncCallbacks; asyncCallbacks = new Set(); savedCallbacks.forEach((item) => item()); } // Very simple in-memory dbprovider for handling IE inprivate windows (and unit tests, maybe?) export class InMemoryProvider extends DbProvider { private _stores: { [storeName: string]: StoreData } = {}; private _lockHelper: TransactionLockHelper | undefined; open(dbName: string, schema: DbSchema, wipeIfExists: boolean, verbose: boolean): Promise<void> { super.open(dbName, schema, wipeIfExists, verbose); each(this._schema!!!.stores, storeSchema => { this._stores[storeSchema.name] = { schema: storeSchema, data: {} }; }); this._lockHelper = new TransactionLockHelper(schema, true); return Promise.resolve<void>(undefined); } protected _deleteDatabaseInternal() { return Promise.resolve(); } openTransaction(storeNames: string[], writeNeeded: boolean): Promise<DbTransaction> { return this._lockHelper!!!.openTransaction(storeNames, writeNeeded).then(token => new InMemoryTransaction(this, this._lockHelper!!!, token)); } close(): Promise<void> { return this._lockHelper!!!.closeWhenPossible().then(() => { this._stores = {}; }); } internal_getStore(name: string): StoreData { return this._stores[name]; } } // Notes: Doesn't limit the stores it can fetch to those in the stores it was "created" with, nor does it handle read-only transactions class InMemoryTransaction implements DbTransaction { private _stores: Dictionary<InMemoryStore> = {}; private _transactionCallback?: () => void; constructor( private _prov: InMemoryProvider, private _lockHelper: TransactionLockHelper, private _transToken: TransactionToken) { this._transactionCallback = () => { this._commitTransaction(); this._lockHelper.transactionComplete(this._transToken); this._transactionCallback = undefined; }; // Close the transaction on the next tick. By definition, anything is completed synchronously here, so after an event tick // goes by, there can't have been anything pending. asyncCallback(this._transactionCallback); } private _commitTransaction(): void { each(this._stores, store => { store.internal_commitPendingData(); }); } getCompletionPromise(): Promise<void> { return this._transToken.completionPromise; } abort(): void { each(this._stores, store => { store.internal_rollbackPendingData(); }); this._stores = {}; if (this._transactionCallback) { abortAsyncCallback(this._transactionCallback); this._transactionCallback = undefined; } this._lockHelper.transactionFailed(this._transToken, 'InMemoryTransaction Aborted'); } markCompleted(): void { // noop } getStore(storeName: string): DbStore { if (!includes(arrayify(this._transToken.storeNames), storeName)) { throw new Error('Store not found in transaction-scoped store list: ' + storeName); } if (this._stores[storeName]) { return this._stores[storeName]; } const store = this._prov.internal_getStore(storeName); if (!store) { throw new Error('Store not found: ' + storeName); } const ims = new InMemoryStore(this, store); this._stores[storeName] = ims; return ims; } internal_isOpen() { return !!this._transactionCallback; } } class InMemoryStore implements DbStore { private _pendingCommitDataChanges: Dictionary<ItemType | undefined> | undefined; private _committedStoreData: Dictionary<ItemType>; private _mergedData: Dictionary<ItemType>; private _storeSchema: StoreSchema; constructor(private _trans: InMemoryTransaction, storeInfo: StoreData) { this._storeSchema = storeInfo.schema; this._committedStoreData = storeInfo.data; this._mergedData = this._committedStoreData; } private _checkDataClone(): void { if (!this._pendingCommitDataChanges) { this._pendingCommitDataChanges = {}; this._mergedData = assign({}, this._committedStoreData); } } internal_commitPendingData(): void { each(this._pendingCommitDataChanges, (val, key) => { if (val === undefined) { delete this._committedStoreData[key]; } else { this._committedStoreData[key] = val; } }); this._pendingCommitDataChanges = undefined; this._mergedData = this._committedStoreData; } internal_rollbackPendingData(): void { this._pendingCommitDataChanges = undefined; this._mergedData = this._committedStoreData; } get(key: KeyType): Promise<ItemType | undefined> { if (!this._trans.internal_isOpen()) { return Promise.reject('InMemoryTransaction already closed'); } const joinedKey = attempt(() => { return serializeKeyToString(key, this._storeSchema.primaryKeyPath); }); if (isError(joinedKey)) { return Promise.reject(joinedKey); } return Promise.resolve(this._mergedData[joinedKey]); } getMultiple(keyOrKeys: KeyType | KeyType[]): Promise<ItemType[]> { if (!this._trans.internal_isOpen()) { return Promise.reject('InMemoryTransaction already closed'); } const joinedKeys = attempt(() => { return formListOfSerializedKeys(keyOrKeys, this._storeSchema.primaryKeyPath); }); if (isError(joinedKeys)) { return Promise.reject(joinedKeys); } return Promise.resolve(compact(map(joinedKeys, key => this._mergedData[key]))); } put(itemOrItems: ItemType | ItemType[]): Promise<void> { if (!this._trans.internal_isOpen()) { return Promise.reject<void>('InMemoryTransaction already closed'); } this._checkDataClone(); const err = attempt(() => { for (const item of arrayify(itemOrItems)) { let pk = getSerializedKeyForKeypath(item, this._storeSchema.primaryKeyPath)!!!; this._pendingCommitDataChanges!!![pk] = item; this._mergedData[pk] = item; } }); if (err) { return Promise.reject<void>(err); } return Promise.resolve<void>(undefined); } remove(keyOrKeys: KeyType | KeyType[]): Promise<void> { if (!this._trans.internal_isOpen()) { return Promise.reject<void>('InMemoryTransaction already closed'); } this._checkDataClone(); const joinedKeys = attempt(() => { return formListOfSerializedKeys(keyOrKeys, this._storeSchema.primaryKeyPath); }); if (isError(joinedKeys)) { return Promise.reject(joinedKeys); } for (const key of joinedKeys) { this._pendingCommitDataChanges!!![key] = undefined; delete this._mergedData[key]; } return Promise.resolve<void>(undefined); } openPrimaryKey(): DbIndex { this._checkDataClone(); return new InMemoryIndex(this._trans, this._mergedData, undefined, this._storeSchema.primaryKeyPath); } openIndex(indexName: string): DbIndex { let indexSchema = find(this._storeSchema.indexes, idx => idx.name === indexName); if (!indexSchema) { throw new Error('Index not found: ' + indexName); } this._checkDataClone(); return new InMemoryIndex(this._trans, this._mergedData, indexSchema, this._storeSchema.primaryKeyPath); } clearAllData(): Promise<void> { if (!this._trans.internal_isOpen()) { return Promise.reject<void>('InMemoryTransaction already closed'); } this._checkDataClone(); each(this._mergedData, (val, key) => { this._pendingCommitDataChanges!!![key] = undefined; }); this._mergedData = {}; return Promise.resolve<void>(undefined); } } // Note: Currently maintains nothing interesting -- rebuilds the results every time from scratch. Scales like crap. class InMemoryIndex extends DbIndexFTSFromRangeQueries { constructor(private _trans: InMemoryTransaction, private _mergedData: Dictionary<ItemType>, indexSchema: IndexSchema | undefined, primaryKeyPath: KeyPathType) { super(indexSchema, primaryKeyPath); } // Warning: This function can throw, make sure to trap. private _calcChunkedData(): Dictionary<ItemType[]> | Dictionary<ItemType> { if (!this._indexSchema) { // Primary key -- use data intact return this._mergedData; } // If it's not the PK index, re-pivot the data to be keyed off the key value built from the keypath let data: Dictionary<ItemType[]> = {}; each(this._mergedData, item => { // Each item may be non-unique so store as an array of items for each key let keys: string[]; if (this._indexSchema!!!.fullText) { keys = map(getFullTextIndexWordsForItem(<string>this._keyPath, item), val => serializeKeyToString(val, <string>this._keyPath)); } else if (this._indexSchema!!!.multiEntry) { // Have to extract the multiple entries into this alternate table... const valsRaw = getValueForSingleKeypath(item, <string>this._keyPath); if (valsRaw) { keys = map(arrayify(valsRaw), val => serializeKeyToString(val, <string>this._keyPath)); } else { keys = []; } } else { keys = [getSerializedKeyForKeypath(item, this._keyPath)!!!]; } for (const key of keys) { if (!data[key]) { data[key] = [item]; } else { data[key].push(item); } } }); return data; } getAll(reverseOrSortOrder?: boolean | QuerySortOrder, limit?: number, offset?: number): Promise<ItemType[]> { if (!this._trans.internal_isOpen()) { return Promise.reject('InMemoryTransaction already closed'); } const data = attempt(() => { return this._calcChunkedData(); }); if (isError(data)) { return Promise.reject(data); } const sortedKeys = keys(data).sort(); return this._returnResultsFromKeys(data, sortedKeys, reverseOrSortOrder, limit, offset); } getOnly(key: KeyType, reverseOrSortOrder?: boolean | QuerySortOrder, limit?: number, offset?: number) : Promise<ItemType[]> { return this.getRange(key, key, false, false, reverseOrSortOrder, limit, offset); } getRange(keyLowRange: KeyType, keyHighRange: KeyType, lowRangeExclusive?: boolean, highRangeExclusive?: boolean, reverseOrSortOrder?: boolean | QuerySortOrder, limit?: number, offset?: number): Promise<ItemType[]> { if (!this._trans.internal_isOpen()) { return Promise.reject('InMemoryTransaction already closed'); } let data: Dictionary<ItemType[]> | Dictionary<ItemType>; let sortedKeys: string[]; const err = attempt(() => { data = this._calcChunkedData(); sortedKeys = this._getKeysForRange(data, keyLowRange, keyHighRange, lowRangeExclusive, highRangeExclusive).sort(); }); if (err) { return Promise.reject(err); } return this._returnResultsFromKeys(data!!!, sortedKeys!!!, reverseOrSortOrder, limit, offset); } // Warning: This function can throw, make sure to trap. private _getKeysForRange(data: Dictionary<ItemType[]> | Dictionary<ItemType>, keyLowRange: KeyType, keyHighRange: KeyType, lowRangeExclusive?: boolean, highRangeExclusive?: boolean): string[] { const keyLow = serializeKeyToString(keyLowRange, this._keyPath); const keyHigh = serializeKeyToString(keyHighRange, this._keyPath); return filter(keys(data), key => (key > keyLow || (key === keyLow && !lowRangeExclusive)) && (key < keyHigh || (key === keyHigh && !highRangeExclusive))); } private _returnResultsFromKeys(data: Dictionary<ItemType[]> | Dictionary<ItemType>, sortedKeys: string[], reverseOrSortOrder?: boolean | QuerySortOrder, limit?: number, offset?: number) { if (reverseOrSortOrder === true || reverseOrSortOrder === QuerySortOrder.Reverse) { sortedKeys = reverse(sortedKeys); } if (offset) { sortedKeys = sortedKeys.slice(offset); } if (limit) { sortedKeys = sortedKeys.slice(0, limit); } let results = map(sortedKeys, key => data[key]); return Promise.resolve(flatten(results)); } countAll(): Promise<number> { if (!this._trans.internal_isOpen()) { return Promise.reject('InMemoryTransaction already closed'); } const data = attempt(() => { return this._calcChunkedData(); }); if (isError(data)) { return Promise.reject(data); } return Promise.resolve(keys(data).length); } countOnly(key: KeyType): Promise<number> { return this.countRange(key, key, false, false); } countRange(keyLowRange: KeyType, keyHighRange: KeyType, lowRangeExclusive?: boolean, highRangeExclusive?: boolean) : Promise<number> { if (!this._trans.internal_isOpen()) { return Promise.reject('InMemoryTransaction already closed'); } const keys = attempt(() => { const data = this._calcChunkedData(); return this._getKeysForRange(data, keyLowRange, keyHighRange, lowRangeExclusive, highRangeExclusive); }); if (isError(keys)) { return Promise.reject(keys); } return Promise.resolve(keys.length); } }
the_stack
import 'react'; // tslint:disable-next-line strict-export-declare-modifiers type Booleanish = boolean | 'true' | 'false'; declare module 'react' { interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> { // Standard HTML Attributes accesskey?: string; class?: string; spellcheck?: Booleanish; tabindex?: number | string; // Unknown radiogroup?: string; // <command>, <menuitem> // Non-standard Attributes autocapitalize?: string; autocorrect?: string; autosave?: string; contenteditable?: Booleanish | 'inherit'; contextmenu?: string; itemid?: string; itemprop?: string; itemref?: string; itemscope?: boolean; itemtype?: string; // Living Standard /** * Hints at the type of data that might be entered by the user while editing the element or its contents * @see https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-inputmode-attribute */ inputmode?: 'none' | 'text' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search'; } interface AllHTMLAttributes<T> extends HTMLAttributes<T> { // Standard HTML Attributes 'accept-charset'?: string; allowfullscreen?: boolean; allowtransparency?: boolean; autocomplete?: string; autofocus?: boolean; autoplay?: boolean; cellpadding?: number | string; cellspacing?: number | string; charset?: string; class?: string; classid?: string; colspan?: number | string; crossorigin?: string; datetime?: string; enctype?: string; for?: string; formaction?: string; formenctype?: string; formmethod?: string; formnovalidate?: boolean; formtarget?: string; frameborder?: number | string; hreflang?: string; 'http-equiv'?: string; keyparams?: string; keytype?: string; marginheight?: number | string; marginwidth?: number | string; maxlength?: number | string; mediagroup?: string; minlength?: number | string; novalidate?: boolean; playsinline?: boolean; readonly?: boolean; rowspan?: number | string; srcdoc?: string; srclang?: string; srcset?: string; usemap?: string; } interface AnchorHTMLAttributes<T> extends HTMLAttributes<T> { hreflang?: string; referrerpolicy?: string; } interface ButtonHTMLAttributes<T> extends HTMLAttributes<T> { autofocus?: boolean; formaction?: string; formenctype?: string; formmethod?: string; formnovalidate?: boolean; formtarget?: string; } interface DelHTMLAttributes<T> extends HTMLAttributes<T> { datetime?: string; } interface FormHTMLAttributes<T> extends HTMLAttributes<T> { 'accept-charset'?: string; autocomplete?: string; enctype?: string; novalidate?: boolean; } interface IframeHTMLAttributes<T> extends HTMLAttributes<T> { allowfullscreen?: boolean; allowtransparency?: boolean; frameborder?: number | string; marginheight?: number | string; marginwidth?: number | string; referrerpolicy?: string; srcdoc?: string; } interface ImgHTMLAttributes<T> extends HTMLAttributes<T> { crossorigin?: 'anonymous' | 'use-credentials' | ''; referrerpolicy?: 'no-referrer' | 'origin' | 'unsafe-url'; srcset?: string; usemap?: string; } interface InputHTMLAttributes<T> extends HTMLAttributes<T> { autocomplete?: string; autofocus?: boolean; crossorigin?: string; formaction?: string; formenctype?: string; formmethod?: string; formnovalidate?: boolean; formtarget?: string; maxlength?: number | string; minlength?: number | string; readonly?: boolean; } interface InsHTMLAttributes<T> extends HTMLAttributes<T> { datetime?: string; } interface KeygenHTMLAttributes<T> extends HTMLAttributes<T> { autofocus?: boolean; keyparams?: string; keytype?: string; } interface LabelHTMLAttributes<T> extends HTMLAttributes<T> { for?: string; } interface LinkHTMLAttributes<T> extends HTMLAttributes<T> { crossorigin?: string; hreflang?: string; charset?: string; } interface MediaHTMLAttributes<T> extends HTMLAttributes<T> { autoplay?: boolean; controlslist?: string; crossorigin?: string; mediagroup?: string; playsinline?: boolean; } interface MetaHTMLAttributes<T> extends HTMLAttributes<T> { charset?: string; 'http-equiv'?: string; } interface ObjectHTMLAttributes<T> extends HTMLAttributes<T> { classid?: string; usemap?: string; } interface OutputHTMLAttributes<T> extends HTMLAttributes<T> { for?: string; } interface ScriptHTMLAttributes<T> extends HTMLAttributes<T> { charset?: string; crossorigin?: string; nomodule?: boolean; } interface SelectHTMLAttributes<T> extends HTMLAttributes<T> { autocomplete?: string; autofocus?: boolean; } interface SourceHTMLAttributes<T> extends HTMLAttributes<T> { srcset?: string; } interface TableHTMLAttributes<T> extends HTMLAttributes<T> { cellpadding?: number | string; cellspacing?: number | string; } interface TdHTMLAttributes<T> extends HTMLAttributes<T> { colspan?: number | string; rowspan?: number | string; } interface TextareaHTMLAttributes<T> extends HTMLAttributes<T> { autocomplete?: string; autofocus?: boolean; dirname?: string; maxlength?: number | string; minlength?: number | string; readonly?: boolean; } interface ThHTMLAttributes<T> extends HTMLAttributes<T> { colspan?: number | string; rowspan?: number | string; } interface TimeHTMLAttributes<T> extends HTMLAttributes<T> { datetime?: string; } interface TrackHTMLAttributes<T> extends HTMLAttributes<T> { srclang?: string; } interface VideoHTMLAttributes<T> extends MediaHTMLAttributes<T> { disablepictureinpicture?: boolean; playsinline?: boolean; } interface SVGAttributes<T> extends AriaAttributes, DOMAttributes<T> { // Attributes also defined in HTMLAttributes class?: string; // Other HTML properties supported by SVG elements in browsers tabindex?: number | string; crossorigin?: 'anonymous' | 'use-credentials' | ''; // SVG Specific attributes 'accent-height'?: number | string; 'alignment-baseline'?: | 'auto' | 'baseline' | 'before-edge' | 'text-before-edge' | 'middle' | 'central' | 'after-edge' | 'text-after-edge' | 'ideographic' | 'alphabetic' | 'hanging' | 'mathematical' | 'inherit'; 'arabic-form'?: 'initial' | 'medial' | 'terminal' | 'isolated'; 'baseline-shift'?: number | string; 'cap-height'?: number | string; 'clip-path'?: string; 'clip-rule'?: number | string; 'color-interpolation'?: number | string; 'color-interpolation-filters'?: 'auto' | 'sRGB' | 'linearRGB' | 'inherit'; 'color-profile'?: number | string; 'color-rendering'?: number | string; 'dominant-baseline'?: number | string; 'enable-background'?: number | string; 'fill-opacity'?: number | string; 'fill-rule'?: 'nonzero' | 'evenodd' | 'inherit'; 'flood-color'?: number | string; 'flood-opacity'?: number | string; 'font-family'?: string; 'font-size'?: number | string; 'font-size-adjust'?: number | string; 'font-stretch'?: number | string; 'font-style'?: number | string; 'font-variant'?: number | string; 'font-weight'?: number | string; 'glyph-name'?: number | string; 'glyph-orientation-horizontal'?: number | string; 'glyph-orientation-vertical'?: number | string; 'horiz-adv-x'?: number | string; 'horiz-origin-x'?: number | string; 'image-rendering'?: number | string; 'letter-spacing'?: number | string; 'lighting-color'?: number | string; 'marker-end'?: string; 'marker-mid'?: string; 'marker-start'?: string; 'overline-position'?: number | string; 'overline-thickness'?: number | string; 'paint-order'?: number | string; 'panose-1'?: number | string; 'pointer-events'?: number | string; 'rendering-intent'?: number | string; 'shape-rendering'?: number | string; 'stop-color'?: string; 'stop-opacity'?: number | string; 'strikethrough-position'?: number | string; 'strikethrough-thickness'?: number | string; 'stroke-dasharray'?: string | number; 'stroke-dashoffset'?: string | number; 'stroke-linecap'?: 'butt' | 'round' | 'square' | 'inherit'; 'stroke-linejoin'?: 'miter' | 'round' | 'bevel' | 'inherit'; 'stroke-miterlimit'?: number | string; 'stroke-opacity'?: number | string; 'stroke-width'?: number | string; 'text-anchor'?: string; 'text-decoration'?: number | string; 'text-rendering'?: number | string; 'underline-position'?: number | string; 'underline-thickness'?: number | string; 'unicode-bidi'?: number | string; 'unicode-range'?: number | string; 'units-per-em'?: number | string; 'v-alphabetic'?: number | string; 'v-hanging'?: number | string; 'v-ideographic'?: number | string; 'v-mathematical'?: number | string; 'vector-effect'?: number | string; 'vert-adv-y'?: number | string; 'vert-origin-x'?: number | string; 'vert-origin-y'?: number | string; 'word-spacing'?: number | string; 'writing-mode'?: number | string; 'x-height'?: number | string; 'xlink:actuate'?: string; 'xlink:arcrole'?: string; 'xlink:href'?: string; 'xlink:role'?: string; 'xlink:show'?: string; 'xlink:title'?: string; 'xlink:type'?: string; 'xml:base'?: string; 'xml:lang'?: string; 'xml:space'?: string; 'xmlns:xlink'?: string; } interface WebViewHTMLAttributes<T> extends HTMLAttributes<T> { allowfullscreen?: boolean; autofocus?: boolean; } }
the_stack
import { Injectable, OnDestroy } from '@angular/core'; const symbolObservable = (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; /** * A callback invoked when a store value changes. It is called with the latest value of a given store. */ export type SubscriberFunction<T> = (value: T) => void; /** * A partial [observer](https://github.com/tc39/proposal-observable#api) notified when a store value changes. A store will call the `next` method every time the store's state is changing. */ export interface SubscriberObject<T> { next: SubscriberFunction<T>; invalidate: () => void; } /** * Expresses interest in store value changes over time. It can be either: * - a callback function: {@link SubscriberFunction}; * - a partial observer: {@link SubscriberObject}. */ export type Subscriber<T> = SubscriberFunction<T> | Partial<SubscriberObject<T>> | null | undefined; /** * A function to unsubscribe from value change notifications. */ export type UnsubscribeFunction = () => void; /** * An object with the `unsubscribe` method. * Subscribable stores might choose to return such object instead of directly returning {@link UnsubscribeFunction} from a subscription call. */ export interface UnsubscribeObject { /** * A method that acts as the {@link UnsubscribeFunction}. */ unsubscribe: UnsubscribeFunction; } export type Unsubscriber = UnsubscribeObject | UnsubscribeFunction; /** * Represents a store accepting registrations (subscribers) and "pushing" notifications on each and every store value change. */ export interface SubscribableStore<T> { /** * A method that makes it possible to register "interest" in store value changes over time. * It is called each and every time the store's value changes. * A registered subscriber is notified synchronously with the latest store value. * * @param subscriber - a subscriber in a form of a {@link SubscriberFunction} or a {@link SubscriberObject}. Returns a {@link Unsubscriber} (function or object with the `unsubscribe` method) that can be used to unregister and stop receiving notifications of store value changes. * @returns The {@link UnsubscribeFunction} or {@link UnsubscribeObject} that can be used to unsubscribe (stop state change notifications). */ subscribe(subscriber: Subscriber<T>): Unsubscriber; } /** * This interface augments the base {@link SubscribableStore} interface with the Angular-specific `OnDestroy` callback. The {@link Readable} stores can be registered in the Angular DI container and will automatically discard all the subscription when a given store is destroyed. */ export interface Readable<T> extends SubscribableStore<T>, OnDestroy { subscribe(subscriber: Subscriber<T>): UnsubscribeFunction & UnsubscribeObject; } /** * A function that can be used to update store's value. This function is called with the current value and should return new store value. */ export type Updater<T> = (value: T) => T; /** * Builds on top of {@link Readable} and represents a store that can be manipulated from "outside": anyone with a reference to writable store can either update or completely replace state of a given store. * * ```typescript * // reset counter's store value to 0 by using the {@link Writable.set} method * counterStore.set(0); * * // increment counter's store value by using the {@link Writable.update} method * counterStore.update(currentValue => currentValue + 1); * ``` */ export interface Writable<T> extends Readable<T> { /** * Replaces store's state with the provided value. * @param value - value to be used as the new state of a store. */ set(value: T): void; /** * Updates store's state by using an {@link Updater} function. * @param updater - a function that takes the current state as an argument and returns the new state. */ update(updater: Updater<T>): void; } const noop = () => {}; const bind = <T>(object: T | null | undefined, fnName: keyof T) => { const fn = object ? object[fnName] : null; return typeof fn === 'function' ? fn.bind(object) : noop; }; const toSubscriberObject = <T>(subscriber: Subscriber<T>): SubscriberObject<T> => typeof subscriber === 'function' ? { next: subscriber.bind(null), invalidate: noop } : { next: bind(subscriber, 'next'), invalidate: bind(subscriber, 'invalidate') }; const returnThis = function <T>(this: T): T { return this; }; const asReadable = <T>(store: Store<T>): Readable<T> => ({ subscribe: store.subscribe.bind(store), ngOnDestroy: store.ngOnDestroy.bind(store), [symbolObservable]: returnThis, }); const queue: [SubscriberFunction<any>, any][] = []; function processQueue() { for (const [subscriberFn, value] of queue) { subscriberFn(value); } queue.length = 0; } const callUnsubscribe = (unsubscribe: Unsubscriber) => typeof unsubscribe === 'function' ? unsubscribe() : unsubscribe.unsubscribe(); function notEqual(a: any, b: any): boolean { const tOfA = typeof a; if (tOfA !== 'function' && tOfA !== 'object') { return !Object.is(a, b); } return true; } /** * A utility function to get the current value from a given store. * It works by subscribing to a store, capturing the value (synchronously) and unsubscribing just after. * * @param store - a store from which the current value is retrieved. * * @example * ```typescript * const myStore = writable(1); * console.log(get(myStore)); // logs 1 * ``` */ export function get<T>(store: SubscribableStore<T>): T { let value: T; callUnsubscribe(store.subscribe((v) => (value = v))); return value!; } /** * Base class that can be extended to easily create a custom {@link Readable} store. * * @example * ```typescript * class CounterStore extends Store { * constructor() { * super(1); // initial value * } * * reset() { * this.set(0); * } * * increment() { * this.update(value => value + 1); * } * } * * const store = new CounterStore(1); * * // logs 1 (initial value) upon subscription * const unsubscribe = store.subscribe((value) => { * console.log(value); * }); * store.increment(); // logs 2 * store.reset(); // logs 0 * * unsubscribe(); // stops notifications and corresponding logging * ``` */ @Injectable() export abstract class Store<T> implements Readable<T> { private _subscribers = new Set<SubscriberObject<T>>(); private _cleanupFn: null | Unsubscriber = null; /** * * @param _value - Initial value of the store */ constructor(private _value: T) {} private _start() { this._cleanupFn = this.onUse() || noop; } private _stop() { const cleanupFn = this._cleanupFn; if (cleanupFn) { this._cleanupFn = null; callUnsubscribe(cleanupFn); } } /** * Replaces store's state with the provided value. * Equivalent of {@link Writable.set}, but internal to the store. * * @param value - value to be used as the new state of a store. */ protected set(value: T): void { if (notEqual(this._value, value)) { this._value = value; if (!this._cleanupFn) { // subscriber not yet initialized return; } const needsProcessQueue = queue.length == 0; for (const subscriber of this._subscribers) { subscriber.invalidate(); queue.push([subscriber.next, value]); } if (needsProcessQueue) { processQueue(); } } } /** * Updates store's state by using an {@link Updater} function. * Equivalent of {@link Writable.update}, but internal to the store. * * @param updater - a function that takes the current state as an argument and returns the new state. */ protected update(updater: Updater<T>): void { this.set(updater(this._value)); } /** * Function called when the number of subscribers changes from 0 to 1 * (but not called when the number of subscribers changes from 1 to 2, ...). * If a function is returned, it will be called when the number of subscribers changes from 1 to 0. * * @example * * ```typescript * class CustomStore extends Store { * onUse() { * console.log('Got the fist subscriber!'); * return () => { * console.log('All subscribers are gone...'); * }; * } * } * * const store = new CustomStore(); * const unsubscribe1 = store.subscribe(() => {}); // logs 'Got the fist subscriber!' * const unsubscribe2 = store.subscribe(() => {}); // nothing is logged as we've got one subscriber already * unsubscribe1(); // nothing is logged as we still have one subscriber * unsubscribe2(); // logs 'All subscribers are gone...' * ``` */ protected onUse(): Unsubscriber | void {} /** * Default Implementation of the {@link SubscribableStore.subscribe}, not meant to be overridden. * @param subscriber - see {@link SubscribableStore.subscribe} */ subscribe(subscriber: Subscriber<T>): UnsubscribeFunction & UnsubscribeObject { const subscriberObject = toSubscriberObject(subscriber); this._subscribers.add(subscriberObject); if (this._subscribers.size == 1) { this._start(); } subscriberObject.next(this._value); const unsubscribe = () => { const removed = this._subscribers.delete(subscriberObject); if (removed && this._subscribers.size === 0) { this._stop(); } }; unsubscribe.unsubscribe = unsubscribe; return unsubscribe; } ngOnDestroy(): void { const hasSubscribers = this._subscribers.size > 0; this._subscribers.clear(); if (hasSubscribers) { this._stop(); } } [symbolObservable](): this { return this; } } export interface OnUseArgument<T> { (value: T): void; set: (value: T) => void; update: (updater: Updater<T>) => void; } /** * A convenience function to create {@link Readable} store instances. * @param value - Initial value of a readable store. * @param onUseFn - A function called when the number of subscribers changes from 0 to 1 * (but not called when the number of subscribers changes from 1 to 2, ...). * If a function is returned, it will be called when the number of subscribers changes from 1 to 0. * * @example * ```typescript * const clock = readable("00:00", setState => { * const intervalID = setInterval(() => { * const date = new Date(); * setState(`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`); * }, 1000); * * return () => clearInterval(intervalID); * }); * ``` */ export function readable<T>( value: T, onUseFn: (arg: OnUseArgument<T>) => void | Unsubscriber = noop ): Readable<T> { const ReadableStoreWithOnUse = class extends Store<T> { protected onUse() { const setFn = (v: T) => this.set(v); setFn.set = setFn; setFn.update = (updater: Updater<T>) => this.update(updater); return onUseFn(setFn); } }; return asReadable(new ReadableStoreWithOnUse(value)); } @Injectable() class WritableStore<T> extends Store<T> implements Writable<T> { constructor(value: T) { super(value); } set(value: T): void { super.set(value); } update(updater: Updater<T>) { super.update(updater); } } /** * A convenience function to create {@link Writable} store instances. * @param value - initial value of a new writable store. * @param onUseFn - A function called when the number of subscribers changes from 0 to 1 * (but not called when the number of subscribers changes from 1 to 2, ...). * If a function is returned, it will be called when the number of subscribers changes from 1 to 0. * * @example * ```typescript * const x = writable(0); * * x.update(v => v + 1); // increment * x.set(0); // reset back to the default value * ``` */ export function writable<T>( value: T, onUseFn: (arg: OnUseArgument<T>) => void | Unsubscriber = noop ): Writable<T> { const WritableStoreWithOnUse = class extends WritableStore<T> { protected onUse() { const setFn = (v: T) => this.set(v); setFn.set = setFn; setFn.update = (updater: Updater<T>) => this.update(updater); return onUseFn(setFn); } }; const store = new WritableStoreWithOnUse(value); return { ...asReadable(store), set: store.set.bind(store), update: store.update.bind(store), }; } type SubscribableStores = | SubscribableStore<any> | readonly [SubscribableStore<any>, ...SubscribableStore<any>[]]; type SubscribableStoresValues<S> = S extends SubscribableStore<infer T> ? T : { [K in keyof S]: S[K] extends SubscribableStore<infer T> ? T : never }; type SyncDeriveFn<T, S> = (values: SubscribableStoresValues<S>) => T; type AsyncDeriveFn<T, S> = ( values: SubscribableStoresValues<S>, set: OnUseArgument<T> ) => Unsubscriber | void; type DeriveFn<T, S> = SyncDeriveFn<T, S> | AsyncDeriveFn<T, S>; function isSyncDeriveFn<T, S>(fn: DeriveFn<T, S>): fn is SyncDeriveFn<T, S> { return fn.length <= 1; } @Injectable() export abstract class DerivedStore< T, S extends SubscribableStores = SubscribableStores > extends Store<T> { constructor(private _stores: S, initialValue: T) { super(initialValue); } protected onUse(): Unsubscriber | void { let initDone = false; let pending = 0; const stores = this._stores; const isArray = Array.isArray(stores); const storesArr = isArray ? (stores as readonly SubscribableStore<any>[]) : [stores as SubscribableStore<any>]; const dependantValues = new Array(storesArr.length); let cleanupFn: null | Unsubscriber = null; const callCleanup = () => { const fn = cleanupFn; if (fn) { cleanupFn = null; callUnsubscribe(fn); } }; const callDerive = () => { if (initDone && !pending) { callCleanup(); cleanupFn = this.derive(isArray ? dependantValues : dependantValues[0]) || noop; } }; const unsubscribers = storesArr.map((store, idx) => store.subscribe({ next: (v) => { dependantValues[idx] = v; pending &= ~(1 << idx); callDerive(); }, invalidate: () => { pending |= 1 << idx; }, }) ); initDone = true; callDerive(); return () => { callCleanup(); unsubscribers.forEach(callUnsubscribe); }; } protected abstract derive(values: SubscribableStoresValues<S>): Unsubscriber | void; } /** * A convenience function to create a new store with a state computed from the latest values of dependent stores. * Each time the state of one of the dependent stores changes, a provided derive function is called to compute a new, derived state. * * @param stores - a single store or an array of dependent stores * @param deriveFn - a function that is used to compute a new state based on the latest values of dependent stores * * @example * ```typescript * const x$ = writable(2); * const y$ = writable(3); * const sum$ = derived([x$, $y], ([x, y]) => x + y); * * // will log 5 upon subscription * sum$.subscribe((value) => { * console.log(value) * }); * * x$.set(3); // will re-evaluate the `([x, y]) => x + y` function and log 6 as this is the new state of the derived store * ``` */ export function derived<T, S extends SubscribableStores>( stores: S, deriveFn: SyncDeriveFn<T, S> ): Readable<T>; export function derived<T, S extends SubscribableStores>( stores: S, deriveFn: AsyncDeriveFn<T, S>, initialValue: T ): Readable<T>; export function derived<T, S extends SubscribableStores>( stores: S, deriveFn: DeriveFn<T, S>, initialValue?: T ): Readable<T> { const Derived = isSyncDeriveFn(deriveFn) ? class extends DerivedStore<T, S> { protected derive(values: SubscribableStoresValues<S>) { this.set(deriveFn(values)); } } : class extends DerivedStore<T, S> { protected derive(values: SubscribableStoresValues<S>) { const setFn = (v: T) => this.set(v); setFn.set = setFn; setFn.update = (updater: Updater<T>) => this.update(updater); return deriveFn(values, setFn); } }; return asReadable(new Derived(stores, initialValue as any)); }
the_stack
import { existsSync, readdirSync, readFileSync, statSync } from 'fs'; import { posix as path, resolve } from 'path'; import { Configuration, Linter } from 'tslint'; import * as ts from 'typescript'; import { JsonDocs } from '@kirbydesign/core/custom-elements'; const { readdir, readFile } = require('fs').promises; const newLine = '\r\n'; const autoGeneratedFileHeader = `// AUTO-GENERATED - PLEASE DON'T EDIT THIS FILE MANUALLY`; const customElements: JsonDocs = require('@kirbydesign/core/custom-elements.json'); type ComponentMetaData = { className: string; decorator: string; selector: string; properties: any[]; methods: any[]; }; type OutputPaths = { base: string; jasmine: string; jest: string; }; export class GenerateMocks { async renderMocks(rootPath: string, outputPaths: OutputPaths, subPath: string) { const inputPath = path.join(rootPath, subPath); const outputPathNormalized = path.normalize(outputPaths.base); const classMap = new Map<string, string[]>(); const exportedProviders: ComponentMetaData[] = []; const exportedTypesWithAliases = await this.getExportedTypesWithAliases(inputPath); const [exportedTypes, aliasesMap] = this.separateTypesFromAliases(exportedTypesWithAliases); await this.traverseFolder( inputPath, outputPathNormalized, classMap, exportedTypes, exportedProviders, aliasesMap ); this.renderMockComponentDeclaration(classMap, outputPathNormalized); this.renderMockProviders(exportedProviders, path.normalize(outputPaths.jasmine), 'jasmine'); this.renderMockProviders(exportedProviders, path.normalize(outputPaths.jest), 'jest'); } private renderMockComponentDeclaration(classMap: Map<string, string[]>, outputPath: string) { const imports = Array.from(classMap.entries()) .map((keyValue) => { const filepath = keyValue[0]; const classNames = keyValue[1]; const relativePath = filepath.replace(outputPath, './').replace('.ts', ''); return `import { ${classNames.join(', ')} } from '${relativePath}';`; }) .join(newLine); const components = Array.from(classMap.values()) .map((classNames) => classNames.join(`,${newLine} `)) .join(`,${newLine} `); const filename = path.join(outputPath, '/mock-components.ts'); const content = `${autoGeneratedFileHeader} ${imports} export const MOCK_COMPONENTS = [ ${components}, ]; `; this.saveFileLinted(filename, content); } private renderMockProviders( exportedProviders: ComponentMetaData[], outputPath: string, testFramework: 'jasmine' | 'jest' ) { const hasObservableProperties = exportedProviders.some((provider) => provider.properties.some((p) => p.type === 'Observable') ); const imports = this.getImports(exportedProviders); if (hasObservableProperties) { imports.push(`import { EMPTY } from 'rxjs';`); } const importStatements = imports.join(newLine); const mockProviderFactoryRenderer = testFramework === 'jasmine' ? this.renderJasmineMockProviderFactory.bind(this) : this.renderJestMockProviderFactory.bind(this); const factories = exportedProviders.map(mockProviderFactoryRenderer).join(newLine + newLine); const providers = exportedProviders .map( (provider) => `{ provide: ${provider.className}, useFactory: ${this.getMockProviderFactoryName(provider.className)} }` ) .join(`,${newLine} `); const filename = path.join(outputPath, '/mock-providers.ts'); const content = `${autoGeneratedFileHeader} ${importStatements} ${factories} export const MOCK_PROVIDERS = [ ${providers}, ]; `; this.saveFileLinted(filename, content); } private async getExportedTypesWithAliases(folderpath: string): Promise<string[]> { const files = await this.getBarrelFiles(folderpath); const exportedTypesAndAliases = await Promise.all( files.map(async (file) => { const fileContent = await readFile(file, 'utf8'); return this.getTypesInFile(fileContent); }) ); return Array.prototype.concat(...exportedTypesAndAliases); } private getTypesInFile(fileContent: any): any[] { const typesInFile = []; const exportRegEx = /^export \{ *(.*) *\} from '\.\//; const exportRegExGlobal = new RegExp(exportRegEx, 'gm'); // "|| []" prevents having to check for undefined: (fileContent.match(exportRegExGlobal) || []).forEach((matchedLine) => { // "slice(1)" skips the full match: (matchedLine.match(exportRegEx) || []).slice(1).forEach((exported) => { // Split multiple entries, trim away whitespace and add: typesInFile.push(...exported.split(',').map((entry) => entry.trim())); }); }); return typesInFile; } private separateTypesFromAliases( exportedTypesWithAliases: string[] ): [string[], Map<string, string>] { // capture group 1 is internal component name, group 2 is exported name const aliasRegex = /(\w+) as (\w+)/; const aliasesMap = new Map<string, string>(); const exportedTypes = exportedTypesWithAliases.map((type) => { const match = type.match(aliasRegex); if (match) { // add both matches to the map, but only return the exported type aliasesMap.set(match[1], match[2]); return match[2]; } return type; }); return [exportedTypes, aliasesMap]; } private async getBarrelFiles(folderpath: string) { const dirents = await readdir(folderpath, { withFileTypes: true }); const files = await Promise.all( dirents .filter((dirent) => { return dirent.isDirectory() || dirent.name.endsWith('index.ts'); }) .map((dirent) => { const res = resolve(folderpath, dirent.name); return dirent.isDirectory() ? this.getBarrelFiles(res) : res; }) ); return Array.prototype.concat(...files); } private async traverseFolder( folderpath: string, outputPath: string, classMap: Map<string, string[]>, exportedTypes: string[], exportedProviders: ComponentMetaData[], aliasesMap: Map<string, string> ) { const folderContent = readdirSync(folderpath); for (const fileOrFolder of folderContent) { const fullPath = path.join(folderpath, fileOrFolder); const ent = statSync(fullPath); if (ent.isDirectory()) { await this.traverseFolder( fullPath, outputPath, classMap, exportedTypes, exportedProviders, aliasesMap ); } else { if (fileOrFolder.endsWith('.component.ts')) { const newFilename = path.join(outputPath, 'components', 'mock.' + fileOrFolder); const classNames = this.renderMock(fullPath, newFilename, exportedTypes, aliasesMap); if (classNames) { classMap.set(newFilename, classNames); } } if (fileOrFolder.endsWith('.controller.ts') || fileOrFolder.endsWith('.service.ts')) { exportedProviders.push( ...this.getExportedProvidersMetadata(fullPath, exportedTypes, aliasesMap) ); } } } } private getExportedProvidersMetadata( fileName: string, exportedTypes: string[], aliasesMap: Map<string, string> ) { return this.generateMetaData(fileName, aliasesMap).filter( (metaData) => metaData.decorator === 'Injectable' && exportedTypes.includes(metaData.className) && metaData.methods.length ); } private renderJasmineMockProviderFactory(componentMetaData: ComponentMetaData) { const methodNames = componentMetaData.methods.map((m) => `'${m.name}'`).join(',' + newLine); const methodNamesArray = `[${methodNames}]`; const observableProperties = this.getObservableProperties(componentMetaData).join( ',' + newLine ); const propertyNamesObject = observableProperties.length ? `, { ${observableProperties} }` : ''; const funcName = this.getMockProviderFactoryName(componentMetaData.className); return `export function ${funcName}() { return jasmine.createSpyObj<${componentMetaData.className}>('${componentMetaData.className}', ${methodNamesArray}${propertyNamesObject} ); }`; } private renderJestMockProviderFactory(componentMetaData: ComponentMetaData) { const mockMethods = componentMetaData.methods.map((m) => `${m.name}: jest.fn()`); const observableProperties = this.getObservableProperties(componentMetaData); const members = mockMethods.concat(observableProperties).join(',' + newLine); const funcName = this.getMockProviderFactoryName(componentMetaData.className); return `export function ${funcName}() { return { ${members} }; }`; } private getObservableProperties(componentMetaData: ComponentMetaData) { return componentMetaData.properties .filter((p) => p.type === 'Observable') .map((p) => `${p.name}: EMPTY`); // Ensure observable properties can be subscribed, see: https://ng-mocks.sudo.eu/extra/mock-observables } private getMockProviderFactoryName(className: string) { return className[0].toLowerCase() + className.slice(1) + 'Factory'; } private renderMock( fileName: string, newFilename: string, exportedTypes: string[], aliasesMap: Map<string, string> ) { const components = this.generateMetaData(fileName, aliasesMap); const hasExportedComponents = components.some( (metaData) => !!metaData.decorator && exportedTypes.includes(metaData.className) ); if (!hasExportedComponents) { // Nothing to generate: return; } const rendered = []; const classNames = []; components.forEach((metaData) => { const mockClassName = 'Mock' + metaData.className; classNames.push(mockClassName); const classDeclaration = this.renderClass(metaData.className, mockClassName, metaData); rendered.push(classDeclaration); }); const startRegion = '// #region AUTO-GENERATED'; const endRegion = '// #endregion'; const autoGeneratedContent = `${startRegion} - PLEASE DON'T EDIT CONTENT WITHIN! ${rendered.join(newLine)} ${endRegion} `; const importStatements = this.getImports(components).join(newLine) + newLine + newLine; let content = importStatements + autoGeneratedContent; if (existsSync(newFilename)) { const existingContent = readFileSync(newFilename).toString(); const regionStartIndex = existingContent.indexOf(startRegion); const beforeRegion = existingContent.substring(0, regionStartIndex); content = beforeRegion + autoGeneratedContent; } this.saveFileLinted(newFilename, content); return classNames; } private renderClass( className: string, mockClassName: string, componentMetaData: ComponentMetaData ): string { const propertiesString = this.renderProperties(componentMetaData.properties); const methodsString = this.renderMethods(componentMetaData.methods); const validSelector = componentMetaData.selector && (componentMetaData.selector.startsWith(`'kirby`) || componentMetaData.selector.startsWith(`'[kirby`)); const tsLintDisableSelector = componentMetaData.selector && !validSelector ? `${newLine} // tslint:disable-next-line: component-selector` : ''; const selector = componentMetaData.selector ? `${tsLintDisableSelector}${newLine} selector: ${componentMetaData.selector},` : ''; const template = componentMetaData.decorator === 'Component' ? `${newLine} template: '<ng-content></ng-content>',` : ''; const providers = ` providers: [ { provide: ${className}, useExisting: forwardRef(() => ${mockClassName}), }, ], `; const config = `{${selector}${template}${providers}}`; const content = `@${componentMetaData.decorator}(${config}) export class ${mockClassName} {${propertiesString}${methodsString}} `; return content; } private getImports(components: ComponentMetaData[]): string[] { const importStatements = []; const angularCoreImports: string[] = []; const hasDecoratedType = (type: string) => components.some((metaData) => metaData.decorator === type); const hasComponent = hasDecoratedType('Component'); const hasDirective = hasDecoratedType('Directive'); if (hasComponent || hasDirective) { angularCoreImports.push('forwardRef'); } if (hasComponent) { angularCoreImports.push('Component'); } if (hasDirective) { angularCoreImports.push('Directive'); } const hasInputOutput = (metaData: ComponentMetaData, direction: string) => metaData.properties.some((prop) => prop.direction === direction); const hasInput = (metaData: ComponentMetaData) => hasInputOutput(metaData, 'Input'); const hasOutput = (metaData: ComponentMetaData) => hasInputOutput(metaData, 'Output'); if (components.some(hasInput)) { angularCoreImports.push('Input'); } if (components.some(hasOutput)) { angularCoreImports.push('Output', 'EventEmitter'); } if (angularCoreImports.length) { importStatements.push(`import { ${angularCoreImports.join(', ')} } from '@angular/core';`); } if ( components.some((metaData) => metaData.properties.some((prop) => prop.type && prop.type.indexOf('Observable<') > -1) ) ) { importStatements.push(`import { Observable } from 'rxjs';`); } const kirbyImports = components.map((metaData) => metaData.className); importStatements.push( `${newLine}import { ${kirbyImports.join(', ')} } from '@kirbydesign/designsystem';` ); return importStatements; } private renderProperties(properties: any[]) { let renderedProps = properties.map((prop) => { switch (prop.direction) { case 'Input': const typeDeclaration = prop.type ? `: ${prop.type}` : ''; const bindingProperty = prop.bindingProperty || ''; return `@Input(${bindingProperty}) ${prop.name}${typeDeclaration};`; case 'Output': return `@Output() ${prop.name} = ${prop.initializer};`; } }); const separator = `${newLine} `; return renderedProps.length ? separator + renderedProps.join(separator) + newLine : ''; } private renderMethods(methods: any[]) { let renderedMethods = methods.map((method) => { return `${method.name}() {};`; }); const separator = `${newLine} `; return renderedMethods.length ? separator + renderedMethods.join(separator) + newLine : ''; } private generateMetaData(fileName: string, aliasesMap: Map<string, string>) { const sourceFile = ts.createSourceFile( fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES2015, /*setParentNodes */ true ); const components: ComponentMetaData[] = []; sourceFile.forEachChild((node) => { if (ts.isClassDeclaration(node)) { const componentMetaData: ComponentMetaData = { className: '', decorator: '', selector: '', properties: [], methods: [], }; this.visitTree(node, componentMetaData, aliasesMap); if (componentMetaData.decorator) { components.push(componentMetaData); } } }); return components; } private visitTree( node: ts.Node, componentMetaData: ComponentMetaData, aliasesMap: Map<string, string> ) { if (ts.isClassDeclaration(node)) { this.visitClassDeclaration(node, componentMetaData); } if (ts.isPropertyDeclaration(node) || ts.isSetAccessorDeclaration(node)) { this.visitPropertyDeclaration(node, componentMetaData); } if (ts.isMethodDeclaration(node)) { this.visitMethodDeclaration(node, componentMetaData); } if (aliasesMap.get(componentMetaData.className)) { // overwrite classname with alias if the classname set by visitClassDecoration is in the map componentMetaData.className = aliasesMap.get(componentMetaData.className); this.visitCustomElementsJSON(componentMetaData); } ts.forEachChild(node, (node) => this.visitTree(node, componentMetaData, aliasesMap)); } private visitClassDeclaration( classDeclaration: ts.ClassDeclaration, componentMetaData: ComponentMetaData ) { const className = classDeclaration.name.getText(); componentMetaData.className = className; if (classDeclaration && classDeclaration.decorators) { classDeclaration.decorators.forEach((decorator) => { if (ts.isCallExpression(decorator.expression)) { if (ts.isIdentifier(decorator.expression.expression)) { const decoratorName = decorator.expression.expression.getText(); if ( decoratorName === 'Component' || decoratorName === 'Directive' || decoratorName === 'Injectable' ) { componentMetaData.decorator = decoratorName; const decoratorArg = decorator.expression.arguments[0]; if (decoratorArg && ts.isObjectLiteralExpression(decoratorArg)) { const selectorProp = decoratorArg.properties.find( (prop) => prop.name.getText() === 'selector' ); if (selectorProp && ts.isPropertyAssignment(selectorProp)) { const selector = selectorProp.initializer.getText(); componentMetaData.selector = selector; } } } } } }); } } private visitPropertyDeclaration( propertyDeclaration: ts.SetAccessorDeclaration | ts.PropertyDeclaration, componentMetaData: ComponentMetaData ) { const inputOutputDecorator = this.getInputOutputDecorator(propertyDeclaration); if (componentMetaData.decorator === 'Injectable') { // Only render provider properties explicitly marked as public : if ( !propertyDeclaration.modifiers || !propertyDeclaration.modifiers.some( (modifier) => modifier.kind === ts.SyntaxKind.PublicKeyword ) ) { return; } } else if (!inputOutputDecorator.type) { // Only render Input/Output properties for components and directives: return; } const name = propertyDeclaration.name.getText(); const type = this.getPropertyType(name, propertyDeclaration, componentMetaData); let initializer: string; if (ts.isPropertyDeclaration(propertyDeclaration)) { initializer = propertyDeclaration.initializer?.getText(); } const prop = { name, type, initializer, direction: inputOutputDecorator.type, bindingProperty: inputOutputDecorator.bindingProperty, }; componentMetaData.properties.push(prop); } private visitMethodDeclaration( methodDeclaration: ts.MethodDeclaration, componentMetaData: ComponentMetaData ) { // Only render methods explicitly marked as public : if ( !methodDeclaration.modifiers || !methodDeclaration.modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.PublicKeyword) ) { return; } const name = methodDeclaration.name.getText(); if (name.startsWith('ng') || name.startsWith('_')) return; const type = methodDeclaration.type; // this.getPropertyType(name, methodDeclaration, componentMetaData); const method = { name, type, }; componentMetaData.methods.push(method); } private visitCustomElementsJSON(componentMetaData: ComponentMetaData) { const currentComponentSelector = componentMetaData.selector.replace(/["']/g, ''); const component = customElements.components.find( (comp) => comp.tag === currentComponentSelector ); if (component) { component.props.forEach((prop) => { componentMetaData.properties.push({ name: prop.name, type: prop.type, initializer: prop.default?.replace(/["']/g, ''), direction: 'Input', }); }); component.events.forEach((event) => { componentMetaData.properties.push({ name: event.event, type: 'EventEmitter', initializer: 'new EventEmitter<' + event.detail + '>()', direction: 'Output', }); }); component.methods.forEach((method) => { componentMetaData.methods.push({ name: method.name, type: method.returns.type, }); }); } } private getInputOutputDecorator( propertyDeclaration: ts.SetAccessorDeclaration | ts.PropertyDeclaration ): { type: 'Input' | 'Output'; bindingProperty: string } { const inputOutputDecorator = { type: undefined, bindingProperty: undefined }; if (propertyDeclaration && propertyDeclaration.decorators) { propertyDeclaration.decorators.forEach((decorator) => { if (ts.isCallExpression(decorator.expression)) { if (ts.isIdentifier(decorator.expression.expression)) { const decoratorName = decorator.expression.expression.getText(); if (decoratorName === 'Input' || decoratorName === 'Output') { inputOutputDecorator.type = decoratorName; const bindingPropertyArg = decorator.expression.arguments[0]; if (bindingPropertyArg && ts.isStringLiteral(bindingPropertyArg)) { inputOutputDecorator.bindingProperty = bindingPropertyArg.getText(); } } } } }); } return inputOutputDecorator; } private getPropertyType( propertyName: string, propertyDeclaration: ts.PropertyDeclaration | ts.SetAccessorDeclaration, componentMetaData: ComponentMetaData ): string { if (ts.isPropertyDeclaration(propertyDeclaration)) { return this.getPropertyTypeFromPropertyDeclaration( propertyName, propertyDeclaration, componentMetaData ); } if (ts.isSetAccessorDeclaration(propertyDeclaration)) { return this.getPropertyTypeFromSetAccessor( propertyName, propertyDeclaration, componentMetaData ); } } private getPropertyTypeFromPropertyDeclaration( propertyName: string, propertyDeclaration: ts.PropertyDeclaration, componentMetaData: ComponentMetaData ): string { let inferredType; if (!propertyDeclaration.type && propertyDeclaration.initializer) { switch (propertyDeclaration.initializer.kind) { case ts.SyntaxKind.FalseKeyword: case ts.SyntaxKind.TrueKeyword: inferredType = 'boolean'; break; case ts.SyntaxKind.NumericLiteral: inferredType = 'number'; break; case ts.SyntaxKind.StringLiteral: inferredType = 'string'; break; case ts.SyntaxKind.ArrayLiteralExpression: inferredType = '[]'; break; default: const propInitializer = propertyDeclaration.initializer.getText(); if (propInitializer.startsWith('new EventEmitter')) { inferredType = 'EventEmitter'; break; } if ( propInitializer.match( /\.asObservable\(\)|^of\(|new (?:Observable|Subject|ReplaySubject)\(/ ) ) { inferredType = 'Observable'; break; } console.warn( `Can't infer type for property '${componentMetaData.className}.${propertyName}':`, ts.SyntaxKind[propertyDeclaration.initializer.kind], `(${propertyDeclaration.initializer.kind})` ); } } return propertyDeclaration.type ? propertyDeclaration.type.getText() : inferredType; } private getPropertyTypeFromSetAccessor( propertyName: string, propertyDeclaration: ts.SetAccessorDeclaration, componentMetaData: ComponentMetaData ): string { let type: string; if (propertyDeclaration.parameters) { const param = propertyDeclaration.parameters[0]; if (param && param.type) { type = param.type.getText(); } } if (!type) { console.warn( `Can't infer type for property '${componentMetaData.className}.${propertyName}' from:`, propertyDeclaration.getText() ); } return type; } private saveFileLinted(filename: string, content: string) { const configuration = Configuration.findConfiguration('tslint.json', filename).results; const linter = new Linter({ fix: true }); linter.lint(filename, content, configuration); } }
the_stack
import * as fhirTypes from '../utils/fhirTypes'; import * as yup from 'yup'; import { ConvectorModel, FlatConvectorModel, ReadOnly, Required, Validate, Default } from '@worldsibu/convector-core'; import { x509Identities } from '../utils/identities.model'; export type date = string; export type instant = string; export type time = string; export type dateTime = string; export type base64Binary = string; export type decimal = number; export type url = string; export type code = string; export type integer = number; export type uri = string; export type canonical = string; export type markdown = string; export type id = string; export type oid = string; export type uuid = string; export type unsignedInt = number; export type positiveInt = number; export type xhtml = string; //export type timestamp = string; export class Financial extends ConvectorModel<Financial>{ // TODO: fix this @Default('fhir.datatypes.Financial') @ReadOnly() public readonly type: string; } export abstract class Element<T extends Element<any>> extends ConvectorModel<T> { @Validate(yup.string()) public id: string; @Validate(yup.lazy(()=> yup.array(Extension.schema()))) public extension?: Array<FlatConvectorModel<Extension>>; } export class Quantity extends Element<Quantity> { @Default('fhir.datatypes.Quantity') @ReadOnly() public readonly type: string; @Validate(yup.number()) public value?: number; @Validate(yup.string()) public comparator?: string; @Validate(yup.string()) public unit?: string; @Validate(yup.string()) public system?: string; @Validate(yup.string()) public code?: string; } export class Extension extends Element<Extension> { @Validate(yup.string()) public id: string; @Validate(yup.lazy(() => yup.array(Extension.schema()))) public extension?: Array<FlatConvectorModel<Extension>>; @Default('fhir.datatypes.Extension') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.number()) public valueInteger?: number; @Validate(yup.number()) public valueDecimal?: number; // Primitives // @Validate(yup.string()) // TODO @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDateTime?: date; @Validate(yup.string()) public valueString?: string; @Validate(yup.string()) public valueUri?: string; @Validate(yup.bool()) public valueBoolean?: string; //o xx valueInstant optional @Validate(yup.string()) public valueCode?: string; @Validate(yup.string()) public valueBase64Binary?: string; // Complex @Validate(yup.lazy(() => Coding.schema())) public valueCoding?: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => CodeableConcept.schema())) public valueCodeableConcept?: FlatConvectorModel<CodeableConcept>; //o Attachment valueAttachment optional @Validate(yup.lazy(() => Identifier.schema())) public valueIdentifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => Quantity.schema())) public valueQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Range.schema())) public valueRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => Period.schema())) public valuePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Ratio.schema())) public valueRatio?: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => HumanName.schema())) public valueHumanName?: FlatConvectorModel<HumanName>; @Validate(yup.lazy(() => Address.schema())) public valueAddress?: FlatConvectorModel<Address>; @Validate(yup.lazy(() => Money.schema())) public valueMoney?: FlatConvectorModel<Money>; //o ContactPoint valueContactPoint optional //o Schedule valueSchedule optional //o Reference valueReference optional } export abstract class BackboneElement extends Element<BackboneElement> { @Validate(yup.lazy(() => Extension.schema())) public modifierExtension?: Extension; } //SimpleQuantity is a restriction of Quantity without comparator export class SimpleQuantity extends Quantity { @Default('fhir.datatypes.SimpleQuantity') @ReadOnly() public readonly type: string; } // Asset inhertitance datatypes export abstract class Resource<T extends Resource<any>> extends ConvectorModel<T> { // identified by id @Required() @Validate(yup.string()) public id: string; @Validate(yup.string()) public implicitRules?: uri; @Validate(yup.string()) public language?: code; @Validate(yup.lazy(() => Meta.schema())) public meta?: FlatConvectorModel<Meta>; } export abstract class DomainResource<T extends DomainResource<any>> extends Resource<T> { @Required() @Validate(yup.string()) public resourceType: string; @Validate(yup.lazy(() => Narrative.schema())) public text?: FlatConvectorModel<Narrative>; @Validate(yup.lazy(() => Resource.schema())) public contained?: FlatConvectorModel<Resource<any>>; @Validate(yup.lazy(() => yup.array(Extension.schema()))) public extension?: Array<FlatConvectorModel<Extension>>; @Validate(yup.lazy(() => Extension.schema())) public modifierExtension?: Extension; } export class BundleEntry extends BackboneElement { @Default('fhir.datatypes.Bundle.BundleEntry') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(BundleLink.schema()))) public link?: Array<FlatConvectorModel<BundleLink>>; @Validate(yup.string()) public fullUrl?: string; @Validate(yup.lazy(() => Resource.schema())) public resource?: FlatConvectorModel<Resource<any>>; @Validate(yup.lazy(() => BundleEntrySearch.schema())) public search?: FlatConvectorModel<BundleEntrySearch>; @Validate(yup.lazy(() => BundleEntryRequest.schema())) public request?: FlatConvectorModel<BundleEntryRequest>; @Validate(yup.lazy(() => BundleEntryResponse.schema())) public response?: FlatConvectorModel<BundleEntryResponse>; } export class BundleEntryResponse extends BackboneElement { @Default('fhir.datatypes.Bundle.BundleEntryResponse') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.string()) public location?: string; @Validate(yup.string()) public etag?: string; @Validate(yup.string()) public lastModified?: string; @Validate(yup.lazy(() => Resource.schema())) public outcome?: FlatConvectorModel<Resource<any>>; } export class ParametersParameter extends BackboneElement { @Default('fhir.datatypes.Parameters.ParametersParameter') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.lazy(() => Resource.schema())) public resource?: FlatConvectorModel<Resource<any>>; @Validate(yup.lazy(() => yup.array(ParametersParameter.schema()))) public part?: Array<FlatConvectorModel<ParametersParameter>>; } export class Organization extends DomainResource<Organization> { @Default('fhir.datatypes.Organization') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.boolean()) public active?: boolean; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public name?: string; @Validate(yup.array(yup.string())) public alias?: Array<string>; @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.lazy(() => yup.array(Address.schema()))) public address?: Array<FlatConvectorModel<Address>>; @Validate(yup.lazy(() => Reference.schema())) public partOf?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(OrganizationContact.schema()))) public contact?: Array<FlatConvectorModel<OrganizationContact>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public endpoint?: Array<FlatConvectorModel<Reference>>; //Endpoint @Validate(yup.array(x509Identities)) public identities: x509Identities[]; } export class Dosage extends DomainResource<Dosage> { @Default('fhir.datatypes.Dosage') @ReadOnly() public readonly type: string; @Validate(yup.number()) public sequence?: number; @Validate(yup.string()) public text_?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public additionalInstruction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public patientInstruction?: string; @Validate(yup.lazy(() => Timing.schema())) public timing?: FlatConvectorModel<Timing>; @Validate(yup.boolean()) public asNeededBoolean?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public asNeededCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public site?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public route?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public method?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(DosageDoseAndRate.schema()))) public doseAndRate?: Array<FlatConvectorModel<DosageDoseAndRate>>; @Validate(yup.lazy(() => Ratio.schema())) public maxDosePerPeriod?: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public maxDosePerAdministration?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public maxDosePerLifetime?: FlatConvectorModel<SimpleQuantity>; } export class Period extends Element<Period> { @Default('fhir.datatypes.Period') @ReadOnly() public readonly type: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public start?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public end?: date; } export class Identifier extends Element<Identifier> { @Default('fhir.datatypes.Identifier') @ReadOnly() public readonly type: string; @Validate(yup.string()) public use?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public system?: string; @Validate(yup.string()) public value?: string; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Reference.schema())) public assigner?: FlatConvectorModel<Reference>; //Organization } export class Timing extends Element<Timing> { @Default('fhir.datatypes.Timing') @ReadOnly() public readonly type: string; @Validate(yup.array(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date'))) public event? : Array<date>; @Validate(yup.lazy(() => TimingRepeat.schema())) public repeat?: FlatConvectorModel<TimingRepeat>; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; } export class CodeableConcept extends Element<CodeableConcept> { @Default('fhir.datatypes.CodeableConcept') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public coding?: Array<FlatConvectorModel<Coding>>; @Validate(yup.string()) public text?: string; } export class Money extends Element<Money> { @Default('fhir.datatypes.Money') @ReadOnly() public readonly type: string; @Validate(yup.number()) public value?: number; @Validate(yup.string()) public currency?: string; } export class Annotation extends Element<Annotation> { @Default('fhir.datatypes.Annotation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Reference.schema())) public authorReference?: FlatConvectorModel<Reference>; //Practitioner|Patient|RelatedPerson|Organization @Validate(yup.string()) public authorString?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public time?: date; @Required() @Validate(yup.string()) public text: string; } export class SampledData extends Element<SampledData> { @Default('fhir.datatypes.SampledData') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => SimpleQuantity.schema())) public origin: FlatConvectorModel<SimpleQuantity>; @Required() @Validate(yup.number()) public period: number; @Validate(yup.number()) public factor?: number; @Validate(yup.number()) public lowerLimit?: number; @Validate(yup.number()) public upperLimit?: number; @Required() @Validate(yup.number()) public dimensions: number; @Validate(yup.string()) public data?: string; } export class Reference extends Element<Reference> { @Default('fhir.datatypes.Reference') @ReadOnly() public readonly type: string; @Validate(yup.string()) public reference?: string; @Validate(yup.string()) public type_?: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.string()) public display?: string; } export class Meta extends Element<Meta> { @Default('fhir.datatypes.Meta') @ReadOnly() public readonly type: string; @Validate(yup.string()) public versionId?: string; @Validate(yup.string()) public lastUpdated?: string; @Validate(yup.string()) public source?: string; @Validate(yup.array(yup.string())) public profile? : Array<string>; //StructureDefinition @Validate(yup.lazy(() => yup.array(Coding.schema()))) public security?: Array<FlatConvectorModel<Coding>>; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public tag?: Array<FlatConvectorModel<Coding>>; } export class Narrative extends Element<Narrative> { @Default('fhir.datatypes.Narrative') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.string()) public div: xhtml; } export class ContactPoint extends Element<ContactPoint> { @Default('fhir.datatypes.ContactPoint') @ReadOnly() public readonly type: string; @Validate(yup.string()) public system?: string; @Validate(yup.string()) public value?: string; @Validate(yup.string()) public use?: string; @Validate(yup.number()) public rank?: number; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; } export class TimingRepeat extends BackboneElement { @Default('fhir.datatypes.Timing.TimingRepeat') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Duration.schema())) public boundsDuration?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => Range.schema())) public boundsRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => Period.schema())) public boundsPeriod?: FlatConvectorModel<Period>; @Validate(yup.number()) public count?: number; @Validate(yup.number()) public countMax?: number; @Validate(yup.number()) public duration?: number; @Validate(yup.number()) public durationMax?: number; @Validate(yup.string()) public durationUnit?: string; @Validate(yup.number()) public frequency?: number; @Validate(yup.number()) public frequencyMax?: number; @Validate(yup.number()) public period?: number; @Validate(yup.number()) public periodMax?: number; @Validate(yup.string()) public periodUnit?: string; @Validate(yup.array(yup.string())) public dayOfWeek? : Array<string>; @Validate(yup.array(yup.string())) public timeOfDay? : Array<string>; @Validate(yup.array(yup.string())) public when? : Array<string>; @Validate(yup.number()) public offset?: number; } export class Attachment extends Element<Attachment> { @Default('fhir.datatypes.Attachment') @ReadOnly() public readonly type: string; @Validate(yup.string()) public contentType?: string; @Validate(yup.string()) public language?: string; @Validate(yup.string()) public data?: string; @Validate(yup.string()) public url?: string; @Validate(yup.number()) public size?: number; @Validate(yup.string()) public hash?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public creation?: date; } export class Address extends Element<Address> { @Default('fhir.datatypes.Address') @ReadOnly() public readonly type: string; @Validate(yup.string()) public use?: string; @Validate(yup.string()) public type_?: string; @Validate(yup.string()) public text?: string; @Validate(yup.array(yup.string())) public line? : Array<string>; @Validate(yup.string()) public city?: string; @Validate(yup.string()) public district?: string; @Validate(yup.string()) public state?: string; @Validate(yup.string()) public postalCode?: string; @Validate(yup.string()) public country?: string; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; } export class Coding extends Element<Coding> { @Default('fhir.datatypes.Coding') @ReadOnly() public readonly type: string; @Validate(yup.string()) public system?: string; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public code?: string; @Validate(yup.string()) public display?: string; @Validate(yup.boolean()) public userSelected?: boolean; } export class Range extends Element<Range> { @Default('fhir.datatypes.Range') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => SimpleQuantity.schema())) public low?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public high?: FlatConvectorModel<SimpleQuantity>; } export class Ratio extends Element<Ratio> { @Default('fhir.datatypes.Ratio') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Quantity.schema())) public numerator?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Quantity.schema())) public denominator?: FlatConvectorModel<Quantity>; } export class HumanName extends Element<HumanName> { @Default('fhir.datatypes.HumanName') @ReadOnly() public readonly type: string; @Validate(yup.string()) public use?: string; @Validate(yup.string()) public text?: string; @Validate(yup.string()) public family?: string; @Validate(yup.array(yup.string())) public given? : Array<string>; @Validate(yup.array(yup.string())) public prefix? : Array<string>; @Validate(yup.array(yup.string())) public suffix? : Array<string>; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; } export class Duration extends Element<Duration> { @Default('fhir.datatypes.Duration') @ReadOnly() public readonly type: string; } export class Age extends Element<Age> { @Default('fhir.datatypes.Age') @ReadOnly() public readonly type: string; } export class AccountCoverage extends BackboneElement { @Default('fhir.datatypes.Account.AccountCoverage') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public coverage: FlatConvectorModel<Reference>; //Coverage @Validate(yup.number()) public priority?: number; } export class AccountGuarantor extends BackboneElement { @Default('fhir.datatypes.Account.AccountGuarantor') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public party: FlatConvectorModel<Reference>; //Patient|RelatedPerson|Organization @Validate(yup.boolean()) public onHold?: boolean; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; } export class Account extends DomainResource<Account> { @Default('fhir.datatypes.Account') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public name?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public subject?: Array<FlatConvectorModel<Reference>>; //Patient|Device|Practitioner|PractitionerRole|Location|HealthcareService|Organization @Validate(yup.lazy(() => Period.schema())) public servicePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(AccountCoverage.schema()))) public coverage?: Array<FlatConvectorModel<AccountCoverage>>; @Validate(yup.lazy(() => Reference.schema())) public owner?: FlatConvectorModel<Reference>; //Organization @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(AccountGuarantor.schema()))) public guarantor?: Array<FlatConvectorModel<AccountGuarantor>>; @Validate(yup.lazy(() => Reference.schema())) public partOf?: FlatConvectorModel<Reference>; //Account } export class ActivityDefinitionParticipant extends BackboneElement { @Default('fhir.datatypes.ActivityDefinition.ActivityDefinitionParticipant') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public role?: FlatConvectorModel<CodeableConcept>; } export class ActivityDefinitionDynamicValue extends BackboneElement { @Default('fhir.datatypes.ActivityDefinition.ActivityDefinitionDynamicValue') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public path: string; @Required() @Validate(yup.lazy(() => Expression.schema())) public expression: FlatConvectorModel<Expression>; } export class ActivityDefinition extends DomainResource<ActivityDefinition> { @Default('fhir.datatypes.ActivityDefinition') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public subtitle?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public subjectCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subjectReference?: FlatConvectorModel<Reference>; //Group @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public usage?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public topic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public author?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public editor?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public reviewer?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public endorser?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public relatedArtifact?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.array(yup.string())) public library? : Array<string>; //Library @Validate(yup.string()) public kind?: string; @Validate(yup.string()) public profile?: string; //StructureDefinition @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public intent?: string; @Validate(yup.string()) public priority?: string; @Validate(yup.boolean()) public doNotPerform?: boolean; @Validate(yup.lazy(() => Timing.schema())) public timingTiming?: FlatConvectorModel<Timing>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public timingDateTime?: date; @Validate(yup.lazy(() => Age.schema())) public timingAge?: FlatConvectorModel<Age>; @Validate(yup.lazy(() => Period.schema())) public timingPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Range.schema())) public timingRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => Duration.schema())) public timingDuration?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => Reference.schema())) public location?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => yup.array(ActivityDefinitionParticipant.schema()))) public participant?: Array<FlatConvectorModel<ActivityDefinitionParticipant>>; @Validate(yup.lazy(() => Reference.schema())) public productReference?: FlatConvectorModel<Reference>; //Medication|Substance @Validate(yup.lazy(() => CodeableConcept.schema())) public productCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => yup.array(Dosage.schema()))) public dosage?: Array<FlatConvectorModel<Dosage>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public bodySite?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public specimenRequirement?: Array<FlatConvectorModel<Reference>>; //SpecimenDefinition @Validate(yup.lazy(() => yup.array(Reference.schema()))) public observationRequirement?: Array<FlatConvectorModel<Reference>>; //ObservationDefinition @Validate(yup.lazy(() => yup.array(Reference.schema()))) public observationResultRequirement?: Array<FlatConvectorModel<Reference>>; //ObservationDefinition @Validate(yup.string()) public transform?: string; //StructureMap @Validate(yup.lazy(() => yup.array(ActivityDefinitionDynamicValue.schema()))) public dynamicValue?: Array<FlatConvectorModel<ActivityDefinitionDynamicValue>>; } export class AdverseEventSuspectEntity extends BackboneElement { @Default('fhir.datatypes.AdverseEvent.AdverseEventSuspectEntity') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public instance: FlatConvectorModel<Reference>; //Immunization|Procedure|Substance|Medication|MedicationAdministration|MedicationStatement|Device @Validate(yup.lazy(() => yup.array(AdverseEventSuspectEntityCausality.schema()))) public causality?: Array<FlatConvectorModel<AdverseEventSuspectEntityCausality>>; } export class AdverseEventSuspectEntityCausality extends BackboneElement { @Default('fhir.datatypes.AdverseEvent.AdverseEventSuspectEntityCausality') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public assessment?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public productRelatedness?: string; @Validate(yup.lazy(() => Reference.schema())) public author?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => CodeableConcept.schema())) public method?: FlatConvectorModel<CodeableConcept>; } export class AdverseEvent extends DomainResource<AdverseEvent> { @Default('fhir.datatypes.AdverseEvent') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Required() @Validate(yup.string()) public actuality: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public event?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group|Practitioner|RelatedPerson @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public detected?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public recordedDate?: date; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public resultingCondition?: Array<FlatConvectorModel<Reference>>; //Condition @Validate(yup.lazy(() => Reference.schema())) public location?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => CodeableConcept.schema())) public seriousness?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public severity?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public outcome?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public recorder?: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|RelatedPerson @Validate(yup.lazy(() => yup.array(Reference.schema()))) public contributor?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole|Device @Validate(yup.lazy(() => yup.array(AdverseEventSuspectEntity.schema()))) public suspectEntity?: Array<FlatConvectorModel<AdverseEventSuspectEntity>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public subjectMedicalHistory?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|AllergyIntolerance|FamilyMemberHistory|Immunization|Procedure|Media|DocumentReference @Validate(yup.lazy(() => yup.array(Reference.schema()))) public referenceDocument?: Array<FlatConvectorModel<Reference>>; //DocumentReference @Validate(yup.lazy(() => yup.array(Reference.schema()))) public study?: Array<FlatConvectorModel<Reference>>; //ResearchStudy } export class AllergyIntoleranceReaction extends BackboneElement { @Default('fhir.datatypes.AllergyIntolerance.AllergyIntoleranceReaction') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public substance?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public manifestation?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public description?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public onset?: date; @Validate(yup.string()) public severity?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public exposureRoute?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class AllergyIntolerance extends DomainResource<AllergyIntolerance> { @Default('fhir.datatypes.AllergyIntolerance') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public clinicalStatus?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public verificationStatus?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public type_?: string; @Validate(yup.array(yup.string())) public category? : Array<string>; @Validate(yup.string()) public criticality?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public onsetDateTime?: date; @Validate(yup.lazy(() => Age.schema())) public onsetAge?: FlatConvectorModel<Age>; @Validate(yup.lazy(() => Period.schema())) public onsetPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Range.schema())) public onsetRange?: FlatConvectorModel<Range>; @Validate(yup.string()) public onsetString?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public recordedDate?: date; @Validate(yup.lazy(() => Reference.schema())) public recorder?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Patient|RelatedPerson @Validate(yup.lazy(() => Reference.schema())) public asserter?: FlatConvectorModel<Reference>; //Patient|RelatedPerson|Practitioner|PractitionerRole @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastOccurrence?: date; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(AllergyIntoleranceReaction.schema()))) public reaction?: Array<FlatConvectorModel<AllergyIntoleranceReaction>>; } export class AppointmentParticipant extends BackboneElement { @Default('fhir.datatypes.Appointment.AppointmentParticipant') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public actor?: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|RelatedPerson|Device|HealthcareService|Location @Validate(yup.string()) public required?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; } export class Appointment extends DomainResource<Appointment> { @Default('fhir.datatypes.Appointment') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public cancelationReason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public serviceCategory?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public serviceType?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public specialty?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public appointmentType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Procedure|Observation|ImmunizationRecommendation @Validate(yup.number()) public priority?: number; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supportingInformation?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.string()) public start?: string; @Validate(yup.string()) public end?: string; @Validate(yup.number()) public minutesDuration?: number; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public slot?: Array<FlatConvectorModel<Reference>>; //Slot @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created?: date; @Validate(yup.string()) public comment?: string; @Validate(yup.string()) public patientInstruction?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //ServiceRequest @Validate(yup.lazy(() => yup.array(AppointmentParticipant.schema()))) public participant?: Array<FlatConvectorModel<AppointmentParticipant>>; @Validate(yup.lazy(() => yup.array(Period.schema()))) public requestedPeriod?: Array<FlatConvectorModel<Period>>; } export class AppointmentResponse extends DomainResource<AppointmentResponse> { @Default('fhir.datatypes.AppointmentResponse') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.lazy(() => Reference.schema())) public appointment: FlatConvectorModel<Reference>; //Appointment @Validate(yup.string()) public start?: string; @Validate(yup.string()) public end?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public participantType?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public actor?: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|RelatedPerson|Device|HealthcareService|Location @Required() @Validate(yup.string()) public participantStatus: string; @Validate(yup.string()) public comment?: string; } export class AuditEventAgent extends BackboneElement { @Default('fhir.datatypes.AuditEvent.AuditEventAgent') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public role?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public who?: FlatConvectorModel<Reference>; //PractitionerRole|Practitioner|Organization|Device|Patient|RelatedPerson @Validate(yup.string()) public altId?: string; @Validate(yup.string()) public name?: string; @Required() @Validate(yup.boolean()) public requestor: boolean; @Validate(yup.lazy(() => Reference.schema())) public location?: FlatConvectorModel<Reference>; //Location @Validate(yup.array(yup.string())) public policy? : Array<string>; @Validate(yup.lazy(() => Coding.schema())) public media?: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => AuditEventAgentNetwork.schema())) public network?: FlatConvectorModel<AuditEventAgentNetwork>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public purposeOfUse?: Array<FlatConvectorModel<CodeableConcept>>; } export class AuditEventAgentNetwork extends BackboneElement { @Default('fhir.datatypes.AuditEvent.AuditEventAgentNetwork') @ReadOnly() public readonly type: string; @Validate(yup.string()) public address?: string; @Validate(yup.string()) public type_?: string; } export class AuditEventSource extends BackboneElement { @Default('fhir.datatypes.AuditEvent.AuditEventSource') @ReadOnly() public readonly type: string; @Validate(yup.string()) public site?: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public observer: FlatConvectorModel<Reference>; //PractitionerRole|Practitioner|Organization|Device|Patient|RelatedPerson @Validate(yup.lazy(() => yup.array(Coding.schema()))) public type_?: Array<FlatConvectorModel<Coding>>; } export class AuditEventEntity extends BackboneElement { @Default('fhir.datatypes.AuditEvent.AuditEventEntity') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Reference.schema())) public what?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => Coding.schema())) public type_?: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => Coding.schema())) public role?: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => Coding.schema())) public lifecycle?: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public securityLabel?: Array<FlatConvectorModel<Coding>>; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public query?: string; @Validate(yup.lazy(() => yup.array(AuditEventEntityDetail.schema()))) public detail?: Array<FlatConvectorModel<AuditEventEntityDetail>>; } export class AuditEventEntityDetail extends BackboneElement { @Default('fhir.datatypes.AuditEvent.AuditEventEntityDetail') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Required() @Validate(yup.string()) public valueString: string; @Required() @Validate(yup.string()) public valueBase64Binary: string; } export class AuditEvent extends DomainResource<AuditEvent> { @Default('fhir.datatypes.AuditEvent') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Coding.schema())) public type_: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public subtype?: Array<FlatConvectorModel<Coding>>; @Validate(yup.string()) public action?: string; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Required() @Validate(yup.string()) public recorded: string; @Validate(yup.string()) public outcome?: string; @Validate(yup.string()) public outcomeDesc?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public purposeOfEvent?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(AuditEventAgent.schema()))) public agent?: Array<FlatConvectorModel<AuditEventAgent>>; @Required() @Validate(yup.lazy(() => AuditEventSource.schema())) public source: FlatConvectorModel<AuditEventSource>; @Validate(yup.lazy(() => yup.array(AuditEventEntity.schema()))) public entity?: Array<FlatConvectorModel<AuditEventEntity>>; } export class Basic extends DomainResource<Basic> { @Default('fhir.datatypes.Basic') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Any @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created?: date; @Validate(yup.lazy(() => Reference.schema())) public author?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Patient|RelatedPerson|Organization } export class Binary extends DomainResource<Binary> { @Default('fhir.datatypes.Binary') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public contentType: string; @Validate(yup.lazy(() => Reference.schema())) public securityContext?: FlatConvectorModel<Reference>; //Any @Validate(yup.string()) public data?: string; } export class BiologicallyDerivedProductCollection extends BackboneElement { @Default('fhir.datatypes.BiologicallyDerivedProduct.BiologicallyDerivedProductCollection') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Reference.schema())) public collector?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => Reference.schema())) public source?: FlatConvectorModel<Reference>; //Patient|Organization @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public collectedDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public collectedPeriod?: FlatConvectorModel<Period>; } export class BiologicallyDerivedProductProcessing extends BackboneElement { @Default('fhir.datatypes.BiologicallyDerivedProduct.BiologicallyDerivedProductProcessing') @ReadOnly() public readonly type: string; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public procedure?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public additive?: FlatConvectorModel<Reference>; //Substance @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public timeDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public timePeriod?: FlatConvectorModel<Period>; } export class BiologicallyDerivedProductManipulation extends BackboneElement { @Default('fhir.datatypes.BiologicallyDerivedProduct.BiologicallyDerivedProductManipulation') @ReadOnly() public readonly type: string; @Validate(yup.string()) public description?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public timeDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public timePeriod?: FlatConvectorModel<Period>; } export class BiologicallyDerivedProductStorage extends BackboneElement { @Default('fhir.datatypes.BiologicallyDerivedProduct.BiologicallyDerivedProductStorage') @ReadOnly() public readonly type: string; @Validate(yup.string()) public description?: string; @Validate(yup.number()) public temperature?: number; @Validate(yup.string()) public scale?: string; @Validate(yup.lazy(() => Period.schema())) public duration?: FlatConvectorModel<Period>; } export class BiologicallyDerivedProduct extends DomainResource<BiologicallyDerivedProduct> { @Default('fhir.datatypes.BiologicallyDerivedProduct') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public productCategory?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public productCode?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public request?: Array<FlatConvectorModel<Reference>>; //ServiceRequest @Validate(yup.number()) public quantity?: number; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public parent?: Array<FlatConvectorModel<Reference>>; //BiologicallyDerivedProduct @Validate(yup.lazy(() => BiologicallyDerivedProductCollection.schema())) public collection?: FlatConvectorModel<BiologicallyDerivedProductCollection>; @Validate(yup.lazy(() => yup.array(BiologicallyDerivedProductProcessing.schema()))) public processing?: Array<FlatConvectorModel<BiologicallyDerivedProductProcessing>>; @Validate(yup.lazy(() => BiologicallyDerivedProductManipulation.schema())) public manipulation?: FlatConvectorModel<BiologicallyDerivedProductManipulation>; @Validate(yup.lazy(() => yup.array(BiologicallyDerivedProductStorage.schema()))) public storage?: Array<FlatConvectorModel<BiologicallyDerivedProductStorage>>; } export class BodyStructure extends DomainResource<BodyStructure> { @Default('fhir.datatypes.BodyStructure') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.boolean()) public active?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public morphology?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public location?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public locationQualifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public description?: string; // @Validate(yup.lazy(() => yup.array(Attachment.schema()))) public image?: Array<FlatConvectorModel<Attachment>>; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient } export class BundleLink extends BackboneElement { @Default('fhir.datatypes.Bundle.BundleLink') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public relation: string; @Required() @Validate(yup.string()) public url: string; } export class BundleEntrySearch extends BackboneElement { @Default('fhir.datatypes.Bundle.BundleEntrySearch') @ReadOnly() public readonly type: string; @Validate(yup.string()) public mode?: string; @Validate(yup.number()) public score?: number; } export class BundleEntryRequest extends BackboneElement { @Default('fhir.datatypes.Bundle.BundleEntryRequest') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public method: string; @Required() @Validate(yup.string()) public url: string; @Validate(yup.string()) public ifNoneMatch?: string; @Validate(yup.string()) public ifModifiedSince?: string; @Validate(yup.string()) public ifMatch?: string; @Validate(yup.string()) public ifNoneExist?: string; } export class Bundle extends DomainResource<Bundle> { @Default('fhir.datatypes.Bundle') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public timestamp?: string; @Validate(yup.number()) public total?: number; @Validate(yup.lazy(() => yup.array(BundleLink.schema()))) public link?: Array<FlatConvectorModel<BundleLink>>; @Validate(yup.lazy(() => yup.array(BundleEntry.schema()))) public entry?: Array<FlatConvectorModel<BundleEntry>>; @Validate(yup.lazy(() => Signature.schema())) public signature?: FlatConvectorModel<Signature>; } export class CapabilityStatementSoftware extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementSoftware') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public version?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public releaseDate?: date; } export class CapabilityStatementImplementation extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementImplementation') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public description: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => Reference.schema())) public custodian?: FlatConvectorModel<Reference>; //Organization } export class CapabilityStatementRest extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementRest') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public mode: string; @Validate(yup.string()) public documentation?: string; @Validate(yup.lazy(() => CapabilityStatementRestSecurity.schema())) public security?: FlatConvectorModel<CapabilityStatementRestSecurity>; @Validate(yup.lazy(() => yup.array(CapabilityStatementRestResource.schema()))) public resource?: Array<FlatConvectorModel<CapabilityStatementRestResource>>; @Validate(yup.lazy(() => yup.array(CapabilityStatementRestInteraction.schema()))) public interaction?: Array<FlatConvectorModel<CapabilityStatementRestInteraction>>; @Validate(yup.lazy(() => yup.array(CapabilityStatementRestResourceSearchParam.schema()))) public searchParam?: Array<FlatConvectorModel<CapabilityStatementRestResourceSearchParam>>; @Validate(yup.lazy(() => yup.array(CapabilityStatementRestResourceOperation.schema()))) public operation?: Array<FlatConvectorModel<CapabilityStatementRestResourceOperation>>; @Validate(yup.array(yup.string())) public compartment? : Array<string>; //CompartmentDefinition } export class CapabilityStatementRestSecurity extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementRestSecurity') @ReadOnly() public readonly type: string; @Validate(yup.boolean()) public cors?: boolean; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public service?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public description?: string; } export class CapabilityStatementRestResource extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementRestResource') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public profile?: string; //StructureDefinition @Validate(yup.array(yup.string())) public supportedProfile? : Array<string>; //StructureDefinition @Validate(yup.string()) public documentation?: string; @Validate(yup.lazy(() => yup.array(CapabilityStatementRestResourceInteraction.schema()))) public interaction?: Array<FlatConvectorModel<CapabilityStatementRestResourceInteraction>>; @Validate(yup.string()) public versioning?: string; @Validate(yup.boolean()) public readHistory?: boolean; @Validate(yup.boolean()) public updateCreate?: boolean; @Validate(yup.boolean()) public conditionalCreate?: boolean; @Validate(yup.string()) public conditionalRead?: string; @Validate(yup.boolean()) public conditionalUpdate?: boolean; @Validate(yup.string()) public conditionalDelete?: string; @Validate(yup.array(yup.string())) public referencePolicy? : Array<string>; @Validate(yup.array(yup.string())) public searchInclude? : Array<string>; @Validate(yup.array(yup.string())) public searchRevInclude? : Array<string>; @Validate(yup.lazy(() => yup.array(CapabilityStatementRestResourceSearchParam.schema()))) public searchParam?: Array<FlatConvectorModel<CapabilityStatementRestResourceSearchParam>>; @Validate(yup.lazy(() => yup.array(CapabilityStatementRestResourceOperation.schema()))) public operation?: Array<FlatConvectorModel<CapabilityStatementRestResourceOperation>>; } export class CapabilityStatementRestResourceInteraction extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementRestResourceInteraction') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.string()) public documentation?: string; } export class CapabilityStatementRestResourceSearchParam extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementRestResourceSearchParam') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public definition?: string; //SearchParameter @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public documentation?: string; } export class CapabilityStatementRestResourceOperation extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementRestResourceOperation') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Required() @Validate(yup.string()) public definition: string; //OperationDefinition @Validate(yup.string()) public documentation?: string; } export class CapabilityStatementRestInteraction extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementRestInteraction') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.string()) public documentation?: string; } export class CapabilityStatementMessaging extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementMessaging') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CapabilityStatementMessagingEndpoint.schema()))) public endpoint?: Array<FlatConvectorModel<CapabilityStatementMessagingEndpoint>>; @Validate(yup.number()) public reliableCache?: number; @Validate(yup.string()) public documentation?: string; @Validate(yup.lazy(() => yup.array(CapabilityStatementMessagingSupportedMessage.schema()))) public supportedMessage?: Array<FlatConvectorModel<CapabilityStatementMessagingSupportedMessage>>; } export class CapabilityStatementMessagingEndpoint extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementMessagingEndpoint') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Coding.schema())) public protocol: FlatConvectorModel<Coding>; @Required() @Validate(yup.string()) public address: string; } export class CapabilityStatementMessagingSupportedMessage extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementMessagingSupportedMessage') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public mode: string; @Required() @Validate(yup.string()) public definition: string; //MessageDefinition } export class CapabilityStatementDocument extends BackboneElement { @Default('fhir.datatypes.CapabilityStatement.CapabilityStatementDocument') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public mode: string; @Validate(yup.string()) public documentation?: string; @Required() @Validate(yup.string()) public profile: string; //StructureDefinition } export class CapabilityStatement extends DomainResource<CapabilityStatement> { @Default('fhir.datatypes.CapabilityStatement') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public copyright?: string; @Required() @Validate(yup.string()) public kind: string; @Validate(yup.array(yup.string())) public instantiates? : Array<string>; //CapabilityStatement @Validate(yup.array(yup.string())) public imports? : Array<string>; //CapabilityStatement @Validate(yup.lazy(() => CapabilityStatementSoftware.schema())) public software?: FlatConvectorModel<CapabilityStatementSoftware>; @Validate(yup.lazy(() => CapabilityStatementImplementation.schema())) public implementation?: FlatConvectorModel<CapabilityStatementImplementation>; @Required() @Validate(yup.string()) public fhirVersion: string; @Validate(yup.array(yup.string())) public format? : Array<string>; @Validate(yup.array(yup.string())) public patchFormat? : Array<string>; @Validate(yup.array(yup.string())) public implementationGuide? : Array<string>; //ImplementationGuide @Validate(yup.lazy(() => yup.array(CapabilityStatementRest.schema()))) public rest?: Array<FlatConvectorModel<CapabilityStatementRest>>; @Validate(yup.lazy(() => yup.array(CapabilityStatementMessaging.schema()))) public messaging?: Array<FlatConvectorModel<CapabilityStatementMessaging>>; @Validate(yup.lazy(() => yup.array(CapabilityStatementDocument.schema()))) public document?: Array<FlatConvectorModel<CapabilityStatementDocument>>; } export class CarePlanActivity extends BackboneElement { @Default('fhir.datatypes.CarePlan.CarePlanActivity') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public outcomeCodeableConcept?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public outcomeReference?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public progress?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => Reference.schema())) public reference?: FlatConvectorModel<Reference>; //Appointment|CommunicationRequest|DeviceRequest|MedicationRequest|NutritionOrder|Task|ServiceRequest|VisionPrescription|RequestGroup @Validate(yup.lazy(() => CarePlanActivityDetail.schema())) public detail?: FlatConvectorModel<CarePlanActivityDetail>; } export class CarePlanActivityDetail extends BackboneElement { @Default('fhir.datatypes.CarePlan.CarePlanActivityDetail') @ReadOnly() public readonly type: string; @Validate(yup.string()) public kind?: string; @Validate(yup.array(yup.string())) public instantiatesCanonical? : Array<string>; //PlanDefinition|ActivityDefinition|Questionnaire|Measure|OperationDefinition @Validate(yup.array(yup.string())) public instantiatesUri? : Array<string>; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport|DocumentReference @Validate(yup.lazy(() => yup.array(Reference.schema()))) public goal?: Array<FlatConvectorModel<Reference>>; //Goal @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public statusReason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public doNotPerform?: boolean; @Validate(yup.lazy(() => Timing.schema())) public scheduledTiming?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => Period.schema())) public scheduledPeriod?: FlatConvectorModel<Period>; @Validate(yup.string()) public scheduledString?: string; @Validate(yup.lazy(() => Reference.schema())) public location?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => yup.array(Reference.schema()))) public performer?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole|Organization|RelatedPerson|Patient|CareTeam|HealthcareService|Device @Validate(yup.lazy(() => CodeableConcept.schema())) public productCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public productReference?: FlatConvectorModel<Reference>; //Medication|Substance @Validate(yup.lazy(() => SimpleQuantity.schema())) public dailyAmount?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.string()) public description?: string; } export class CarePlan extends DomainResource<CarePlan> { @Default('fhir.datatypes.CarePlan') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.array(yup.string())) public instantiatesCanonical? : Array<string>; //PlanDefinition|Questionnaire|Measure|ActivityDefinition|OperationDefinition @Validate(yup.array(yup.string())) public instantiatesUri? : Array<string>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //CarePlan @Validate(yup.lazy(() => yup.array(Reference.schema()))) public replaces?: Array<FlatConvectorModel<Reference>>; //CarePlan @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //CarePlan @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.string()) public intent: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public description?: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created?: date; @Validate(yup.lazy(() => Reference.schema())) public author?: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|Device|RelatedPerson|Organization|CareTeam @Validate(yup.lazy(() => yup.array(Reference.schema()))) public contributor?: Array<FlatConvectorModel<Reference>>; //Patient|Practitioner|PractitionerRole|Device|RelatedPerson|Organization|CareTeam @Validate(yup.lazy(() => yup.array(Reference.schema()))) public careTeam?: Array<FlatConvectorModel<Reference>>; //CareTeam @Validate(yup.lazy(() => yup.array(Reference.schema()))) public addresses?: Array<FlatConvectorModel<Reference>>; //Condition @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supportingInfo?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(Reference.schema()))) public goal?: Array<FlatConvectorModel<Reference>>; //Goal @Validate(yup.lazy(() => yup.array(CarePlanActivity.schema()))) public activity?: Array<FlatConvectorModel<CarePlanActivity>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class CareTeamParticipant extends BackboneElement { @Default('fhir.datatypes.CareTeam.CareTeamParticipant') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public role?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public member?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|RelatedPerson|Patient|Organization|CareTeam @Validate(yup.lazy(() => Reference.schema())) public onBehalfOf?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; } export class CareTeam extends DomainResource<CareTeam> { @Default('fhir.datatypes.CareTeam') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public name?: string; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CareTeamParticipant.schema()))) public participant?: Array<FlatConvectorModel<CareTeamParticipant>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition @Validate(yup.lazy(() => yup.array(Reference.schema()))) public managingOrganization?: Array<FlatConvectorModel<Reference>>; //Organization @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class CatalogEntryRelatedEntry extends BackboneElement { @Default('fhir.datatypes.CatalogEntry.CatalogEntryRelatedEntry') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public relationtype: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public item: FlatConvectorModel<Reference>; //CatalogEntry } export class CatalogEntry extends DomainResource<CatalogEntry> { @Default('fhir.datatypes.CatalogEntry') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.boolean()) public orderable: boolean; @Required() @Validate(yup.lazy(() => Reference.schema())) public referencedItem: FlatConvectorModel<Reference>; //Medication|Device|Organization|Practitioner|PractitionerRole|HealthcareService|ActivityDefinition|PlanDefinition|SpecimenDefinition|ObservationDefinition|Binary @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public additionalIdentifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public classification?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => Period.schema())) public validityPeriod?: FlatConvectorModel<Period>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public validTo?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastUpdated?: date; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public additionalCharacteristic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public additionalClassification?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CatalogEntryRelatedEntry.schema()))) public relatedEntry?: Array<FlatConvectorModel<CatalogEntryRelatedEntry>>; } export class ChargeItemPerformer extends BackboneElement { @Default('fhir.datatypes.ChargeItem.ChargeItemPerformer') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public function_?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public actor: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|CareTeam|Patient|Device|RelatedPerson } export class ChargeItem extends DomainResource<ChargeItem> { @Default('fhir.datatypes.ChargeItem') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.array(yup.string())) public definitionUri? : Array<string>; @Validate(yup.array(yup.string())) public definitionCanonical? : Array<string>; //ChargeItemDefinition @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //ChargeItem @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public context?: FlatConvectorModel<Reference>; //Encounter|EpisodeOfCare @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public occurrenceDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public occurrencePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Timing.schema())) public occurrenceTiming?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => yup.array(ChargeItemPerformer.schema()))) public performer?: Array<FlatConvectorModel<ChargeItemPerformer>>; @Validate(yup.lazy(() => Reference.schema())) public performingOrganization?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public requestingOrganization?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public costCenter?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Quantity.schema())) public quantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public bodysite?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.number()) public factorOverride?: number; @Validate(yup.lazy(() => Money.schema())) public priceOverride?: FlatConvectorModel<Money>; @Validate(yup.string()) public overrideReason?: string; @Validate(yup.lazy(() => Reference.schema())) public enterer?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|Patient|Device|RelatedPerson @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public enteredDate?: date; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reason?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public service?: Array<FlatConvectorModel<Reference>>; //DiagnosticReport|ImagingStudy|Immunization|MedicationAdministration|MedicationDispense|Observation|Procedure|SupplyDelivery @Validate(yup.lazy(() => Reference.schema())) public productReference?: FlatConvectorModel<Reference>; //Device|Medication|Substance @Validate(yup.lazy(() => CodeableConcept.schema())) public productCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public account?: Array<FlatConvectorModel<Reference>>; //Account @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supportingInformation?: Array<FlatConvectorModel<Reference>>; //Any } export class ChargeItemDefinitionApplicability extends BackboneElement { @Default('fhir.datatypes.ChargeItemDefinition.ChargeItemDefinitionApplicability') @ReadOnly() public readonly type: string; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public language?: string; @Validate(yup.string()) public expression?: string; } export class ChargeItemDefinitionPropertyGroup extends BackboneElement { @Default('fhir.datatypes.ChargeItemDefinition.ChargeItemDefinitionPropertyGroup') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(ChargeItemDefinitionApplicability.schema()))) public applicability?: Array<FlatConvectorModel<ChargeItemDefinitionApplicability>>; @Validate(yup.lazy(() => yup.array(ChargeItemDefinitionPropertyGroupPriceComponent.schema()))) public priceComponent?: Array<FlatConvectorModel<ChargeItemDefinitionPropertyGroupPriceComponent>>; } export class ChargeItemDefinitionPropertyGroupPriceComponent extends BackboneElement { @Default('fhir.datatypes.ChargeItemDefinition.ChargeItemDefinitionPropertyGroupPriceComponent') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public amount?: FlatConvectorModel<Money>; } export class ChargeItemDefinition extends DomainResource<ChargeItemDefinition> { @Default('fhir.datatypes.ChargeItemDefinition') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public url: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public title?: string; @Validate(yup.array(yup.string())) public derivedFromUri? : Array<string>; @Validate(yup.array(yup.string())) public partOf? : Array<string>; //ChargeItemDefinition @Validate(yup.array(yup.string())) public replaces? : Array<string>; //ChargeItemDefinition @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public instance?: Array<FlatConvectorModel<Reference>>; //Medication|Substance|Device @Validate(yup.lazy(() => yup.array(ChargeItemDefinitionApplicability.schema()))) public applicability?: Array<FlatConvectorModel<ChargeItemDefinitionApplicability>>; @Validate(yup.lazy(() => yup.array(ChargeItemDefinitionPropertyGroup.schema()))) public propertyGroup?: Array<FlatConvectorModel<ChargeItemDefinitionPropertyGroup>>; } export class ClaimRelated extends BackboneElement { @Default('fhir.datatypes.Claim.ClaimRelated') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Reference.schema())) public claim?: FlatConvectorModel<Reference>; //Claim @Validate(yup.lazy(() => CodeableConcept.schema())) public relationship?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Identifier.schema())) public reference?: FlatConvectorModel<Identifier>; } export class ClaimPayee extends BackboneElement { @Default('fhir.datatypes.Claim.ClaimPayee') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public party?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|Patient|RelatedPerson } export class ClaimCareTeam extends BackboneElement { @Default('fhir.datatypes.Claim.ClaimCareTeam') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Required() @Validate(yup.lazy(() => Reference.schema())) public provider: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.boolean()) public responsible?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public role?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public qualification?: FlatConvectorModel<CodeableConcept>; } export class ClaimSupportingInfo extends BackboneElement { @Default('fhir.datatypes.Claim.ClaimSupportingInfo') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public category: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public timingDate?: date; @Validate(yup.lazy(() => Period.schema())) public timingPeriod?: FlatConvectorModel<Period>; @Validate(yup.boolean()) public valueBoolean?: boolean; @Validate(yup.string()) public valueString?: string; @Validate(yup.lazy(() => Quantity.schema())) public valueQuantity?: FlatConvectorModel<Quantity>; // @Validate(yup.lazy(() => Attachment.schema())) public valueAttachment?: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => Reference.schema())) public valueReference?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => CodeableConcept.schema())) public reason?: FlatConvectorModel<CodeableConcept>; } export class ClaimDiagnosis extends BackboneElement { @Default('fhir.datatypes.Claim.ClaimDiagnosis') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public diagnosisCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public diagnosisReference: FlatConvectorModel<Reference>; //Condition @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public onAdmission?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public packageCode?: FlatConvectorModel<CodeableConcept>; } export class ClaimProcedure extends BackboneElement { @Default('fhir.datatypes.Claim.ClaimProcedure') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public procedureCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public procedureReference: FlatConvectorModel<Reference>; //Procedure @Validate(yup.lazy(() => yup.array(Reference.schema()))) public udi?: Array<FlatConvectorModel<Reference>>; //Device } export class ClaimInsurance extends BackboneElement { @Default('fhir.datatypes.Claim.ClaimInsurance') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Required() @Validate(yup.boolean()) public focal: boolean; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Required() @Validate(yup.lazy(() => Reference.schema())) public coverage: FlatConvectorModel<Reference>; //Coverage @Validate(yup.string()) public businessArrangement?: string; @Validate(yup.array(yup.string())) public preAuthRef? : Array<string>; @Validate(yup.lazy(() => Reference.schema())) public claimResponse?: FlatConvectorModel<Reference>; //ClaimResponse } export class ClaimAccident extends BackboneElement { @Default('fhir.datatypes.Claim.ClaimAccident') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date: date; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Address.schema())) public locationAddress?: FlatConvectorModel<Address>; @Validate(yup.lazy(() => Reference.schema())) public locationReference?: FlatConvectorModel<Reference>; //Location } export class ClaimItem extends BackboneElement { @Default('fhir.datatypes.Claim.ClaimItem') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Validate(yup.array(yup.number())) public careTeamSequence? : Array<number>; @Validate(yup.array(yup.number())) public diagnosisSequence? : Array<number>; @Validate(yup.array(yup.number())) public procedureSequence? : Array<number>; @Validate(yup.array(yup.number())) public informationSequence? : Array<number>; @Validate(yup.lazy(() => CodeableConcept.schema())) public revenue?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public programCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public servicedDate?: date; @Validate(yup.lazy(() => Period.schema())) public servicedPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => CodeableConcept.schema())) public locationCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Address.schema())) public locationAddress?: FlatConvectorModel<Address>; @Validate(yup.lazy(() => Reference.schema())) public locationReference?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public udi?: Array<FlatConvectorModel<Reference>>; //Device @Validate(yup.lazy(() => CodeableConcept.schema())) public bodySite?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public subSite?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public encounter?: Array<FlatConvectorModel<Reference>>; //Encounter @Validate(yup.lazy(() => yup.array(ClaimItemDetail.schema()))) public detail?: Array<FlatConvectorModel<ClaimItemDetail>>; } export class ClaimItemDetail extends BackboneElement { @Default('fhir.datatypes.Claim.ClaimItemDetail') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Validate(yup.lazy(() => CodeableConcept.schema())) public revenue?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public programCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public udi?: Array<FlatConvectorModel<Reference>>; //Device @Validate(yup.lazy(() => yup.array(ClaimItemDetailSubDetail.schema()))) public subDetail?: Array<FlatConvectorModel<ClaimItemDetailSubDetail>>; } export class ClaimItemDetailSubDetail extends BackboneElement { @Default('fhir.datatypes.Claim.ClaimItemDetailSubDetail') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Validate(yup.lazy(() => CodeableConcept.schema())) public revenue?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public programCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public udi?: Array<FlatConvectorModel<Reference>>; //Device } export class Claim extends DomainResource<Claim> { @Default('fhir.datatypes.Claim') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public subType?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string()) public use: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => Period.schema())) public billablePeriod?: FlatConvectorModel<Period>; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created: date; @Validate(yup.lazy(() => Reference.schema())) public enterer?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => Reference.schema())) public insurer?: FlatConvectorModel<Reference>; //Organization @Required() @Validate(yup.lazy(() => Reference.schema())) public provider: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public priority: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public fundsReserve?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(ClaimRelated.schema()))) public related?: Array<FlatConvectorModel<ClaimRelated>>; @Validate(yup.lazy(() => Reference.schema())) public prescription?: FlatConvectorModel<Reference>; //DeviceRequest|MedicationRequest|VisionPrescription @Validate(yup.lazy(() => Reference.schema())) public originalPrescription?: FlatConvectorModel<Reference>; //DeviceRequest|MedicationRequest|VisionPrescription @Validate(yup.lazy(() => ClaimPayee.schema())) public payee?: FlatConvectorModel<ClaimPayee>; @Validate(yup.lazy(() => Reference.schema())) public referral?: FlatConvectorModel<Reference>; //ServiceRequest @Validate(yup.lazy(() => Reference.schema())) public facility?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => yup.array(ClaimCareTeam.schema()))) public careTeam?: Array<FlatConvectorModel<ClaimCareTeam>>; @Validate(yup.lazy(() => yup.array(ClaimSupportingInfo.schema()))) public supportingInfo?: Array<FlatConvectorModel<ClaimSupportingInfo>>; @Validate(yup.lazy(() => yup.array(ClaimDiagnosis.schema()))) public diagnosis?: Array<FlatConvectorModel<ClaimDiagnosis>>; @Validate(yup.lazy(() => yup.array(ClaimProcedure.schema()))) public procedure?: Array<FlatConvectorModel<ClaimProcedure>>; @Validate(yup.lazy(() => yup.array(ClaimInsurance.schema()))) public insurance?: Array<FlatConvectorModel<ClaimInsurance>>; @Validate(yup.lazy(() => ClaimAccident.schema())) public accident?: FlatConvectorModel<ClaimAccident>; @Validate(yup.lazy(() => yup.array(ClaimItem.schema()))) public item?: Array<FlatConvectorModel<ClaimItem>>; @Validate(yup.lazy(() => Money.schema())) public total?: FlatConvectorModel<Money>; } export class ClaimResponseItem extends BackboneElement { @Default('fhir.datatypes.ClaimResponse.ClaimResponseItem') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public itemSequence: number; @Validate(yup.array(yup.number())) public noteNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ClaimResponseItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ClaimResponseItemAdjudication>>; @Validate(yup.lazy(() => yup.array(ClaimResponseItemDetail.schema()))) public detail?: Array<FlatConvectorModel<ClaimResponseItemDetail>>; } export class ClaimResponseItemAdjudication extends BackboneElement { @Default('fhir.datatypes.ClaimResponse.ClaimResponseItemAdjudication') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public category: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public reason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Money.schema())) public amount?: FlatConvectorModel<Money>; @Validate(yup.number()) public value?: number; } export class ClaimResponseItemDetail extends BackboneElement { @Default('fhir.datatypes.ClaimResponse.ClaimResponseItemDetail') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public detailSequence: number; @Validate(yup.array(yup.number())) public noteNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ClaimResponseItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ClaimResponseItemAdjudication>>; @Validate(yup.lazy(() => yup.array(ClaimResponseItemDetailSubDetail.schema()))) public subDetail?: Array<FlatConvectorModel<ClaimResponseItemDetailSubDetail>>; } export class ClaimResponseItemDetailSubDetail extends BackboneElement { @Default('fhir.datatypes.ClaimResponse.ClaimResponseItemDetailSubDetail') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public subDetailSequence: number; @Validate(yup.array(yup.number())) public noteNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ClaimResponseItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ClaimResponseItemAdjudication>>; } export class ClaimResponseAddItem extends BackboneElement { @Default('fhir.datatypes.ClaimResponse.ClaimResponseAddItem') @ReadOnly() public readonly type: string; @Validate(yup.array(yup.number())) public itemSequence? : Array<number>; @Validate(yup.array(yup.number())) public detailSequence? : Array<number>; @Validate(yup.array(yup.number())) public subdetailSequence? : Array<number>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public provider?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole|Organization @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public programCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public servicedDate?: date; @Validate(yup.lazy(() => Period.schema())) public servicedPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => CodeableConcept.schema())) public locationCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Address.schema())) public locationAddress?: FlatConvectorModel<Address>; @Validate(yup.lazy(() => Reference.schema())) public locationReference?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => CodeableConcept.schema())) public bodySite?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public subSite?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.array(yup.number())) public noteNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ClaimResponseItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ClaimResponseItemAdjudication>>; @Validate(yup.lazy(() => yup.array(ClaimResponseAddItemDetail.schema()))) public detail?: Array<FlatConvectorModel<ClaimResponseAddItemDetail>>; } export class ClaimResponseAddItemDetail extends BackboneElement { @Default('fhir.datatypes.ClaimResponse.ClaimResponseAddItemDetail') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.array(yup.number())) public noteNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ClaimResponseItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ClaimResponseItemAdjudication>>; @Validate(yup.lazy(() => yup.array(ClaimResponseAddItemDetailSubDetail.schema()))) public subDetail?: Array<FlatConvectorModel<ClaimResponseAddItemDetailSubDetail>>; } export class ClaimResponseAddItemDetailSubDetail extends BackboneElement { @Default('fhir.datatypes.ClaimResponse.ClaimResponseAddItemDetailSubDetail') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.array(yup.number())) public noteNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ClaimResponseItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ClaimResponseItemAdjudication>>; } export class ClaimResponseTotal extends BackboneElement { @Default('fhir.datatypes.ClaimResponse.ClaimResponseTotal') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public category: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Money.schema())) public amount: FlatConvectorModel<Money>; } export class ClaimResponsePayment extends BackboneElement { @Default('fhir.datatypes.ClaimResponse.ClaimResponsePayment') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Money.schema())) public adjustment?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => CodeableConcept.schema())) public adjustmentReason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Required() @Validate(yup.lazy(() => Money.schema())) public amount: FlatConvectorModel<Money>; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; } export class ClaimResponseProcessNote extends BackboneElement { @Default('fhir.datatypes.ClaimResponse.ClaimResponseProcessNote') @ReadOnly() public readonly type: string; @Validate(yup.number()) public number?: number; @Validate(yup.string()) public type_?: string; @Required() @Validate(yup.string()) public text: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public language?: FlatConvectorModel<CodeableConcept>; } export class ClaimResponseInsurance extends BackboneElement { @Default('fhir.datatypes.ClaimResponse.ClaimResponseInsurance') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Required() @Validate(yup.boolean()) public focal: boolean; @Required() @Validate(yup.lazy(() => Reference.schema())) public coverage: FlatConvectorModel<Reference>; //Coverage @Validate(yup.string()) public businessArrangement?: string; @Validate(yup.lazy(() => Reference.schema())) public claimResponse?: FlatConvectorModel<Reference>; //ClaimResponse } export class ClaimResponseError extends BackboneElement { @Default('fhir.datatypes.ClaimResponse.ClaimResponseError') @ReadOnly() public readonly type: string; @Validate(yup.number()) public itemSequence?: number; @Validate(yup.number()) public detailSequence?: number; @Validate(yup.number()) public subDetailSequence?: number; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; } export class ClaimResponse extends DomainResource<ClaimResponse> { @Default('fhir.datatypes.ClaimResponse') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public subType?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string()) public use: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created: date; @Required() @Validate(yup.lazy(() => Reference.schema())) public insurer: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public requestor?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => Reference.schema())) public request?: FlatConvectorModel<Reference>; //Claim @Required() @Validate(yup.string()) public outcome: string; @Validate(yup.string()) public disposition?: string; @Validate(yup.string()) public preAuthRef?: string; @Validate(yup.lazy(() => Period.schema())) public preAuthPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => CodeableConcept.schema())) public payeeType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(ClaimResponseItem.schema()))) public item?: Array<FlatConvectorModel<ClaimResponseItem>>; @Validate(yup.lazy(() => yup.array(ClaimResponseAddItem.schema()))) public addItem?: Array<FlatConvectorModel<ClaimResponseAddItem>>; @Validate(yup.lazy(() => yup.array(ClaimResponseItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ClaimResponseItemAdjudication>>; @Validate(yup.lazy(() => yup.array(ClaimResponseTotal.schema()))) public total?: Array<FlatConvectorModel<ClaimResponseTotal>>; @Validate(yup.lazy(() => ClaimResponsePayment.schema())) public payment?: FlatConvectorModel<ClaimResponsePayment>; @Validate(yup.lazy(() => CodeableConcept.schema())) public fundsReserve?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public formCode?: FlatConvectorModel<CodeableConcept>; // @Validate(yup.lazy(() => Attachment.schema())) public form?: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => yup.array(ClaimResponseProcessNote.schema()))) public processNote?: Array<FlatConvectorModel<ClaimResponseProcessNote>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public communicationRequest?: Array<FlatConvectorModel<Reference>>; //CommunicationRequest @Validate(yup.lazy(() => yup.array(ClaimResponseInsurance.schema()))) public insurance?: Array<FlatConvectorModel<ClaimResponseInsurance>>; @Validate(yup.lazy(() => yup.array(ClaimResponseError.schema()))) public error?: Array<FlatConvectorModel<ClaimResponseError>>; } export class ClinicalImpressionInvestigation extends BackboneElement { @Default('fhir.datatypes.ClinicalImpression.ClinicalImpressionInvestigation') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public item?: Array<FlatConvectorModel<Reference>>; //Observation|QuestionnaireResponse|FamilyMemberHistory|DiagnosticReport|RiskAssessment|ImagingStudy|Media } export class ClinicalImpressionFinding extends BackboneElement { @Default('fhir.datatypes.ClinicalImpression.ClinicalImpressionFinding') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public itemCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public itemReference?: FlatConvectorModel<Reference>; //Condition|Observation|Media @Validate(yup.string()) public basis?: string; } export class ClinicalImpression extends DomainResource<ClinicalImpression> { @Default('fhir.datatypes.ClinicalImpression') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public statusReason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public description?: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public effectiveDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.lazy(() => Reference.schema())) public assessor?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => Reference.schema())) public previous?: FlatConvectorModel<Reference>; //ClinicalImpression @Validate(yup.lazy(() => yup.array(Reference.schema()))) public problem?: Array<FlatConvectorModel<Reference>>; //Condition|AllergyIntolerance @Validate(yup.lazy(() => yup.array(ClinicalImpressionInvestigation.schema()))) public investigation?: Array<FlatConvectorModel<ClinicalImpressionInvestigation>>; @Validate(yup.array(yup.string())) public protocol? : Array<string>; @Validate(yup.string()) public summary?: string; @Validate(yup.lazy(() => yup.array(ClinicalImpressionFinding.schema()))) public finding?: Array<FlatConvectorModel<ClinicalImpressionFinding>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public prognosisCodeableConcept?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public prognosisReference?: Array<FlatConvectorModel<Reference>>; //RiskAssessment @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supportingInfo?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class CodeSystemFilter extends BackboneElement { @Default('fhir.datatypes.CodeSystem.CodeSystemFilter') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.string()) public description?: string; @Validate(yup.array(yup.string())) public operator? : Array<string>; @Required() @Validate(yup.string()) public value: string; } export class CodeSystemProperty extends BackboneElement { @Default('fhir.datatypes.CodeSystem.CodeSystemProperty') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.string()) public uri?: string; @Validate(yup.string()) public description?: string; @Required() @Validate(yup.string()) public type_: string; } export class CodeSystemConcept extends BackboneElement { @Default('fhir.datatypes.CodeSystem.CodeSystemConcept') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.string()) public display?: string; @Validate(yup.string()) public definition?: string; @Validate(yup.lazy(() => yup.array(CodeSystemConceptDesignation.schema()))) public designation?: Array<FlatConvectorModel<CodeSystemConceptDesignation>>; @Validate(yup.lazy(() => yup.array(CodeSystemConceptProperty.schema()))) public property?: Array<FlatConvectorModel<CodeSystemConceptProperty>>; @Validate(yup.lazy(() => yup.array(CodeSystemConcept.schema()))) public concept?: Array<FlatConvectorModel<CodeSystemConcept>>; } export class CodeSystemConceptDesignation extends BackboneElement { @Default('fhir.datatypes.CodeSystem.CodeSystemConceptDesignation') @ReadOnly() public readonly type: string; @Validate(yup.string()) public language?: string; @Validate(yup.lazy(() => Coding.schema())) public use?: FlatConvectorModel<Coding>; @Required() @Validate(yup.string()) public value: string; } export class CodeSystemConceptProperty extends BackboneElement { @Default('fhir.datatypes.CodeSystem.CodeSystemConceptProperty') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Required() @Validate(yup.string()) public valueCode: string; @Required() @Validate(yup.lazy(() => Coding.schema())) public valueCoding: FlatConvectorModel<Coding>; @Required() @Validate(yup.string()) public valueString: string; @Required() @Validate(yup.number()) public valueInteger: number; @Required() @Validate(yup.boolean()) public valueBoolean: boolean; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDateTime: date; @Required() @Validate(yup.number()) public valueDecimal: number; } export class CodeSystem extends DomainResource<CodeSystem> { @Default('fhir.datatypes.CodeSystem') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.boolean()) public caseSensitive?: boolean; @Validate(yup.string()) public valueSet?: string; //ValueSet @Validate(yup.string()) public hierarchyMeaning?: string; @Validate(yup.boolean()) public compositional?: boolean; @Validate(yup.boolean()) public versionNeeded?: boolean; @Required() @Validate(yup.string()) public content: string; @Validate(yup.string()) public supplements?: string; //CodeSystem @Validate(yup.number()) public count?: number; @Validate(yup.lazy(() => yup.array(CodeSystemFilter.schema()))) public filter?: Array<FlatConvectorModel<CodeSystemFilter>>; @Validate(yup.lazy(() => yup.array(CodeSystemProperty.schema()))) public property?: Array<FlatConvectorModel<CodeSystemProperty>>; @Validate(yup.lazy(() => yup.array(CodeSystemConcept.schema()))) public concept?: Array<FlatConvectorModel<CodeSystemConcept>>; } export class CommunicationPayload extends BackboneElement { @Default('fhir.datatypes.Communication.CommunicationPayload') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public contentString: string; // @Required() @Validate(yup.lazy(() => Attachment.schema())) public contentAttachment: FlatConvectorModel<Attachment>; @Required() @Validate(yup.lazy(() => Reference.schema())) public contentReference: FlatConvectorModel<Reference>; //Any } export class Communication extends DomainResource<Communication> { @Default('fhir.datatypes.Communication') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.array(yup.string())) public instantiatesCanonical? : Array<string>; //PlanDefinition|ActivityDefinition|Measure|OperationDefinition|Questionnaire @Validate(yup.array(yup.string())) public instantiatesUri? : Array<string>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(Reference.schema()))) public inResponseTo?: Array<FlatConvectorModel<Reference>>; //Communication @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public statusReason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public priority?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public medium?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => CodeableConcept.schema())) public topic?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public about?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public sent?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public received?: date; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public recipient?: Array<FlatConvectorModel<Reference>>; //Device|Organization|Patient|Practitioner|PractitionerRole|RelatedPerson|Group|CareTeam|HealthcareService @Validate(yup.lazy(() => Reference.schema())) public sender?: FlatConvectorModel<Reference>; //Device|Organization|Patient|Practitioner|PractitionerRole|RelatedPerson|HealthcareService @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport|DocumentReference @Validate(yup.lazy(() => yup.array(CommunicationPayload.schema()))) public payload?: Array<FlatConvectorModel<CommunicationPayload>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class CommunicationRequestPayload extends BackboneElement { @Default('fhir.datatypes.CommunicationRequest.CommunicationRequestPayload') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public contentString: string; // @Required() @Validate(yup.lazy(() => Attachment.schema())) public contentAttachment: FlatConvectorModel<Attachment>; @Required() @Validate(yup.lazy(() => Reference.schema())) public contentReference: FlatConvectorModel<Reference>; //Any } export class CommunicationRequest extends DomainResource<CommunicationRequest> { @Default('fhir.datatypes.CommunicationRequest') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(Reference.schema()))) public replaces?: Array<FlatConvectorModel<Reference>>; //CommunicationRequest @Validate(yup.lazy(() => Identifier.schema())) public groupIdentifier?: FlatConvectorModel<Identifier>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public statusReason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public priority?: string; @Validate(yup.boolean()) public doNotPerform?: boolean; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public medium?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => yup.array(Reference.schema()))) public about?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.lazy(() => yup.array(CommunicationRequestPayload.schema()))) public payload?: Array<FlatConvectorModel<CommunicationRequestPayload>>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public occurrenceDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public occurrencePeriod?: FlatConvectorModel<Period>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public authoredOn?: date; @Validate(yup.lazy(() => Reference.schema())) public requester?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|Patient|RelatedPerson|Device @Validate(yup.lazy(() => yup.array(Reference.schema()))) public recipient?: Array<FlatConvectorModel<Reference>>; //Device|Organization|Patient|Practitioner|PractitionerRole|RelatedPerson|Group|CareTeam|HealthcareService @Validate(yup.lazy(() => Reference.schema())) public sender?: FlatConvectorModel<Reference>; //Device|Organization|Patient|Practitioner|PractitionerRole|RelatedPerson|HealthcareService @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport|DocumentReference @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class CompartmentDefinitionResource extends BackboneElement { @Default('fhir.datatypes.CompartmentDefinition.CompartmentDefinitionResource') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.array(yup.string())) public param? : Array<string>; @Validate(yup.string()) public documentation?: string; } export class CompartmentDefinition extends DomainResource<CompartmentDefinition> { @Default('fhir.datatypes.CompartmentDefinition') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public url: string; @Validate(yup.string()) public version?: string; @Required() @Validate(yup.string()) public name: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.string()) public purpose?: string; @Required() @Validate(yup.string()) public code: string; @Required() @Validate(yup.boolean()) public search: boolean; @Validate(yup.lazy(() => yup.array(CompartmentDefinitionResource.schema()))) public resource?: Array<FlatConvectorModel<CompartmentDefinitionResource>>; } export class CompositionAttester extends BackboneElement { @Default('fhir.datatypes.Composition.CompositionAttester') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public mode: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public time?: date; @Validate(yup.lazy(() => Reference.schema())) public party?: FlatConvectorModel<Reference>; //Patient|RelatedPerson|Practitioner|PractitionerRole|Organization } export class CompositionRelatesTo extends BackboneElement { @Default('fhir.datatypes.Composition.CompositionRelatesTo') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Required() @Validate(yup.lazy(() => Identifier.schema())) public targetIdentifier: FlatConvectorModel<Identifier>; @Required() @Validate(yup.lazy(() => Reference.schema())) public targetReference: FlatConvectorModel<Reference>; //Composition } export class CompositionEvent extends BackboneElement { @Default('fhir.datatypes.Composition.CompositionEvent') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public code?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public detail?: Array<FlatConvectorModel<Reference>>; //Any } export class CompositionSection extends BackboneElement { @Default('fhir.datatypes.Composition.CompositionSection') @ReadOnly() public readonly type: string; @Validate(yup.string()) public title?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public author?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole|Device|Patient|RelatedPerson|Organization @Validate(yup.lazy(() => Reference.schema())) public focus?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => Narrative.schema())) public text?: FlatConvectorModel<Narrative>; @Validate(yup.string()) public mode?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public orderedBy?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public entry?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => CodeableConcept.schema())) public emptyReason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CompositionSection.schema()))) public section?: Array<FlatConvectorModel<CompositionSection>>; } export class Composition extends DomainResource<Composition> { @Default('fhir.datatypes.Composition') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date: date; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public author?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole|Device|Patient|RelatedPerson|Organization @Required() @Validate(yup.string()) public title: string; @Validate(yup.string()) public confidentiality?: string; @Validate(yup.lazy(() => yup.array(CompositionAttester.schema()))) public attester?: Array<FlatConvectorModel<CompositionAttester>>; @Validate(yup.lazy(() => Reference.schema())) public custodian?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(CompositionRelatesTo.schema()))) public relatesTo?: Array<FlatConvectorModel<CompositionRelatesTo>>; @Validate(yup.lazy(() => yup.array(CompositionEvent.schema()))) public event?: Array<FlatConvectorModel<CompositionEvent>>; @Validate(yup.lazy(() => yup.array(CompositionSection.schema()))) public section?: Array<FlatConvectorModel<CompositionSection>>; } export class ConceptMapGroup extends BackboneElement { @Default('fhir.datatypes.ConceptMap.ConceptMapGroup') @ReadOnly() public readonly type: string; @Validate(yup.string()) public source?: string; @Validate(yup.string()) public sourceVersion?: string; @Validate(yup.string()) public target?: string; @Validate(yup.string()) public targetVersion?: string; @Validate(yup.lazy(() => yup.array(ConceptMapGroupElement.schema()))) public element?: Array<FlatConvectorModel<ConceptMapGroupElement>>; @Validate(yup.lazy(() => ConceptMapGroupUnmapped.schema())) public unmapped?: FlatConvectorModel<ConceptMapGroupUnmapped>; } export class ConceptMapGroupElement extends BackboneElement { @Default('fhir.datatypes.ConceptMap.ConceptMapGroupElement') @ReadOnly() public readonly type: string; @Validate(yup.string()) public code?: string; @Validate(yup.string()) public display?: string; @Validate(yup.lazy(() => yup.array(ConceptMapGroupElementTarget.schema()))) public target?: Array<FlatConvectorModel<ConceptMapGroupElementTarget>>; } export class ConceptMapGroupElementTarget extends BackboneElement { @Default('fhir.datatypes.ConceptMap.ConceptMapGroupElementTarget') @ReadOnly() public readonly type: string; @Validate(yup.string()) public code?: string; @Validate(yup.string()) public display?: string; @Required() @Validate(yup.string()) public equivalence: string; @Validate(yup.string()) public comment?: string; @Validate(yup.lazy(() => yup.array(ConceptMapGroupElementTargetDependsOn.schema()))) public dependsOn?: Array<FlatConvectorModel<ConceptMapGroupElementTargetDependsOn>>; @Validate(yup.lazy(() => yup.array(ConceptMapGroupElementTargetDependsOn.schema()))) public product?: Array<FlatConvectorModel<ConceptMapGroupElementTargetDependsOn>>; } export class ConceptMapGroupElementTargetDependsOn extends BackboneElement { @Default('fhir.datatypes.ConceptMap.ConceptMapGroupElementTargetDependsOn') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public property: string; @Validate(yup.string()) public system?: string; //CodeSystem @Required() @Validate(yup.string()) public value: string; @Validate(yup.string()) public display?: string; } export class ConceptMapGroupUnmapped extends BackboneElement { @Default('fhir.datatypes.ConceptMap.ConceptMapGroupUnmapped') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public mode: string; @Validate(yup.string()) public code?: string; @Validate(yup.string()) public display?: string; @Validate(yup.string()) public url?: string; //ConceptMap } export class ConceptMap extends DomainResource<ConceptMap> { @Default('fhir.datatypes.ConceptMap') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.string()) public sourceUri?: string; @Validate(yup.string()) public sourceCanonical?: string; //ValueSet @Validate(yup.string()) public targetUri?: string; @Validate(yup.string()) public targetCanonical?: string; //ValueSet @Validate(yup.lazy(() => yup.array(ConceptMapGroup.schema()))) public group?: Array<FlatConvectorModel<ConceptMapGroup>>; } export class ConditionStage extends BackboneElement { @Default('fhir.datatypes.Condition.ConditionStage') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public summary?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public assessment?: Array<FlatConvectorModel<Reference>>; //ClinicalImpression|DiagnosticReport|Observation @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; } export class ConditionEvidence extends BackboneElement { @Default('fhir.datatypes.Condition.ConditionEvidence') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public code?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public detail?: Array<FlatConvectorModel<Reference>>; //Any } export class Condition extends DomainResource<Condition> { @Default('fhir.datatypes.Condition') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public clinicalStatus?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public verificationStatus?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public severity?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public bodySite?: Array<FlatConvectorModel<CodeableConcept>>; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public onsetDateTime?: date; @Validate(yup.lazy(() => Age.schema())) public onsetAge?: FlatConvectorModel<Age>; @Validate(yup.lazy(() => Period.schema())) public onsetPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Range.schema())) public onsetRange?: FlatConvectorModel<Range>; @Validate(yup.string()) public onsetString?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public abatementDateTime?: date; @Validate(yup.lazy(() => Age.schema())) public abatementAge?: FlatConvectorModel<Age>; @Validate(yup.lazy(() => Period.schema())) public abatementPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Range.schema())) public abatementRange?: FlatConvectorModel<Range>; @Validate(yup.string()) public abatementString?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public recordedDate?: date; @Validate(yup.lazy(() => Reference.schema())) public recorder?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Patient|RelatedPerson @Validate(yup.lazy(() => Reference.schema())) public asserter?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Patient|RelatedPerson @Validate(yup.lazy(() => yup.array(ConditionStage.schema()))) public stage?: Array<FlatConvectorModel<ConditionStage>>; @Validate(yup.lazy(() => yup.array(ConditionEvidence.schema()))) public evidence?: Array<FlatConvectorModel<ConditionEvidence>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class ConsentPolicy extends BackboneElement { @Default('fhir.datatypes.Consent.ConsentPolicy') @ReadOnly() public readonly type: string; @Validate(yup.string()) public authority?: string; @Validate(yup.string()) public uri?: string; } export class ConsentVerification extends BackboneElement { @Default('fhir.datatypes.Consent.ConsentVerification') @ReadOnly() public readonly type: string; @Required() @Validate(yup.boolean()) public verified: boolean; @Validate(yup.lazy(() => Reference.schema())) public verifiedWith?: FlatConvectorModel<Reference>; //Patient|RelatedPerson @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public verificationDate?: date; } export class ConsentProvision extends BackboneElement { @Default('fhir.datatypes.Consent.ConsentProvision') @ReadOnly() public readonly type: string; @Validate(yup.string()) public type_?: string; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(ConsentProvisionActor.schema()))) public actor?: Array<FlatConvectorModel<ConsentProvisionActor>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public action?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public securityLabel?: Array<FlatConvectorModel<Coding>>; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public purpose?: Array<FlatConvectorModel<Coding>>; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public class_?: Array<FlatConvectorModel<Coding>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public code?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Period.schema())) public dataPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(ConsentProvisionData.schema()))) public data?: Array<FlatConvectorModel<ConsentProvisionData>>; @Validate(yup.lazy(() => yup.array(ConsentProvision.schema()))) public provision?: Array<FlatConvectorModel<ConsentProvision>>; } export class ConsentProvisionActor extends BackboneElement { @Default('fhir.datatypes.Consent.ConsentProvisionActor') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public role: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public reference: FlatConvectorModel<Reference>; //Device|Group|CareTeam|Organization|Patient|Practitioner|RelatedPerson|PractitionerRole } export class ConsentProvisionData extends BackboneElement { @Default('fhir.datatypes.Consent.ConsentProvisionData') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public meaning: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public reference: FlatConvectorModel<Reference>; //Any } export class Consent extends DomainResource<Consent> { @Default('fhir.datatypes.Consent') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public scope: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public patient?: FlatConvectorModel<Reference>; //Patient @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public dateTime?: date; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public performer?: Array<FlatConvectorModel<Reference>>; //Organization|Patient|Practitioner|RelatedPerson|PractitionerRole @Validate(yup.lazy(() => yup.array(Reference.schema()))) public organization?: Array<FlatConvectorModel<Reference>>; //Organization // @Validate(yup.lazy(() => Attachment.schema())) public sourceAttachment?: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => Reference.schema())) public sourceReference?: FlatConvectorModel<Reference>; //Consent|DocumentReference|Contract|QuestionnaireResponse @Validate(yup.lazy(() => yup.array(ConsentPolicy.schema()))) public policy?: Array<FlatConvectorModel<ConsentPolicy>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public policyRule?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(ConsentVerification.schema()))) public verification?: Array<FlatConvectorModel<ConsentVerification>>; @Validate(yup.lazy(() => ConsentProvision.schema())) public provision?: FlatConvectorModel<ConsentProvision>; } export class ContactDetail extends DomainResource<ContactDetail> { @Default('fhir.datatypes.ContactDetail') @ReadOnly() public readonly type: string; @Validate(yup.string()) public name?: string; @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; } export class ContractContentDefinition extends BackboneElement { @Default('fhir.datatypes.Contract.ContractContentDefinition') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public subType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public publisher?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public publicationDate?: date; @Required() @Validate(yup.string()) public publicationStatus: string; @Validate(yup.string()) public copyright?: string; } export class ContractTerm extends BackboneElement { @Default('fhir.datatypes.Contract.ContractTerm') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public issued?: date; @Validate(yup.lazy(() => Period.schema())) public applies?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => CodeableConcept.schema())) public topicCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public topicReference?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public subType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public text?: string; @Validate(yup.lazy(() => yup.array(ContractTermSecurityLabel.schema()))) public securityLabel?: Array<FlatConvectorModel<ContractTermSecurityLabel>>; @Required() @Validate(yup.lazy(() => ContractTermOffer.schema())) public offer: FlatConvectorModel<ContractTermOffer>; @Validate(yup.lazy(() => yup.array(ContractTermAsset.schema()))) public asset?: Array<FlatConvectorModel<ContractTermAsset>>; @Validate(yup.lazy(() => yup.array(ContractTermAction.schema()))) public action?: Array<FlatConvectorModel<ContractTermAction>>; @Validate(yup.lazy(() => yup.array(ContractTerm.schema()))) public group?: Array<FlatConvectorModel<ContractTerm>>; } export class ContractTermSecurityLabel extends BackboneElement { @Default('fhir.datatypes.Contract.ContractTermSecurityLabel') @ReadOnly() public readonly type: string; @Validate(yup.array(yup.number())) public number? : Array<number>; @Required() @Validate(yup.lazy(() => Coding.schema())) public classification: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public category?: Array<FlatConvectorModel<Coding>>; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public control?: Array<FlatConvectorModel<Coding>>; } export class ContractTermOffer extends BackboneElement { @Default('fhir.datatypes.Contract.ContractTermOffer') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(ContractTermOfferParty.schema()))) public party?: Array<FlatConvectorModel<ContractTermOfferParty>>; @Validate(yup.lazy(() => Reference.schema())) public topic?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public decision?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public decisionMode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContractTermOfferAnswer.schema()))) public answer?: Array<FlatConvectorModel<ContractTermOfferAnswer>>; @Validate(yup.string()) public text?: string; @Validate(yup.array(yup.string())) public linkId? : Array<string>; @Validate(yup.array(yup.number())) public securityLabelNumber? : Array<number>; } export class ContractTermOfferParty extends BackboneElement { @Default('fhir.datatypes.Contract.ContractTermOfferParty') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reference?: Array<FlatConvectorModel<Reference>>; //Patient|RelatedPerson|Practitioner|PractitionerRole|Device|Group|Organization @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public role: FlatConvectorModel<CodeableConcept>; } export class ContractTermOfferAnswer extends BackboneElement { @Default('fhir.datatypes.Contract.ContractTermOfferAnswer') @ReadOnly() public readonly type: string; @Required() @Validate(yup.boolean()) public valueBoolean: boolean; @Required() @Validate(yup.number()) public valueDecimal: number; @Required() @Validate(yup.number()) public valueInteger: number; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDate: date; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDateTime: date; @Required() @Validate(yup.string()) public valueTime: string; @Required() @Validate(yup.string()) public valueString: string; @Required() @Validate(yup.string()) public valueUri: string; // @Required() @Validate(yup.lazy(() => Attachment.schema())) public valueAttachment: FlatConvectorModel<Attachment>; @Required() @Validate(yup.lazy(() => Coding.schema())) public valueCoding: FlatConvectorModel<Coding>; @Required() @Validate(yup.lazy(() => Quantity.schema())) public valueQuantity: FlatConvectorModel<Quantity>; @Required() @Validate(yup.lazy(() => Reference.schema())) public valueReference: FlatConvectorModel<Reference>; //Any } export class ContractTermAsset extends BackboneElement { @Default('fhir.datatypes.Contract.ContractTermAsset') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public scope?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public typeReference?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public subtype?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Coding.schema())) public relationship?: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => yup.array(ContractTermAssetContext.schema()))) public context?: Array<FlatConvectorModel<ContractTermAssetContext>>; @Validate(yup.string()) public condition?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public periodType?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Period.schema()))) public period?: Array<FlatConvectorModel<Period>>; @Validate(yup.lazy(() => yup.array(Period.schema()))) public usePeriod?: Array<FlatConvectorModel<Period>>; @Validate(yup.string()) public text?: string; @Validate(yup.array(yup.string())) public linkId? : Array<string>; @Validate(yup.lazy(() => yup.array(ContractTermOfferAnswer.schema()))) public answer?: Array<FlatConvectorModel<ContractTermOfferAnswer>>; @Validate(yup.array(yup.number())) public securityLabelNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ContractTermAssetValuedItem.schema()))) public valuedItem?: Array<FlatConvectorModel<ContractTermAssetValuedItem>>; } export class ContractTermAssetContext extends BackboneElement { @Default('fhir.datatypes.Contract.ContractTermAssetContext') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Reference.schema())) public reference?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public code?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public text?: string; } export class ContractTermAssetValuedItem extends BackboneElement { @Default('fhir.datatypes.Contract.ContractTermAssetValuedItem') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public entityCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public entityReference?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public effectiveTime?: date; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.number()) public points?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.string()) public payment?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public paymentDate?: date; @Validate(yup.lazy(() => Reference.schema())) public responsible?: FlatConvectorModel<Reference>; //Organization|Patient|Practitioner|PractitionerRole|RelatedPerson @Validate(yup.lazy(() => Reference.schema())) public recipient?: FlatConvectorModel<Reference>; //Organization|Patient|Practitioner|PractitionerRole|RelatedPerson @Validate(yup.array(yup.string())) public linkId? : Array<string>; @Validate(yup.array(yup.number())) public securityLabelNumber? : Array<number>; } export class ContractTermAction extends BackboneElement { @Default('fhir.datatypes.Contract.ContractTermAction') @ReadOnly() public readonly type: string; @Validate(yup.boolean()) public doNotPerform?: boolean; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(ContractTermActionSubject.schema()))) public subject?: Array<FlatConvectorModel<ContractTermActionSubject>>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public intent: FlatConvectorModel<CodeableConcept>; @Validate(yup.array(yup.string())) public linkId? : Array<string>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public status: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public context?: FlatConvectorModel<Reference>; //Encounter|EpisodeOfCare @Validate(yup.array(yup.string())) public contextLinkId? : Array<string>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public occurrenceDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public occurrencePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Timing.schema())) public occurrenceTiming?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public requester?: Array<FlatConvectorModel<Reference>>; //Patient|RelatedPerson|Practitioner|PractitionerRole|Device|Group|Organization @Validate(yup.array(yup.string())) public requesterLinkId? : Array<string>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public performerType?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public performerRole?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public performer?: FlatConvectorModel<Reference>; //RelatedPerson|Patient|Practitioner|PractitionerRole|CareTeam|Device|Substance|Organization|Location @Validate(yup.array(yup.string())) public performerLinkId? : Array<string>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport|DocumentReference|Questionnaire|QuestionnaireResponse @Validate(yup.array(yup.string())) public reason? : Array<string>; @Validate(yup.array(yup.string())) public reasonLinkId? : Array<string>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.array(yup.number())) public securityLabelNumber? : Array<number>; } export class ContractTermActionSubject extends BackboneElement { @Default('fhir.datatypes.Contract.ContractTermActionSubject') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reference?: Array<FlatConvectorModel<Reference>>; //Patient|RelatedPerson|Practitioner|PractitionerRole|Device|Group|Organization @Validate(yup.lazy(() => CodeableConcept.schema())) public role?: FlatConvectorModel<CodeableConcept>; } export class ContractSigner extends BackboneElement { @Default('fhir.datatypes.Contract.ContractSigner') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Coding.schema())) public type_: FlatConvectorModel<Coding>; @Required() @Validate(yup.lazy(() => Reference.schema())) public party: FlatConvectorModel<Reference>; //Organization|Patient|Practitioner|PractitionerRole|RelatedPerson @Validate(yup.lazy(() => yup.array(Signature.schema()))) public signature?: Array<FlatConvectorModel<Signature>>; } export class ContractFriendly extends BackboneElement { @Default('fhir.datatypes.Contract.ContractFriendly') @ReadOnly() public readonly type: string; // @Required() @Validate(yup.lazy(() => Attachment.schema())) public contentAttachment: FlatConvectorModel<Attachment>; @Required() @Validate(yup.lazy(() => Reference.schema())) public contentReference: FlatConvectorModel<Reference>; //Composition|DocumentReference|QuestionnaireResponse } export class ContractLegal extends BackboneElement { @Default('fhir.datatypes.Contract.ContractLegal') @ReadOnly() public readonly type: string; // @Required() @Validate(yup.lazy(() => Attachment.schema())) public contentAttachment: FlatConvectorModel<Attachment>; @Required() @Validate(yup.lazy(() => Reference.schema())) public contentReference: FlatConvectorModel<Reference>; //Composition|DocumentReference|QuestionnaireResponse } export class ContractRule extends BackboneElement { @Default('fhir.datatypes.Contract.ContractRule') @ReadOnly() public readonly type: string; // @Required() @Validate(yup.lazy(() => Attachment.schema())) public contentAttachment: FlatConvectorModel<Attachment>; @Required() @Validate(yup.lazy(() => Reference.schema())) public contentReference: FlatConvectorModel<Reference>; //DocumentReference } export class Contract extends DomainResource<Contract> { @Default('fhir.datatypes.Contract') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public url?: string; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public legalState?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public instantiatesCanonical?: FlatConvectorModel<Reference>; //Contract @Validate(yup.string()) public instantiatesUri?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public contentDerivative?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public issued?: date; @Validate(yup.lazy(() => Period.schema())) public applies?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => CodeableConcept.schema())) public expirationType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public subject?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(Reference.schema()))) public authority?: Array<FlatConvectorModel<Reference>>; //Organization @Validate(yup.lazy(() => yup.array(Reference.schema()))) public domain?: Array<FlatConvectorModel<Reference>>; //Location @Validate(yup.lazy(() => yup.array(Reference.schema()))) public site?: Array<FlatConvectorModel<Reference>>; //Location @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public subtitle?: string; @Validate(yup.array(yup.string())) public alias? : Array<string>; @Validate(yup.lazy(() => Reference.schema())) public author?: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => CodeableConcept.schema())) public scope?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public topicCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public topicReference?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public subType?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => ContractContentDefinition.schema())) public contentDefinition?: FlatConvectorModel<ContractContentDefinition>; @Validate(yup.lazy(() => yup.array(ContractTerm.schema()))) public term?: Array<FlatConvectorModel<ContractTerm>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supportingInfo?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(Reference.schema()))) public relevantHistory?: Array<FlatConvectorModel<Reference>>; //Provenance @Validate(yup.lazy(() => yup.array(ContractSigner.schema()))) public signer?: Array<FlatConvectorModel<ContractSigner>>; @Validate(yup.lazy(() => yup.array(ContractFriendly.schema()))) public friendly?: Array<FlatConvectorModel<ContractFriendly>>; @Validate(yup.lazy(() => yup.array(ContractLegal.schema()))) public legal?: Array<FlatConvectorModel<ContractLegal>>; @Validate(yup.lazy(() => yup.array(ContractRule.schema()))) public rule?: Array<FlatConvectorModel<ContractRule>>; // @Validate(yup.lazy(() => Attachment.schema())) public legallyBindingAttachment?: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => Reference.schema())) public legallyBindingReference?: FlatConvectorModel<Reference>; //Composition|DocumentReference|QuestionnaireResponse|Contract } export class Contributor extends DomainResource<Contributor> { @Default('fhir.datatypes.Contributor') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; } export class Count extends DomainResource<Count> { @Default('fhir.datatypes.Count') @ReadOnly() public readonly type: string; } export class CoverageClass extends BackboneElement { @Default('fhir.datatypes.Coverage.CoverageClass') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string()) public value: string; @Validate(yup.string()) public name?: string; } export class CoverageCostToBeneficiary extends BackboneElement { @Default('fhir.datatypes.Coverage.CoverageCostToBeneficiary') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => SimpleQuantity.schema())) public valueQuantity: FlatConvectorModel<SimpleQuantity>; @Required() @Validate(yup.lazy(() => Money.schema())) public valueMoney: FlatConvectorModel<Money>; @Validate(yup.lazy(() => yup.array(CoverageCostToBeneficiaryException.schema()))) public exception?: Array<FlatConvectorModel<CoverageCostToBeneficiaryException>>; } export class CoverageCostToBeneficiaryException extends BackboneElement { @Default('fhir.datatypes.Coverage.CoverageCostToBeneficiaryException') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; } export class Coverage extends DomainResource<Coverage> { @Default('fhir.datatypes.Coverage') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public policyHolder?: FlatConvectorModel<Reference>; //Patient|RelatedPerson|Organization @Validate(yup.lazy(() => Reference.schema())) public subscriber?: FlatConvectorModel<Reference>; //Patient|RelatedPerson @Validate(yup.string()) public subscriberId?: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public beneficiary: FlatConvectorModel<Reference>; //Patient @Validate(yup.string()) public dependent?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public relationship?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public payor?: Array<FlatConvectorModel<Reference>>; //Organization|Patient|RelatedPerson @Validate(yup.lazy(() => yup.array(CoverageClass.schema()))) public class_?: Array<FlatConvectorModel<CoverageClass>>; @Validate(yup.number()) public order?: number; @Validate(yup.string()) public network?: string; @Validate(yup.lazy(() => yup.array(CoverageCostToBeneficiary.schema()))) public costToBeneficiary?: Array<FlatConvectorModel<CoverageCostToBeneficiary>>; @Validate(yup.boolean()) public subrogation?: boolean; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public contract?: Array<FlatConvectorModel<Reference>>; //Contract } export class CoverageEligibilityRequestSupportingInfo extends BackboneElement { @Default('fhir.datatypes.CoverageEligibilityRequest.CoverageEligibilityRequestSupportingInfo') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Required() @Validate(yup.lazy(() => Reference.schema())) public information: FlatConvectorModel<Reference>; //Any @Validate(yup.boolean()) public appliesToAll?: boolean; } export class CoverageEligibilityRequestInsurance extends BackboneElement { @Default('fhir.datatypes.CoverageEligibilityRequest.CoverageEligibilityRequestInsurance') @ReadOnly() public readonly type: string; @Validate(yup.boolean()) public focal?: boolean; @Required() @Validate(yup.lazy(() => Reference.schema())) public coverage: FlatConvectorModel<Reference>; //Coverage @Validate(yup.string()) public businessArrangement?: string; } export class CoverageEligibilityRequestItem extends BackboneElement { @Default('fhir.datatypes.CoverageEligibilityRequest.CoverageEligibilityRequestItem') @ReadOnly() public readonly type: string; @Validate(yup.array(yup.number())) public supportingInfoSequence? : Array<number>; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public provider?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => Reference.schema())) public facility?: FlatConvectorModel<Reference>; //Location|Organization @Validate(yup.lazy(() => yup.array(CoverageEligibilityRequestItemDiagnosis.schema()))) public diagnosis?: Array<FlatConvectorModel<CoverageEligibilityRequestItemDiagnosis>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public detail?: Array<FlatConvectorModel<Reference>>; //Any } export class CoverageEligibilityRequestItemDiagnosis extends BackboneElement { @Default('fhir.datatypes.CoverageEligibilityRequest.CoverageEligibilityRequestItemDiagnosis') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public diagnosisCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public diagnosisReference?: FlatConvectorModel<Reference>; //Condition } export class CoverageEligibilityRequest extends DomainResource<CoverageEligibilityRequest> { @Default('fhir.datatypes.CoverageEligibilityRequest') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public priority?: FlatConvectorModel<CodeableConcept>; @Validate(yup.array(yup.string())) public purpose? : Array<string>; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public servicedDate?: date; @Validate(yup.lazy(() => Period.schema())) public servicedPeriod?: FlatConvectorModel<Period>; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created: date; @Validate(yup.lazy(() => Reference.schema())) public enterer?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => Reference.schema())) public provider?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Required() @Validate(yup.lazy(() => Reference.schema())) public insurer: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public facility?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => yup.array(CoverageEligibilityRequestSupportingInfo.schema()))) public supportingInfo?: Array<FlatConvectorModel<CoverageEligibilityRequestSupportingInfo>>; @Validate(yup.lazy(() => yup.array(CoverageEligibilityRequestInsurance.schema()))) public insurance?: Array<FlatConvectorModel<CoverageEligibilityRequestInsurance>>; @Validate(yup.lazy(() => yup.array(CoverageEligibilityRequestItem.schema()))) public item?: Array<FlatConvectorModel<CoverageEligibilityRequestItem>>; } export class CoverageEligibilityResponseInsurance extends BackboneElement { @Default('fhir.datatypes.CoverageEligibilityResponse.CoverageEligibilityResponseInsurance') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public coverage: FlatConvectorModel<Reference>; //Coverage @Validate(yup.boolean()) public inforce?: boolean; @Validate(yup.lazy(() => Period.schema())) public benefitPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CoverageEligibilityResponseInsuranceItem.schema()))) public item?: Array<FlatConvectorModel<CoverageEligibilityResponseInsuranceItem>>; } export class CoverageEligibilityResponseInsuranceItem extends BackboneElement { @Default('fhir.datatypes.CoverageEligibilityResponse.CoverageEligibilityResponseInsuranceItem') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public provider?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.boolean()) public excluded?: boolean; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public network?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public unit?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public term?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CoverageEligibilityResponseInsuranceItemBenefit.schema()))) public benefit?: Array<FlatConvectorModel<CoverageEligibilityResponseInsuranceItemBenefit>>; @Validate(yup.boolean()) public authorizationRequired?: boolean; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public authorizationSupporting?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public authorizationUrl?: string; } export class CoverageEligibilityResponseInsuranceItemBenefit extends BackboneElement { @Default('fhir.datatypes.CoverageEligibilityResponse.CoverageEligibilityResponseInsuranceItemBenefit') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public allowedUnsignedInt?: number; @Validate(yup.string()) public allowedString?: string; @Validate(yup.lazy(() => Money.schema())) public allowedMoney?: FlatConvectorModel<Money>; @Validate(yup.number()) public usedUnsignedInt?: number; @Validate(yup.string()) public usedString?: string; @Validate(yup.lazy(() => Money.schema())) public usedMoney?: FlatConvectorModel<Money>; } export class CoverageEligibilityResponseError extends BackboneElement { @Default('fhir.datatypes.CoverageEligibilityResponse.CoverageEligibilityResponseError') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; } export class CoverageEligibilityResponse extends DomainResource<CoverageEligibilityResponse> { @Default('fhir.datatypes.CoverageEligibilityResponse') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.array(yup.string())) public purpose? : Array<string>; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public servicedDate?: date; @Validate(yup.lazy(() => Period.schema())) public servicedPeriod?: FlatConvectorModel<Period>; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created: date; @Validate(yup.lazy(() => Reference.schema())) public requestor?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Required() @Validate(yup.lazy(() => Reference.schema())) public request: FlatConvectorModel<Reference>; //CoverageEligibilityRequest @Required() @Validate(yup.string()) public outcome: string; @Validate(yup.string()) public disposition?: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public insurer: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(CoverageEligibilityResponseInsurance.schema()))) public insurance?: Array<FlatConvectorModel<CoverageEligibilityResponseInsurance>>; @Validate(yup.string()) public preAuthRef?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public form?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CoverageEligibilityResponseError.schema()))) public error?: Array<FlatConvectorModel<CoverageEligibilityResponseError>>; } export class DataRequirementCodeFilter extends BackboneElement { @Default('fhir.datatypes.DataRequirement.DataRequirementCodeFilter') @ReadOnly() public readonly type: string; @Validate(yup.string()) public path?: string; @Validate(yup.string()) public searchParam?: string; @Validate(yup.string()) public valueSet?: string; //ValueSet @Validate(yup.lazy(() => yup.array(Coding.schema()))) public code?: Array<FlatConvectorModel<Coding>>; } export class DataRequirementDateFilter extends BackboneElement { @Default('fhir.datatypes.DataRequirement.DataRequirementDateFilter') @ReadOnly() public readonly type: string; @Validate(yup.string()) public path?: string; @Validate(yup.string()) public searchParam?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public valuePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Duration.schema())) public valueDuration?: FlatConvectorModel<Duration>; } export class DataRequirementSort extends BackboneElement { @Default('fhir.datatypes.DataRequirement.DataRequirementSort') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public path: string; @Required() @Validate(yup.string()) public direction: string; } export class DataRequirement extends DomainResource<DataRequirement> { @Default('fhir.datatypes.DataRequirement') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.array(yup.string())) public profile? : Array<string>; //StructureDefinition @Validate(yup.lazy(() => CodeableConcept.schema())) public subjectCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subjectReference?: FlatConvectorModel<Reference>; //Group @Validate(yup.array(yup.string())) public mustSupport? : Array<string>; @Validate(yup.lazy(() => yup.array(DataRequirementCodeFilter.schema()))) public codeFilter?: Array<FlatConvectorModel<DataRequirementCodeFilter>>; @Validate(yup.lazy(() => yup.array(DataRequirementDateFilter.schema()))) public dateFilter?: Array<FlatConvectorModel<DataRequirementDateFilter>>; @Validate(yup.number()) public limit?: number; @Validate(yup.lazy(() => yup.array(DataRequirementSort.schema()))) public sort?: Array<FlatConvectorModel<DataRequirementSort>>; } export class DetectedIssueEvidence extends BackboneElement { @Default('fhir.datatypes.DetectedIssue.DetectedIssueEvidence') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public code?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public detail?: Array<FlatConvectorModel<Reference>>; //Any } export class DetectedIssueMitigation extends BackboneElement { @Default('fhir.datatypes.DetectedIssue.DetectedIssueMitigation') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public action: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.lazy(() => Reference.schema())) public author?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole } export class DetectedIssue extends DomainResource<DetectedIssue> { @Default('fhir.datatypes.DetectedIssue') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public severity?: string; @Validate(yup.lazy(() => Reference.schema())) public patient?: FlatConvectorModel<Reference>; //Patient @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public identifiedDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public identifiedPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Reference.schema())) public author?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Device @Validate(yup.lazy(() => yup.array(Reference.schema()))) public implicated?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(DetectedIssueEvidence.schema()))) public evidence?: Array<FlatConvectorModel<DetectedIssueEvidence>>; @Validate(yup.string()) public detail?: string; @Validate(yup.string()) public reference?: string; @Validate(yup.lazy(() => yup.array(DetectedIssueMitigation.schema()))) public mitigation?: Array<FlatConvectorModel<DetectedIssueMitigation>>; } export class DeviceUdiCarrier extends BackboneElement { @Default('fhir.datatypes.Device.DeviceUdiCarrier') @ReadOnly() public readonly type: string; @Validate(yup.string()) public deviceIdentifier?: string; @Validate(yup.string()) public issuer?: string; @Validate(yup.string()) public jurisdiction?: string; @Validate(yup.string()) public carrierAIDC?: string; @Validate(yup.string()) public carrierHRF?: string; @Validate(yup.string()) public entryType?: string; } export class DeviceDeviceName extends BackboneElement { @Default('fhir.datatypes.Device.DeviceDeviceName') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Required() @Validate(yup.string()) public type_: string; } export class DeviceSpecialization extends BackboneElement { @Default('fhir.datatypes.Device.DeviceSpecialization') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public systemType: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public version?: string; } export class DeviceVersion extends BackboneElement { @Default('fhir.datatypes.Device.DeviceVersion') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Identifier.schema())) public component?: FlatConvectorModel<Identifier>; @Required() @Validate(yup.string()) public value: string; } export class DeviceProperty extends BackboneElement { @Default('fhir.datatypes.Device.DeviceProperty') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Quantity.schema()))) public valueQuantity?: Array<FlatConvectorModel<Quantity>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public valueCode?: Array<FlatConvectorModel<CodeableConcept>>; } export class Device extends DomainResource<Device> { @Default('fhir.datatypes.Device') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => Reference.schema())) public definition?: FlatConvectorModel<Reference>; //DeviceDefinition @Validate(yup.lazy(() => yup.array(DeviceUdiCarrier.schema()))) public udiCarrier?: Array<FlatConvectorModel<DeviceUdiCarrier>>; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public statusReason?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public distinctIdentifier?: string; @Validate(yup.string()) public manufacturer?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public manufactureDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public expirationDate?: date; @Validate(yup.string()) public lotNumber?: string; @Validate(yup.string()) public serialNumber?: string; @Validate(yup.lazy(() => yup.array(DeviceDeviceName.schema()))) public deviceName?: Array<FlatConvectorModel<DeviceDeviceName>>; @Validate(yup.string()) public modelNumber?: string; @Validate(yup.string()) public partNumber?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(DeviceSpecialization.schema()))) public specialization?: Array<FlatConvectorModel<DeviceSpecialization>>; @Validate(yup.lazy(() => yup.array(DeviceVersion.schema()))) public version?: Array<FlatConvectorModel<DeviceVersion>>; @Validate(yup.lazy(() => yup.array(DeviceProperty.schema()))) public property?: Array<FlatConvectorModel<DeviceProperty>>; @Validate(yup.lazy(() => Reference.schema())) public patient?: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => Reference.schema())) public owner?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public contact?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.lazy(() => Reference.schema())) public location?: FlatConvectorModel<Reference>; //Location @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public safety?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public parent?: FlatConvectorModel<Reference>; //Device } export class DeviceDefinitionUdiDeviceIdentifier extends BackboneElement { @Default('fhir.datatypes.DeviceDefinition.DeviceDefinitionUdiDeviceIdentifier') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public deviceIdentifier: string; @Required() @Validate(yup.string()) public issuer: string; @Required() @Validate(yup.string()) public jurisdiction: string; } export class DeviceDefinitionDeviceName extends BackboneElement { @Default('fhir.datatypes.DeviceDefinition.DeviceDefinitionDeviceName') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Required() @Validate(yup.string()) public type_: string; } export class DeviceDefinitionSpecialization extends BackboneElement { @Default('fhir.datatypes.DeviceDefinition.DeviceDefinitionSpecialization') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public systemType: string; @Validate(yup.string()) public version?: string; } export class DeviceDefinitionCapability extends BackboneElement { @Default('fhir.datatypes.DeviceDefinition.DeviceDefinitionCapability') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public description?: Array<FlatConvectorModel<CodeableConcept>>; } export class DeviceDefinitionProperty extends BackboneElement { @Default('fhir.datatypes.DeviceDefinition.DeviceDefinitionProperty') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Quantity.schema()))) public valueQuantity?: Array<FlatConvectorModel<Quantity>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public valueCode?: Array<FlatConvectorModel<CodeableConcept>>; } export class DeviceDefinitionMaterial extends BackboneElement { @Default('fhir.datatypes.DeviceDefinition.DeviceDefinitionMaterial') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public substance: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public alternate?: boolean; @Validate(yup.boolean()) public allergenicIndicator?: boolean; } export class DeviceDefinition extends DomainResource<DeviceDefinition> { @Default('fhir.datatypes.DeviceDefinition') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(DeviceDefinitionUdiDeviceIdentifier.schema()))) public udiDeviceIdentifier?: Array<FlatConvectorModel<DeviceDefinitionUdiDeviceIdentifier>>; @Validate(yup.string()) public manufacturerString?: string; @Validate(yup.lazy(() => Reference.schema())) public manufacturerReference?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(DeviceDefinitionDeviceName.schema()))) public deviceName?: Array<FlatConvectorModel<DeviceDefinitionDeviceName>>; @Validate(yup.string()) public modelNumber?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(DeviceDefinitionSpecialization.schema()))) public specialization?: Array<FlatConvectorModel<DeviceDefinitionSpecialization>>; @Validate(yup.array(yup.string())) public version? : Array<string>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public safety?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ProductShelfLife.schema()))) public shelfLifeStorage?: Array<FlatConvectorModel<ProductShelfLife>>; @Validate(yup.lazy(() => ProdCharacteristic.schema())) public physicalCharacteristics?: FlatConvectorModel<ProdCharacteristic>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public languageCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(DeviceDefinitionCapability.schema()))) public capability?: Array<FlatConvectorModel<DeviceDefinitionCapability>>; @Validate(yup.lazy(() => yup.array(DeviceDefinitionProperty.schema()))) public property?: Array<FlatConvectorModel<DeviceDefinitionProperty>>; @Validate(yup.lazy(() => Reference.schema())) public owner?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public contact?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.string()) public url?: string; @Validate(yup.string()) public onlineInformation?: string; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => Quantity.schema())) public quantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Reference.schema())) public parentDevice?: FlatConvectorModel<Reference>; //DeviceDefinition @Validate(yup.lazy(() => yup.array(DeviceDefinitionMaterial.schema()))) public material?: Array<FlatConvectorModel<DeviceDefinitionMaterial>>; } export class DeviceMetricCalibration extends BackboneElement { @Default('fhir.datatypes.DeviceMetric.DeviceMetricCalibration') @ReadOnly() public readonly type: string; @Validate(yup.string()) public type_?: string; @Validate(yup.string()) public state?: string; @Validate(yup.string()) public time?: string; } export class DeviceMetric extends DomainResource<DeviceMetric> { @Default('fhir.datatypes.DeviceMetric') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public unit?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public source?: FlatConvectorModel<Reference>; //Device @Validate(yup.lazy(() => Reference.schema())) public parent?: FlatConvectorModel<Reference>; //Device @Validate(yup.string()) public operationalStatus?: string; @Validate(yup.string()) public color?: string; @Required() @Validate(yup.string()) public category: string; @Validate(yup.lazy(() => Timing.schema())) public measurementPeriod?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => yup.array(DeviceMetricCalibration.schema()))) public calibration?: Array<FlatConvectorModel<DeviceMetricCalibration>>; } export class DeviceRequestParameter extends BackboneElement { @Default('fhir.datatypes.DeviceRequest.DeviceRequestParameter') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public valueCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Quantity.schema())) public valueQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Range.schema())) public valueRange?: FlatConvectorModel<Range>; @Validate(yup.boolean()) public valueBoolean?: boolean; } export class DeviceRequest extends DomainResource<DeviceRequest> { @Default('fhir.datatypes.DeviceRequest') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.array(yup.string())) public instantiatesCanonical? : Array<string>; //ActivityDefinition|PlanDefinition @Validate(yup.array(yup.string())) public instantiatesUri? : Array<string>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(Reference.schema()))) public priorRequest?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => Identifier.schema())) public groupIdentifier?: FlatConvectorModel<Identifier>; @Validate(yup.string()) public status?: string; @Required() @Validate(yup.string()) public intent: string; @Validate(yup.string()) public priority?: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public codeReference: FlatConvectorModel<Reference>; //Device @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public codeCodeableConcept: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(DeviceRequestParameter.schema()))) public parameter?: Array<FlatConvectorModel<DeviceRequestParameter>>; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group|Location|Device @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public occurrenceDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public occurrencePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Timing.schema())) public occurrenceTiming?: FlatConvectorModel<Timing>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public authoredOn?: date; @Validate(yup.lazy(() => Reference.schema())) public requester?: FlatConvectorModel<Reference>; //Device|Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => CodeableConcept.schema())) public performerType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public performer?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|CareTeam|HealthcareService|Patient|Device|RelatedPerson @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport|DocumentReference @Validate(yup.lazy(() => yup.array(Reference.schema()))) public insurance?: Array<FlatConvectorModel<Reference>>; //Coverage|ClaimResponse @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supportingInfo?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public relevantHistory?: Array<FlatConvectorModel<Reference>>; //Provenance } export class DeviceUseStatement extends DomainResource<DeviceUseStatement> { @Default('fhir.datatypes.DeviceUseStatement') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //ServiceRequest @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => yup.array(Reference.schema()))) public derivedFrom?: Array<FlatConvectorModel<Reference>>; //ServiceRequest|Procedure|Claim|Observation|QuestionnaireResponse|DocumentReference @Validate(yup.lazy(() => Timing.schema())) public timingTiming?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => Period.schema())) public timingPeriod?: FlatConvectorModel<Period>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public timingDateTime?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public recordedOn?: date; @Validate(yup.lazy(() => Reference.schema())) public source?: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|RelatedPerson @Required() @Validate(yup.lazy(() => Reference.schema())) public device: FlatConvectorModel<Reference>; //Device @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport|DocumentReference|Media @Validate(yup.lazy(() => CodeableConcept.schema())) public bodySite?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class DiagnosticReportMedia extends BackboneElement { @Default('fhir.datatypes.DiagnosticReport.DiagnosticReportMedia') @ReadOnly() public readonly type: string; @Validate(yup.string()) public comment?: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public link: FlatConvectorModel<Reference>; //Media } export class DiagnosticReport extends DomainResource<DiagnosticReport> { @Default('fhir.datatypes.DiagnosticReport') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //CarePlan|ImmunizationRecommendation|MedicationRequest|NutritionOrder|ServiceRequest @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Group|Device|Location @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public effectiveDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.string()) public issued?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public performer?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole|Organization|CareTeam @Validate(yup.lazy(() => yup.array(Reference.schema()))) public resultsInterpreter?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole|Organization|CareTeam @Validate(yup.lazy(() => yup.array(Reference.schema()))) public specimen?: Array<FlatConvectorModel<Reference>>; //Specimen @Validate(yup.lazy(() => yup.array(Reference.schema()))) public result?: Array<FlatConvectorModel<Reference>>; //Observation @Validate(yup.lazy(() => yup.array(Reference.schema()))) public imagingStudy?: Array<FlatConvectorModel<Reference>>; //ImagingStudy @Validate(yup.lazy(() => yup.array(DiagnosticReportMedia.schema()))) public media?: Array<FlatConvectorModel<DiagnosticReportMedia>>; @Validate(yup.string()) public conclusion?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public conclusionCode?: Array<FlatConvectorModel<CodeableConcept>>; // @Validate(yup.lazy(() => yup.array(Attachment.schema()))) public presentedForm?: Array<FlatConvectorModel<Attachment>>; } export class Distance extends DomainResource<Distance> { @Default('fhir.datatypes.Distance') @ReadOnly() public readonly type: string; } export class DocumentManifestRelated extends BackboneElement { @Default('fhir.datatypes.DocumentManifest.DocumentManifestRelated') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => Reference.schema())) public ref?: FlatConvectorModel<Reference>; //Any } export class DocumentManifest extends DomainResource<DocumentManifest> { @Default('fhir.datatypes.DocumentManifest') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public masterIdentifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Practitioner|Group|Device @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created?: date; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public author?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole|Organization|Device|Patient|RelatedPerson @Validate(yup.lazy(() => yup.array(Reference.schema()))) public recipient?: Array<FlatConvectorModel<Reference>>; //Patient|Practitioner|PractitionerRole|RelatedPerson|Organization @Validate(yup.string()) public source?: string; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public content?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(DocumentManifestRelated.schema()))) public related?: Array<FlatConvectorModel<DocumentManifestRelated>>; } export class DocumentReferenceRelatesTo extends BackboneElement { @Default('fhir.datatypes.DocumentReference.DocumentReferenceRelatesTo') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public target: FlatConvectorModel<Reference>; //DocumentReference } export class DocumentReferenceContent extends BackboneElement { @Default('fhir.datatypes.DocumentReference.DocumentReferenceContent') @ReadOnly() public readonly type: string; // @Required() @Validate(yup.lazy(() => Attachment.schema())) public attachment: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => Coding.schema())) public format?: FlatConvectorModel<Coding>; } export class DocumentReferenceContext extends BackboneElement { @Default('fhir.datatypes.DocumentReference.DocumentReferenceContext') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public encounter?: Array<FlatConvectorModel<Reference>>; //Encounter|EpisodeOfCare @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public event?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => CodeableConcept.schema())) public facilityType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public practiceSetting?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public sourcePatientInfo?: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => yup.array(Reference.schema()))) public related?: Array<FlatConvectorModel<Reference>>; //Any } export class DocumentReference extends DomainResource<DocumentReference> { @Default('fhir.datatypes.DocumentReference') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public masterIdentifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.string()) public docStatus?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Practitioner|Group|Device @Validate(yup.string()) public date?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public author?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole|Organization|Device|Patient|RelatedPerson @Validate(yup.lazy(() => Reference.schema())) public authenticator?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => Reference.schema())) public custodian?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(DocumentReferenceRelatesTo.schema()))) public relatesTo?: Array<FlatConvectorModel<DocumentReferenceRelatesTo>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public securityLabel?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(DocumentReferenceContent.schema()))) public content?: Array<FlatConvectorModel<DocumentReferenceContent>>; @Validate(yup.lazy(() => DocumentReferenceContext.schema())) public context?: FlatConvectorModel<DocumentReferenceContext>; } export class DosageDoseAndRate extends BackboneElement { @Default('fhir.datatypes.Dosage.DosageDoseAndRate') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Range.schema())) public doseRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public doseQuantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Ratio.schema())) public rateRatio?: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => Range.schema())) public rateRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public rateQuantity?: FlatConvectorModel<SimpleQuantity>; } export class EffectEvidenceSynthesisSampleSize extends BackboneElement { @Default('fhir.datatypes.EffectEvidenceSynthesis.EffectEvidenceSynthesisSampleSize') @ReadOnly() public readonly type: string; @Validate(yup.string()) public description?: string; @Validate(yup.number()) public numberOfStudies?: number; @Validate(yup.number()) public numberOfParticipants?: number; } export class EffectEvidenceSynthesisResultsByExposure extends BackboneElement { @Default('fhir.datatypes.EffectEvidenceSynthesis.EffectEvidenceSynthesisResultsByExposure') @ReadOnly() public readonly type: string; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public exposureState?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public variantState?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public riskEvidenceSynthesis: FlatConvectorModel<Reference>; //RiskEvidenceSynthesis } export class EffectEvidenceSynthesisEffectEstimate extends BackboneElement { @Default('fhir.datatypes.EffectEvidenceSynthesis.EffectEvidenceSynthesisEffectEstimate') @ReadOnly() public readonly type: string; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public variantState?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public value?: number; @Validate(yup.lazy(() => CodeableConcept.schema())) public unitOfMeasure?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(EffectEvidenceSynthesisEffectEstimatePrecisionEstimate.schema()))) public precisionEstimate?: Array<FlatConvectorModel<EffectEvidenceSynthesisEffectEstimatePrecisionEstimate>>; } export class EffectEvidenceSynthesisEffectEstimatePrecisionEstimate extends BackboneElement { @Default('fhir.datatypes.EffectEvidenceSynthesis.EffectEvidenceSynthesisEffectEstimatePrecisionEstimate') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public level?: number; @Validate(yup.number()) public from?: number; @Validate(yup.number()) public to?: number; } export class EffectEvidenceSynthesisCertainty extends BackboneElement { @Default('fhir.datatypes.EffectEvidenceSynthesis.EffectEvidenceSynthesisCertainty') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public rating?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(EffectEvidenceSynthesisCertaintyCertaintySubcomponent.schema()))) public certaintySubcomponent?: Array<FlatConvectorModel<EffectEvidenceSynthesisCertaintyCertaintySubcomponent>>; } export class EffectEvidenceSynthesisCertaintyCertaintySubcomponent extends BackboneElement { @Default('fhir.datatypes.EffectEvidenceSynthesis.EffectEvidenceSynthesisCertaintyCertaintySubcomponent') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public rating?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class EffectEvidenceSynthesis extends DomainResource<EffectEvidenceSynthesis> { @Default('fhir.datatypes.EffectEvidenceSynthesis') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public topic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public author?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public editor?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public reviewer?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public endorser?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public relatedArtifact?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public synthesisType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public studyType?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public population: FlatConvectorModel<Reference>; //EvidenceVariable @Required() @Validate(yup.lazy(() => Reference.schema())) public exposure: FlatConvectorModel<Reference>; //EvidenceVariable @Required() @Validate(yup.lazy(() => Reference.schema())) public exposureAlternative: FlatConvectorModel<Reference>; //EvidenceVariable @Required() @Validate(yup.lazy(() => Reference.schema())) public outcome: FlatConvectorModel<Reference>; //EvidenceVariable @Validate(yup.lazy(() => EffectEvidenceSynthesisSampleSize.schema())) public sampleSize?: FlatConvectorModel<EffectEvidenceSynthesisSampleSize>; @Validate(yup.lazy(() => yup.array(EffectEvidenceSynthesisResultsByExposure.schema()))) public resultsByExposure?: Array<FlatConvectorModel<EffectEvidenceSynthesisResultsByExposure>>; @Validate(yup.lazy(() => yup.array(EffectEvidenceSynthesisEffectEstimate.schema()))) public effectEstimate?: Array<FlatConvectorModel<EffectEvidenceSynthesisEffectEstimate>>; @Validate(yup.lazy(() => yup.array(EffectEvidenceSynthesisCertainty.schema()))) public certainty?: Array<FlatConvectorModel<EffectEvidenceSynthesisCertainty>>; } export class ElementDefinitionSlicing extends BackboneElement { @Default('fhir.datatypes.ElementDefinition.ElementDefinitionSlicing') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(ElementDefinitionSlicingDiscriminator.schema()))) public discriminator?: Array<FlatConvectorModel<ElementDefinitionSlicingDiscriminator>>; @Validate(yup.string()) public description?: string; @Validate(yup.boolean()) public ordered?: boolean; @Required() @Validate(yup.string()) public rules: string; } export class ElementDefinitionSlicingDiscriminator extends BackboneElement { @Default('fhir.datatypes.ElementDefinition.ElementDefinitionSlicingDiscriminator') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Required() @Validate(yup.string()) public path: string; } export class ElementDefinitionBase extends BackboneElement { @Default('fhir.datatypes.ElementDefinition.ElementDefinitionBase') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public path: string; @Required() @Validate(yup.number()) public min: number; @Required() @Validate(yup.string()) public max: string; } export class ElementDefinitionType extends BackboneElement { @Default('fhir.datatypes.ElementDefinition.ElementDefinitionType') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.array(yup.string())) public profile? : Array<string>; //StructureDefinition|ImplementationGuide @Validate(yup.array(yup.string())) public targetProfile? : Array<string>; //StructureDefinition|ImplementationGuide @Validate(yup.array(yup.string())) public aggregation? : Array<string>; @Validate(yup.string()) public versioning?: string; } export class ElementDefinitionExample extends BackboneElement { @Default('fhir.datatypes.ElementDefinition.ElementDefinitionExample') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public label: string; } export class ElementDefinitionConstraint extends BackboneElement { @Default('fhir.datatypes.ElementDefinition.ElementDefinitionConstraint') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public key: string; @Validate(yup.string()) public requirements?: string; @Required() @Validate(yup.string()) public severity: string; @Required() @Validate(yup.string()) public human: string; @Validate(yup.string()) public expression?: string; @Validate(yup.string()) public xpath?: string; @Validate(yup.string()) public source?: string; //StructureDefinition } export class ElementDefinitionBinding extends BackboneElement { @Default('fhir.datatypes.ElementDefinition.ElementDefinitionBinding') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public strength: string; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public valueSet?: string; //ValueSet } export class ElementDefinitionMapping extends BackboneElement { @Default('fhir.datatypes.ElementDefinition.ElementDefinitionMapping') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public identity: string; @Validate(yup.string()) public language?: string; @Required() @Validate(yup.string()) public map: string; @Validate(yup.string()) public comment?: string; } export class ElementDefinition extends DomainResource<ElementDefinition> { @Default('fhir.datatypes.ElementDefinition') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public path: string; @Validate(yup.array(yup.string())) public representation? : Array<string>; @Validate(yup.string()) public sliceName?: string; @Validate(yup.boolean()) public sliceIsConstraining?: boolean; @Validate(yup.string()) public label?: string; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public code?: Array<FlatConvectorModel<Coding>>; @Validate(yup.lazy(() => ElementDefinitionSlicing.schema())) public slicing?: FlatConvectorModel<ElementDefinitionSlicing>; @Validate(yup.string()) public short?: string; @Validate(yup.string()) public definition?: string; @Validate(yup.string()) public comment?: string; @Validate(yup.string()) public requirements?: string; @Validate(yup.array(yup.string())) public alias? : Array<string>; @Validate(yup.number()) public min?: number; @Validate(yup.string()) public max?: string; @Validate(yup.lazy(() => ElementDefinitionBase.schema())) public base?: FlatConvectorModel<ElementDefinitionBase>; @Validate(yup.string()) public contentReference?: string; @Validate(yup.lazy(() => yup.array(ElementDefinitionType.schema()))) public type_?: Array<FlatConvectorModel<ElementDefinitionType>>; @Validate(yup.string()) public meaningWhenMissing?: string; @Validate(yup.string()) public orderMeaning?: string; @Validate(yup.lazy(() => yup.array(ElementDefinitionExample.schema()))) public example?: Array<FlatConvectorModel<ElementDefinitionExample>>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public minValueDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public minValueDateTime?: date; @Validate(yup.string()) public minValueInstant?: string; @Validate(yup.string()) public minValueTime?: string; @Validate(yup.number()) public minValueDecimal?: number; @Validate(yup.number()) public minValueInteger?: number; @Validate(yup.number()) public minValuePositiveInt?: number; @Validate(yup.number()) public minValueUnsignedInt?: number; @Validate(yup.lazy(() => Quantity.schema())) public minValueQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public maxValueDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public maxValueDateTime?: date; @Validate(yup.string()) public maxValueInstant?: string; @Validate(yup.string()) public maxValueTime?: string; @Validate(yup.number()) public maxValueDecimal?: number; @Validate(yup.number()) public maxValueInteger?: number; @Validate(yup.number()) public maxValuePositiveInt?: number; @Validate(yup.number()) public maxValueUnsignedInt?: number; @Validate(yup.lazy(() => Quantity.schema())) public maxValueQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.number()) public maxLength?: number; @Validate(yup.array(yup.string())) public condition? : Array<string>; @Validate(yup.lazy(() => yup.array(ElementDefinitionConstraint.schema()))) public constraint?: Array<FlatConvectorModel<ElementDefinitionConstraint>>; @Validate(yup.boolean()) public mustSupport?: boolean; @Validate(yup.boolean()) public isModifier?: boolean; @Validate(yup.string()) public isModifierReason?: string; @Validate(yup.boolean()) public isSummary?: boolean; @Validate(yup.lazy(() => ElementDefinitionBinding.schema())) public binding?: FlatConvectorModel<ElementDefinitionBinding>; @Validate(yup.lazy(() => yup.array(ElementDefinitionMapping.schema()))) public mapping?: Array<FlatConvectorModel<ElementDefinitionMapping>>; } export class EncounterStatusHistory extends BackboneElement { @Default('fhir.datatypes.Encounter.EncounterStatusHistory') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.lazy(() => Period.schema())) public period: FlatConvectorModel<Period>; } export class EncounterClassHistory extends BackboneElement { @Default('fhir.datatypes.Encounter.EncounterClassHistory') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Coding.schema())) public class_: FlatConvectorModel<Coding>; @Required() @Validate(yup.lazy(() => Period.schema())) public period: FlatConvectorModel<Period>; } export class EncounterParticipant extends BackboneElement { @Default('fhir.datatypes.Encounter.EncounterParticipant') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Reference.schema())) public individual?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|RelatedPerson } export class EncounterDiagnosis extends BackboneElement { @Default('fhir.datatypes.Encounter.EncounterDiagnosis') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public condition: FlatConvectorModel<Reference>; //Condition|Procedure @Validate(yup.lazy(() => CodeableConcept.schema())) public use?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public rank?: number; } export class EncounterHospitalization extends BackboneElement { @Default('fhir.datatypes.Encounter.EncounterHospitalization') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public preAdmissionIdentifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => Reference.schema())) public origin?: FlatConvectorModel<Reference>; //Location|Organization @Validate(yup.lazy(() => CodeableConcept.schema())) public admitSource?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public reAdmission?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public dietPreference?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public specialCourtesy?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public specialArrangement?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public destination?: FlatConvectorModel<Reference>; //Location|Organization @Validate(yup.lazy(() => CodeableConcept.schema())) public dischargeDisposition?: FlatConvectorModel<CodeableConcept>; } export class EncounterLocation extends BackboneElement { @Default('fhir.datatypes.Encounter.EncounterLocation') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public location: FlatConvectorModel<Reference>; //Location @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public physicalType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; } export class Encounter extends DomainResource<Encounter> { @Default('fhir.datatypes.Encounter') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => yup.array(EncounterStatusHistory.schema()))) public statusHistory?: Array<FlatConvectorModel<EncounterStatusHistory>>; @Required() @Validate(yup.lazy(() => Coding.schema())) public class_: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => yup.array(EncounterClassHistory.schema()))) public classHistory?: Array<FlatConvectorModel<EncounterClassHistory>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public serviceType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public priority?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => yup.array(Reference.schema()))) public episodeOfCare?: Array<FlatConvectorModel<Reference>>; //EpisodeOfCare @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //ServiceRequest @Validate(yup.lazy(() => yup.array(EncounterParticipant.schema()))) public participant?: Array<FlatConvectorModel<EncounterParticipant>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public appointment?: Array<FlatConvectorModel<Reference>>; //Appointment @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Duration.schema())) public length?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Procedure|Observation|ImmunizationRecommendation @Validate(yup.lazy(() => yup.array(EncounterDiagnosis.schema()))) public diagnosis?: Array<FlatConvectorModel<EncounterDiagnosis>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public account?: Array<FlatConvectorModel<Reference>>; //Account @Validate(yup.lazy(() => EncounterHospitalization.schema())) public hospitalization?: FlatConvectorModel<EncounterHospitalization>; @Validate(yup.lazy(() => yup.array(EncounterLocation.schema()))) public location?: Array<FlatConvectorModel<EncounterLocation>>; @Validate(yup.lazy(() => Reference.schema())) public serviceProvider?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public partOf?: FlatConvectorModel<Reference>; //Encounter } export class Endpoint extends DomainResource<Endpoint> { @Default('fhir.datatypes.Endpoint') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.lazy(() => Coding.schema())) public connectionType: FlatConvectorModel<Coding>; @Validate(yup.string()) public name?: string; @Validate(yup.lazy(() => Reference.schema())) public managingOrganization?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public contact?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public payloadType?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.array(yup.string())) public payloadMimeType? : Array<string>; @Required() @Validate(yup.string()) public address: string; @Validate(yup.array(yup.string())) public header? : Array<string>; } export class EnrollmentRequest extends DomainResource<EnrollmentRequest> { @Default('fhir.datatypes.EnrollmentRequest') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public status?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created?: date; @Validate(yup.lazy(() => Reference.schema())) public insurer?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public provider?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => Reference.schema())) public candidate?: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => Reference.schema())) public coverage?: FlatConvectorModel<Reference>; //Coverage } export class EnrollmentResponse extends DomainResource<EnrollmentResponse> { @Default('fhir.datatypes.EnrollmentResponse') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => Reference.schema())) public request?: FlatConvectorModel<Reference>; //EnrollmentRequest @Validate(yup.string()) public outcome?: string; @Validate(yup.string()) public disposition?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created?: date; @Validate(yup.lazy(() => Reference.schema())) public organization?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public requestProvider?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization } export class EpisodeOfCareStatusHistory extends BackboneElement { @Default('fhir.datatypes.EpisodeOfCare.EpisodeOfCareStatusHistory') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.lazy(() => Period.schema())) public period: FlatConvectorModel<Period>; } export class EpisodeOfCareDiagnosis extends BackboneElement { @Default('fhir.datatypes.EpisodeOfCare.EpisodeOfCareDiagnosis') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public condition: FlatConvectorModel<Reference>; //Condition @Validate(yup.lazy(() => CodeableConcept.schema())) public role?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public rank?: number; } export class EpisodeOfCare extends DomainResource<EpisodeOfCare> { @Default('fhir.datatypes.EpisodeOfCare') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => yup.array(EpisodeOfCareStatusHistory.schema()))) public statusHistory?: Array<FlatConvectorModel<EpisodeOfCareStatusHistory>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(EpisodeOfCareDiagnosis.schema()))) public diagnosis?: Array<FlatConvectorModel<EpisodeOfCareDiagnosis>>; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => Reference.schema())) public managingOrganization?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public referralRequest?: Array<FlatConvectorModel<Reference>>; //ServiceRequest @Validate(yup.lazy(() => Reference.schema())) public careManager?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => yup.array(Reference.schema()))) public team?: Array<FlatConvectorModel<Reference>>; //CareTeam @Validate(yup.lazy(() => yup.array(Reference.schema()))) public account?: Array<FlatConvectorModel<Reference>>; //Account } export class EventDefinition extends DomainResource<EventDefinition> { @Default('fhir.datatypes.EventDefinition') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public subtitle?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public subjectCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subjectReference?: FlatConvectorModel<Reference>; //Group @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public usage?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public topic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public author?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public editor?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public reviewer?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public endorser?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public relatedArtifact?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.lazy(() => yup.array(TriggerDefinition.schema()))) public trigger?: Array<FlatConvectorModel<TriggerDefinition>>; } export class Evidence extends DomainResource<Evidence> { @Default('fhir.datatypes.Evidence') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public shortTitle?: string; @Validate(yup.string()) public subtitle?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public topic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public author?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public editor?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public reviewer?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public endorser?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public relatedArtifact?: Array<FlatConvectorModel<RelatedArtifact>>; @Required() @Validate(yup.lazy(() => Reference.schema())) public exposureBackground: FlatConvectorModel<Reference>; //EvidenceVariable @Validate(yup.lazy(() => yup.array(Reference.schema()))) public exposureVariant?: Array<FlatConvectorModel<Reference>>; //EvidenceVariable @Validate(yup.lazy(() => yup.array(Reference.schema()))) public outcome?: Array<FlatConvectorModel<Reference>>; //EvidenceVariable } export class EvidenceVariableCharacteristic extends BackboneElement { @Default('fhir.datatypes.EvidenceVariable.EvidenceVariableCharacteristic') @ReadOnly() public readonly type: string; @Validate(yup.string()) public description?: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public definitionReference: FlatConvectorModel<Reference>; //Group @Required() @Validate(yup.string()) public definitionCanonical: string; //ActivityDefinition @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public definitionCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Expression.schema())) public definitionExpression: FlatConvectorModel<Expression>; @Required() @Validate(yup.lazy(() => DataRequirement.schema())) public definitionDataRequirement: FlatConvectorModel<DataRequirement>; @Required() @Validate(yup.lazy(() => TriggerDefinition.schema())) public definitionTriggerDefinition: FlatConvectorModel<TriggerDefinition>; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public usageContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.boolean()) public exclude?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public participantEffectiveDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public participantEffectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Duration.schema())) public participantEffectiveDuration?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => Timing.schema())) public participantEffectiveTiming?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => Duration.schema())) public timeFromStart?: FlatConvectorModel<Duration>; @Validate(yup.string()) public groupMeasure?: string; } export class EvidenceVariable extends DomainResource<EvidenceVariable> { @Default('fhir.datatypes.EvidenceVariable') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public shortTitle?: string; @Validate(yup.string()) public subtitle?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public topic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public author?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public editor?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public reviewer?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public endorser?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public relatedArtifact?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.string()) public type_?: string; @Validate(yup.lazy(() => yup.array(EvidenceVariableCharacteristic.schema()))) public characteristic?: Array<FlatConvectorModel<EvidenceVariableCharacteristic>>; } export class ExampleScenarioActor extends BackboneElement { @Default('fhir.datatypes.ExampleScenario.ExampleScenarioActor') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public actorId: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public description?: string; } export class ExampleScenarioInstance extends BackboneElement { @Default('fhir.datatypes.ExampleScenario.ExampleScenarioInstance') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public resourceId: string; @Required() @Validate(yup.string()) public resourceType: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(ExampleScenarioInstanceVersion.schema()))) public version?: Array<FlatConvectorModel<ExampleScenarioInstanceVersion>>; @Validate(yup.lazy(() => yup.array(ExampleScenarioInstanceContainedInstance.schema()))) public containedInstance?: Array<FlatConvectorModel<ExampleScenarioInstanceContainedInstance>>; } export class ExampleScenarioInstanceVersion extends BackboneElement { @Default('fhir.datatypes.ExampleScenario.ExampleScenarioInstanceVersion') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public versionId: string; @Required() @Validate(yup.string()) public description: string; } export class ExampleScenarioInstanceContainedInstance extends BackboneElement { @Default('fhir.datatypes.ExampleScenario.ExampleScenarioInstanceContainedInstance') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public resourceId: string; @Validate(yup.string()) public versionId?: string; } export class ExampleScenarioProcess extends BackboneElement { @Default('fhir.datatypes.ExampleScenario.ExampleScenarioProcess') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public title: string; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public preConditions?: string; @Validate(yup.string()) public postConditions?: string; @Validate(yup.lazy(() => yup.array(ExampleScenarioProcessStep.schema()))) public step?: Array<FlatConvectorModel<ExampleScenarioProcessStep>>; } export class ExampleScenarioProcessStep extends BackboneElement { @Default('fhir.datatypes.ExampleScenario.ExampleScenarioProcessStep') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(ExampleScenarioProcess.schema()))) public process?: Array<FlatConvectorModel<ExampleScenarioProcess>>; @Validate(yup.boolean()) public pause?: boolean; @Validate(yup.lazy(() => ExampleScenarioProcessStepOperation.schema())) public operation?: FlatConvectorModel<ExampleScenarioProcessStepOperation>; @Validate(yup.lazy(() => yup.array(ExampleScenarioProcessStepAlternative.schema()))) public alternative?: Array<FlatConvectorModel<ExampleScenarioProcessStepAlternative>>; } export class ExampleScenarioProcessStepOperation extends BackboneElement { @Default('fhir.datatypes.ExampleScenario.ExampleScenarioProcessStepOperation') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public number: string; @Validate(yup.string()) public type_?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public initiator?: string; @Validate(yup.string()) public receiver?: string; @Validate(yup.string()) public description?: string; @Validate(yup.boolean()) public initiatorActive?: boolean; @Validate(yup.boolean()) public receiverActive?: boolean; @Validate(yup.lazy(() => ExampleScenarioInstanceContainedInstance.schema())) public request?: FlatConvectorModel<ExampleScenarioInstanceContainedInstance>; @Validate(yup.lazy(() => ExampleScenarioInstanceContainedInstance.schema())) public response?: FlatConvectorModel<ExampleScenarioInstanceContainedInstance>; } export class ExampleScenarioProcessStepAlternative extends BackboneElement { @Default('fhir.datatypes.ExampleScenario.ExampleScenarioProcessStepAlternative') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public title: string; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(ExampleScenarioProcessStep.schema()))) public step?: Array<FlatConvectorModel<ExampleScenarioProcessStep>>; } export class ExampleScenario extends DomainResource<ExampleScenario> { @Default('fhir.datatypes.ExampleScenario') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public copyright?: string; @Validate(yup.string()) public purpose?: string; @Validate(yup.lazy(() => yup.array(ExampleScenarioActor.schema()))) public actor?: Array<FlatConvectorModel<ExampleScenarioActor>>; @Validate(yup.lazy(() => yup.array(ExampleScenarioInstance.schema()))) public instance?: Array<FlatConvectorModel<ExampleScenarioInstance>>; @Validate(yup.lazy(() => yup.array(ExampleScenarioProcess.schema()))) public process?: Array<FlatConvectorModel<ExampleScenarioProcess>>; @Validate(yup.array(yup.string())) public workflow? : Array<string>; //ExampleScenario } export class ExplanationOfBenefitRelated extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitRelated') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Reference.schema())) public claim?: FlatConvectorModel<Reference>; //Claim @Validate(yup.lazy(() => CodeableConcept.schema())) public relationship?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Identifier.schema())) public reference?: FlatConvectorModel<Identifier>; } export class ExplanationOfBenefitPayee extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitPayee') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public party?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|Patient|RelatedPerson } export class ExplanationOfBenefitCareTeam extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitCareTeam') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Required() @Validate(yup.lazy(() => Reference.schema())) public provider: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.boolean()) public responsible?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public role?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public qualification?: FlatConvectorModel<CodeableConcept>; } export class ExplanationOfBenefitSupportingInfo extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitSupportingInfo') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public category: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public timingDate?: date; @Validate(yup.lazy(() => Period.schema())) public timingPeriod?: FlatConvectorModel<Period>; @Validate(yup.boolean()) public valueBoolean?: boolean; @Validate(yup.string()) public valueString?: string; @Validate(yup.lazy(() => Quantity.schema())) public valueQuantity?: FlatConvectorModel<Quantity>; // @Validate(yup.lazy(() => Attachment.schema())) public valueAttachment?: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => Reference.schema())) public valueReference?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => Coding.schema())) public reason?: FlatConvectorModel<Coding>; } export class ExplanationOfBenefitDiagnosis extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitDiagnosis') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public diagnosisCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public diagnosisReference: FlatConvectorModel<Reference>; //Condition @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public onAdmission?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public packageCode?: FlatConvectorModel<CodeableConcept>; } export class ExplanationOfBenefitProcedure extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitProcedure') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public procedureCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public procedureReference: FlatConvectorModel<Reference>; //Procedure @Validate(yup.lazy(() => yup.array(Reference.schema()))) public udi?: Array<FlatConvectorModel<Reference>>; //Device } export class ExplanationOfBenefitInsurance extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitInsurance') @ReadOnly() public readonly type: string; @Required() @Validate(yup.boolean()) public focal: boolean; @Required() @Validate(yup.lazy(() => Reference.schema())) public coverage: FlatConvectorModel<Reference>; //Coverage @Validate(yup.array(yup.string())) public preAuthRef? : Array<string>; } export class ExplanationOfBenefitAccident extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitAccident') @ReadOnly() public readonly type: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Address.schema())) public locationAddress?: FlatConvectorModel<Address>; @Validate(yup.lazy(() => Reference.schema())) public locationReference?: FlatConvectorModel<Reference>; //Location } export class ExplanationOfBenefitItem extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitItem') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Validate(yup.array(yup.number())) public careTeamSequence? : Array<number>; @Validate(yup.array(yup.number())) public diagnosisSequence? : Array<number>; @Validate(yup.array(yup.number())) public procedureSequence? : Array<number>; @Validate(yup.array(yup.number())) public informationSequence? : Array<number>; @Validate(yup.lazy(() => CodeableConcept.schema())) public revenue?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public programCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public servicedDate?: date; @Validate(yup.lazy(() => Period.schema())) public servicedPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => CodeableConcept.schema())) public locationCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Address.schema())) public locationAddress?: FlatConvectorModel<Address>; @Validate(yup.lazy(() => Reference.schema())) public locationReference?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public udi?: Array<FlatConvectorModel<Reference>>; //Device @Validate(yup.lazy(() => CodeableConcept.schema())) public bodySite?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public subSite?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public encounter?: Array<FlatConvectorModel<Reference>>; //Encounter @Validate(yup.array(yup.number())) public noteNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ExplanationOfBenefitItemAdjudication>>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitItemDetail.schema()))) public detail?: Array<FlatConvectorModel<ExplanationOfBenefitItemDetail>>; } export class ExplanationOfBenefitItemAdjudication extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitItemAdjudication') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public category: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public reason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Money.schema())) public amount?: FlatConvectorModel<Money>; @Validate(yup.number()) public value?: number; } export class ExplanationOfBenefitItemDetail extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitItemDetail') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Validate(yup.lazy(() => CodeableConcept.schema())) public revenue?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public programCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public udi?: Array<FlatConvectorModel<Reference>>; //Device @Validate(yup.array(yup.number())) public noteNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ExplanationOfBenefitItemAdjudication>>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitItemDetailSubDetail.schema()))) public subDetail?: Array<FlatConvectorModel<ExplanationOfBenefitItemDetailSubDetail>>; } export class ExplanationOfBenefitItemDetailSubDetail extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitItemDetailSubDetail') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public sequence: number; @Validate(yup.lazy(() => CodeableConcept.schema())) public revenue?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public programCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public udi?: Array<FlatConvectorModel<Reference>>; //Device @Validate(yup.array(yup.number())) public noteNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ExplanationOfBenefitItemAdjudication>>; } export class ExplanationOfBenefitAddItem extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitAddItem') @ReadOnly() public readonly type: string; @Validate(yup.array(yup.number())) public itemSequence? : Array<number>; @Validate(yup.array(yup.number())) public detailSequence? : Array<number>; @Validate(yup.array(yup.number())) public subDetailSequence? : Array<number>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public provider?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole|Organization @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public programCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public servicedDate?: date; @Validate(yup.lazy(() => Period.schema())) public servicedPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => CodeableConcept.schema())) public locationCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Address.schema())) public locationAddress?: FlatConvectorModel<Address>; @Validate(yup.lazy(() => Reference.schema())) public locationReference?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => CodeableConcept.schema())) public bodySite?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public subSite?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.array(yup.number())) public noteNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ExplanationOfBenefitItemAdjudication>>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitAddItemDetail.schema()))) public detail?: Array<FlatConvectorModel<ExplanationOfBenefitAddItemDetail>>; } export class ExplanationOfBenefitAddItemDetail extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitAddItemDetail') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.array(yup.number())) public noteNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ExplanationOfBenefitItemAdjudication>>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitAddItemDetailSubDetail.schema()))) public subDetail?: Array<FlatConvectorModel<ExplanationOfBenefitAddItemDetailSubDetail>>; } export class ExplanationOfBenefitAddItemDetailSubDetail extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitAddItemDetailSubDetail') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public productOrService: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public modifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Money.schema())) public unitPrice?: FlatConvectorModel<Money>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public net?: FlatConvectorModel<Money>; @Validate(yup.array(yup.number())) public noteNumber? : Array<number>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ExplanationOfBenefitItemAdjudication>>; } export class ExplanationOfBenefitTotal extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitTotal') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public category: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Money.schema())) public amount: FlatConvectorModel<Money>; } export class ExplanationOfBenefitPayment extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitPayment') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Money.schema())) public adjustment?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => CodeableConcept.schema())) public adjustmentReason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.lazy(() => Money.schema())) public amount?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; } export class ExplanationOfBenefitProcessNote extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitProcessNote') @ReadOnly() public readonly type: string; @Validate(yup.number()) public number?: number; @Validate(yup.string()) public type_?: string; @Validate(yup.string()) public text?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public language?: FlatConvectorModel<CodeableConcept>; } export class ExplanationOfBenefitBenefitBalance extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitBenefitBalance') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public category: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public excluded?: boolean; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public network?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public unit?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public term?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitBenefitBalanceFinancial.schema()))) public financial?: Array<FlatConvectorModel<ExplanationOfBenefitBenefitBalanceFinancial>>; } export class ExplanationOfBenefitBenefitBalanceFinancial extends BackboneElement { @Default('fhir.datatypes.ExplanationOfBenefit.ExplanationOfBenefitBenefitBalanceFinancial') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public allowedUnsignedInt?: number; @Validate(yup.string()) public allowedString?: string; @Validate(yup.lazy(() => Money.schema())) public allowedMoney?: FlatConvectorModel<Money>; @Validate(yup.number()) public usedUnsignedInt?: number; @Validate(yup.lazy(() => Money.schema())) public usedMoney?: FlatConvectorModel<Money>; } export class ExplanationOfBenefit extends DomainResource<ExplanationOfBenefit> { @Default('fhir.datatypes.ExplanationOfBenefit') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public subType?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string()) public use: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => Period.schema())) public billablePeriod?: FlatConvectorModel<Period>; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created: date; @Validate(yup.lazy(() => Reference.schema())) public enterer?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Required() @Validate(yup.lazy(() => Reference.schema())) public insurer: FlatConvectorModel<Reference>; //Organization @Required() @Validate(yup.lazy(() => Reference.schema())) public provider: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => CodeableConcept.schema())) public priority?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public fundsReserveRequested?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public fundsReserve?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitRelated.schema()))) public related?: Array<FlatConvectorModel<ExplanationOfBenefitRelated>>; @Validate(yup.lazy(() => Reference.schema())) public prescription?: FlatConvectorModel<Reference>; //MedicationRequest|VisionPrescription @Validate(yup.lazy(() => Reference.schema())) public originalPrescription?: FlatConvectorModel<Reference>; //MedicationRequest @Validate(yup.lazy(() => ExplanationOfBenefitPayee.schema())) public payee?: FlatConvectorModel<ExplanationOfBenefitPayee>; @Validate(yup.lazy(() => Reference.schema())) public referral?: FlatConvectorModel<Reference>; //ServiceRequest @Validate(yup.lazy(() => Reference.schema())) public facility?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => Reference.schema())) public claim?: FlatConvectorModel<Reference>; //Claim @Validate(yup.lazy(() => Reference.schema())) public claimResponse?: FlatConvectorModel<Reference>; //ClaimResponse @Required() @Validate(yup.string()) public outcome: string; @Validate(yup.string()) public disposition?: string; @Validate(yup.array(yup.string())) public preAuthRef? : Array<string>; @Validate(yup.lazy(() => yup.array(Period.schema()))) public preAuthRefPeriod?: Array<FlatConvectorModel<Period>>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitCareTeam.schema()))) public careTeam?: Array<FlatConvectorModel<ExplanationOfBenefitCareTeam>>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitSupportingInfo.schema()))) public supportingInfo?: Array<FlatConvectorModel<ExplanationOfBenefitSupportingInfo>>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitDiagnosis.schema()))) public diagnosis?: Array<FlatConvectorModel<ExplanationOfBenefitDiagnosis>>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitProcedure.schema()))) public procedure?: Array<FlatConvectorModel<ExplanationOfBenefitProcedure>>; @Validate(yup.number()) public precedence?: number; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitInsurance.schema()))) public insurance?: Array<FlatConvectorModel<ExplanationOfBenefitInsurance>>; @Validate(yup.lazy(() => ExplanationOfBenefitAccident.schema())) public accident?: FlatConvectorModel<ExplanationOfBenefitAccident>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitItem.schema()))) public item?: Array<FlatConvectorModel<ExplanationOfBenefitItem>>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitAddItem.schema()))) public addItem?: Array<FlatConvectorModel<ExplanationOfBenefitAddItem>>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitItemAdjudication.schema()))) public adjudication?: Array<FlatConvectorModel<ExplanationOfBenefitItemAdjudication>>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitTotal.schema()))) public total?: Array<FlatConvectorModel<ExplanationOfBenefitTotal>>; @Validate(yup.lazy(() => ExplanationOfBenefitPayment.schema())) public payment?: FlatConvectorModel<ExplanationOfBenefitPayment>; @Validate(yup.lazy(() => CodeableConcept.schema())) public formCode?: FlatConvectorModel<CodeableConcept>; // @Validate(yup.lazy(() => Attachment.schema())) public form?: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitProcessNote.schema()))) public processNote?: Array<FlatConvectorModel<ExplanationOfBenefitProcessNote>>; @Validate(yup.lazy(() => Period.schema())) public benefitPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(ExplanationOfBenefitBenefitBalance.schema()))) public benefitBalance?: Array<FlatConvectorModel<ExplanationOfBenefitBenefitBalance>>; } export class Expression extends DomainResource<Expression> { @Default('fhir.datatypes.Expression') @ReadOnly() public readonly type: string; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public name?: string; @Required() @Validate(yup.string()) public language: string; @Validate(yup.string()) public expression?: string; @Validate(yup.string()) public reference?: string; } export class FamilyMemberHistoryCondition extends BackboneElement { @Default('fhir.datatypes.FamilyMemberHistory.FamilyMemberHistoryCondition') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public outcome?: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public contributedToDeath?: boolean; @Validate(yup.lazy(() => Age.schema())) public onsetAge?: FlatConvectorModel<Age>; @Validate(yup.lazy(() => Range.schema())) public onsetRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => Period.schema())) public onsetPeriod?: FlatConvectorModel<Period>; @Validate(yup.string()) public onsetString?: string; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class FamilyMemberHistory extends DomainResource<FamilyMemberHistory> { @Default('fhir.datatypes.FamilyMemberHistory') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.array(yup.string())) public instantiatesCanonical? : Array<string>; //PlanDefinition|Questionnaire|ActivityDefinition|Measure|OperationDefinition @Validate(yup.array(yup.string())) public instantiatesUri? : Array<string>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public dataAbsentReason?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public name?: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public relationship: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public sex?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Period.schema())) public bornPeriod?: FlatConvectorModel<Period>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public bornDate?: date; @Validate(yup.string()) public bornString?: string; @Validate(yup.lazy(() => Age.schema())) public ageAge?: FlatConvectorModel<Age>; @Validate(yup.lazy(() => Range.schema())) public ageRange?: FlatConvectorModel<Range>; @Validate(yup.string()) public ageString?: string; @Validate(yup.boolean()) public estimatedAge?: boolean; @Validate(yup.boolean()) public deceasedBoolean?: boolean; @Validate(yup.lazy(() => Age.schema())) public deceasedAge?: FlatConvectorModel<Age>; @Validate(yup.lazy(() => Range.schema())) public deceasedRange?: FlatConvectorModel<Range>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public deceasedDate?: date; @Validate(yup.string()) public deceasedString?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|AllergyIntolerance|QuestionnaireResponse|DiagnosticReport|DocumentReference @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(FamilyMemberHistoryCondition.schema()))) public condition?: Array<FlatConvectorModel<FamilyMemberHistoryCondition>>; } export class Flag extends DomainResource<Flag> { @Default('fhir.datatypes.Flag') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Location|Group|Organization|Practitioner|PlanDefinition|Medication|Procedure @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.lazy(() => Reference.schema())) public author?: FlatConvectorModel<Reference>; //Device|Organization|Patient|Practitioner|PractitionerRole } export class GoalTarget extends BackboneElement { @Default('fhir.datatypes.Goal.GoalTarget') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public measure?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Quantity.schema())) public detailQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Range.schema())) public detailRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => CodeableConcept.schema())) public detailCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public detailString?: string; @Validate(yup.boolean()) public detailBoolean?: boolean; @Validate(yup.number()) public detailInteger?: number; @Validate(yup.lazy(() => Ratio.schema())) public detailRatio?: FlatConvectorModel<Ratio>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public dueDate?: date; @Validate(yup.lazy(() => Duration.schema())) public dueDuration?: FlatConvectorModel<Duration>; } export class Goal extends DomainResource<Goal> { @Default('fhir.datatypes.Goal') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public lifecycleStatus: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public achievementStatus?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public priority?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public description: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group|Organization @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public startDate?: date; @Validate(yup.lazy(() => CodeableConcept.schema())) public startCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(GoalTarget.schema()))) public target?: Array<FlatConvectorModel<GoalTarget>>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public statusDate?: date; @Validate(yup.string()) public statusReason?: string; @Validate(yup.lazy(() => Reference.schema())) public expressedBy?: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|RelatedPerson @Validate(yup.lazy(() => yup.array(Reference.schema()))) public addresses?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|MedicationStatement|NutritionOrder|ServiceRequest|RiskAssessment @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public outcomeCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public outcomeReference?: Array<FlatConvectorModel<Reference>>; //Observation } export class GraphDefinitionLink extends BackboneElement { @Default('fhir.datatypes.GraphDefinition.GraphDefinitionLink') @ReadOnly() public readonly type: string; @Validate(yup.string()) public path?: string; @Validate(yup.string()) public sliceName?: string; @Validate(yup.number()) public min?: number; @Validate(yup.string()) public max?: string; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(GraphDefinitionLinkTarget.schema()))) public target?: Array<FlatConvectorModel<GraphDefinitionLinkTarget>>; } export class GraphDefinitionLinkTarget extends BackboneElement { @Default('fhir.datatypes.GraphDefinition.GraphDefinitionLinkTarget') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public params?: string; @Validate(yup.string()) public profile?: string; //StructureDefinition @Validate(yup.lazy(() => yup.array(GraphDefinitionLinkTargetCompartment.schema()))) public compartment?: Array<FlatConvectorModel<GraphDefinitionLinkTargetCompartment>>; @Validate(yup.lazy(() => yup.array(GraphDefinitionLink.schema()))) public link?: Array<FlatConvectorModel<GraphDefinitionLink>>; } export class GraphDefinitionLinkTargetCompartment extends BackboneElement { @Default('fhir.datatypes.GraphDefinition.GraphDefinitionLinkTargetCompartment') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public use: string; @Required() @Validate(yup.string()) public code: string; @Required() @Validate(yup.string()) public rule: string; @Validate(yup.string()) public expression?: string; @Validate(yup.string()) public description?: string; } export class GraphDefinition extends DomainResource<GraphDefinition> { @Default('fhir.datatypes.GraphDefinition') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.string()) public version?: string; @Required() @Validate(yup.string()) public name: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Required() @Validate(yup.string()) public start: string; @Validate(yup.string()) public profile?: string; //StructureDefinition @Validate(yup.lazy(() => yup.array(GraphDefinitionLink.schema()))) public link?: Array<FlatConvectorModel<GraphDefinitionLink>>; } export class GroupCharacteristic extends BackboneElement { @Default('fhir.datatypes.Group.GroupCharacteristic') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public valueCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.boolean()) public valueBoolean: boolean; @Required() @Validate(yup.lazy(() => Quantity.schema())) public valueQuantity: FlatConvectorModel<Quantity>; @Required() @Validate(yup.lazy(() => Range.schema())) public valueRange: FlatConvectorModel<Range>; @Required() @Validate(yup.lazy(() => Reference.schema())) public valueReference: FlatConvectorModel<Reference>; @Required() @Validate(yup.boolean()) public exclude: boolean; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; } export class GroupMember extends BackboneElement { @Default('fhir.datatypes.Group.GroupMember') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public entity: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|Device|Medication|Substance|Group @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.boolean()) public inactive?: boolean; } export class Group extends DomainResource<Group> { @Default('fhir.datatypes.Group') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.boolean()) public active?: boolean; @Required() @Validate(yup.string()) public type_: string; @Required() @Validate(yup.boolean()) public actual: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public name?: string; @Validate(yup.number()) public quantity?: number; @Validate(yup.lazy(() => Reference.schema())) public managingEntity?: FlatConvectorModel<Reference>; //Organization|RelatedPerson|Practitioner|PractitionerRole @Validate(yup.lazy(() => yup.array(GroupCharacteristic.schema()))) public characteristic?: Array<FlatConvectorModel<GroupCharacteristic>>; @Validate(yup.lazy(() => yup.array(GroupMember.schema()))) public member?: Array<FlatConvectorModel<GroupMember>>; } export class GuidanceResponse extends DomainResource<GuidanceResponse> { @Default('fhir.datatypes.GuidanceResponse') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public requestIdentifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public moduleUri: string; @Required() @Validate(yup.string()) public moduleCanonical: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public moduleCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public occurrenceDateTime?: date; @Validate(yup.lazy(() => Reference.schema())) public performer?: FlatConvectorModel<Reference>; //Device @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport|DocumentReference @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public evaluationMessage?: Array<FlatConvectorModel<Reference>>; //OperationOutcome @Validate(yup.lazy(() => Reference.schema())) public outputParameters?: FlatConvectorModel<Reference>; //Parameters @Validate(yup.lazy(() => Reference.schema())) public result?: FlatConvectorModel<Reference>; //CarePlan|RequestGroup @Validate(yup.lazy(() => yup.array(DataRequirement.schema()))) public dataRequirement?: Array<FlatConvectorModel<DataRequirement>>; } export class HealthcareServiceEligibility extends BackboneElement { @Default('fhir.datatypes.HealthcareService.HealthcareServiceEligibility') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public comment?: string; } export class HealthcareServiceAvailableTime extends BackboneElement { @Default('fhir.datatypes.HealthcareService.HealthcareServiceAvailableTime') @ReadOnly() public readonly type: string; @Validate(yup.array(yup.string())) public daysOfWeek? : Array<string>; @Validate(yup.boolean()) public allDay?: boolean; @Validate(yup.string()) public availableStartTime?: string; @Validate(yup.string()) public availableEndTime?: string; } export class HealthcareServiceNotAvailable extends BackboneElement { @Default('fhir.datatypes.HealthcareService.HealthcareServiceNotAvailable') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public description: string; @Validate(yup.lazy(() => Period.schema())) public during?: FlatConvectorModel<Period>; } export class HealthcareService extends DomainResource<HealthcareService> { @Default('fhir.datatypes.HealthcareService') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.boolean()) public active?: boolean; @Validate(yup.lazy(() => Reference.schema())) public providedBy?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public specialty?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public location?: Array<FlatConvectorModel<Reference>>; //Location @Validate(yup.string()) public name?: string; @Validate(yup.string()) public comment?: string; @Validate(yup.string()) public extraDetails?: string; // @Validate(yup.lazy(() => Attachment.schema())) public photo?: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public coverageArea?: Array<FlatConvectorModel<Reference>>; //Location @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public serviceProvisionCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(HealthcareServiceEligibility.schema()))) public eligibility?: Array<FlatConvectorModel<HealthcareServiceEligibility>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public program?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public characteristic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public communication?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public referralMethod?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.boolean()) public appointmentRequired?: boolean; @Validate(yup.lazy(() => yup.array(HealthcareServiceAvailableTime.schema()))) public availableTime?: Array<FlatConvectorModel<HealthcareServiceAvailableTime>>; @Validate(yup.lazy(() => yup.array(HealthcareServiceNotAvailable.schema()))) public notAvailable?: Array<FlatConvectorModel<HealthcareServiceNotAvailable>>; @Validate(yup.string()) public availabilityExceptions?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public endpoint?: Array<FlatConvectorModel<Reference>>; //Endpoint } export class ImagingStudySeries extends BackboneElement { @Default('fhir.datatypes.ImagingStudy.ImagingStudySeries') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public uid: string; @Validate(yup.number()) public number?: number; @Required() @Validate(yup.lazy(() => Coding.schema())) public modality: FlatConvectorModel<Coding>; @Validate(yup.string()) public description?: string; @Validate(yup.number()) public numberOfInstances?: number; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public endpoint?: Array<FlatConvectorModel<Reference>>; //Endpoint @Validate(yup.lazy(() => Coding.schema())) public bodySite?: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => Coding.schema())) public laterality?: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public specimen?: Array<FlatConvectorModel<Reference>>; //Specimen @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public started?: date; @Validate(yup.lazy(() => yup.array(ImagingStudySeriesPerformer.schema()))) public performer?: Array<FlatConvectorModel<ImagingStudySeriesPerformer>>; @Validate(yup.lazy(() => yup.array(ImagingStudySeriesInstance.schema()))) public instance?: Array<FlatConvectorModel<ImagingStudySeriesInstance>>; } export class ImagingStudySeriesPerformer extends BackboneElement { @Default('fhir.datatypes.ImagingStudy.ImagingStudySeriesPerformer') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public function_?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public actor: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|CareTeam|Patient|Device|RelatedPerson } export class ImagingStudySeriesInstance extends BackboneElement { @Default('fhir.datatypes.ImagingStudy.ImagingStudySeriesInstance') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public uid: string; @Required() @Validate(yup.lazy(() => Coding.schema())) public sopClass: FlatConvectorModel<Coding>; @Validate(yup.number()) public number?: number; @Validate(yup.string()) public title?: string; } export class ImagingStudy extends DomainResource<ImagingStudy> { @Default('fhir.datatypes.ImagingStudy') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public modality?: Array<FlatConvectorModel<Coding>>; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Device|Group @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public started?: date; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //CarePlan|ServiceRequest|Appointment|AppointmentResponse|Task @Validate(yup.lazy(() => Reference.schema())) public referrer?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => yup.array(Reference.schema()))) public interpreter?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => yup.array(Reference.schema()))) public endpoint?: Array<FlatConvectorModel<Reference>>; //Endpoint @Validate(yup.number()) public numberOfSeries?: number; @Validate(yup.number()) public numberOfInstances?: number; @Validate(yup.lazy(() => Reference.schema())) public procedureReference?: FlatConvectorModel<Reference>; //Procedure @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public procedureCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public location?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|Media|DiagnosticReport|DocumentReference @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(ImagingStudySeries.schema()))) public series?: Array<FlatConvectorModel<ImagingStudySeries>>; } export class ImmunizationPerformer extends BackboneElement { @Default('fhir.datatypes.Immunization.ImmunizationPerformer') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public function_?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public actor: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization } export class ImmunizationEducation extends BackboneElement { @Default('fhir.datatypes.Immunization.ImmunizationEducation') @ReadOnly() public readonly type: string; @Validate(yup.string()) public documentType?: string; @Validate(yup.string()) public reference?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public publicationDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public presentationDate?: date; } export class ImmunizationReaction extends BackboneElement { @Default('fhir.datatypes.Immunization.ImmunizationReaction') @ReadOnly() public readonly type: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.lazy(() => Reference.schema())) public detail?: FlatConvectorModel<Reference>; //Observation @Validate(yup.boolean()) public reported?: boolean; } export class ImmunizationProtocolApplied extends BackboneElement { @Default('fhir.datatypes.Immunization.ImmunizationProtocolApplied') @ReadOnly() public readonly type: string; @Validate(yup.string()) public series?: string; @Validate(yup.lazy(() => Reference.schema())) public authority?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public targetDisease?: Array<FlatConvectorModel<CodeableConcept>>; @Required() @Validate(yup.number()) public doseNumberPositiveInt: number; @Required() @Validate(yup.string()) public doseNumberString: string; @Validate(yup.number()) public seriesDosesPositiveInt?: number; @Validate(yup.string()) public seriesDosesString?: string; } export class Immunization extends DomainResource<Immunization> { @Default('fhir.datatypes.Immunization') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public statusReason?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public vaccineCode: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public occurrenceDateTime: date; @Required() @Validate(yup.string()) public occurrenceString: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public recorded?: date; @Validate(yup.boolean()) public primarySource?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public reportOrigin?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public location?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => Reference.schema())) public manufacturer?: FlatConvectorModel<Reference>; //Organization @Validate(yup.string()) public lotNumber?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public expirationDate?: date; @Validate(yup.lazy(() => CodeableConcept.schema())) public site?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public route?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public doseQuantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => yup.array(ImmunizationPerformer.schema()))) public performer?: Array<FlatConvectorModel<ImmunizationPerformer>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport @Validate(yup.boolean()) public isSubpotent?: boolean; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public subpotentReason?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ImmunizationEducation.schema()))) public education?: Array<FlatConvectorModel<ImmunizationEducation>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public programEligibility?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public fundingSource?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(ImmunizationReaction.schema()))) public reaction?: Array<FlatConvectorModel<ImmunizationReaction>>; @Validate(yup.lazy(() => yup.array(ImmunizationProtocolApplied.schema()))) public protocolApplied?: Array<FlatConvectorModel<ImmunizationProtocolApplied>>; } export class ImmunizationEvaluation extends DomainResource<ImmunizationEvaluation> { @Default('fhir.datatypes.ImmunizationEvaluation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.lazy(() => Reference.schema())) public authority?: FlatConvectorModel<Reference>; //Organization @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public targetDisease: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public immunizationEvent: FlatConvectorModel<Reference>; //Immunization @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public doseStatus: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public doseStatusReason?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public series?: string; @Validate(yup.number()) public doseNumberPositiveInt?: number; @Validate(yup.string()) public doseNumberString?: string; @Validate(yup.number()) public seriesDosesPositiveInt?: number; @Validate(yup.string()) public seriesDosesString?: string; } export class ImmunizationRecommendationRecommendation extends BackboneElement { @Default('fhir.datatypes.ImmunizationRecommendation.ImmunizationRecommendationRecommendation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public vaccineCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public targetDisease?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public contraindicatedVaccineCode?: Array<FlatConvectorModel<CodeableConcept>>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public forecastStatus: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public forecastReason?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ImmunizationRecommendationRecommendationDateCriterion.schema()))) public dateCriterion?: Array<FlatConvectorModel<ImmunizationRecommendationRecommendationDateCriterion>>; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public series?: string; @Validate(yup.number()) public doseNumberPositiveInt?: number; @Validate(yup.string()) public doseNumberString?: string; @Validate(yup.number()) public seriesDosesPositiveInt?: number; @Validate(yup.string()) public seriesDosesString?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supportingImmunization?: Array<FlatConvectorModel<Reference>>; //Immunization|ImmunizationEvaluation @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supportingPatientInformation?: Array<FlatConvectorModel<Reference>>; //Any } export class ImmunizationRecommendationRecommendationDateCriterion extends BackboneElement { @Default('fhir.datatypes.ImmunizationRecommendation.ImmunizationRecommendationRecommendationDateCriterion') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public value: date; } export class ImmunizationRecommendation extends DomainResource<ImmunizationRecommendation> { @Default('fhir.datatypes.ImmunizationRecommendation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date: date; @Validate(yup.lazy(() => Reference.schema())) public authority?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(ImmunizationRecommendationRecommendation.schema()))) public recommendation?: Array<FlatConvectorModel<ImmunizationRecommendationRecommendation>>; } export class ImplementationGuideDependsOn extends BackboneElement { @Default('fhir.datatypes.ImplementationGuide.ImplementationGuideDependsOn') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public uri: string; //ImplementationGuide @Validate(yup.string()) public packageId?: string; @Validate(yup.string()) public version?: string; } export class ImplementationGuideGlobal extends BackboneElement { @Default('fhir.datatypes.ImplementationGuide.ImplementationGuideGlobal') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Required() @Validate(yup.string()) public profile: string; //StructureDefinition } export class ImplementationGuideDefinition extends BackboneElement { @Default('fhir.datatypes.ImplementationGuide.ImplementationGuideDefinition') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(ImplementationGuideDefinitionGrouping.schema()))) public grouping?: Array<FlatConvectorModel<ImplementationGuideDefinitionGrouping>>; @Validate(yup.lazy(() => yup.array(ImplementationGuideDefinitionResource.schema()))) public resource?: Array<FlatConvectorModel<ImplementationGuideDefinitionResource>>; @Validate(yup.lazy(() => ImplementationGuideDefinitionPage.schema())) public page?: FlatConvectorModel<ImplementationGuideDefinitionPage>; @Validate(yup.lazy(() => yup.array(ImplementationGuideDefinitionParameter.schema()))) public parameter?: Array<FlatConvectorModel<ImplementationGuideDefinitionParameter>>; @Validate(yup.lazy(() => yup.array(ImplementationGuideDefinitionTemplate.schema()))) public template?: Array<FlatConvectorModel<ImplementationGuideDefinitionTemplate>>; } export class ImplementationGuideDefinitionGrouping extends BackboneElement { @Default('fhir.datatypes.ImplementationGuide.ImplementationGuideDefinitionGrouping') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public description?: string; } export class ImplementationGuideDefinitionResource extends BackboneElement { @Default('fhir.datatypes.ImplementationGuide.ImplementationGuideDefinitionResource') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public reference: FlatConvectorModel<Reference>; //Any @Validate(yup.array(yup.string())) public fhirVersion? : Array<string>; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public description?: string; @Validate(yup.boolean()) public exampleBoolean?: boolean; @Validate(yup.string()) public exampleCanonical?: string; //StructureDefinition @Validate(yup.string()) public groupingId?: string; } export class ImplementationGuideDefinitionPage extends BackboneElement { @Default('fhir.datatypes.ImplementationGuide.ImplementationGuideDefinitionPage') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public nameUrl: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public nameReference: FlatConvectorModel<Reference>; //Binary @Required() @Validate(yup.string()) public title: string; @Required() @Validate(yup.string()) public generation: string; @Validate(yup.lazy(() => yup.array(ImplementationGuideDefinitionPage.schema()))) public page?: Array<FlatConvectorModel<ImplementationGuideDefinitionPage>>; } export class ImplementationGuideDefinitionParameter extends BackboneElement { @Default('fhir.datatypes.ImplementationGuide.ImplementationGuideDefinitionParameter') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Required() @Validate(yup.string()) public value: string; } export class ImplementationGuideDefinitionTemplate extends BackboneElement { @Default('fhir.datatypes.ImplementationGuide.ImplementationGuideDefinitionTemplate') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Required() @Validate(yup.string()) public source: string; @Validate(yup.string()) public scope?: string; } export class ImplementationGuideManifest extends BackboneElement { @Default('fhir.datatypes.ImplementationGuide.ImplementationGuideManifest') @ReadOnly() public readonly type: string; @Validate(yup.string()) public rendering?: string; @Validate(yup.lazy(() => yup.array(ImplementationGuideManifestResource.schema()))) public resource?: Array<FlatConvectorModel<ImplementationGuideManifestResource>>; @Validate(yup.lazy(() => yup.array(ImplementationGuideManifestPage.schema()))) public page?: Array<FlatConvectorModel<ImplementationGuideManifestPage>>; @Validate(yup.array(yup.string())) public image? : Array<string>; @Validate(yup.array(yup.string())) public other? : Array<string>; } export class ImplementationGuideManifestResource extends BackboneElement { @Default('fhir.datatypes.ImplementationGuide.ImplementationGuideManifestResource') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public reference: FlatConvectorModel<Reference>; //Any @Validate(yup.boolean()) public exampleBoolean?: boolean; @Validate(yup.string()) public exampleCanonical?: string; //StructureDefinition @Validate(yup.string()) public relativePath?: string; } export class ImplementationGuideManifestPage extends BackboneElement { @Default('fhir.datatypes.ImplementationGuide.ImplementationGuideManifestPage') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public title?: string; @Validate(yup.array(yup.string())) public anchor? : Array<string>; } export class ImplementationGuide extends DomainResource<ImplementationGuide> { @Default('fhir.datatypes.ImplementationGuide') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public url: string; @Validate(yup.string()) public version?: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public copyright?: string; @Required() @Validate(yup.string()) public packageId: string; @Validate(yup.string()) public license?: string; @Validate(yup.array(yup.string())) public fhirVersion? : Array<string>; @Validate(yup.lazy(() => yup.array(ImplementationGuideDependsOn.schema()))) public dependsOn?: Array<FlatConvectorModel<ImplementationGuideDependsOn>>; @Validate(yup.lazy(() => yup.array(ImplementationGuideGlobal.schema()))) public global?: Array<FlatConvectorModel<ImplementationGuideGlobal>>; @Validate(yup.lazy(() => ImplementationGuideDefinition.schema())) public definition?: FlatConvectorModel<ImplementationGuideDefinition>; @Validate(yup.lazy(() => ImplementationGuideManifest.schema())) public manifest?: FlatConvectorModel<ImplementationGuideManifest>; } export class InsurancePlanContact extends BackboneElement { @Default('fhir.datatypes.InsurancePlan.InsurancePlanContact') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public purpose?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => HumanName.schema())) public name?: FlatConvectorModel<HumanName>; @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.lazy(() => Address.schema())) public address?: FlatConvectorModel<Address>; } export class InsurancePlanCoverage extends BackboneElement { @Default('fhir.datatypes.InsurancePlan.InsurancePlanCoverage') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public network?: Array<FlatConvectorModel<Reference>>; //Organization @Validate(yup.lazy(() => yup.array(InsurancePlanCoverageBenefit.schema()))) public benefit?: Array<FlatConvectorModel<InsurancePlanCoverageBenefit>>; } export class InsurancePlanCoverageBenefit extends BackboneElement { @Default('fhir.datatypes.InsurancePlan.InsurancePlanCoverageBenefit') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public requirement?: string; @Validate(yup.lazy(() => yup.array(InsurancePlanCoverageBenefitLimit.schema()))) public limit?: Array<FlatConvectorModel<InsurancePlanCoverageBenefitLimit>>; } export class InsurancePlanCoverageBenefitLimit extends BackboneElement { @Default('fhir.datatypes.InsurancePlan.InsurancePlanCoverageBenefitLimit') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Quantity.schema())) public value?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; } export class InsurancePlanPlan extends BackboneElement { @Default('fhir.datatypes.InsurancePlan.InsurancePlanPlan') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public coverageArea?: Array<FlatConvectorModel<Reference>>; //Location @Validate(yup.lazy(() => yup.array(Reference.schema()))) public network?: Array<FlatConvectorModel<Reference>>; //Organization @Validate(yup.lazy(() => yup.array(InsurancePlanPlanGeneralCost.schema()))) public generalCost?: Array<FlatConvectorModel<InsurancePlanPlanGeneralCost>>; @Validate(yup.lazy(() => yup.array(InsurancePlanPlanSpecificCost.schema()))) public specificCost?: Array<FlatConvectorModel<InsurancePlanPlanSpecificCost>>; } export class InsurancePlanPlanGeneralCost extends BackboneElement { @Default('fhir.datatypes.InsurancePlan.InsurancePlanPlanGeneralCost') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public groupSize?: number; @Validate(yup.lazy(() => Money.schema())) public cost?: FlatConvectorModel<Money>; @Validate(yup.string()) public comment?: string; } export class InsurancePlanPlanSpecificCost extends BackboneElement { @Default('fhir.datatypes.InsurancePlan.InsurancePlanPlanSpecificCost') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public category: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(InsurancePlanPlanSpecificCostBenefit.schema()))) public benefit?: Array<FlatConvectorModel<InsurancePlanPlanSpecificCostBenefit>>; } export class InsurancePlanPlanSpecificCostBenefit extends BackboneElement { @Default('fhir.datatypes.InsurancePlan.InsurancePlanPlanSpecificCostBenefit') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(InsurancePlanPlanSpecificCostBenefitCost.schema()))) public cost?: Array<FlatConvectorModel<InsurancePlanPlanSpecificCostBenefitCost>>; } export class InsurancePlanPlanSpecificCostBenefitCost extends BackboneElement { @Default('fhir.datatypes.InsurancePlan.InsurancePlanPlanSpecificCostBenefitCost') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public applicability?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public qualifiers?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Quantity.schema())) public value?: FlatConvectorModel<Quantity>; } export class InsurancePlan extends DomainResource<InsurancePlan> { @Default('fhir.datatypes.InsurancePlan') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public name?: string; @Validate(yup.array(yup.string())) public alias? : Array<string>; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Reference.schema())) public ownedBy?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public administeredBy?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(Reference.schema()))) public coverageArea?: Array<FlatConvectorModel<Reference>>; //Location @Validate(yup.lazy(() => yup.array(InsurancePlanContact.schema()))) public contact?: Array<FlatConvectorModel<InsurancePlanContact>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public endpoint?: Array<FlatConvectorModel<Reference>>; //Endpoint @Validate(yup.lazy(() => yup.array(Reference.schema()))) public network?: Array<FlatConvectorModel<Reference>>; //Organization @Validate(yup.lazy(() => yup.array(InsurancePlanCoverage.schema()))) public coverage?: Array<FlatConvectorModel<InsurancePlanCoverage>>; @Validate(yup.lazy(() => yup.array(InsurancePlanPlan.schema()))) public plan?: Array<FlatConvectorModel<InsurancePlanPlan>>; } export class InvoiceParticipant extends BackboneElement { @Default('fhir.datatypes.Invoice.InvoiceParticipant') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public role?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public actor: FlatConvectorModel<Reference>; //Practitioner|Organization|Patient|PractitionerRole|Device|RelatedPerson } export class InvoiceLineItem extends BackboneElement { @Default('fhir.datatypes.Invoice.InvoiceLineItem') @ReadOnly() public readonly type: string; @Validate(yup.number()) public sequence?: number; @Required() @Validate(yup.lazy(() => Reference.schema())) public chargeItemReference: FlatConvectorModel<Reference>; //ChargeItem @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public chargeItemCodeableConcept: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(InvoiceLineItemPriceComponent.schema()))) public priceComponent?: Array<FlatConvectorModel<InvoiceLineItemPriceComponent>>; } export class InvoiceLineItemPriceComponent extends BackboneElement { @Default('fhir.datatypes.Invoice.InvoiceLineItemPriceComponent') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public factor?: number; @Validate(yup.lazy(() => Money.schema())) public amount?: FlatConvectorModel<Money>; } export class Invoice extends DomainResource<Invoice> { @Default('fhir.datatypes.Invoice') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.string()) public cancelledReason?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public recipient?: FlatConvectorModel<Reference>; //Organization|Patient|RelatedPerson @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.lazy(() => yup.array(InvoiceParticipant.schema()))) public participant?: Array<FlatConvectorModel<InvoiceParticipant>>; @Validate(yup.lazy(() => Reference.schema())) public issuer?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public account?: FlatConvectorModel<Reference>; //Account @Validate(yup.lazy(() => yup.array(InvoiceLineItem.schema()))) public lineItem?: Array<FlatConvectorModel<InvoiceLineItem>>; @Validate(yup.lazy(() => yup.array(InvoiceLineItemPriceComponent.schema()))) public totalPriceComponent?: Array<FlatConvectorModel<InvoiceLineItemPriceComponent>>; @Validate(yup.lazy(() => Money.schema())) public totalNet?: FlatConvectorModel<Money>; @Validate(yup.lazy(() => Money.schema())) public totalGross?: FlatConvectorModel<Money>; @Validate(yup.string()) public paymentTerms?: string; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class Library extends DomainResource<Library> { @Default('fhir.datatypes.Library') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public subtitle?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public subjectCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subjectReference?: FlatConvectorModel<Reference>; //Group @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public usage?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public topic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public author?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public editor?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public reviewer?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public endorser?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public relatedArtifact?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.lazy(() => yup.array(ParameterDefinition.schema()))) public parameter?: Array<FlatConvectorModel<ParameterDefinition>>; @Validate(yup.lazy(() => yup.array(DataRequirement.schema()))) public dataRequirement?: Array<FlatConvectorModel<DataRequirement>>; // @Validate(yup.lazy(() => yup.array(Attachment.schema()))) public content?: Array<FlatConvectorModel<Attachment>>; } export class LinkageItem extends BackboneElement { @Default('fhir.datatypes.Linkage.LinkageItem') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public resource: FlatConvectorModel<Reference>; //Any } export class Linkage extends DomainResource<Linkage> { @Default('fhir.datatypes.Linkage') @ReadOnly() public readonly type: string; @Validate(yup.boolean()) public active?: boolean; @Validate(yup.lazy(() => Reference.schema())) public author?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => yup.array(LinkageItem.schema()))) public item?: Array<FlatConvectorModel<LinkageItem>>; } export class ListEntry extends BackboneElement { @Default('fhir.datatypes.List.ListEntry') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public flag?: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public deleted?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Required() @Validate(yup.lazy(() => Reference.schema())) public item: FlatConvectorModel<Reference>; //Any } export class List extends DomainResource<List> { @Default('fhir.datatypes.List') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.string()) public mode: string; @Validate(yup.string()) public title?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Group|Device|Location @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.lazy(() => Reference.schema())) public source?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Patient|Device @Validate(yup.lazy(() => CodeableConcept.schema())) public orderedBy?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(ListEntry.schema()))) public entry?: Array<FlatConvectorModel<ListEntry>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public emptyReason?: FlatConvectorModel<CodeableConcept>; } export class LocationPosition extends BackboneElement { @Default('fhir.datatypes.Location.LocationPosition') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public longitude: number; @Required() @Validate(yup.number()) public latitude: number; @Validate(yup.number()) public altitude?: number; } export class LocationHoursOfOperation extends BackboneElement { @Default('fhir.datatypes.Location.LocationHoursOfOperation') @ReadOnly() public readonly type: string; @Validate(yup.array(yup.string())) public daysOfWeek? : Array<string>; @Validate(yup.boolean()) public allDay?: boolean; @Validate(yup.string()) public openingTime?: string; @Validate(yup.string()) public closingTime?: string; } export class Location extends DomainResource<Location> { @Default('fhir.datatypes.Location') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => Coding.schema())) public operationalStatus?: FlatConvectorModel<Coding>; @Validate(yup.string()) public name?: string; @Validate(yup.array(yup.string())) public alias? : Array<string>; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public mode?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.lazy(() => Address.schema())) public address?: FlatConvectorModel<Address>; @Validate(yup.lazy(() => CodeableConcept.schema())) public physicalType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => LocationPosition.schema())) public position?: FlatConvectorModel<LocationPosition>; @Validate(yup.lazy(() => Reference.schema())) public managingOrganization?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public partOf?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => yup.array(LocationHoursOfOperation.schema()))) public hoursOfOperation?: Array<FlatConvectorModel<LocationHoursOfOperation>>; @Validate(yup.string()) public availabilityExceptions?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public endpoint?: Array<FlatConvectorModel<Reference>>; //Endpoint } export class MarketingStatus extends DomainResource<MarketingStatus> { @Default('fhir.datatypes.MarketingStatus') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public country: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public jurisdiction?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public status: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Period.schema())) public dateRange: FlatConvectorModel<Period>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public restoreDate?: date; } export class MeasureGroup extends BackboneElement { @Default('fhir.datatypes.Measure.MeasureGroup') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(MeasureGroupPopulation.schema()))) public population?: Array<FlatConvectorModel<MeasureGroupPopulation>>; @Validate(yup.lazy(() => yup.array(MeasureGroupStratifier.schema()))) public stratifier?: Array<FlatConvectorModel<MeasureGroupStratifier>>; } export class MeasureGroupPopulation extends BackboneElement { @Default('fhir.datatypes.Measure.MeasureGroupPopulation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public description?: string; @Required() @Validate(yup.lazy(() => Expression.schema())) public criteria: FlatConvectorModel<Expression>; } export class MeasureGroupStratifier extends BackboneElement { @Default('fhir.datatypes.Measure.MeasureGroupStratifier') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => Expression.schema())) public criteria?: FlatConvectorModel<Expression>; @Validate(yup.lazy(() => yup.array(MeasureGroupStratifierComponent.schema()))) public component?: Array<FlatConvectorModel<MeasureGroupStratifierComponent>>; } export class MeasureGroupStratifierComponent extends BackboneElement { @Default('fhir.datatypes.Measure.MeasureGroupStratifierComponent') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public description?: string; @Required() @Validate(yup.lazy(() => Expression.schema())) public criteria: FlatConvectorModel<Expression>; } export class MeasureSupplementalData extends BackboneElement { @Default('fhir.datatypes.Measure.MeasureSupplementalData') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public usage?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public description?: string; @Required() @Validate(yup.lazy(() => Expression.schema())) public criteria: FlatConvectorModel<Expression>; } export class Measure extends DomainResource<Measure> { @Default('fhir.datatypes.Measure') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public subtitle?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public subjectCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subjectReference?: FlatConvectorModel<Reference>; //Group @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public usage?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public topic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public author?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public editor?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public reviewer?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public endorser?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public relatedArtifact?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.array(yup.string())) public library? : Array<string>; //Library @Validate(yup.string()) public disclaimer?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public scoring?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public compositeScoring?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public riskAdjustment?: string; @Validate(yup.string()) public rateAggregation?: string; @Validate(yup.string()) public rationale?: string; @Validate(yup.string()) public clinicalRecommendationStatement?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public improvementNotation?: FlatConvectorModel<CodeableConcept>; @Validate(yup.array(yup.string())) public definition? : Array<string>; @Validate(yup.string()) public guidance?: string; @Validate(yup.lazy(() => yup.array(MeasureGroup.schema()))) public group?: Array<FlatConvectorModel<MeasureGroup>>; @Validate(yup.lazy(() => yup.array(MeasureSupplementalData.schema()))) public supplementalData?: Array<FlatConvectorModel<MeasureSupplementalData>>; } export class MeasureReportGroup extends BackboneElement { @Default('fhir.datatypes.MeasureReport.MeasureReportGroup') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(MeasureReportGroupPopulation.schema()))) public population?: Array<FlatConvectorModel<MeasureReportGroupPopulation>>; @Validate(yup.lazy(() => Quantity.schema())) public measureScore?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => yup.array(MeasureReportGroupStratifier.schema()))) public stratifier?: Array<FlatConvectorModel<MeasureReportGroupStratifier>>; } export class MeasureReportGroupPopulation extends BackboneElement { @Default('fhir.datatypes.MeasureReport.MeasureReportGroupPopulation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public count?: number; @Validate(yup.lazy(() => Reference.schema())) public subjectResults?: FlatConvectorModel<Reference>; //List } export class MeasureReportGroupStratifier extends BackboneElement { @Default('fhir.datatypes.MeasureReport.MeasureReportGroupStratifier') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public code?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(MeasureReportGroupStratifierStratum.schema()))) public stratum?: Array<FlatConvectorModel<MeasureReportGroupStratifierStratum>>; } export class MeasureReportGroupStratifierStratum extends BackboneElement { @Default('fhir.datatypes.MeasureReport.MeasureReportGroupStratifierStratum') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public value?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(MeasureReportGroupStratifierStratumComponent.schema()))) public component?: Array<FlatConvectorModel<MeasureReportGroupStratifierStratumComponent>>; @Validate(yup.lazy(() => yup.array(MeasureReportGroupStratifierStratumPopulation.schema()))) public population?: Array<FlatConvectorModel<MeasureReportGroupStratifierStratumPopulation>>; @Validate(yup.lazy(() => Quantity.schema())) public measureScore?: FlatConvectorModel<Quantity>; } export class MeasureReportGroupStratifierStratumComponent extends BackboneElement { @Default('fhir.datatypes.MeasureReport.MeasureReportGroupStratifierStratumComponent') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public value: FlatConvectorModel<CodeableConcept>; } export class MeasureReportGroupStratifierStratumPopulation extends BackboneElement { @Default('fhir.datatypes.MeasureReport.MeasureReportGroupStratifierStratumPopulation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public count?: number; @Validate(yup.lazy(() => Reference.schema())) public subjectResults?: FlatConvectorModel<Reference>; //List } export class MeasureReport extends DomainResource<MeasureReport> { @Default('fhir.datatypes.MeasureReport') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.string()) public type_: string; @Required() @Validate(yup.string()) public measure: string; //Measure @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|Location|Device|RelatedPerson|Group @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.lazy(() => Reference.schema())) public reporter?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Location|Organization @Required() @Validate(yup.lazy(() => Period.schema())) public period: FlatConvectorModel<Period>; @Validate(yup.lazy(() => CodeableConcept.schema())) public improvementNotation?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(MeasureReportGroup.schema()))) public group?: Array<FlatConvectorModel<MeasureReportGroup>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public evaluatedResource?: Array<FlatConvectorModel<Reference>>; //Any } export class Media extends DomainResource<Media> { @Default('fhir.datatypes.Media') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //ServiceRequest|CarePlan @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //Any @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public modality?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public view?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|Group|Device|Specimen|Location @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public createdDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public createdPeriod?: FlatConvectorModel<Period>; @Validate(yup.string()) public issued?: string; @Validate(yup.lazy(() => Reference.schema())) public operator?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|CareTeam|Patient|Device|RelatedPerson @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public bodySite?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public deviceName?: string; @Validate(yup.lazy(() => Reference.schema())) public device?: FlatConvectorModel<Reference>; //Device|DeviceMetric|Device @Validate(yup.number()) public height?: number; @Validate(yup.number()) public width?: number; @Validate(yup.number()) public frames?: number; @Validate(yup.number()) public duration?: number; // @Required() @Validate(yup.lazy(() => Attachment.schema())) public content: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class MedicationIngredient extends BackboneElement { @Default('fhir.datatypes.Medication.MedicationIngredient') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public itemCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public itemReference: FlatConvectorModel<Reference>; //Substance|Medication @Validate(yup.boolean()) public isActive?: boolean; @Validate(yup.lazy(() => Ratio.schema())) public strength?: FlatConvectorModel<Ratio>; } export class MedicationBatch extends BackboneElement { @Default('fhir.datatypes.Medication.MedicationBatch') @ReadOnly() public readonly type: string; @Validate(yup.string()) public lotNumber?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public expirationDate?: date; } export class Medication extends DomainResource<Medication> { @Default('fhir.datatypes.Medication') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => Reference.schema())) public manufacturer?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => CodeableConcept.schema())) public form?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Ratio.schema())) public amount?: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => yup.array(MedicationIngredient.schema()))) public ingredient?: Array<FlatConvectorModel<MedicationIngredient>>; @Validate(yup.lazy(() => MedicationBatch.schema())) public batch?: FlatConvectorModel<MedicationBatch>; } export class MedicationAdministrationPerformer extends BackboneElement { @Default('fhir.datatypes.MedicationAdministration.MedicationAdministrationPerformer') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public function_?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public actor: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Patient|RelatedPerson|Device } export class MedicationAdministrationDosage extends BackboneElement { @Default('fhir.datatypes.MedicationAdministration.MedicationAdministrationDosage') @ReadOnly() public readonly type: string; @Validate(yup.string()) public text?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public site?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public route?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public method?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public dose?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Ratio.schema())) public rateRatio?: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public rateQuantity?: FlatConvectorModel<SimpleQuantity>; } export class MedicationAdministration extends DomainResource<MedicationAdministration> { @Default('fhir.datatypes.MedicationAdministration') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.array(yup.string())) public instantiates? : Array<string>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //MedicationAdministration|Procedure @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public statusReason?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public medicationCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public medicationReference: FlatConvectorModel<Reference>; //Medication @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public context?: FlatConvectorModel<Reference>; //Encounter|EpisodeOfCare @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supportingInformation?: Array<FlatConvectorModel<Reference>>; //Any @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public effectiveDateTime: date; @Required() @Validate(yup.lazy(() => Period.schema())) public effectivePeriod: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(MedicationAdministrationPerformer.schema()))) public performer?: Array<FlatConvectorModel<MedicationAdministrationPerformer>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport @Validate(yup.lazy(() => Reference.schema())) public request?: FlatConvectorModel<Reference>; //MedicationRequest @Validate(yup.lazy(() => yup.array(Reference.schema()))) public device?: Array<FlatConvectorModel<Reference>>; //Device @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => MedicationAdministrationDosage.schema())) public dosage?: FlatConvectorModel<MedicationAdministrationDosage>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public eventHistory?: Array<FlatConvectorModel<Reference>>; //Provenance } export class MedicationDispensePerformer extends BackboneElement { @Default('fhir.datatypes.MedicationDispense.MedicationDispensePerformer') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public function_?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public actor: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|Patient|Device|RelatedPerson } export class MedicationDispenseSubstitution extends BackboneElement { @Default('fhir.datatypes.MedicationDispense.MedicationDispenseSubstitution') @ReadOnly() public readonly type: string; @Required() @Validate(yup.boolean()) public wasSubstituted: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reason?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public responsibleParty?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole } export class MedicationDispense extends DomainResource<MedicationDispense> { @Default('fhir.datatypes.MedicationDispense') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //Procedure @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public statusReasonCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public statusReasonReference?: FlatConvectorModel<Reference>; //DetectedIssue @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public medicationCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public medicationReference: FlatConvectorModel<Reference>; //Medication @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public context?: FlatConvectorModel<Reference>; //Encounter|EpisodeOfCare @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supportingInformation?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(MedicationDispensePerformer.schema()))) public performer?: Array<FlatConvectorModel<MedicationDispensePerformer>>; @Validate(yup.lazy(() => Reference.schema())) public location?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => yup.array(Reference.schema()))) public authorizingPrescription?: Array<FlatConvectorModel<Reference>>; //MedicationRequest @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public daysSupply?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public whenPrepared?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public whenHandedOver?: date; @Validate(yup.lazy(() => Reference.schema())) public destination?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => yup.array(Reference.schema()))) public receiver?: Array<FlatConvectorModel<Reference>>; //Patient|Practitioner @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(Dosage.schema()))) public dosageInstruction?: Array<FlatConvectorModel<Dosage>>; @Validate(yup.lazy(() => MedicationDispenseSubstitution.schema())) public substitution?: FlatConvectorModel<MedicationDispenseSubstitution>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public detectedIssue?: Array<FlatConvectorModel<Reference>>; //DetectedIssue @Validate(yup.lazy(() => yup.array(Reference.schema()))) public eventHistory?: Array<FlatConvectorModel<Reference>>; //Provenance } export class MedicationKnowledgeRelatedMedicationKnowledge extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeRelatedMedicationKnowledge') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reference?: Array<FlatConvectorModel<Reference>>; //MedicationKnowledge } export class MedicationKnowledgeMonograph extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeMonograph') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public source?: FlatConvectorModel<Reference>; //DocumentReference|Media } export class MedicationKnowledgeIngredient extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeIngredient') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public itemCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public itemReference: FlatConvectorModel<Reference>; //Substance @Validate(yup.boolean()) public isActive?: boolean; @Validate(yup.lazy(() => Ratio.schema())) public strength?: FlatConvectorModel<Ratio>; } export class MedicationKnowledgeCost extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeCost') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public source?: string; @Required() @Validate(yup.lazy(() => Money.schema())) public cost: FlatConvectorModel<Money>; } export class MedicationKnowledgeMonitoringProgram extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeMonitoringProgram') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public name?: string; } export class MedicationKnowledgeAdministrationGuidelines extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeAdministrationGuidelines') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(MedicationKnowledgeAdministrationGuidelinesDosage.schema()))) public dosage?: Array<FlatConvectorModel<MedicationKnowledgeAdministrationGuidelinesDosage>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public indicationCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public indicationReference?: FlatConvectorModel<Reference>; //ObservationDefinition @Validate(yup.lazy(() => yup.array(MedicationKnowledgeAdministrationGuidelinesPatientCharacteristics.schema()))) public patientCharacteristics?: Array<FlatConvectorModel<MedicationKnowledgeAdministrationGuidelinesPatientCharacteristics>>; } export class MedicationKnowledgeAdministrationGuidelinesDosage extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeAdministrationGuidelinesDosage') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Dosage.schema()))) public dosage?: Array<FlatConvectorModel<Dosage>>; } export class MedicationKnowledgeAdministrationGuidelinesPatientCharacteristics extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeAdministrationGuidelinesPatientCharacteristics') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public characteristicCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => SimpleQuantity.schema())) public characteristicQuantity: FlatConvectorModel<SimpleQuantity>; @Validate(yup.array(yup.string())) public value? : Array<string>; } export class MedicationKnowledgeMedicineClassification extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeMedicineClassification') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public classification?: Array<FlatConvectorModel<CodeableConcept>>; } export class MedicationKnowledgePackaging extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgePackaging') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; } export class MedicationKnowledgeDrugCharacteristic extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeDrugCharacteristic') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public valueCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public valueString?: string; @Validate(yup.lazy(() => SimpleQuantity.schema())) public valueQuantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.string()) public valueBase64Binary?: string; } export class MedicationKnowledgeRegulatory extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeRegulatory') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public regulatoryAuthority: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(MedicationKnowledgeRegulatorySubstitution.schema()))) public substitution?: Array<FlatConvectorModel<MedicationKnowledgeRegulatorySubstitution>>; @Validate(yup.lazy(() => yup.array(MedicationKnowledgeRegulatorySchedule.schema()))) public schedule?: Array<FlatConvectorModel<MedicationKnowledgeRegulatorySchedule>>; @Validate(yup.lazy(() => MedicationKnowledgeRegulatoryMaxDispense.schema())) public maxDispense?: FlatConvectorModel<MedicationKnowledgeRegulatoryMaxDispense>; } export class MedicationKnowledgeRegulatorySubstitution extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeRegulatorySubstitution') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.boolean()) public allowed: boolean; } export class MedicationKnowledgeRegulatorySchedule extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeRegulatorySchedule') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public schedule: FlatConvectorModel<CodeableConcept>; } export class MedicationKnowledgeRegulatoryMaxDispense extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeRegulatoryMaxDispense') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Duration.schema())) public period?: FlatConvectorModel<Duration>; } export class MedicationKnowledgeKinetics extends BackboneElement { @Default('fhir.datatypes.MedicationKnowledge.MedicationKnowledgeKinetics') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(SimpleQuantity.schema()))) public areaUnderCurve?: Array<FlatConvectorModel<SimpleQuantity>>; @Validate(yup.lazy(() => yup.array(SimpleQuantity.schema()))) public lethalDose50?: Array<FlatConvectorModel<SimpleQuantity>>; @Validate(yup.lazy(() => Duration.schema())) public halfLifePeriod?: FlatConvectorModel<Duration>; } export class MedicationKnowledge extends DomainResource<MedicationKnowledge> { @Default('fhir.datatypes.MedicationKnowledge') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => Reference.schema())) public manufacturer?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => CodeableConcept.schema())) public doseForm?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public amount?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.array(yup.string())) public synonym? : Array<string>; @Validate(yup.lazy(() => yup.array(MedicationKnowledgeRelatedMedicationKnowledge.schema()))) public relatedMedicationKnowledge?: Array<FlatConvectorModel<MedicationKnowledgeRelatedMedicationKnowledge>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public associatedMedication?: Array<FlatConvectorModel<Reference>>; //Medication @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public productType?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(MedicationKnowledgeMonograph.schema()))) public monograph?: Array<FlatConvectorModel<MedicationKnowledgeMonograph>>; @Validate(yup.lazy(() => yup.array(MedicationKnowledgeIngredient.schema()))) public ingredient?: Array<FlatConvectorModel<MedicationKnowledgeIngredient>>; @Validate(yup.string()) public preparationInstruction?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public intendedRoute?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(MedicationKnowledgeCost.schema()))) public cost?: Array<FlatConvectorModel<MedicationKnowledgeCost>>; @Validate(yup.lazy(() => yup.array(MedicationKnowledgeMonitoringProgram.schema()))) public monitoringProgram?: Array<FlatConvectorModel<MedicationKnowledgeMonitoringProgram>>; @Validate(yup.lazy(() => yup.array(MedicationKnowledgeAdministrationGuidelines.schema()))) public administrationGuidelines?: Array<FlatConvectorModel<MedicationKnowledgeAdministrationGuidelines>>; @Validate(yup.lazy(() => yup.array(MedicationKnowledgeMedicineClassification.schema()))) public medicineClassification?: Array<FlatConvectorModel<MedicationKnowledgeMedicineClassification>>; @Validate(yup.lazy(() => MedicationKnowledgePackaging.schema())) public packaging?: FlatConvectorModel<MedicationKnowledgePackaging>; @Validate(yup.lazy(() => yup.array(MedicationKnowledgeDrugCharacteristic.schema()))) public drugCharacteristic?: Array<FlatConvectorModel<MedicationKnowledgeDrugCharacteristic>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public contraindication?: Array<FlatConvectorModel<Reference>>; //DetectedIssue @Validate(yup.lazy(() => yup.array(MedicationKnowledgeRegulatory.schema()))) public regulatory?: Array<FlatConvectorModel<MedicationKnowledgeRegulatory>>; @Validate(yup.lazy(() => yup.array(MedicationKnowledgeKinetics.schema()))) public kinetics?: Array<FlatConvectorModel<MedicationKnowledgeKinetics>>; } export class MedicationRequestDispenseRequest extends BackboneElement { @Default('fhir.datatypes.MedicationRequest.MedicationRequestDispenseRequest') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => MedicationRequestDispenseRequestInitialFill.schema())) public initialFill?: FlatConvectorModel<MedicationRequestDispenseRequestInitialFill>; @Validate(yup.lazy(() => Duration.schema())) public dispenseInterval?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => Period.schema())) public validityPeriod?: FlatConvectorModel<Period>; @Validate(yup.number()) public numberOfRepeatsAllowed?: number; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Duration.schema())) public expectedSupplyDuration?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => Reference.schema())) public performer?: FlatConvectorModel<Reference>; //Organization } export class MedicationRequestDispenseRequestInitialFill extends BackboneElement { @Default('fhir.datatypes.MedicationRequest.MedicationRequestDispenseRequestInitialFill') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Duration.schema())) public duration?: FlatConvectorModel<Duration>; } export class MedicationRequestSubstitution extends BackboneElement { @Default('fhir.datatypes.MedicationRequest.MedicationRequestSubstitution') @ReadOnly() public readonly type: string; @Required() @Validate(yup.boolean()) public allowedBoolean: boolean; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public allowedCodeableConcept: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public reason?: FlatConvectorModel<CodeableConcept>; } export class MedicationRequest extends DomainResource<MedicationRequest> { @Default('fhir.datatypes.MedicationRequest') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public statusReason?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string()) public intent: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public priority?: string; @Validate(yup.boolean()) public doNotPerform?: boolean; @Validate(yup.boolean()) public reportedBoolean?: boolean; @Validate(yup.lazy(() => Reference.schema())) public reportedReference?: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|RelatedPerson|Organization @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public medicationCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public medicationReference: FlatConvectorModel<Reference>; //Medication @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supportingInformation?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public authoredOn?: date; @Validate(yup.lazy(() => Reference.schema())) public requester?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|Patient|RelatedPerson|Device @Validate(yup.lazy(() => Reference.schema())) public performer?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|Patient|Device|RelatedPerson|CareTeam @Validate(yup.lazy(() => CodeableConcept.schema())) public performerType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public recorder?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation @Validate(yup.array(yup.string())) public instantiatesCanonical? : Array<string>; @Validate(yup.array(yup.string())) public instantiatesUri? : Array<string>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //CarePlan|MedicationRequest|ServiceRequest|ImmunizationRecommendation @Validate(yup.lazy(() => Identifier.schema())) public groupIdentifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => CodeableConcept.schema())) public courseOfTherapyType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public insurance?: Array<FlatConvectorModel<Reference>>; //Coverage|ClaimResponse @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(Dosage.schema()))) public dosageInstruction?: Array<FlatConvectorModel<Dosage>>; @Validate(yup.lazy(() => MedicationRequestDispenseRequest.schema())) public dispenseRequest?: FlatConvectorModel<MedicationRequestDispenseRequest>; @Validate(yup.lazy(() => MedicationRequestSubstitution.schema())) public substitution?: FlatConvectorModel<MedicationRequestSubstitution>; @Validate(yup.lazy(() => Reference.schema())) public priorPrescription?: FlatConvectorModel<Reference>; //MedicationRequest @Validate(yup.lazy(() => yup.array(Reference.schema()))) public detectedIssue?: Array<FlatConvectorModel<Reference>>; //DetectedIssue @Validate(yup.lazy(() => yup.array(Reference.schema()))) public eventHistory?: Array<FlatConvectorModel<Reference>>; //Provenance } export class MedicationStatement extends DomainResource<MedicationStatement> { @Default('fhir.datatypes.MedicationStatement') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //MedicationRequest|CarePlan|ServiceRequest @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //MedicationAdministration|MedicationDispense|MedicationStatement|Procedure|Observation @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public statusReason?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public medicationCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public medicationReference: FlatConvectorModel<Reference>; //Medication @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public context?: FlatConvectorModel<Reference>; //Encounter|EpisodeOfCare @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public effectiveDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public dateAsserted?: date; @Validate(yup.lazy(() => Reference.schema())) public informationSource?: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|RelatedPerson|Organization @Validate(yup.lazy(() => yup.array(Reference.schema()))) public derivedFrom?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(Dosage.schema()))) public dosage?: Array<FlatConvectorModel<Dosage>>; } export class MedicinalProductName extends BackboneElement { @Default('fhir.datatypes.MedicinalProduct.MedicinalProductName') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public productName: string; @Validate(yup.lazy(() => yup.array(MedicinalProductNameNamePart.schema()))) public namePart?: Array<FlatConvectorModel<MedicinalProductNameNamePart>>; @Validate(yup.lazy(() => yup.array(MedicinalProductNameCountryLanguage.schema()))) public countryLanguage?: Array<FlatConvectorModel<MedicinalProductNameCountryLanguage>>; } export class MedicinalProductNameNamePart extends BackboneElement { @Default('fhir.datatypes.MedicinalProduct.MedicinalProductNameNamePart') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public part: string; @Required() @Validate(yup.lazy(() => Coding.schema())) public type_: FlatConvectorModel<Coding>; } export class MedicinalProductNameCountryLanguage extends BackboneElement { @Default('fhir.datatypes.MedicinalProduct.MedicinalProductNameCountryLanguage') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public country: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public jurisdiction?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public language: FlatConvectorModel<CodeableConcept>; } export class MedicinalProductManufacturingBusinessOperation extends BackboneElement { @Default('fhir.datatypes.MedicinalProduct.MedicinalProductManufacturingBusinessOperation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public operationType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Identifier.schema())) public authorisationReferenceNumber?: FlatConvectorModel<Identifier>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public effectiveDate?: date; @Validate(yup.lazy(() => CodeableConcept.schema())) public confidentialityIndicator?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public manufacturer?: Array<FlatConvectorModel<Reference>>; //Organization @Validate(yup.lazy(() => Reference.schema())) public regulator?: FlatConvectorModel<Reference>; //Organization } export class MedicinalProductSpecialDesignation extends BackboneElement { @Default('fhir.datatypes.MedicinalProduct.MedicinalProductSpecialDesignation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public intendedUse?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public indicationCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public indicationReference?: FlatConvectorModel<Reference>; //MedicinalProductIndication @Validate(yup.lazy(() => CodeableConcept.schema())) public status?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.lazy(() => CodeableConcept.schema())) public species?: FlatConvectorModel<CodeableConcept>; } export class MedicinalProduct extends DomainResource<MedicinalProduct> { @Default('fhir.datatypes.MedicinalProduct') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Coding.schema())) public domain?: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => CodeableConcept.schema())) public combinedPharmaceuticalDoseForm?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public legalStatusOfSupply?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public additionalMonitoringIndicator?: FlatConvectorModel<CodeableConcept>; @Validate(yup.array(yup.string())) public specialMeasures? : Array<string>; @Validate(yup.lazy(() => CodeableConcept.schema())) public paediatricUseIndicator?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public productClassification?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(MarketingStatus.schema()))) public marketingStatus?: Array<FlatConvectorModel<MarketingStatus>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public pharmaceuticalProduct?: Array<FlatConvectorModel<Reference>>; //MedicinalProductPharmaceutical @Validate(yup.lazy(() => yup.array(Reference.schema()))) public packagedMedicinalProduct?: Array<FlatConvectorModel<Reference>>; //MedicinalProductPackaged @Validate(yup.lazy(() => yup.array(Reference.schema()))) public attachedDocument?: Array<FlatConvectorModel<Reference>>; //DocumentReference @Validate(yup.lazy(() => yup.array(Reference.schema()))) public masterFile?: Array<FlatConvectorModel<Reference>>; //DocumentReference @Validate(yup.lazy(() => yup.array(Reference.schema()))) public contact?: Array<FlatConvectorModel<Reference>>; //Organization|PractitionerRole @Validate(yup.lazy(() => yup.array(Reference.schema()))) public clinicalTrial?: Array<FlatConvectorModel<Reference>>; //ResearchStudy @Validate(yup.lazy(() => yup.array(MedicinalProductName.schema()))) public name?: Array<FlatConvectorModel<MedicinalProductName>>; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public crossReference?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(MedicinalProductManufacturingBusinessOperation.schema()))) public manufacturingBusinessOperation?: Array<FlatConvectorModel<MedicinalProductManufacturingBusinessOperation>>; @Validate(yup.lazy(() => yup.array(MedicinalProductSpecialDesignation.schema()))) public specialDesignation?: Array<FlatConvectorModel<MedicinalProductSpecialDesignation>>; } export class MedicinalProductAuthorizationJurisdictionalAuthorization extends BackboneElement { @Default('fhir.datatypes.MedicinalProductAuthorization.MedicinalProductAuthorizationJurisdictionalAuthorization') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public country?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public legalStatusOfSupply?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Period.schema())) public validityPeriod?: FlatConvectorModel<Period>; } export class MedicinalProductAuthorizationProcedure extends BackboneElement { @Default('fhir.datatypes.MedicinalProductAuthorization.MedicinalProductAuthorizationProcedure') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Period.schema())) public datePeriod?: FlatConvectorModel<Period>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public dateDateTime?: date; @Validate(yup.lazy(() => yup.array(MedicinalProductAuthorizationProcedure.schema()))) public application?: Array<FlatConvectorModel<MedicinalProductAuthorizationProcedure>>; } export class MedicinalProductAuthorization extends DomainResource<MedicinalProductAuthorization> { @Default('fhir.datatypes.MedicinalProductAuthorization') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //MedicinalProduct|MedicinalProductPackaged @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public country?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public status?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public statusDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public restoreDate?: date; @Validate(yup.lazy(() => Period.schema())) public validityPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Period.schema())) public dataExclusivityPeriod?: FlatConvectorModel<Period>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public dateOfFirstAuthorization?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public internationalBirthDate?: date; @Validate(yup.lazy(() => CodeableConcept.schema())) public legalBasis?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(MedicinalProductAuthorizationJurisdictionalAuthorization.schema()))) public jurisdictionalAuthorization?: Array<FlatConvectorModel<MedicinalProductAuthorizationJurisdictionalAuthorization>>; @Validate(yup.lazy(() => Reference.schema())) public holder?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public regulator?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => MedicinalProductAuthorizationProcedure.schema())) public procedure?: FlatConvectorModel<MedicinalProductAuthorizationProcedure>; } export class MedicinalProductContraindicationOtherTherapy extends BackboneElement { @Default('fhir.datatypes.MedicinalProductContraindication.MedicinalProductContraindicationOtherTherapy') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public therapyRelationshipType: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public medicationCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public medicationReference: FlatConvectorModel<Reference>; //MedicinalProduct|Medication|Substance|SubstanceSpecification } export class MedicinalProductContraindication extends DomainResource<MedicinalProductContraindication> { @Default('fhir.datatypes.MedicinalProductContraindication') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public subject?: Array<FlatConvectorModel<Reference>>; //MedicinalProduct|Medication @Validate(yup.lazy(() => CodeableConcept.schema())) public disease?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public diseaseStatus?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public comorbidity?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public therapeuticIndication?: Array<FlatConvectorModel<Reference>>; //MedicinalProductIndication @Validate(yup.lazy(() => yup.array(MedicinalProductContraindicationOtherTherapy.schema()))) public otherTherapy?: Array<FlatConvectorModel<MedicinalProductContraindicationOtherTherapy>>; @Validate(yup.lazy(() => yup.array(Population.schema()))) public population?: Array<FlatConvectorModel<Population>>; } export class MedicinalProductIndicationOtherTherapy extends BackboneElement { @Default('fhir.datatypes.MedicinalProductIndication.MedicinalProductIndicationOtherTherapy') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public therapyRelationshipType: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public medicationCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public medicationReference: FlatConvectorModel<Reference>; //MedicinalProduct|Medication|Substance|SubstanceSpecification } export class MedicinalProductIndication extends DomainResource<MedicinalProductIndication> { @Default('fhir.datatypes.MedicinalProductIndication') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public subject?: Array<FlatConvectorModel<Reference>>; //MedicinalProduct|Medication @Validate(yup.lazy(() => CodeableConcept.schema())) public diseaseSymptomProcedure?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public diseaseStatus?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public comorbidity?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public intendedEffect?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Quantity.schema())) public duration?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => yup.array(MedicinalProductIndicationOtherTherapy.schema()))) public otherTherapy?: Array<FlatConvectorModel<MedicinalProductIndicationOtherTherapy>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public undesirableEffect?: Array<FlatConvectorModel<Reference>>; //MedicinalProductUndesirableEffect @Validate(yup.lazy(() => yup.array(Population.schema()))) public population?: Array<FlatConvectorModel<Population>>; } export class MedicinalProductIngredientSpecifiedSubstance extends BackboneElement { @Default('fhir.datatypes.MedicinalProductIngredient.MedicinalProductIngredientSpecifiedSubstance') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public group: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public confidentiality?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(MedicinalProductIngredientSpecifiedSubstanceStrength.schema()))) public strength?: Array<FlatConvectorModel<MedicinalProductIngredientSpecifiedSubstanceStrength>>; } export class MedicinalProductIngredientSpecifiedSubstanceStrength extends BackboneElement { @Default('fhir.datatypes.MedicinalProductIngredient.MedicinalProductIngredientSpecifiedSubstanceStrength') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Ratio.schema())) public presentation: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => Ratio.schema())) public presentationLowLimit?: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => Ratio.schema())) public concentration?: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => Ratio.schema())) public concentrationLowLimit?: FlatConvectorModel<Ratio>; @Validate(yup.string()) public measurementPoint?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public country?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(MedicinalProductIngredientSpecifiedSubstanceStrengthReferenceStrength.schema()))) public referenceStrength?: Array<FlatConvectorModel<MedicinalProductIngredientSpecifiedSubstanceStrengthReferenceStrength>>; } export class MedicinalProductIngredientSpecifiedSubstanceStrengthReferenceStrength extends BackboneElement { @Default('fhir.datatypes.MedicinalProductIngredient.MedicinalProductIngredientSpecifiedSubstanceStrengthReferenceStrength') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public substance?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Ratio.schema())) public strength: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => Ratio.schema())) public strengthLowLimit?: FlatConvectorModel<Ratio>; @Validate(yup.string()) public measurementPoint?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public country?: Array<FlatConvectorModel<CodeableConcept>>; } export class MedicinalProductIngredientSubstance extends BackboneElement { @Default('fhir.datatypes.MedicinalProductIngredient.MedicinalProductIngredientSubstance') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(MedicinalProductIngredientSpecifiedSubstanceStrength.schema()))) public strength?: Array<FlatConvectorModel<MedicinalProductIngredientSpecifiedSubstanceStrength>>; } export class MedicinalProductIngredient extends DomainResource<MedicinalProductIngredient> { @Default('fhir.datatypes.MedicinalProductIngredient') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public role: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public allergenicIndicator?: boolean; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public manufacturer?: Array<FlatConvectorModel<Reference>>; //Organization @Validate(yup.lazy(() => yup.array(MedicinalProductIngredientSpecifiedSubstance.schema()))) public specifiedSubstance?: Array<FlatConvectorModel<MedicinalProductIngredientSpecifiedSubstance>>; @Validate(yup.lazy(() => MedicinalProductIngredientSubstance.schema())) public substance?: FlatConvectorModel<MedicinalProductIngredientSubstance>; } export class MedicinalProductInteractionInteractant extends BackboneElement { @Default('fhir.datatypes.MedicinalProductInteraction.MedicinalProductInteractionInteractant') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public itemReference: FlatConvectorModel<Reference>; //MedicinalProduct|Medication|Substance|ObservationDefinition @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public itemCodeableConcept: FlatConvectorModel<CodeableConcept>; } export class MedicinalProductInteraction extends DomainResource<MedicinalProductInteraction> { @Default('fhir.datatypes.MedicinalProductInteraction') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public subject?: Array<FlatConvectorModel<Reference>>; //MedicinalProduct|Medication|Substance @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(MedicinalProductInteractionInteractant.schema()))) public interactant?: Array<FlatConvectorModel<MedicinalProductInteractionInteractant>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public effect?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public incidence?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public management?: FlatConvectorModel<CodeableConcept>; } export class MedicinalProductManufactured extends DomainResource<MedicinalProductManufactured> { @Default('fhir.datatypes.MedicinalProductManufactured') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public manufacturedDoseForm: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public unitOfPresentation?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Quantity.schema())) public quantity: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public manufacturer?: Array<FlatConvectorModel<Reference>>; //Organization @Validate(yup.lazy(() => yup.array(Reference.schema()))) public ingredient?: Array<FlatConvectorModel<Reference>>; //MedicinalProductIngredient @Validate(yup.lazy(() => ProdCharacteristic.schema())) public physicalCharacteristics?: FlatConvectorModel<ProdCharacteristic>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public otherCharacteristics?: Array<FlatConvectorModel<CodeableConcept>>; } export class MedicinalProductPackagedBatchIdentifier extends BackboneElement { @Default('fhir.datatypes.MedicinalProductPackaged.MedicinalProductPackagedBatchIdentifier') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Identifier.schema())) public outerPackaging: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => Identifier.schema())) public immediatePackaging?: FlatConvectorModel<Identifier>; } export class MedicinalProductPackagedPackageItem extends BackboneElement { @Default('fhir.datatypes.MedicinalProductPackaged.MedicinalProductPackagedPackageItem') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Quantity.schema())) public quantity: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public material?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public alternateMaterial?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public device?: Array<FlatConvectorModel<Reference>>; //DeviceDefinition @Validate(yup.lazy(() => yup.array(Reference.schema()))) public manufacturedItem?: Array<FlatConvectorModel<Reference>>; //MedicinalProductManufactured @Validate(yup.lazy(() => yup.array(MedicinalProductPackagedPackageItem.schema()))) public packageItem?: Array<FlatConvectorModel<MedicinalProductPackagedPackageItem>>; @Validate(yup.lazy(() => ProdCharacteristic.schema())) public physicalCharacteristics?: FlatConvectorModel<ProdCharacteristic>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public otherCharacteristics?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ProductShelfLife.schema()))) public shelfLifeStorage?: Array<FlatConvectorModel<ProductShelfLife>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public manufacturer?: Array<FlatConvectorModel<Reference>>; //Organization } export class MedicinalProductPackaged extends DomainResource<MedicinalProductPackaged> { @Default('fhir.datatypes.MedicinalProductPackaged') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public subject?: Array<FlatConvectorModel<Reference>>; //MedicinalProduct @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public legalStatusOfSupply?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(MarketingStatus.schema()))) public marketingStatus?: Array<FlatConvectorModel<MarketingStatus>>; @Validate(yup.lazy(() => Reference.schema())) public marketingAuthorization?: FlatConvectorModel<Reference>; //MedicinalProductAuthorization @Validate(yup.lazy(() => yup.array(Reference.schema()))) public manufacturer?: Array<FlatConvectorModel<Reference>>; //Organization @Validate(yup.lazy(() => yup.array(MedicinalProductPackagedBatchIdentifier.schema()))) public batchIdentifier?: Array<FlatConvectorModel<MedicinalProductPackagedBatchIdentifier>>; @Validate(yup.lazy(() => yup.array(MedicinalProductPackagedPackageItem.schema()))) public packageItem?: Array<FlatConvectorModel<MedicinalProductPackagedPackageItem>>; } export class MedicinalProductPharmaceuticalCharacteristics extends BackboneElement { @Default('fhir.datatypes.MedicinalProductPharmaceutical.MedicinalProductPharmaceuticalCharacteristics') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public status?: FlatConvectorModel<CodeableConcept>; } export class MedicinalProductPharmaceuticalRouteOfAdministration extends BackboneElement { @Default('fhir.datatypes.MedicinalProductPharmaceutical.MedicinalProductPharmaceuticalRouteOfAdministration') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Quantity.schema())) public firstDose?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Quantity.schema())) public maxSingleDose?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Quantity.schema())) public maxDosePerDay?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Ratio.schema())) public maxDosePerTreatmentPeriod?: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => Duration.schema())) public maxTreatmentPeriod?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => yup.array(MedicinalProductPharmaceuticalRouteOfAdministrationTargetSpecies.schema()))) public targetSpecies?: Array<FlatConvectorModel<MedicinalProductPharmaceuticalRouteOfAdministrationTargetSpecies>>; } export class MedicinalProductPharmaceuticalRouteOfAdministrationTargetSpecies extends BackboneElement { @Default('fhir.datatypes.MedicinalProductPharmaceutical.MedicinalProductPharmaceuticalRouteOfAdministrationTargetSpecies') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(MedicinalProductPharmaceuticalRouteOfAdministrationTargetSpeciesWithdrawalPeriod.schema()))) public withdrawalPeriod?: Array<FlatConvectorModel<MedicinalProductPharmaceuticalRouteOfAdministrationTargetSpeciesWithdrawalPeriod>>; } export class MedicinalProductPharmaceuticalRouteOfAdministrationTargetSpeciesWithdrawalPeriod extends BackboneElement { @Default('fhir.datatypes.MedicinalProductPharmaceutical.MedicinalProductPharmaceuticalRouteOfAdministrationTargetSpeciesWithdrawalPeriod') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public tissue: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Quantity.schema())) public value: FlatConvectorModel<Quantity>; @Validate(yup.string()) public supportingInformation?: string; } export class MedicinalProductPharmaceutical extends DomainResource<MedicinalProductPharmaceutical> { @Default('fhir.datatypes.MedicinalProductPharmaceutical') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public administrableDoseForm: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public unitOfPresentation?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public ingredient?: Array<FlatConvectorModel<Reference>>; //MedicinalProductIngredient @Validate(yup.lazy(() => yup.array(Reference.schema()))) public device?: Array<FlatConvectorModel<Reference>>; //DeviceDefinition @Validate(yup.lazy(() => yup.array(MedicinalProductPharmaceuticalCharacteristics.schema()))) public characteristics?: Array<FlatConvectorModel<MedicinalProductPharmaceuticalCharacteristics>>; @Validate(yup.lazy(() => yup.array(MedicinalProductPharmaceuticalRouteOfAdministration.schema()))) public routeOfAdministration?: Array<FlatConvectorModel<MedicinalProductPharmaceuticalRouteOfAdministration>>; } export class MedicinalProductUndesirableEffect extends DomainResource<MedicinalProductUndesirableEffect> { @Default('fhir.datatypes.MedicinalProductUndesirableEffect') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public subject?: Array<FlatConvectorModel<Reference>>; //MedicinalProduct|Medication @Validate(yup.lazy(() => CodeableConcept.schema())) public symptomConditionEffect?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public classification?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public frequencyOfOccurrence?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Population.schema()))) public population?: Array<FlatConvectorModel<Population>>; } export class MessageDefinitionFocus extends BackboneElement { @Default('fhir.datatypes.MessageDefinition.MessageDefinitionFocus') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.string()) public profile?: string; //StructureDefinition @Required() @Validate(yup.number()) public min: number; @Validate(yup.string()) public max?: string; } export class MessageDefinitionAllowedResponse extends BackboneElement { @Default('fhir.datatypes.MessageDefinition.MessageDefinitionAllowedResponse') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public message: string; //MessageDefinition @Validate(yup.string()) public situation?: string; } export class MessageDefinition extends DomainResource<MessageDefinition> { @Default('fhir.datatypes.MessageDefinition') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Validate(yup.array(yup.string())) public replaces? : Array<string>; //MessageDefinition @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.string()) public base?: string; //MessageDefinition @Validate(yup.array(yup.string())) public parent? : Array<string>; //ActivityDefinition|PlanDefinition @Required() @Validate(yup.lazy(() => Coding.schema())) public eventCoding: FlatConvectorModel<Coding>; @Required() @Validate(yup.string()) public eventUri: string; @Validate(yup.string()) public category?: string; @Validate(yup.lazy(() => yup.array(MessageDefinitionFocus.schema()))) public focus?: Array<FlatConvectorModel<MessageDefinitionFocus>>; @Validate(yup.string()) public responseRequired?: string; @Validate(yup.lazy(() => yup.array(MessageDefinitionAllowedResponse.schema()))) public allowedResponse?: Array<FlatConvectorModel<MessageDefinitionAllowedResponse>>; @Validate(yup.array(yup.string())) public graph? : Array<string>; //GraphDefinition } export class MessageHeaderDestination extends BackboneElement { @Default('fhir.datatypes.MessageHeader.MessageHeaderDestination') @ReadOnly() public readonly type: string; @Validate(yup.string()) public name?: string; @Validate(yup.lazy(() => Reference.schema())) public target?: FlatConvectorModel<Reference>; //Device @Required() @Validate(yup.string()) public endpoint: string; @Validate(yup.lazy(() => Reference.schema())) public receiver?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization } export class MessageHeaderSource extends BackboneElement { @Default('fhir.datatypes.MessageHeader.MessageHeaderSource') @ReadOnly() public readonly type: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public software?: string; @Validate(yup.string()) public version?: string; @Validate(yup.lazy(() => ContactPoint.schema())) public contact?: FlatConvectorModel<ContactPoint>; @Required() @Validate(yup.string()) public endpoint: string; } export class MessageHeaderResponse extends BackboneElement { @Default('fhir.datatypes.MessageHeader.MessageHeaderResponse') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public identifier: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.lazy(() => Reference.schema())) public details?: FlatConvectorModel<Reference>; //OperationOutcome } export class MessageHeader extends DomainResource<MessageHeader> { @Default('fhir.datatypes.MessageHeader') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Coding.schema())) public eventCoding: FlatConvectorModel<Coding>; @Required() @Validate(yup.string()) public eventUri: string; @Validate(yup.lazy(() => yup.array(MessageHeaderDestination.schema()))) public destination?: Array<FlatConvectorModel<MessageHeaderDestination>>; @Validate(yup.lazy(() => Reference.schema())) public sender?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => Reference.schema())) public enterer?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => Reference.schema())) public author?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Required() @Validate(yup.lazy(() => MessageHeaderSource.schema())) public source: FlatConvectorModel<MessageHeaderSource>; @Validate(yup.lazy(() => Reference.schema())) public responsible?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => CodeableConcept.schema())) public reason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => MessageHeaderResponse.schema())) public response?: FlatConvectorModel<MessageHeaderResponse>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public focus?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.string()) public definition?: string; //MessageDefinition } export class MetadataResource extends DomainResource<MetadataResource> { @Default('fhir.datatypes.MetadataResource') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; } export class MolecularSequenceReferenceSeq extends BackboneElement { @Default('fhir.datatypes.MolecularSequence.MolecularSequenceReferenceSeq') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public chromosome?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public genomeBuild?: string; @Validate(yup.string()) public orientation?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public referenceSeqId?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public referenceSeqPointer?: FlatConvectorModel<Reference>; //MolecularSequence @Validate(yup.string()) public referenceSeqString?: string; @Validate(yup.string()) public strand?: string; @Validate(yup.number()) public windowStart?: number; @Validate(yup.number()) public windowEnd?: number; } export class MolecularSequenceVariant extends BackboneElement { @Default('fhir.datatypes.MolecularSequence.MolecularSequenceVariant') @ReadOnly() public readonly type: string; @Validate(yup.number()) public start?: number; @Validate(yup.number()) public end?: number; @Validate(yup.string()) public observedAllele?: string; @Validate(yup.string()) public referenceAllele?: string; @Validate(yup.string()) public cigar?: string; @Validate(yup.lazy(() => Reference.schema())) public variantPointer?: FlatConvectorModel<Reference>; //Observation } export class MolecularSequenceQuality extends BackboneElement { @Default('fhir.datatypes.MolecularSequence.MolecularSequenceQuality') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public standardSequence?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public start?: number; @Validate(yup.number()) public end?: number; @Validate(yup.lazy(() => Quantity.schema())) public score?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => CodeableConcept.schema())) public method?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public truthTP?: number; @Validate(yup.number()) public queryTP?: number; @Validate(yup.number()) public truthFN?: number; @Validate(yup.number()) public queryFP?: number; @Validate(yup.number()) public gtFP?: number; @Validate(yup.number()) public precision?: number; @Validate(yup.number()) public recall?: number; @Validate(yup.number()) public fScore?: number; @Validate(yup.lazy(() => MolecularSequenceQualityRoc.schema())) public roc?: FlatConvectorModel<MolecularSequenceQualityRoc>; } export class MolecularSequenceQualityRoc extends BackboneElement { @Default('fhir.datatypes.MolecularSequence.MolecularSequenceQualityRoc') @ReadOnly() public readonly type: string; @Validate(yup.array(yup.number())) public score? : Array<number>; @Validate(yup.array(yup.number())) public numTP? : Array<number>; @Validate(yup.array(yup.number())) public numFP? : Array<number>; @Validate(yup.array(yup.number())) public numFN? : Array<number>; @Validate(yup.array(yup.number())) public precision? : Array<number>; @Validate(yup.array(yup.number())) public sensitivity? : Array<number>; @Validate(yup.array(yup.number())) public fMeasure? : Array<number>; } export class MolecularSequenceRepository extends BackboneElement { @Default('fhir.datatypes.MolecularSequence.MolecularSequenceRepository') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public url?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public datasetId?: string; @Validate(yup.string()) public variantsetId?: string; @Validate(yup.string()) public readsetId?: string; } export class MolecularSequenceStructureVariant extends BackboneElement { @Default('fhir.datatypes.MolecularSequence.MolecularSequenceStructureVariant') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public variantType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public exact?: boolean; @Validate(yup.number()) public length?: number; @Validate(yup.lazy(() => MolecularSequenceStructureVariantOuter.schema())) public outer?: FlatConvectorModel<MolecularSequenceStructureVariantOuter>; @Validate(yup.lazy(() => MolecularSequenceStructureVariantInner.schema())) public inner?: FlatConvectorModel<MolecularSequenceStructureVariantInner>; } export class MolecularSequenceStructureVariantOuter extends BackboneElement { @Default('fhir.datatypes.MolecularSequence.MolecularSequenceStructureVariantOuter') @ReadOnly() public readonly type: string; @Validate(yup.number()) public start?: number; @Validate(yup.number()) public end?: number; } export class MolecularSequenceStructureVariantInner extends BackboneElement { @Default('fhir.datatypes.MolecularSequence.MolecularSequenceStructureVariantInner') @ReadOnly() public readonly type: string; @Validate(yup.number()) public start?: number; @Validate(yup.number()) public end?: number; } export class MolecularSequence extends DomainResource<MolecularSequence> { @Default('fhir.datatypes.MolecularSequence') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public type_?: string; @Required() @Validate(yup.number()) public coordinateSystem: number; @Validate(yup.lazy(() => Reference.schema())) public patient?: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => Reference.schema())) public specimen?: FlatConvectorModel<Reference>; //Specimen @Validate(yup.lazy(() => Reference.schema())) public device?: FlatConvectorModel<Reference>; //Device @Validate(yup.lazy(() => Reference.schema())) public performer?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Quantity.schema())) public quantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => MolecularSequenceReferenceSeq.schema())) public referenceSeq?: FlatConvectorModel<MolecularSequenceReferenceSeq>; @Validate(yup.lazy(() => yup.array(MolecularSequenceVariant.schema()))) public variant?: Array<FlatConvectorModel<MolecularSequenceVariant>>; @Validate(yup.string()) public observedSeq?: string; @Validate(yup.lazy(() => yup.array(MolecularSequenceQuality.schema()))) public quality?: Array<FlatConvectorModel<MolecularSequenceQuality>>; @Validate(yup.number()) public readCoverage?: number; @Validate(yup.lazy(() => yup.array(MolecularSequenceRepository.schema()))) public repository?: Array<FlatConvectorModel<MolecularSequenceRepository>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public pointer?: Array<FlatConvectorModel<Reference>>; //MolecularSequence @Validate(yup.lazy(() => yup.array(MolecularSequenceStructureVariant.schema()))) public structureVariant?: Array<FlatConvectorModel<MolecularSequenceStructureVariant>>; } export class MoneyQuantity extends DomainResource<MoneyQuantity> { @Default('fhir.datatypes.MoneyQuantity') @ReadOnly() public readonly type: string; } export class NamingSystemUniqueId extends BackboneElement { @Default('fhir.datatypes.NamingSystem.NamingSystemUniqueId') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Required() @Validate(yup.string()) public value: string; @Validate(yup.boolean()) public preferred?: boolean; @Validate(yup.string()) public comment?: string; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; } export class NamingSystem extends DomainResource<NamingSystem> { @Default('fhir.datatypes.NamingSystem') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.string()) public kind: string; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public responsible?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public usage?: string; @Validate(yup.lazy(() => yup.array(NamingSystemUniqueId.schema()))) public uniqueId?: Array<FlatConvectorModel<NamingSystemUniqueId>>; } export class NutritionOrderOralDiet extends BackboneElement { @Default('fhir.datatypes.NutritionOrder.NutritionOrderOralDiet') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Timing.schema()))) public schedule?: Array<FlatConvectorModel<Timing>>; @Validate(yup.lazy(() => yup.array(NutritionOrderOralDietNutrient.schema()))) public nutrient?: Array<FlatConvectorModel<NutritionOrderOralDietNutrient>>; @Validate(yup.lazy(() => yup.array(NutritionOrderOralDietTexture.schema()))) public texture?: Array<FlatConvectorModel<NutritionOrderOralDietTexture>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public fluidConsistencyType?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public instruction?: string; } export class NutritionOrderOralDietNutrient extends BackboneElement { @Default('fhir.datatypes.NutritionOrder.NutritionOrderOralDietNutrient') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public modifier?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public amount?: FlatConvectorModel<SimpleQuantity>; } export class NutritionOrderOralDietTexture extends BackboneElement { @Default('fhir.datatypes.NutritionOrder.NutritionOrderOralDietTexture') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public modifier?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public foodType?: FlatConvectorModel<CodeableConcept>; } export class NutritionOrderSupplement extends BackboneElement { @Default('fhir.datatypes.NutritionOrder.NutritionOrderSupplement') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public productName?: string; @Validate(yup.lazy(() => yup.array(Timing.schema()))) public schedule?: Array<FlatConvectorModel<Timing>>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.string()) public instruction?: string; } export class NutritionOrderEnteralFormula extends BackboneElement { @Default('fhir.datatypes.NutritionOrder.NutritionOrderEnteralFormula') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public baseFormulaType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public baseFormulaProductName?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public additiveType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public additiveProductName?: string; @Validate(yup.lazy(() => SimpleQuantity.schema())) public caloricDensity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => CodeableConcept.schema())) public routeofAdministration?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(NutritionOrderEnteralFormulaAdministration.schema()))) public administration?: Array<FlatConvectorModel<NutritionOrderEnteralFormulaAdministration>>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public maxVolumeToDeliver?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.string()) public administrationInstruction?: string; } export class NutritionOrderEnteralFormulaAdministration extends BackboneElement { @Default('fhir.datatypes.NutritionOrder.NutritionOrderEnteralFormulaAdministration') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Timing.schema())) public schedule?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public rateQuantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => Ratio.schema())) public rateRatio?: FlatConvectorModel<Ratio>; } export class NutritionOrder extends DomainResource<NutritionOrder> { @Default('fhir.datatypes.NutritionOrder') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.array(yup.string())) public instantiatesCanonical? : Array<string>; //ActivityDefinition|PlanDefinition @Validate(yup.array(yup.string())) public instantiatesUri? : Array<string>; @Validate(yup.array(yup.string())) public instantiates? : Array<string>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.string()) public intent: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public dateTime: date; @Validate(yup.lazy(() => Reference.schema())) public orderer?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => yup.array(Reference.schema()))) public allergyIntolerance?: Array<FlatConvectorModel<Reference>>; //AllergyIntolerance @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public foodPreferenceModifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public excludeFoodModifier?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => NutritionOrderOralDiet.schema())) public oralDiet?: FlatConvectorModel<NutritionOrderOralDiet>; @Validate(yup.lazy(() => yup.array(NutritionOrderSupplement.schema()))) public supplement?: Array<FlatConvectorModel<NutritionOrderSupplement>>; @Validate(yup.lazy(() => NutritionOrderEnteralFormula.schema())) public enteralFormula?: FlatConvectorModel<NutritionOrderEnteralFormula>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class ObservationReferenceRange extends BackboneElement { @Default('fhir.datatypes.Observation.ObservationReferenceRange') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => SimpleQuantity.schema())) public low?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public high?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public appliesTo?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Range.schema())) public age?: FlatConvectorModel<Range>; @Validate(yup.string()) public text?: string; } export class ObservationComponent extends BackboneElement { @Default('fhir.datatypes.Observation.ObservationComponent') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Quantity.schema())) public valueQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => CodeableConcept.schema())) public valueCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public valueString?: string; @Validate(yup.boolean()) public valueBoolean?: boolean; @Validate(yup.number()) public valueInteger?: number; @Validate(yup.lazy(() => Range.schema())) public valueRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => Ratio.schema())) public valueRatio?: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => SampledData.schema())) public valueSampledData?: FlatConvectorModel<SampledData>; @Validate(yup.string()) public valueTime?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public valuePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => CodeableConcept.schema())) public dataAbsentReason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public interpretation?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ObservationReferenceRange.schema()))) public referenceRange?: Array<FlatConvectorModel<ObservationReferenceRange>>; } export class Observation extends DomainResource<Observation> { @Default('fhir.datatypes.Observation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //CarePlan|DeviceRequest|ImmunizationRecommendation|MedicationRequest|NutritionOrder|ServiceRequest @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //MedicationAdministration|MedicationDispense|MedicationStatement|Procedure|Immunization|ImagingStudy @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Group|Device|Location @Validate(yup.lazy(() => yup.array(Reference.schema()))) public focus?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public effectiveDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Timing.schema())) public effectiveTiming?: FlatConvectorModel<Timing>; @Validate(yup.string()) public effectiveInstant?: string; @Validate(yup.string()) public issued?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public performer?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole|Organization|CareTeam|Patient|RelatedPerson @Validate(yup.lazy(() => Quantity.schema())) public valueQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => CodeableConcept.schema())) public valueCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public valueString?: string; @Validate(yup.boolean()) public valueBoolean?: boolean; @Validate(yup.number()) public valueInteger?: number; @Validate(yup.lazy(() => Range.schema())) public valueRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => Ratio.schema())) public valueRatio?: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => SampledData.schema())) public valueSampledData?: FlatConvectorModel<SampledData>; @Validate(yup.string()) public valueTime?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public valuePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => CodeableConcept.schema())) public dataAbsentReason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public interpretation?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public bodySite?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public method?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public specimen?: FlatConvectorModel<Reference>; //Specimen @Validate(yup.lazy(() => Reference.schema())) public device?: FlatConvectorModel<Reference>; //Device|DeviceMetric @Validate(yup.lazy(() => yup.array(ObservationReferenceRange.schema()))) public referenceRange?: Array<FlatConvectorModel<ObservationReferenceRange>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public hasMember?: Array<FlatConvectorModel<Reference>>; //Observation|QuestionnaireResponse|MolecularSequence @Validate(yup.lazy(() => yup.array(Reference.schema()))) public derivedFrom?: Array<FlatConvectorModel<Reference>>; //DocumentReference|ImagingStudy|Media|QuestionnaireResponse|Observation|MolecularSequence @Validate(yup.lazy(() => yup.array(ObservationComponent.schema()))) public component?: Array<FlatConvectorModel<ObservationComponent>>; } export class ObservationDefinitionQuantitativeDetails extends BackboneElement { @Default('fhir.datatypes.ObservationDefinition.ObservationDefinitionQuantitativeDetails') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public customaryUnit?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public unit?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public conversionFactor?: number; @Validate(yup.number()) public decimalPrecision?: number; } export class ObservationDefinitionQualifiedInterval extends BackboneElement { @Default('fhir.datatypes.ObservationDefinition.ObservationDefinitionQualifiedInterval') @ReadOnly() public readonly type: string; @Validate(yup.string()) public category?: string; @Validate(yup.lazy(() => Range.schema())) public range?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => CodeableConcept.schema())) public context?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public appliesTo?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public gender?: string; @Validate(yup.lazy(() => Range.schema())) public age?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => Range.schema())) public gestationalAge?: FlatConvectorModel<Range>; @Validate(yup.string()) public condition?: string; } export class ObservationDefinition extends DomainResource<ObservationDefinition> { @Default('fhir.datatypes.ObservationDefinition') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.array(yup.string())) public permittedDataType? : Array<string>; @Validate(yup.boolean()) public multipleResultsAllowed?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public method?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public preferredReportName?: string; @Validate(yup.lazy(() => ObservationDefinitionQuantitativeDetails.schema())) public quantitativeDetails?: FlatConvectorModel<ObservationDefinitionQuantitativeDetails>; @Validate(yup.lazy(() => yup.array(ObservationDefinitionQualifiedInterval.schema()))) public qualifiedInterval?: Array<FlatConvectorModel<ObservationDefinitionQualifiedInterval>>; @Validate(yup.lazy(() => Reference.schema())) public validCodedValueSet?: FlatConvectorModel<Reference>; //ValueSet @Validate(yup.lazy(() => Reference.schema())) public normalCodedValueSet?: FlatConvectorModel<Reference>; //ValueSet @Validate(yup.lazy(() => Reference.schema())) public abnormalCodedValueSet?: FlatConvectorModel<Reference>; //ValueSet @Validate(yup.lazy(() => Reference.schema())) public criticalCodedValueSet?: FlatConvectorModel<Reference>; //ValueSet } export class OperationDefinitionParameter extends BackboneElement { @Default('fhir.datatypes.OperationDefinition.OperationDefinitionParameter') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Required() @Validate(yup.string()) public use: string; @Required() @Validate(yup.number()) public min: number; @Required() @Validate(yup.string()) public max: string; @Validate(yup.string()) public documentation?: string; @Validate(yup.string()) public type_?: string; @Validate(yup.array(yup.string())) public targetProfile? : Array<string>; //StructureDefinition @Validate(yup.string()) public searchType?: string; @Validate(yup.lazy(() => OperationDefinitionParameterBinding.schema())) public binding?: FlatConvectorModel<OperationDefinitionParameterBinding>; @Validate(yup.lazy(() => yup.array(OperationDefinitionParameterReferencedFrom.schema()))) public referencedFrom?: Array<FlatConvectorModel<OperationDefinitionParameterReferencedFrom>>; @Validate(yup.lazy(() => yup.array(OperationDefinitionParameter.schema()))) public part?: Array<FlatConvectorModel<OperationDefinitionParameter>>; } export class OperationDefinitionParameterBinding extends BackboneElement { @Default('fhir.datatypes.OperationDefinition.OperationDefinitionParameterBinding') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public strength: string; @Required() @Validate(yup.string()) public valueSet: string; //ValueSet } export class OperationDefinitionParameterReferencedFrom extends BackboneElement { @Default('fhir.datatypes.OperationDefinition.OperationDefinitionParameterReferencedFrom') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public source: string; @Validate(yup.string()) public sourceId?: string; } export class OperationDefinitionOverload extends BackboneElement { @Default('fhir.datatypes.OperationDefinition.OperationDefinitionOverload') @ReadOnly() public readonly type: string; @Validate(yup.array(yup.string())) public parameterName? : Array<string>; @Validate(yup.string()) public comment?: string; } export class OperationDefinition extends DomainResource<OperationDefinition> { @Default('fhir.datatypes.OperationDefinition') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.string()) public version?: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.string()) public kind: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.boolean()) public affectsState?: boolean; @Required() @Validate(yup.string()) public code: string; @Validate(yup.string()) public comment?: string; @Validate(yup.string()) public base?: string; //OperationDefinition @Validate(yup.array(yup.string())) public resource? : Array<string>; @Required() @Validate(yup.boolean()) public system: boolean; @Required() @Validate(yup.boolean()) public type_: boolean; @Required() @Validate(yup.boolean()) public instance: boolean; @Validate(yup.string()) public inputProfile?: string; //StructureDefinition @Validate(yup.string()) public outputProfile?: string; //StructureDefinition @Validate(yup.lazy(() => yup.array(OperationDefinitionParameter.schema()))) public parameter?: Array<FlatConvectorModel<OperationDefinitionParameter>>; @Validate(yup.lazy(() => yup.array(OperationDefinitionOverload.schema()))) public overload?: Array<FlatConvectorModel<OperationDefinitionOverload>>; } export class OperationOutcomeIssue extends BackboneElement { @Default('fhir.datatypes.OperationOutcome.OperationOutcomeIssue') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public severity: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public details?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public diagnostics?: string; @Validate(yup.array(yup.string())) public location? : Array<string>; @Validate(yup.array(yup.string())) public expression? : Array<string>; } export class OperationOutcome extends DomainResource<OperationOutcome> { @Default('fhir.datatypes.OperationOutcome') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(OperationOutcomeIssue.schema()))) public issue?: Array<FlatConvectorModel<OperationOutcomeIssue>>; } export class OrganizationContact extends BackboneElement { @Default('fhir.datatypes.Organization.OrganizationContact') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public purpose?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => HumanName.schema())) public name?: FlatConvectorModel<HumanName>; @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.lazy(() => Address.schema())) public address?: FlatConvectorModel<Address>; } export class OrganizationAffiliation extends DomainResource<OrganizationAffiliation> { @Default('fhir.datatypes.OrganizationAffiliation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.boolean()) public active?: boolean; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Reference.schema())) public organization?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public participatingOrganization?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(Reference.schema()))) public network?: Array<FlatConvectorModel<Reference>>; //Organization @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public code?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public specialty?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public location?: Array<FlatConvectorModel<Reference>>; //Location @Validate(yup.lazy(() => yup.array(Reference.schema()))) public healthcareService?: Array<FlatConvectorModel<Reference>>; //HealthcareService @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public endpoint?: Array<FlatConvectorModel<Reference>>; //Endpoint } export class ParameterDefinition extends DomainResource<ParameterDefinition> { @Default('fhir.datatypes.ParameterDefinition') @ReadOnly() public readonly type: string; @Validate(yup.string()) public name?: string; @Required() @Validate(yup.string()) public use: string; @Validate(yup.number()) public min?: number; @Validate(yup.string()) public max?: string; @Validate(yup.string()) public documentation?: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public profile?: string; //StructureDefinition } export class Parameters extends DomainResource<Parameters> { @Default('fhir.datatypes.Parameters') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(ParametersParameter.schema()))) public parameter?: Array<FlatConvectorModel<ParametersParameter>>; } export class PatientContact extends BackboneElement { @Default('fhir.datatypes.Patient.PatientContact') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public relationship?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => HumanName.schema())) public name?: FlatConvectorModel<HumanName>; @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.lazy(() => Address.schema())) public address?: FlatConvectorModel<Address>; @Validate(yup.string()) public gender?: string; @Validate(yup.lazy(() => Reference.schema())) public organization?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; } export class PatientCommunication extends BackboneElement { @Default('fhir.datatypes.Patient.PatientCommunication') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public language: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public preferred?: boolean; } export class PatientLink extends BackboneElement { @Default('fhir.datatypes.Patient.PatientLink') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public other: FlatConvectorModel<Reference>; //Patient|RelatedPerson @Required() @Validate(yup.string()) public type_: string; } export class Patient extends DomainResource<Patient> { @Default('fhir.datatypes.Patient') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.boolean()) public active?: boolean; @Validate(yup.lazy(() => yup.array(HumanName.schema()))) public name?: Array<FlatConvectorModel<HumanName>>; @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.string()) public gender?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public birthDate?: date; @Validate(yup.boolean()) public deceasedBoolean?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public deceasedDateTime?: date; @Validate(yup.lazy(() => yup.array(Address.schema()))) public address?: Array<FlatConvectorModel<Address>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public maritalStatus?: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public multipleBirthBoolean?: boolean; @Validate(yup.number()) public multipleBirthInteger?: number; // @Validate(yup.lazy(() => yup.array(Attachment.schema()))) public photo?: Array<FlatConvectorModel<Attachment>>; @Validate(yup.lazy(() => yup.array(PatientContact.schema()))) public contact?: Array<FlatConvectorModel<PatientContact>>; @Validate(yup.lazy(() => yup.array(PatientCommunication.schema()))) public communication?: Array<FlatConvectorModel<PatientCommunication>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public generalPractitioner?: Array<FlatConvectorModel<Reference>>; //Organization|Practitioner|PractitionerRole @Validate(yup.lazy(() => Reference.schema())) public managingOrganization?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(PatientLink.schema()))) public link?: Array<FlatConvectorModel<PatientLink>>; } export class PaymentNotice extends DomainResource<PaymentNotice> { @Default('fhir.datatypes.PaymentNotice') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => Reference.schema())) public request?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => Reference.schema())) public response?: FlatConvectorModel<Reference>; //Any @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created: date; @Validate(yup.lazy(() => Reference.schema())) public provider?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Required() @Validate(yup.lazy(() => Reference.schema())) public payment: FlatConvectorModel<Reference>; //PaymentReconciliation @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public paymentDate?: date; @Validate(yup.lazy(() => Reference.schema())) public payee?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Required() @Validate(yup.lazy(() => Reference.schema())) public recipient: FlatConvectorModel<Reference>; //Organization @Required() @Validate(yup.lazy(() => Money.schema())) public amount: FlatConvectorModel<Money>; @Validate(yup.lazy(() => CodeableConcept.schema())) public paymentStatus?: FlatConvectorModel<CodeableConcept>; } export class PaymentReconciliationDetail extends BackboneElement { @Default('fhir.datatypes.PaymentReconciliation.PaymentReconciliationDetail') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => Identifier.schema())) public predecessor?: FlatConvectorModel<Identifier>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public request?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => Reference.schema())) public submitter?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => Reference.schema())) public response?: FlatConvectorModel<Reference>; //Any @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.lazy(() => Reference.schema())) public responsible?: FlatConvectorModel<Reference>; //PractitionerRole @Validate(yup.lazy(() => Reference.schema())) public payee?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => Money.schema())) public amount?: FlatConvectorModel<Money>; } export class PaymentReconciliationProcessNote extends BackboneElement { @Default('fhir.datatypes.PaymentReconciliation.PaymentReconciliationProcessNote') @ReadOnly() public readonly type: string; @Validate(yup.string()) public type_?: string; @Validate(yup.string()) public text?: string; } export class PaymentReconciliation extends DomainResource<PaymentReconciliation> { @Default('fhir.datatypes.PaymentReconciliation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created: date; @Validate(yup.lazy(() => Reference.schema())) public paymentIssuer?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public request?: FlatConvectorModel<Reference>; //Task @Validate(yup.lazy(() => Reference.schema())) public requestor?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.string()) public outcome?: string; @Validate(yup.string()) public disposition?: string; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public paymentDate: date; @Required() @Validate(yup.lazy(() => Money.schema())) public paymentAmount: FlatConvectorModel<Money>; @Validate(yup.lazy(() => Identifier.schema())) public paymentIdentifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => yup.array(PaymentReconciliationDetail.schema()))) public detail?: Array<FlatConvectorModel<PaymentReconciliationDetail>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public formCode?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(PaymentReconciliationProcessNote.schema()))) public processNote?: Array<FlatConvectorModel<PaymentReconciliationProcessNote>>; } export class PersonLink extends BackboneElement { @Default('fhir.datatypes.Person.PersonLink') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public target: FlatConvectorModel<Reference>; //Patient|Practitioner|RelatedPerson|Person @Validate(yup.string()) public assurance?: string; } export class Person extends DomainResource<Person> { @Default('fhir.datatypes.Person') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(HumanName.schema()))) public name?: Array<FlatConvectorModel<HumanName>>; @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.string()) public gender?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public birthDate?: date; @Validate(yup.lazy(() => yup.array(Address.schema()))) public address?: Array<FlatConvectorModel<Address>>; // @Validate(yup.lazy(() => Attachment.schema())) public photo?: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => Reference.schema())) public managingOrganization?: FlatConvectorModel<Reference>; //Organization @Validate(yup.boolean()) public active?: boolean; @Validate(yup.lazy(() => yup.array(PersonLink.schema()))) public link?: Array<FlatConvectorModel<PersonLink>>; } export class PlanDefinitionGoal extends BackboneElement { @Default('fhir.datatypes.PlanDefinition.PlanDefinitionGoal') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public description: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public priority?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public start?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public addresses?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public documentation?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.lazy(() => yup.array(PlanDefinitionGoalTarget.schema()))) public target?: Array<FlatConvectorModel<PlanDefinitionGoalTarget>>; } export class PlanDefinitionGoalTarget extends BackboneElement { @Default('fhir.datatypes.PlanDefinition.PlanDefinitionGoalTarget') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public measure?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Quantity.schema())) public detailQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Range.schema())) public detailRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => CodeableConcept.schema())) public detailCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Duration.schema())) public due?: FlatConvectorModel<Duration>; } export class PlanDefinitionAction extends BackboneElement { @Default('fhir.datatypes.PlanDefinition.PlanDefinitionAction') @ReadOnly() public readonly type: string; @Validate(yup.string()) public prefix?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public textEquivalent?: string; @Validate(yup.string()) public priority?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public code?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reason?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public documentation?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.array(yup.string())) public goalId? : Array<string>; @Validate(yup.lazy(() => CodeableConcept.schema())) public subjectCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subjectReference?: FlatConvectorModel<Reference>; //Group @Validate(yup.lazy(() => yup.array(TriggerDefinition.schema()))) public trigger?: Array<FlatConvectorModel<TriggerDefinition>>; @Validate(yup.lazy(() => yup.array(PlanDefinitionActionCondition.schema()))) public condition?: Array<FlatConvectorModel<PlanDefinitionActionCondition>>; @Validate(yup.lazy(() => yup.array(DataRequirement.schema()))) public input?: Array<FlatConvectorModel<DataRequirement>>; @Validate(yup.lazy(() => yup.array(DataRequirement.schema()))) public output?: Array<FlatConvectorModel<DataRequirement>>; @Validate(yup.lazy(() => yup.array(PlanDefinitionActionRelatedAction.schema()))) public relatedAction?: Array<FlatConvectorModel<PlanDefinitionActionRelatedAction>>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public timingDateTime?: date; @Validate(yup.lazy(() => Age.schema())) public timingAge?: FlatConvectorModel<Age>; @Validate(yup.lazy(() => Period.schema())) public timingPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Duration.schema())) public timingDuration?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => Range.schema())) public timingRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => Timing.schema())) public timingTiming?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => yup.array(PlanDefinitionActionParticipant.schema()))) public participant?: Array<FlatConvectorModel<PlanDefinitionActionParticipant>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public groupingBehavior?: string; @Validate(yup.string()) public selectionBehavior?: string; @Validate(yup.string()) public requiredBehavior?: string; @Validate(yup.string()) public precheckBehavior?: string; @Validate(yup.string()) public cardinalityBehavior?: string; @Validate(yup.string()) public definitionCanonical?: string; //ActivityDefinition|PlanDefinition|Questionnaire @Validate(yup.string()) public definitionUri?: string; @Validate(yup.string()) public transform?: string; //StructureMap @Validate(yup.lazy(() => yup.array(PlanDefinitionActionDynamicValue.schema()))) public dynamicValue?: Array<FlatConvectorModel<PlanDefinitionActionDynamicValue>>; @Validate(yup.lazy(() => yup.array(PlanDefinitionAction.schema()))) public action?: Array<FlatConvectorModel<PlanDefinitionAction>>; } export class PlanDefinitionActionCondition extends BackboneElement { @Default('fhir.datatypes.PlanDefinition.PlanDefinitionActionCondition') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public kind: string; @Validate(yup.lazy(() => Expression.schema())) public expression?: FlatConvectorModel<Expression>; } export class PlanDefinitionActionRelatedAction extends BackboneElement { @Default('fhir.datatypes.PlanDefinition.PlanDefinitionActionRelatedAction') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public actionId: string; @Required() @Validate(yup.string()) public relationship: string; @Validate(yup.lazy(() => Duration.schema())) public offsetDuration?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => Range.schema())) public offsetRange?: FlatConvectorModel<Range>; } export class PlanDefinitionActionParticipant extends BackboneElement { @Default('fhir.datatypes.PlanDefinition.PlanDefinitionActionParticipant') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public role?: FlatConvectorModel<CodeableConcept>; } export class PlanDefinitionActionDynamicValue extends BackboneElement { @Default('fhir.datatypes.PlanDefinition.PlanDefinitionActionDynamicValue') @ReadOnly() public readonly type: string; @Validate(yup.string()) public path?: string; @Validate(yup.lazy(() => Expression.schema())) public expression?: FlatConvectorModel<Expression>; } export class PlanDefinition extends DomainResource<PlanDefinition> { @Default('fhir.datatypes.PlanDefinition') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public subtitle?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public subjectCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subjectReference?: FlatConvectorModel<Reference>; //Group @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public usage?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public topic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public author?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public editor?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public reviewer?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public endorser?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public relatedArtifact?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.array(yup.string())) public library? : Array<string>; //Library @Validate(yup.lazy(() => yup.array(PlanDefinitionGoal.schema()))) public goal?: Array<FlatConvectorModel<PlanDefinitionGoal>>; @Validate(yup.lazy(() => yup.array(PlanDefinitionAction.schema()))) public action?: Array<FlatConvectorModel<PlanDefinitionAction>>; } export class Population extends DomainResource<Population> { @Default('fhir.datatypes.Population') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Range.schema())) public ageRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => CodeableConcept.schema())) public ageCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public gender?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public race?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public physiologicalCondition?: FlatConvectorModel<CodeableConcept>; } export class PractitionerQualification extends BackboneElement { @Default('fhir.datatypes.Practitioner.PractitionerQualification') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Reference.schema())) public issuer?: FlatConvectorModel<Reference>; //Organization } export class Practitioner extends DomainResource<Practitioner> { @Default('fhir.datatypes.Practitioner') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.boolean()) public active?: boolean; @Validate(yup.lazy(() => yup.array(HumanName.schema()))) public name?: Array<FlatConvectorModel<HumanName>>; @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.lazy(() => yup.array(Address.schema()))) public address?: Array<FlatConvectorModel<Address>>; @Validate(yup.string()) public gender?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public birthDate?: date; // @Validate(yup.lazy(() => yup.array(Attachment.schema()))) public photo?: Array<FlatConvectorModel<Attachment>>; @Validate(yup.lazy(() => yup.array(PractitionerQualification.schema()))) public qualification?: Array<FlatConvectorModel<PractitionerQualification>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public communication?: Array<FlatConvectorModel<CodeableConcept>>; } export class PractitionerRoleAvailableTime extends BackboneElement { @Default('fhir.datatypes.PractitionerRole.PractitionerRoleAvailableTime') @ReadOnly() public readonly type: string; @Validate(yup.array(yup.string())) public daysOfWeek? : Array<string>; @Validate(yup.boolean()) public allDay?: boolean; @Validate(yup.string()) public availableStartTime?: string; @Validate(yup.string()) public availableEndTime?: string; } export class PractitionerRoleNotAvailable extends BackboneElement { @Default('fhir.datatypes.PractitionerRole.PractitionerRoleNotAvailable') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public description: string; @Validate(yup.lazy(() => Period.schema())) public during?: FlatConvectorModel<Period>; } export class PractitionerRole extends DomainResource<PractitionerRole> { @Default('fhir.datatypes.PractitionerRole') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.boolean()) public active?: boolean; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Reference.schema())) public practitioner?: FlatConvectorModel<Reference>; //Practitioner @Validate(yup.lazy(() => Reference.schema())) public organization?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public code?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public specialty?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public location?: Array<FlatConvectorModel<Reference>>; //Location @Validate(yup.lazy(() => yup.array(Reference.schema()))) public healthcareService?: Array<FlatConvectorModel<Reference>>; //HealthcareService @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.lazy(() => yup.array(PractitionerRoleAvailableTime.schema()))) public availableTime?: Array<FlatConvectorModel<PractitionerRoleAvailableTime>>; @Validate(yup.lazy(() => yup.array(PractitionerRoleNotAvailable.schema()))) public notAvailable?: Array<FlatConvectorModel<PractitionerRoleNotAvailable>>; @Validate(yup.string()) public availabilityExceptions?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public endpoint?: Array<FlatConvectorModel<Reference>>; //Endpoint } export class ProcedurePerformer extends BackboneElement { @Default('fhir.datatypes.Procedure.ProcedurePerformer') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public function_?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public actor: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|Patient|RelatedPerson|Device @Validate(yup.lazy(() => Reference.schema())) public onBehalfOf?: FlatConvectorModel<Reference>; //Organization } export class ProcedureFocalDevice extends BackboneElement { @Default('fhir.datatypes.Procedure.ProcedureFocalDevice') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public action?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public manipulated: FlatConvectorModel<Reference>; //Device } export class Procedure extends DomainResource<Procedure> { @Default('fhir.datatypes.Procedure') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.array(yup.string())) public instantiatesCanonical? : Array<string>; //PlanDefinition|ActivityDefinition|Measure|OperationDefinition|Questionnaire @Validate(yup.array(yup.string())) public instantiatesUri? : Array<string>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //CarePlan|ServiceRequest @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //Procedure|Observation|MedicationAdministration @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public statusReason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public performedDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public performedPeriod?: FlatConvectorModel<Period>; @Validate(yup.string()) public performedString?: string; @Validate(yup.lazy(() => Age.schema())) public performedAge?: FlatConvectorModel<Age>; @Validate(yup.lazy(() => Range.schema())) public performedRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => Reference.schema())) public recorder?: FlatConvectorModel<Reference>; //Patient|RelatedPerson|Practitioner|PractitionerRole @Validate(yup.lazy(() => Reference.schema())) public asserter?: FlatConvectorModel<Reference>; //Patient|RelatedPerson|Practitioner|PractitionerRole @Validate(yup.lazy(() => yup.array(ProcedurePerformer.schema()))) public performer?: Array<FlatConvectorModel<ProcedurePerformer>>; @Validate(yup.lazy(() => Reference.schema())) public location?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|Procedure|DiagnosticReport|DocumentReference @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public bodySite?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public outcome?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public report?: Array<FlatConvectorModel<Reference>>; //DiagnosticReport|DocumentReference|Composition @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public complication?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public complicationDetail?: Array<FlatConvectorModel<Reference>>; //Condition @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public followUp?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(ProcedureFocalDevice.schema()))) public focalDevice?: Array<FlatConvectorModel<ProcedureFocalDevice>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public usedReference?: Array<FlatConvectorModel<Reference>>; //Device|Medication|Substance @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public usedCode?: Array<FlatConvectorModel<CodeableConcept>>; } export class ProdCharacteristic extends DomainResource<ProdCharacteristic> { @Default('fhir.datatypes.ProdCharacteristic') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Quantity.schema())) public height?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Quantity.schema())) public width?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Quantity.schema())) public depth?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Quantity.schema())) public weight?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Quantity.schema())) public nominalVolume?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Quantity.schema())) public externalDiameter?: FlatConvectorModel<Quantity>; @Validate(yup.string()) public shape?: string; @Validate(yup.array(yup.string())) public color? : Array<string>; @Validate(yup.array(yup.string())) public imprint? : Array<string>; // @Validate(yup.lazy(() => yup.array(Attachment.schema()))) public image?: Array<FlatConvectorModel<Attachment>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public scoring?: FlatConvectorModel<CodeableConcept>; } export class ProductShelfLife extends DomainResource<ProductShelfLife> { @Default('fhir.datatypes.ProductShelfLife') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Quantity.schema())) public period: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public specialPrecautionsForStorage?: Array<FlatConvectorModel<CodeableConcept>>; } export class ProvenanceAgent extends BackboneElement { @Default('fhir.datatypes.Provenance.ProvenanceAgent') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public role?: Array<FlatConvectorModel<CodeableConcept>>; @Required() @Validate(yup.lazy(() => Reference.schema())) public who: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|RelatedPerson|Patient|Device|Organization @Validate(yup.lazy(() => Reference.schema())) public onBehalfOf?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|RelatedPerson|Patient|Device|Organization } export class ProvenanceEntity extends BackboneElement { @Default('fhir.datatypes.Provenance.ProvenanceEntity') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public role: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public what: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => yup.array(ProvenanceAgent.schema()))) public agent?: Array<FlatConvectorModel<ProvenanceAgent>>; } export class Provenance extends DomainResource<Provenance> { @Default('fhir.datatypes.Provenance') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public target?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => Period.schema())) public occurredPeriod?: FlatConvectorModel<Period>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public occurredDateTime?: date; @Required() @Validate(yup.string()) public recorded: string; @Validate(yup.array(yup.string())) public policy? : Array<string>; @Validate(yup.lazy(() => Reference.schema())) public location?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reason?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public activity?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(ProvenanceAgent.schema()))) public agent?: Array<FlatConvectorModel<ProvenanceAgent>>; @Validate(yup.lazy(() => yup.array(ProvenanceEntity.schema()))) public entity?: Array<FlatConvectorModel<ProvenanceEntity>>; @Validate(yup.lazy(() => yup.array(Signature.schema()))) public signature?: Array<FlatConvectorModel<Signature>>; } export class QuestionnaireItem extends BackboneElement { @Default('fhir.datatypes.Questionnaire.QuestionnaireItem') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public linkId: string; @Validate(yup.string()) public definition?: string; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public code?: Array<FlatConvectorModel<Coding>>; @Validate(yup.string()) public prefix?: string; @Validate(yup.string()) public text?: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.lazy(() => yup.array(QuestionnaireItemEnableWhen.schema()))) public enableWhen?: Array<FlatConvectorModel<QuestionnaireItemEnableWhen>>; @Validate(yup.string()) public enableBehavior?: string; @Validate(yup.boolean()) public required?: boolean; @Validate(yup.boolean()) public repeats?: boolean; @Validate(yup.boolean()) public readOnly?: boolean; @Validate(yup.number()) public maxLength?: number; @Validate(yup.string()) public answerValueSet?: string; //ValueSet @Validate(yup.lazy(() => yup.array(QuestionnaireItemAnswerOption.schema()))) public answerOption?: Array<FlatConvectorModel<QuestionnaireItemAnswerOption>>; @Validate(yup.lazy(() => yup.array(QuestionnaireItemInitial.schema()))) public initial?: Array<FlatConvectorModel<QuestionnaireItemInitial>>; @Validate(yup.lazy(() => yup.array(QuestionnaireItem.schema()))) public item?: Array<FlatConvectorModel<QuestionnaireItem>>; } export class QuestionnaireItemEnableWhen extends BackboneElement { @Default('fhir.datatypes.Questionnaire.QuestionnaireItemEnableWhen') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public question: string; @Required() @Validate(yup.string()) public operator: string; @Required() @Validate(yup.boolean()) public answerBoolean: boolean; @Required() @Validate(yup.number()) public answerDecimal: number; @Required() @Validate(yup.number()) public answerInteger: number; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public answerDate: date; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public answerDateTime: date; @Required() @Validate(yup.string()) public answerTime: string; @Required() @Validate(yup.string()) public answerString: string; @Required() @Validate(yup.lazy(() => Coding.schema())) public answerCoding: FlatConvectorModel<Coding>; @Required() @Validate(yup.lazy(() => Quantity.schema())) public answerQuantity: FlatConvectorModel<Quantity>; @Required() @Validate(yup.lazy(() => Reference.schema())) public answerReference: FlatConvectorModel<Reference>; //Any } export class QuestionnaireItemAnswerOption extends BackboneElement { @Default('fhir.datatypes.Questionnaire.QuestionnaireItemAnswerOption') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public valueInteger: number; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDate: date; @Required() @Validate(yup.string()) public valueTime: string; @Required() @Validate(yup.string()) public valueString: string; @Required() @Validate(yup.lazy(() => Coding.schema())) public valueCoding: FlatConvectorModel<Coding>; @Required() @Validate(yup.lazy(() => Reference.schema())) public valueReference: FlatConvectorModel<Reference>; //Any @Validate(yup.boolean()) public initialSelected?: boolean; } export class QuestionnaireItemInitial extends BackboneElement { @Default('fhir.datatypes.Questionnaire.QuestionnaireItemInitial') @ReadOnly() public readonly type: string; @Required() @Validate(yup.boolean()) public valueBoolean: boolean; @Required() @Validate(yup.number()) public valueDecimal: number; @Required() @Validate(yup.number()) public valueInteger: number; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDate: date; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDateTime: date; @Required() @Validate(yup.string()) public valueTime: string; @Required() @Validate(yup.string()) public valueString: string; @Required() @Validate(yup.string()) public valueUri: string; // @Required() @Validate(yup.lazy(() => Attachment.schema())) public valueAttachment: FlatConvectorModel<Attachment>; @Required() @Validate(yup.lazy(() => Coding.schema())) public valueCoding: FlatConvectorModel<Coding>; @Required() @Validate(yup.lazy(() => Quantity.schema())) public valueQuantity: FlatConvectorModel<Quantity>; @Required() @Validate(yup.lazy(() => Reference.schema())) public valueReference: FlatConvectorModel<Reference>; //Any } export class Questionnaire extends DomainResource<Questionnaire> { @Default('fhir.datatypes.Questionnaire') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Validate(yup.array(yup.string())) public derivedFrom? : Array<string>; //Questionnaire @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.array(yup.string())) public subjectType? : Array<string>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public code?: Array<FlatConvectorModel<Coding>>; @Validate(yup.lazy(() => yup.array(QuestionnaireItem.schema()))) public item?: Array<FlatConvectorModel<QuestionnaireItem>>; } export class QuestionnaireResponseItem extends BackboneElement { @Default('fhir.datatypes.QuestionnaireResponse.QuestionnaireResponseItem') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public linkId: string; @Validate(yup.string()) public definition?: string; @Validate(yup.string()) public text?: string; @Validate(yup.lazy(() => yup.array(QuestionnaireResponseItemAnswer.schema()))) public answer?: Array<FlatConvectorModel<QuestionnaireResponseItemAnswer>>; @Validate(yup.lazy(() => yup.array(QuestionnaireResponseItem.schema()))) public item?: Array<FlatConvectorModel<QuestionnaireResponseItem>>; } export class QuestionnaireResponseItemAnswer extends BackboneElement { @Default('fhir.datatypes.QuestionnaireResponse.QuestionnaireResponseItemAnswer') @ReadOnly() public readonly type: string; @Validate(yup.boolean()) public valueBoolean?: boolean; @Validate(yup.number()) public valueDecimal?: number; @Validate(yup.number()) public valueInteger?: number; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDateTime?: date; @Validate(yup.string()) public valueTime?: string; @Validate(yup.string()) public valueString?: string; @Validate(yup.string()) public valueUri?: string; // @Validate(yup.lazy(() => Attachment.schema())) public valueAttachment?: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => Coding.schema())) public valueCoding?: FlatConvectorModel<Coding>; @Validate(yup.lazy(() => Quantity.schema())) public valueQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Reference.schema())) public valueReference?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => yup.array(QuestionnaireResponseItem.schema()))) public item?: Array<FlatConvectorModel<QuestionnaireResponseItem>>; } export class QuestionnaireResponse extends DomainResource<QuestionnaireResponse> { @Default('fhir.datatypes.QuestionnaireResponse') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //CarePlan|ServiceRequest @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //Observation|Procedure @Validate(yup.string()) public questionnaire?: string; //Questionnaire @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public authored?: date; @Validate(yup.lazy(() => Reference.schema())) public author?: FlatConvectorModel<Reference>; //Device|Practitioner|PractitionerRole|Patient|RelatedPerson|Organization @Validate(yup.lazy(() => Reference.schema())) public source?: FlatConvectorModel<Reference>; //Patient|Practitioner|PractitionerRole|RelatedPerson @Validate(yup.lazy(() => yup.array(QuestionnaireResponseItem.schema()))) public item?: Array<FlatConvectorModel<QuestionnaireResponseItem>>; } export class RelatedArtifact extends DomainResource<RelatedArtifact> { @Default('fhir.datatypes.RelatedArtifact') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public label?: string; @Validate(yup.string()) public display?: string; @Validate(yup.string()) public citation?: string; @Validate(yup.string()) public url?: string; // @Validate(yup.lazy(() => Attachment.schema())) public document?: FlatConvectorModel<Attachment>; @Validate(yup.string()) public resource?: string; //Any } export class RelatedPersonCommunication extends BackboneElement { @Default('fhir.datatypes.RelatedPerson.RelatedPersonCommunication') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public language: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public preferred?: boolean; } export class RelatedPerson extends DomainResource<RelatedPerson> { @Default('fhir.datatypes.RelatedPerson') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.boolean()) public active?: boolean; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public relationship?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(HumanName.schema()))) public name?: Array<FlatConvectorModel<HumanName>>; @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public telecom?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.string()) public gender?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public birthDate?: date; @Validate(yup.lazy(() => yup.array(Address.schema()))) public address?: Array<FlatConvectorModel<Address>>; // @Validate(yup.lazy(() => yup.array(Attachment.schema()))) public photo?: Array<FlatConvectorModel<Attachment>>; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(RelatedPersonCommunication.schema()))) public communication?: Array<FlatConvectorModel<RelatedPersonCommunication>>; } export class RequestGroupAction extends BackboneElement { @Default('fhir.datatypes.RequestGroup.RequestGroupAction') @ReadOnly() public readonly type: string; @Validate(yup.string()) public prefix?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public textEquivalent?: string; @Validate(yup.string()) public priority?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public code?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public documentation?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.lazy(() => yup.array(RequestGroupActionCondition.schema()))) public condition?: Array<FlatConvectorModel<RequestGroupActionCondition>>; @Validate(yup.lazy(() => yup.array(RequestGroupActionRelatedAction.schema()))) public relatedAction?: Array<FlatConvectorModel<RequestGroupActionRelatedAction>>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public timingDateTime?: date; @Validate(yup.lazy(() => Age.schema())) public timingAge?: FlatConvectorModel<Age>; @Validate(yup.lazy(() => Period.schema())) public timingPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Duration.schema())) public timingDuration?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => Range.schema())) public timingRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => Timing.schema())) public timingTiming?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public participant?: Array<FlatConvectorModel<Reference>>; //Patient|Practitioner|PractitionerRole|RelatedPerson|Device @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public groupingBehavior?: string; @Validate(yup.string()) public selectionBehavior?: string; @Validate(yup.string()) public requiredBehavior?: string; @Validate(yup.string()) public precheckBehavior?: string; @Validate(yup.string()) public cardinalityBehavior?: string; @Validate(yup.lazy(() => Reference.schema())) public resource?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => yup.array(RequestGroupAction.schema()))) public action?: Array<FlatConvectorModel<RequestGroupAction>>; } export class RequestGroupActionCondition extends BackboneElement { @Default('fhir.datatypes.RequestGroup.RequestGroupActionCondition') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public kind: string; @Validate(yup.lazy(() => Expression.schema())) public expression?: FlatConvectorModel<Expression>; } export class RequestGroupActionRelatedAction extends BackboneElement { @Default('fhir.datatypes.RequestGroup.RequestGroupActionRelatedAction') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public actionId: string; @Required() @Validate(yup.string()) public relationship: string; @Validate(yup.lazy(() => Duration.schema())) public offsetDuration?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => Range.schema())) public offsetRange?: FlatConvectorModel<Range>; } export class RequestGroup extends DomainResource<RequestGroup> { @Default('fhir.datatypes.RequestGroup') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.array(yup.string())) public instantiatesCanonical? : Array<string>; @Validate(yup.array(yup.string())) public instantiatesUri? : Array<string>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(Reference.schema()))) public replaces?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => Identifier.schema())) public groupIdentifier?: FlatConvectorModel<Identifier>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.string()) public intent: string; @Validate(yup.string()) public priority?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public authoredOn?: date; @Validate(yup.lazy(() => Reference.schema())) public author?: FlatConvectorModel<Reference>; //Device|Practitioner|PractitionerRole @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport|DocumentReference @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(RequestGroupAction.schema()))) public action?: Array<FlatConvectorModel<RequestGroupAction>>; } export class ResearchDefinition extends DomainResource<ResearchDefinition> { @Default('fhir.datatypes.ResearchDefinition') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public shortTitle?: string; @Validate(yup.string()) public subtitle?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public subjectCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subjectReference?: FlatConvectorModel<Reference>; //Group @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.array(yup.string())) public comment? : Array<string>; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public usage?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public topic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public author?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public editor?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public reviewer?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public endorser?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public relatedArtifact?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.array(yup.string())) public library? : Array<string>; //Library @Required() @Validate(yup.lazy(() => Reference.schema())) public population: FlatConvectorModel<Reference>; //ResearchElementDefinition @Validate(yup.lazy(() => Reference.schema())) public exposure?: FlatConvectorModel<Reference>; //ResearchElementDefinition @Validate(yup.lazy(() => Reference.schema())) public exposureAlternative?: FlatConvectorModel<Reference>; //ResearchElementDefinition @Validate(yup.lazy(() => Reference.schema())) public outcome?: FlatConvectorModel<Reference>; //ResearchElementDefinition } export class ResearchElementDefinitionCharacteristic extends BackboneElement { @Default('fhir.datatypes.ResearchElementDefinition.ResearchElementDefinitionCharacteristic') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public definitionCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string()) public definitionCanonical: string; //ValueSet @Required() @Validate(yup.lazy(() => Expression.schema())) public definitionExpression: FlatConvectorModel<Expression>; @Required() @Validate(yup.lazy(() => DataRequirement.schema())) public definitionDataRequirement: FlatConvectorModel<DataRequirement>; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public usageContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.boolean()) public exclude?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public unitOfMeasure?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public studyEffectiveDescription?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public studyEffectiveDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public studyEffectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Duration.schema())) public studyEffectiveDuration?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => Timing.schema())) public studyEffectiveTiming?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => Duration.schema())) public studyEffectiveTimeFromStart?: FlatConvectorModel<Duration>; @Validate(yup.string()) public studyEffectiveGroupMeasure?: string; @Validate(yup.string()) public participantEffectiveDescription?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public participantEffectiveDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public participantEffectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Duration.schema())) public participantEffectiveDuration?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => Timing.schema())) public participantEffectiveTiming?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => Duration.schema())) public participantEffectiveTimeFromStart?: FlatConvectorModel<Duration>; @Validate(yup.string()) public participantEffectiveGroupMeasure?: string; } export class ResearchElementDefinition extends DomainResource<ResearchElementDefinition> { @Default('fhir.datatypes.ResearchElementDefinition') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Validate(yup.string()) public shortTitle?: string; @Validate(yup.string()) public subtitle?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public subjectCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subjectReference?: FlatConvectorModel<Reference>; //Group @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.array(yup.string())) public comment? : Array<string>; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public usage?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public topic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public author?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public editor?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public reviewer?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public endorser?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public relatedArtifact?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.array(yup.string())) public library? : Array<string>; //Library @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public variableType?: string; @Validate(yup.lazy(() => yup.array(ResearchElementDefinitionCharacteristic.schema()))) public characteristic?: Array<FlatConvectorModel<ResearchElementDefinitionCharacteristic>>; } export class ResearchStudyArm extends BackboneElement { @Default('fhir.datatypes.ResearchStudy.ResearchStudyArm') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public description?: string; } export class ResearchStudyObjective extends BackboneElement { @Default('fhir.datatypes.ResearchStudy.ResearchStudyObjective') @ReadOnly() public readonly type: string; @Validate(yup.string()) public name?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; } export class ResearchStudy extends DomainResource<ResearchStudy> { @Default('fhir.datatypes.ResearchStudy') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public title?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public protocol?: Array<FlatConvectorModel<Reference>>; //PlanDefinition @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //ResearchStudy @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public primaryPurposeType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public phase?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public focus?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public condition?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public relatedArtifact?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public keyword?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public location?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public enrollment?: Array<FlatConvectorModel<Reference>>; //Group @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Reference.schema())) public sponsor?: FlatConvectorModel<Reference>; //Organization @Validate(yup.lazy(() => Reference.schema())) public principalInvestigator?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => yup.array(Reference.schema()))) public site?: Array<FlatConvectorModel<Reference>>; //Location @Validate(yup.lazy(() => CodeableConcept.schema())) public reasonStopped?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(ResearchStudyArm.schema()))) public arm?: Array<FlatConvectorModel<ResearchStudyArm>>; @Validate(yup.lazy(() => yup.array(ResearchStudyObjective.schema()))) public objective?: Array<FlatConvectorModel<ResearchStudyObjective>>; } export class ResearchSubject extends DomainResource<ResearchSubject> { @Default('fhir.datatypes.ResearchSubject') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Required() @Validate(yup.lazy(() => Reference.schema())) public study: FlatConvectorModel<Reference>; //ResearchStudy @Required() @Validate(yup.lazy(() => Reference.schema())) public individual: FlatConvectorModel<Reference>; //Patient @Validate(yup.string()) public assignedArm?: string; @Validate(yup.string()) public actualArm?: string; @Validate(yup.lazy(() => Reference.schema())) public consent?: FlatConvectorModel<Reference>; //Consent } export class RiskAssessmentPrediction extends BackboneElement { @Default('fhir.datatypes.RiskAssessment.RiskAssessmentPrediction') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public outcome?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public probabilityDecimal?: number; @Validate(yup.lazy(() => Range.schema())) public probabilityRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => CodeableConcept.schema())) public qualitativeRisk?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public relativeRisk?: number; @Validate(yup.lazy(() => Period.schema())) public whenPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Range.schema())) public whenRange?: FlatConvectorModel<Range>; @Validate(yup.string()) public rationale?: string; } export class RiskAssessment extends DomainResource<RiskAssessment> { @Default('fhir.datatypes.RiskAssessment') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => Reference.schema())) public basedOn?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => Reference.schema())) public parent?: FlatConvectorModel<Reference>; //Any @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public method?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public occurrenceDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public occurrencePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Reference.schema())) public condition?: FlatConvectorModel<Reference>; //Condition @Validate(yup.lazy(() => Reference.schema())) public performer?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Device @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport|DocumentReference @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basis?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(RiskAssessmentPrediction.schema()))) public prediction?: Array<FlatConvectorModel<RiskAssessmentPrediction>>; @Validate(yup.string()) public mitigation?: string; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class RiskEvidenceSynthesisSampleSize extends BackboneElement { @Default('fhir.datatypes.RiskEvidenceSynthesis.RiskEvidenceSynthesisSampleSize') @ReadOnly() public readonly type: string; @Validate(yup.string()) public description?: string; @Validate(yup.number()) public numberOfStudies?: number; @Validate(yup.number()) public numberOfParticipants?: number; } export class RiskEvidenceSynthesisRiskEstimate extends BackboneElement { @Default('fhir.datatypes.RiskEvidenceSynthesis.RiskEvidenceSynthesisRiskEstimate') @ReadOnly() public readonly type: string; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public value?: number; @Validate(yup.lazy(() => CodeableConcept.schema())) public unitOfMeasure?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public denominatorCount?: number; @Validate(yup.number()) public numeratorCount?: number; @Validate(yup.lazy(() => yup.array(RiskEvidenceSynthesisRiskEstimatePrecisionEstimate.schema()))) public precisionEstimate?: Array<FlatConvectorModel<RiskEvidenceSynthesisRiskEstimatePrecisionEstimate>>; } export class RiskEvidenceSynthesisRiskEstimatePrecisionEstimate extends BackboneElement { @Default('fhir.datatypes.RiskEvidenceSynthesis.RiskEvidenceSynthesisRiskEstimatePrecisionEstimate') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public level?: number; @Validate(yup.number()) public from?: number; @Validate(yup.number()) public to?: number; } export class RiskEvidenceSynthesisCertainty extends BackboneElement { @Default('fhir.datatypes.RiskEvidenceSynthesis.RiskEvidenceSynthesisCertainty') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public rating?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(RiskEvidenceSynthesisCertaintyCertaintySubcomponent.schema()))) public certaintySubcomponent?: Array<FlatConvectorModel<RiskEvidenceSynthesisCertaintyCertaintySubcomponent>>; } export class RiskEvidenceSynthesisCertaintyCertaintySubcomponent extends BackboneElement { @Default('fhir.datatypes.RiskEvidenceSynthesis.RiskEvidenceSynthesisCertaintyCertaintySubcomponent') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public rating?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class RiskEvidenceSynthesis extends DomainResource<RiskEvidenceSynthesis> { @Default('fhir.datatypes.RiskEvidenceSynthesis') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public copyright?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public approvalDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastReviewDate?: date; @Validate(yup.lazy(() => Period.schema())) public effectivePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public topic?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public author?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public editor?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public reviewer?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public endorser?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.lazy(() => yup.array(RelatedArtifact.schema()))) public relatedArtifact?: Array<FlatConvectorModel<RelatedArtifact>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public synthesisType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public studyType?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public population: FlatConvectorModel<Reference>; //EvidenceVariable @Validate(yup.lazy(() => Reference.schema())) public exposure?: FlatConvectorModel<Reference>; //EvidenceVariable @Required() @Validate(yup.lazy(() => Reference.schema())) public outcome: FlatConvectorModel<Reference>; //EvidenceVariable @Validate(yup.lazy(() => RiskEvidenceSynthesisSampleSize.schema())) public sampleSize?: FlatConvectorModel<RiskEvidenceSynthesisSampleSize>; @Validate(yup.lazy(() => RiskEvidenceSynthesisRiskEstimate.schema())) public riskEstimate?: FlatConvectorModel<RiskEvidenceSynthesisRiskEstimate>; @Validate(yup.lazy(() => yup.array(RiskEvidenceSynthesisCertainty.schema()))) public certainty?: Array<FlatConvectorModel<RiskEvidenceSynthesisCertainty>>; } export class Schedule extends DomainResource<Schedule> { @Default('fhir.datatypes.Schedule') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.boolean()) public active?: boolean; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public serviceCategory?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public serviceType?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public specialty?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public actor?: Array<FlatConvectorModel<Reference>>; //Patient|Practitioner|PractitionerRole|RelatedPerson|Device|HealthcareService|Location @Validate(yup.lazy(() => Period.schema())) public planningHorizon?: FlatConvectorModel<Period>; @Validate(yup.string()) public comment?: string; } export class SearchParameterComponent extends BackboneElement { @Default('fhir.datatypes.SearchParameter.SearchParameterComponent') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public definition: string; //SearchParameter @Required() @Validate(yup.string()) public expression: string; } export class SearchParameter extends DomainResource<SearchParameter> { @Default('fhir.datatypes.SearchParameter') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public url: string; @Validate(yup.string()) public version?: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public derivedFrom?: string; //SearchParameter @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Required() @Validate(yup.string()) public description: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.array(yup.string())) public base? : Array<string>; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public expression?: string; @Validate(yup.string()) public xpath?: string; @Validate(yup.string()) public xpathUsage?: string; @Validate(yup.array(yup.string())) public target? : Array<string>; @Validate(yup.boolean()) public multipleOr?: boolean; @Validate(yup.boolean()) public multipleAnd?: boolean; @Validate(yup.array(yup.string())) public comparator? : Array<string>; @Validate(yup.array(yup.string())) public modifier? : Array<string>; @Validate(yup.array(yup.string())) public chain? : Array<string>; @Validate(yup.lazy(() => yup.array(SearchParameterComponent.schema()))) public component?: Array<FlatConvectorModel<SearchParameterComponent>>; } export class ServiceRequest extends DomainResource<ServiceRequest> { @Default('fhir.datatypes.ServiceRequest') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.array(yup.string())) public instantiatesCanonical? : Array<string>; //ActivityDefinition|PlanDefinition @Validate(yup.array(yup.string())) public instantiatesUri? : Array<string>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //CarePlan|ServiceRequest|MedicationRequest @Validate(yup.lazy(() => yup.array(Reference.schema()))) public replaces?: Array<FlatConvectorModel<Reference>>; //ServiceRequest @Validate(yup.lazy(() => Identifier.schema())) public requisition?: FlatConvectorModel<Identifier>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.string()) public intent: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public priority?: string; @Validate(yup.boolean()) public doNotPerform?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public orderDetail?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Quantity.schema())) public quantityQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Ratio.schema())) public quantityRatio?: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => Range.schema())) public quantityRange?: FlatConvectorModel<Range>; @Required() @Validate(yup.lazy(() => Reference.schema())) public subject: FlatConvectorModel<Reference>; //Patient|Group|Location|Device @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public occurrenceDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public occurrencePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Timing.schema())) public occurrenceTiming?: FlatConvectorModel<Timing>; @Validate(yup.boolean()) public asNeededBoolean?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public asNeededCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public authoredOn?: date; @Validate(yup.lazy(() => Reference.schema())) public requester?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|Patient|RelatedPerson|Device @Validate(yup.lazy(() => CodeableConcept.schema())) public performerType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public performer?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole|Organization|CareTeam|HealthcareService|Patient|Device|RelatedPerson @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public locationCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public locationReference?: Array<FlatConvectorModel<Reference>>; //Location @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport|DocumentReference @Validate(yup.lazy(() => yup.array(Reference.schema()))) public insurance?: Array<FlatConvectorModel<Reference>>; //Coverage|ClaimResponse @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supportingInfo?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(Reference.schema()))) public specimen?: Array<FlatConvectorModel<Reference>>; //Specimen @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public bodySite?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.string()) public patientInstruction?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public relevantHistory?: Array<FlatConvectorModel<Reference>>; //Provenance } export class Signature extends DomainResource<Signature> { @Default('fhir.datatypes.Signature') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public type_?: Array<FlatConvectorModel<Coding>>; @Required() @Validate(yup.string()) public when: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public who: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|RelatedPerson|Patient|Device|Organization @Validate(yup.lazy(() => Reference.schema())) public onBehalfOf?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|RelatedPerson|Patient|Device|Organization @Validate(yup.string()) public targetFormat?: string; @Validate(yup.string()) public sigFormat?: string; @Validate(yup.string()) public data?: string; } export class Slot extends DomainResource<Slot> { @Default('fhir.datatypes.Slot') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public serviceCategory?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public serviceType?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public specialty?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public appointmentType?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public schedule: FlatConvectorModel<Reference>; //Schedule @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.string()) public start: string; @Required() @Validate(yup.string()) public end: string; @Validate(yup.boolean()) public overbooked?: boolean; @Validate(yup.string()) public comment?: string; } export class SpecimenCollection extends BackboneElement { @Default('fhir.datatypes.Specimen.SpecimenCollection') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Reference.schema())) public collector?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public collectedDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public collectedPeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Duration.schema())) public duration?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => CodeableConcept.schema())) public method?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public bodySite?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public fastingStatusCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Duration.schema())) public fastingStatusDuration?: FlatConvectorModel<Duration>; } export class SpecimenProcessing extends BackboneElement { @Default('fhir.datatypes.Specimen.SpecimenProcessing') @ReadOnly() public readonly type: string; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public procedure?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public additive?: Array<FlatConvectorModel<Reference>>; //Substance @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public timeDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public timePeriod?: FlatConvectorModel<Period>; } export class SpecimenContainer extends BackboneElement { @Default('fhir.datatypes.Specimen.SpecimenContainer') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public capacity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public specimenQuantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => CodeableConcept.schema())) public additiveCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public additiveReference?: FlatConvectorModel<Reference>; //Substance } export class Specimen extends DomainResource<Specimen> { @Default('fhir.datatypes.Specimen') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => Identifier.schema())) public accessionIdentifier?: FlatConvectorModel<Identifier>; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public subject?: FlatConvectorModel<Reference>; //Patient|Group|Device|Substance|Location @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public receivedTime?: date; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public parent?: Array<FlatConvectorModel<Reference>>; //Specimen @Validate(yup.lazy(() => yup.array(Reference.schema()))) public request?: Array<FlatConvectorModel<Reference>>; //ServiceRequest @Validate(yup.lazy(() => SpecimenCollection.schema())) public collection?: FlatConvectorModel<SpecimenCollection>; @Validate(yup.lazy(() => yup.array(SpecimenProcessing.schema()))) public processing?: Array<FlatConvectorModel<SpecimenProcessing>>; @Validate(yup.lazy(() => yup.array(SpecimenContainer.schema()))) public container?: Array<FlatConvectorModel<SpecimenContainer>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public condition?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class SpecimenDefinitionTypeTested extends BackboneElement { @Default('fhir.datatypes.SpecimenDefinition.SpecimenDefinitionTypeTested') @ReadOnly() public readonly type: string; @Validate(yup.boolean()) public isDerived?: boolean; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string()) public preference: string; @Validate(yup.lazy(() => SpecimenDefinitionTypeTestedContainer.schema())) public container?: FlatConvectorModel<SpecimenDefinitionTypeTestedContainer>; @Validate(yup.string()) public requirement?: string; @Validate(yup.lazy(() => Duration.schema())) public retentionTime?: FlatConvectorModel<Duration>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public rejectionCriterion?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(SpecimenDefinitionTypeTestedHandling.schema()))) public handling?: Array<FlatConvectorModel<SpecimenDefinitionTypeTestedHandling>>; } export class SpecimenDefinitionTypeTestedContainer extends BackboneElement { @Default('fhir.datatypes.SpecimenDefinition.SpecimenDefinitionTypeTestedContainer') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public material?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public cap?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => SimpleQuantity.schema())) public capacity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => SimpleQuantity.schema())) public minimumVolumeQuantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.string()) public minimumVolumeString?: string; @Validate(yup.lazy(() => yup.array(SpecimenDefinitionTypeTestedContainerAdditive.schema()))) public additive?: Array<FlatConvectorModel<SpecimenDefinitionTypeTestedContainerAdditive>>; @Validate(yup.string()) public preparation?: string; } export class SpecimenDefinitionTypeTestedContainerAdditive extends BackboneElement { @Default('fhir.datatypes.SpecimenDefinition.SpecimenDefinitionTypeTestedContainerAdditive') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public additiveCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public additiveReference: FlatConvectorModel<Reference>; //Substance } export class SpecimenDefinitionTypeTestedHandling extends BackboneElement { @Default('fhir.datatypes.SpecimenDefinition.SpecimenDefinitionTypeTestedHandling') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public temperatureQualifier?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Range.schema())) public temperatureRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => Duration.schema())) public maxDuration?: FlatConvectorModel<Duration>; @Validate(yup.string()) public instruction?: string; } export class SpecimenDefinition extends DomainResource<SpecimenDefinition> { @Default('fhir.datatypes.SpecimenDefinition') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => CodeableConcept.schema())) public typeCollected?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public patientPreparation?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public timeAspect?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public collection?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(SpecimenDefinitionTypeTested.schema()))) public typeTested?: Array<FlatConvectorModel<SpecimenDefinitionTypeTested>>; } export class StructureDefinitionMapping extends BackboneElement { @Default('fhir.datatypes.StructureDefinition.StructureDefinitionMapping') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public identity: string; @Validate(yup.string()) public uri?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public comment?: string; } export class StructureDefinitionContext extends BackboneElement { @Default('fhir.datatypes.StructureDefinition.StructureDefinitionContext') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Required() @Validate(yup.string()) public expression: string; } export class StructureDefinitionSnapshot extends BackboneElement { @Default('fhir.datatypes.StructureDefinition.StructureDefinitionSnapshot') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(ElementDefinition.schema()))) public element?: Array<FlatConvectorModel<ElementDefinition>>; } export class StructureDefinitionDifferential extends BackboneElement { @Default('fhir.datatypes.StructureDefinition.StructureDefinitionDifferential') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(ElementDefinition.schema()))) public element?: Array<FlatConvectorModel<ElementDefinition>>; } export class StructureDefinition extends DomainResource<StructureDefinition> { @Default('fhir.datatypes.StructureDefinition') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public url: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.lazy(() => yup.array(Coding.schema()))) public keyword?: Array<FlatConvectorModel<Coding>>; @Validate(yup.string()) public fhirVersion?: string; @Validate(yup.lazy(() => yup.array(StructureDefinitionMapping.schema()))) public mapping?: Array<FlatConvectorModel<StructureDefinitionMapping>>; @Required() @Validate(yup.string()) public kind: string; @Required() @Validate(yup.boolean()) public abstract: boolean; @Validate(yup.lazy(() => yup.array(StructureDefinitionContext.schema()))) public context?: Array<FlatConvectorModel<StructureDefinitionContext>>; @Validate(yup.array(yup.string())) public contextInvariant? : Array<string>; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public baseDefinition?: string; //StructureDefinition @Validate(yup.string()) public derivation?: string; @Validate(yup.lazy(() => StructureDefinitionSnapshot.schema())) public snapshot?: FlatConvectorModel<StructureDefinitionSnapshot>; @Validate(yup.lazy(() => StructureDefinitionDifferential.schema())) public differential?: FlatConvectorModel<StructureDefinitionDifferential>; } export class StructureMapStructure extends BackboneElement { @Default('fhir.datatypes.StructureMap.StructureMapStructure') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public url: string; //StructureDefinition @Required() @Validate(yup.string()) public mode: string; @Validate(yup.string()) public alias?: string; @Validate(yup.string()) public documentation?: string; } export class StructureMapGroup extends BackboneElement { @Default('fhir.datatypes.StructureMap.StructureMapGroup') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public extends?: string; @Required() @Validate(yup.string()) public typeMode: string; @Validate(yup.string()) public documentation?: string; @Validate(yup.lazy(() => yup.array(StructureMapGroupInput.schema()))) public input?: Array<FlatConvectorModel<StructureMapGroupInput>>; @Validate(yup.lazy(() => yup.array(StructureMapGroupRule.schema()))) public rule?: Array<FlatConvectorModel<StructureMapGroupRule>>; } export class StructureMapGroupInput extends BackboneElement { @Default('fhir.datatypes.StructureMap.StructureMapGroupInput') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public type_?: string; @Required() @Validate(yup.string()) public mode: string; @Validate(yup.string()) public documentation?: string; } export class StructureMapGroupRule extends BackboneElement { @Default('fhir.datatypes.StructureMap.StructureMapGroupRule') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.lazy(() => yup.array(StructureMapGroupRuleSource.schema()))) public source?: Array<FlatConvectorModel<StructureMapGroupRuleSource>>; @Validate(yup.lazy(() => yup.array(StructureMapGroupRuleTarget.schema()))) public target?: Array<FlatConvectorModel<StructureMapGroupRuleTarget>>; @Validate(yup.lazy(() => yup.array(StructureMapGroupRule.schema()))) public rule?: Array<FlatConvectorModel<StructureMapGroupRule>>; @Validate(yup.lazy(() => yup.array(StructureMapGroupRuleDependent.schema()))) public dependent?: Array<FlatConvectorModel<StructureMapGroupRuleDependent>>; @Validate(yup.string()) public documentation?: string; } export class StructureMapGroupRuleSource extends BackboneElement { @Default('fhir.datatypes.StructureMap.StructureMapGroupRuleSource') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public context: string; @Validate(yup.number()) public min?: number; @Validate(yup.string()) public max?: string; @Validate(yup.string()) public type_?: string; @Validate(yup.string()) public element?: string; @Validate(yup.string()) public listMode?: string; @Validate(yup.string()) public variable?: string; @Validate(yup.string()) public condition?: string; @Validate(yup.string()) public check?: string; @Validate(yup.string()) public logMessage?: string; } export class StructureMapGroupRuleTarget extends BackboneElement { @Default('fhir.datatypes.StructureMap.StructureMapGroupRuleTarget') @ReadOnly() public readonly type: string; @Validate(yup.string()) public context?: string; @Validate(yup.string()) public contextType?: string; @Validate(yup.string()) public element?: string; @Validate(yup.string()) public variable?: string; @Validate(yup.array(yup.string())) public listMode? : Array<string>; @Validate(yup.string()) public listRuleId?: string; @Validate(yup.string()) public transform?: string; @Validate(yup.lazy(() => yup.array(StructureMapGroupRuleTargetParameter.schema()))) public parameter?: Array<FlatConvectorModel<StructureMapGroupRuleTargetParameter>>; } export class StructureMapGroupRuleTargetParameter extends BackboneElement { @Default('fhir.datatypes.StructureMap.StructureMapGroupRuleTargetParameter') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public valueId: string; @Required() @Validate(yup.string()) public valueString: string; @Required() @Validate(yup.boolean()) public valueBoolean: boolean; @Required() @Validate(yup.number()) public valueInteger: number; @Required() @Validate(yup.number()) public valueDecimal: number; } export class StructureMapGroupRuleDependent extends BackboneElement { @Default('fhir.datatypes.StructureMap.StructureMapGroupRuleDependent') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.array(yup.string())) public variable? : Array<string>; } export class StructureMap extends DomainResource<StructureMap> { @Default('fhir.datatypes.StructureMap') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public url: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.lazy(() => yup.array(StructureMapStructure.schema()))) public structure?: Array<FlatConvectorModel<StructureMapStructure>>; @Validate(yup.array(yup.string())) public import? : Array<string>; //StructureMap @Validate(yup.lazy(() => yup.array(StructureMapGroup.schema()))) public group?: Array<FlatConvectorModel<StructureMapGroup>>; } export class SubscriptionChannel extends BackboneElement { @Default('fhir.datatypes.Subscription.SubscriptionChannel') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public endpoint?: string; @Validate(yup.string()) public payload?: string; @Validate(yup.array(yup.string())) public header? : Array<string>; } export class Subscription extends DomainResource<Subscription> { @Default('fhir.datatypes.Subscription') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => yup.array(ContactPoint.schema()))) public contact?: Array<FlatConvectorModel<ContactPoint>>; @Validate(yup.string()) public end?: string; @Required() @Validate(yup.string()) public reason: string; @Required() @Validate(yup.string()) public criteria: string; @Validate(yup.string()) public error?: string; @Required() @Validate(yup.lazy(() => SubscriptionChannel.schema())) public channel: FlatConvectorModel<SubscriptionChannel>; } export class SubstanceInstance extends BackboneElement { @Default('fhir.datatypes.Substance.SubstanceInstance') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public expiry?: date; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; } export class SubstanceIngredient extends BackboneElement { @Default('fhir.datatypes.Substance.SubstanceIngredient') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Ratio.schema())) public quantity?: FlatConvectorModel<Ratio>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public substanceCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public substanceReference: FlatConvectorModel<Reference>; //Substance } export class Substance extends DomainResource<Substance> { @Default('fhir.datatypes.Substance') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public category?: Array<FlatConvectorModel<CodeableConcept>>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public code: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(SubstanceInstance.schema()))) public instance?: Array<FlatConvectorModel<SubstanceInstance>>; @Validate(yup.lazy(() => yup.array(SubstanceIngredient.schema()))) public ingredient?: Array<FlatConvectorModel<SubstanceIngredient>>; } export class SubstanceAmountReferenceRange extends BackboneElement { @Default('fhir.datatypes.SubstanceAmount.SubstanceAmountReferenceRange') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Quantity.schema())) public lowLimit?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Quantity.schema())) public highLimit?: FlatConvectorModel<Quantity>; } export class SubstanceAmount extends DomainResource<SubstanceAmount> { @Default('fhir.datatypes.SubstanceAmount') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Quantity.schema())) public amountQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Range.schema())) public amountRange?: FlatConvectorModel<Range>; @Validate(yup.string()) public amountString?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public amountType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public amountText?: string; @Validate(yup.lazy(() => SubstanceAmountReferenceRange.schema())) public referenceRange?: FlatConvectorModel<SubstanceAmountReferenceRange>; } export class SubstanceNucleicAcidSubunit extends BackboneElement { @Default('fhir.datatypes.SubstanceNucleicAcid.SubstanceNucleicAcidSubunit') @ReadOnly() public readonly type: string; @Validate(yup.number()) public subunit?: number; @Validate(yup.string()) public sequence?: string; @Validate(yup.number()) public length?: number; // @Validate(yup.lazy(() => Attachment.schema())) public sequenceAttachment?: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => CodeableConcept.schema())) public fivePrime?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public threePrime?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(SubstanceNucleicAcidSubunitLinkage.schema()))) public linkage?: Array<FlatConvectorModel<SubstanceNucleicAcidSubunitLinkage>>; @Validate(yup.lazy(() => yup.array(SubstanceNucleicAcidSubunitSugar.schema()))) public sugar?: Array<FlatConvectorModel<SubstanceNucleicAcidSubunitSugar>>; } export class SubstanceNucleicAcidSubunitLinkage extends BackboneElement { @Default('fhir.datatypes.SubstanceNucleicAcid.SubstanceNucleicAcidSubunitLinkage') @ReadOnly() public readonly type: string; @Validate(yup.string()) public connectivity?: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public residueSite?: string; } export class SubstanceNucleicAcidSubunitSugar extends BackboneElement { @Default('fhir.datatypes.SubstanceNucleicAcid.SubstanceNucleicAcidSubunitSugar') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public residueSite?: string; } export class SubstanceNucleicAcid extends DomainResource<SubstanceNucleicAcid> { @Default('fhir.datatypes.SubstanceNucleicAcid') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public sequenceType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public numberOfSubunits?: number; @Validate(yup.string()) public areaOfHybridisation?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public oligoNucleotideType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(SubstanceNucleicAcidSubunit.schema()))) public subunit?: Array<FlatConvectorModel<SubstanceNucleicAcidSubunit>>; } export class SubstancePolymerMonomerSet extends BackboneElement { @Default('fhir.datatypes.SubstancePolymer.SubstancePolymerMonomerSet') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public ratioType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(SubstancePolymerMonomerSetStartingMaterial.schema()))) public startingMaterial?: Array<FlatConvectorModel<SubstancePolymerMonomerSetStartingMaterial>>; } export class SubstancePolymerMonomerSetStartingMaterial extends BackboneElement { @Default('fhir.datatypes.SubstancePolymer.SubstancePolymerMonomerSetStartingMaterial') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public material?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public isDefining?: boolean; @Validate(yup.lazy(() => SubstanceAmount.schema())) public amount?: FlatConvectorModel<SubstanceAmount>; } export class SubstancePolymerRepeat extends BackboneElement { @Default('fhir.datatypes.SubstancePolymer.SubstancePolymerRepeat') @ReadOnly() public readonly type: string; @Validate(yup.number()) public numberOfUnits?: number; @Validate(yup.string()) public averageMolecularFormula?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public repeatUnitAmountType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(SubstancePolymerRepeatRepeatUnit.schema()))) public repeatUnit?: Array<FlatConvectorModel<SubstancePolymerRepeatRepeatUnit>>; } export class SubstancePolymerRepeatRepeatUnit extends BackboneElement { @Default('fhir.datatypes.SubstancePolymer.SubstancePolymerRepeatRepeatUnit') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public orientationOfPolymerisation?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public repeatUnit?: string; @Validate(yup.lazy(() => SubstanceAmount.schema())) public amount?: FlatConvectorModel<SubstanceAmount>; @Validate(yup.lazy(() => yup.array(SubstancePolymerRepeatRepeatUnitDegreeOfPolymerisation.schema()))) public degreeOfPolymerisation?: Array<FlatConvectorModel<SubstancePolymerRepeatRepeatUnitDegreeOfPolymerisation>>; @Validate(yup.lazy(() => yup.array(SubstancePolymerRepeatRepeatUnitStructuralRepresentation.schema()))) public structuralRepresentation?: Array<FlatConvectorModel<SubstancePolymerRepeatRepeatUnitStructuralRepresentation>>; } export class SubstancePolymerRepeatRepeatUnitDegreeOfPolymerisation extends BackboneElement { @Default('fhir.datatypes.SubstancePolymer.SubstancePolymerRepeatRepeatUnitDegreeOfPolymerisation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public degree?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => SubstanceAmount.schema())) public amount?: FlatConvectorModel<SubstanceAmount>; } export class SubstancePolymerRepeatRepeatUnitStructuralRepresentation extends BackboneElement { @Default('fhir.datatypes.SubstancePolymer.SubstancePolymerRepeatRepeatUnitStructuralRepresentation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public representation?: string; // @Validate(yup.lazy(() => Attachment.schema())) public attachment?: FlatConvectorModel<Attachment>; } export class SubstancePolymer extends DomainResource<SubstancePolymer> { @Default('fhir.datatypes.SubstancePolymer') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public class_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public geometry?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public copolymerConnectivity?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.array(yup.string())) public modification? : Array<string>; @Validate(yup.lazy(() => yup.array(SubstancePolymerMonomerSet.schema()))) public monomerSet?: Array<FlatConvectorModel<SubstancePolymerMonomerSet>>; @Validate(yup.lazy(() => yup.array(SubstancePolymerRepeat.schema()))) public repeat?: Array<FlatConvectorModel<SubstancePolymerRepeat>>; } export class SubstanceProteinSubunit extends BackboneElement { @Default('fhir.datatypes.SubstanceProtein.SubstanceProteinSubunit') @ReadOnly() public readonly type: string; @Validate(yup.number()) public subunit?: number; @Validate(yup.string()) public sequence?: string; @Validate(yup.number()) public length?: number; // @Validate(yup.lazy(() => Attachment.schema())) public sequenceAttachment?: FlatConvectorModel<Attachment>; @Validate(yup.lazy(() => Identifier.schema())) public nTerminalModificationId?: FlatConvectorModel<Identifier>; @Validate(yup.string()) public nTerminalModification?: string; @Validate(yup.lazy(() => Identifier.schema())) public cTerminalModificationId?: FlatConvectorModel<Identifier>; @Validate(yup.string()) public cTerminalModification?: string; } export class SubstanceProtein extends DomainResource<SubstanceProtein> { @Default('fhir.datatypes.SubstanceProtein') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public sequenceType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.number()) public numberOfSubunits?: number; @Validate(yup.array(yup.string())) public disulfideLinkage? : Array<string>; @Validate(yup.lazy(() => yup.array(SubstanceProteinSubunit.schema()))) public subunit?: Array<FlatConvectorModel<SubstanceProteinSubunit>>; } export class SubstanceReferenceInformationGene extends BackboneElement { @Default('fhir.datatypes.SubstanceReferenceInformation.SubstanceReferenceInformationGene') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public geneSequenceOrigin?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public gene?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public source?: Array<FlatConvectorModel<Reference>>; //DocumentReference } export class SubstanceReferenceInformationGeneElement extends BackboneElement { @Default('fhir.datatypes.SubstanceReferenceInformation.SubstanceReferenceInformationGeneElement') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Identifier.schema())) public element?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public source?: Array<FlatConvectorModel<Reference>>; //DocumentReference } export class SubstanceReferenceInformationClassification extends BackboneElement { @Default('fhir.datatypes.SubstanceReferenceInformation.SubstanceReferenceInformationClassification') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public domain?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public classification?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public subtype?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public source?: Array<FlatConvectorModel<Reference>>; //DocumentReference } export class SubstanceReferenceInformationTarget extends BackboneElement { @Default('fhir.datatypes.SubstanceReferenceInformation.SubstanceReferenceInformationTarget') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public target?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public interaction?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public organism?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public organismType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Quantity.schema())) public amountQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Range.schema())) public amountRange?: FlatConvectorModel<Range>; @Validate(yup.string()) public amountString?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public amountType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public source?: Array<FlatConvectorModel<Reference>>; //DocumentReference } export class SubstanceReferenceInformation extends DomainResource<SubstanceReferenceInformation> { @Default('fhir.datatypes.SubstanceReferenceInformation') @ReadOnly() public readonly type: string; @Validate(yup.string()) public comment?: string; @Validate(yup.lazy(() => yup.array(SubstanceReferenceInformationGene.schema()))) public gene?: Array<FlatConvectorModel<SubstanceReferenceInformationGene>>; @Validate(yup.lazy(() => yup.array(SubstanceReferenceInformationGeneElement.schema()))) public geneElement?: Array<FlatConvectorModel<SubstanceReferenceInformationGeneElement>>; @Validate(yup.lazy(() => yup.array(SubstanceReferenceInformationClassification.schema()))) public classification?: Array<FlatConvectorModel<SubstanceReferenceInformationClassification>>; @Validate(yup.lazy(() => yup.array(SubstanceReferenceInformationTarget.schema()))) public target?: Array<FlatConvectorModel<SubstanceReferenceInformationTarget>>; } export class SubstanceSourceMaterialFractionDescription extends BackboneElement { @Default('fhir.datatypes.SubstanceSourceMaterial.SubstanceSourceMaterialFractionDescription') @ReadOnly() public readonly type: string; @Validate(yup.string()) public fraction?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public materialType?: FlatConvectorModel<CodeableConcept>; } export class SubstanceSourceMaterialOrganism extends BackboneElement { @Default('fhir.datatypes.SubstanceSourceMaterial.SubstanceSourceMaterialOrganism') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public family?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public genus?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public species?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public intraspecificType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public intraspecificDescription?: string; @Validate(yup.lazy(() => yup.array(SubstanceSourceMaterialOrganismAuthor.schema()))) public author?: Array<FlatConvectorModel<SubstanceSourceMaterialOrganismAuthor>>; @Validate(yup.lazy(() => SubstanceSourceMaterialOrganismHybrid.schema())) public hybrid?: FlatConvectorModel<SubstanceSourceMaterialOrganismHybrid>; @Validate(yup.lazy(() => SubstanceSourceMaterialOrganismOrganismGeneral.schema())) public organismGeneral?: FlatConvectorModel<SubstanceSourceMaterialOrganismOrganismGeneral>; } export class SubstanceSourceMaterialOrganismAuthor extends BackboneElement { @Default('fhir.datatypes.SubstanceSourceMaterial.SubstanceSourceMaterialOrganismAuthor') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public authorType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public authorDescription?: string; } export class SubstanceSourceMaterialOrganismHybrid extends BackboneElement { @Default('fhir.datatypes.SubstanceSourceMaterial.SubstanceSourceMaterialOrganismHybrid') @ReadOnly() public readonly type: string; @Validate(yup.string()) public maternalOrganismId?: string; @Validate(yup.string()) public maternalOrganismName?: string; @Validate(yup.string()) public paternalOrganismId?: string; @Validate(yup.string()) public paternalOrganismName?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public hybridType?: FlatConvectorModel<CodeableConcept>; } export class SubstanceSourceMaterialOrganismOrganismGeneral extends BackboneElement { @Default('fhir.datatypes.SubstanceSourceMaterial.SubstanceSourceMaterialOrganismOrganismGeneral') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public kingdom?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public phylum?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public class_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public order?: FlatConvectorModel<CodeableConcept>; } export class SubstanceSourceMaterialPartDescription extends BackboneElement { @Default('fhir.datatypes.SubstanceSourceMaterial.SubstanceSourceMaterialPartDescription') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public part?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public partLocation?: FlatConvectorModel<CodeableConcept>; } export class SubstanceSourceMaterial extends DomainResource<SubstanceSourceMaterial> { @Default('fhir.datatypes.SubstanceSourceMaterial') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public sourceMaterialClass?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public sourceMaterialType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public sourceMaterialState?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Identifier.schema())) public organismId?: FlatConvectorModel<Identifier>; @Validate(yup.string()) public organismName?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public parentSubstanceId?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.array(yup.string())) public parentSubstanceName? : Array<string>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public countryOfOrigin?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.array(yup.string())) public geographicalLocation? : Array<string>; @Validate(yup.lazy(() => CodeableConcept.schema())) public developmentStage?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(SubstanceSourceMaterialFractionDescription.schema()))) public fractionDescription?: Array<FlatConvectorModel<SubstanceSourceMaterialFractionDescription>>; @Validate(yup.lazy(() => SubstanceSourceMaterialOrganism.schema())) public organism?: FlatConvectorModel<SubstanceSourceMaterialOrganism>; @Validate(yup.lazy(() => yup.array(SubstanceSourceMaterialPartDescription.schema()))) public partDescription?: Array<FlatConvectorModel<SubstanceSourceMaterialPartDescription>>; } export class SubstanceSpecificationMoiety extends BackboneElement { @Default('fhir.datatypes.SubstanceSpecification.SubstanceSpecificationMoiety') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public role?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.string()) public name?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public stereochemistry?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public opticalActivity?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public molecularFormula?: string; @Validate(yup.lazy(() => Quantity.schema())) public amountQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.string()) public amountString?: string; } export class SubstanceSpecificationProperty extends BackboneElement { @Default('fhir.datatypes.SubstanceSpecification.SubstanceSpecificationProperty') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public parameters?: string; @Validate(yup.lazy(() => Reference.schema())) public definingSubstanceReference?: FlatConvectorModel<Reference>; //SubstanceSpecification|Substance @Validate(yup.lazy(() => CodeableConcept.schema())) public definingSubstanceCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Quantity.schema())) public amountQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.string()) public amountString?: string; } export class SubstanceSpecificationStructure extends BackboneElement { @Default('fhir.datatypes.SubstanceSpecification.SubstanceSpecificationStructure') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public stereochemistry?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public opticalActivity?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public molecularFormula?: string; @Validate(yup.string()) public molecularFormulaByMoiety?: string; @Validate(yup.lazy(() => yup.array(SubstanceSpecificationStructureIsotope.schema()))) public isotope?: Array<FlatConvectorModel<SubstanceSpecificationStructureIsotope>>; @Validate(yup.lazy(() => SubstanceSpecificationStructureIsotopeMolecularWeight.schema())) public molecularWeight?: FlatConvectorModel<SubstanceSpecificationStructureIsotopeMolecularWeight>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public source?: Array<FlatConvectorModel<Reference>>; //DocumentReference @Validate(yup.lazy(() => yup.array(SubstanceSpecificationStructureRepresentation.schema()))) public representation?: Array<FlatConvectorModel<SubstanceSpecificationStructureRepresentation>>; } export class SubstanceSpecificationStructureIsotope extends BackboneElement { @Default('fhir.datatypes.SubstanceSpecification.SubstanceSpecificationStructureIsotope') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => CodeableConcept.schema())) public name?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public substitution?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Quantity.schema())) public halfLife?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => SubstanceSpecificationStructureIsotopeMolecularWeight.schema())) public molecularWeight?: FlatConvectorModel<SubstanceSpecificationStructureIsotopeMolecularWeight>; } export class SubstanceSpecificationStructureIsotopeMolecularWeight extends BackboneElement { @Default('fhir.datatypes.SubstanceSpecification.SubstanceSpecificationStructureIsotopeMolecularWeight') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public method?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Quantity.schema())) public amount?: FlatConvectorModel<Quantity>; } export class SubstanceSpecificationStructureRepresentation extends BackboneElement { @Default('fhir.datatypes.SubstanceSpecification.SubstanceSpecificationStructureRepresentation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public representation?: string; // @Validate(yup.lazy(() => Attachment.schema())) public attachment?: FlatConvectorModel<Attachment>; } export class SubstanceSpecificationCode extends BackboneElement { @Default('fhir.datatypes.SubstanceSpecification.SubstanceSpecificationCode') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public status?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public statusDate?: date; @Validate(yup.string()) public comment?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public source?: Array<FlatConvectorModel<Reference>>; //DocumentReference } export class SubstanceSpecificationName extends BackboneElement { @Default('fhir.datatypes.SubstanceSpecification.SubstanceSpecificationName') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public status?: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public preferred?: boolean; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public language?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public domain?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(SubstanceSpecificationName.schema()))) public synonym?: Array<FlatConvectorModel<SubstanceSpecificationName>>; @Validate(yup.lazy(() => yup.array(SubstanceSpecificationName.schema()))) public translation?: Array<FlatConvectorModel<SubstanceSpecificationName>>; @Validate(yup.lazy(() => yup.array(SubstanceSpecificationNameOfficial.schema()))) public official?: Array<FlatConvectorModel<SubstanceSpecificationNameOfficial>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public source?: Array<FlatConvectorModel<Reference>>; //DocumentReference } export class SubstanceSpecificationNameOfficial extends BackboneElement { @Default('fhir.datatypes.SubstanceSpecification.SubstanceSpecificationNameOfficial') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public authority?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public status?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; } export class SubstanceSpecificationRelationship extends BackboneElement { @Default('fhir.datatypes.SubstanceSpecification.SubstanceSpecificationRelationship') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Reference.schema())) public substanceReference?: FlatConvectorModel<Reference>; //SubstanceSpecification @Validate(yup.lazy(() => CodeableConcept.schema())) public substanceCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public relationship?: FlatConvectorModel<CodeableConcept>; @Validate(yup.boolean()) public isDefining?: boolean; @Validate(yup.lazy(() => Quantity.schema())) public amountQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Range.schema())) public amountRange?: FlatConvectorModel<Range>; @Validate(yup.lazy(() => Ratio.schema())) public amountRatio?: FlatConvectorModel<Ratio>; @Validate(yup.string()) public amountString?: string; @Validate(yup.lazy(() => Ratio.schema())) public amountRatioLowLimit?: FlatConvectorModel<Ratio>; @Validate(yup.lazy(() => CodeableConcept.schema())) public amountType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public source?: Array<FlatConvectorModel<Reference>>; //DocumentReference } export class SubstanceSpecification extends DomainResource<SubstanceSpecification> { @Default('fhir.datatypes.SubstanceSpecification') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public status?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public domain?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public source?: Array<FlatConvectorModel<Reference>>; //DocumentReference @Validate(yup.string()) public comment?: string; @Validate(yup.lazy(() => yup.array(SubstanceSpecificationMoiety.schema()))) public moiety?: Array<FlatConvectorModel<SubstanceSpecificationMoiety>>; @Validate(yup.lazy(() => yup.array(SubstanceSpecificationProperty.schema()))) public property?: Array<FlatConvectorModel<SubstanceSpecificationProperty>>; @Validate(yup.lazy(() => Reference.schema())) public referenceInformation?: FlatConvectorModel<Reference>; //SubstanceReferenceInformation @Validate(yup.lazy(() => SubstanceSpecificationStructure.schema())) public structure?: FlatConvectorModel<SubstanceSpecificationStructure>; @Validate(yup.lazy(() => yup.array(SubstanceSpecificationCode.schema()))) public code?: Array<FlatConvectorModel<SubstanceSpecificationCode>>; @Validate(yup.lazy(() => yup.array(SubstanceSpecificationName.schema()))) public name?: Array<FlatConvectorModel<SubstanceSpecificationName>>; @Validate(yup.lazy(() => yup.array(SubstanceSpecificationStructureIsotopeMolecularWeight.schema()))) public molecularWeight?: Array<FlatConvectorModel<SubstanceSpecificationStructureIsotopeMolecularWeight>>; @Validate(yup.lazy(() => yup.array(SubstanceSpecificationRelationship.schema()))) public relationship?: Array<FlatConvectorModel<SubstanceSpecificationRelationship>>; @Validate(yup.lazy(() => Reference.schema())) public nucleicAcid?: FlatConvectorModel<Reference>; //SubstanceNucleicAcid @Validate(yup.lazy(() => Reference.schema())) public polymer?: FlatConvectorModel<Reference>; //SubstancePolymer @Validate(yup.lazy(() => Reference.schema())) public protein?: FlatConvectorModel<Reference>; //SubstanceProtein @Validate(yup.lazy(() => Reference.schema())) public sourceMaterial?: FlatConvectorModel<Reference>; //SubstanceSourceMaterial } export class SupplyDeliverySuppliedItem extends BackboneElement { @Default('fhir.datatypes.SupplyDelivery.SupplyDeliverySuppliedItem') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => SimpleQuantity.schema())) public quantity?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.lazy(() => CodeableConcept.schema())) public itemCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public itemReference?: FlatConvectorModel<Reference>; //Medication|Substance|Device } export class SupplyDelivery extends DomainResource<SupplyDelivery> { @Default('fhir.datatypes.SupplyDelivery') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //SupplyRequest @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //SupplyDelivery|Contract @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => Reference.schema())) public patient?: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => CodeableConcept.schema())) public type_?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => SupplyDeliverySuppliedItem.schema())) public suppliedItem?: FlatConvectorModel<SupplyDeliverySuppliedItem>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public occurrenceDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public occurrencePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Timing.schema())) public occurrenceTiming?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => Reference.schema())) public supplier?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => Reference.schema())) public destination?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => yup.array(Reference.schema()))) public receiver?: Array<FlatConvectorModel<Reference>>; //Practitioner|PractitionerRole } export class SupplyRequestParameter extends BackboneElement { @Default('fhir.datatypes.SupplyRequest.SupplyRequestParameter') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public valueCodeableConcept?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Quantity.schema())) public valueQuantity?: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => Range.schema())) public valueRange?: FlatConvectorModel<Range>; @Validate(yup.boolean()) public valueBoolean?: boolean; } export class SupplyRequest extends DomainResource<SupplyRequest> { @Default('fhir.datatypes.SupplyRequest') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public status?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public category?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public priority?: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public itemCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Reference.schema())) public itemReference: FlatConvectorModel<Reference>; //Medication|Substance|Device @Required() @Validate(yup.lazy(() => Quantity.schema())) public quantity: FlatConvectorModel<Quantity>; @Validate(yup.lazy(() => yup.array(SupplyRequestParameter.schema()))) public parameter?: Array<FlatConvectorModel<SupplyRequestParameter>>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public occurrenceDateTime?: date; @Validate(yup.lazy(() => Period.schema())) public occurrencePeriod?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => Timing.schema())) public occurrenceTiming?: FlatConvectorModel<Timing>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public authoredOn?: date; @Validate(yup.lazy(() => Reference.schema())) public requester?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|Patient|RelatedPerson|Device @Validate(yup.lazy(() => yup.array(Reference.schema()))) public supplier?: Array<FlatConvectorModel<Reference>>; //Organization|HealthcareService @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public reasonCode?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public reasonReference?: Array<FlatConvectorModel<Reference>>; //Condition|Observation|DiagnosticReport|DocumentReference @Validate(yup.lazy(() => Reference.schema())) public deliverFrom?: FlatConvectorModel<Reference>; //Organization|Location @Validate(yup.lazy(() => Reference.schema())) public deliverTo?: FlatConvectorModel<Reference>; //Organization|Location|Patient } export class TaskRestriction extends BackboneElement { @Default('fhir.datatypes.Task.TaskRestriction') @ReadOnly() public readonly type: string; @Validate(yup.number()) public repetitions?: number; @Validate(yup.lazy(() => Period.schema())) public period?: FlatConvectorModel<Period>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public recipient?: Array<FlatConvectorModel<Reference>>; //Patient|Practitioner|PractitionerRole|RelatedPerson|Group|Organization } export class TaskInput extends BackboneElement { @Default('fhir.datatypes.Task.TaskInput') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; } export class TaskOutput extends BackboneElement { @Default('fhir.datatypes.Task.TaskOutput') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public type_: FlatConvectorModel<CodeableConcept>; } export class Task extends DomainResource<Task> { @Default('fhir.datatypes.Task') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public instantiatesCanonical?: string; //ActivityDefinition @Validate(yup.string()) public instantiatesUri?: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public basedOn?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => Identifier.schema())) public groupIdentifier?: FlatConvectorModel<Identifier>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public partOf?: Array<FlatConvectorModel<Reference>>; //Task @Required() @Validate(yup.string()) public status: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public statusReason?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => CodeableConcept.schema())) public businessStatus?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string()) public intent: string; @Validate(yup.string()) public priority?: string; @Validate(yup.lazy(() => CodeableConcept.schema())) public code?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => Reference.schema())) public focus?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => Reference.schema())) public for?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Validate(yup.lazy(() => Period.schema())) public executionPeriod?: FlatConvectorModel<Period>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public authoredOn?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastModified?: date; @Validate(yup.lazy(() => Reference.schema())) public requester?: FlatConvectorModel<Reference>; //Device|Organization|Patient|Practitioner|PractitionerRole|RelatedPerson @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public performerType?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Reference.schema())) public owner?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization|CareTeam|HealthcareService|Patient|Device|RelatedPerson @Validate(yup.lazy(() => Reference.schema())) public location?: FlatConvectorModel<Reference>; //Location @Validate(yup.lazy(() => CodeableConcept.schema())) public reasonCode?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => Reference.schema())) public reasonReference?: FlatConvectorModel<Reference>; //Any @Validate(yup.lazy(() => yup.array(Reference.schema()))) public insurance?: Array<FlatConvectorModel<Reference>>; //Coverage|ClaimResponse @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public relevantHistory?: Array<FlatConvectorModel<Reference>>; //Provenance @Validate(yup.lazy(() => TaskRestriction.schema())) public restriction?: FlatConvectorModel<TaskRestriction>; @Validate(yup.lazy(() => yup.array(TaskInput.schema()))) public input?: Array<FlatConvectorModel<TaskInput>>; @Validate(yup.lazy(() => yup.array(TaskOutput.schema()))) public output?: Array<FlatConvectorModel<TaskOutput>>; } export class TerminologyCapabilitiesSoftware extends BackboneElement { @Default('fhir.datatypes.TerminologyCapabilities.TerminologyCapabilitiesSoftware') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public version?: string; } export class TerminologyCapabilitiesImplementation extends BackboneElement { @Default('fhir.datatypes.TerminologyCapabilities.TerminologyCapabilitiesImplementation') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public description: string; @Validate(yup.string()) public url?: string; } export class TerminologyCapabilitiesCodeSystem extends BackboneElement { @Default('fhir.datatypes.TerminologyCapabilities.TerminologyCapabilitiesCodeSystem') @ReadOnly() public readonly type: string; @Validate(yup.string()) public uri?: string; //CodeSystem @Validate(yup.lazy(() => yup.array(TerminologyCapabilitiesCodeSystemVersion.schema()))) public version?: Array<FlatConvectorModel<TerminologyCapabilitiesCodeSystemVersion>>; @Validate(yup.boolean()) public subsumption?: boolean; } export class TerminologyCapabilitiesCodeSystemVersion extends BackboneElement { @Default('fhir.datatypes.TerminologyCapabilities.TerminologyCapabilitiesCodeSystemVersion') @ReadOnly() public readonly type: string; @Validate(yup.string()) public code?: string; @Validate(yup.boolean()) public isDefault?: boolean; @Validate(yup.boolean()) public compositional?: boolean; @Validate(yup.array(yup.string())) public language? : Array<string>; @Validate(yup.lazy(() => yup.array(TerminologyCapabilitiesCodeSystemVersionFilter.schema()))) public filter?: Array<FlatConvectorModel<TerminologyCapabilitiesCodeSystemVersionFilter>>; @Validate(yup.array(yup.string())) public property? : Array<string>; } export class TerminologyCapabilitiesCodeSystemVersionFilter extends BackboneElement { @Default('fhir.datatypes.TerminologyCapabilities.TerminologyCapabilitiesCodeSystemVersionFilter') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.array(yup.string())) public op? : Array<string>; } export class TerminologyCapabilitiesExpansion extends BackboneElement { @Default('fhir.datatypes.TerminologyCapabilities.TerminologyCapabilitiesExpansion') @ReadOnly() public readonly type: string; @Validate(yup.boolean()) public hierarchical?: boolean; @Validate(yup.boolean()) public paging?: boolean; @Validate(yup.boolean()) public incomplete?: boolean; @Validate(yup.lazy(() => yup.array(TerminologyCapabilitiesExpansionParameter.schema()))) public parameter?: Array<FlatConvectorModel<TerminologyCapabilitiesExpansionParameter>>; @Validate(yup.string()) public textFilter?: string; } export class TerminologyCapabilitiesExpansionParameter extends BackboneElement { @Default('fhir.datatypes.TerminologyCapabilities.TerminologyCapabilitiesExpansionParameter') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public documentation?: string; } export class TerminologyCapabilitiesValidateCode extends BackboneElement { @Default('fhir.datatypes.TerminologyCapabilities.TerminologyCapabilitiesValidateCode') @ReadOnly() public readonly type: string; @Required() @Validate(yup.boolean()) public translations: boolean; } export class TerminologyCapabilitiesTranslation extends BackboneElement { @Default('fhir.datatypes.TerminologyCapabilities.TerminologyCapabilitiesTranslation') @ReadOnly() public readonly type: string; @Required() @Validate(yup.boolean()) public needsMap: boolean; } export class TerminologyCapabilitiesClosure extends BackboneElement { @Default('fhir.datatypes.TerminologyCapabilities.TerminologyCapabilitiesClosure') @ReadOnly() public readonly type: string; @Validate(yup.boolean()) public translation?: boolean; } export class TerminologyCapabilities extends DomainResource<TerminologyCapabilities> { @Default('fhir.datatypes.TerminologyCapabilities') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public copyright?: string; @Required() @Validate(yup.string()) public kind: string; @Validate(yup.lazy(() => TerminologyCapabilitiesSoftware.schema())) public software?: FlatConvectorModel<TerminologyCapabilitiesSoftware>; @Validate(yup.lazy(() => TerminologyCapabilitiesImplementation.schema())) public implementation?: FlatConvectorModel<TerminologyCapabilitiesImplementation>; @Validate(yup.boolean()) public lockedDate?: boolean; @Validate(yup.lazy(() => yup.array(TerminologyCapabilitiesCodeSystem.schema()))) public codeSystem?: Array<FlatConvectorModel<TerminologyCapabilitiesCodeSystem>>; @Validate(yup.lazy(() => TerminologyCapabilitiesExpansion.schema())) public expansion?: FlatConvectorModel<TerminologyCapabilitiesExpansion>; @Validate(yup.string()) public codeSearch?: string; @Validate(yup.lazy(() => TerminologyCapabilitiesValidateCode.schema())) public validateCode?: FlatConvectorModel<TerminologyCapabilitiesValidateCode>; @Validate(yup.lazy(() => TerminologyCapabilitiesTranslation.schema())) public translation?: FlatConvectorModel<TerminologyCapabilitiesTranslation>; @Validate(yup.lazy(() => TerminologyCapabilitiesClosure.schema())) public closure?: FlatConvectorModel<TerminologyCapabilitiesClosure>; } export class TestReportParticipant extends BackboneElement { @Default('fhir.datatypes.TestReport.TestReportParticipant') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Required() @Validate(yup.string()) public uri: string; @Validate(yup.string()) public display?: string; } export class TestReportSetup extends BackboneElement { @Default('fhir.datatypes.TestReport.TestReportSetup') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(TestReportSetupAction.schema()))) public action?: Array<FlatConvectorModel<TestReportSetupAction>>; } export class TestReportSetupAction extends BackboneElement { @Default('fhir.datatypes.TestReport.TestReportSetupAction') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => TestReportSetupActionOperation.schema())) public operation?: FlatConvectorModel<TestReportSetupActionOperation>; @Validate(yup.lazy(() => TestReportSetupActionAssert.schema())) public assert?: FlatConvectorModel<TestReportSetupActionAssert>; } export class TestReportSetupActionOperation extends BackboneElement { @Default('fhir.datatypes.TestReport.TestReportSetupActionOperation') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public result: string; @Validate(yup.string()) public message?: string; @Validate(yup.string()) public detail?: string; } export class TestReportSetupActionAssert extends BackboneElement { @Default('fhir.datatypes.TestReport.TestReportSetupActionAssert') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public result: string; @Validate(yup.string()) public message?: string; @Validate(yup.string()) public detail?: string; } export class TestReportTest extends BackboneElement { @Default('fhir.datatypes.TestReport.TestReportTest') @ReadOnly() public readonly type: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(TestReportTestAction.schema()))) public action?: Array<FlatConvectorModel<TestReportTestAction>>; } export class TestReportTestAction extends BackboneElement { @Default('fhir.datatypes.TestReport.TestReportTestAction') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => TestReportSetupActionOperation.schema())) public operation?: FlatConvectorModel<TestReportSetupActionOperation>; @Validate(yup.lazy(() => TestReportSetupActionAssert.schema())) public assert?: FlatConvectorModel<TestReportSetupActionAssert>; } export class TestReportTeardown extends BackboneElement { @Default('fhir.datatypes.TestReport.TestReportTeardown') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(TestReportTeardownAction.schema()))) public action?: Array<FlatConvectorModel<TestReportTeardownAction>>; } export class TestReportTeardownAction extends BackboneElement { @Default('fhir.datatypes.TestReport.TestReportTeardownAction') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => TestReportSetupActionOperation.schema())) public operation: FlatConvectorModel<TestReportSetupActionOperation>; } export class TestReport extends DomainResource<TestReport> { @Default('fhir.datatypes.TestReport') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.string()) public name?: string; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public testScript: FlatConvectorModel<Reference>; //TestScript @Required() @Validate(yup.string()) public result: string; @Validate(yup.number()) public score?: number; @Validate(yup.string()) public tester?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public issued?: date; @Validate(yup.lazy(() => yup.array(TestReportParticipant.schema()))) public participant?: Array<FlatConvectorModel<TestReportParticipant>>; @Validate(yup.lazy(() => TestReportSetup.schema())) public setup?: FlatConvectorModel<TestReportSetup>; @Validate(yup.lazy(() => yup.array(TestReportTest.schema()))) public test?: Array<FlatConvectorModel<TestReportTest>>; @Validate(yup.lazy(() => TestReportTeardown.schema())) public teardown?: FlatConvectorModel<TestReportTeardown>; } export class TestScriptOrigin extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptOrigin') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public index: number; @Required() @Validate(yup.lazy(() => Coding.schema())) public profile: FlatConvectorModel<Coding>; } export class TestScriptDestination extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptDestination') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public index: number; @Required() @Validate(yup.lazy(() => Coding.schema())) public profile: FlatConvectorModel<Coding>; } export class TestScriptMetadata extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptMetadata') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(TestScriptMetadataLink.schema()))) public link?: Array<FlatConvectorModel<TestScriptMetadataLink>>; @Validate(yup.lazy(() => yup.array(TestScriptMetadataCapability.schema()))) public capability?: Array<FlatConvectorModel<TestScriptMetadataCapability>>; } export class TestScriptMetadataLink extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptMetadataLink') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public url: string; @Validate(yup.string()) public description?: string; } export class TestScriptMetadataCapability extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptMetadataCapability') @ReadOnly() public readonly type: string; @Required() @Validate(yup.boolean()) public required: boolean; @Required() @Validate(yup.boolean()) public validated: boolean; @Validate(yup.string()) public description?: string; @Validate(yup.array(yup.number())) public origin? : Array<number>; @Validate(yup.number()) public destination?: number; @Validate(yup.array(yup.string())) public link? : Array<string>; @Required() @Validate(yup.string()) public capabilities: string; //CapabilityStatement } export class TestScriptFixture extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptFixture') @ReadOnly() public readonly type: string; @Required() @Validate(yup.boolean()) public autocreate: boolean; @Required() @Validate(yup.boolean()) public autodelete: boolean; @Validate(yup.lazy(() => Reference.schema())) public resource?: FlatConvectorModel<Reference>; //Any } export class TestScriptVariable extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptVariable') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public defaultValue?: string; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public expression?: string; @Validate(yup.string()) public headerField?: string; @Validate(yup.string()) public hint?: string; @Validate(yup.string()) public path?: string; @Validate(yup.string()) public sourceId?: string; } export class TestScriptSetup extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptSetup') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(TestScriptSetupAction.schema()))) public action?: Array<FlatConvectorModel<TestScriptSetupAction>>; } export class TestScriptSetupAction extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptSetupAction') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => TestScriptSetupActionOperation.schema())) public operation?: FlatConvectorModel<TestScriptSetupActionOperation>; @Validate(yup.lazy(() => TestScriptSetupActionAssert.schema())) public assert?: FlatConvectorModel<TestScriptSetupActionAssert>; } export class TestScriptSetupActionOperation extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptSetupActionOperation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Coding.schema())) public type_?: FlatConvectorModel<Coding>; @Validate(yup.string()) public resource?: string; @Validate(yup.string()) public label?: string; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public accept?: string; @Validate(yup.string()) public contentType?: string; @Validate(yup.number()) public destination?: number; @Required() @Validate(yup.boolean()) public encodeRequestUrl: boolean; @Validate(yup.string()) public method?: string; @Validate(yup.number()) public origin?: number; @Validate(yup.string()) public params?: string; @Validate(yup.lazy(() => yup.array(TestScriptSetupActionOperationRequestHeader.schema()))) public requestHeader?: Array<FlatConvectorModel<TestScriptSetupActionOperationRequestHeader>>; @Validate(yup.string()) public requestId?: string; @Validate(yup.string()) public responseId?: string; @Validate(yup.string()) public sourceId?: string; @Validate(yup.string()) public targetId?: string; @Validate(yup.string()) public url?: string; } export class TestScriptSetupActionOperationRequestHeader extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptSetupActionOperationRequestHeader') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public field: string; @Required() @Validate(yup.string()) public value: string; } export class TestScriptSetupActionAssert extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptSetupActionAssert') @ReadOnly() public readonly type: string; @Validate(yup.string()) public label?: string; @Validate(yup.string()) public description?: string; @Validate(yup.string()) public direction?: string; @Validate(yup.string()) public compareToSourceId?: string; @Validate(yup.string()) public compareToSourceExpression?: string; @Validate(yup.string()) public compareToSourcePath?: string; @Validate(yup.string()) public contentType?: string; @Validate(yup.string()) public expression?: string; @Validate(yup.string()) public headerField?: string; @Validate(yup.string()) public minimumId?: string; @Validate(yup.boolean()) public navigationLinks?: boolean; @Validate(yup.string()) public operator?: string; @Validate(yup.string()) public path?: string; @Validate(yup.string()) public requestMethod?: string; @Validate(yup.string()) public requestURL?: string; @Validate(yup.string()) public resource?: string; @Validate(yup.string()) public response?: string; @Validate(yup.string()) public responseCode?: string; @Validate(yup.string()) public sourceId?: string; @Validate(yup.string()) public validateProfileId?: string; @Validate(yup.string()) public value?: string; @Required() @Validate(yup.boolean()) public warningOnly: boolean; } export class TestScriptTest extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptTest') @ReadOnly() public readonly type: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(TestScriptTestAction.schema()))) public action?: Array<FlatConvectorModel<TestScriptTestAction>>; } export class TestScriptTestAction extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptTestAction') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => TestScriptSetupActionOperation.schema())) public operation?: FlatConvectorModel<TestScriptSetupActionOperation>; @Validate(yup.lazy(() => TestScriptSetupActionAssert.schema())) public assert?: FlatConvectorModel<TestScriptSetupActionAssert>; } export class TestScriptTeardown extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptTeardown') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(TestScriptTeardownAction.schema()))) public action?: Array<FlatConvectorModel<TestScriptTeardownAction>>; } export class TestScriptTeardownAction extends BackboneElement { @Default('fhir.datatypes.TestScript.TestScriptTeardownAction') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => TestScriptSetupActionOperation.schema())) public operation: FlatConvectorModel<TestScriptSetupActionOperation>; } export class TestScript extends DomainResource<TestScript> { @Default('fhir.datatypes.TestScript') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public url: string; @Validate(yup.lazy(() => Identifier.schema())) public identifier?: FlatConvectorModel<Identifier>; @Validate(yup.string()) public version?: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.lazy(() => yup.array(TestScriptOrigin.schema()))) public origin?: Array<FlatConvectorModel<TestScriptOrigin>>; @Validate(yup.lazy(() => yup.array(TestScriptDestination.schema()))) public destination?: Array<FlatConvectorModel<TestScriptDestination>>; @Validate(yup.lazy(() => TestScriptMetadata.schema())) public metadata?: FlatConvectorModel<TestScriptMetadata>; @Validate(yup.lazy(() => yup.array(TestScriptFixture.schema()))) public fixture?: Array<FlatConvectorModel<TestScriptFixture>>; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public profile?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.lazy(() => yup.array(TestScriptVariable.schema()))) public variable?: Array<FlatConvectorModel<TestScriptVariable>>; @Validate(yup.lazy(() => TestScriptSetup.schema())) public setup?: FlatConvectorModel<TestScriptSetup>; @Validate(yup.lazy(() => yup.array(TestScriptTest.schema()))) public test?: Array<FlatConvectorModel<TestScriptTest>>; @Validate(yup.lazy(() => TestScriptTeardown.schema())) public teardown?: FlatConvectorModel<TestScriptTeardown>; } export class TriggerDefinition extends DomainResource<TriggerDefinition> { @Default('fhir.datatypes.TriggerDefinition') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public type_: string; @Validate(yup.string()) public name?: string; @Validate(yup.lazy(() => Timing.schema())) public timingTiming?: FlatConvectorModel<Timing>; @Validate(yup.lazy(() => Reference.schema())) public timingReference?: FlatConvectorModel<Reference>; //Schedule @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public timingDate?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public timingDateTime?: date; @Validate(yup.lazy(() => yup.array(DataRequirement.schema()))) public data?: Array<FlatConvectorModel<DataRequirement>>; @Validate(yup.lazy(() => Expression.schema())) public condition?: FlatConvectorModel<Expression>; } export class UsageContext extends DomainResource<UsageContext> { @Default('fhir.datatypes.UsageContext') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Coding.schema())) public code: FlatConvectorModel<Coding>; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public valueCodeableConcept: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.lazy(() => Quantity.schema())) public valueQuantity: FlatConvectorModel<Quantity>; @Required() @Validate(yup.lazy(() => Range.schema())) public valueRange: FlatConvectorModel<Range>; @Required() @Validate(yup.lazy(() => Reference.schema())) public valueReference: FlatConvectorModel<Reference>; //PlanDefinition|ResearchStudy|InsurancePlan|HealthcareService|Group|Location|Organization } export class ValueSetCompose extends BackboneElement { @Default('fhir.datatypes.ValueSet.ValueSetCompose') @ReadOnly() public readonly type: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lockedDate?: date; @Validate(yup.boolean()) public inactive?: boolean; @Validate(yup.lazy(() => yup.array(ValueSetComposeInclude.schema()))) public include?: Array<FlatConvectorModel<ValueSetComposeInclude>>; @Validate(yup.lazy(() => yup.array(ValueSetComposeInclude.schema()))) public exclude?: Array<FlatConvectorModel<ValueSetComposeInclude>>; } export class ValueSetComposeInclude extends BackboneElement { @Default('fhir.datatypes.ValueSet.ValueSetComposeInclude') @ReadOnly() public readonly type: string; @Validate(yup.string()) public system?: string; @Validate(yup.string()) public version?: string; @Validate(yup.lazy(() => yup.array(ValueSetComposeIncludeConcept.schema()))) public concept?: Array<FlatConvectorModel<ValueSetComposeIncludeConcept>>; @Validate(yup.lazy(() => yup.array(ValueSetComposeIncludeFilter.schema()))) public filter?: Array<FlatConvectorModel<ValueSetComposeIncludeFilter>>; @Validate(yup.array(yup.string())) public valueSet? : Array<string>; //ValueSet } export class ValueSetComposeIncludeConcept extends BackboneElement { @Default('fhir.datatypes.ValueSet.ValueSetComposeIncludeConcept') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public code: string; @Validate(yup.string()) public display?: string; @Validate(yup.lazy(() => yup.array(ValueSetComposeIncludeConceptDesignation.schema()))) public designation?: Array<FlatConvectorModel<ValueSetComposeIncludeConceptDesignation>>; } export class ValueSetComposeIncludeConceptDesignation extends BackboneElement { @Default('fhir.datatypes.ValueSet.ValueSetComposeIncludeConceptDesignation') @ReadOnly() public readonly type: string; @Validate(yup.string()) public language?: string; @Validate(yup.lazy(() => Coding.schema())) public use?: FlatConvectorModel<Coding>; @Required() @Validate(yup.string()) public value: string; } export class ValueSetComposeIncludeFilter extends BackboneElement { @Default('fhir.datatypes.ValueSet.ValueSetComposeIncludeFilter') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public property: string; @Required() @Validate(yup.string()) public op: string; @Required() @Validate(yup.string()) public value: string; } export class ValueSetExpansion extends BackboneElement { @Default('fhir.datatypes.ValueSet.ValueSetExpansion') @ReadOnly() public readonly type: string; @Validate(yup.string()) public identifier?: string; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public timestamp: date; @Validate(yup.number()) public total?: number; @Validate(yup.number()) public offset?: number; @Validate(yup.lazy(() => yup.array(ValueSetExpansionParameter.schema()))) public parameter?: Array<FlatConvectorModel<ValueSetExpansionParameter>>; @Validate(yup.lazy(() => yup.array(ValueSetExpansionContains.schema()))) public contains?: Array<FlatConvectorModel<ValueSetExpansionContains>>; } export class ValueSetExpansionParameter extends BackboneElement { @Default('fhir.datatypes.ValueSet.ValueSetExpansionParameter') @ReadOnly() public readonly type: string; @Required() @Validate(yup.string()) public name: string; @Validate(yup.string()) public valueString?: string; @Validate(yup.boolean()) public valueBoolean?: boolean; @Validate(yup.number()) public valueInteger?: number; @Validate(yup.number()) public valueDecimal?: number; @Validate(yup.string()) public valueUri?: string; @Validate(yup.string()) public valueCode?: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public valueDateTime?: date; } export class ValueSetExpansionContains extends BackboneElement { @Default('fhir.datatypes.ValueSet.ValueSetExpansionContains') @ReadOnly() public readonly type: string; @Validate(yup.string()) public system?: string; @Validate(yup.boolean()) public abstract?: boolean; @Validate(yup.boolean()) public inactive?: boolean; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public code?: string; @Validate(yup.string()) public display?: string; @Validate(yup.lazy(() => yup.array(ValueSetComposeIncludeConceptDesignation.schema()))) public designation?: Array<FlatConvectorModel<ValueSetComposeIncludeConceptDesignation>>; @Validate(yup.lazy(() => yup.array(ValueSetExpansionContains.schema()))) public contains?: Array<FlatConvectorModel<ValueSetExpansionContains>>; } export class ValueSet extends DomainResource<ValueSet> { @Default('fhir.datatypes.ValueSet') @ReadOnly() public readonly type: string; @Validate(yup.string()) public url?: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Validate(yup.string()) public version?: string; @Validate(yup.string()) public name?: string; @Validate(yup.string()) public title?: string; @Required() @Validate(yup.string()) public status: string; @Validate(yup.boolean()) public experimental?: boolean; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public publisher?: string; @Validate(yup.lazy(() => yup.array(ContactDetail.schema()))) public contact?: Array<FlatConvectorModel<ContactDetail>>; @Validate(yup.string()) public description?: string; @Validate(yup.lazy(() => yup.array(UsageContext.schema()))) public useContext?: Array<FlatConvectorModel<UsageContext>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public jurisdiction?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.boolean()) public immutable?: boolean; @Validate(yup.string()) public purpose?: string; @Validate(yup.string()) public copyright?: string; @Validate(yup.lazy(() => ValueSetCompose.schema())) public compose?: FlatConvectorModel<ValueSetCompose>; @Validate(yup.lazy(() => ValueSetExpansion.schema())) public expansion?: FlatConvectorModel<ValueSetExpansion>; } export class VerificationResultPrimarySource extends BackboneElement { @Default('fhir.datatypes.VerificationResult.VerificationResultPrimarySource') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Reference.schema())) public who?: FlatConvectorModel<Reference>; //Organization|Practitioner|PractitionerRole @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public type_?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public communicationMethod?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => CodeableConcept.schema())) public validationStatus?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public validationDate?: date; @Validate(yup.lazy(() => CodeableConcept.schema())) public canPushUpdates?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public pushTypeAvailable?: Array<FlatConvectorModel<CodeableConcept>>; } export class VerificationResultAttestation extends BackboneElement { @Default('fhir.datatypes.VerificationResult.VerificationResultAttestation') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => Reference.schema())) public who?: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole|Organization @Validate(yup.lazy(() => Reference.schema())) public onBehalfOf?: FlatConvectorModel<Reference>; //Organization|Practitioner|PractitionerRole @Validate(yup.lazy(() => CodeableConcept.schema())) public communicationMethod?: FlatConvectorModel<CodeableConcept>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public date?: date; @Validate(yup.string()) public sourceIdentityCertificate?: string; @Validate(yup.string()) public proxyIdentityCertificate?: string; @Validate(yup.lazy(() => Signature.schema())) public proxySignature?: FlatConvectorModel<Signature>; @Validate(yup.lazy(() => Signature.schema())) public sourceSignature?: FlatConvectorModel<Signature>; } export class VerificationResultValidator extends BackboneElement { @Default('fhir.datatypes.VerificationResult.VerificationResultValidator') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => Reference.schema())) public organization: FlatConvectorModel<Reference>; //Organization @Validate(yup.string()) public identityCertificate?: string; @Validate(yup.lazy(() => Signature.schema())) public attestationSignature?: FlatConvectorModel<Signature>; } export class VerificationResult extends DomainResource<VerificationResult> { @Default('fhir.datatypes.VerificationResult') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Reference.schema()))) public target?: Array<FlatConvectorModel<Reference>>; //Any @Validate(yup.array(yup.string())) public targetLocation? : Array<string>; @Validate(yup.lazy(() => CodeableConcept.schema())) public need?: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string()) public status: string; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public statusDate?: date; @Validate(yup.lazy(() => CodeableConcept.schema())) public validationType?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(CodeableConcept.schema()))) public validationProcess?: Array<FlatConvectorModel<CodeableConcept>>; @Validate(yup.lazy(() => Timing.schema())) public frequency?: FlatConvectorModel<Timing>; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public lastPerformed?: date; @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public nextScheduled?: date; @Validate(yup.lazy(() => CodeableConcept.schema())) public failureAction?: FlatConvectorModel<CodeableConcept>; @Validate(yup.lazy(() => yup.array(VerificationResultPrimarySource.schema()))) public primarySource?: Array<FlatConvectorModel<VerificationResultPrimarySource>>; @Validate(yup.lazy(() => VerificationResultAttestation.schema())) public attestation?: FlatConvectorModel<VerificationResultAttestation>; @Validate(yup.lazy(() => yup.array(VerificationResultValidator.schema()))) public validator?: Array<FlatConvectorModel<VerificationResultValidator>>; } export class VisionPrescriptionLensSpecification extends BackboneElement { @Default('fhir.datatypes.VisionPrescription.VisionPrescriptionLensSpecification') @ReadOnly() public readonly type: string; @Required() @Validate(yup.lazy(() => CodeableConcept.schema())) public product: FlatConvectorModel<CodeableConcept>; @Required() @Validate(yup.string()) public eye: string; @Validate(yup.number()) public sphere?: number; @Validate(yup.number()) public cylinder?: number; @Validate(yup.number()) public axis?: number; @Validate(yup.lazy(() => yup.array(VisionPrescriptionLensSpecificationPrism.schema()))) public prism?: Array<FlatConvectorModel<VisionPrescriptionLensSpecificationPrism>>; @Validate(yup.number()) public add?: number; @Validate(yup.number()) public power?: number; @Validate(yup.number()) public backCurve?: number; @Validate(yup.number()) public diameter?: number; @Validate(yup.lazy(() => SimpleQuantity.schema())) public duration?: FlatConvectorModel<SimpleQuantity>; @Validate(yup.string()) public color?: string; @Validate(yup.string()) public brand?: string; @Validate(yup.lazy(() => yup.array(Annotation.schema()))) public note?: Array<FlatConvectorModel<Annotation>>; } export class VisionPrescriptionLensSpecificationPrism extends BackboneElement { @Default('fhir.datatypes.VisionPrescription.VisionPrescriptionLensSpecificationPrism') @ReadOnly() public readonly type: string; @Required() @Validate(yup.number()) public amount: number; @Required() @Validate(yup.string()) public base: string; } export class VisionPrescription extends DomainResource<VisionPrescription> { @Default('fhir.datatypes.VisionPrescription') @ReadOnly() public readonly type: string; @Validate(yup.lazy(() => yup.array(Identifier.schema()))) public identifier?: Array<FlatConvectorModel<Identifier>>; @Required() @Validate(yup.string()) public status: string; @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public created: date; @Required() @Validate(yup.lazy(() => Reference.schema())) public patient: FlatConvectorModel<Reference>; //Patient @Validate(yup.lazy(() => Reference.schema())) public encounter?: FlatConvectorModel<Reference>; //Encounter @Required() @Validate(yup.string().matches(fhirTypes.dateRegex, 'Invalid Date')) public dateWritten: date; @Required() @Validate(yup.lazy(() => Reference.schema())) public prescriber: FlatConvectorModel<Reference>; //Practitioner|PractitionerRole @Validate(yup.lazy(() => yup.array(VisionPrescriptionLensSpecification.schema()))) public lensSpecification?: Array<FlatConvectorModel<VisionPrescriptionLensSpecification>>; }
the_stack
module TDev.AST.ExprParser { export var infixProps:any = null; function getInfixProperty(o:string) { if (infixProps == null) { infixProps = {} var api = TDev.api; [api.core.Number, api.core.Boolean, api.core.String, api.core.Unknown].forEach(function (k:Kind) { k.listProperties().forEach(function (p:IProperty) { if (p.getInfixPriority() > 0 && !infixProps[p.getName()]) infixProps[p.getName()] = p; }); }); } if (/^fun:/.test(o)) o = "fun" return infixProps[o]; } var isDigit = (c:string) => /^[0-9]$/.test(c); function mkComma(op0:StackOp) { var r = new StackOp(); r.copyFrom(op0); r.type = "operator"; r.infixProperty = getInfixProperty(","); r.op = ","; return r; } function mkZero(op0:StackOp) { var r = new StackOp(); r.copyFrom(op0); r.type = "literal"; r.expr = mkLit(0.0); r.expr.loc = r; return r; } export function parse0(tokens:Token[]) { var dt:string; var res:StackOp[] = []; for (var i = 0; i < tokens.length; ++i) { tokens[i].clearError(); } for (var i = 0; i < tokens.length; ++i) { var t = tokens[i]; var r = new StackOp(); r.type = t.nodeType(); r.tokens = tokens; r.beg = i; r.len = 1; res.push(r); switch (r.type) { case "literal": case "thingRef": // r.expr = AstNode.mk({ type: r.type, data: (<any> t).data }); r.expr = <Expr>t; r.expr.loc = r; break; case "propertyRef": r.propertyRef = <PropertyRef>t; break; case "operator": dt = t.getText(); if (/^[0-9\.]$/.test(dt)) { var seenDot = false; var num = ""; var c = ""; while (i < tokens.length) { if (tokens[i].nodeType() !== "operator") break; c = tokens[i].getText(); if (isDigit(c)) { num += c; } else if (c === "." && !seenDot) { num += c; seenDot = true; } else break; i++; } r.len = i - r.beg; i--; if (num === ".") { r.markError(lf("TD142: expecting a digit before or after the dot")); num = "0.0"; } r.type = "literal"; var lit = mkLit(parseFloat(num)); lit.stringForm = num r.expr = lit r.expr.loc = r; } else { if (dt === "(" || dt === ")") r.prioOverride = -1; else r.infixProperty = getInfixProperty(dt); if (!r.prio()) r.markError(lf("TD143: unknown operator {0}", dt)); // shouldn't happen r.op = dt; } break; default: Util.die(); break; } } return res; } export function parse1(tokens0:Token[]) { var tokens = parse0(tokens0); var currentTok = 0; if (tokens.length == 1 && tokens[0].prio() == api.opStmtPriority) { var z = mkZero(tokens[0]) z.expr = mkPlaceholderThingRef() tokens.push(z) } function expect(op:string) { var loc:StackOp = null; if (currentTok >= tokens.length) loc = tokens.peek(); else loc = tokens[currentTok]; if (currentTok >= tokens.length || loc.op !== op) { loc.markError(lf("TD144: it seems you're missing '{0}', try adding it", op)); return false; } else { currentTok++; return true; } } function reduceOps(stack:StackOp[], minPrio:number) { if (minPrio == 4 || minPrio == 98) minPrio++; // priority 4 and 98 binds right var top = stack.pop(); while (stack.length > 0 && stack.peek().prio() >= minPrio) { var curOp = stack.pop(); var leftArg = stack.pop(); Util.assert(!!leftArg.expr); var prop = curOp.infixProperty; var args = [leftArg.expr, top.expr]; if (prop.getInfixPriority() > 0 && prop.getParameters().length === 1) { args = [top.expr]; } var endLoc = top.beg + top.len; var newTop = new StackOp(); newTop.tokens = top.tokens; top = newTop; var pr = PropertyRef.mkProp(curOp.infixProperty) top.expr = mkCall(pr, args); var op = curOp.tokens[curOp.beg] if (op instanceof Operator) { (<Operator>op).call = <Call>top.expr pr.fromOp = <Operator>op } top.beg = leftArg.beg; top.len = endLoc - top.beg; Util.assert(!isNaN(top.len)); top.expr.loc = top; } stack.push(top); } function parseCallArgs(firstArg:Expr) : Expr[] { var args:AstNode[] = []; var t = tokens[currentTok]; if (!t) return [firstArg]; if (t.op === "(") { currentTok++; t = tokens[currentTok]; if (!t) { expect(")") return [firstArg] } } else if (t.expr) { t.markError(lf("TD145: there seem to be an operator (like '+', '(' or ',') missing here")); // and keep going } else { return [firstArg] } if (!!t && t.op == ")") { currentTok++; return [firstArg]; } var e = parseParenFree(false); args = e.flatten(TDev.api.core.TupleProp); expect(")"); return [firstArg].concat(<Expr[]>args); } function parseParenFree(isTop:boolean):Expr { var stack:StackOp[] = []; while (currentTok < tokens.length) { var prev = stack.peek(); var op = tokens[currentTok++]; var prevExpr = prev != null ? prev.expr : null; if (op.expr !== null) { if (prev != null && prev.prio() === 0) { op.markError(lf("TD145: there seem to be an operator (like '+', '(' or ',') missing here")); stack.push(mkComma(op)); } if (prev != null && prev.prioOverride == 98 && op.expr instanceof Literal) { (<Literal>op.expr).possiblyNegative = true } stack.push(op); } else if (op.prio() > 0) { if (prevExpr === null && op.op === "-") { op.prioOverride = 98; prev = mkZero(op); stack.push(prev); } if (op.op === "not" || op.op == "async" || op.op == "await" || /^fun:/.test(op.op) || op.prio() == api.opStmtPriority) { if (prevExpr === null) { prev = mkZero(op); stack.push(prev); } else { op.markError(lf("TD146: we didn't expect '{0}' here", op.op)) } } if (!prev || !prev.expr) { op.markError(lf("TD147: we didn't expect '{0}' here", op.op)); if (op.op == ",") { stack.push(mkZero(op)); reduceOps(stack, op.prio()); stack.push(op); } } else { reduceOps(stack, op.prio()); stack.push(op); } } else if (op.type === "propertyRef") { // prefix property? if (!prevExpr) { if (stack.length > 1 && stack[stack.length - 2].expr !== null) { var stackTop = stack.pop() stackTop.markError(lf("TD148: we didn't expect {0} here", stackTop.op ? "'" + stackTop.op + "'" : lf("this"))) prevExpr = stack.peek().expr; // and continue with normal parsing } else { op.markError(lf("TD149: property needs an expression in front")); continue; } } else { var end = op.beg + op.len; op.beg = prev.beg; op.len = end - op.beg; stack.pop(); } var args = parseCallArgs(prevExpr); op.expr = mkCall(op.propertyRef, args); op.expr.loc = op; var prevTok = tokens[currentTok - 1]; op.len = prevTok.beg + prevTok.len - op.beg; Util.assert(!isNaN(op.len)); stack.push(op); } else if (op.prio() < 0) { if (op.op === "(") { if (prevExpr) { op.markError(lf("TD150: cannot call the thing before '('")); stack.push(mkComma(op)); } var nl = new StackOp(); nl.expr = parseParenFree(false); nl.expr.loc = nl; nl.copyFrom(op); stack.push(nl); if (!expect(")")) { op.markError(lf("TD151: unclosed '('")); } var lasttok = tokens[currentTok - 1] nl.len = lasttok.beg + lasttok.len - op.beg; } else if (op.op === ")") { if (isTop) { op.markError(lf("TD152: unexpected ')'")); } else { currentTok--; break; } } } else { // doesn't happen? op.markError(lf("TD153: parse error")); } } while (stack.length > 0) { if (stack.peek().expr === null) { stack.peek().markError(lf("TD154: the operator needs something after it")); if (/^fun:/.test(stack.peek().op)) { stack.push(mkZero(stack.peek())) break } else { stack.pop(); } } else { break; } } reduceOps(stack, 0.1); var t = stack.peek(); if (!t || !t.expr) return <Expr>mkPlaceholderThingRef(); else return t.expr; } return parseParenFree(true); } }
the_stack
const keywords = { a: "", abort: "non-reserved", abs: "", absent: "", absolute: "non-reserved", access: "non-reserved", according: "", action: "non-reserved", ada: "", add: "non-reserved", admin: "non-reserved", after: "non-reserved", aggregate: "non-reserved", all: "reserved", allocate: "", also: "non-reserved", alter: "non-reserved", always: "non-reserved", analyse: "reserved", analyze: "reserved", and: "reserved", any: "reserved", are: "", array: "reserved", array_agg: "", array_max_cardinality: "", as: "reserved", asc: "reserved", asensitive: "", assertion: "non-reserved", assignment: "non-reserved", asymmetric: "reserved", at: "non-reserved", atomic: "", attach: "non-reserved", attribute: "non-reserved", attributes: "", authorization: "reserved (can be function or type)", avg: "", backward: "non-reserved", base64: "", before: "non-reserved", begin: "non-reserved", begin_frame: "", begin_partition: "", bernoulli: "", between: "non-reserved (cannot be function or type)", bigint: "non-reserved (cannot be function or type)", binary: "reserved (can be function or type)", bit: "non-reserved (cannot be function or type)", bit_length: "", blob: "", blocked: "", bom: "", boolean: "non-reserved (cannot be function or type)", both: "reserved", breadth: "", by: "non-reserved", c: "", cache: "non-reserved", call: "", called: "non-reserved", cardinality: "", cascade: "non-reserved", cascaded: "non-reserved", case: "reserved", cast: "reserved", catalog: "non-reserved", catalog_name: "", ceil: "", ceiling: "", chain: "non-reserved", char: "non-reserved (cannot be function or type)", character: "non-reserved (cannot be function or type)", characteristics: "non-reserved", characters: "", character_length: "", character_set_catalog: "", character_set_name: "", character_set_schema: "", char_length: "", check: "reserved", checkpoint: "non-reserved", class: "non-reserved", class_origin: "", clob: "", close: "non-reserved", cluster: "non-reserved", coalesce: "non-reserved (cannot be function or type)", cobol: "", collate: "reserved", collation: "reserved (can be function or type)", collation_catalog: "", collation_name: "", collation_schema: "", collect: "", column: "reserved", columns: "non-reserved", column_name: "", command_function: "", command_function_code: "", comment: "non-reserved", comments: "non-reserved", commit: "non-reserved", committed: "non-reserved", concurrently: "reserved (can be function or type)", condition: "", condition_number: "", configuration: "non-reserved", conflict: "non-reserved", connect: "", connection: "non-reserved", connection_name: "", constraint: "reserved", constraints: "non-reserved", constraint_catalog: "", constraint_name: "", constraint_schema: "", constructor: "", contains: "", content: "non-reserved", continue: "non-reserved", control: "", conversion: "non-reserved", convert: "", copy: "non-reserved", corr: "", corresponding: "", cost: "non-reserved", count: "", covar_pop: "", covar_samp: "", create: "reserved", cross: "reserved (can be function or type)", csv: "non-reserved", cube: "non-reserved", cume_dist: "", current: "non-reserved", current_catalog: "reserved", current_date: "reserved", current_default_transform_group: "", current_path: "", current_role: "reserved", current_row: "", current_schema: "reserved (can be function or type)", current_time: "reserved", current_timestamp: "reserved", current_transform_group_for_type: "", current_user: "reserved", cursor: "non-reserved", cursor_name: "", cycle: "non-reserved", data: "non-reserved", database: "non-reserved", datalink: "", date: "", datetime_interval_code: "", datetime_interval_precision: "", day: "non-reserved", db: "", deallocate: "non-reserved", dec: "non-reserved (cannot be function or type)", decimal: "non-reserved (cannot be function or type)", declare: "non-reserved", default: "reserved", defaults: "non-reserved", deferrable: "reserved", deferred: "non-reserved", defined: "", definer: "non-reserved", degree: "", delete: "non-reserved", delimiter: "non-reserved", delimiters: "non-reserved", dense_rank: "", depends: "non-reserved", depth: "", deref: "", derived: "", desc: "reserved", describe: "", descriptor: "", detach: "non-reserved", deterministic: "", diagnostics: "", dictionary: "non-reserved", disable: "non-reserved", discard: "non-reserved", disconnect: "", dispatch: "", distinct: "reserved", dlnewcopy: "", dlpreviouscopy: "", dlurlcomplete: "", dlurlcompleteonly: "", dlurlcompletewrite: "", dlurlpath: "", dlurlpathonly: "", dlurlpathwrite: "", dlurlscheme: "", dlurlserver: "", dlvalue: "", do: "reserved", document: "non-reserved", domain: "non-reserved", double: "non-reserved", drop: "non-reserved", dynamic: "", dynamic_function: "", dynamic_function_code: "", each: "non-reserved", element: "", else: "reserved", empty: "", enable: "non-reserved", encoding: "non-reserved", encrypted: "non-reserved", end: "reserved", "end-exec": "", end_frame: "", end_partition: "", enforced: "", enum: "non-reserved", equals: "", escape: "non-reserved", event: "non-reserved", every: "", except: "reserved", exception: "", exclude: "non-reserved", excluding: "non-reserved", exclusive: "non-reserved", exec: "", execute: "non-reserved", exists: "non-reserved (cannot be function or type)", exp: "", explain: "non-reserved", expression: "", extension: "non-reserved", external: "non-reserved", extract: "non-reserved (cannot be function or type)", false: "reserved", family: "non-reserved", fetch: "reserved", file: "", filter: "non-reserved", final: "", first: "non-reserved", first_value: "", flag: "", float: "non-reserved (cannot be function or type)", floor: "", following: "non-reserved", for: "reserved", force: "non-reserved", foreign: "reserved", fortran: "", forward: "non-reserved", found: "", frame_row: "", free: "", freeze: "reserved (can be function or type)", from: "reserved", fs: "", full: "reserved (can be function or type)", function: "non-reserved", functions: "non-reserved", fusion: "", g: "", general: "", generated: "non-reserved", get: "", global: "non-reserved", go: "", goto: "", grant: "reserved", granted: "non-reserved", greatest: "non-reserved (cannot be function or type)", group: "reserved", grouping: "non-reserved (cannot be function or type)", groups: "", handler: "non-reserved", having: "reserved", header: "non-reserved", hex: "", hierarchy: "", hold: "non-reserved", hour: "non-reserved", id: "", identity: "non-reserved", if: "non-reserved", ignore: "", ilike: "reserved (can be function or type)", immediate: "non-reserved", immediately: "", immutable: "non-reserved", implementation: "", implicit: "non-reserved", import: "non-reserved", in: "reserved", including: "non-reserved", increment: "non-reserved", indent: "", index: "non-reserved", indexes: "non-reserved", indicator: "", inherit: "non-reserved", inherits: "non-reserved", initially: "reserved", inline: "non-reserved", inner: "reserved (can be function or type)", inout: "non-reserved (cannot be function or type)", input: "non-reserved", insensitive: "non-reserved", insert: "non-reserved", instance: "", instantiable: "", instead: "non-reserved", int: "non-reserved (cannot be function or type)", integer: "non-reserved (cannot be function or type)", integrity: "", intersect: "reserved", intersection: "", interval: "non-reserved (cannot be function or type)", into: "reserved", invoker: "non-reserved", is: "reserved (can be function or type)", isnull: "reserved (can be function or type)", isolation: "non-reserved", join: "reserved (can be function or type)", k: "", key: "non-reserved", key_member: "", key_type: "", label: "non-reserved", lag: "", language: "non-reserved", large: "non-reserved", last: "non-reserved", last_value: "", lateral: "reserved", lead: "", leading: "reserved", leakproof: "non-reserved", least: "non-reserved (cannot be function or type)", left: "reserved (can be function or type)", length: "", level: "non-reserved", library: "", like: "reserved (can be function or type)", like_regex: "", limit: "reserved", link: "", listen: "non-reserved", ln: "", load: "non-reserved", local: "non-reserved", localtime: "reserved", localtimestamp: "reserved", location: "non-reserved", locator: "", lock: "non-reserved", locked: "non-reserved", logged: "non-reserved", lower: "", m: "", map: "", mapping: "non-reserved", match: "non-reserved", matched: "", materialized: "non-reserved", max: "", maxvalue: "non-reserved", max_cardinality: "", member: "", merge: "", message_length: "", message_octet_length: "", message_text: "", method: "non-reserved", min: "", minute: "non-reserved", minvalue: "non-reserved", mod: "", mode: "non-reserved", modifies: "", module: "", month: "non-reserved", more: "", move: "non-reserved", multiset: "", mumps: "", name: "non-reserved", names: "non-reserved", namespace: "", national: "non-reserved (cannot be function or type)", natural: "reserved (can be function or type)", nchar: "non-reserved (cannot be function or type)", nclob: "", nesting: "", new: "non-reserved", next: "non-reserved", nfc: "", nfd: "", nfkc: "", nfkd: "", nil: "", no: "non-reserved", none: "non-reserved (cannot be function or type)", normalize: "", normalized: "", not: "reserved", nothing: "non-reserved", notify: "non-reserved", notnull: "reserved (can be function or type)", nowait: "non-reserved", nth_value: "", ntile: "", null: "reserved", nullable: "", nullif: "non-reserved (cannot be function or type)", nulls: "non-reserved", number: "", numeric: "non-reserved (cannot be function or type)", object: "non-reserved", occurrences_regex: "", octets: "", octet_length: "", of: "non-reserved", off: "non-reserved", offset: "reserved", oids: "non-reserved", old: "non-reserved", on: "reserved", only: "reserved", open: "", operator: "non-reserved", option: "non-reserved", options: "non-reserved", or: "reserved", order: "reserved", ordering: "", ordinality: "non-reserved", others: "", out: "non-reserved (cannot be function or type)", outer: "reserved (can be function or type)", output: "", over: "non-reserved", overlaps: "reserved (can be function or type)", overlay: "non-reserved (cannot be function or type)", overriding: "non-reserved", owned: "non-reserved", owner: "non-reserved", p: "", pad: "", parallel: "non-reserved", parameter: "", parameter_mode: "", parameter_name: "", parameter_ordinal_position: "", parameter_specific_catalog: "", parameter_specific_name: "", parameter_specific_schema: "", parser: "non-reserved", partial: "non-reserved", partition: "non-reserved", pascal: "", passing: "non-reserved", passthrough: "", password: "non-reserved", path: "", percent: "", percentile_cont: "", percentile_disc: "", percent_rank: "", period: "", permission: "", placing: "reserved", plans: "non-reserved", pli: "", policy: "non-reserved", portion: "", position: "non-reserved (cannot be function or type)", position_regex: "", power: "", precedes: "", preceding: "non-reserved", precision: "non-reserved (cannot be function or type)", prepare: "non-reserved", prepared: "non-reserved", preserve: "non-reserved", primary: "reserved", prior: "non-reserved", privileges: "non-reserved", procedural: "non-reserved", procedure: "non-reserved", program: "non-reserved", public: "", publication: "non-reserved", quote: "non-reserved", range: "non-reserved", rank: "", read: "non-reserved", reads: "", real: "non-reserved (cannot be function or type)", reassign: "non-reserved", recheck: "non-reserved", recovery: "", recursive: "non-reserved", ref: "non-reserved", references: "reserved", referencing: "non-reserved", refresh: "non-reserved", regr_avgx: "", regr_avgy: "", regr_count: "", regr_intercept: "", regr_r2: "", regr_slope: "", regr_sxx: "", regr_sxy: "", regr_syy: "", reindex: "non-reserved", relative: "non-reserved", release: "non-reserved", rename: "non-reserved", repeatable: "non-reserved", replace: "non-reserved", replica: "non-reserved", requiring: "", reset: "non-reserved", respect: "", restart: "non-reserved", restore: "", restrict: "non-reserved", result: "", return: "", returned_cardinality: "", returned_length: "", returned_octet_length: "", returned_sqlstate: "", returning: "reserved", returns: "non-reserved", revoke: "non-reserved", right: "reserved (can be function or type)", role: "non-reserved", rollback: "non-reserved", rollup: "non-reserved", routine: "", routine_catalog: "", routine_name: "", routine_schema: "", row: "non-reserved (cannot be function or type)", rows: "non-reserved", row_count: "", row_number: "", rule: "non-reserved", savepoint: "non-reserved", scale: "", schema: "non-reserved", schemas: "non-reserved", schema_name: "", scope: "", scope_catalog: "", scope_name: "", scope_schema: "", scroll: "non-reserved", search: "non-reserved", second: "non-reserved", section: "", security: "non-reserved", select: "reserved", selective: "", self: "", sensitive: "", sequence: "non-reserved", sequences: "non-reserved", serializable: "non-reserved", server: "non-reserved", server_name: "", session: "non-reserved", session_user: "reserved", set: "non-reserved", setof: "non-reserved (cannot be function or type)", sets: "non-reserved", share: "non-reserved", show: "non-reserved", similar: "reserved (can be function or type)", simple: "non-reserved", size: "", skip: "non-reserved", smallint: "non-reserved (cannot be function or type)", snapshot: "non-reserved", some: "reserved", source: "", space: "", specific: "", specifictype: "", specific_name: "", sql: "non-reserved", sqlcode: "", sqlerror: "", sqlexception: "", sqlstate: "", sqlwarning: "", sqrt: "", stable: "non-reserved", standalone: "non-reserved", start: "non-reserved", state: "", statement: "non-reserved", static: "", statistics: "non-reserved", stddev_pop: "", stddev_samp: "", stdin: "non-reserved", stdout: "non-reserved", storage: "non-reserved", strict: "non-reserved", strip: "non-reserved", structure: "", style: "", subclass_origin: "", submultiset: "", subscription: "non-reserved", substring: "non-reserved (cannot be function or type)", substring_regex: "", succeeds: "", sum: "", symmetric: "reserved", sysid: "non-reserved", system: "non-reserved", system_time: "", system_user: "", t: "", table: "reserved", tables: "non-reserved", tablesample: "reserved (can be function or type)", tablespace: "non-reserved", table_name: "", temp: "non-reserved", template: "non-reserved", temporary: "non-reserved", text: "non-reserved", then: "reserved", ties: "", time: "non-reserved (cannot be function or type)", timestamp: "non-reserved (cannot be function or type)", timezone_hour: "", timezone_minute: "", to: "reserved", token: "", top_level_count: "", trailing: "reserved", transaction: "non-reserved", transactions_committed: "", transactions_rolled_back: "", transaction_active: "", transform: "non-reserved", transforms: "", translate: "", translate_regex: "", translation: "", treat: "non-reserved (cannot be function or type)", trigger: "non-reserved", trigger_catalog: "", trigger_name: "", trigger_schema: "", trim: "non-reserved (cannot be function or type)", trim_array: "", true: "reserved", truncate: "non-reserved", trusted: "non-reserved", type: "non-reserved", types: "non-reserved", uescape: "", unbounded: "non-reserved", uncommitted: "non-reserved", under: "", unencrypted: "non-reserved", union: "reserved", unique: "reserved", unknown: "non-reserved", unlink: "", unlisten: "non-reserved", unlogged: "non-reserved", unnamed: "", unnest: "", until: "non-reserved", untyped: "", update: "non-reserved", upper: "", uri: "", usage: "", user: "reserved", user_defined_type_catalog: "", user_defined_type_code: "", user_defined_type_name: "", user_defined_type_schema: "", using: "reserved", vacuum: "non-reserved", valid: "non-reserved", validate: "non-reserved", validator: "non-reserved", value: "non-reserved", values: "non-reserved (cannot be function or type)", value_of: "", varbinary: "", varchar: "non-reserved (cannot be function or type)", variadic: "reserved", varying: "non-reserved", var_pop: "", var_samp: "", verbose: "reserved (can be function or type)", version: "non-reserved", versioning: "", view: "non-reserved", views: "non-reserved", volatile: "non-reserved", when: "reserved", whenever: "", where: "reserved", whitespace: "non-reserved", width_bucket: "", window: "reserved", with: "reserved", within: "non-reserved", without: "non-reserved", work: "non-reserved", wrapper: "non-reserved", write: "non-reserved", xml: "non-reserved", xmlagg: "", xmlattributes: "non-reserved (cannot be function or type)", xmlbinary: "", xmlcast: "", xmlcomment: "", xmlconcat: "non-reserved (cannot be function or type)", xmldeclaration: "", xmldocument: "", xmlelement: "non-reserved (cannot be function or type)", xmlexists: "non-reserved (cannot be function or type)", xmlforest: "non-reserved (cannot be function or type)", xmliterate: "", xmlnamespaces: "non-reserved (cannot be function or type)", xmlparse: "non-reserved (cannot be function or type)", xmlpi: "non-reserved (cannot be function or type)", xmlquery: "", xmlroot: "non-reserved (cannot be function or type)", xmlschema: "", xmlserialize: "non-reserved (cannot be function or type)", xmltable: "non-reserved (cannot be function or type)", xmltext: "", xmlvalidate: "", year: "non-reserved", yes: "non-reserved", zone: "non-reserved", }; export default Object.keys(keywords);
the_stack
import { Agile, CallbackSubscriptionContainer, ComponentSubscriptionContainer, RuntimeJob, Observer, Runtime, SubscriptionContainer, } from '../../../src'; import * as Utils from '@agile-ts/utils'; import { LogMock } from '../../helper/logMock'; import waitForExpect from 'wait-for-expect'; describe('Runtime Tests', () => { let dummyAgile: Agile; beforeEach(() => { LogMock.mockLogs(); dummyAgile = new Agile(); jest.clearAllMocks(); }); it('should create Runtime', () => { const runtime = new Runtime(dummyAgile); expect(runtime.agileInstance()).toBe(dummyAgile); expect(runtime.currentJob).toBeNull(); expect(runtime.jobQueue).toStrictEqual([]); expect(runtime.jobsToRerender).toStrictEqual([]); expect(Array.from(runtime.notReadyJobsToRerender)).toStrictEqual([]); expect(runtime.isPerformingJobs).toBeFalsy(); expect(runtime.bucketTimeout).toBeNull(); }); describe('Runtime Function Tests', () => { let runtime: Runtime; let dummyObserver1: Observer; let dummyObserver2: Observer; let dummyObserver3: Observer; beforeEach(() => { runtime = new Runtime(dummyAgile); dummyObserver1 = new Observer(dummyAgile, { key: 'dummyObserver1' }); dummyObserver2 = new Observer(dummyAgile, { key: 'dummyObserver2' }); dummyObserver3 = new Observer(dummyAgile, { key: 'dummyObserver3' }); }); describe('ingest function tests', () => { let dummyJob: RuntimeJob; beforeEach(() => { dummyJob = new RuntimeJob(dummyObserver1); runtime.perform = jest.fn(); }); it("should perform specified Job immediately if jobQueue isn't being processed (default config)", () => { runtime.isPerformingJobs = false; runtime.ingest(dummyJob); expect(runtime.jobQueue).toStrictEqual([]); expect(runtime.perform).toHaveBeenCalledWith(dummyJob); }); it("shouldn't perform specified Job immediately if jobQueue is being processed (default config)", () => { runtime.isPerformingJobs = true; runtime.ingest(dummyJob); expect(runtime.jobQueue).toStrictEqual([dummyJob]); expect(runtime.perform).not.toHaveBeenCalled(); }); it('should perform specified Job immediately (config.perform = true)', () => { runtime.isPerformingJobs = true; runtime.ingest(dummyJob, { perform: true }); expect(runtime.jobQueue).toStrictEqual([]); expect(runtime.perform).toHaveBeenCalledWith(dummyJob); }); it("shouldn't perform specified Job immediately (config.perform = false)", () => { runtime.isPerformingJobs = false; runtime.ingest(dummyJob, { perform: false }); expect(runtime.jobQueue).toStrictEqual([dummyJob]); expect(runtime.perform).not.toHaveBeenCalled(); }); }); describe('perform function tests', () => { let dummyJob1: RuntimeJob; let dummyJob2: RuntimeJob; let dummyJob3: RuntimeJob; beforeEach(() => { dummyJob1 = new RuntimeJob(dummyObserver1, { key: 'dummyJob1' }); dummyJob2 = new RuntimeJob(dummyObserver2, { key: 'dummyJob2' }); dummyJob3 = new RuntimeJob(dummyObserver1, { key: 'dummyJob3' }); dummyJob1.rerender = true; dummyJob2.rerender = true; dummyJob3.rerender = false; runtime.updateSubscribers = jest.fn(); jest.spyOn(dummyObserver1, 'perform'); jest.spyOn(dummyObserver2, 'perform'); dummyObserver1.ingest = jest.fn(); dummyObserver2.ingest = jest.fn(); }); it( "should perform specified Job and all remaining Jobs in the 'jobQueue' " + "and call 'updateSubscribers' in a setTimeout (bucket) " + 'if at least one performed Job needs to rerender (config.bucket = true)', async () => { runtime.agileInstance().config.bucket = true; runtime.bucketTimeout = null; runtime.jobQueue.push(dummyJob2); runtime.jobQueue.push(dummyJob3); runtime.perform(dummyJob1); expect(dummyObserver1.perform).toHaveBeenCalledWith(dummyJob1); expect(dummyJob1.performed).toBeTruthy(); expect(dummyObserver2.perform).toHaveBeenCalledWith(dummyJob2); expect(dummyJob2.performed).toBeTruthy(); expect(dummyObserver1.perform).toHaveBeenCalledWith(dummyJob3); expect(dummyJob3.performed).toBeTruthy(); expect(runtime.isPerformingJobs).toBeFalsy(); // because Jobs were performed expect(runtime.jobQueue).toStrictEqual([]); expect(runtime.jobsToRerender).toStrictEqual([dummyJob1, dummyJob2]); expect(runtime.bucketTimeout).not.toBeNull(); // Because 'updateSubscribers' is called in a timeout await waitForExpect(() => { expect(runtime.updateSubscribers).toHaveBeenCalledTimes(1); expect(runtime.bucketTimeout).toBeNull(); }); } ); it( "should perform specified Job and all remaining Jobs in the 'jobQueue' " + "and call 'updateSubscribers' " + 'if at least one performed Job needs to rerender (config.bucket = false)', async () => { runtime.agileInstance().config.bucket = false; runtime.bucketTimeout = null; runtime.jobQueue.push(dummyJob2); runtime.jobQueue.push(dummyJob3); runtime.perform(dummyJob1); expect(runtime.bucketTimeout).toBeNull(); expect(runtime.updateSubscribers).toHaveBeenCalledTimes(1); } ); it( "should perform specified Job and all remaining Jobs in the 'jobQueue' " + "and shouldn't call 'updateSubscribers' although at least one performed Job needs to rerender" + 'if a bucket timeout is already active (config.bucket = true)', async () => { runtime.agileInstance().config.bucket = true; runtime.bucketTimeout = 'notNull' as any; runtime.jobQueue.push(dummyJob2); runtime.jobQueue.push(dummyJob3); runtime.perform(dummyJob1); expect(runtime.bucketTimeout).toBe('notNull'); expect(runtime.updateSubscribers).not.toHaveBeenCalled(); } ); it('should perform specified Job and ingest its dependents into the runtime', async () => { dummyJob1.observer.dependents.add(dummyObserver2); dummyJob1.observer.dependents.add(dummyObserver1); runtime.perform(dummyJob1); expect(dummyObserver1.perform).toHaveBeenCalledWith(dummyJob1); expect(dummyJob1.performed).toBeTruthy(); expect(dummyObserver1.ingest).toHaveBeenCalledTimes(1); expect(dummyObserver2.ingest).toHaveBeenCalledTimes(1); }); it( "should perform specified Job and all remaining Jobs in the 'jobQueue' " + "and shouldn't call 'updateSubscribes' " + 'if no performed Job needs to rerender', async () => { dummyJob1.rerender = false; runtime.jobQueue.push(dummyJob3); runtime.perform(dummyJob1); expect(dummyObserver1.perform).toHaveBeenCalledWith(dummyJob1); expect(dummyJob1.performed).toBeTruthy(); expect(dummyObserver1.perform).toHaveBeenCalledWith(dummyJob3); expect(dummyJob3.performed).toBeTruthy(); expect(runtime.isPerformingJobs).toBeFalsy(); // because Jobs were performed expect(runtime.jobQueue).toStrictEqual([]); expect(runtime.jobsToRerender).toStrictEqual([]); expect(runtime.bucketTimeout).toBeNull(); expect(runtime.updateSubscribers).not.toHaveBeenCalled(); } ); }); describe('updateSubscribers function tests', () => { let dummyJob1: RuntimeJob; let dummyJob2: RuntimeJob; let dummyJob3: RuntimeJob; const dummySubscriptionContainer1IntegrationInstance = () => { /* empty function */ }; let dummySubscriptionContainer1: SubscriptionContainer; const dummySubscriptionContainer2IntegrationInstance = { my: 'cool component', }; let dummySubscriptionContainer2: SubscriptionContainer; beforeEach(() => { dummySubscriptionContainer1 = dummyAgile.subController.subscribe( dummySubscriptionContainer1IntegrationInstance, [dummyObserver1] ); dummySubscriptionContainer2 = dummyAgile.subController.subscribe( dummySubscriptionContainer2IntegrationInstance, [dummyObserver2, dummyObserver3] ); dummyJob1 = new RuntimeJob(dummyObserver1); dummyJob2 = new RuntimeJob(dummyObserver2); dummyJob3 = new RuntimeJob(dummyObserver3); runtime.updateSubscriptionContainer = jest.fn(); jest.spyOn(runtime, 'extractToUpdateSubscriptionContainer'); }); it('should return false if Agile has no registered Integration', () => { dummyAgile.hasIntegration = jest.fn(() => false); runtime.jobsToRerender = [dummyJob1, dummyJob2]; const response = runtime.updateSubscribers(); expect(response).toBeFalsy(); expect(runtime.jobsToRerender).toStrictEqual([]); expect(Array.from(runtime.notReadyJobsToRerender)).toStrictEqual([]); expect( runtime.extractToUpdateSubscriptionContainer ).not.toHaveBeenCalled(); expect(runtime.updateSubscriptionContainer).not.toHaveBeenCalled(); }); it('should return false if jobsToRerender and notReadyJobsToRerender queue are both empty', () => { dummyAgile.hasIntegration = jest.fn(() => true); runtime.jobsToRerender = []; runtime.notReadyJobsToRerender = new Set(); const response = runtime.updateSubscribers(); expect(response).toBeFalsy(); expect(response).toBeFalsy(); expect(runtime.jobsToRerender).toStrictEqual([]); expect(Array.from(runtime.notReadyJobsToRerender)).toStrictEqual([]); expect( runtime.extractToUpdateSubscriptionContainer ).not.toHaveBeenCalled(); expect(runtime.updateSubscriptionContainer).not.toHaveBeenCalled(); }); it('should return false if no Subscription Container of the Jobs to rerender queue needs to update', () => { dummyAgile.hasIntegration = jest.fn(() => true); jest .spyOn(runtime, 'extractToUpdateSubscriptionContainer') .mockReturnValueOnce([]); runtime.jobsToRerender = [dummyJob1, dummyJob2]; runtime.notReadyJobsToRerender = new Set([dummyJob3]); const response = runtime.updateSubscribers(); expect(response).toBeFalsy(); expect(runtime.jobsToRerender).toStrictEqual([]); expect(Array.from(runtime.notReadyJobsToRerender)).toStrictEqual([]); expect( runtime.extractToUpdateSubscriptionContainer ).toHaveBeenCalledWith([dummyJob1, dummyJob2, dummyJob3]); expect(runtime.updateSubscriptionContainer).not.toHaveBeenCalled(); }); it('should return true if at least one Subscription Container of the Jobs to rerender queue needs to update', () => { dummyAgile.hasIntegration = jest.fn(() => true); jest .spyOn(runtime, 'extractToUpdateSubscriptionContainer') .mockReturnValueOnce([ dummySubscriptionContainer1, dummySubscriptionContainer2, ]); runtime.jobsToRerender = [dummyJob1, dummyJob2]; runtime.notReadyJobsToRerender = new Set([dummyJob3]); const response = runtime.updateSubscribers(); expect(response).toBeTruthy(); expect(runtime.jobsToRerender).toStrictEqual([]); expect(Array.from(runtime.notReadyJobsToRerender)).toStrictEqual([]); expect( runtime.extractToUpdateSubscriptionContainer ).toHaveBeenCalledWith([dummyJob1, dummyJob2, dummyJob3]); expect(runtime.updateSubscriptionContainer).toHaveBeenCalledWith([ dummySubscriptionContainer1, dummySubscriptionContainer2, ]); }); }); describe('extractToUpdateSubscriptionContainer function tests', () => { let dummyJob1: RuntimeJob; let dummyJob2: RuntimeJob; const dummySubscriptionContainer1IntegrationInstance = () => { /* empty function */ }; let dummySubscriptionContainer1: SubscriptionContainer; const dummySubscriptionContainer2IntegrationInstance = { my: 'cool component', }; let dummySubscriptionContainer2: SubscriptionContainer; beforeEach(() => { dummySubscriptionContainer1 = dummyAgile.subController.subscribe( dummySubscriptionContainer1IntegrationInstance, [dummyObserver1] ); dummySubscriptionContainer2 = dummyAgile.subController.subscribe( dummySubscriptionContainer2IntegrationInstance, [dummyObserver2] ); dummyJob1 = new RuntimeJob(dummyObserver1); dummyJob2 = new RuntimeJob(dummyObserver2); jest.spyOn(runtime, 'handleSelectors'); }); it( "shouldn't extract not ready Subscription Container from the specified Jobs, " + "should add it to the 'notReadyJobsToRerender' queue and print a warning", () => { jest .spyOn(runtime, 'handleSelectors') .mockReturnValueOnce(true) .mockReturnValueOnce(true); dummySubscriptionContainer1.ready = true; dummySubscriptionContainer2.ready = false; const response = runtime.extractToUpdateSubscriptionContainer([ dummyJob1, dummyJob2, ]); expect(response).toStrictEqual([dummySubscriptionContainer1]); // Called with Job that ran through expect(runtime.handleSelectors).toHaveBeenCalledTimes(1); expect(runtime.handleSelectors).toHaveBeenCalledWith( dummySubscriptionContainer1, dummyJob1 ); expect(Array.from(runtime.notReadyJobsToRerender)).toStrictEqual([ dummyJob2, ]); // Job that ran through expect( Array.from(dummyJob1.subscriptionContainersToUpdate) ).toStrictEqual([]); expect(dummyJob1.timesTriedToUpdateCount).toBe(0); expect( Array.from(dummySubscriptionContainer1.updatedSubscribers) ).toStrictEqual([dummyObserver1]); // Job that didn't ran through expect( Array.from(dummyJob2.subscriptionContainersToUpdate) ).toStrictEqual([dummySubscriptionContainer2]); expect(dummyJob2.timesTriedToUpdateCount).toBe(1); expect( Array.from(dummySubscriptionContainer2.updatedSubscribers) ).toStrictEqual([]); // Called with Job that didn't ran through expect(console.warn).toHaveBeenCalledTimes(1); LogMock.hasLoggedCode( '16:02:00', [dummySubscriptionContainer2.key], dummySubscriptionContainer2 ); } ); it( "shouldn't extract not ready Subscription Container from the specified Jobs, " + "should remove the Job when it exceeded the max 'maxTriesToUpdate' " + 'and print a warning', () => { jest .spyOn(runtime, 'handleSelectors') .mockReturnValueOnce(true) .mockReturnValueOnce(true); dummySubscriptionContainer1.ready = true; dummySubscriptionContainer2.ready = false; const numberOfTries = (dummyJob2.config.maxTriesToUpdate ?? 0) + 1; dummyJob2.timesTriedToUpdateCount = numberOfTries; const response = runtime.extractToUpdateSubscriptionContainer([ dummyJob1, dummyJob2, ]); expect(response).toStrictEqual([dummySubscriptionContainer1]); // Called with Job that ran through expect(runtime.handleSelectors).toHaveBeenCalledTimes(1); expect(runtime.handleSelectors).toHaveBeenCalledWith( dummySubscriptionContainer1, dummyJob1 ); expect(Array.from(runtime.notReadyJobsToRerender)).toStrictEqual([]); // Because exceeded Job was removed // Job that ran through expect( Array.from(dummyJob1.subscriptionContainersToUpdate) ).toStrictEqual([]); expect(dummyJob1.timesTriedToUpdateCount).toBe(0); expect( Array.from(dummySubscriptionContainer1.updatedSubscribers) ).toStrictEqual([dummyObserver1]); // Job that didn't ran through expect( Array.from(dummyJob2.subscriptionContainersToUpdate) ).toStrictEqual([dummySubscriptionContainer2]); expect(dummyJob2.timesTriedToUpdateCount).toBe(numberOfTries); expect( Array.from(dummySubscriptionContainer2.updatedSubscribers) ).toStrictEqual([]); // Called with Job that didn't ran through expect(console.warn).toHaveBeenCalledTimes(1); LogMock.hasLoggedCode( '16:02:01', [dummyJob2.config.maxTriesToUpdate], dummySubscriptionContainer2 ); } ); it("shouldn't extract Subscription Container if the selected property hasn't changed", () => { jest .spyOn(runtime, 'handleSelectors') .mockReturnValueOnce(false) .mockReturnValueOnce(true); dummySubscriptionContainer1.ready = true; dummySubscriptionContainer2.ready = true; const response = runtime.extractToUpdateSubscriptionContainer([ dummyJob1, dummyJob2, ]); expect(response).toStrictEqual([dummySubscriptionContainer2]); expect(runtime.handleSelectors).toHaveBeenCalledTimes(2); expect(runtime.handleSelectors).toHaveBeenCalledWith( dummySubscriptionContainer1, dummyJob1 ); expect(runtime.handleSelectors).toHaveBeenCalledWith( dummySubscriptionContainer2, dummyJob2 ); // Since the Job is ready but the Observer value simply hasn't changed // -> no point in trying to update it again expect(Array.from(runtime.notReadyJobsToRerender)).toStrictEqual([]); // Job that didn't ran through expect( Array.from(dummyJob1.subscriptionContainersToUpdate) ).toStrictEqual([]); expect(dummyJob1.timesTriedToUpdateCount).toBe(0); expect( Array.from(dummySubscriptionContainer1.updatedSubscribers) ).toStrictEqual([]); // Job that ran through expect( Array.from(dummyJob2.subscriptionContainersToUpdate) ).toStrictEqual([]); expect(dummyJob2.timesTriedToUpdateCount).toBe(0); expect( Array.from(dummySubscriptionContainer2.updatedSubscribers) ).toStrictEqual([dummyObserver2]); expect(console.warn).toHaveBeenCalledTimes(0); }); it('should extract ready and to update Subscription Containers', () => { jest .spyOn(runtime, 'handleSelectors') .mockReturnValueOnce(true) .mockReturnValueOnce(true); dummySubscriptionContainer1.ready = true; dummySubscriptionContainer2.ready = true; const response = runtime.extractToUpdateSubscriptionContainer([ dummyJob1, dummyJob2, ]); expect(response).toStrictEqual([ dummySubscriptionContainer1, dummySubscriptionContainer2, ]); expect(runtime.handleSelectors).toHaveBeenCalledTimes(2); expect(runtime.handleSelectors).toHaveBeenCalledWith( dummySubscriptionContainer1, dummyJob1 ); expect(runtime.handleSelectors).toHaveBeenCalledWith( dummySubscriptionContainer2, dummyJob2 ); expect(Array.from(runtime.notReadyJobsToRerender)).toStrictEqual([]); // Job that ran through expect( Array.from(dummyJob1.subscriptionContainersToUpdate) ).toStrictEqual([]); expect(dummyJob1.timesTriedToUpdateCount).toBe(0); expect( Array.from(dummySubscriptionContainer1.updatedSubscribers) ).toStrictEqual([dummyObserver1]); // Job that ran through expect( Array.from(dummyJob2.subscriptionContainersToUpdate) ).toStrictEqual([]); expect(dummyJob2.timesTriedToUpdateCount).toBe(0); expect( Array.from(dummySubscriptionContainer2.updatedSubscribers) ).toStrictEqual([dummyObserver2]); expect(console.warn).not.toHaveBeenCalled(); }); }); describe('updateSubscriptionContainer function tests', () => { const dummyIntegration1 = { dummy: 'component' }; let componentSubscriptionContainer1: ComponentSubscriptionContainer; const dummyIntegration2 = jest.fn(); let callbackSubscriptionContainer2: CallbackSubscriptionContainer; const dummyIntegration3 = jest.fn(); let callbackSubscriptionContainer3: CallbackSubscriptionContainer; beforeEach(() => { componentSubscriptionContainer1 = dummyAgile.subController.subscribe( dummyIntegration1, [dummyObserver1] ) as ComponentSubscriptionContainer; componentSubscriptionContainer1.updatedSubscribers = new Set([ dummyObserver1, ]); callbackSubscriptionContainer2 = dummyAgile.subController.subscribe( dummyIntegration2, [dummyObserver2] ) as CallbackSubscriptionContainer; callbackSubscriptionContainer2.updatedSubscribers = new Set([ dummyObserver2, ]); callbackSubscriptionContainer3 = dummyAgile.subController.subscribe( dummyIntegration3, [dummyObserver3] ) as CallbackSubscriptionContainer; callbackSubscriptionContainer3.updatedSubscribers = new Set([ dummyObserver3, ]); dummyAgile.integrations.update = jest.fn(); }); it('should update the specified Subscription Container', () => { jest .spyOn(runtime, 'getUpdatedObserverValues') .mockReturnValueOnce('propsBasedOnUpdatedObservers' as any); runtime.updateSubscriptionContainer([ componentSubscriptionContainer1, callbackSubscriptionContainer2, callbackSubscriptionContainer3, ]); // Component Subscription Container 1 expect(dummyAgile.integrations.update).toHaveBeenCalledTimes(1); expect(dummyAgile.integrations.update).toHaveBeenCalledWith( dummyIntegration1, 'propsBasedOnUpdatedObservers' ); expect( Array.from(componentSubscriptionContainer1.updatedSubscribers) ).toStrictEqual([]); // Callback Subscription Container 2 expect(callbackSubscriptionContainer2.callback).toHaveBeenCalledTimes( 1 ); expect( Array.from(callbackSubscriptionContainer2.updatedSubscribers) ).toStrictEqual([]); // Callback Subscription Container 3 expect(callbackSubscriptionContainer3.callback).toHaveBeenCalledTimes( 1 ); expect( Array.from(callbackSubscriptionContainer2.updatedSubscribers) ).toStrictEqual([]); }); }); describe('getUpdatedObserverValues function tests', () => { let subscriptionContainer: SubscriptionContainer; const dummyFunction = () => { /* empty function */ }; beforeEach(() => { subscriptionContainer = dummyAgile.subController.subscribe( dummyFunction, [dummyObserver1, dummyObserver2, dummyObserver3] ); dummyObserver1.value = 'dummyObserverValue1'; dummyObserver3.value = 'dummyObserverValue3'; dummyObserver1.key = 'dummyObserver1KeyInObserver'; dummyObserver2.key = undefined; subscriptionContainer.subscriberKeysWeakMap.set( dummyObserver2, 'dummyObserver2KeyInWeakMap' ); dummyObserver3.key = 'dummyObserver3KeyInObserver'; subscriptionContainer.subscriberKeysWeakMap.set( dummyObserver3, 'dummyObserver3KeyInWeakMap' ); }); it('should map the values of the updated Observers into an object and return it', () => { subscriptionContainer.updatedSubscribers.add(dummyObserver1); subscriptionContainer.updatedSubscribers.add(dummyObserver2); subscriptionContainer.updatedSubscribers.add(dummyObserver3); const props = runtime.getUpdatedObserverValues(subscriptionContainer); expect(props).toStrictEqual({ dummyObserver1KeyInObserver: 'dummyObserverValue1', dummyObserver2KeyInWeakMap: null, dummyObserver3KeyInWeakMap: 'dummyObserverValue3', }); expect( Array.from(subscriptionContainer.updatedSubscribers) ).toStrictEqual([dummyObserver1, dummyObserver2, dummyObserver3]); }); }); describe('handleSelector function tests', () => { let objectSubscriptionContainer: SubscriptionContainer; const dummyFunction = () => { /* empty function */ }; let objectJob: RuntimeJob; let arraySubscriptionContainer: SubscriptionContainer; const dummyFunction2 = () => { /* empty function */ }; let arrayJob: RuntimeJob; beforeEach(() => { // Create Job with object based value objectSubscriptionContainer = dummyAgile.subController.subscribe( dummyFunction, [dummyObserver1] ); dummyObserver1.value = { data: { name: 'jeff' }, }; dummyObserver1.previousValue = { data: { name: 'jeff' }, }; objectSubscriptionContainer.selectorsWeakMap.set(dummyObserver1, { methods: [(value) => value?.data?.name], }); objectJob = new RuntimeJob(dummyObserver1, { key: 'dummyObjectJob1' }); // Create Job with array based value arraySubscriptionContainer = dummyAgile.subController.subscribe( dummyFunction2, { dummyObserver2: dummyObserver2 } ).subscriptionContainer; dummyObserver2.value = [ { data: { name: 'jeff' }, }, { data: { name: 'hans' }, }, { data: { name: 'frank' }, }, ]; dummyObserver2.previousValue = [ { data: { name: 'jeff' }, }, { data: { name: 'hans' }, }, { data: { name: 'frank' }, }, ]; arraySubscriptionContainer.selectorsWeakMap.set(dummyObserver2, { methods: [ (value) => value[0]?.data?.name, (value) => value[2]?.data?.name, ], }); arrayJob = new RuntimeJob(dummyObserver2, { key: 'dummyObjectJob2' }); jest.spyOn(Utils, 'notEqual'); // Because not equals is called once during the creation of the Subscription Containers jest.clearAllMocks(); }); it('should return true if Subscription Container has no selector methods', () => { objectSubscriptionContainer.selectorsWeakMap.delete(dummyObserver1); const response = runtime.handleSelectors( objectSubscriptionContainer, objectJob ); expect(response).toBeTruthy(); expect(Utils.notEqual).not.toHaveBeenCalled(); }); it('should return true if selected property has changed (object value)', () => { dummyObserver1.value = { data: { name: 'changedName' }, }; const response = runtime.handleSelectors( objectSubscriptionContainer, objectJob ); expect(response).toBeTruthy(); expect(Utils.notEqual).toHaveBeenCalledTimes(1); expect(Utils.notEqual).toHaveBeenCalledWith( dummyObserver1.value.data.name, dummyObserver1.previousValue.data.name ); }); it("should return false if selected property hasn't changed (object value)", () => { const response = runtime.handleSelectors( objectSubscriptionContainer, objectJob ); expect(response).toBeFalsy(); expect(Utils.notEqual).toHaveBeenCalledTimes(1); expect(Utils.notEqual).toHaveBeenCalledWith( dummyObserver1.value.data.name, dummyObserver1.previousValue.data.name ); }); // TODO the deepness check isn't possible with the current way of handling selector methods // it('should return true if selected property has changed in the deepness (object value)', () => { // dummyObserver1.value = { // key: 'dummyObserverValue1', // }; // dummyObserver1.previousValue = { // key: 'dummyObserverValue1', // data: { name: undefined }, // }; // // const response = runtime.handleSelectors( // objectSubscriptionContainer, // objectJob // ); // // expect(response).toBeTruthy(); // expect(Utils.notEqual).toHaveBeenCalledWith(undefined, undefined); // }); it('should return true if a selected property has changed (array value)', () => { dummyObserver2.value = [ { data: { name: 'jeff' }, }, { data: { name: 'hans' }, }, { data: { name: 'changedName' }, }, ]; const response = runtime.handleSelectors( arraySubscriptionContainer, arrayJob ); expect(response).toBeTruthy(); expect(Utils.notEqual).toHaveBeenCalledTimes(2); expect(Utils.notEqual).toHaveBeenCalledWith( dummyObserver2.value['0'].data.name, dummyObserver2.previousValue['0'].data.name ); expect(Utils.notEqual).toHaveBeenCalledWith( dummyObserver2.value['2'].data.name, dummyObserver2.previousValue['2'].data.name ); }); it("should return false if used property hasn't changed (array value)", () => { dummyObserver2.value = [ { data: { name: 'jeff' }, }, { data: { name: 'changedName (but not selected)' }, }, { data: { name: 'frank' }, }, ]; const response = runtime.handleSelectors( arraySubscriptionContainer, arrayJob ); expect(response).toBeFalsy(); expect(Utils.notEqual).toHaveBeenCalledTimes(2); expect(Utils.notEqual).toHaveBeenCalledWith( dummyObserver2.value['0'].data.name, dummyObserver2.previousValue['0'].data.name ); expect(Utils.notEqual).toHaveBeenCalledWith( dummyObserver2.value['2'].data.name, dummyObserver2.previousValue['2'].data.name ); }); }); }); });
the_stack
import { extractGlobTypes } from 'html-typings'; import { joinPages } from './tools/joinPages'; import { polymerBuild } from './tools/build'; import processhtml from 'gulp-processhtml'; import childProcess from 'child_process'; import StreamZip from 'node-stream-zip'; import beautify from 'gulp-beautify'; import Undertaker from 'undertaker'; import replace from 'gulp-replace'; import gulpBabel from 'gulp-babel'; import ts from 'gulp-typescript'; import rename from 'gulp-rename'; import banner from 'gulp-banner'; import * as rollup from 'rollup'; import xpi from 'firefox-xpi'; import crisper from 'crisper'; import mkdirp from 'mkdirp'; import zip from 'gulp-zip'; import "reflect-metadata"; import chalk from 'chalk'; import which from 'which'; import gulp from 'gulp'; import glob from 'glob'; import path from 'path'; import del from 'del'; import fs from 'fs'; // Only show subtasks when they are actually being run, otherwise // the -T screen is just being spammed const REGISTER_SUBTASKS = process.argv.indexOf('-T') === -1 && process.argv.indexOf('--tasks') === -1; const BANNERS = { html: '<!--Original can be found at https://www.github.com/SanderRonde' + '/CustomRightClickMenu\nThis code may only be used under the MIT' + ' style license found in the LICENSE.txt file-->\n', js: '/*!\n * Original can be found at https://github.com/SanderRonde' + '/CustomRightClickMenu \n * This code may only be used under the MIT' + ' style license found in the LICENSE.txt file \n**/\n' } type DescribedFunction<T extends ReturnFunction = ReturnFunction> = T & { description: string; } type ReturnFunction = (() => void)|(() => Promise<any>)| (() => NodeJS.ReadWriteStream)|Undertaker.TaskFunction; const descriptions: Map<string, string> = new Map(); /** * Generates a root task with given description * root tasks are meant to be called, contrary to * child tasks which are just there to preserve * structure and to be called for specific reasons. */ function genRootTask<T extends ReturnFunction>(name: string, description: string, toRun: T): T { if (!toRun && typeof description !== 'string') { console.log(`Missing root task name for task with description ${description}`); process.exit(1); } (toRun as DescribedFunction).description = description; descriptions.set(name, description); return toRun; } /** * Creates a directory */ function assertDir(dirPath: string): Promise<void> { return new Promise((resolve, reject) => { mkdirp(dirPath, (err) => { if (err) { reject(err); } else { resolve(); } }) }); } /** * Write a file */ function writeFile(filePath: string, data: string, options?: { encoding?: 'utf8'; }): Promise<void> { return new Promise(async (resolve, reject) => { await assertDir(path.dirname(filePath)).catch((err) => { resolve(err); }); if (!options) { fs.writeFile(filePath, data, { encoding: 'utf8' }, (err) => { if (err) { reject(err); } else { resolve(); } }); } else { fs.writeFile(filePath, data, options, (err) => { if (err) { reject(err); } else { resolve(); } }); } }); } /** * Caches the stream piped into this. If glob is provided, * uses the glob to source a stream from given glob * using cwd if provided, default is ./ (aka project root) */ function cacheStream(name: string, glob?: string | string[], cwd?: string): NodeJS.ReadWriteStream { const stream = gulp.dest(`./.buildcache/${name}/`); if (glob) { return gulp.src(glob, { cwd: cwd || __dirname }).pipe(stream); } return stream; } /** * Checks if cache with given name exists */ function cacheExists(name: string): boolean { return fs.existsSync(`./.buildcache/${name}`); } /** * Reads the cache and tries to find given cache name. * If it fails, calls fallback and uses it instead */ function cache(name: string, fallback: () => NodeJS.ReadWriteStream): NodeJS.ReadWriteStream { if (!(cacheExists(name))) { return fallback().pipe(cacheStream(name)); } return gulp.src(`./.buildcache/${name}/**/*`); } /** * Read a file */ function readFile(filePath: string, options?: { encoding?: 'utf8'; }): Promise<string> { return new Promise<string>((resolve, reject) => { if (!options) { fs.readFile(filePath, { encoding: 'utf8' }, (err, data) => { if (err) { reject(err); } else { resolve(data); } }); } else { fs.readFile(filePath, options, (err, data) => { if (err) { reject(err); } else { resolve(data.toString()); } }); } }); } /* Decorators */ interface TaskStructure { type: 'parallel'|'series'; children: (TaskStructure|ReturnFunction)[]; } function parallel(...tasks: (ReturnFunction|TaskStructure)[]): TaskStructure { return { type: 'parallel', children: tasks } } function series(...tasks: (ReturnFunction|TaskStructure)[]): TaskStructure { return { type: 'series', children: tasks } } function describe(description: string): MethodDecorator { return (_target, _propertyName, descriptor) => { (descriptor.value as unknown as DescribedFunction).description = description; } } const taskClassMetaKey = Symbol('task-class'); function taskClass(name: string): ClassDecorator { return (target) => { Reflect.defineMetadata(taskClassMetaKey, name, target); } } const groupMetaKey = Symbol('group'); // Not used for anything as of now except for documentation purposes function group(name: string): PropertyDecorator { return (target, propertyKey) => { Reflect.defineMetadata(groupMetaKey, name, target, propertyKey); } } const rootTaskMetaKey = Symbol('root-task'); function rootTask(nameOrDescription: string, description?: string): PropertyDecorator { let name: string = null; if (!description) { description = nameOrDescription; } else { name = nameOrDescription; } return ((target: any, propertyKey: string, descr: any) => { descr && ((descr.value as DescribedFunction).description = description); descriptions.set(name || propertyKey, description); Reflect.defineMetadata(rootTaskMetaKey, [name || propertyKey, description], target, propertyKey); }) as any; } const subtaskMetaKey = Symbol('root-task'); function subTask(nameOrDescription: string, description?: string): PropertyDecorator { let name: string = ''; if (!description) { description = nameOrDescription; } else { name = nameOrDescription; } return (target, propertyKey) => { Reflect.defineMetadata(subtaskMetaKey, [name, description], target, propertyKey); } } @taskClass('') class Tasks { @group('convenience') static Convenience = (() => { class Convenience { static Clean = (() => { @taskClass('clean') class Clean { @describe('Cleans the build cache dir') static async cache() { await del('./.buildcache'); } @describe('Cleans the /build directory') static async build() { await del('./build'); } @describe('Cleans the /dist directory') static async dist() { await del('./dist'); } @rootTask('cleanDist', 'Cleans the /dist directory') static cleanDist = series( Clean.dist ); @rootTask('clean', 'Cleans the building and caching directories') static clean = parallel( Clean.cache, Clean.build, Clean.dist ); } return Clean; })(); static PrepareForHotReload = (() => { @taskClass('prepareForHotReload') class PrepareForHotReload { @describe('Crisps the bower components') static crispComponents() { return new Promise((resolve, reject) => { glob('./app/bower_components/**/*.html', async (err, matches) => { if (err) { reject(err); return; } await Promise.all([matches.map((file) => { return new Promise(async (resolve) => { const content = await readFile(file); const { name, dir } = path.parse(file); const { html, js } = crisper({ jsFileName: `${name}.js`, source: content, scriptInHead: false, cleanup: false }); await Promise.all([ writeFile(file, html), writeFile(path.join(dir, `${name}.js`), js), ]); resolve(); }); })]).catch(reject); resolve(); }); }); }; @describe('Copies monaco files and beautifies them') static copyMonacoBeautiful() { return gulp .src([ '**/**', ], { base: 'node_modules/monaco-editor/min', cwd: 'node_modules/monaco-editor/min' }) .pipe(replace(/node = node\.parentNode/g, 'node = node.parentNode || node.host')) .pipe(replace(/document\.body/g, 'MonacoEditorHookManager.getLocalBodyShadowRoot')) .pipe(replace(/document\.caretRangeFromPoint/g, 'MonacoEditorHookManager.caretRangeFromPoint(arguments[0])')) .pipe(replace(/this.target(\s)?=(\s)?e.target/g, 'this.target = e.path ? e.path[0] : e.target')) .pipe(beautify()) .pipe(gulp.dest('app/elements/options/editpages/monaco-editor/src/min/')); }; @describe('Embed the typescript compiler') static tsEmbedDev() { return gulp .src('typescript.js', { cwd: './node_modules/typescript/lib', base: './node_modules/typescript/lib' }) .pipe(gulp.dest('./app/js/libraries/')) }; @describe('Embed the less compiler') static async lessEmbedDev() { const less = await readFile('./resources/buildresources/less.min.js'); await writeFile('./app/js/libraries/less.js', less); }; @describe('Embed the stylus compiler)') static async stylusEmbedDev() { const stylus = await readFile('./resources/buildresources/stylus.min.js'); await writeFile('./app/js/libraries/stylus.js', stylus); }; @describe('Embed the CRM API definitions)') static async crmapiLib() { await writeFile('./app/js/libraries/crmapi.d.ts', await Tasks.Definitions._joinDefs()); }; @rootTask('prepareForHotReload', 'Prepares the extension for hot reloading, developing through ' + 'the app/ directory instead and not having to build make sure to run ' + '`yarn install --force --ignore-engines` before this') static prepareForHotReload = parallel( PrepareForHotReload.crispComponents, PrepareForHotReload.copyMonacoBeautiful, PrepareForHotReload.tsEmbedDev, PrepareForHotReload.lessEmbedDev, PrepareForHotReload.stylusEmbedDev, PrepareForHotReload.crmapiLib ) } return PrepareForHotReload; })(); @rootTask('disableHotReload', 'Disables hot reloading, required for proper build') static disableHotReload() { return new Promise((resolve, reject) => { which('yarn', (err, cmdPath) => { if (err) { reject(err); } else { const cmd = childProcess.spawn(cmdPath, ['--force', '--ignore-engines']); cmd.on('close', (code) => { if (code !== 0) { reject(`Yarn failed with exit code ${code}`) } else { resolve(); } }); } }); }); } } return Convenience; })(); @group('i18n') static I18N = (() => { interface I18NMessage { message: string; description?: string; placeholders?: { [key: string]: { content: string; example?: string; } } } type I18NRoot = { [key: string]: I18NRoot|I18NMessage; }; @taskClass('i18n') class I18N { private static _isMessage(descriptor: I18NMessage|I18NRoot): descriptor is I18NMessage { if (!('message' in descriptor)) return false; return typeof descriptor.message === 'string'; } private static _isIgnored(key: string) { return key === '$schema' || key === 'comments'; } private static _walkMessages(root: I18NRoot, fn: (message: I18NMessage, currentPath: string[], key: string) => void, currentPath: string[] = []) { for (const key in root) { const message = root[key]; if (this._isIgnored(key)) continue; if (this._isMessage(message)) { fn(message, currentPath, key); } else { this._walkMessages(message, fn, [...currentPath, key]); } } } private static _getFreshFileExport(file: string) { const resolved = require.resolve(`./${file}`); if (resolved in require.cache) { delete require.cache[resolved]; } const { Messages } = require(`./${file}`); return Messages; } private static getMessageFiles(): Promise<[any, string][]> { return new Promise<[any, string][]>((resolve, reject) => { glob('./app/_locales/*/messages.js', async (err, matches) => { if (err) { reject(); return; } resolve(matches.map((file) => { return [require(file).Messages, file] as [any, string]; })); }); }); } private static _genPath(currentPath: string[], key: string) { if (currentPath.length === 0) { // First item, return key by itself return key; } // Requires an @ and dots for the rest return [ currentPath.slice(0, 2).join('_'), ...currentPath.slice(2), key ].join('_'); } @describe('Compiles the .ts files into .js files') static compileTS() { return new Promise(async (resolve, reject) => { const files = await new Promise<string[]>((resolve, reject) => { glob('app/_locales/**/*.ts', (err, matches) => { if (err) { reject(err); } else { resolve(matches.filter( f => !f.endsWith('.d.ts') )); } }); }); const dest = (() => { if (files.length > 1) { return './app/_locales'; } return files[0].split('messages.ts')[0]; })(); const project = ts.createProject('app/_locales/tsconfig.json'); const proj = project.src().pipe(project()); proj.once('error', () => { reject('Error(s) thrown during compilation'); }); proj.js.pipe(gulp.dest(dest)).once('end', () => { resolve(null); }); }); } static Compile = (() => { @taskClass('compile') class Compile { private static _removeMetadata(message: I18NMessage) { const cleanedMessage: Partial<I18NMessage> = {}; cleanedMessage.message = message.message; if (message.placeholders) { cleanedMessage.placeholders = {}; } for (const placeholder in message.placeholders || {}) { cleanedMessage.placeholders[placeholder] = { content: message.placeholders[placeholder].content } } return cleanedMessage as I18NMessage; } private static _normalizeMessages(root: I18NRoot) { const normalized: { [key: string]: I18NMessage; } = {}; I18N._walkMessages(root, (message, currentPath, key) => { normalized[I18N._genPath(currentPath, key)] = this._removeMetadata(message); }); return normalized; } static async _compileI18NFile(file: string, data?: any) { const normalized = this._normalizeMessages( data || I18N._getFreshFileExport(file)); await writeFile(path.join(path.dirname(file), 'messages.json'), JSON.stringify(normalized, null, '\t')); } @describe('Turns I18N TS files into messages.json files') static async compile() { const files = await I18N.getMessageFiles(); await files.map(([ data, fileName ]) => { Compile._compileI18NFile(fileName, data); }); } private static _activeTask: Promise<any>; @describe('Runs when watched file changes') static async watchFileChange() { let currentTask = Compile._activeTask; await Compile._activeTask.then(() => { if (Compile._activeTask !== currentTask) { return Compile._activeTask; } else { Compile._activeTask = null; return true; } }); } @describe('Watches for file changes and compiles on change') static async watcher() { const watcher = gulp.watch('./app/_locales/*/messages.js', Compile.watchFileChange); watcher.on('change', (fileName) => { Compile._activeTask = (async () => { const fileData = I18N._getFreshFileExport(fileName); await I18N.Compile._compileI18NFile(fileName, fileData); })(); }); watcher.on('add', (fileName) => { Compile._activeTask = (async () => { const fileData = I18N._getFreshFileExport(fileName); await I18N.Compile._compileI18NFile(fileName, fileData); })(); }); return watcher; } @subTask('watch', 'Compiles, then watches for file changes and compiles on change') static watch = series( Compile.compile, Compile.watcher ); } return Compile; })(); static Defs = (() => { type NestedObject = { [key: string]: string|NestedObject; }; const I18NMessage = [ 'interface I18NMessage {', ' message: string;', ' description?: string;', ' placeholders?: {', ' [key: string]: {', ' example?: string;', ' content: string;', ' }', ' }', '}' ].join('\n'); const marker = 'x'.repeat(50); const readonlyExpr = new RegExp(`"${marker}"`, 'g'); type Change = { direction: 'forwards'|'backwards'; name: string; }; @taskClass('defs') class Defs { private static async _typeMessages(root: I18NRoot, typed: NestedObject = {}) { I18N._walkMessages(root, (_message, currentPath, finalKey) => { let currentObj = typed; for (const key of currentPath) { if (!(key in currentObj)) { currentObj[key] = {}; } currentObj = currentObj[key] as NestedObject; } currentObj[finalKey] = marker; }); return typed; } @describe('Generates the lang spec from input files, making sure all ' + 'fields are represented in all languages') static async genSpec() { const files = await I18N.getMessageFiles(); const typed: NestedObject = {}; await files.map(([data]) => { return Defs._typeMessages(data, typed); }); const spec = JSON.stringify(typed, null, '\t').replace( readonlyExpr, 'I18NMessage'); const specFile = `${I18NMessage}\nexport type LocaleSpec = ${spec}`; await writeFile(path.join(__dirname, 'app/_locales/i18n.d.ts'), specFile); } private static _getMatches(a: string[], b: string[]): number { let matches: number = 0; for (let i = 0; i < Math.max(a.length, b.length); i++) { if (a[i] === b[i]) { matches++; } else { return matches; } } return matches; } private static _getDiffPath(a: string[], b: string[]): Change[] { let matches = Defs._getMatches(a, b); if (a.length === b.length && matches === a.length) return []; return [ ...a.slice(matches).reverse().map((item) => { return { direction: 'backwards', name: item } as Change; }), ...b.slice(matches).map((item) => { return { direction: 'forwards', name: item } as Change; }) ] } private static _indent(length: number) { return '\t'.repeat(length); } static genEnumMessages(root: I18NRoot) { let str: string[] = []; let tree: string[] = []; I18N._walkMessages(root, (_message, currentPath, finalKey) => { const diff = Defs._getDiffPath(tree, currentPath); if (diff.length) { for (let i = 0; i < diff.length; i++) { const change = diff[i]; if (change.direction === 'backwards') { str.push(Defs._indent(tree.length - 1) + '}'); tree.pop(); } else if (i === diff.length - 1) { // Last one, this is an enum instead str.push(Defs._indent(tree.length) + `export const enum ${change.name} {`); tree.push(change.name); } else { str.push(Defs._indent(tree.length) + `export namespace ${change.name} {`); tree.push(change.name); } } } str.push(`${Defs._indent(tree.length)}"${finalKey}" = '${ I18N._genPath(currentPath, finalKey)}',`); }); for (let i = 0; i < tree.length; i++) { str.push(Defs._indent(tree.length - 1) + '}'); } return `export namespace I18NKeys {\n${ str.map(i => Defs._indent(1) + i).join('\n') }\n}`; } @describe('Generates enums that can be used to reference some ' + 'property in typescript, preventing typos and allowing for ' + 'the finding of references') static async genEnums() { const files = await I18N.getMessageFiles(); if (files.length === 0) { console.log('No source files to generate enums from'); return; } const enums = await Defs.genEnumMessages(files[0][0]); await writeFile(path.join(__dirname, 'app/_locales/i18n-keys.ts'), enums); } @rootTask('i18nDefs', 'Generates definitions files based on i18n files') static defs = series( I18N.compileTS, Defs.genEnums ) @rootTask('i18nSpec', 'Generates language spec') static spec = series( Defs.genSpec ) private static _activeTask: Promise<any>; @describe('Runs when watched file changes') static async watchFileChange() { let currentTask = Defs._activeTask; await Defs._activeTask.then(() => { if (Defs._activeTask !== currentTask) { return Defs._activeTask; } else { Defs._activeTask = null; return true; } }); } @describe('Watches for file changes and updates enums on change') static async watcher() { const watcher = gulp.watch('./app/_locales/*/messages.js', Defs.watchFileChange); watcher.on('change', (fileName) => { Defs._activeTask = (async () => { const fileData = I18N._getFreshFileExport(fileName); const enums = await I18N.Defs.genEnumMessages(fileData) await writeFile(path.join(__dirname, 'app/_locales/i18n-keys.ts'), enums); })(); }); watcher.on('add', (fileName) => { Defs._activeTask = (async () => { const fileData = I18N._getFreshFileExport(fileName); const enums = await I18N.Defs.genEnumMessages(fileData) await writeFile(path.join(__dirname, 'app/_locales/i18n-keys.ts'), enums); })(); }); return watcher; } @subTask('watch', 'Gens enums, then watches for file changes and updates enums on change') static watch = series( Defs.genEnums, Defs.watcher ) } return Defs; })(); private static _activeTask: Promise<any>; @describe('Runs when watched file changes') static async watchFileChange() { let currentTask = I18N._activeTask; await I18N._activeTask.then(() => { if (I18N._activeTask !== currentTask) { return I18N._activeTask; } else { I18N._activeTask = null; return true; } }); } @describe('Turns I18N TS files into messages.json files whenever they change') static watcher() { const watcher = gulp.watch('./app/_locales/*/messages.js', I18N.watchFileChange); watcher.on('change', (fileName) => { I18N._activeTask = (async () => { const fileData = I18N._getFreshFileExport(fileName); const [ , enums] = await Promise.all([ I18N.Compile._compileI18NFile(fileName, fileData), I18N.Defs.genEnumMessages(fileData) ]); await writeFile(path.join(__dirname, 'app/_locales/i18n-keys.ts'), enums); })(); }); watcher.on('add', (fileName) => { I18N._activeTask = (async () => { const fileData = I18N._getFreshFileExport(fileName); const [ , enums] = await Promise.all([ I18N.Compile._compileI18NFile(fileName, fileData), I18N.Defs.genEnumMessages(fileData) ]); await writeFile(path.join(__dirname, 'app/_locales/i18n-keys.ts'), enums); })(); }); return watcher; } @subTask('watch', 'Turns I18N TS files into messages.json files and repeats it whenever they change') static watch = series( I18N.Compile.compile, I18N.watcher ) @rootTask('i18n', 'Compiles I18N files and generates spec and enum files') static i18n = series( I18N.Defs.genEnums, I18N.Compile.compile ) } return I18N; })(); @group('compilation') static Compilation = (() => { class Compilation { @rootTask('fileIdMaps', 'Updates the HTML to Typescript maps') static async fileIdMaps() { const pattern = '{app/elements/**/*.html,!app/elements/elements.html}'; const typings = await extractGlobTypes(pattern); await writeFile('./app/elements/fileIdMaps.d.ts', typings); } @rootTask('defs', 'Generates definitions for various TS files. Required for compilation') static defs = parallel( Compilation.fileIdMaps, Tasks.I18N.Defs.defs ) static Compile = (() => { @taskClass('compile') class Compile { @describe('Compiles the app/ directory\'s typescript') static app() { return new Promise((resolve, reject) => { const project = ts.createProject('app/tsconfig.json'); const proj = project.src().pipe(project()); proj.once('error', () => { reject('Error(s) thrown during compilation'); }); proj.js.pipe(gulp.dest('./app')).once('end', () => { resolve(null); }); }); } @describe('Compiles the test/ directory\'s typescript') static test() { return new Promise((resolve, reject) => { const project = ts.createProject('test/tsconfig.json'); const proj = project.src().pipe(project()); proj.once('error', () => { reject('Error(s) thrown during compilation'); }); proj.js.pipe(gulp.dest('./test')).once('end', () => { resolve(null); }); }); } @rootTask('compile', 'Compiles the typescript') static compile = series( Compilation.defs, parallel( Compile.app, Compile.test ) ) } return Compile; })(); } return Compilation; })(); @group('documentation-website') static DocumentationWebsite = (() => { function typedocCloned() { return new Promise((resolve) => { fs.stat(path.join(__dirname, 'typedoc', 'package.json'), (err) => { if (err) { //Doesn't exist yet resolve(false); } else { resolve(true); } }); }); } async function runCmd(cmd: string, cwd: string = __dirname, allowFailure: boolean = false) { return new Promise((resolve, reject) => { childProcess.exec(cmd, { cwd: cwd }, (err, stdout, stderr) => { if (err !== null && !allowFailure) { console.log(stdout, stderr); reject(err); } else { resolve(); } }); }); } async function cloneTypedoc() { let cwd = __dirname; console.log('Cloning typedoc locally'); console.log('Cloning into ./typedoc/'); await runCmd('git clone https://github.com/TypeStrong/typedoc typedoc') cwd = path.join(cwd, 'typedoc/'); console.log('Getting this extension\'s version of typescript'); const CRMPackage = JSON.parse(await readFile(path.join(__dirname, 'package.json'))); const tsVersion = CRMPackage.devDependencies.typescript; console.log('Removing post install hook'); const file = await readFile(path.join(__dirname, 'typedoc', 'package.json')); await writeFile(path.join(__dirname, 'typedoc', 'package.json'), file.replace(/"prepare":/g, "\"ignored\":")); console.log('Installing typedoc dependencies (this may take a few minutes)'); await runCmd('npm install', cwd); console.log('Running post install hook'); await runCmd('tsc --project .', cwd, true); console.log('Installing this extension\'s typescript version in cloned typedoc'); await runCmd(`npm install --save typescript@${tsVersion}`, cwd); console.log('Done!'); } class DocumentationWebsite { @rootTask('documentationWebsite', 'Extracts the files needed for the documentationWebsite' + ' and places them in build/website') static async documentationWebsite() { console.log('Checking if typedoc has been cloned...'); const exists = await typedocCloned(); if (!exists) { await cloneTypedoc(); } const typedoc = require('./typedoc'); const app = new typedoc.Application({ mode: 'file', out: 'documentation/', includeDeclarations: true, entryPoint: 'CRM', theme: 'docs/theme', name: 'CRM API', readme: 'none', ignoreCompilerErrors: true }); const src = app.expandInputFiles(['./tools/definitions/crmapi.d.ts']); const project = app.convert(src); if (!project) { throw new Error('Failed to load TypeDoc project'); } app.generateDocs(project, 'documentation/'); } @rootTask('moveFavicon', 'Moves the favicon for the website to the directory') static moveFavicon() { return gulp .src('favicon.ico', { cwd: './test/UI/', base: './test/UI/' }) .pipe(gulp.dest('./documentation/')); } } return DocumentationWebsite; })(); @group('building') static Building = (() => { class Building { static Build = (() => { @taskClass('build') class Build { static PrePolymer = (() => { @taskClass('prepolymer') class PrePolymer { @describe('Copies monaco files from node_modules to app/ and temp/') static copyMonacoJs() { return cache('monaco-js', () => { return gulp .src([ '**/**/*.js', ], { base: 'node_modules/monaco-editor/min', cwd: 'node_modules/monaco-editor/min' }) }).pipe(gulp.dest('temp/elements/options/editpages/monaco-editor/src/min/')) .pipe(gulp.dest('app/elements/options/editpages/monaco-editor/src/min/')); } @describe('Copies non-js monaco files from node_modules to app/ and temp/') static copyMonacoNonJs() { return cache('monaco-non-js', () => { return gulp .src([ '**/**', '!**/**/*.js', ], { base: 'node_modules/monaco-editor/min', cwd: 'node_modules/monaco-editor/min' }) }).pipe(gulp.dest('temp/elements/options/editpages/monaco-editor/src/min/')) .pipe(gulp.dest('app/elements/options/editpages/monaco-editor/src/min/')); } @describe('Replaces CRM-dev with CRM in the manifest') static devManifest() { return gulp .src('manifest.json', { cwd: './app/', base: './app/' }) .pipe(replace(/CRM-dev/g, 'CRM')) .pipe(gulp.dest('./temp/')); } @describe('Bundles the backgroundpage up') static async rollupBackground() { const bundle = await rollup.rollup({ input: './app/js/background.js', external: ['tslib'], onwarn: (warning) => { if (typeof warning === 'string') { console.log(warning); } else { switch (warning.code) { case 'THIS_IS_UNDEFINED': case 'EVAL': return; default: console.log(warning.message); } } } }); await bundle.write({ format: 'iife', globals: { tslib: 'tslib_1' }, file: './temp/js/background.js' }); } @describe('Copies files necessary for building from app/ to temp/') static copyBuild() { return gulp .src([ 'fonts/*', 'js/**/*', 'html/install.html', 'html/logging.html', 'html/options.html', 'html/background.html', 'bower_components/**/*', 'images/chromearrow.png', 'images/shadowImg.png', 'images/shadowImgRight.png', 'images/stylesheet.gif', 'images/whitearrow.png', 'images/country_flags/**/*', '_locales/**/*', 'js/libraries/jsonfn.js', 'js/libraries/md5.js', 'js/libraries/jquery/jquery-3.3.1.js', 'icon-large.png', 'icon-small.png', 'icon-supersmall.png', 'LICENSE.txt', 'elements/util/change-log/changelog.js', '!js/background/**/*', '!js/background.js', '!bower_components/webcomponentsjs/webcomponents-lite.js' ], { base: './app/', cwd: './app/' }) .pipe(gulp.dest('./temp/')) } @describe('Copies install page files to temp/') static copyInstalling() { return gulp .src([ 'install-confirm/install-confirm.html', 'install-confirm/install-confirm.css', 'install-confirm/install-confirm.js', 'install-error/install-error.html', 'install-error/install-error.css', 'install-error/install-error.js', 'install-page/install-page.html', 'install-page/install-page.css', 'install-page/install-page.js' ], { base: './app/elements/installing/', cwd: './app/elements/installing/' }) .pipe(gulp.dest('./temp/elements/installing')); } @describe('Inline external CSS imports into HTML files') static inlineImports() { return gulp .src('**/*.html', { cwd: './app/elements/', base: './app/elements/' }) .pipe(processhtml({ strip: true, data: { classes: 'content extension', base: 'html/' } })) .pipe(gulp.dest('./temp/elements/')); } @describe('Change where "this" points to in webcomponents-lite') static changeWebComponentThis() { return gulp .src('bower_components/webcomponentsjs/webcomponents-lite.js', { cwd: './app/', base: './app/' }) .pipe(replace(/window===this((\s)?)\?((\s)?)this/g, 'true?window')) .pipe(gulp.dest('./temp/')); } @describe('Embeds the typescript compilation library') static embedTS() { return cache('ts-lib-ugly', () => { return gulp .src('typescript.js', { cwd: './node_modules/typescript/lib', base: './node_modules/typescript/lib' }) }).pipe(gulp.dest('./temp/js/libraries')); } @describe('Embeds the Less compiler') static async embedLess() { const less = await readFile('./resources/buildresources/less.min.js'); await writeFile('./temp/js/libraries/less.js', less); } @describe('Embeds the stylus compiler') static async embedStylus() { const stylus = await readFile('./resources/buildresources/stylus.min.js'); await writeFile('./temp/js/libraries/stylus.js', stylus); } @describe('Embeds the CRM API') static async embedCRMAPI() { await writeFile('./temp/js/libraries/crmapi.d.ts', await Tasks.Definitions._joinDefs()); } static Entrypoint = (() => { @taskClass('entrypoint') class Entrypoint { @describe('Run processhtml on the entrypoint') static process() { return gulp .src([ 'html/entrypointPrefix.html', 'elements/installing/install-confirm/install-confirm.html' ], { cwd: './app/', base: './app/' }) .pipe(processhtml({ strip: true, data: { classes: 'content extension', base: 'html/' } })) .pipe(gulp.dest('./temp/')); } @describe('Crisp the entrypoint file') static async crisp() { const entrypointPrefix = await readFile('./temp/html/entrypointPrefix.html'); const { html, js } = crisper({ jsFileName: 'entrypointPrefix.js', source: entrypointPrefix, scriptInHead: true, cleanup: false }); await Promise.all([ writeFile('./temp/html/entrypointPrefix.html', html), writeFile('./temp/html/entrypointPrefix.js', js), ]); } @subTask('Entrypointprefix stuff') static entrypoint = series( Entrypoint.process, Entrypoint.crisp ) } return Entrypoint; })(); @describe('Run processhtml on the generated files in the temp/ dir') static processHTMLTemp() { return gulp .src([ './temp/html/background.html', './temp/html/logging.html', './temp/html/install.html', './temp/html/options.html' ]) .pipe(processhtml({ strip: true, data: { classes: 'content extension', base: 'html/' } })) .pipe(gulp.dest('./temp/html/')); } @subTask('All pre-polymer tasks during building') static prepolymer = series( Tasks.Convenience.Clean.build, parallel( PrePolymer.copyMonacoJs, PrePolymer.copyMonacoNonJs ), parallel( PrePolymer.devManifest, PrePolymer.rollupBackground, PrePolymer.copyBuild, PrePolymer.copyInstalling, PrePolymer.inlineImports, PrePolymer.changeWebComponentThis, PrePolymer.embedTS, PrePolymer.embedLess, PrePolymer.embedStylus, PrePolymer.embedCRMAPI, PrePolymer.Entrypoint.entrypoint ), PrePolymer.processHTMLTemp ) } return PrePolymer; })(); static PostPolymer = (() => { @taskClass('postpolymer') class PostPolymer { @describe('Moves all files up a directory, from build/temp to build/') static moveUpDir() { return gulp .src('**/*', { cwd: './build/temp', base: './build/temp' }) .pipe(gulp.dest('./build')) } @describe('Cleans the build/temp/ directory') static async cleanBuildTemp() { await del('./build/temp/'); } @describe('Copy the webcomponent libraries from temp/ to build/') static copyWebComponentLibs() { return gulp .src([ 'webcomponentsjs/*.js', '!webcomponentsjs/webcomponents-lite.js' ], { cwd: './temp/bower_components', base: './temp/bower_components' }) .pipe(gulp.dest('./build/bower_components')); } @describe('Copies entrypointPrefix from temp/ to build/') static copyPrefixJs() { return gulp .src('html/entrypointPrefix.js', { cwd: './temp/', base: './temp/' }) .pipe(gulp.dest('./build/')); } static EntrypointJS = (() => { @taskClass('entrypointJS') class EntrypointJS { static Crisp = (() => { @taskClass('crisp') class Crisp { @describe('Crisps the options.html page') static async options() { const options = await readFile('./build/html/options.html'); const { html, js } = crisper({ jsFileName: 'options.js', source: options, scriptInHead: false, cleanup: false }); const optionsRemoved = html.replace( /<script src="options.js"><\/script>/g, ''); await Promise.all([ writeFile('./build/html/options.html', optionsRemoved), writeFile('./build/html/options.js', js) ]); } @describe('Crisps the logging.html page') static async logging() { const content = await readFile('./build/html/logging.html'); const { html, js } = crisper({ jsFileName: 'logging.js', source: content, scriptInHead: false, cleanup: false }); const tagRemoved = html.replace( /<script src="logging.js"><\/script>/g, ''); await Promise.all([ writeFile('./build/html/logging.html', tagRemoved), writeFile('./build/html/logging.js', js), ]); } @describe('Crisps the install.html page') static async install() { const content = await readFile('./build/html/install.html'); const { html, js } = crisper({ jsFileName: 'install.js', source: content, scriptInHead: false, cleanup: false }); const tagRemoved = html.replace( /<script src="install.js"><\/script>/g, ''); await Promise.all([ writeFile('./build/html/install.html', tagRemoved), writeFile('./build/html/install.js', js), ]); } @describe('Crisps the background.html page') static async background() { const background = await readFile('./build/html/background.html'); const { html, js } = crisper({ jsFileName: 'background.js', source: background, scriptInHead: false, cleanup: false }); await Promise.all([ writeFile('./build/html/background.html', html), writeFile('./build/html/background.js', js), ]); } @subTask('Crisping of all entrypoints') static crisp = parallel( Crisp.options, Crisp.logging, Crisp.install, Crisp.background ) } return Crisp; })(); static Babel = (() => { @taskClass('babel') class Babel { @describe('Babel the options page') static options() { return gulp .src('./build/html/options.js') .pipe(gulpBabel({ compact: false, presets: ['es3', 'es2015'] })) .pipe(rename('options.es3.js')) .pipe(gulp.dest('./build/html/')); } @describe('Babel the logging page') static logging() { return gulp .src('./build/html/logging.js') .pipe(gulpBabel({ compact: false, presets: ['es3', 'es2015'] })) .pipe(rename('logging.es3.js')) .pipe(gulp.dest('./build/html/')); } @describe('Babel the install page') static install() { return gulp .src('./build/html/install.js') .pipe(gulpBabel({ compact: false, presets: ['es3', 'es2015'] })) .pipe(rename('install.es3.js')) .pipe(gulp.dest('./build/html/')); } @describe('Babel the background page') static background() { return gulp .src('./build/html/background.js') .pipe(gulpBabel({ compact: false, presets: ['es3', 'es2015'] })) .pipe(gulp.dest('./build/html/')); } @describe('Joins the options page with the prefix') static async joinOptions() { await joinPages({ parts: [ 'temp/html/entrypointPrefix.html', 'build/html/options.html' ], dest: 'build/html/options.html' }); } @describe('Joins the logging page with the prefix') static async joinLogging() { await joinPages({ parts: [ 'temp/html/entrypointPrefix.html', 'build/html/logging.html' ], dest: 'build/html/logging.html' }); } @describe('Joins the install page with the prefix') static async joinInstall() { await joinPages({ parts: [ 'temp/html/entrypointPrefix.html', 'build/html/install.html' ], dest: 'build/html/install.html' }); } @subTask('Babelify all entrypoints and join them with the prefix') static babel = parallel( Babel.options, Babel.logging, Babel.install, Babel.background, Babel.joinOptions, Babel.joinLogging, Babel.joinInstall ) } return Babel; })(); @describe('Fix some bugs in the background and options pages') static fixBackgroundOptions() { return gulp .src([ './build/html/background.js', './build/html/options.js', './build/html/options.es3.js', './build/html/install.js', './build/html/install.es3.js', './build/html/logging.js', './build/html/logging.es3.js' ]) .pipe(replace( /Object.setPrototypeOf\(((\w|\.)+),(\s*)((\w|\.)*)\)/g, 'typeof Object[\'setPrototype\' + \'Of\'] === \'function\'' + '?Object[\'setPrototype\' + \'Of\']($1,$4):$1.__proto__ = $4' )) .pipe(replace( /typeof (\w+)\.global\.define/g, 'typeof ($1.global = $1.global || {}).define' )) .pipe(replace( /use strict/g, 'use notstrict' )) .pipe(replace( /\s\(\(\)\=\>\{'use notstrict';if\(!window.customElements\)(.*)\s/g, `try { eval('class foo {}'); eval("(()=>{if(!window.customElements)$1")` + ` } catch (e) { }` )) .pipe(gulp.dest('./build/html/')); } @describe('Fix some bugs in the webcomponents file that is used in the options page') static fixWebcomponentOptionsBugs() { return gulp .src([ './bower_components/webcomponentsjs/webcomponents-lite.js' ], { cwd: './temp/', base: './temp/' }) .pipe(replace( /Object.setPrototypeOf\(((\w|\.)+),(\s*)((\w|\.)*)\)/g, 'typeof Object[\'setPrototype\' + \'Of\'] === \'function\'' + '?Object[\'setPrototype\' + \'Of\']($1,$4):$1.__proto__ = $4' )) .pipe(replace( /typeof l\.global\.define/g, 'typeof (l.global = l.global || {}).define' )) .pipe(replace( /use strict/g, 'use notstrict' )) .pipe(replace( /\s\(\(\)\=\>\{'use notstrict';if\(!window.customElements\)(.*)\s/g, `try { eval('class foo {}'); eval("(()=>{if(!window.customElements)$1")` + ` } catch (e) { }` )) .pipe(gulp.dest('./build/')); } @describe('Don\'t defer loads in entrypoint HTML files') static nodefer() { return gulp .src([ './build/html/options.html', './build/html/install.html', './build/html/logging.html', ]) .pipe(replace(/\sdefer/g, '')) .pipe(gulp.dest('./build/html/')); } static Banners = (() => { @taskClass('banners') class Banners { @describe('Creates banners in the HTML files') static html() { return gulp .src(['build/html/**.html']) .pipe(banner(BANNERS.html)) .pipe(gulp.dest('./build/html/')) } @describe('Creates banners in the JS files') static js() { return gulp .src([ 'html/**.js', 'js/crmapi.js', ], { cwd: './build', base: './build' }) .pipe(banner(BANNERS.js + '\n\nvar exports = {};')) .pipe(replace(/export\s*\{\}/g, '')) .pipe(gulp.dest('./build/')) } @subTask('Creates banners in all HTML and JS files') static banners = parallel( Banners.html, Banners.js ) } return Banners; })(); @subTask('Crisps, babels and joins all entrypoints') static entrypointJS = series( EntrypointJS.Crisp.crisp, EntrypointJS.Babel.babel, parallel( EntrypointJS.fixBackgroundOptions, EntrypointJS.fixWebcomponentOptionsBugs, EntrypointJS.nodefer ), EntrypointJS.Banners.banners ) } return EntrypointJS; })(); static Monaco = (() => { @taskClass('monaco') class Monaco { @describe('Copies JS files from monaco to build/ and uglifies them') static js() { return cache('monaco-post-js', () => { return gulp .src([ '**/**/*.js', ], { base: 'node_modules/monaco-editor/min', cwd: 'node_modules/monaco-editor/min' }) .pipe(replace(/node = node\.parentNode/g, 'node = node.parentNode || node.host')) .pipe(replace(/document\.body/g, 'MonacoEditorHookManager.getLocalBodyShadowRoot')) .pipe(replace(/document\.caretRangeFromPoint/g, 'MonacoEditorHookManager.caretRangeFromPoint(arguments[0])')) .pipe(replace(/this.target(\s)?=(\s)?e.target/g, 'this.target = e.path ? e.path[0] : e.target')) }).pipe(gulp.dest('build/elements/options/editpages/monaco-editor/src/min/')); } @describe('Copies non-JS files from monaco to build/') static nonjs() { return gulp .src([ '**/**', '!**/**/*.js', ], { base: 'node_modules/monaco-editor/min', cwd: 'node_modules/monaco-editor/min' }) .pipe( gulp.dest( 'build/elements/options/editpages/monaco-editor/src/min/')); } @subTask('Operations related to copying monaco') static monaco = parallel( Monaco.js, Monaco.nonjs ) } return Monaco; })(); @describe('Cleans the temp/ directory') static async cleanTemp() { await del('./temp'); } @subTask('postpolymer', 'All post-polymer tasks during building') static postpolymer = series( PostPolymer.moveUpDir, PostPolymer.cleanBuildTemp, parallel( PostPolymer.copyWebComponentLibs, PostPolymer.copyPrefixJs ), PostPolymer.EntrypointJS.entrypointJS, parallel( PostPolymer.cleanTemp, PostPolymer.Monaco.monaco ) ) } return PostPolymer; })(); static Dev = (() => { @taskClass('dev') class Dev { @describe('Builds polymer in dev mode') static async polymer() { await polymerBuild({ project: { entrypoint: [ "html/options.html", "html/logging.html", "html/install.html" ], sources: ['elements/**'], root: "temp/", extraDependencies: [ "html/background.html", "fonts/**/*", '_locales/**/*', "images/**/*", "js/libraries/csslint.js", "js/libraries/jslint.js", "js/libraries/crmapi.d.ts", "js/contentscripts/contentscript.js", "js/libraries/tern/*.*", "icon-large.png", "icon-small.png", "icon-supersmall.png", "LICENSE.txt", "manifest.json" ], nonPolymerEntrypoints: [ "html/background.html" ] }, optimization: { bundle: true, js: { compile: true } }, dest: './build/' }); } @describe('Beautifies all JS files') static async beautify() { return gulp .src('build/**/*.js') .pipe(beautify()) .pipe(gulp.dest('./build/')); } } return Dev; })(); @describe('Copies extra dependencies not already copied by polymer') static extraUglifiedDependencies() { return gulp .src([ './js/contentscripts/openusercss.js', './js/contentscripts/usercss.js', './js/contentscripts/userstyles.js', './js/sandbox.js', './js/libraries/typescript.js', './js/libraries/less.js', './js/libraries/stylus.js', './js/contentscripts/contentscript.js', './js/polyfills/browser.js' ], { cwd: './temp', base: './temp' }) .pipe(gulp.dest('./build')); } static extraDependencies() { return gulp .src([ './js/crmapi.js', ], { cwd: './temp', base: './temp' }) .pipe(gulp.dest('./build')); } @rootTask('buildDevNoCompile', 'Builds the extension and attempts to beautify' + ' the code and skips compilation') static buildDevNoCompile = series( Build.PrePolymer.prepolymer, Build.Dev.polymer, parallel( Build.extraUglifiedDependencies, Build.extraDependencies ), Build.PostPolymer.postpolymer, Build.Dev.beautify ) static Prod = (() => { @taskClass('prod') class Prod { @describe('Runs the polymer build command') static async polymer() { await polymerBuild({ project: { entrypoint: [ "html/options.html", "html/logging.html", "html/install.html" ], root: "temp/", extraDependencies: [ "html/background.html", "fonts/**/*", "images/**/*", '_locales/**/*', "js/libraries/csslint.js", "js/libraries/jslint.js", "js/libraries/crmapi.d.ts", "js/contentscripts/contentscript.js", "js/libraries/tern/*.*", "icon-large.png", "icon-small.png", "icon-supersmall.png", "LICENSE.txt", "manifest.json" ], nonPolymerEntrypoints: [ "html/background.html" ] }, optimization: { bundle: true, js: { compile: true, minify: true }, css: { minify: true }, html: { minify: true } }, dest: './build/' }); } @describe('Uglifies the entrypoint prefix') static uglify() { return gulp .src([ './build/html/entrypointPrefix.js' ]) .pipe(gulp.dest('./build/html/')); } } return Prod; })(); @rootTask('buildNoCompile', 'Builds the extension and skips compilation') static buildNoCompile = series( Build.PrePolymer.prepolymer, Build.Prod.polymer, Build.extraDependencies, Build.PostPolymer.postpolymer, Build.Prod.uglify ) @rootTask('buildDev', 'Builds the extension and attempts to beautify the code') static buildDev = series( Tasks.Compilation.Compile.compile, Tasks.I18N.i18n, Build.buildDevNoCompile ) @rootTask('build', 'Builds the extension') static build = series( Tasks.Compilation.Compile.compile, Tasks.I18N.i18n, Build.buildNoCompile ) @rootTask('testBuild', 'Attempts to build everything') static testBuild = series( Tasks.Convenience.Clean.clean, Build.build, Tasks.Convenience.Clean.clean, Tasks.DocumentationWebsite.documentationWebsite, Tasks.Convenience.Clean.clean ) } return Build; })(); static BuildZip = (() => { @taskClass('buildZip') class BuildZip { @describe('Zips the build/ directory') static zip() { return gulp .src([ '**', '!Custom Right-Click Menu.zip', ], { cwd: './build/', base: './build/' }) .pipe(zip('Custom Right-Click Menu.zip')) .pipe(gulp.dest('./build')); } @rootTask('buildZip', 'Builds the extension and zips it') static buildZip = series( Building.Build.build, BuildZip.zip ) } return BuildZip; })(); static BuildTest = (() => { @taskClass('buildTest') class BuildTest { @describe('joins the test HTML pages') static async join() { await joinPages({ parts: [ 'test/UI/skeleton.html', 'build/html/background.html', 'build/html/options.html' ], dest: 'build/html/UITest.html' }); } @rootTask('buildTest', 'Builds the tests') static buildTest = series( Building.Build.build, BuildTest.join ) } return BuildTest; })(); } return Building; })(); @group('demowebsite') static DemoWebsite = (() => { class DemoWebsite { static DemoWebsite = (() => { @taskClass('demoWebsite') class DemoWebsite { @describe('Copies the demo website to /demo') static copy() { return gulp .src('UITest.html', { cwd: './build/html', base: './build/html' }) .pipe(replace(/<title>((\w|\s)+)<\/title>/g, '<title>Demo</title>')) .pipe(replace(/<head>/, '<head><base href="../build/html/">')) .pipe(rename('index.html')) .pipe(gulp.dest('./demo')); } @rootTask('demoWebsite', 'Creates the demo and moves the demo website to /demo') static demoWebsite = series( Tasks.Building.BuildTest.buildTest, DemoWebsite.copy ) } return DemoWebsite; })(); @rootTask('removeBowerComponents', 'Removes the app/bower_components folder') static async removeBowerComponents() { await del('./app/bower_components'); } @rootTask('noJekyll', 'Copies the nojekyll file to the root') static copyJeckyllConfig() { return gulp .src('.nojekyll', { cwd: './resources/demo', base: './resources/demo' }) .pipe(gulp.dest('./')); } @rootTask('changeGitIgnore', 'Moves the gitignore for the gh-pages branch to the root') static changeGitIgnore() { return gulp .src('gh-pages-gitignore.gitignore', { cwd: './tools', base: './tools' }) .pipe(rename('.gitignore')) .pipe(gulp.dest('./')); } } return DemoWebsite; })(); @group('definitions') static Definitions = (() => { /** * Replace a line with given callback's response when regexp matches * * @param {string[]} lines - The lines to iterate through * @param {RegExp} regexp - The expression that should match * @param {(match: RegExpExecArray) => Promise<string>} callback - A function that * returns the to-replace string based on the match * @returns {Promise<string[]>} - The new array */ async function doReplace(lines: string[], regexp: RegExp, callback: (match: RegExpExecArray) => Promise<string>): Promise<string[]> { let match; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if ((match = regexp.exec(line))) { const replacement = (await callback(match)).split('\n'); lines.splice(i, 1, ...replacement); return doReplace(lines, regexp, callback); } } return lines; } async function joinDefs() { const srcFile = await readFile('./tools/definitions/crmapi.d.ts'); const lines = srcFile.split('\n'); return (await doReplace(lines, /\/\/\/(\s*)<reference path="(.*)"(\s*)\/>/, async (match) => { const file = match[2]; return await readFile(path.join('./tools/definitions', file)); })).join('\n'); } class Definitions { public static _joinDefs = joinDefs; /** * Replace a line with given callback's response when regexp matches * * @param {string[]} lines - The lines to iterate through * @param {RegExp} regexp - The expression that should match * @param {(match: RegExpExecArray) => Promise<string>} callback - A function that * returns the to-replace string based on the match * @returns {Promise<string[]>} - The new array */ public static _doReplace = doReplace; @rootTask('genDefs', 'Move all crmapi .d.ts files into a single file') static async genDefs() { await writeFile('./dist/defs/crmapi.d.ts', await Definitions._joinDefs()); } } return Definitions; })(); @group('browser') static Browser = (() => { /** * Moves a browser's manifest * * @param {string} browser - The name of the browser * @param {string} dest - The dir to place it in */ function moveBrowser(browser: string, dest: string) { return gulp .src(`./app/manifest.${browser}.json`) .pipe(rename('manifest.json')) .pipe(gulp.dest(dest)); } /** * Replace the short name of the extension from CRM-dev to CRM */ function replaceShortName() { return gulp .src('manifest.json', { cwd: './build/', base: './build/' }) .pipe(replace(/CRM-dev/g, 'CRM')) .pipe(gulp.dest('./build')); } /** * Moves the /build directory to the /dist/{browser} directory * * @param {string} browser - The name of the browser */ function moveToDist(browser: string) { return gulp .src('./**/*', { cwd: './build/', base: './build/' }) .pipe(gulp.dest(`./dist/${browser}`)); } /** * Move the built files to /dist and create a zip to place in /dist/packed */ function doMove(browser: string, replaceName?: boolean): Undertaker.TaskFunction { const fns = [...replaceName ? [function replaceName() { return replaceShortName(); }] : [], gulp.parallel( function copy() { return moveToDist(browser); }, function createZip() { return gulp .src('./**/*', { cwd: './build/', base: './build/' }) .pipe(zip(`Custom Right-Click Menu.${browser}.zip`)) .pipe(gulp.dest(`./dist/packed/`)); })]; return gulp.series(...fns); } class Browser { @rootTask('Copy the chrome manifest.json') static browserChrome() { return moveBrowser('chrome', './app'); } @rootTask('Copy the firefox manifest.json') static browserFirefox() { return moveBrowser('firefox', './app'); } @rootTask('Copy the edge manifest.json') static browserEdge() { return moveBrowser('edge', './app'); } @rootTask('Copy the opera manifest.json') static browserOpera() { return moveBrowser('opera', './app'); } @rootTask('Copy the chrome manifest.json') static browserChromeBuild() { return moveBrowser('chrome', './build'); } @rootTask('Copy the firefox manifest.json') static browserFirefoxBuild() { return moveBrowser('firefox', './build'); } @rootTask('Copy the edge manifest.json') static browserEdgeBuild() { return moveBrowser('edge', './build'); } @rootTask('Copy the opera manifest.json') static browserOperaBuild() { return moveBrowser('opera', './build'); } @rootTask('Copies the unstashed manifest to /build') static copyUnstashed() { return gulp .src('./app/manifest.json') .pipe(gulp.dest('./build')); } @rootTask('Copy the current manifest and store it to undo overrides later') static stashBrowser() { return gulp .src('./app/manifest.json', { allowEmpty: true } as any) .pipe(rename('manifest.temp.json')) .pipe(gulp.dest('./app')); } @rootTask('Undo any overrides since the last stashing of the manifest') static unstashBrowser() { return gulp .src('./app/manifest.temp.json', { allowEmpty: true } as any) .pipe(rename('manifest.json')) .pipe(gulp.dest('./app')); } @rootTask('Copies the /build folder to the /dist/chrome folder with a test manifest') static chromeToDistTest = doMove('chrome'); @rootTask('Copies the /build folder to the /dist/firefox folder with a test manifest') static firefoxToDistTest = doMove('firefox'); @rootTask('Copies the /build folder to the /dist/edge folder with a test manifest') static edgeToDistTest = doMove('edge') @rootTask('Copies the /build folder to the /dist/opera folder with a test manifest') static operaToDistTest = doMove('opera') @rootTask('Copies the /build folder to the /dist/chrome folder') static chromeToDist = doMove('chrome', true); @rootTask('Copies the /build folder to the /dist/firefox folder') static firefoxToDist = doMove('firefox', true); @rootTask('Copies the /build folder to the /dist/edge folder') static edgeToDist = doMove('edge', true); @rootTask('Copies the /build folder to the /dist/opera folder') static operaToDist = doMove('opera', true); static genCRX = (() => { @taskClass('genCRX') class GenCRX { @describe('Generates the CRX file for firefox') static firefox() { return gulp .src([ '**', '!Custom Right-Click Menu.zip' ], { cwd: './dist/firefox/', base: './dist/firefox' }) .pipe(zip('Custom Right-Click Menu.zip')) .pipe(rename('Custom Right-Click Menu.firefox.crx')) .pipe(gulp.dest('./dist/packed/')); } @describe('Generates the CRX file for chrome)') static chrome() { return gulp .src([ '**', '!Custom Right-Click Menu.zip' ], { cwd: './dist/chrome/', base: './dist/chrome' }) .pipe(zip('Custom Right-Click Menu.zip')) .pipe(rename('Custom Right-Click Menu.chrome.crx')) .pipe(gulp.dest('./dist/packed/')); } @rootTask('genCRX', 'Generates a crx file and places it in the /dist/packed folder') static genCRX = parallel( GenCRX.firefox, GenCRX.chrome ); } return GenCRX; })(); @describe('Generates an xpi file and places it in the /dist/packed folder') static async genXPI() { await xpi('./dist/packed/Custom Right-Click Menu.firefox.xpi', './dist/firefox'); } } return Browser; })(); @group('distribution') static Distribution = (() => { class Distribution { static Zip = (() => { @taskClass('zip') class Zip { @describe('Zips the build/ directory and places it in ' + 'artifacts.build.zip') static build() { return gulp .src([ 'build/**', ]) .pipe(zip('artifacts.build.zip')) .pipe(gulp.dest('./')); } @describe('Zips the dist/ directory and places it in ' + 'artifacts.dist.zip') static dist() { return gulp .src([ 'dist/**', ]) .pipe(zip('artifacts.dist.zip')) .pipe(gulp.dest('./')); } @rootTask('zipArtifacts', 'Creates a zip file from the build/ and dist/ dirs') static zipArtifacts = parallel( Zip.build, Zip.dist ); } return Zip; })(); static Unzip = (() => { @taskClass('unzip') class Unzip { @describe('Unzips artifacts.build.zip to build/') static async build() { await new Promise((resolve, reject) => { const zip = new StreamZip({ file: 'artifacts.build.zip', storeEntries: true }); mkdirp(path.join(__dirname, 'build/'), (err) => { if (err) { reject(err); } else { zip.on('ready', () => { zip.extract(null, path.join(__dirname, 'build/'), (err) => { if (err) { reject(err); } else { zip.close(); resolve(); } }); }); } }); }); } @describe('Unzips artifacts.dist.zip to dist/') static async dist() { await new Promise((resolve, reject) => { const zip = new StreamZip({ file: 'artifacts.dist.zip', storeEntries: true }); mkdirp(path.join(__dirname, 'dist/'), (err) => { if (err) { reject(err); } else { zip.on('ready', () => { zip.extract(null, path.join(__dirname, 'dist/'), (err) => { if (err) { reject(err); } else { zip.close(); resolve(); } }); }); } }); }); } @rootTask('unzipArtifacts', 'Unzips the artifacts.dist.zip and artifacts.build.zip files') static unzipArtifacts = parallel( Unzip.build, Unzip.dist ); } return Unzip; })(); @rootTask('genAppx:copy', 'Copies store images to the packaged dir') static genAppxCopy() { return gulp .src('resources/logo/edge/*') .pipe(gulp .dest('dist/CRM/edgeextension/manifest/Assets')) } @rootTask('genAppx:replace', 'Replaces manifest fields in edge extension manifest') static async genAppxReplace() { let packageManifest = await readFile( 'dist/CRM/edgeextension/manifest/appxmanifest.xml'); /** * @type {{"version": string}} */ const edgeManifest: { "version": string; } = JSON.parse(await readFile( 'dist/edge/manifest.json')); /** * @type {{"Name": string, "Publisher": string, "PublisherDisplayName": string}} */ const secrets: { "Name": string; "Publisher": string; "PublisherDisplayName": string; } = JSON.parse(await readFile( 'resources/buildresources/edge_secrets.json')); packageManifest = packageManifest .replace(/INSERT-YOUR-PACKAGE-IDENTITY-NAME-HERE/g, secrets.Name) .replace(/CN=INSERT-YOUR-PACKAGE-IDENTITY-PUBLISHER-HERE/g, secrets.Publisher) .replace(/INSERT-YOUR-PACKAGE-PROPERTIES-PUBLISHERDISPLAYNAME-HERE/g, secrets.PublisherDisplayName) .replace(/Version="(\.|\d)+"/, `Version="${edgeManifest.version}.0"`); await writeFile( 'dist/CRM/edgeextension/manifest/appxmanifest.xml', packageManifest); } @rootTask('genAppx:clean', 'Cleans the left over appx files') static async genAppxClean() { await del('./dist/CRM'); } } return Distribution; })(); @group('meta') static Meta = (() => { /** * Repeats given {char} {amount} times * * @param {string} char - The char to repeat * @param {number} amount - The amount of times to repeat it * * @returns {string} The new string */ function repeat(char: string, amount: number): string { return new Array(amount).fill(char).join(''); } class Meta { @rootTask('tasks', 'Lists all top-level tasks') static async tasks() { console.log('These are the top-level tasks:'); console.log(''); const longest = Array.from(descriptions.keys()).map(k => k.length) .reduce((prev, current) => { return Math.max(prev, current); }, 0); for (const [task, description] of descriptions.entries()) { console.log(`${chalk.bold(task)}${ repeat(' ', longest - task.length)} - ${description}`); } } @rootTask('default', 'The default task (build)') static default = series( Tasks.Building.Build.build ); } return Meta; })(); } namespace TaskGeneration { function joinNames(first: string, second: string): string { if (first === '') return second; if (second === '') return first; return `${first}.${second}`; } function getFnProperties<T>(taskTree: T): Partial<T> { const props: Partial<T> = {}; for (const key of Object.getOwnPropertyNames(taskTree)) { if (key !== 'length' && key !== 'prototype' && key !== 'name') { props[key as keyof T] = taskTree[key as keyof T]; } } return props; } function collapseTask(root: TaskStructure|Function): Undertaker.TaskFunction { if (typeof root === 'function') return root as Undertaker.TaskFunction; const fns = root.children.map((child: ReturnFunction|TaskStructure) => { if (typeof child === 'function') { // Regular function, get name if (REGISTER_SUBTASKS) { return fnNames.get(child); } else { return child; } } else { // Task structure return collapseTask(child); } }); return root.type === 'parallel' ? gulp.parallel(...fns) : gulp.series(...fns); } const fnNames: WeakMap<ReturnFunction, string> = new WeakMap(); export function createBasicTasks(taskTree: any, baseName: string = '') { const currentName = joinNames(baseName, Reflect.getOwnMetadata(taskClassMetaKey, taskTree) || ''); const root = getFnProperties(taskTree); for (const key in root) { if (key.startsWith('_')) continue; const value = taskTree[key]; if (Reflect.getOwnMetadata(taskClassMetaKey, value) || Reflect.getOwnMetadata(groupMetaKey, taskTree, key)) { // Subtree createBasicTasks(value, currentName); } else if (typeof value === 'function' && !Reflect.getOwnMetadata(rootTaskMetaKey, taskTree, key)) { // Sub-function const taskName = (value as Function).name; const joinedNames = joinNames(currentName, taskName); if (REGISTER_SUBTASKS) { gulp.task(joinedNames, value); } fnNames.set(value, joinedNames); } else if (Reflect.getOwnMetadata(subtaskMetaKey, taskTree, key)) { // Sub-task const [ taskName ] = Reflect.getOwnMetadata(subtaskMetaKey, taskTree, key); const joinedNames = joinNames(currentName, taskName); if (REGISTER_SUBTASKS) { gulp.task(joinedNames, collapseTask(value)); } fnNames.set(value, joinedNames); } else if (Reflect.getOwnMetadata(rootTaskMetaKey, taskTree, key)) { const reflected = Reflect.getOwnMetadata(rootTaskMetaKey, taskTree, key); let [ taskName ] = reflected; if (typeof value === 'function') { taskName = taskName || key; } fnNames.set(value, taskName); } } return taskTree; } export function createRootTasks(taskTree: any) { const root = getFnProperties(taskTree); for (const key in root) { if (key.startsWith('_')) continue; const value = taskTree[key]; if (Reflect.getOwnMetadata(taskClassMetaKey, value) || Reflect.getOwnMetadata(groupMetaKey, taskTree, key)) { // Subtree createRootTasks(value); } else if (Reflect.getOwnMetadata(rootTaskMetaKey, taskTree, key)) { // Main task const reflected = Reflect.getOwnMetadata(rootTaskMetaKey, taskTree, key); let [ taskName, description ] = reflected; if (typeof value === 'function') { taskName = taskName || key; } gulp.task(taskName, genRootTask(taskName, description, collapseTask(value))); } } } } TaskGeneration.createBasicTasks(Tasks) TaskGeneration.createRootTasks(Tasks);
the_stack
import { ChangeLogItem, ChangeLogKind, ContentProvider, Header, Image, Sponsor, IssueKind, SupportChannel, SocialMediaProvider, SponsorProvider } from "../../vscode-whats-new/src/ContentProvider"; export class BookmarksContentProvider implements ContentProvider { public provideHeader(logoUrl: string): Header { return <Header>{ logo: <Image>{ src: logoUrl, height: 50, width: 50 }, message: `<b>Bookmarks</b> helps you to navigate in your code, <b>moving</b> between important positions easily and quickly. No more need to <i>search for code</i>. It also supports a set of <b>selection</b> commands, which allows you to select bookmarked lines and regions between lines.`}; } public provideChangeLog(): ChangeLogItem[] { const changeLog: ChangeLogItem[] = []; changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "13.2.2", releaseDate: "September 2021" } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: "Update Tabnine URL" }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "13.2.1", releaseDate: "August 2021" } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Remove unnecessary files from extension package", id: 465, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "13.2.0", releaseDate: "August 2021" } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "New <b>Sticky Engine</b> with improved support to Formatters, Multi-cursor and Undo operations", id: 463, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "<b>View as Tree</b> and <b>View as List</b> options in Side Bar", id: 453, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "New command to Hide/Show bookmark position in Side Bar", id: 143, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Updated translations", id: 464, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Bookmark positions didn't update after pasting content above", id: 446, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Bookmark positions didn't update after adding empty lines above", id: 457, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Bookmark moving off original line", id: 168, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Undo messes up bookmarks", id: 116, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "<b>Toggle</b> command in Notebook cells causes duplicate editor to be opened", id: 456, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "<b>Toggle</b> command causes exiting diff editor", id: 440, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "13.1.0", releaseDate: "May 2021" } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Support <b>Virtual Workspaces</b>", id: 432, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Support <b>Workspace Trust</b>", id: 430, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Return to line/column when cancel List or List from All Files", id: 386, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Update pt-br translation", id: 376, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Latest bookmark could not be removed", id: 422, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Minor grammatical and spelling issue", id: 388, kind: IssueKind.PR, kudos: "@derekpock" } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Security Alert: lodash", id: 433, kind: IssueKind.PR, kudos: "dependabot" } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Security Alert: ssri", id: 425, kind: IssueKind.PR, kudos: "dependabot" } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Security Alert: y18n", id: 418, kind: IssueKind.PR, kudos: "dependabot" } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Security Alert: elliptic", id: 408, kind: IssueKind.PR, kudos: "dependabot" } }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "13.0.4", releaseDate: "March 2021" } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Bookmarks on deleted/missing files breaks jumping", id: 390, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Toggling bookmarks on Untitled documents does not work", id: 391, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "13.0.3", releaseDate: "March 2021" } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: "Update Tabnine URL" }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "13.0.2", releaseDate: "February 2021" } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Command `bookmarks.toggle` not found - loading empty workspace with random files", id: 395, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "13.0.1", releaseDate: "February 2021" } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Command `bookmarks.toggle` not found - extension was not activated", id: 387, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "13.0.0", releaseDate: "February 2021" } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Support <b>Remote Development</b>", id: 230, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Improvements on <b>multi-root</b> support", id: 193, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Group bookmarks by folder on multi-root in Side Bar", id: 249, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Cross-platform support", id: 205, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Do not show welcome page if installed by Settings Sync", id: 377, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "12.1.4", releaseDate: "January 2021" } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: "Update Tabnine URL" }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "12.1.3", releaseDate: "January 2021" } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Added new translations", id: 367, kind: IssueKind.PR, kudos: "@loniceras" } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: "Update Tabnine URL" }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "12.1.2", releaseDate: "January 2021" } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: "Tabnine becomes a Sponsor" }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "12.1.0", releaseDate: "December 2020" } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Support submenu for editor commands", id: 351, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.CHANGED, detail: { message: "Setting <b>bookmarks.navigateThroughAllFiles</b> is now <b>true</b> by default", id: 102, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Remove unnecessary files from extension package", id: 355, kind: IssueKind.Issue } }); return changeLog; } public provideSupportChannels(): SupportChannel[] { const supportChannels: SupportChannel[] = []; supportChannels.push({ title: "Become a sponsor on Patreon", link: "https://www.patreon.com/alefragnani", message: "Become a Sponsor" }); supportChannels.push({ title: "Donate via PayPal", link: "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=EP57F3B6FXKTU&lc=US&item_name=Alessandro%20Fragnani&item_number=vscode%20extensions&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted", message: "Donate via PayPal" }); return supportChannels; } } export class BookmarksSponsorProvider implements SponsorProvider { public provideSponsors(): Sponsor[] { const sponsors: Sponsor[] = []; const sponsorCodeStream: Sponsor = <Sponsor>{ title: "Learn more about Codestream", link: "https://sponsorlink.codestream.com/?utm_source=vscmarket&utm_campaign=bookmarks&utm_medium=banner", image: { dark: "https://alt-images.codestream.com/codestream_logo_bookmarks.png", light: "https://alt-images.codestream.com/codestream_logo_bookmarks.png" }, width: 52, // message: `<p>Eliminate context switching and costly distractions. // Create and merge PRs and perform code reviews from inside your // IDE while using jump-to-definition, your keybindings, and other IDE favorites.</p>`, // extra: // `<a title="Learn more about CodeStream" href="https://sponsorlink.codestream.com/?utm_source=vscmarket&utm_campaign=bookmarks&utm_medium=banner"> // Learn more</a>` }; sponsors.push(sponsorCodeStream); const sponsorTabnine: Sponsor = <Sponsor>{ title: "Learn more about Tabnine", link: "https://bit.ly/2LZsrQ9", image: { dark: "https://github.com/alefragnani/oss-resources/raw/master/images/sponsors/tabnine-hi-res.png", light: "https://github.com/alefragnani/oss-resources/raw/master/images/sponsors/tabnine-hi-res.png" }, width: 40, // message: `<p>Improve your Bookmarks experience with Tabnine code // completions! Tabnine is a free powerful Artificial Intelligence // assistant designed to help you code faster, reduce mistakes, // and discover best coding practices - without ever leaving the // comfort of VSCode.</p>`, // extra: // `<a title="Learn more about Tabnine" href="https://www.tabnine.com"> // Get it now</a>` }; sponsors.push(sponsorTabnine); return sponsors; } } export class BookmarksSocialMediaProvider implements SocialMediaProvider { public provideSocialMedias() { return [{ title: "Follow me on Twitter", link: "https://www.twitter.com/alefragnani" }]; } }
the_stack
module PageStack{ export var DEBUG = false; const history_go = history.go; export var currentStack:StateStack; var iFrameHistoryLengthAsFake = 0; /** * callback when user press back history button * @return is back press consumed */ export var backListener:()=>boolean; /** * callback when call PageStack.openPage() * @return opened page or true means open success */ export var pageOpenHandler:(pageId:string, pageExtra?:any, isRestore?:boolean)=>any; /** * callback when user modify location.hash * @return opened page or true means open success */ export var pagePushHandler:(pageId:string, pageExtra?:any)=>any; /** * callback when page will close * @return closed page or true means close success. The history will back after close success */ export var pageCloseHandler:(pageId:string, pageExtra?:any)=>any; let historyLocking = false;//wait history go complete let windowLoadLocking = true;//wait window load finish let pendingFuncLock = []; let initCalled = false; export function init(){ initCalled = true; _init(); //override history go/back/forward history.go = function(delta:number){ PageStack.go(delta); }; history.back = function(delta=-1){ PageStack.go(delta); }; history.forward = function(delta=1){ PageStack.go(delta); }; } function checkInitCalled(){ if(!initCalled) throw Error("PageStack.init() must be call first"); } function _init(){ currentStack = history.state; if(currentStack && !currentStack.isRoot){ console.log('already has history.state when _init PageState, restore page'); restorePageFromStackIfNeed(); }else{ currentStack = currentStack || { pageId: '', isRoot: true, stack: [{pageId: null}] }; let initOpenUrl = location.hash; if(initOpenUrl && initOpenUrl.indexOf('#')===0) initOpenUrl = initOpenUrl.substring(1); removeLastHistoryIfFaked(); ensureLockDo(()=>{ //set root hash '#' when _init PageStack history.replaceState(currentStack, null, '#'); }); if(initOpenUrl && initOpenUrl.length>0){ if(firePagePush(initOpenUrl, null)){ notifyNewPageOpened(initOpenUrl); } } } ensureLastHistoryFaked(); if (document.readyState === 'complete') { windowLoadLocking = false; setTimeout(initOnpopstate, 0); }else{ window.addEventListener('load', ()=>{ windowLoadLocking = false; //init listener popstate delay, because safari will trigger a 'onpopstate' when page load finish, should ignore this. window.removeEventListener('popstate', onpopstateListener); //a 'popstate' event will trigger before next frame in safari setTimeout(initOnpopstate, 0); }); } } //_init onpopstate, deal when user press back / modify location hash let onpopstateListener = function(ev:PopStateEvent){ let stack = <StateStack>ev.state; if(historyLocking){ //historyGo method will callback to here, do nothing only remember stack currentStack = stack; return; } if(DEBUG) console.log('onpopstate', stack); if(!stack){ //no state, user modified the hash. let pageId = location.hash; if(pageId[0]==='#') pageId = pageId.substring(1); //back the changed hash page & fake page historyGo(-2, false); if(firePagePush(pageId, null)){ notifyNewPageOpened(pageId); }else{ ensureLastHistoryFaked(); } }else if(currentStack.stack.length!=stack.stack.length){ //will happen when back multi page (long click back button on pc chrome) let delta = stack.stack.length - currentStack.stack.length; if(delta>=0){ console.warn('something error! stack: ', stack, 'last stack: ', currentStack); return; } var stackList = currentStack.stack; currentStack = stack; //history already change, try close the pages tryClosePageAfterHistoryChanged(stackList, delta); }else{ currentStack = stack; //user press back button. if(fireBackPressed()){ //user handle the back press. ensureLastHistoryFaked(); }else{ var stackList = currentStack.stack; var pageId = stackList[stackList.length-1].pageId; if(firePageClose(pageId, stackList[stackList.length-1].extra)){ //should go back real. historyGo(-1); }else{ ensureLastHistoryFaked(); } } } }; function initOnpopstate(){ window.removeEventListener('popstate', onpopstateListener); window.addEventListener('popstate', onpopstateListener); } export function go(delta:number, pageAlreadyClose=false){ checkInitCalled(); if(historyLocking){ //do delay ensureLockDo(()=>{ go(delta); }); return; } var stackList = currentStack.stack; if(delta===-1 && !pageAlreadyClose){ if(!firePageClose(stackList[stackList.length-1].pageId, stackList[stackList.length-1].extra)){ //page not close, can't go back return; } } removeLastHistoryIfFaked(); historyGo(delta); if(delta<-1 && !pageAlreadyClose) { ensureLockDo(()=> { //after history already change, fire close page tryClosePageAfterHistoryChanged(stackList, delta); }); } } function tryClosePageAfterHistoryChanged(stateListBeforeHistoryChange:StateSaved[], delta:number){ let historyLength = stateListBeforeHistoryChange.length; for(let i=historyLength+delta; i<historyLength; i++){ let state = stateListBeforeHistoryChange[i]; if(!firePageClose(state.pageId, state.extra)){ //restore the page history if not close notifyNewPageOpened(state.pageId, state.extra); } } } export function back(pageAlreadyClose=false){ checkInitCalled(); go(-1, pageAlreadyClose); } export function openPage(pageId:string, extra?:any):any { checkInitCalled(); pageId+=''; var openResult = firePageOpen(pageId, extra); if(openResult){ notifyNewPageOpened(pageId, extra); } return openResult; } export function backToPage(pageId:string){ checkInitCalled(); if(DEBUG) console.log('backToPage', pageId); if(historyLocking){ //do delay ensureLockDo(()=>{ backToPage(pageId); }); } let stackList = currentStack.stack; let historyLength = stackList.length; for(let i=historyLength-1; i>=0; i--){//reverse let state = stackList[i]; if(state.pageId == pageId){ let delta = i - historyLength; removeLastHistoryIfFaked(); historyGo(delta); return; } } } let releaseLockingTimeout; let requestHistoryGoWhenLocking = 0; let ensureFakeAfterHistoryChange = false; export function historyGo(delta:number, ensureFaked=true){ if(delta>=0) return;//not support forward if(history.length === 1) return;//no history ensureFakeAfterHistoryChange = ensureFakeAfterHistoryChange || ensureFaked; if(historyLocking){ requestHistoryGoWhenLocking += delta; return; } if(DEBUG) console.log('historyGo', delta); historyLocking = true; const state = history.state; if(releaseLockingTimeout) clearTimeout(releaseLockingTimeout); function checkRelease(){ clearTimeout(releaseLockingTimeout); if(history.state === state){ releaseLockingTimeout = setTimeout(checkRelease, 0); }else{ let continueGo = requestHistoryGoWhenLocking; if(continueGo!=0){ requestHistoryGoWhenLocking = 0; historyLocking = false; historyGo(continueGo, false); }else { //history change complete if(ensureFakeAfterHistoryChange) ensureLastHistoryFakedImpl(); ensureFakeAfterHistoryChange = false; releaseLockingTimeout = setTimeout(()=> { historyLocking = false; }, 10); } } } releaseLockingTimeout = setTimeout(checkRelease, 0); history_go.call(history, delta); } //if page reload, but the page content will clear, should re-open pages function restorePageFromStackIfNeed(){ if(currentStack){ let copy = currentStack.stack.concat(); copy.shift();//ignore root stack for(let saveState of copy){ firePageOpen(saveState.pageId, saveState.extra, true); } } } function fireBackPressed():boolean { if(backListener){ try { return backListener(); } catch (e) { console.error(e); } } } function firePageOpen(pageId:string, pageExtra?:any, isRestore=false):any { if(pageOpenHandler){ try { return pageOpenHandler(pageId, pageExtra, isRestore); } catch (e) { console.error(e); } } } function firePagePush(pageId:string, pageExtra?:any):any { if(pagePushHandler){ try { return pagePushHandler(pageId, pageExtra); } catch (e) { console.error(e); } } } function firePageClose(pageId:string, pageExtra?:any):boolean { if(pageCloseHandler){ try { return pageCloseHandler(pageId, pageExtra); } catch (e) { console.error(e); } } } /** * call when app logic already close page. sync browser history here. */ export function notifyPageClosed(pageId:string):void { checkInitCalled(); if(DEBUG) console.log('notifyPageClosed', pageId); if(historyLocking){ //do delay ensureLockDo(()=>{ notifyPageClosed(pageId); }); return; } let stackList = currentStack.stack; let historyLength = stackList.length; for(let i=historyLength-1; i>=0; i--){//reverse let state = stackList[i]; if(state.pageId == pageId){ if(i === historyLength-1){//last page closed, back the history now removeLastHistoryIfFaked(); historyGo(-1); }else{ let delta = i - historyLength; (function (delta) { removeLastHistoryIfFaked(); //back history to the aim page first historyGo(delta); //then re-add other pages to history ensureLockDoAtFront(()=> { let historyLength = stackList.length; let pageStartAddIndex = historyLength + delta + 1; for (let j = pageStartAddIndex; j < historyLength; j++) { notifyNewPageOpened(stackList[j].pageId, stackList[j].extra); } }); })(delta); } return; } } } /** * call when app logic already open page. sync browser history here. */ export function notifyNewPageOpened(pageId:string, extra?:any){ checkInitCalled(); if(DEBUG) console.log('notifyNewPageOpened', pageId); let state:StateSaved = { pageId : pageId, extra : extra }; ensureLockDo(function(){ currentStack.stack.push(state); currentStack.pageId = pageId; currentStack.isRoot = false; if(history.state.isFake){ //replace the fake page history.replaceState(currentStack, null, '#'+pageId); }else{ history.pushState(currentStack, null, '#'+pageId); } ensureLastHistoryFakedImpl(); }); } export function getPageExtra(pageId?:string):any { checkInitCalled(); let stackList = currentStack.stack; let historyLength = stackList.length; if(!pageId){ return stackList[historyLength - 1].extra; }else{ for(let i=historyLength-1; i>=0; i--) {//reverse let state = stackList[i]; if(state.pageId == pageId){ return state.extra; } } } } export function setPageExtra(extra:any, pageId?:string):void { checkInitCalled(); removeLastHistoryIfFaked(); ensureLockDo(function() { let stackList = currentStack.stack; let historyLength = stackList.length; if(!pageId){ stackList[historyLength - 1].extra = extra; history.replaceState(currentStack, null, ''); }else{ for(let i=historyLength-1; i>=0; i--) {//reverse let state = stackList[i]; if(state.pageId == pageId){ state.extra = extra; history.replaceState(currentStack, null, ''); break; } } } ensureLastHistoryFakedImpl(); }); } function ensureLockDo(func:()=>any){ checkInitCalled(); if(!historyLocking && !windowLoadLocking){ func(); return; } pendingFuncLock.push(func); _queryLockDo(); } function ensureLockDoAtFront(func:()=>any, runNowIfNotLock=false){ checkInitCalled(); if(!historyLocking && !windowLoadLocking && runNowIfNotLock){ func(); return; } pendingFuncLock.splice(0, 0, func); _queryLockDo(); } let execLockedTimeoutId:number; function _queryLockDo(){ if(execLockedTimeoutId) clearTimeout(execLockedTimeoutId); function execLockedFunctions(){ if(historyLocking || windowLoadLocking){ clearTimeout(execLockedTimeoutId); execLockedTimeoutId = setTimeout(execLockedFunctions, 0); }else{ let f; while(f = pendingFuncLock.shift()){ f(); if(historyLocking || windowLoadLocking){ //case history change when call the function, all other functions will call next frame. clearTimeout(execLockedTimeoutId); execLockedTimeoutId = setTimeout(execLockedFunctions, 0); break; } } } } execLockedTimeoutId = setTimeout(execLockedFunctions, 0); } /** * If current page has iFrame, you should call this method to fix history before close the page. * (no need if iFrame has no history) * @param historyLengthWhenInitIFrame */ export function preClosePageHasIFrame(historyLengthWhenInitIFrame:number){ history.pushState({isFake:true}, null, null); iFrameHistoryLengthAsFake = history.length - historyLengthWhenInitIFrame; } function removeLastHistoryIfFaked(){ ensureLockDo(removeLastHistoryIfFakedImpl); } function removeLastHistoryIfFakedImpl(){ if(history.state && history.state.isFake){ if(DEBUG) console.log('remove Fake History'); history.replaceState(null, null, '');//make history.state.isFake = false historyGo(-1 - iFrameHistoryLengthAsFake, false); iFrameHistoryLengthAsFake = 0; } } function ensureLastHistoryFaked(){ ensureLockDo(ensureLastHistoryFakedImpl); } function ensureLastHistoryFakedImpl(){ if(!history.state.isFake){ if(DEBUG) console.log('append Fake History'); history.pushState({ isFake: true, isRoot: currentStack.isRoot, stack: currentStack.stack, }, null, ''); } } export interface StateStack { pageId:string; isRoot?:boolean; stack:StateSaved[]; } export interface StateSaved { pageId:string; extra?:any; } }
the_stack
import * as React from "react"; import { makeKeyClick } from "./utils/react"; import { Action, BoardType } from "./types"; import { $setting, get } from "./views/settings"; import { currentBoardIsROM } from "./boards"; import { changeCurrentAction } from "./app/appControl"; import moveImage from "./img/toolbar/move.png"; import lineImage from "./img/toolbar/line.png"; import stickylineImage from "./img/toolbar/stickyline.png"; import rotateImage from "./img/toolbar/rotate.png"; import eraserImage from "./img/toolbar/eraser.png"; import telescopeImage from "./img/toolbar/telescope.png"; import blueImage from "./img/toolbar/blue.png"; import blue3Image from "./img/toolbar/blue3.png"; import redImage from "./img/toolbar/red.png"; import red3Image from "./img/toolbar/red3.png"; import happeningImage from "./img/toolbar/happening.png"; import happening3Image from "./img/toolbar/happening3.png"; import chanceImage from "./img/toolbar/chance.png"; import chance2Image from "./img/toolbar/chance2.png"; import chance3Image from "./img/toolbar/chance3.png"; import bowserImage from "./img/toolbar/bowser.png"; import bowser3Image from "./img/toolbar/bowser3.png"; import minigameImage from "./img/toolbar/minigame.png"; import shroomImage from "./img/toolbar/shroom.png"; import otherImage from "./img/toolbar/other.png"; import starImage from "./img/toolbar/star.png"; import blackstarImage from "./img/toolbar/blackstar.png"; import arrowImage from "./img/toolbar/arrow.png"; import startImage from "./img/toolbar/start.png"; import itemImage from "./img/toolbar/item.png"; import item3Image from "./img/toolbar/item3.png"; import battleImage from "./img/toolbar/battle.png"; import battle3Image from "./img/toolbar/battle3.png"; import bankImage from "./img/toolbar/bank.png"; import bank3Image from "./img/toolbar/bank3.png"; import gameguyImage from "./img/toolbar/gameguy.png"; import banksubtypeImage from "./img/toolbar/banksubtype.png"; import banksubtype2Image from "./img/toolbar/banksubtype2.png"; import bankcoinsubtypeImage from "./img/toolbar/bankcoinsubtype.png"; import itemshopsubtypeImage from "./img/toolbar/itemshopsubtype.png"; import itemshopsubtype2Image from "./img/toolbar/itemshopsubtype2.png"; import toadImage from "./img/toolbar/toad.png"; import mstarImage from "./img/toolbar/mstar.png"; import booImage from "./img/toolbar/boo.png"; import bowsercharacterImage from "./img/toolbar/bowsercharacter.png"; import koopaImage from "./img/toolbar/koopa.png"; import markstarImage from "./img/toolbar/markstar.png"; import markgateImage from "./img/toolbar/markgate.png"; import basic3Image from "./img/toolbar/basic3.png"; import minigameduel3Image from "./img/toolbar/minigameduel3.png"; import reverse3Image from "./img/toolbar/reverse3.png"; import happeningduel3Image from "./img/toolbar/happeningduel3.png"; import gameguyduelImage from "./img/toolbar/gameguyduel.png"; import powerupImage from "./img/toolbar/powerup.png"; import startblueImage from "./img/toolbar/startblue.png"; import startredImage from "./img/toolbar/startred.png"; import "./css/toolbar.scss"; // This used to be a toolbar... now it is the toolbox contents. interface IToolbarItem { name: string; icon: string; type: Action; draggable?: boolean; advanced?: boolean; } interface IToolbarSpacer { spacer: true; } type ToolbarItem = IToolbarItem | IToolbarSpacer const mp1_actions: ToolbarItem[] = [ { "name": "Move spaces", "icon": moveImage, "type": Action.MOVE }, { "name": "Connect spaces", "icon": lineImage, "type": Action.LINE }, { "name": "Connect multiple spaces in one click", "icon": stickylineImage, "type": Action.LINE_STICKY }, { "name": "Erase spaces and lines", "icon": eraserImage, "type": Action.ERASE }, { "name": "Telescope tool: move your cursor over the map to visualize how it will look during gameplay", "icon": telescopeImage, "type": Action.TELESCOPE }, { "spacer": true}, { "name": "Add blue space", "icon": blueImage, "type": Action.ADD_BLUE, draggable: true }, { "name": "Add red space", "icon": redImage, "type": Action.ADD_RED, draggable: true }, { "name": "Add happening space", "icon": happeningImage, "type": Action.ADD_HAPPENING, draggable: true }, { "name": "Add chance time space", "icon": chanceImage, "type": Action.ADD_CHANCE, draggable: true }, { "name": "Add Bowser space", "icon": bowserImage, "type": Action.ADD_BOWSER, draggable: true }, { "name": "Add Mini-Game space", "icon": minigameImage, "type": Action.ADD_MINIGAME, draggable: true }, { "name": "Add shroom space", "icon": shroomImage, "type": Action.ADD_SHROOM, draggable: true }, { "name": "Add invisible space", "icon": otherImage, "type": Action.ADD_OTHER, draggable: true }, { "name": "Add star space (decoration)", "icon": starImage, "type": Action.ADD_STAR, draggable: true, advanced: true }, { "name": "Add start space", "icon": startImage, "type": Action.ADD_START, draggable: true, advanced: true }, { "spacer": true}, // { // "group": "Other spaces", // "icon": otherImage, // "actions": [ { "name": "Add Toad", "icon": toadImage, "type": Action.ADD_TOAD_CHARACTER, draggable: true }, { "name": "Add Boo", "icon": booImage, "type": Action.ADD_BOO_CHARACTER, draggable: true }, { "name": "Add Bowser", "icon": bowsercharacterImage, "type": Action.ADD_BOWSER_CHARACTER, draggable: true }, { "name": "Add Koopa Troopa", "icon": koopaImage, "type": Action.ADD_KOOPA_CHARACTER, draggable: true }, { "name": "Mark space as hosting star", "icon": markstarImage, "type": Action.MARK_STAR }, // ] // } ]; const mp2_actions: ToolbarItem[] = [ { "name": "Move spaces", "icon": moveImage, "type": Action.MOVE }, { "name": "Connect spaces", "icon": lineImage, "type": Action.LINE }, { "name": "Connect multiple spaces in one click", "icon": stickylineImage, "type": Action.LINE_STICKY }, { "name": "Erase spaces and lines", "icon": eraserImage, "type": Action.ERASE }, { "name": "Rotate arrow spaces", "icon": rotateImage, "type": Action.ROTATE }, { "name": "Telescope tool: move your cursor over the map to visualize how it will look during gameplay", "icon": telescopeImage, "type": Action.TELESCOPE }, { "spacer": true}, { "name": "Add blue space", "icon": blueImage, "type": Action.ADD_BLUE, draggable: true }, { "name": "Add red space", "icon": redImage, "type": Action.ADD_RED, draggable: true }, { "name": "Add happening space", "icon": happeningImage, "type": Action.ADD_HAPPENING, draggable: true }, { "name": "Add chance time space", "icon": chance2Image, "type": Action.ADD_CHANCE, draggable: true }, { "name": "Add Bowser space", "icon": bowserImage, "type": Action.ADD_BOWSER, draggable: true }, { "name": "Add item space", "icon": itemImage, "type": Action.ADD_ITEM, draggable: true }, { "name": "Add battle space", "icon": battleImage, "type": Action.ADD_BATTLE, draggable: true }, { "name": "Add bank space", "icon": bankImage, "type": Action.ADD_BANK, draggable: true }, { "name": "Add invisible space", "icon": otherImage, "type": Action.ADD_OTHER, draggable: true }, { "name": "Add star space (decoration)", "icon": starImage, "type": Action.ADD_STAR, draggable: true, advanced: true }, { "name": "Add black star space (decoration)", "icon": blackstarImage, "type": Action.ADD_BLACKSTAR, draggable: true, advanced: true }, { "name": "Add start space", "icon": startImage, "type": Action.ADD_START, draggable: true, advanced: true }, { "name": "Add arrow space", "icon": arrowImage, "type": Action.ADD_ARROW, draggable: true }, { "spacer": true}, { "name": "Add Toad", "icon": toadImage, "type": Action.ADD_TOAD_CHARACTER, draggable: true }, { "name": "Add Boo", "icon": booImage, "type": Action.ADD_BOO_CHARACTER, draggable: true }, { "name": "Add bank", "icon": banksubtype2Image, "type": Action.ADD_BANK_SUBTYPE, draggable: true }, { "name": "Add bank coin stack", "icon": bankcoinsubtypeImage, "type": Action.ADD_BANKCOIN_SUBTYPE, draggable: true }, { "name": "Add item shop", "icon": itemshopsubtype2Image, "type": Action.ADD_ITEMSHOP_SUBTYPE, draggable: true }, { "name": "Mark space as hosting star", "icon": markstarImage, "type": Action.MARK_STAR }, ]; const mp3_actions: ToolbarItem[] = [ { "name": "Move spaces", "icon": moveImage, "type": Action.MOVE }, { "name": "Connect spaces", "icon": lineImage, "type": Action.LINE }, { "name": "Connect multiple spaces in one click", "icon": stickylineImage, "type": Action.LINE_STICKY }, { "name": "Erase spaces and lines", "icon": eraserImage, "type": Action.ERASE }, { "name": "Rotate arrow spaces", "icon": rotateImage, "type": Action.ROTATE }, { "name": "Telescope tool: move your cursor over the map to visualize how it will look during gameplay", "icon": telescopeImage, "type": Action.TELESCOPE }, { "spacer": true}, { "name": "Add blue space", "icon": blue3Image, "type": Action.ADD_BLUE, draggable: true }, { "name": "Add red space", "icon": red3Image, "type": Action.ADD_RED, draggable: true }, { "name": "Add happening space", "icon": happening3Image, "type": Action.ADD_HAPPENING, draggable: true }, { "name": "Add chance time space", "icon": chance3Image, "type": Action.ADD_CHANCE, draggable: true }, { "name": "Add Bowser space", "icon": bowser3Image, "type": Action.ADD_BOWSER, draggable: true }, { "name": "Add item space", "icon": item3Image, "type": Action.ADD_ITEM, draggable: true }, { "name": "Add battle space", "icon": battle3Image, "type": Action.ADD_BATTLE, draggable: true }, { "name": "Add bank space", "icon": bank3Image, "type": Action.ADD_BANK, draggable: true }, { "name": "Add Game Guy space", "icon": gameguyImage, "type": Action.ADD_GAMEGUY, draggable: true }, { "name": "Add invisible space", "icon": otherImage, "type": Action.ADD_OTHER, draggable: true }, { "name": "Add star space (decoration)", "icon": starImage, "type": Action.ADD_STAR, draggable: true, advanced: true }, { "name": "Add start space", "icon": startImage, "type": Action.ADD_START, draggable: true, advanced: true }, { "name": "Add arrow space", "icon": arrowImage, "type": Action.ADD_ARROW, draggable: true }, { "spacer": true}, { "name": "Add Millennium Star", "icon": mstarImage, "type": Action.ADD_TOAD_CHARACTER, draggable: true }, { "name": "Add Boo", "icon": booImage, "type": Action.ADD_BOO_CHARACTER, draggable: true }, { "name": "Add bank", "icon": banksubtypeImage, "type": Action.ADD_BANK_SUBTYPE, draggable: true }, { "name": "Add bank coin stack", "icon": bankcoinsubtypeImage, "type": Action.ADD_BANKCOIN_SUBTYPE, draggable: true }, { "name": "Add item shop", "icon": itemshopsubtypeImage, "type": Action.ADD_ITEMSHOP_SUBTYPE, draggable: true }, { "name": "Mark space as hosting star", "icon": markstarImage, "type": Action.MARK_STAR }, { "name": "Mark space as Skeleton Key gate", "icon": markgateImage, "type": Action.MARK_GATE }, ]; const mp3_duel_actions: ToolbarItem[] = [ { "name": "Move spaces", "icon": moveImage, "type": Action.MOVE }, { "name": "Connect spaces", "icon": lineImage, "type": Action.LINE }, { "name": "Connect multiple spaces in one click", "icon": stickylineImage, "type": Action.LINE_STICKY }, { "name": "Erase spaces and lines", "icon": eraserImage, "type": Action.ERASE }, { "name": "Telescope tool: move your cursor over the map to visualize how it will look during gameplay", "icon": telescopeImage, "type": Action.TELESCOPE }, { "spacer": true}, { "name": "Add basic space", "icon": basic3Image, "type": Action.ADD_DUEL_BASIC, draggable: true }, { "name": "Add Mini-Game space", "icon": minigameduel3Image, "type": Action.ADD_MINIGAME, draggable: true }, { "name": "Add reverse space", "icon": reverse3Image, "type": Action.ADD_DUEL_REVERSE, draggable: true }, { "name": "Add happening space", "icon": happeningduel3Image, "type": Action.ADD_HAPPENING, draggable: true }, { "name": "Add Game Guy space", "icon": gameguyduelImage, "type": Action.ADD_GAMEGUY, draggable: true }, { "name": "Add power-up space", "icon": powerupImage, "type": Action.ADD_DUEL_POWERUP, draggable: true }, { "name": "Add invisible space", "icon": otherImage, "type": Action.ADD_OTHER, draggable: true }, { "name": "Add blue start space", "icon": startblueImage, "type": Action.ADD_DUEL_START_BLUE, draggable: true, advanced: true }, { "name": "Add red start space", "icon": startredImage, "type": Action.ADD_DUEL_START_RED, draggable: true, advanced: true }, ]; function _itemIsSpacer(item: ToolbarItem): item is IToolbarSpacer { return "spacer" in item && item.spacer; } function _getActions(gameVersion: number, boardType: BoardType) { let actions; switch (gameVersion) { case 1: actions = mp1_actions; break; case 2: actions = mp2_actions; break; case 3: if (boardType === BoardType.DUEL) actions = mp3_duel_actions; else actions = mp3_actions; break; default: throw new Error(`Unknown game version found by Toolbar (${gameVersion})`); } if (!get($setting.uiAdvanced)) { actions = actions.filter(a => !(a as IToolbarItem).advanced); } return actions; } function _buttonClicked(type: Action) { changeCurrentAction(type); } interface IToolbarProps { currentAction: Action; gameVersion: number; boardType: BoardType; } export class Toolbar extends React.Component<IToolbarProps> { state = {} render() { if (currentBoardIsROM()) { return ( <div className="toolbarReadonly">Board is readonly.</div> ); } let i = 0; let actions = _getActions(this.props.gameVersion, this.props.boardType); let actionElements = actions.map(item => { // if (item.group) { // return ( // <ToolbarGroup key={item.group} icon={item.icon} actions={item.actions} currentAction={this.props.currentAction} /> // ) // } if (_itemIsSpacer(item)) { return ( <ToolbarSpacer key={"spacer" + i++} /> ); } let isCurrentAction = this.props.currentAction === item.type; return ( <ToolbarButton key={item.type} current={isCurrentAction} action={item} /> ); }); return ( <div className="toolbar" role="toolbar"> {actionElements} </div> ); } }; // const ToolbarGroup = class ToolbarGroup extends React.Component { // render() { // var btnClass = "toolbarGroup"; // var icon; // var actions = this.props.actions.map(item => { // if (item.type === this.props.currentAction) // icon = item.icon; // var isCurrentAction = this.props.currentAction === item.type; // return ( // <ToolbarButton key={item.type} action={item} current={isCurrentAction} /> // ); // }); // if (icon) // btnClass += " selected"; // Select the group if one of its actions is selected. // else // icon = this.props.icon; // var left = actions.length * -50; // var maxWidth = actions.length * 50; // if (actions.length >= 5) { // left /= 2; // maxWidth /= 2; // } // var panelStyle = { left: left, maxWidth: maxWidth }; // return ( // <div className={btnClass} title={this.props.group} role="button" tabIndex="0"> // <img className="toolbarIcon" src={icon}></img> // <div className="toolbarGroupPanel" style={panelStyle}> // {actions} // </div> // </div> // ); // } // }; interface IToolbarButtonProps { action: IToolbarItem; current: boolean; } class ToolbarButton extends React.Component<IToolbarButtonProps> { handleClick = () => { _buttonClicked(this.props.action.type); } onDragStart = (event: any) => { if (!this.props.action.draggable) return; // Disobeying draggable? Its more likely than you think! // Drag-drop is not really recommended, but user testing found it intuitive. event.dataTransfer.setData("text", JSON.stringify({ action: this.props.action })); } render() { let btnClass = "toolbarButton"; if (this.props.current) btnClass += " selected"; return ( <div className={btnClass} title={this.props.action.name} role="button" tabIndex={0} onClick={this.handleClick} onKeyDown={makeKeyClick(this.handleClick)} draggable={this.props.action.draggable} onDragStart={this.onDragStart}> <img className="toolbarIcon" src={this.props.action.icon} alt=""></img> </div> ); } }; const ToolbarSpacer = class ToolbarSpacer extends React.Component { render() { return ( <div className="toolbarSpacer" role="separator"></div> ); } };
the_stack
namespace egret { /** * @private */ const enum Keys{ eventTarget, eventsMap, captureEventsMap, notifyLevel } let ONCE_EVENT_LIST:egret.sys.EventBin[] = []; /** * The EventDispatcher class is the base class for all classes that dispatchEvent events. The EventDispatcher class implements * the IEventDispatcher interface and is the base class for the DisplayObject class. The EventDispatcher class allows * any object on the display list to be an event target and as such, to use the methods of the IEventDispatcher interface. * Event targets are an important part of the Egret event model. The event target serves as the focal point for how events * flow through the display list hierarchy. When an event such as a touch tap, Egret dispatches an event object into the * event flow from the root of the display list. The event object then makes its way through the display list until it * reaches the event target, at which point it begins its return trip through the display list. This round-trip journey * to the event target is conceptually divided into three phases: <br/> * the capture phase comprises the journey from the root to the last node before the event target's node, the target * phase comprises only the event target node, and the bubbling phase comprises any subsequent nodes encountered on * the return trip to the root of the display list. In general, the easiest way for a user-defined class to gain event * dispatching capabilities is to extend EventDispatcher. If this is impossible (that is, if the class is already extending * another class), you can instead implement the IEventDispatcher interface, create an EventDispatcher member, and write simple * hooks to route calls into the aggregated EventDispatcher. * @see egret.IEventDispatcher * @version Egret 2.4 * @platform Web,Native * @includeExample egret/events/EventDispatcher.ts * @language en_US */ /** * EventDispatcher 是 Egret 的事件派发器类,负责进行事件的发送和侦听。 * 事件目标是事件如何通过显示列表层次结构这一问题的焦点。当发生鼠标单击、触摸或按键等事件时, * 框架会将事件对象调度到从显示列表根开始的事件流中。然后该事件对象在显示列表中前进,直到到达事件目标, * 然后从这一点开始其在显示列表中的回程。在概念上,到事件目标的此往返行程被划分为三个阶段: * 捕获阶段包括从根到事件目标节点之前的最后一个节点的行程,目标阶段仅包括事件目标节点,冒泡阶段包括回程上遇到的任何后续节点到显示列表的根。 * 通常,使用户定义的类能够调度事件的最简单方法是扩展 EventDispatcher。如果无法扩展(即,如果该类已经扩展了另一个类),则可以实现 * IEventDispatcher 接口,创建 EventDispatcher 成员,并编写一些简单的映射,将调用连接到聚合的 EventDispatcher 中。 * @see egret.IEventDispatcher * @version Egret 2.4 * @platform Web,Native * @includeExample egret/events/EventDispatcher.ts * @language zh_CN */ export class EventDispatcher extends HashObject implements IEventDispatcher { /** * create an instance of the EventDispatcher class. * @param target The target object for events dispatched to the EventDispatcher object. This parameter is used when * the EventDispatcher instance is aggregated by a class that implements IEventDispatcher; it is necessary so that the * containing object can be the target for events. Do not use this parameter in simple cases in which a class extends EventDispatcher. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 创建一个 EventDispatcher 类的实例 * @param target 此 EventDispatcher 所抛出事件对象的 target 指向。此参数主要用于一个实现了 IEventDispatcher 接口的自定义类, * 以便抛出的事件对象的 target 属性可以指向自定义类自身。请勿在直接继承 EventDispatcher 的情况下使用此参数。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public constructor(target:IEventDispatcher = null) { super(); this.$EventDispatcher = { 0: target ? target : this, 1: {}, 2: {}, 3: 0 }; } /** * @private */ $EventDispatcher:Object; /** * @private * * @param useCapture */ $getEventMap(useCapture?:boolean) { let values = this.$EventDispatcher; let eventMap:any = useCapture ? values[Keys.captureEventsMap] : values[Keys.eventsMap]; return eventMap; } /** * @inheritDoc * @version Egret 2.4 * @platform Web,Native */ public addEventListener(type:string, listener:Function, thisObject:any, useCapture?:boolean, priority?:number):void { this.$addListener(type, listener, thisObject, useCapture, priority); } /** * @inheritDoc * @version Egret 2.4 * @platform Web,Native */ public once(type:string, listener:Function, thisObject:any, useCapture?:boolean, priority?:number):void { this.$addListener(type, listener, thisObject, useCapture, priority, true); } /** * @private */ $addListener(type:string, listener:Function, thisObject:any, useCapture?:boolean, priority?:number, dispatchOnce?:boolean):void { if (DEBUG && !listener) { $error(1003, "listener"); } let values = this.$EventDispatcher; let eventMap:any = useCapture ? values[Keys.captureEventsMap] : values[Keys.eventsMap]; let list:egret.sys.EventBin[] = eventMap[type]; if (!list) { list = eventMap[type] = []; } else if (values[Keys.notifyLevel] !== 0) { eventMap[type] = list = list.concat(); } this.$insertEventBin(list, type, listener, thisObject, useCapture, priority, dispatchOnce); } $insertEventBin(list:any[], type:string, listener:Function, thisObject:any, useCapture?:boolean, priority?:number, dispatchOnce?:boolean):boolean { priority = +priority | 0; let insertIndex = -1; let length = list.length; for (let i = 0; i < length; i++) { let bin = list[i]; if (bin.listener == listener && bin.thisObject == thisObject && bin.target == this) { return false; } if (insertIndex == -1 && bin.priority < priority) { insertIndex = i; } } let eventBin:sys.EventBin = { type: type, listener: listener, thisObject: thisObject, priority: priority, target: this, useCapture: useCapture, dispatchOnce: !!dispatchOnce }; if (insertIndex !== -1) { list.splice(insertIndex, 0, eventBin); } else { list.push(eventBin); } return true; } /** * @inheritDoc * @version Egret 2.4 * @platform Web,Native */ public removeEventListener(type:string, listener:Function, thisObject:any, useCapture?:boolean):void { let values = this.$EventDispatcher; let eventMap:Object = useCapture ? values[Keys.captureEventsMap] : values[Keys.eventsMap]; let list:egret.sys.EventBin[] = eventMap[type]; if (!list) { return; } if (values[Keys.notifyLevel] !== 0) { eventMap[type] = list = list.concat(); } this.$removeEventBin(list, listener, thisObject); if (list.length == 0) { eventMap[type] = null; } } $removeEventBin(list:any[], listener:Function, thisObject:any):boolean { let length = list.length; for (let i = 0; i < length; i++) { let bin = list[i]; if (bin.listener == listener && bin.thisObject == thisObject && bin.target == this) { list.splice(i, 1); return true; } } return false; } /** * @inheritDoc * @version Egret 2.4 * @platform Web,Native */ public hasEventListener(type:string):boolean { let values = this.$EventDispatcher; return !!(values[Keys.eventsMap][type] || values[Keys.captureEventsMap][type]); } /** * @inheritDoc * @version Egret 2.4 * @platform Web,Native */ public willTrigger(type:string):boolean { return this.hasEventListener(type); } /** * @inheritDoc * @version Egret 2.4 * @platform Web,Native */ public dispatchEvent(event:Event):boolean { event.$currentTarget = this.$EventDispatcher[Keys.eventTarget]; event.$setTarget(event.$currentTarget); return this.$notifyListener(event, false); } /** * @private */ $notifyListener(event:Event, capturePhase:boolean):boolean { let values = this.$EventDispatcher; let eventMap:Object = capturePhase ? values[Keys.captureEventsMap] : values[Keys.eventsMap]; let list:egret.sys.EventBin[] = eventMap[event.$type]; if (!list) { return true; } let length = list.length; if (length == 0) { return true; } let onceList = ONCE_EVENT_LIST; //做个标记,防止外部修改原始数组导致遍历错误。这里不直接调用list.concat()因为dispatch()方法调用通常比on()等方法频繁。 values[Keys.notifyLevel]++; for (let i = 0; i < length; i++) { let eventBin = list[i]; eventBin.listener.call(eventBin.thisObject, event); if (eventBin.dispatchOnce) { onceList.push(eventBin); } if (event.$isPropagationImmediateStopped) { break; } } values[Keys.notifyLevel]--; while (onceList.length) { let eventBin = onceList.pop(); eventBin.target.removeEventListener(eventBin.type, eventBin.listener, eventBin.thisObject, eventBin.useCapture); } return !event.$isDefaultPrevented; } /** * Distribute a specified event parameters. * @param type The type of the event. Event listeners can access this information through the inherited type property. * @param bubbles Determines whether the Event object bubbles. Event listeners can access this information through * the inherited bubbles property. * @param data {any} data * @param cancelable Determines whether the Event object can be canceled. The default values is false. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 派发一个指定参数的事件。 * @param type {string} 事件类型 * @param bubbles {boolean} 确定 Event 对象是否参与事件流的冒泡阶段。默认值为 false。 * @param data {any} 事件data * @param cancelable {boolean} 确定是否可以取消 Event 对象。默认值为 false。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public dispatchEventWith(type:string, bubbles?:boolean, data?:any, cancelable?: boolean):boolean { if (bubbles || this.hasEventListener(type)) { let event:Event = Event.create(Event, type, bubbles, cancelable); event.data = data; let result = this.dispatchEvent(event); Event.release(event); return result; } return true; } } } namespace egret.sys { /** * @private * 事件信息对象 */ export interface EventBin { type:string; /** * @private */ listener: Function; /** * @private */ thisObject:any; /** * @private */ priority:number; /** * @private */ target:IEventDispatcher; /** * @private */ useCapture:boolean; /** * @private */ dispatchOnce:boolean; } }
the_stack
import { Trans } from "@lingui/macro"; import { i18nMark } from "@lingui/react"; import mixin from "reactjs-mixin"; import { Link } from "react-router"; import { MountService } from "foundation-ui"; import * as React from "react"; import { request } from "@dcos/mesos-client"; import { ProductIcons } from "@dcos/ui-kit/dist/packages/icons/dist/product-icons-enum"; import MarathonStore from "#PLUGINS/services/src/js/stores/MarathonStore"; import DateUtil from "#SRC/js/utils/DateUtil"; import { MesosMasterRequestType } from "#SRC/js/core/MesosMasterRequest"; import container from "#SRC/js/container"; import StoreMixin from "#SRC/js/mixins/StoreMixin"; import Breadcrumb from "../../components/Breadcrumb"; import BreadcrumbTextContent from "../../components/BreadcrumbTextContent"; import Config from "../../config/Config"; import ConfigStore from "../../stores/ConfigStore"; import ConfigurationMap from "../../components/ConfigurationMap"; import ConfigurationMapHeading from "../../components/ConfigurationMapHeading"; import ConfigurationMapLabel from "../../components/ConfigurationMapLabel"; import ConfigurationMapRow from "../../components/ConfigurationMapRow"; import ConfigurationMapSection from "../../components/ConfigurationMapSection"; import ConfigurationMapValue from "../../components/ConfigurationMapValue"; import { findNestedPropertyInObject } from "../../utils/Util"; import HashMapDisplay from "../../components/HashMapDisplay"; import Loader from "../../components/Loader"; import MetadataStore from "../../stores/MetadataStore"; import Page from "../../components/Page"; import VersionsModal from "../../components/modals/VersionsModal"; import { isEmpty } from "../../utils/ValidatorUtil"; import dcosVersion$ from "#SRC/js/stores/dcos-version"; const SystemOverviewBreadcrumbs = () => { const crumbs = [ <Breadcrumb key={0} title="Cluster"> <BreadcrumbTextContent> <Link to="/cluster/overview"> <Trans render="span">Overview</Trans> </Link> </BreadcrumbTextContent> </Breadcrumb>, ]; return ( <Page.Header.Breadcrumbs iconID={ProductIcons.Cluster} breadcrumbs={crumbs} /> ); }; class OverviewDetailTab extends mixin(StoreMixin) { state = { isClusterBuildInfoOpen: false, masterInfo: undefined, cluster: undefined, version: undefined, buildTime: undefined, startTime: undefined, dcosVersion: undefined, }; store_listeners = [ { name: "config", events: ["ccidSuccess"] }, { name: "marathon", events: ["instanceInfoSuccess"] }, { name: "metadata", events: ["dcosBuildInfoChange", "success"] }, ]; componentDidMount(...args) { super.componentDidMount(...args); MarathonStore.fetchMarathonInstanceInfo(); MetadataStore.fetchDCOSBuildInfo(); dcosVersion$.subscribe(({ version }) => { this.setState({ dcosVersion: version }); }); request({ type: "GET_FLAGS" }, "/mesos/api/v1?GET_FLAGS").subscribe( (response) => { const cluster = JSON.parse(response).get_flags.flags.find( (flag) => flag.name === "cluster" ); if (cluster) { this.setState({ cluster: cluster.value }); } } ); request({ type: "GET_VERSION" }, "/mesos/api/v1?GET_VERSION").subscribe( (response) => { const info = JSON.parse(response).get_version.version_info; if (info) { this.setState({ version: info.version, buildTime: info.build_time, }); } } ); container.get(MesosMasterRequestType).subscribe((response) => { const { get_master: { master_info: masterInfo, elected_time: electedTime, start_time: startTime, }, } = JSON.parse(response); this.setState({ masterInfo, electedTime, startTime }); }); } handleClusterConfigModalOpen = () => { this.setState({ isClusterBuildInfoOpen: true }); }; handleClusterConfigModalClose = () => { this.setState({ isClusterBuildInfoOpen: false }); }; getLoading() { return <Loader size="small" type="ballBeat" />; } getClusterDetails() { let ccid = ConfigStore.get("ccid"); let publicIP = this.getPublicIP(); let productVersion = this.state.dcosVersion; if (Object.keys(ccid).length) { ccid = ccid.zbase32_public_key; } else { ccid = this.getLoading(); } if (productVersion == null) { productVersion = this.getLoading(); } if (publicIP == null) { publicIP = this.getLoading(); } return ( <ConfigurationMapSection> <ConfigurationMapRow key="version"> <Trans render={<ConfigurationMapLabel />}> {Config.productName} Version </Trans> <ConfigurationMapValue>{productVersion}</ConfigurationMapValue> </ConfigurationMapRow> <ConfigurationMapRow key="ccid"> <Trans render={<ConfigurationMapLabel />}> Cryptographic Cluster ID </Trans> <ConfigurationMapValue>{ccid}</ConfigurationMapValue> </ConfigurationMapRow> <ConfigurationMapRow key="publicIP"> <Trans render={<ConfigurationMapLabel />}>Public IP</Trans> <ConfigurationMapValue>{publicIP}</ConfigurationMapValue> </ConfigurationMapRow> <MountService.Mount type="OverviewDetailTab:AdditionalGeneralDetails:Nodes" limit={1} /> <MountService.Mount type="OverviewDetailTab:AdditionalGeneralDetails:Date" limit={1} /> </ConfigurationMapSection> ); } getMarathonDetailsHash() { const marathonDetails = MarathonStore.getInstanceInfo(); if (!Object.keys(marathonDetails).length) { return null; } return { "Marathon Details": { Version: marathonDetails.version, "Framework ID": marathonDetails.frameworkId, Leader: marathonDetails.leader, "Marathon Config": marathonDetails.marathon_config, "ZooKeeper Config": marathonDetails.zookeeper_config, }, }; } getPageHeaderActions() { return [ { label: i18nMark("View Cluster Configuration"), onItemSelect: this.handleClusterConfigModalOpen, }, ]; } getPublicIP() { const publicIP = findNestedPropertyInObject( MetadataStore.get("metadata"), "PUBLIC_IPV4" ); if (!publicIP) { return null; } return publicIP; } /** * Get user if existent otherwise * return null * * @param {String} mesosBuildUser * @returns {Component|Null} User string or null * * @memberOf OverviewDetailTab */ getMesosBuildUser(mesosBuildUser) { if (isEmpty(mesosBuildUser)) { return null; } return <Trans render="span">by {mesosBuildUser}</Trans>; } /** * Build Mesos details * * @returns {Component} Mesos details component * * @memberOf OverviewDetailTab */ getMesosDetails() { const { masterInfo, cluster, version, buildTime, startTime, electedTime, buildUser, } = this.state; const mesosMasterInfo = masterInfo || this.getLoading(); const mesosCluster = cluster || this.getLoading(); const mesosVersion = version || this.getLoading(); const mesosBuilt = buildTime ? DateUtil.msToRelativeTime(buildTime * 1000) : this.getLoading(); const mesosStarted = startTime ? DateUtil.msToRelativeTime(startTime * 1000) : this.getLoading(); const mesosElected = electedTime ? DateUtil.msToRelativeTime(electedTime * 1000) : this.getLoading(); const mesosBuildUser = buildUser; return ( <ConfigurationMapSection> <ConfigurationMapRow key="cluster"> <Trans render={<ConfigurationMapLabel />}>Cluster</Trans> <ConfigurationMapValue>{mesosCluster}</ConfigurationMapValue> </ConfigurationMapRow> <ConfigurationMapRow key="leader"> <Trans render={<ConfigurationMapLabel />}>Leader</Trans> <ConfigurationMapValue> {mesosMasterInfo.hostname}:{mesosMasterInfo.port} </ConfigurationMapValue> </ConfigurationMapRow> <ConfigurationMapRow key="version"> <Trans render={<ConfigurationMapLabel />}>Version</Trans> <ConfigurationMapValue>{mesosVersion}</ConfigurationMapValue> </ConfigurationMapRow> <ConfigurationMapRow key="built"> <Trans render={<ConfigurationMapLabel />}>Built</Trans> <ConfigurationMapValue> {mesosBuilt} {this.getMesosBuildUser(mesosBuildUser)} </ConfigurationMapValue> </ConfigurationMapRow> <ConfigurationMapRow key="started"> <Trans render={<ConfigurationMapLabel />}>Started</Trans> <ConfigurationMapValue>{mesosStarted}</ConfigurationMapValue> </ConfigurationMapRow> <ConfigurationMapRow key="elected"> <Trans render={<ConfigurationMapLabel />}>Elected</Trans> <ConfigurationMapValue>{mesosElected}</ConfigurationMapValue> </ConfigurationMapRow> </ConfigurationMapSection> ); } render() { const buildInfo = MetadataStore.get("dcosBuildInfo"); const marathonHash = this.getMarathonDetailsHash(); let marathonDetails = null; let versionsModal = null; if (marathonHash) { marathonDetails = <HashMapDisplay hash={marathonHash} />; } if (buildInfo != null) { versionsModal = ( <VersionsModal onClose={this.handleClusterConfigModalClose} open={this.state.isClusterBuildInfoOpen} versionDump={buildInfo} /> ); } return ( <Page> <Page.Header actions={this.getPageHeaderActions()} breadcrumbs={<SystemOverviewBreadcrumbs />} /> <div className="container"> <ConfigurationMap> <Trans render={<ConfigurationMapHeading className="flush-top" />}> Cluster Details </Trans> <Trans render={<ConfigurationMapHeading level={2} />}> General </Trans> {this.getClusterDetails()} <Trans render={<ConfigurationMapHeading level={2} />}> Mesos Details </Trans> {this.getMesosDetails()} {marathonDetails} <MountService.Mount type="OverviewDetailTab:AdditionalClusterDetails" /> </ConfigurationMap> </div> {versionsModal} </Page> ); } } OverviewDetailTab.routeConfig = { label: i18nMark("Overview"), matches: /^\/overview\/details/, }; export default OverviewDetailTab;
the_stack
import { InanoSQLAdapter, InanoSQLTable, InanoSQLPlugin, InanoSQLInstance, adapterCreateIndexFilter, adapterConnectFilter, adapterDeleteIndexFilter, adapterAddIndexValueFilter, adapterDeleteIndexValueFilter, adapterReadIndexKeyFilter, adapterReadIndexKeysFilter } from "@nano-sql/core/lib/interfaces"; import { generateID, deepSet, chainAsync, allAsync, blankTableDefinition } from "@nano-sql/core/lib/utilities"; import * as redis from "redis"; const noClient = `No Redis client!`; export const RedisIndex = (connectArgs?: redis.ClientOpts, getClient?: (redisClient: redis.RedisClient) => void): InanoSQLPlugin => { let _db: redis.RedisClient; let _tableConfigs: { [tableName: string]: InanoSQLTable; } = {}; let id: string; const key = (tableName: string, key: any): string => { return id + "." + tableName + "." + key; } const maybeMapIndex = (table: string, index: any[]): any[] => { if (_tableConfigs[table].isPkNum) return index.map(i => parseFloat(i)); return index; } const getTableIndex = (table: string, complete: (index: any[]) => void, error: (err: any) => void) => { _db.zrangebyscore(key("_index_", table), "-inf", "+inf", (err, result) => { if (err) { error(err); return; } complete(maybeMapIndex(table, result)); }); } const readZIndex = (table: string, type: "range" | "offset" | "all", offsetOrLow: any, limitOrHigh: any, reverse: boolean, complete: (index: any[]) => void, error: (err: any) => void): void => { switch (type) { case "offset": if (reverse) { _db.zrevrange(key("_index_", table), offsetOrLow + 1, offsetOrLow + limitOrHigh, (err, results) => { if (err) { error(err); return; } complete(results); }); } else { _db.zrange(key("_index_", table), offsetOrLow, offsetOrLow + limitOrHigh - 1, (err, results) => { if (err) { error(err); return; } complete(results); }); } break; case "all": getTableIndex(table, (index) => { if (reverse) { complete(index.reverse()); } else { complete(index); } }, error); break; case "range": if (_tableConfigs[table].isPkNum) { _db.zrangebyscore(key("_index_", table), offsetOrLow, limitOrHigh, (err, result) => { if (err) { error(err); return; } complete(reverse ? result.reverse() : result); }); } else { _db.zrangebylex(key("_index_", table), "[" + offsetOrLow, "[" + limitOrHigh, (err, result) => { if (err) { error(err); return; } complete(reverse ? result.reverse() : result); }); } break; } } return { name: "Redis Index", version: 2.04, filters: [ { name: "adapterConnect", priority: 1000, call: (inputArgs: adapterConnectFilter, complete: (args: adapterConnectFilter) => void, cancel: (info: any) => void) => { id = inputArgs.res.id; _db = redis.createClient(connectArgs); _db.on("ready", () => { if (getClient) { getClient(_db); } complete(inputArgs); }); _db.on("error", cancel); } }, { name: "adapterCreateIndex", priority: 1000, call: (inputArgs: adapterCreateIndexFilter, complete: (args: any) => void, cancel: (info: any) => void) => { complete(false); if (!inputArgs) { cancel("Query taken over by another plugin!"); return; } const indexName = `_idx_${inputArgs.res.table}_${inputArgs.res.indexName}`; _tableConfigs[indexName] = { ...blankTableDefinition, pkType: inputArgs.res.type, pkCol: ["id"], isPkNum: ["float", "int", "number"].indexOf(inputArgs.res.type) !== -1 }; inputArgs.res.complete(); } }, { name: "adapterDeleteIndex", priority: 1000, call: (inputArgs: adapterDeleteIndexFilter, complete: (args: any) => void, cancel: (info: any) => void) => { complete(false); if (!inputArgs) { cancel("Query taken over by another plugin!"); return; } const indexName = `_idx_${inputArgs.res.table}_${inputArgs.res.indexName}`; let ptr = "0"; const getNextPage = () => { _db.zscan(key("_index_", indexName), ptr, (err, result) => { if (err) { inputArgs.res.error(err); return; } if (!result[1].length && result[0] !== "0") { ptr = result[0]; getNextPage(); return; } const PKS = (result[1] || []).filter((v, i) => i % 2 === 0); chainAsync(PKS, (pk, i, next, err) => { // clear table contents _db.del(key(indexName, pk), (delErr) => { if (delErr) { err(delErr); return; } next(); }) }).then(() => { if (result[0] === "0") { // done reading index, delete it _db.del(key("_index_", indexName), (delErr) => { if (delErr) { inputArgs.res.error(delErr); return; } inputArgs.res.complete(); }); } else { ptr = result[0]; getNextPage(); } }).catch(inputArgs.res.error); }); } getNextPage(); } }, { name: "adapterAddIndexValue", priority: 1000, call: (inputArgs: adapterAddIndexValueFilter, complete: (args: any) => void, cancel: (info: any) => void) => { complete(false); if (!inputArgs) { cancel("Query taken over by another plugin!"); return; } const indexName = `_idx_${inputArgs.res.table}_${inputArgs.res.indexName}`; // key = rowID // value = indexKey return allAsync(["_index_", "_table_"], (item, i, next, err) => { switch (item) { case "_index_": // update index _db.zadd(key("_index_", indexName), _tableConfigs[indexName].isPkNum ? parseFloat(inputArgs.res.value) : 0, inputArgs.res.value, (error) => { if (error) { err(error); return; } next(); }); break; case "_table_": // update row value const rowID = inputArgs.res.key; const isNum = typeof rowID === "number"; _db.zadd(key(indexName, inputArgs.res.value), 0, (isNum ? "num:" : "") + rowID, (error, result) => { if (error) { err(error); return; } next(); }); break; } }).then(inputArgs.res.complete).catch(inputArgs.res.error); } }, { name: "adapterDeleteIndexValue", priority: 1000, call: (inputArgs: adapterDeleteIndexValueFilter, complete: (args: any) => void, cancel: (info: any) => void) => { complete(false); if (!inputArgs) { cancel("Query taken over by another plugin!"); return; } const indexName = `_idx_${inputArgs.res.table}_${inputArgs.res.indexName}`; // key = rowID // value = indexKey const rowID = inputArgs.res.key; const isNum = typeof rowID === "number"; _db.zrem(key(indexName, inputArgs.res.value), (isNum ? "num:" : "") + rowID, (err, result) => { if (err) { inputArgs.res.error(err); return; } inputArgs.res.complete(); }); } }, { name: "adapterReadIndexKey", priority: 1000, call: (inputArgs: adapterReadIndexKeyFilter, complete: (args: any) => void, cancel: (info: any) => void) => { complete(false); if (!inputArgs) { cancel("Query taken over by another plugin!"); return; } const indexName = `_idx_${inputArgs.res.table}_${inputArgs.res.indexName}`; _db.zrangebylex(key(indexName, inputArgs.res.pk), "-", "+", (err, result) => { if (err) { inputArgs.res.error(err); return; } if (!result) { inputArgs.res.complete(); return; } result.forEach((value, i) => { inputArgs.res.onRowPK(value.indexOf("num:") === 0 ? parseFloat(value.replace("num:", "")) : value); }) inputArgs.res.complete(); }) } }, { name: "adapterReadIndexKeys", priority: 1000, call: (inputArgs: adapterReadIndexKeysFilter, complete: (args: any) => void, cancel: (info: any) => void) => { complete(false); if (!inputArgs) { cancel("Query taken over by another plugin!"); return; } const indexName = `_idx_${inputArgs.res.table}_${inputArgs.res.indexName}`; readZIndex(indexName, inputArgs.res.type, inputArgs.res.offsetOrLow, inputArgs.res.limitOrHigh, inputArgs.res.reverse, (primaryKeys) => { chainAsync(primaryKeys, (indexKey, i, pkNext, pkErr) => { _db.zrangebylex(key(indexName, indexKey), "-", "+", (err, result) => { if (err) { inputArgs.res.error(err); return; } if (!result) { pkNext(); return; } result.forEach((value, i) => { inputArgs.res.onRowPK(value.indexOf("num:") === 0 ? parseFloat(value.replace("num:", "")) : value, i); }) pkNext(); }) }).then(() => { inputArgs.res.complete(); }) }, inputArgs.res.error); } } ] } }
the_stack
// The MIT License (MIT) // // vs-deploy (https://github.com/mkloubert/vs-deploy) // Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER import * as deploy_contracts from './contracts'; import * as deploy_helpers from './helpers'; import * as deploy_values from './values'; import * as deploy_workspace from './workspace'; import * as FS from 'fs'; import * as i18 from './i18'; import * as Path from 'path'; const MergeDeep = require('merge-deep'); import * as OS from 'os'; import * as vs_deploy from './deploy'; import * as vscode from 'vscode'; import * as Workflows from 'node-workflows'; let buildTaskTimer: NodeJS.Timer; let gitPullTimer: NodeJS.Timer; /** * Returns a merged config object. * * @param {deploy_contracts.DeployConfiguration} cfg The base object. * * @returns {Promise<deploy_contracts.DeployConfiguration>} The promise. */ export function mergeConfig(cfg: deploy_contracts.DeployConfiguration): Promise<deploy_contracts.DeployConfiguration> { let values = deploy_values.getBuildInValues(); values = values.concat(deploy_values.toValueObjects(cfg.values)); let myName: string; if (cfg) { myName = cfg.name; } if (deploy_helpers.isEmptyString(myName)) { myName = OS.hostname(); } myName = deploy_helpers.normalizeString(myName); return new Promise<deploy_contracts.DeployConfiguration>((resolve, reject) => { let completed = (err: any, c?: deploy_contracts.DeployConfiguration) => { if (err) { reject(err); } else { let result = c || cfg; if (result) { try { delete result['imports']; } catch (e) { deploy_helpers.log(i18.t('errors.withCategory', 'config.mergeConfig(1)', e)); } } try { result = deploy_helpers.cloneObject(result); } catch (e) { deploy_helpers.log(i18.t('errors.withCategory', 'config.mergeConfig(2)', e)); } resolve(result); } }; try { if (cfg) { let wf = Workflows.create(); // normalize list // by keeping sure to have // import entry objects let allImports = deploy_helpers.asArray(cfg.imports).filter(x => x).map(imp => { if ('object' !== typeof imp) { // convert to object imp = { from: deploy_helpers.toStringSafe(imp), }; } return imp; }); // isFor allImports = allImports.filter(imp => { let validHosts = deploy_helpers.asArray(imp.isFor) .map(x => deploy_helpers.normalizeString(x)) .filter(x => '' !== x); if (validHosts.length < 1) { return true; } return validHosts.indexOf(myName) > -1; }); // platforms allImports = deploy_helpers.filterPlatformItems(allImports); // if allImports = deploy_helpers.filterConditionalItems(allImports, values); // sort allImports = allImports.sort((x, y) => { return deploy_helpers.compareValuesBy(x, y, t => deploy_helpers.getSortValue(t, () => myName)); }); // build workflow actions for each import entry allImports.filter(x => x).forEach(imp => { wf.next((ctx) => { let c: deploy_contracts.DeployConfiguration = ctx.value; return new Promise<any>((res, rej) => { try { // get file path let src = deploy_helpers.toStringSafe(imp.from); src = deploy_values.replaceWithValues(values, src); if (!Path.isAbsolute(src)) { src = Path.join(deploy_workspace.getRootPath(), '.vscode', src); } src = Path.resolve(src); let loadImportFile = () => { FS.readFile(src, (err, data) => { if (err) { rej(err); } else { try { if (data && data.length > 0) { let childCfg: deploy_contracts.DeployConfiguration = JSON.parse(data.toString('utf8')); if (childCfg) { mergeConfig(childCfg).then((cc) => { try { if (cc) { let newCfg = cc; if (deploy_helpers.toBooleanSafe(imp.merge, true)) { newCfg = MergeDeep({}, c, cc); } cc = newCfg; } ctx.value = deploy_helpers.cloneObject(cc); res(); } catch (e) { rej(e); // update error } }).catch((err) => { rej(err); }); } else { res(); // empty => no update } } else { res(); // no data } } catch (e) { res(e); // JSON error } } }); }; if ('' !== src.trim()) { // first check if file exists FS.exists(src, (exists) => { if (exists) { loadImportFile(); } else { res(); // files does no exist } }); } else { res(); // no file defined } } catch (e) { rej(e); } }); }); }); wf.on('action.after', (err, ctx) => { if (!err) { ctx.result = ctx.value; // update result } }); wf.start(cfg).then((newCfg) => { completed(null, newCfg || cfg); }).catch((err) => { completed(err); }); } else { completed(null); } } catch (e) { completed(e); } }); } /** * Runs the build task, if defined in config. */ export function runBuildTask() { let me: vs_deploy.Deployer = this; let cfg = me.config; // close old timer (if defined) try { let btt = buildTaskTimer; if (btt) { clearTimeout(btt); } } catch (e) { me.log(i18.t('errors.withCategory', 'config.runBuildTask(1)', e)); } finally { buildTaskTimer = null; } let doRun = false; let timeToWait: number; if (!deploy_helpers.isNullOrUndefined(cfg.runBuildTaskOnStartup)) { if ('boolean' === typeof cfg.runBuildTaskOnStartup) { doRun = cfg.runBuildTaskOnStartup; } else { doRun = true; timeToWait = parseInt(deploy_helpers.toStringSafe(cfg.runBuildTaskOnStartup)); } } let executeBuildTaskCommand = () => { vscode.commands.executeCommand('workbench.action.tasks.build').then(() => { }, (err) => { me.log(i18.t('errors.withCategory', 'config.runBuildTask(2)', err)); }); }; if (doRun) { if (isNaN(timeToWait)) { executeBuildTaskCommand(); } else { buildTaskTimer = setTimeout(() => { executeBuildTaskCommand(); }, timeToWait); } } } /** * Runs the git sync, if defined in config. * * @return {Promise<any>} The promise. */ export function runGitPull(): Promise<any> { let me: vs_deploy.Deployer = this; let cfg = me.config; return new Promise<any>((resolve, reject) => { try { // close old timer (if defined) try { let gst = gitPullTimer; if (gst) { clearTimeout(gst); } } catch (e) { me.log(i18.t('errors.withCategory', 'config.runGitPull(1)', e)); } finally { gitPullTimer = null; } let doRun = false; let timeToWait: number; if (!deploy_helpers.isNullOrUndefined(cfg.runGitPullOnStartup)) { if ('boolean' === typeof cfg.runGitPullOnStartup) { doRun = cfg.runGitPullOnStartup; } else { doRun = true; timeToWait = parseInt(deploy_helpers.toStringSafe(cfg.runGitPullOnStartup)); } } let executeGitSyncCommand = () => { vscode.commands.executeCommand('git.pull').then(() => { resolve(); }, (err) => { reject(err); }); }; if (doRun) { if (isNaN(timeToWait)) { executeGitSyncCommand(); } else { gitPullTimer = setTimeout(() => { executeGitSyncCommand(); }, timeToWait); } } else { resolve(); } } catch (e) { reject(e); } }); }
the_stack
// bundled version of @reach/dialog // their latest release doesn't allow react v18 for now import * as react from "react"; import * as reactDom from "react-dom"; function _extends$1() { _extends = Object.assign || function (target) { for (let i = 1; i < arguments.length; i++) { const source = arguments[i]; for (const key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function createCommonjsModule(fn, basedir, module) { return ( (module = { path: basedir, exports: {}, require: function (path, base) { return commonjsRequire( path, base === undefined || base === null ? module.path : base, ); }, }), fn(module, module.exports), module.exports ); } function commonjsRequire() { throw new Error( "Dynamic requires are not currently supported by @rollup/plugin-commonjs", ); } /* VITE PROCESS POLYFILL (based on https://github.com/calvinmetcalf/node-process-es6) */ function defaultSetTimout() { throw new Error("setTimeout has not been defined"); } function defaultClearTimeout() { throw new Error("clearTimeout has not been defined"); } let cachedSetTimeout = defaultSetTimout; let cachedClearTimeout = defaultClearTimeout; let globalContext; if (typeof window !== "undefined") { globalContext = window; } else if (typeof self !== "undefined") { globalContext = self; } else { globalContext = {}; } if (typeof globalContext.setTimeout === "function") { cachedSetTimeout = setTimeout; } if (typeof globalContext.clearTimeout === "function") { cachedClearTimeout = clearTimeout; } function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ( (cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout ) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ( (cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout ) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } let queue = []; let draining = false; let currentQueue; let queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } const timeout = runTimeout(cleanUpNextTick); draining = true; let len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } function nextTick(fun) { const args = new Array(arguments.length - 1); if (arguments.length > 1) { for (let i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; const title = "browser"; const platform = "browser"; const browser = true; const argv = []; const version = ""; // empty string to avoid regexp issues const versions = {}; const release = {}; const config = {}; function noop() {} const on = noop; const addListener = noop; const once = noop; const off = noop; const removeListener = noop; const removeAllListeners = noop; const emit = noop; function binding(name) { throw new Error("process.binding is not supported"); } function cwd() { return "/"; } function chdir(dir) { throw new Error("process.chdir is not supported"); } function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js const performance = globalContext.performance || {}; const performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { return new Date().getTime(); }; // generate timestamp or delta // see http://nodejs.org/api/process.html#process_process_hrtime function hrtime(previousTimestamp) { const clocktime = performanceNow.call(performance) * 1e-3; let seconds = Math.floor(clocktime); let nanoseconds = Math.floor((clocktime % 1) * 1e9); if (previousTimestamp) { seconds = seconds - previousTimestamp[0]; nanoseconds = nanoseconds - previousTimestamp[1]; if (nanoseconds < 0) { seconds--; nanoseconds += 1e9; } } return [seconds, nanoseconds]; } const startTime = new Date(); function uptime() { const currentTime = new Date(); const dif = currentTime - startTime; return dif / 1000; } const process = { nextTick: nextTick, title: title, browser: browser, env: { NODE_ENV: "development" }, argv: argv, version: version, versions: versions, on: on, addListener: addListener, once: once, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, emit: emit, binding: binding, cwd: cwd, chdir: chdir, umask: umask, hrtime: hrtime, platform: platform, release: release, config: config, uptime: uptime, }; const objectAssign = function (target, source) { let from; const to = toObject(target); let symbols; for (let s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (const key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (let i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /* eslint-disable no-restricted-globals, eqeqeq */ /** * React currently throws a warning when using useLayoutEffect on the server. * To get around it, we can conditionally useEffect on the server (no-op) and * useLayoutEffect in the browser. We occasionally need useLayoutEffect to * ensure we don't get a render flash for certain operations, but we may also * need affected components to render on the server. One example is when setting * a component's descendants to retrieve their index values. * * Important to note that using this hook as an escape hatch will break the * eslint dependency warnings unless you rename the import to `useLayoutEffect`. * Use sparingly only when the effect won't effect the rendered HTML to avoid * any server/client mismatch. * * If a useLayoutEffect is needed and the result would create a mismatch, it's * likely that the component in question shouldn't be rendered on the server at * all, so a better approach would be to lazily render those in a parent * component after client-side hydration. * * TODO: We are calling useLayoutEffect in a couple of places that will likely * cause some issues for SSR users, whether the warning shows or not. Audit and * fix these. * * https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85 * https://github.com/reduxjs/react-redux/blob/master/src/utils/useIsomorphicLayoutEffect.js * * @param effect * @param deps */ const useIsomorphicLayoutEffect = /*#__PURE__*/ canUseDOM() ? react.useLayoutEffect : react.useEffect; const checkedPkgs = {}; /** * When in dev mode, checks that styles for a given @reach package are loaded. * * @param packageName Name of the package to check. * @example checkStyles("dialog") will check for styles for @reach/dialog */ let checkStyles = noop; { // In CJS files, "development" is stripped from our build, but we need // it to prevent style checks from clogging up user logs while testing. // This is a workaround until we can tweak the build a bit to accommodate. const _ref$1 = typeof process !== "undefined" ? process : { env: { NODE_ENV: "development", }, }, env = _ref$1.env; checkStyles = function checkStyles(packageName) { // only check once per package if (checkedPkgs[packageName]) return; checkedPkgs[packageName] = true; if ( env.NODE_ENV !== "test" && parseInt( window .getComputedStyle(document.body) .getPropertyValue("--reach-" + packageName), 10, ) !== 1 ) { console.warn( "@reach/" + packageName + ' styles not found. If you are using a bundler like webpack or parcel include this in the entry file of your app before any of your own styles:\n\n import "@reach/' + packageName + '/styles.css";\n\n Otherwise you\'ll need to include them some other way:\n\n <link rel="stylesheet" type="text/css" href="node_modules/@reach/' + packageName + '/styles.css" />\n\n For more information visit https://ui.reach.tech/styling.\n ', ); } }; } /** * Passes or assigns an arbitrary value to a ref function or object. * * @param ref * @param value */ function assignRef$1(ref, value) { if (ref == null) return; if (isFunction(ref)) { ref(value); } else { try { ref.current = value; } catch (error) { throw new Error( 'Cannot assign value "' + value + '" to ref "' + ref + '"', ); } } } function canUseDOM() { return !!( typeof window !== "undefined" && window.document && window.document.createElement ); } /** * This is a hack for sure. The thing is, getting a component to intelligently * infer props based on a component or JSX string passed into an `as` prop is * kind of a huge pain. Getting it to work and satisfy the constraints of * `forwardRef` seems dang near impossible. To avoid needing to do this awkward * type song-and-dance every time we want to forward a ref into a component * that accepts an `as` prop, we abstract all of that mess to this function for * the time time being. */ function forwardRefWithAs(render) { return /*#__PURE__*/ react.forwardRef(render); } /** * Get an element's owner document. Useful when components are used in iframes * or other environments like dev tools. * * @param element */ function getOwnerDocument(element) { return canUseDOM() ? (element ? element.ownerDocument : document) : null; } /** * Checks whether or not a value is a function. * * @param value */ function isFunction(value) { return !!(value && {}.toString.call(value) == "[object Function]"); } /** * Checks whether or not a value is a string. * * @param value */ function isString(value) { return typeof value === "string"; } /** * No-op function. */ let useCheckStyles = noop; { useCheckStyles = function useCheckStyles(pkg) { const name = react.useRef(pkg); react.useEffect( function () { return void (name.current = pkg); }, [pkg], ); react.useEffect(function () { return checkStyles(name.current); }, []); }; } /** * Forces a re-render, similar to `forceUpdate` in class components. */ function useForceUpdate() { const _React$useState2 = react.useState(Object.create(null)), dispatch = _React$useState2[1]; return react.useCallback(function () { dispatch(Object.create(null)); }, []); } /** * Passes or assigns a value to multiple refs (typically a DOM node). Useful for * dealing with components that need an explicit ref for DOM calculations but * also forwards refs assigned by an app. * * @param refs Refs to fork */ function useForkedRef() { for ( var _len4 = arguments.length, refs = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++ ) { refs[_key4] = arguments[_key4]; } return react.useMemo(function () { if ( refs.every(function (ref) { return ref == null; }) ) { return null; } return function (node) { refs.forEach(function (ref) { assignRef$1(ref, node); }); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [].concat(refs)); } /** * Wraps a lib-defined event handler and a user-defined event handler, returning * a single handler that allows a user to prevent lib-defined handlers from * firing. * * @param theirHandler User-supplied event handler * @param ourHandler Library-supplied event handler */ function wrapEvent(theirHandler, ourHandler) { return function (event) { theirHandler && theirHandler(event); if (!event.defaultPrevented) { return ourHandler(event); } }; } // Export types /** * Welcome to @reach/portal! * * Creates and appends a DOM node to the end of `document.body` and renders a * React tree into it. Useful for rendering a natural React element hierarchy * with a different DOM hierarchy to prevent parent styles from clipping or * hiding content (for popovers, dropdowns, and modals). * * @see Docs https://reach.tech/portal * @see Source https://github.com/reach/reach-ui/tree/main/packages/portal * @see React https://reactjs.org/docs/portals.html */ /** * Portal * * @see Docs https://reach.tech/portal#portal */ const Portal = function Portal(_ref) { const children = _ref.children, _ref$type = _ref.type, type = _ref$type === void 0 ? "reach-portal" : _ref$type; const mountNode = react.useRef(null); const portalNode = react.useRef(null); const forceUpdate = useForceUpdate(); useIsomorphicLayoutEffect( function () { // This ref may be null when a hot-loader replaces components on the page if (!mountNode.current) return; // It's possible that the content of the portal has, itself, been portaled. // In that case, it's important to append to the correct document element. const ownerDocument = mountNode.current.ownerDocument; portalNode.current = ownerDocument == null ? void 0 : ownerDocument.createElement(type); ownerDocument.body.appendChild(portalNode.current); forceUpdate(); return function () { if (portalNode.current && portalNode.current.ownerDocument) { portalNode.current.ownerDocument.body.removeChild(portalNode.current); } }; }, [type, forceUpdate], ); return portalNode.current ? /*#__PURE__*/ reactDom.createPortal(children, portalNode.current) : /*#__PURE__*/ react.createElement("span", { ref: mountNode, }); }; /** * @see Docs https://reach.tech/portal#portal-props */ { Portal.displayName = "Portal"; } //////////////////////////////////////////////////////////////////////////////// function _objectWithoutPropertiesLoose$1(source, excluded) { if (source == null) return {}; const target = {}; const sourceKeys = Object.keys(source); let key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } const reactIs_development = createCommonjsModule(function (module, exports) { { (function () { // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. const hasSymbol = typeof Symbol === "function" && Symbol.for; const REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 0xeac7; const REACT_PORTAL_TYPE = hasSymbol ? Symbol.for("react.portal") : 0xeaca; const REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for("react.fragment") : 0xeacb; const REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for("react.strict_mode") : 0xeacc; const REACT_PROFILER_TYPE = hasSymbol ? Symbol.for("react.profiler") : 0xead2; const REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for("react.provider") : 0xeacd; const REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary // (unstable) APIs that have been removed. Can we remove the symbols? const REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for("react.async_mode") : 0xeacf; const REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for("react.concurrent_mode") : 0xeacf; const REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for("react.forward_ref") : 0xead0; const REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 0xead1; const REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for("react.suspense_list") : 0xead8; const REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 0xead3; const REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 0xead4; const REACT_BLOCK_TYPE = hasSymbol ? Symbol.for("react.block") : 0xead9; const REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for("react.fundamental") : 0xead5; const REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for("react.responder") : 0xead6; const REACT_SCOPE_TYPE = hasSymbol ? Symbol.for("react.scope") : 0xead7; function isValidElementType(type) { return ( typeof type === "string" || typeof type === "function" || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || (typeof type === "object" && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE)) ); } function typeOf(object) { if (typeof object === "object" && object !== null) { const $$typeof = object.$$typeof; switch ($$typeof) { case REACT_ELEMENT_TYPE: var type = object.type; switch (type) { case REACT_ASYNC_MODE_TYPE: case REACT_CONCURRENT_MODE_TYPE: case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: case REACT_SUSPENSE_TYPE: return type; default: var $$typeofType = type && type.$$typeof; switch ($$typeofType) { case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_LAZY_TYPE: case REACT_MEMO_TYPE: case REACT_PROVIDER_TYPE: return $$typeofType; default: return $$typeof; } } case REACT_PORTAL_TYPE: return $$typeof; } } return undefined; } // AsyncMode is deprecated along with isAsyncMode const AsyncMode = REACT_ASYNC_MODE_TYPE; const ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; const ContextConsumer = REACT_CONTEXT_TYPE; const ContextProvider = REACT_PROVIDER_TYPE; const Element = REACT_ELEMENT_TYPE; const ForwardRef = REACT_FORWARD_REF_TYPE; const Fragment = REACT_FRAGMENT_TYPE; const Lazy = REACT_LAZY_TYPE; const Memo = REACT_MEMO_TYPE; const Portal = REACT_PORTAL_TYPE; const Profiler = REACT_PROFILER_TYPE; const StrictMode = REACT_STRICT_MODE_TYPE; const Suspense = REACT_SUSPENSE_TYPE; let hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated function isAsyncMode(object) { { if (!hasWarnedAboutDeprecatedIsAsyncMode) { hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint console["warn"]( "The ReactIs.isAsyncMode() alias has been deprecated, " + "and will be removed in React 17+. Update your code to use " + "ReactIs.isConcurrentMode() instead. It has the exact same API.", ); } } return ( isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE ); } function isConcurrentMode(object) { return typeOf(object) === REACT_CONCURRENT_MODE_TYPE; } function isContextConsumer(object) { return typeOf(object) === REACT_CONTEXT_TYPE; } function isContextProvider(object) { return typeOf(object) === REACT_PROVIDER_TYPE; } function isElement(object) { return ( typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE ); } function isForwardRef(object) { return typeOf(object) === REACT_FORWARD_REF_TYPE; } function isFragment(object) { return typeOf(object) === REACT_FRAGMENT_TYPE; } function isLazy(object) { return typeOf(object) === REACT_LAZY_TYPE; } function isMemo(object) { return typeOf(object) === REACT_MEMO_TYPE; } function isPortal(object) { return typeOf(object) === REACT_PORTAL_TYPE; } function isProfiler(object) { return typeOf(object) === REACT_PROFILER_TYPE; } function isStrictMode(object) { return typeOf(object) === REACT_STRICT_MODE_TYPE; } function isSuspense(object) { return typeOf(object) === REACT_SUSPENSE_TYPE; } exports.AsyncMode = AsyncMode; exports.ConcurrentMode = ConcurrentMode; exports.ContextConsumer = ContextConsumer; exports.ContextProvider = ContextProvider; exports.Element = Element; exports.ForwardRef = ForwardRef; exports.Fragment = Fragment; exports.Lazy = Lazy; exports.Memo = Memo; exports.Portal = Portal; exports.Profiler = Profiler; exports.StrictMode = StrictMode; exports.Suspense = Suspense; exports.isAsyncMode = isAsyncMode; exports.isConcurrentMode = isConcurrentMode; exports.isContextConsumer = isContextConsumer; exports.isContextProvider = isContextProvider; exports.isElement = isElement; exports.isForwardRef = isForwardRef; exports.isFragment = isFragment; exports.isLazy = isLazy; exports.isMemo = isMemo; exports.isPortal = isPortal; exports.isProfiler = isProfiler; exports.isStrictMode = isStrictMode; exports.isSuspense = isSuspense; exports.isValidElementType = isValidElementType; exports.typeOf = typeOf; })(); } }); const reactIs = createCommonjsModule(function (module) { { module.exports = reactIs_development; } }); /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const ReactPropTypesSecret$1 = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"; const ReactPropTypesSecret_1 = ReactPropTypesSecret$1; let printWarning$1 = function () {}; { var ReactPropTypesSecret = ReactPropTypesSecret_1; var loggedTypeFailures = {}; var has$1 = Function.call.bind(Object.prototype.hasOwnProperty); printWarning$1 = function (text) { const message = "Warning: " + text; if (typeof console !== "undefined") { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { { for (const typeSpecName in typeSpecs) { if (has$1(typeSpecs, typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== "function") { const err = Error( (componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; " + "it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.", ); err.name = "Invariant Violation"; throw err; } error = typeSpecs[typeSpecName]( values, typeSpecName, componentName, location, null, ReactPropTypesSecret, ); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning$1( (componentName || "React class") + ": type specification of " + location + " `" + typeSpecName + "` is invalid; the type checker " + "function must return `null` or an `Error` but returned a " + typeof error + ". " + "You may have forgotten to pass an argument to the type checker " + "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + "shape all require an argument).", ); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; const stack = getStack ? getStack() : ""; printWarning$1( "Failed " + location + " type: " + error.message + (stack != null ? stack : ""), ); } } } } } /** * Resets warning cache when testing. * * @private */ checkPropTypes.resetWarningCache = function () { { loggedTypeFailures = {}; } }; const checkPropTypes_1 = checkPropTypes; const has = Function.call.bind(Object.prototype.hasOwnProperty); let printWarning = function () {}; { printWarning = function (text) { const message = "Warning: " + text; if (typeof console !== "undefined") { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; } function emptyFunctionThatReturnsNull() { return null; } const factoryWithTypeCheckers = function (isValidElement, throwOnDirectAccess) { /* global Symbol */ const ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; const FAUX_ITERATOR_SYMBOL = "@@iterator"; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { const iteratorFn = maybeIterable && ((ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL]) || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === "function") { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ const ANONYMOUS = "<<anonymous>>"; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. const ReactPropTypes = { array: createPrimitiveTypeChecker("array"), bool: createPrimitiveTypeChecker("boolean"), func: createPrimitiveTypeChecker("function"), number: createPrimitiveTypeChecker("number"), object: createPrimitiveTypeChecker("object"), string: createPrimitiveTypeChecker("string"), symbol: createPrimitiveTypeChecker("symbol"), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), elementType: createElementTypeTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, exact: createStrictShapeTypeChecker, }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ""; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType( isRequired, props, propName, componentName, location, propFullName, secret, ) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret_1) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package const err = new Error( "Calling PropTypes validators directly is not supported by the `prop-types` package. " + "Use `PropTypes.checkPropTypes()` to call them. " + "Read more at http://fb.me/use-check-prop-types", ); err.name = "Invariant Violation"; throw err; } else if (typeof console !== "undefined") { // Old behavior for people using React.PropTypes const cacheKey = componentName + ":" + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { printWarning( "You are manually calling a React.PropTypes validation " + "function for the `" + propFullName + "` prop on `" + componentName + "`. This is deprecated " + "and will throw in the standalone `prop-types` package. " + "You may be seeing this warning due to a third-party PropTypes " + "library. See https://fb.me/react-warning-dont-call-proptypes " + "for details.", ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError( "The " + location + " `" + propFullName + "` is marked as required " + ("in `" + componentName + "`, but its value is `null`."), ); } return new PropTypeError( "The " + location + " `" + propFullName + "` is marked as required in " + ("`" + componentName + "`, but its value is `undefined`."), ); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } const chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate( props, propName, componentName, location, propFullName, secret, ) { const propValue = props[propName]; const propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. const preciseType = getPreciseType(propValue); return new PropTypeError( "Invalid " + location + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`."), ); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunctionThatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== "function") { return new PropTypeError( "Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf.", ); } const propValue = props[propName]; if (!Array.isArray(propValue)) { const propType = getPropType(propValue); return new PropTypeError( "Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array."), ); } for (let i = 0; i < propValue.length; i++) { const error = typeChecker( propValue, i, componentName, location, propFullName + "[" + i + "]", ReactPropTypesSecret_1, ); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { const propValue = props[propName]; if (!isValidElement(propValue)) { const propType = getPropType(propValue); return new PropTypeError( "Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement."), ); } return null; } return createChainableTypeChecker(validate); } function createElementTypeTypeChecker() { function validate(props, propName, componentName, location, propFullName) { const propValue = props[propName]; if (!reactIs.isValidElementType(propValue)) { const propType = getPropType(propValue); return new PropTypeError( "Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement type."), ); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { const expectedClassName = expectedClass.name || ANONYMOUS; const actualClassName = getClassName(props[propName]); return new PropTypeError( "Invalid " + location + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`."), ); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { { if (arguments.length > 1) { printWarning( "Invalid arguments supplied to oneOf, expected an array, got " + arguments.length + " arguments. " + "A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).", ); } else { printWarning( "Invalid argument supplied to oneOf, expected an array.", ); } } return emptyFunctionThatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { const propValue = props[propName]; for (let i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } const valuesString = JSON.stringify( expectedValues, function replacer(key, value) { const type = getPreciseType(value); if (type === "symbol") { return String(value); } return value; }, ); return new PropTypeError( "Invalid " + location + " `" + propFullName + "` of value `" + String(propValue) + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + "."), ); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== "function") { return new PropTypeError( "Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf.", ); } const propValue = props[propName]; const propType = getPropType(propValue); if (propType !== "object") { return new PropTypeError( "Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an object."), ); } for (const key in propValue) { if (has(propValue, key)) { const error = typeChecker( propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret_1, ); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { printWarning( "Invalid argument supplied to oneOfType, expected an instance of array.", ); return emptyFunctionThatReturnsNull; } for (let i = 0; i < arrayOfTypeCheckers.length; i++) { const checker = arrayOfTypeCheckers[i]; if (typeof checker !== "function") { printWarning( "Invalid argument supplied to oneOfType. Expected an array of check functions, but " + "received " + getPostfixForTypeWarning(checker) + " at index " + i + ".", ); return emptyFunctionThatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (let i = 0; i < arrayOfTypeCheckers.length; i++) { const checker = arrayOfTypeCheckers[i]; if ( checker( props, propName, componentName, location, propFullName, ReactPropTypesSecret_1, ) == null ) { return null; } } return new PropTypeError( "Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`."), ); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError( "Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode."), ); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { const propValue = props[propName]; const propType = getPropType(propValue); if (propType !== "object") { return new PropTypeError( "Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."), ); } for (const key in shapeTypes) { const checker = shapeTypes[key]; if (!checker) { continue; } const error = checker( propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret_1, ); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createStrictShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { const propValue = props[propName]; const propType = getPropType(propValue); if (propType !== "object") { return new PropTypeError( "Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."), ); } // We need to check all keys in case some are required but missing from // props. const allKeys = objectAssign({}, props[propName], shapeTypes); for (const key in allKeys) { const checker = shapeTypes[key]; if (!checker) { return new PropTypeError( "Invalid " + location + " `" + propFullName + "` key `" + key + "` supplied to `" + componentName + "`." + "\nBad object: " + JSON.stringify(props[propName], null, " ") + "\nValid keys: " + JSON.stringify(Object.keys(shapeTypes), null, " "), ); } const error = checker( propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret_1, ); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case "number": case "string": case "undefined": return true; case "boolean": return !propValue; case "object": if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { const iterator = iteratorFn.call(propValue); let step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { const entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === "symbol") { return true; } // falsy value can't be a Symbol if (!propValue) { return false; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue["@@toStringTag"] === "Symbol") { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === "function" && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { const propType = typeof propValue; if (Array.isArray(propValue)) { return "array"; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return "object"; } if (isSymbol(propType, propValue)) { return "symbol"; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === "undefined" || propValue === null) { return "" + propValue; } const propType = getPropType(propValue); if (propType === "object") { if (propValue instanceof Date) { return "date"; } else if (propValue instanceof RegExp) { return "regexp"; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { const type = getPreciseType(value); switch (type) { case "array": case "object": return "an " + type; case "boolean": case "date": case "regexp": return "a " + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes_1; ReactPropTypes.resetWarningCache = checkPropTypes_1.resetWarningCache; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; const propTypes$1 = createCommonjsModule(function (module) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ { const ReactIs = reactIs; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod const throwOnDirectAccess = true; module.exports = factoryWithTypeCheckers( ReactIs.isElement, throwOnDirectAccess, ); } }); const FOCUS_GROUP = "data-focus-lock"; const FOCUS_DISABLED = "data-focus-lock-disabled"; const FOCUS_ALLOW = "data-no-focus-lock"; const FOCUS_AUTO = "data-autofocus-inside"; /** * Assigns a value for a given ref, no matter of the ref format * @param {RefObject} ref - a callback function or ref object * @param value - a new value * * @see https://github.com/theKashey/use-callback-ref#assignref * @example * const refObject = useRef(); * const refFn = (ref) => {....} * * assignRef(refObject, "refValue"); * assignRef(refFn, "refValue"); */ function assignRef(ref, value) { if (typeof ref === "function") { ref(value); } else if (ref) { ref.current = value; } return ref; } /** * creates a MutableRef with ref change callback * @param initialValue - initial ref value * @param {Function} callback - a callback to run when value changes * * @example * const ref = useCallbackRef(0, (newValue, oldValue) => console.log(oldValue, '->', newValue); * ref.current = 1; * // prints 0 -> 1 * * @see https://reactjs.org/docs/hooks-reference.html#useref * @see https://github.com/theKashey/use-callback-ref#usecallbackref---to-replace-reactuseref * @returns {MutableRefObject} */ function useCallbackRef(initialValue, callback) { var ref = react.useState(function () { return { // value value: initialValue, // last callback callback: callback, // "memoized" public interface facade: { get current() { return ref.value; }, set current(value) { const last = ref.value; if (last !== value) { ref.value = value; ref.callback(value, last); } }, }, }; })[0]; // update callback ref.callback = callback; return ref.facade; } /** * Merges two or more refs together providing a single interface to set their value * @param {RefObject|Ref} refs * @returns {MutableRefObject} - a new ref, which translates all changes to {refs} * * @see {@link mergeRefs} a version without buit-in memoization * @see https://github.com/theKashey/use-callback-ref#usemergerefs * @example * const Component = React.forwardRef((props, ref) => { * const ownRef = useRef(); * const domRef = useMergeRefs([ref, ownRef]); // 👈 merge together * return <div ref={domRef}>...</div> * } */ function useMergeRefs(refs, defaultValue) { return useCallbackRef(defaultValue, function (newValue) { return refs.forEach(function (ref) { return assignRef(ref, newValue); }); }); } const hiddenGuard = { width: "1px", height: "0px", padding: 0, overflow: "hidden", position: "fixed", top: "1px", left: "1px", }; ({ children: propTypes$1.node, }); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign$1 = function () { __assign$1 = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (const p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign$1.apply(this, arguments); }; function __rest$1(s, e) { const t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if ( e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]) ) t[p[i]] = s[p[i]]; } return t; } function ItoI(a) { return a; } function innerCreateMedium(defaults, middleware) { if (middleware === void 0) { middleware = ItoI; } let buffer = []; let assigned = false; const medium = { read: function () { if (assigned) { throw new Error( "Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.", ); } if (buffer.length) { return buffer[buffer.length - 1]; } return defaults; }, useMedium: function (data) { const item = middleware(data, assigned); buffer.push(item); return function () { buffer = buffer.filter(function (x) { return x !== item; }); }; }, assignSyncMedium: function (cb) { assigned = true; while (buffer.length) { const cbs = buffer; buffer = []; cbs.forEach(cb); } buffer = { push: function (x) { return cb(x); }, filter: function () { return buffer; }, }; }, assignMedium: function (cb) { assigned = true; let pendingQueue = []; if (buffer.length) { const cbs = buffer; buffer = []; cbs.forEach(cb); pendingQueue = buffer; } const executeQueue = function () { const cbs = pendingQueue; pendingQueue = []; cbs.forEach(cb); }; const cycle = function () { return Promise.resolve().then(executeQueue); }; cycle(); buffer = { push: function (x) { pendingQueue.push(x); cycle(); }, filter: function (filter) { pendingQueue = pendingQueue.filter(filter); return buffer; }, }; }, }; return medium; } function createMedium(defaults, middleware) { if (middleware === void 0) { middleware = ItoI; } return innerCreateMedium(defaults, middleware); } function createSidecarMedium(options) { if (options === void 0) { options = {}; } const medium = innerCreateMedium(null); medium.options = __assign$1({ async: true, ssr: false }, options); return medium; } const SideCar$1 = function (_a) { const sideCar = _a.sideCar, rest = __rest$1(_a, ["sideCar"]); if (!sideCar) { throw new Error( "Sidecar: please provide `sideCar` property to import the right car", ); } const Target = sideCar.read(); if (!Target) { throw new Error("Sidecar medium not found"); } return react.createElement(Target, __assign$1({}, rest)); }; SideCar$1.isSideCarExport = true; function exportSidecar(medium, exported) { medium.useMedium(exported); return SideCar$1; } const mediumFocus = createMedium({}, function (_ref) { const target = _ref.target, currentTarget = _ref.currentTarget; return { target: target, currentTarget: currentTarget, }; }); const mediumBlur = createMedium(); const mediumEffect = createMedium(); const mediumSidecar = createSidecarMedium({ async: true, }); const emptyArray = []; const FocusLock = /*#__PURE__*/ react.forwardRef(function FocusLockUI( props, parentRef, ) { let _extends2; const _React$useState = react.useState(), realObserved = _React$useState[0], setObserved = _React$useState[1]; const observed = react.useRef(); const isActive = react.useRef(false); const originalFocusedElement = react.useRef(null); const children = props.children, disabled = props.disabled, noFocusGuards = props.noFocusGuards, persistentFocus = props.persistentFocus, crossFrame = props.crossFrame, autoFocus = props.autoFocus, allowTextSelection = props.allowTextSelection, group = props.group, className = props.className, whiteList = props.whiteList, _props$shards = props.shards, shards = _props$shards === void 0 ? emptyArray : _props$shards, _props$as = props.as, Container = _props$as === void 0 ? "div" : _props$as, _props$lockProps = props.lockProps, containerProps = _props$lockProps === void 0 ? {} : _props$lockProps, SideCar = props.sideCar, shouldReturnFocus = props.returnFocus, onActivationCallback = props.onActivation, onDeactivationCallback = props.onDeactivation; const _React$useState2 = react.useState({}), id = _React$useState2[0]; // SIDE EFFECT CALLBACKS const onActivation = react.useCallback( function () { originalFocusedElement.current = originalFocusedElement.current || (document && document.activeElement); if (observed.current && onActivationCallback) { onActivationCallback(observed.current); } isActive.current = true; }, [onActivationCallback], ); const onDeactivation = react.useCallback( function () { isActive.current = false; if (onDeactivationCallback) { onDeactivationCallback(observed.current); } }, [onDeactivationCallback], ); const returnFocus = react.useCallback( function (allowDefer) { const current = originalFocusedElement.current; if (Boolean(shouldReturnFocus) && current && current.focus) { const focusOptions = typeof shouldReturnFocus === "object" ? shouldReturnFocus : undefined; originalFocusedElement.current = null; if (allowDefer) { // React might return focus after update // it's safer to defer the action Promise.resolve().then(function () { return current.focus(focusOptions); }); } else { current.focus(focusOptions); } } }, [shouldReturnFocus], ); // MEDIUM CALLBACKS const onFocus = react.useCallback(function (event) { if (isActive.current) { mediumFocus.useMedium(event); } }, []); const onBlur = mediumBlur.useMedium; // REF PROPAGATION // not using real refs due to race conditions const setObserveNode = react.useCallback(function (newObserved) { if (observed.current !== newObserved) { observed.current = newObserved; setObserved(newObserved); } }, []); { if (typeof allowTextSelection !== "undefined") { // eslint-disable-next-line no-console console.warn( "React-Focus-Lock: allowTextSelection is deprecated and enabled by default", ); } react.useEffect(function () { if (!observed.current) { // eslint-disable-next-line no-console console.error("FocusLock: could not obtain ref to internal node"); } }, []); } const lockProps = _extends$1( ((_extends2 = {}), (_extends2[FOCUS_DISABLED] = disabled && "disabled"), (_extends2[FOCUS_GROUP] = group), _extends2), containerProps, ); const hasLeadingGuards = noFocusGuards !== true; const hasTailingGuards = hasLeadingGuards && noFocusGuards !== "tail"; const mergedRef = useMergeRefs([parentRef, setObserveNode]); return /*#__PURE__*/ react.createElement( react.Fragment, null, hasLeadingGuards && [ /*#__PURE__*/ react.createElement("div", { key: "guard-first", "data-focus-guard": true, tabIndex: disabled ? -1 : 0, style: hiddenGuard, }), /*#__PURE__*/ // nearest focus guard react.createElement("div", { key: "guard-nearest", "data-focus-guard": true, tabIndex: disabled ? -1 : 1, style: hiddenGuard, }), // first tabbed element guard ], !disabled && /*#__PURE__*/ react.createElement(SideCar, { id: id, sideCar: mediumSidecar, observed: realObserved, disabled: disabled, persistentFocus: persistentFocus, crossFrame: crossFrame, autoFocus: autoFocus, whiteList: whiteList, shards: shards, onActivation: onActivation, onDeactivation: onDeactivation, returnFocus: returnFocus, }), /*#__PURE__*/ react.createElement( Container, _extends$1( { ref: mergedRef, }, lockProps, { className: className, onBlur: onBlur, onFocus: onFocus, }, ), children, ), hasTailingGuards && /*#__PURE__*/ react.createElement("div", { "data-focus-guard": true, tabIndex: disabled ? -1 : 0, style: hiddenGuard, }), ); }); FocusLock.propTypes = { children: propTypes$1.node, disabled: propTypes$1.bool, returnFocus: propTypes$1.oneOfType([propTypes$1.bool, propTypes$1.object]), noFocusGuards: propTypes$1.bool, allowTextSelection: propTypes$1.bool, autoFocus: propTypes$1.bool, persistentFocus: propTypes$1.bool, crossFrame: propTypes$1.bool, group: propTypes$1.string, className: propTypes$1.string, whiteList: propTypes$1.func, shards: propTypes$1.arrayOf(propTypes$1.any), as: propTypes$1.oneOfType([ propTypes$1.string, propTypes$1.func, propTypes$1.object, ]), lockProps: propTypes$1.object, onActivation: propTypes$1.func, onDeactivation: propTypes$1.func, sideCar: propTypes$1.any.isRequired, }; FocusLock.defaultProps = { children: undefined, disabled: false, returnFocus: false, noFocusGuards: false, autoFocus: true, persistentFocus: false, crossFrame: true, allowTextSelection: undefined, group: undefined, className: undefined, whiteList: undefined, shards: undefined, as: "div", lockProps: {}, onActivation: undefined, onDeactivation: undefined, }; function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true, }); } else { obj[key] = value; } return obj; } function withSideEffect(reducePropsToState, handleStateChangeOnClient) { { if (typeof reducePropsToState !== "function") { throw new Error("Expected reducePropsToState to be a function."); } if (typeof handleStateChangeOnClient !== "function") { throw new Error("Expected handleStateChangeOnClient to be a function."); } } function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || "Component"; } return function wrap(WrappedComponent) { { if (typeof WrappedComponent !== "function") { throw new Error("Expected WrappedComponent to be a React component."); } } const mountedInstances = []; let state; function emitChange() { state = reducePropsToState( mountedInstances.map(function (instance) { return instance.props; }), ); handleStateChangeOnClient(state); } const SideEffect = /*#__PURE__*/ (function (_PureComponent) { _inheritsLoose(SideEffect, _PureComponent); function SideEffect() { return _PureComponent.apply(this, arguments) || this; } // Try to use displayName of wrapped component SideEffect.peek = function peek() { return state; }; const _proto = SideEffect.prototype; _proto.componentDidMount = function componentDidMount() { mountedInstances.push(this); emitChange(); }; _proto.componentDidUpdate = function componentDidUpdate() { emitChange(); }; _proto.componentWillUnmount = function componentWillUnmount() { const index = mountedInstances.indexOf(this); mountedInstances.splice(index, 1); emitChange(); }; _proto.render = function render() { return /*#__PURE__*/ react.createElement(WrappedComponent, this.props); }; return SideEffect; })(react.PureComponent); _defineProperty( SideEffect, "displayName", "SideEffect(" + getDisplayName(WrappedComponent) + ")", ); return SideEffect; }; } const toArray = function (a) { const ret = Array(a.length); for (let i = 0; i < a.length; ++i) { ret[i] = a[i]; } return ret; }; const asArray = function (a) { return Array.isArray(a) ? a : [a]; }; const filterNested = function (nodes) { const contained = new Set(); const l = nodes.length; for (let i = 0; i < l; i += 1) { for (let j = i + 1; j < l; j += 1) { const position = nodes[i].compareDocumentPosition(nodes[j]); if ((position & Node.DOCUMENT_POSITION_CONTAINED_BY) > 0) { contained.add(j); } if ((position & Node.DOCUMENT_POSITION_CONTAINS) > 0) { contained.add(i); } } } return nodes.filter(function (_, index) { return !contained.has(index); }); }; var getTopParent = function (node) { return node.parentNode ? getTopParent(node.parentNode) : node; }; const getAllAffectedNodes = function (node) { const nodes = asArray(node); return nodes.filter(Boolean).reduce(function (acc, currentNode) { const group = currentNode.getAttribute(FOCUS_GROUP); acc.push.apply( acc, group ? filterNested( toArray( getTopParent(currentNode).querySelectorAll( "[" + FOCUS_GROUP + '="' + group + '"]:not([' + FOCUS_DISABLED + '="disabled"])', ), ), ) : [currentNode], ); return acc; }, []); }; const isElementHidden = function (computedStyle) { if (!computedStyle || !computedStyle.getPropertyValue) { return false; } return ( computedStyle.getPropertyValue("display") === "none" || computedStyle.getPropertyValue("visibility") === "hidden" ); }; var isVisible = function (node) { return ( !node || node === document || (node && node.nodeType === Node.DOCUMENT_NODE) || (!isElementHidden(window.getComputedStyle(node, null)) && isVisible( node.parentNode && node.parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE ? node.parentNode.host : node.parentNode, )) ); }; const notHiddenInput = function (node) { return !( (node.tagName === "INPUT" || node.tagName === "BUTTON") && (node.type === "hidden" || node.disabled) ); }; const isGuard = function (node) { return Boolean(node && node.dataset && node.dataset.focusGuard); }; const isNotAGuard = function (node) { return !isGuard(node); }; const isDefined = function (x) { return Boolean(x); }; const tabSort = function (a, b) { const tabDiff = a.tabIndex - b.tabIndex; const indexDiff = a.index - b.index; if (tabDiff) { if (!a.tabIndex) { return 1; } if (!b.tabIndex) { return -1; } } return tabDiff || indexDiff; }; const orderByTabIndex = function (nodes, filterNegative, keepGuards) { return toArray(nodes) .map(function (node, index) { return { node: node, index: index, tabIndex: keepGuards && node.tabIndex === -1 ? (node.dataset || {}).focusGuard ? 0 : -1 : node.tabIndex, }; }) .filter(function (data) { return !filterNegative || data.tabIndex >= 0; }) .sort(tabSort); }; const tabbables = [ "button:enabled", "select:enabled", "textarea:enabled", "input:enabled", "a[href]", "area[href]", "summary", "iframe", "object", "embed", "audio[controls]", "video[controls]", "[tabindex]", "[contenteditable]", "[autofocus]", ]; const queryTabbables = tabbables.join(","); const queryGuardTabbables = queryTabbables + ", [data-focus-guard]"; const getFocusables = function (parents, withGuards) { return parents.reduce(function (acc, parent) { return acc.concat( toArray( parent.querySelectorAll( withGuards ? queryGuardTabbables : queryTabbables, ), ), parent.parentNode ? toArray(parent.parentNode.querySelectorAll(queryTabbables)).filter( function (node) { return node === parent; }, ) : [], ); }, []); }; const getParentAutofocusables = function (parent) { const parentFocus = parent.querySelectorAll("[" + FOCUS_AUTO + "]"); return toArray(parentFocus) .map(function (node) { return getFocusables([node]); }) .reduce(function (acc, nodes) { return acc.concat(nodes); }, []); }; const filterFocusable = function (nodes) { return toArray(nodes) .filter(function (node) { return isVisible(node); }) .filter(function (node) { return notHiddenInput(node); }); }; const getTabbableNodes = function (topNodes, withGuards) { return orderByTabIndex( filterFocusable(getFocusables(topNodes, withGuards)), true, withGuards, ); }; const getAllTabbableNodes = function (topNodes) { return orderByTabIndex(filterFocusable(getFocusables(topNodes)), false); }; const parentAutofocusables = function (topNode) { return filterFocusable(getParentAutofocusables(topNode)); }; var getParents = function (node, parents) { if (parents === void 0) { parents = []; } parents.push(node); if (node.parentNode) { getParents(node.parentNode, parents); } return parents; }; const getCommonParent = function (nodeA, nodeB) { const parentsA = getParents(nodeA); const parentsB = getParents(nodeB); for (let i = 0; i < parentsA.length; i += 1) { const currentParent = parentsA[i]; if (parentsB.indexOf(currentParent) >= 0) { return currentParent; } } return false; }; const getTopCommonParent = function ( baseActiveElement, leftEntry, rightEntries, ) { const activeElements = asArray(baseActiveElement); const leftEntries = asArray(leftEntry); const activeElement = activeElements[0]; let topCommon = false; leftEntries.filter(Boolean).forEach(function (entry) { topCommon = getCommonParent(topCommon || entry, entry) || topCommon; rightEntries.filter(Boolean).forEach(function (subEntry) { const common = getCommonParent(activeElement, subEntry); if (common) { if (!topCommon || common.contains(topCommon)) { topCommon = common; } else { topCommon = getCommonParent(common, topCommon); } } }); }); return topCommon; }; const allParentAutofocusables = function (entries) { return entries.reduce(function (acc, node) { return acc.concat(parentAutofocusables(node)); }, []); }; const getFocusabledIn = function (topNode) { const entries = getAllAffectedNodes(topNode).filter(isNotAGuard); const commonParent = getTopCommonParent(topNode, topNode, entries); const outerNodes = getTabbableNodes([commonParent], true); const innerElements = getTabbableNodes(entries) .filter(function (_a) { const node = _a.node; return isNotAGuard(node); }) .map(function (_a) { const node = _a.node; return node; }); return outerNodes.map(function (_a) { const node = _a.node, index = _a.index; return { node: node, index: index, lockItem: innerElements.indexOf(node) >= 0, guard: isGuard(node), }; }); }; const focusInFrame = function (frame) { return frame === document.activeElement; }; const focusInsideIframe = function (topNode) { return Boolean( toArray(topNode.querySelectorAll("iframe")).some(function (node) { return focusInFrame(node); }), ); }; const focusInside = function (topNode) { const activeElement = document && document.activeElement; if ( !activeElement || (activeElement.dataset && activeElement.dataset.focusGuard) ) { return false; } return getAllAffectedNodes(topNode).reduce(function (result, node) { return result || node.contains(activeElement) || focusInsideIframe(node); }, false); }; const focusIsHidden = function () { return ( document && toArray(document.querySelectorAll("[" + FOCUS_ALLOW + "]")).some(function ( node, ) { return node.contains(document.activeElement); }) ); }; const isRadio = function (node) { return node.tagName === "INPUT" && node.type === "radio"; }; const findSelectedRadio = function (node, nodes) { return ( nodes .filter(isRadio) .filter(function (el) { return el.name === node.name; }) .filter(function (el) { return el.checked; })[0] || node ); }; const correctNode = function (node, nodes) { if (isRadio(node) && node.name) { return findSelectedRadio(node, nodes); } return node; }; const correctNodes = function (nodes) { const resultSet = new Set(); nodes.forEach(function (node) { return resultSet.add(correctNode(node, nodes)); }); return nodes.filter(function (node) { return resultSet.has(node); }); }; const pickFirstFocus = function (nodes) { if (nodes[0] && nodes.length > 1) { return correctNode(nodes[0], nodes); } return nodes[0]; }; const pickFocusable = function (nodes, index) { if (nodes.length > 1) { return nodes.indexOf(correctNode(nodes[index], nodes)); } return index; }; const NEW_FOCUS = "NEW_FOCUS"; const newFocus = function (innerNodes, outerNodes, activeElement, lastNode) { const cnt = innerNodes.length; const firstFocus = innerNodes[0]; const lastFocus = innerNodes[cnt - 1]; const isOnGuard = isGuard(activeElement); if (innerNodes.indexOf(activeElement) >= 0) { return undefined; } const activeIndex = outerNodes.indexOf(activeElement); const lastIndex = lastNode ? outerNodes.indexOf(lastNode) : activeIndex; const lastNodeInside = lastNode ? innerNodes.indexOf(lastNode) : -1; const indexDiff = activeIndex - lastIndex; const firstNodeIndex = outerNodes.indexOf(firstFocus); const lastNodeIndex = outerNodes.indexOf(lastFocus); const correctedNodes = correctNodes(outerNodes); const correctedIndexDiff = correctedNodes.indexOf(activeElement) - (lastNode ? correctedNodes.indexOf(lastNode) : activeIndex); const returnFirstNode = pickFocusable(innerNodes, 0); const returnLastNode = pickFocusable(innerNodes, cnt - 1); if (activeIndex === -1 || lastNodeInside === -1) { return NEW_FOCUS; } if (!indexDiff && lastNodeInside >= 0) { return lastNodeInside; } if (activeIndex <= firstNodeIndex && isOnGuard && Math.abs(indexDiff) > 1) { return returnLastNode; } if (activeIndex >= lastNodeIndex && isOnGuard && Math.abs(indexDiff) > 1) { return returnFirstNode; } if (indexDiff && Math.abs(correctedIndexDiff) > 1) { return lastNodeInside; } if (activeIndex <= firstNodeIndex) { return returnLastNode; } if (activeIndex > lastNodeIndex) { return returnFirstNode; } if (indexDiff) { if (Math.abs(indexDiff) > 1) { return lastNodeInside; } return (cnt + lastNodeInside + indexDiff) % cnt; } return undefined; }; const findAutoFocused = function (autoFocusables) { return function (node) { return ( node.autofocus || (node.dataset && !!node.dataset.autofocus) || autoFocusables.indexOf(node) >= 0 ); }; }; const reorderNodes = function (srcNodes, dstNodes) { const remap = new Map(); dstNodes.forEach(function (entity) { return remap.set(entity.node, entity); }); return srcNodes .map(function (node) { return remap.get(node); }) .filter(isDefined); }; const getFocusMerge = function (topNode, lastNode) { const activeElement = document && document.activeElement; const entries = getAllAffectedNodes(topNode).filter(isNotAGuard); const commonParent = getTopCommonParent( activeElement || topNode, topNode, entries, ); const anyFocusable = getAllTabbableNodes(entries); let innerElements = getTabbableNodes(entries).filter(function (_a) { const node = _a.node; return isNotAGuard(node); }); if (!innerElements[0]) { innerElements = anyFocusable; if (!innerElements[0]) { return undefined; } } const outerNodes = getAllTabbableNodes([commonParent]).map(function (_a) { const node = _a.node; return node; }); const orderedInnerElements = reorderNodes(outerNodes, innerElements); const innerNodes = orderedInnerElements.map(function (_a) { const node = _a.node; return node; }); const newId = newFocus(innerNodes, outerNodes, activeElement, lastNode); if (newId === NEW_FOCUS) { const autoFocusable = anyFocusable .map(function (_a) { const node = _a.node; return node; }) .filter(findAutoFocused(allParentAutofocusables(entries))); return { node: autoFocusable && autoFocusable.length ? pickFirstFocus(autoFocusable) : pickFirstFocus(innerNodes), }; } if (newId === undefined) { return newId; } return orderedInnerElements[newId]; }; const focusOn = function (target) { target.focus(); if ("contentWindow" in target && target.contentWindow) { target.contentWindow.focus(); } }; let guardCount = 0; let lockDisabled = false; const setFocus = function (topNode, lastNode) { const focusable = getFocusMerge(topNode, lastNode); if (lockDisabled) { return; } if (focusable) { if (guardCount > 2) { console.error( "FocusLock: focus-fighting detected. Only one focus management system could be active. " + "See https://github.com/theKashey/focus-lock/#focus-fighting", ); lockDisabled = true; setTimeout(function () { lockDisabled = false; }, 1); return; } guardCount++; focusOn(focusable.node); guardCount--; } }; function deferAction(action) { // Hidding setImmediate from Webpack to avoid inserting polyfill const _window = window, setImmediate = _window.setImmediate; if (typeof setImmediate !== "undefined") { setImmediate(action); } else { setTimeout(action, 1); } } const focusOnBody = function focusOnBody() { return document && document.activeElement === document.body; }; const isFreeFocus = function isFreeFocus() { return focusOnBody() || focusIsHidden(); }; let lastActiveTrap = null; let lastActiveFocus = null; let lastPortaledElement = null; let focusWasOutsideWindow = false; const defaultWhitelist = function defaultWhitelist() { return true; }; const focusWhitelisted = function focusWhitelisted(activeElement) { return (lastActiveTrap.whiteList || defaultWhitelist)(activeElement); }; const recordPortal = function recordPortal(observerNode, portaledElement) { lastPortaledElement = { observerNode: observerNode, portaledElement: portaledElement, }; }; const focusIsPortaledPair = function focusIsPortaledPair(element) { return lastPortaledElement && lastPortaledElement.portaledElement === element; }; function autoGuard(startIndex, end, step, allNodes) { let lastGuard = null; let i = startIndex; do { const item = allNodes[i]; if (item.guard) { if (item.node.dataset.focusAutoGuard) { lastGuard = item; } } else if (item.lockItem) { if (i !== startIndex) { // we will tab to the next element return; } lastGuard = null; } else { break; } } while ((i += step) !== end); if (lastGuard) { lastGuard.node.tabIndex = 0; } } const extractRef$1 = function extractRef(ref) { return ref && "current" in ref ? ref.current : ref; }; const focusWasOutside = function focusWasOutside(crossFrameOption) { if (crossFrameOption) { // with cross frame return true for any value return Boolean(focusWasOutsideWindow); } // in other case return only of focus went a while aho return focusWasOutsideWindow === "meanwhile"; }; const activateTrap = function activateTrap() { let result = false; if (lastActiveTrap) { const _lastActiveTrap = lastActiveTrap, observed = _lastActiveTrap.observed, persistentFocus = _lastActiveTrap.persistentFocus, autoFocus = _lastActiveTrap.autoFocus, shards = _lastActiveTrap.shards, crossFrame = _lastActiveTrap.crossFrame; const workingNode = observed || (lastPortaledElement && lastPortaledElement.portaledElement); const activeElement = document && document.activeElement; if (workingNode) { const workingArea = [workingNode].concat( shards.map(extractRef$1).filter(Boolean), ); if (!activeElement || focusWhitelisted(activeElement)) { if ( persistentFocus || focusWasOutside(crossFrame) || !isFreeFocus() || (!lastActiveFocus && autoFocus) ) { if ( workingNode && !(focusInside(workingArea) || focusIsPortaledPair(activeElement)) ) { if (document && !lastActiveFocus && activeElement && !autoFocus) { // Check if blur() exists, which is missing on certain elements on IE if (activeElement.blur) { activeElement.blur(); } document.body.focus(); } else { result = setFocus(workingArea, lastActiveFocus); lastPortaledElement = {}; } } focusWasOutsideWindow = false; lastActiveFocus = document && document.activeElement; } } if (document) { const newActiveElement = document && document.activeElement; const allNodes = getFocusabledIn(workingArea); const focusedIndex = allNodes .map(function (_ref) { const node = _ref.node; return node; }) .indexOf(newActiveElement); if (focusedIndex > -1) { // remove old focus allNodes .filter(function (_ref2) { const guard = _ref2.guard, node = _ref2.node; return guard && node.dataset.focusAutoGuard; }) .forEach(function (_ref3) { const node = _ref3.node; return node.removeAttribute("tabIndex"); }); autoGuard(focusedIndex, allNodes.length, +1, allNodes); autoGuard(focusedIndex, -1, -1, allNodes); } } } } return result; }; const onTrap = function onTrap(event) { if (activateTrap() && event) { // prevent scroll jump event.stopPropagation(); event.preventDefault(); } }; const onBlur = function onBlur() { return deferAction(activateTrap); }; const onFocus = function onFocus(event) { // detect portal const source = event.target; const currentNode = event.currentTarget; if (!currentNode.contains(source)) { recordPortal(currentNode, source); } }; const FocusWatcher = function FocusWatcher() { return null; }; ({ children: propTypes$1.node.isRequired, }); const onWindowBlur = function onWindowBlur() { focusWasOutsideWindow = "just"; // using setTimeout to set this variable after React/sidecar reaction setTimeout(function () { focusWasOutsideWindow = "meanwhile"; }, 0); }; const attachHandler = function attachHandler() { document.addEventListener("focusin", onTrap, true); document.addEventListener("focusout", onBlur); window.addEventListener("blur", onWindowBlur); }; const detachHandler = function detachHandler() { document.removeEventListener("focusin", onTrap, true); document.removeEventListener("focusout", onBlur); window.removeEventListener("blur", onWindowBlur); }; function reducePropsToState(propsList) { return propsList.filter(function (_ref5) { const disabled = _ref5.disabled; return !disabled; }); } function handleStateChangeOnClient(traps) { const trap = traps.slice(-1)[0]; if (trap && !lastActiveTrap) { attachHandler(); } const lastTrap = lastActiveTrap; const sameTrap = lastTrap && trap && trap.id === lastTrap.id; lastActiveTrap = trap; if (lastTrap && !sameTrap) { lastTrap.onDeactivation(); // return focus only of last trap was removed if ( !traps.filter(function (_ref6) { const id = _ref6.id; return id === lastTrap.id; }).length ) { // allow defer is no other trap is awaiting restore lastTrap.returnFocus(!trap); } } if (trap) { lastActiveFocus = null; if (!sameTrap || lastTrap.observed !== trap.observed) { trap.onActivation(); } activateTrap(); deferAction(activateTrap); } else { detachHandler(); lastActiveFocus = null; } } // bind medium mediumFocus.assignSyncMedium(onFocus); mediumBlur.assignMedium(onBlur); mediumEffect.assignMedium(function (cb) { return cb({ moveFocusInside: setFocus, focusInside: focusInside, }); }); const FocusTrap = withSideEffect( reducePropsToState, handleStateChangeOnClient, )(FocusWatcher); /* that would be a BREAKING CHANGE! // delaying sidecar execution till the first usage const RequireSideCar = (props) => { // eslint-disable-next-line global-require const SideCar = require('./Trap').default; return <SideCar {...props} />; }; */ const FocusLockCombination = /*#__PURE__*/ react.forwardRef( function FocusLockUICombination(props, ref) { return /*#__PURE__*/ react.createElement( FocusLock, _extends$1( { sideCar: FocusTrap, ref: ref, }, props, ), ); }, ); const _ref = FocusLock.propTypes || {}; _ref.sideCar; const propTypes = _objectWithoutPropertiesLoose$1(_ref, ["sideCar"]); FocusLockCombination.propTypes = propTypes; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (const p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { const t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if ( e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]) ) t[p[i]] = s[p[i]]; } return t; } const zeroRightClassName = "right-scroll-bar-position"; const fullWidthClassName = "width-before-scroll-bar"; const noScrollbarsClassName = "with-scroll-bars-hidden"; const removedBarSizeVariable = "--removed-body-scroll-bar-size"; const effectCar = createSidecarMedium(); const nothing = function () { return; }; /** * Removes scrollbar from the page and contain the scroll within the Lock */ const RemoveScroll = react.forwardRef(function (props, parentRef) { const ref = react.useRef(null); const _a = react.useState({ onScrollCapture: nothing, onWheelCapture: nothing, onTouchMoveCapture: nothing, }), callbacks = _a[0], setCallbacks = _a[1]; const forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container = _b === void 0 ? "div" : _b, rest = __rest(props, [ "forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noIsolation", "inert", "allowPinchZoom", "as", ]); const SideCar = sideCar; const containerRef = useMergeRefs([ref, parentRef]); const containerProps = __assign({}, rest, callbacks); return react.createElement( react.Fragment, null, enabled && react.createElement(SideCar, { sideCar: effectCar, removeScrollBar: removeScrollBar, shards: shards, noIsolation: noIsolation, inert: inert, setCallbacks: setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref, }), forwardProps ? react.cloneElement( react.Children.only(children), __assign({}, containerProps, { ref: containerRef }), ) : react.createElement( Container, __assign({}, containerProps, { className: className, ref: containerRef, }), children, ), ); }); RemoveScroll.defaultProps = { enabled: true, removeScrollBar: true, inert: false, }; RemoveScroll.classNames = { fullWidth: fullWidthClassName, zeroRight: zeroRightClassName, }; const getNonce = function () { if (typeof __webpack_nonce__ !== "undefined") { return __webpack_nonce__; } return undefined; }; function makeStyleTag() { if (!document) return null; const tag = document.createElement("style"); tag.type = "text/css"; const nonce = getNonce(); if (nonce) { tag.setAttribute("nonce", nonce); } return tag; } function injectStyles(tag, css) { if (tag.styleSheet) { tag.styleSheet.cssText = css; } else { tag.appendChild(document.createTextNode(css)); } } function insertStyleTag(tag) { const head = document.head || document.getElementsByTagName("head")[0]; head.appendChild(tag); } const stylesheetSingleton = function () { let counter = 0; let stylesheet = null; return { add: function (style) { if (counter == 0) { if ((stylesheet = makeStyleTag())) { injectStyles(stylesheet, style); insertStyleTag(stylesheet); } } counter++; }, remove: function () { counter--; if (!counter && stylesheet) { stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet); stylesheet = null; } }, }; }; const styleHookSingleton = function () { const sheet = stylesheetSingleton(); return function (styles) { react.useEffect(function () { sheet.add(styles); return function () { sheet.remove(); }; }, []); }; }; const styleSingleton = function () { const useStyle = styleHookSingleton(); const Sheet = function (_a) { const styles = _a.styles; useStyle(styles); return null; }; return Sheet; }; const zeroGap = { left: 0, top: 0, right: 0, gap: 0, }; const parse = function (x) { return parseInt(x || "", 10) || 0; }; const getOffset = function (gapMode) { const cs = window.getComputedStyle(document.body); const left = cs[gapMode === "padding" ? "paddingLeft" : "marginLeft"]; const top = cs[gapMode === "padding" ? "paddingTop" : "marginTop"]; const right = cs[gapMode === "padding" ? "paddingRight" : "marginRight"]; return [parse(left), parse(top), parse(right)]; }; const getGapWidth = function (gapMode) { if (gapMode === void 0) { gapMode = "margin"; } if (typeof window === "undefined") { return zeroGap; } const offsets = getOffset(gapMode); const documentWidth = document.documentElement.clientWidth; const windowWidth = window.innerWidth; return { left: offsets[0], top: offsets[1], right: offsets[2], gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0]), }; }; const Style = styleSingleton(); const getStyles = function (_a, allowRelative, gapMode, important) { const left = _a.left, top = _a.top, right = _a.right, gap = _a.gap; if (gapMode === void 0) { gapMode = "margin"; } return ( "\n ." + noScrollbarsClassName + " {\n overflow: hidden " + important + ";\n padding-right: " + gap + "px " + important + ";\n }\n body {\n overflow: hidden " + important + ";\n " + [ allowRelative && "position: relative " + important + ";", gapMode === "margin" && "\n padding-left: " + left + "px;\n padding-top: " + top + "px;\n padding-right: " + right + "px;\n margin-left:0;\n margin-top:0;\n margin-right: " + gap + "px " + important + ";\n ", gapMode === "padding" && "padding-right: " + gap + "px " + important + ";", ] .filter(Boolean) .join("") + "\n }\n \n ." + zeroRightClassName + " {\n right: " + gap + "px " + important + ";\n }\n \n ." + fullWidthClassName + " {\n margin-right: " + gap + "px " + important + ";\n }\n \n ." + zeroRightClassName + " ." + zeroRightClassName + " {\n right: 0 " + important + ";\n }\n \n ." + fullWidthClassName + " ." + fullWidthClassName + " {\n margin-right: 0 " + important + ";\n }\n \n body {\n " + removedBarSizeVariable + ": " + gap + "px;\n }\n" ); }; const RemoveScrollBar = function (props) { const _a = react.useState(getGapWidth(props.gapMode)), gap = _a[0], setGap = _a[1]; react.useEffect( function () { setGap(getGapWidth(props.gapMode)); }, [props.gapMode], ); const noRelative = props.noRelative, noImportant = props.noImportant, _b = props.gapMode, gapMode = _b === void 0 ? "margin" : _b; return react.createElement(Style, { styles: getStyles( gap, !noRelative, gapMode, !noImportant ? "!important" : "", ), }); }; const elementCouldBeVScrolled = function (node) { const styles = window.getComputedStyle(node); return ( styles.overflowY !== "hidden" && // not-not-scrollable !(styles.overflowY === styles.overflowX && styles.overflowY === "visible") // scrollable ); }; const elementCouldBeHScrolled = function (node) { const styles = window.getComputedStyle(node); return ( styles.overflowX !== "hidden" && // not-not-scrollable !(styles.overflowY === styles.overflowX && styles.overflowX === "visible") // scrollable ); }; const locationCouldBeScrolled = function (axis, node) { let current = node; do { const isScrollable = elementCouldBeScrolled(axis, current); if (isScrollable) { const _a = getScrollVariables(axis, current), s = _a[1], d = _a[2]; if (s > d) { return true; } } current = current.parentNode; } while (current && current !== document.body); return false; }; const getVScrollVariables = function (_a) { const scrollTop = _a.scrollTop, scrollHeight = _a.scrollHeight, clientHeight = _a.clientHeight; return [scrollTop, scrollHeight, clientHeight]; }; const getHScrollVariables = function (_a) { const scrollLeft = _a.scrollLeft, scrollWidth = _a.scrollWidth, clientWidth = _a.clientWidth; return [scrollLeft, scrollWidth, clientWidth]; }; var elementCouldBeScrolled = function (axis, node) { return axis === "v" ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node); }; var getScrollVariables = function (axis, node) { return axis === "v" ? getVScrollVariables(node) : getHScrollVariables(node); }; const handleScroll = function ( axis, endTarget, event, sourceDelta, noOverscroll, ) { const delta = sourceDelta; // find scrollable target let target = event.target; const targetInLock = endTarget.contains(target); let shouldCancelScroll = false; const isDeltaPositive = delta > 0; let availableScroll = 0; let availableScrollTop = 0; do { const _a = getScrollVariables(axis, target), position = _a[0], scroll_1 = _a[1], capacity = _a[2]; const elementScroll = scroll_1 - capacity - position; if (position || elementScroll) { if (elementCouldBeScrolled(axis, target)) { availableScroll += elementScroll; availableScrollTop += position; } } target = target.parentNode; } while ( // portaled content (!targetInLock && target !== document.body) || // self content (targetInLock && (endTarget.contains(target) || endTarget === target)) ); if ( isDeltaPositive && ((noOverscroll && availableScroll === 0) || (!noOverscroll && delta > availableScroll)) ) { shouldCancelScroll = true; } else if ( !isDeltaPositive && ((noOverscroll && availableScrollTop === 0) || (!noOverscroll && -delta > availableScrollTop)) ) { shouldCancelScroll = true; } return shouldCancelScroll; }; let passiveSupported = false; if (typeof window !== "undefined") { try { const options = Object.defineProperty({}, "passive", { get: function () { passiveSupported = true; return true; }, }); window.addEventListener("test", options, options); window.removeEventListener("test", options, options); } catch (err) { passiveSupported = false; } } const nonPassive = passiveSupported ? { passive: false } : false; const getTouchXY = function (event) { return "changedTouches" in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0]; }; const getDeltaXY = function (event) { return [event.deltaX, event.deltaY]; }; const extractRef = function (ref) { return ref && "current" in ref ? ref.current : ref; }; const deltaCompare = function (x, y) { return x[0] === y[0] && x[1] === y[1]; }; const generateStyle = function (id) { return ( "\n .block-interactivity-" + id + " {pointer-events: none;}\n .allow-interactivity-" + id + " {pointer-events: all;}\n" ); }; let idCounter = 0; let lockStack = []; function RemoveScrollSideCar(props) { const shouldPreventQueue = react.useRef([]); const touchStartRef = react.useRef([0, 0]); const activeAxis = react.useRef(); const id = react.useState(idCounter++)[0]; const Style = react.useState(function () { return styleSingleton(); })[0]; const lastProps = react.useRef(props); react.useEffect( function () { lastProps.current = props; }, [props], ); react.useEffect( function () { if (props.inert) { document.body.classList.add("block-interactivity-" + id); const allow_1 = [props.lockRef.current] .concat((props.shards || []).map(extractRef)) .filter(Boolean); allow_1.forEach(function (el) { return el.classList.add("allow-interactivity-" + id); }); return function () { document.body.classList.remove("block-interactivity-" + id); allow_1.forEach(function (el) { return el.classList.remove("allow-interactivity-" + id); }); }; } return; }, [props.inert, props.lockRef.current, props.shards], ); const shouldCancelEvent = react.useCallback(function (event, parent) { if ("touches" in event && event.touches.length === 2) { return !lastProps.current.allowPinchZoom; } const touch = getTouchXY(event); const touchStart = touchStartRef.current; const deltaX = "deltaX" in event ? event.deltaX : touchStart[0] - touch[0]; const deltaY = "deltaY" in event ? event.deltaY : touchStart[1] - touch[1]; let currentAxis; const target = event.target; const moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? "h" : "v"; let canBeScrolledInMainDirection = locationCouldBeScrolled( moveDirection, target, ); if (!canBeScrolledInMainDirection) { return true; } if (canBeScrolledInMainDirection) { currentAxis = moveDirection; } else { currentAxis = moveDirection === "v" ? "h" : "v"; canBeScrolledInMainDirection = locationCouldBeScrolled( moveDirection, target, ); // other axis might be not scrollable } if (!canBeScrolledInMainDirection) { return false; } if ( !activeAxis.current && "changedTouches" in event && (deltaX || deltaY) ) { activeAxis.current = currentAxis; } if (!currentAxis) { return true; } const cancelingAxis = activeAxis.current || currentAxis; return handleScroll( cancelingAxis, parent, event, cancelingAxis === "h" ? deltaX : deltaY, true, ); }, []); const shouldPrevent = react.useCallback(function (_event) { const event = _event; if (!lockStack.length || lockStack[lockStack.length - 1] !== Style) { // not the last active return; } const delta = "deltaY" in event ? getDeltaXY(event) : getTouchXY(event); const sourceEvent = shouldPreventQueue.current.filter(function (e) { return ( e.name === event.type && e.target === event.target && deltaCompare(e.delta, delta) ); })[0]; // self event, and should be canceled if (sourceEvent && sourceEvent.should) { event.preventDefault(); return; } // outside or shard event if (!sourceEvent) { const shardNodes = (lastProps.current.shards || []) .map(extractRef) .filter(Boolean) .filter(function (node) { return node.contains(event.target); }); const shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation; if (shouldStop) { event.preventDefault(); } } }, []); const shouldCancel = react.useCallback(function ( name, delta, target, should, ) { const event = { name: name, delta: delta, target: target, should: should }; shouldPreventQueue.current.push(event); setTimeout(function () { shouldPreventQueue.current = shouldPreventQueue.current.filter(function ( e, ) { return e !== event; }); }, 1); }, []); const scrollTouchStart = react.useCallback(function (event) { touchStartRef.current = getTouchXY(event); activeAxis.current = undefined; }, []); const scrollWheel = react.useCallback(function (event) { shouldCancel( event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current), ); }, []); const scrollTouchMove = react.useCallback(function (event) { shouldCancel( event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current), ); }, []); react.useEffect(function () { lockStack.push(Style); props.setCallbacks({ onScrollCapture: scrollWheel, onWheelCapture: scrollWheel, onTouchMoveCapture: scrollTouchMove, }); document.addEventListener("wheel", shouldPrevent, nonPassive); document.addEventListener("touchmove", shouldPrevent, nonPassive); document.addEventListener("touchstart", scrollTouchStart, nonPassive); return function () { lockStack = lockStack.filter(function (inst) { return inst !== Style; }); document.removeEventListener("wheel", shouldPrevent, nonPassive); document.removeEventListener("touchmove", shouldPrevent, nonPassive); document.removeEventListener("touchstart", scrollTouchStart, nonPassive); }; }, []); const removeScrollBar = props.removeScrollBar, inert = props.inert; return react.createElement( react.Fragment, null, inert ? react.createElement(Style, { styles: generateStyle(id) }) : null, removeScrollBar ? react.createElement(RemoveScrollBar, { gapMode: "margin" }) : null, ); } const SideCar = exportSidecar(effectCar, RemoveScrollSideCar); const ReactRemoveScroll = react.forwardRef(function (props, ref) { return react.createElement( RemoveScroll, __assign({}, props, { ref: ref, sideCar: SideCar }), ); }); ReactRemoveScroll.classNames = RemoveScroll.classNames; function _extends() { _extends = Object.assign || function (target) { for (let i = 1; i < arguments.length; i++) { const source = arguments[i]; for (const key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; const target = {}; const sourceKeys = Object.keys(source); let key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } const overlayPropTypes = { allowPinchZoom: propTypes$1.bool, dangerouslyBypassFocusLock: propTypes$1.bool, dangerouslyBypassScrollLock: propTypes$1.bool, // TODO: initialFocusRef: function initialFocusRef() { return null; }, onDismiss: propTypes$1.func, }; //////////////////////////////////////////////////////////////////////////////// /** * DialogOverlay * * Low-level component if you need more control over the styles or rendering of * the dialog overlay. * * Note: You must render a `DialogContent` inside. * * @see Docs https://reach.tech/dialog#dialogoverlay */ const DialogOverlay = /*#__PURE__*/ forwardRefWithAs(function DialogOverlay( _ref, forwardedRef, ) { const _ref$as = _ref.as, Comp = _ref$as === void 0 ? "div" : _ref$as, _ref$isOpen = _ref.isOpen, isOpen = _ref$isOpen === void 0 ? true : _ref$isOpen, props = _objectWithoutPropertiesLoose(_ref, ["as", "isOpen"]); useCheckStyles("dialog"); // We want to ignore the immediate focus of a tooltip so it doesn't pop // up again when the menu closes, only pops up when focus returns again // to the tooltip (like native OS tooltips). react.useEffect( function () { if (isOpen) { // @ts-ignore window.__REACH_DISABLE_TOOLTIPS = true; } else { window.requestAnimationFrame(function () { // Wait a frame so that this doesn't fire before tooltip does // @ts-ignore window.__REACH_DISABLE_TOOLTIPS = false; }); } }, [isOpen], ); return isOpen ? /*#__PURE__*/ react.createElement( Portal, { "data-reach-dialog-wrapper": "", }, /*#__PURE__*/ react.createElement( DialogInner, _extends( { ref: forwardedRef, as: Comp, }, props, ), ), ) : null; }); { DialogOverlay.displayName = "DialogOverlay"; DialogOverlay.propTypes = /*#__PURE__*/ _extends({}, overlayPropTypes, { isOpen: propTypes$1.bool, }); } //////////////////////////////////////////////////////////////////////////////// /** * DialogInner */ var DialogInner = /*#__PURE__*/ forwardRefWithAs(function DialogInner( _ref2, forwardedRef, ) { const allowPinchZoom = _ref2.allowPinchZoom, _ref2$as = _ref2.as, Comp = _ref2$as === void 0 ? "div" : _ref2$as, _ref2$dangerouslyBypa = _ref2.dangerouslyBypassFocusLock, dangerouslyBypassFocusLock = _ref2$dangerouslyBypa === void 0 ? false : _ref2$dangerouslyBypa, _ref2$dangerouslyBypa2 = _ref2.dangerouslyBypassScrollLock, dangerouslyBypassScrollLock = _ref2$dangerouslyBypa2 === void 0 ? false : _ref2$dangerouslyBypa2, initialFocusRef = _ref2.initialFocusRef, onClick = _ref2.onClick, _ref2$onDismiss = _ref2.onDismiss, onDismiss = _ref2$onDismiss === void 0 ? noop : _ref2$onDismiss, onKeyDown = _ref2.onKeyDown, onMouseDown = _ref2.onMouseDown, _ref2$unstable_lockFo = _ref2.unstable_lockFocusAcrossFrames, unstable_lockFocusAcrossFrames = _ref2$unstable_lockFo === void 0 ? true : _ref2$unstable_lockFo, props = _objectWithoutPropertiesLoose(_ref2, [ "allowPinchZoom", "as", "dangerouslyBypassFocusLock", "dangerouslyBypassScrollLock", "initialFocusRef", "onClick", "onDismiss", "onKeyDown", "onMouseDown", "unstable_lockFocusAcrossFrames", ]); const mouseDownTarget = react.useRef(null); const overlayNode = react.useRef(null); const ref = useForkedRef(overlayNode, forwardedRef); const activateFocusLock = react.useCallback( function () { if (initialFocusRef && initialFocusRef.current) { initialFocusRef.current.focus(); } }, [initialFocusRef], ); function handleClick(event) { if (mouseDownTarget.current === event.target) { event.stopPropagation(); onDismiss(event); } } function handleKeyDown(event) { if (event.key === "Escape") { event.stopPropagation(); onDismiss(event); } } function handleMouseDown(event) { mouseDownTarget.current = event.target; } react.useEffect(function () { return overlayNode.current ? createAriaHider(overlayNode.current) : void null; }, []); return /*#__PURE__*/ react.createElement( FocusLockCombination, { autoFocus: true, returnFocus: true, onActivation: activateFocusLock, disabled: dangerouslyBypassFocusLock, crossFrame: unstable_lockFocusAcrossFrames, }, /*#__PURE__*/ react.createElement( ReactRemoveScroll, { allowPinchZoom: allowPinchZoom, enabled: !dangerouslyBypassScrollLock, }, /*#__PURE__*/ react.createElement( Comp, _extends({}, props, { ref: ref, "data-reach-dialog-overlay": "", /* * We can ignore the `no-static-element-interactions` warning here * because our overlay is only designed to capture any outside * clicks, not to serve as a clickable element itself. */ onClick: wrapEvent(onClick, handleClick), onKeyDown: wrapEvent(onKeyDown, handleKeyDown), onMouseDown: wrapEvent(onMouseDown, handleMouseDown), }), ), ), ); }); { DialogOverlay.displayName = "DialogOverlay"; DialogOverlay.propTypes = /*#__PURE__*/ _extends({}, overlayPropTypes); } //////////////////////////////////////////////////////////////////////////////// /** * DialogContent * * Low-level component if you need more control over the styles or rendering of * the dialog content. * * Note: Must be a child of `DialogOverlay`. * * Note: You only need to use this when you are also styling `DialogOverlay`, * otherwise you can use the high-level `Dialog` component and pass the props * to it. Any props passed to `Dialog` component (besides `isOpen` and * `onDismiss`) will be spread onto `DialogContent`. * * @see Docs https://reach.tech/dialog#dialogcontent */ const DialogContent = /*#__PURE__*/ forwardRefWithAs(function DialogContent( _ref3, forwardedRef, ) { const _ref3$as = _ref3.as, Comp = _ref3$as === void 0 ? "div" : _ref3$as, onClick = _ref3.onClick; _ref3.onKeyDown; const props = _objectWithoutPropertiesLoose(_ref3, [ "as", "onClick", "onKeyDown", ]); return /*#__PURE__*/ react.createElement( Comp, _extends( { "aria-modal": "true", role: "dialog", tabIndex: -1, }, props, { ref: forwardedRef, "data-reach-dialog-content": "", onClick: wrapEvent(onClick, function (event) { event.stopPropagation(); }), }, ), ); }); /** * @see Docs https://reach.tech/dialog#dialogcontent-props */ { DialogContent.displayName = "DialogContent"; DialogContent.propTypes = { "aria-label": ariaLabelType, "aria-labelledby": ariaLabelType, }; } //////////////////////////////////////////////////////////////////////////////// /** * Dialog * * High-level component to render a modal dialog window over the top of the page * (or another dialog). * * @see Docs https://reach.tech/dialog#dialog */ /** @type {any} */ const Dialog = /*#__PURE__*/ forwardRefWithAs(function Dialog( _ref4, forwardedRef, ) { const _ref4$allowPinchZoom = _ref4.allowPinchZoom, allowPinchZoom = _ref4$allowPinchZoom === void 0 ? false : _ref4$allowPinchZoom, initialFocusRef = _ref4.initialFocusRef, isOpen = _ref4.isOpen, _ref4$onDismiss = _ref4.onDismiss, onDismiss = _ref4$onDismiss === void 0 ? noop : _ref4$onDismiss, props = _objectWithoutPropertiesLoose(_ref4, [ "allowPinchZoom", "initialFocusRef", "isOpen", "onDismiss", ]); return /*#__PURE__*/ react.createElement( DialogOverlay, { allowPinchZoom: allowPinchZoom, initialFocusRef: initialFocusRef, isOpen: isOpen, onDismiss: onDismiss, }, /*#__PURE__*/ react.createElement( DialogContent, _extends( { ref: forwardedRef, }, props, ), ), ); }); /** * @see Docs https://reach.tech/dialog#dialog-props */ { Dialog.displayName = "Dialog"; Dialog.propTypes = { isOpen: propTypes$1.bool, onDismiss: propTypes$1.func, "aria-label": ariaLabelType, "aria-labelledby": ariaLabelType, }; } //////////////////////////////////////////////////////////////////////////////// function createAriaHider(dialogNode) { const originalValues = []; const rootNodes = []; const ownerDocument = getOwnerDocument(dialogNode); if (!dialogNode) { { console.warn( "A ref has not yet been attached to a dialog node when attempting to call `createAriaHider`.", ); } return noop; } Array.prototype.forEach.call( ownerDocument.querySelectorAll("body > *"), function (node) { let _dialogNode$parentNod, _dialogNode$parentNod2; const portalNode = (_dialogNode$parentNod = dialogNode.parentNode) == null ? void 0 : (_dialogNode$parentNod2 = _dialogNode$parentNod.parentNode) == null ? void 0 : _dialogNode$parentNod2.parentNode; if (node === portalNode) { return; } const attr = node.getAttribute("aria-hidden"); const alreadyHidden = attr !== null && attr !== "false"; if (alreadyHidden) { return; } originalValues.push(attr); rootNodes.push(node); node.setAttribute("aria-hidden", "true"); }, ); return function () { rootNodes.forEach(function (node, index) { const originalValue = originalValues[index]; if (originalValue === null) { node.removeAttribute("aria-hidden"); } else { node.setAttribute("aria-hidden", originalValue); } }); }; } function ariaLabelType(props, propName, compName, location, propFullName) { const details = "\nSee https://www.w3.org/TR/wai-aria/#aria-label for details."; if (!props["aria-label"] && !props["aria-labelledby"]) { return new Error( "A <" + compName + "> must have either an `aria-label` or `aria-labelledby` prop.\n " + details, ); } if (props["aria-label"] && props["aria-labelledby"]) { return new Error( "You provided both `aria-label` and `aria-labelledby` props to a <" + compName + ">. If the a label for this component is visible on the screen, that label's component should be given a unique ID prop, and that ID should be passed as the `aria-labelledby` prop into <" + compName + ">. If the label cannot be determined programmatically from the content of the element, an alternative label should be provided as the `aria-label` prop, which will be used as an `aria-label` on the HTML tag." + details, ); } else if (props[propName] != null && !isString(props[propName])) { return new Error( "Invalid prop `" + propName + "` supplied to `" + compName + "`. Expected `string`, received `" + (Array.isArray(propFullName) ? "array" : typeof propFullName) + "`.", ); } return null; } //////////////////////////////////////////////////////////////////////////////// export default Dialog; export { Dialog, DialogContent, DialogOverlay };
the_stack
import { HttpClient } from '@angular/common/http'; import { Injectable, OnDestroy } from '@angular/core'; import { ItemAnnotation, ProfileUpdate, TagCleanupUpdate, TagValue } from '@destinyitemmanager/dim-api-types'; import { environment } from '@env/environment'; import { IconDefinition } from '@fortawesome/pro-light-svg-icons'; import { faCabinetFiling } from '@fortawesome/pro-regular-svg-icons'; import { faBan, faBolt, faHeart, faSave as fasSave } from '@fortawesome/pro-solid-svg-icons'; import { format } from 'date-fns'; import * as LZString from 'lz-string'; import { BehaviorSubject, Subject } from 'rxjs'; import { debounceTime, takeUntil } from 'rxjs/operators'; import { AuthService } from './auth.service'; import { DimSyncService } from './dim-sync.service'; import { InventoryItem } from './model'; import { NotificationService } from './notification.service'; import { SignedOnUserService } from './signed-on-user.service'; const MARK_URL = '/api/mark'; const LOG_CSS = `color: royalblue`; @Injectable() export class MarkService implements OnDestroy { // right now we only use this for DIM-sync public loading$: BehaviorSubject<boolean> = new BehaviorSubject(false); public currentMarks$: BehaviorSubject<Marks | null> = new BehaviorSubject(null); private cleanMarks$: BehaviorSubject<Marks | null> = new BehaviorSubject(null); // the original marks loaded from the server // have an observable for dirty that's debounced to once every second that writes updates to server private marksChanged: Subject<boolean> = new Subject<boolean>(); public dirty$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); public hashTags$: BehaviorSubject<string[]> = new BehaviorSubject<string[]>([]); public markChoices: MarkChoice[]; public markDict: { [id: string]: MarkChoice }; private badState = false; private failCount = 0; private unsubscribe$: Subject<void> = new Subject<void>(); constructor( private httpClient: HttpClient, private notificationService: NotificationService, private dimSyncService: DimSyncService, private authService: AuthService, private signedOnUserService: SignedOnUserService ) { // auto save every 5 seconds if dirty this.markChoices = MarkService.buildMarkChoices(); this.markDict = {}; for (const mc of this.markChoices) { this.markDict[mc.value] = mc; } // asdf this.marksChanged .pipe(takeUntil(this.unsubscribe$), debounceTime(5000)) .subscribe(() => { if (this.dirty$.value === true && !this.badState) { this.saveMarks(); } }); } private async load(platform: number, memberId: string): Promise<Marks> { const requestUrl = `${MARK_URL}/${20 + platform}/${memberId}`; let marks = await this.httpClient.get<Marks>(requestUrl).toPromise(); if (marks.memberId == null) { marks = MarkService.buildEmptyMarks(platform, memberId); } return marks; } // returns true if dimSync decision is needed public async loadPlayer(platform: number, memberId: string): Promise<boolean> { let bootstrapMarks = this.currentMarks$.getValue(); let freshLoad = false; // if this is our initial load, grab out D2C settings, we need to do so to see if we should be using DIM-sync if (!bootstrapMarks) { freshLoad = true; bootstrapMarks = await this.load(platform, memberId); } let marks; // if we're using DIM Sync if (bootstrapMarks?.dimSyncChoice == 'enabled') { // grab the DIM data const dimAnnotations = await this.dimSyncService.getDimTags(); // convert it into D2C format marks = MarkService.buildMarksFromDIM(dimAnnotations, bootstrapMarks); } else { if (freshLoad) { marks = bootstrapMarks; } else { marks = await this.load(platform, memberId); } } // push out marks to UI this.currentMarks$.next(marks); // save a copy of our DIM server state for diffing on save this.cleanMarks$.next(cloneMarks(marks)); // if the user has not mad ea DIM selection, eventually have the UI prompt them return (marks.dimSyncChoice == null); } public async saveMarks(): Promise<void> { // if they have no gear we may have "cleaned up" all their marks, don't save that // as it could wipe all their marks if (this.badState) { this.notificationService.fail( 'Gear likely missing, saving marks disabled' ); return; } // setup our marks header for saving to D2C const marks = this.currentMarks$.getValue(); marks.magic = 'this is magic!'; marks.token = await this.authService.getKey(); marks.apiKey = environment.bungie.apiKey; marks.bungieId = this.signedOnUserService.signedOnUser$.getValue()?.membership.bungieId; marks.modified = new Date().toJSON(); const s = JSON.stringify(marks); const lzSaveMe: string = LZString.compressToBase64(s); const postMe = { data: lzSaveMe, }; let success; // if we're using DIM sync, write to both but only really worry about DIM if (marks.dimSyncChoice == 'enabled') { const updates = MarkService.generateDimUpdates(this.cleanMarks$.getValue(), marks); success = await this.dimSyncService.setDimTags(updates); try { await this.httpClient.post<SaveResult>(MARK_URL, postMe).toPromise(); // DIM sync is incremental, so we need to reset our cleanMarks here this.cleanMarks$.next(cloneMarks(marks)); } catch (x) { // just log an error saving to D2C, it's not our golden copy anymore console.log('Error saving to D2Checklist, ignoring b/c we\'re using DIM sync'); console.dir(x); } } else { // if we're using D2C, its success drives us const result = await this.httpClient.post<SaveResult>(MARK_URL, postMe).toPromise(); success = result.status && result.status === 'success'; } if (success) { this.dirty$.next(false); this.failCount = 0; } else { this.failCount++; // if we failed 5 times in a row, stop spamming the server if (this.failCount > 5) { this.notificationService.fail( 'Mark service is down. Marks will not be saved, please try again later.' ); this.dirty$.next(false); } } } public async restoreMarksFromFile(file: File): Promise<boolean> { const sText = await MarkService.readFileAsString(file); try { const marks: Marks = JSON.parse(sText); if (marks.memberId == null) { throw new Error('File is invalid, no memberId included'); } if (marks.marked == null || Object.keys(marks.marked).length == 0) { throw new Error('File is invalid, no marks included'); } if (marks.memberId != this.currentMarks$.getValue().memberId) { throw new Error( 'Marks don\'t match. Current member id: ' + this.currentMarks$.getValue().memberId + ' but file used ' + marks.memberId ); } this.currentMarks$.next(marks); this.notificationService.success( `Successfully imported ${Object.keys(this.currentMarks$.getValue().marked).length } marks from ${file.name}` ); // also save to server await this.saveMarks(); return true; } catch (x) { this.notificationService.fail('Failed to parse input file: ' + x); return false; } } public downloadMarks() { const anch: HTMLAnchorElement = document.createElement('a'); const sMarks = JSON.stringify(this.currentMarks$.getValue(), null, 2); anch.setAttribute( 'href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(sMarks) ); anch.setAttribute('download', `d2checklist-tags_${format(new Date(), 'yyyy-MM-dd')}.json`); anch.setAttribute('visibility', 'hidden'); document.body.appendChild(anch); anch.click(); } public static buildMarkChoices(): MarkChoice[] { const a = []; a.push({ label: 'Upgrade', value: 'upgrade', icon: faHeart, }); a.push({ label: 'Keep', value: 'keep', icon: fasSave, }); a.push({ label: 'Infuse', value: 'infuse', icon: faBolt, }); a.push({ label: 'Junk', value: 'junk', icon: faBan, }); a.push({ label: 'Archive', value: 'archive', icon: faCabinetFiling, }); return a; } private static buildEmptyMarks(platform: number, memberId: string): Marks { return { marked: {}, notes: {}, favs: {}, dimSyncChoice: null, todo: {}, magic: null, platform: platform, memberId: memberId, }; } private static processMarks( m: { [key: string]: string }, items: InventoryItem[] ): boolean { let unusedDelete = false; const usedKeys: any = {}; let totalKeys = 0, missingKeys = 0; for (const key of Object.keys(m)) { usedKeys[key] = false; totalKeys++; } for (const item of items) { const mark: any = m[item.id]; if (mark != null && mark.trim().length > 0) { if (mark == 'upgrade') { item.markLabel = 'Upgrade'; item.mark = mark; } else if (mark == 'keep') { item.markLabel = 'Keep'; item.mark = mark; } else if (mark == 'infuse') { item.markLabel = 'Infuse'; item.mark = mark; } else if (mark == 'junk') { item.markLabel = 'Junk'; item.mark = mark; } else if (mark == 'archive') { item.markLabel = 'Archive'; item.mark = mark; } else { console.log('%c Ignoring mark: ' + mark, LOG_CSS); continue; } usedKeys[item.id] = true; } } for (const key of Object.keys(usedKeys)) { if (usedKeys[key] === false) { console.log('%c Deleting unused key (tag) : ' + key, LOG_CSS); delete m[key]; unusedDelete = true; missingKeys++; } } console.log('%c Marks: ' + missingKeys + ' unused out of total ' + totalKeys, LOG_CSS); return unusedDelete; } private static grabHashTags(note: string): string[] { return note.split(' ').filter(v => v.startsWith('#')); } private processNotes( m: { [key: string]: string }, items: InventoryItem[] ): boolean { let unusedDelete = false; const usedKeys: any = {}; let totalKeys = 0, missingKeys = 0; for (const key of Object.keys(m)) { usedKeys[key] = false; totalKeys++; } const hashTags = new Set(); for (const item of items) { const note: string = m[item.id]; if (note != null && note.trim().length > 0) { item.notes = note; item.searchText = item.searchText + ' has:notes'; usedKeys[item.id] = true; const noteHashTags = MarkService.grabHashTags(note); for (const n of noteHashTags) { hashTags.add(n); } } } for (const key of Object.keys(usedKeys)) { if (usedKeys[key] === false) { console.log('%c Deleting unused key (note): ' + key, LOG_CSS); delete m[key]; unusedDelete = true; missingKeys++; } } console.log('%c Notes: ' + missingKeys + ' unused out of total ' + totalKeys, LOG_CSS); this.hashTags$.next((Array.from(hashTags) as string[]).sort()); return unusedDelete; } private hasPrivateItems(items: InventoryItem[]) { for (const i of items) { if (!i.equipped.getValue()) { return true; } } return false; } public processItems(items: InventoryItem[]): void { // if we don't have both, don't do anything const currentMarks = this.currentMarks$.getValue(); if (currentMarks == null || items.length == 0) { return; } // if there are no private items, don't bother processing marks in any way, including saving them if (!this.hasPrivateItems(items)) { this.notificationService.info( 'No private items found, disabling marking.' ); this.badState = true; return; } this.badState = false; const updatedMarks: boolean = MarkService.processMarks( currentMarks.marked, items ); const updatedNotes: boolean = this.processNotes( currentMarks.notes, items ); // if we changed anything here, push the new marks and mark things as dirty if (updatedMarks || updatedNotes) { this.currentMarks$.next(currentMarks); this.dirty$.next(true); } } updateItem(item: InventoryItem): void { if (item.id == null) { return; } const currentMarks = this.currentMarks$.getValue(); if (item.mark == null) { item.markLabel = null; delete currentMarks.marked[item.id]; } else { const mc: MarkChoice = this.markDict[item.mark]; if (mc != null) { item.markLabel = mc.label; } else { console.log('%c Ignoring mark: ' + item.mark, LOG_CSS); item.mark = null; return; } currentMarks.marked[item.id] = item.mark; } if (item.notes == null || item.notes.trim().length == 0) { delete currentMarks.notes[item.id]; } else { currentMarks.notes[item.id] = item.notes; } this.dirty$.next(true); this.marksChanged.next(true); } ngOnDestroy(): void { this.unsubscribe$.next(); this.unsubscribe$.complete(); } async disableDimSync(setting: DimSyncChoice): Promise<void> { this.currentMarks$.getValue().dimSyncChoice = setting; await this.saveMarks(); this.notificationService.info('DIM sync disabled. D2Checklist will use its own services for syncing now.'); } async doInitialDimSync(): Promise<boolean> { this.loading$.next(true); try { const selectedUser = this.signedOnUserService.signedOnUser$.getValue(); const d2cMarks = await this.load(selectedUser.userInfo.membershipType, selectedUser.userInfo.membershipId); if (d2cMarks == null || this.badState) { this.notificationService.info( 'Things don\'t look healthy right now, try again later.' ); return false; } const dimAnnotations = await this.dimSyncService.getDimTags(); // we need to convert what we got from DIM into psuedo-marks for comparison sake const origDimMarks = MarkService.buildMarksFromDIM(dimAnnotations, d2cMarks); // now we fold the DIM marks into our D2C marks to see what our final state out to look like const newD2CMarks = MarkService.unionD2CAndDim(d2cMarks, dimAnnotations); newD2CMarks.dimSyncChoice = 'enabled'; // push our current state out to D2C this.currentMarks$.next(newD2CMarks); await this.saveMarks(); // compare the server DIM state w/ our new state and generate a list of transactions necessary for them to be in-sync const updates = MarkService.generateDimUpdates(origDimMarks, newD2CMarks); const updateCount = updates.filter((x) => x.action === 'tag').length; const cleanupElem: TagCleanupUpdate = updates.find( (x) => x.action === 'tag_cleanup' ) as TagCleanupUpdate; const delCount = cleanupElem ? cleanupElem.payload.length : 0; const success = await this.dimSyncService.setDimTags(updates); if (success) { this.notificationService.success( `Exported ${updateCount} tags to DIM-sync. Removed ${delCount}.` ); } return true; } finally { this.loading$.next(false); } } private static buildMarksFromDIM(dimMarks: ItemAnnotation[], d2cMarks: Marks): Marks { const targetMarks = cloneMarks(d2cMarks, true); MarkService.mergeDimIntoD2C(targetMarks, dimMarks, false); return targetMarks; } public static readFileAsString(file: File): Promise<string | null> { return new Promise<string>((resolve, reject) => { if (!file) { resolve(null); } const reader = new FileReader(); reader.onload = (e) => { const text = reader.result.toString(); resolve(text); }; reader.readAsText(file); }); } private static d2cTagToDimTag(tag: string): TagValue { return tag === 'upgrade' ? 'favorite' : (tag as TagValue); } private static dimTagToD2cTag(tag: TagValue): string { return tag === 'favorite' ? 'upgrade' : tag; } // This updates the D2C marks in place private static mergeDimIntoD2C( d2cMarks: Marks, dimMarks: ItemAnnotation[], deleteUnmatched: boolean ): ImportResult { // we're going to slowly prune items out of our old list if we're deleting // the ones left are the items that were, effectively, deleted const oldMarks = d2cMarks.marked; const oldNotes = d2cMarks.notes; if (deleteUnmatched) { d2cMarks.marked = {}; d2cMarks.notes = {}; } for (const d of dimMarks) { if (d.tag) { d2cMarks.marked[d.id] = MarkService.dimTagToD2cTag(d.tag); if (deleteUnmatched) { delete oldMarks[d.id]; } } if (d.notes) { d2cMarks.notes[d.id] = d.notes; if (deleteUnmatched) { delete oldNotes[d.id]; } } } return { imported: dimMarks.length, deleted: deleteUnmatched ? Object.keys(oldMarks).length + Object.keys(oldNotes).length : 0, }; } private static generateDimUpdates(oldMarks: Marks, newMarks: Marks): ProfileUpdate[] { const keys: Set<string> = new Set(); for (const k of Object.keys(oldMarks.marked)) { keys.add(k); } for (const k of Object.keys(oldMarks.notes)) { keys.add(k); } for (const k of Object.keys(newMarks.marked)) { keys.add(k); } for (const k of Object.keys(newMarks.notes)) { keys.add(k); } const returnMe: ProfileUpdate[] = []; const deleteTags: string[] = []; keys.forEach((k) => { const oldMark = oldMarks.marked[k]; const oldNote = oldMarks.notes[k]; const newMark = newMarks.marked[k]; const newNote = newMarks.notes[k]; if (oldMark == newMark && oldNote == newNote) { // do nothing, nothing changed } else if (newMark == null && newNote == null) { // delete me deleteTags.push(k); return; } else { // upsert me returnMe.push({ action: 'tag', payload: { id: k, tag: MarkService.d2cTagToDimTag(newMark), notes: newNote ? newNote : null }, }); } }); if (deleteTags.length > 0) { returnMe.push({ action: 'tag_cleanup', payload: deleteTags, }); } console.dir(returnMe); return returnMe; } private static unionD2CAndDim( origD2cMarks: Marks, dimMarks: ItemAnnotation[]): Marks { // deep clone marks const d2cMarks = cloneMarks(origD2cMarks); let updateCount = 0; // fold in our dim notes and tags where we don't already have data for (const dimAnnot of dimMarks) { if (dimAnnot.notes) { if (!d2cMarks.notes[dimAnnot.id]) { d2cMarks.notes[dimAnnot.id] = dimAnnot.notes; updateCount++; } } if (dimAnnot.tag) { if (!d2cMarks.marked[dimAnnot.id]) { d2cMarks.marked[dimAnnot.id] = MarkService.dimTagToD2cTag(dimAnnot.tag); updateCount++; } } } console.log(`%c Folded in ${updateCount} updates from DIM sync`, LOG_CSS); return d2cMarks; } } export declare type DimSyncChoice = | 'disabled' | 'enabled' | null; function cloneMarks(x: Marks, headerOnly?: boolean): Marks { return { marked: headerOnly ? {} : { ...x.marked }, notes: headerOnly ? {} : { ...x.notes }, favs: headerOnly ? {} : { ...x.favs }, dimSyncChoice: x.dimSyncChoice, todo: x.todo, magic: x.magic, platform: x.platform, memberId: x.memberId, modified: x.modified, token: x.token, bungieId: x.bungieId, apiKey: x.apiKey }; } export interface Marks { marked: { [key: string]: string }; notes: { [key: string]: string }; favs: { [key: string]: boolean }; // not used for anything in d2 dimSyncChoice: DimSyncChoice; todo: any; // not used for anything in d2 magic: string; platform: number; memberId: string; modified?: string; token?: string; bungieId?: string; apiKey?: string; } export interface MarkChoice { label: string; value: string; icon: IconDefinition; } interface SaveResult { status: string; } interface ImportResult { imported: number; deleted: number; }
the_stack
import { Component, h } from "preact"; import { IS_WEB, isNumericalKey, randomString } from "../src/util"; import { BaseObjectDescriptor, InspectorData, PropertyDescriptor, ValueDescriptor } from "./serializer"; type ElementLike = JSX.Element | string | null; type ElementList = ElementLike[]; export class Inspector extends Component<InspectorData, void>{ private parents = new Set(); // Used for circular reference detection. private renderKey(d: ValueDescriptor, arrayIndex: number | null = null): ElementList { switch (d.type) { case "string": const value = d.value; // Keys that look like javascript identifiers are rendered without // quote marks. Numerical keys can be omitted entirely. const isSimpleKey = /^[a-z$_][\w$_]*$/i.test(value); const isArrayKey = (typeof arrayIndex === "number") && isNumericalKey(value); if (isArrayKey || isSimpleKey) { // 12: {...} // simple_key: {...} let elements = [ <span class="inspector__key cm-property">{ value }</span>, ": " ]; // If the array keys are in the right order without holes, hide them // from the collapsed view. if (isArrayKey && Number(value) === arrayIndex) { elements = addClass(elements, "inspector--show-if-parent-expanded"); } return elements; } else { // "my!weird*key\n": {...} return [ <span class="inspector__key cm-string"> { JSON.stringify(value) } </span>, ": " ]; } case "symbol": // [Symbol(some symbol)]: {...} return [ "[", <span class="inspector__key cm-property">{ d.value }</span>, "] :" ]; default: // Keys are always either a string, symbol, or prototype key. throw new Error("Unexpected key type"); } } private renderValue(d: ValueDescriptor): ElementList { // Render primitive values. switch (d.type) { case "boolean": return [<span class="cm-atom">{ d.value }</span>]; case "date": return [<span class="cm-string-2">{ d.value }</span>]; case "getter": return [<span class="cm-keyword">[getter]</span>]; case "gettersetter": return [<span class="cm-keyword">[getter/setter]</span>]; case "null": return [<span class="cm-atom">null</span>]; case "number": return [<span class="cm-number">{ d.value }</span>]; case "regexp": return [<span class="cm-string-2">{ d.value }</span>]; case "setter": return [<span class="cm-keyword">[setter]</span>]; case "string": return [<span class="cm-string">{ JSON.stringify(d.value) }</span>]; case "symbol": return [<span class="cm-string">{ d.value }</span>]; case "undefined": return [<span class="cm-atom">undefined</span>]; } // Detect circular references. if (this.parents.has(d)) { return [<span class="cm-keyword">[circular]</span>]; } this.parents.add(d); // Render the list of properties and other content that is expanded when the // expand button is clicked. const listItems: ElementList = []; if (d.type === "tensor") { // TODO: the tensor is currently formatted by Tensor.toString(), // and displayed in a monospace font. Make it nicer by using a table. // Remove the outer layer of square brackets added by toString(). const formatted = d.formatted.replace(/(^\[)|(\]$)/g, "") .replace(/,\n+ /g, "\n"); listItems.push( <li class="inspector__li inspector__prop"> <div class="inspector__content inspector__content--pre"> { formatted } </div> </li> ); } // Add regular array/object properties. const isArray = d.type === "array"; listItems.push(...d.props.map((prop, index) => this.renderProperty(prop, isArray ? index : null) )); // Wrap the items in an <ul> element, but only if the list contains at // least one item. const list: ElementLike = (listItems.length > 0) ? <ul class="inspector__list inspector__prop-list"> { ...listItems } </ul> : null; // Render the object header, containing the class name, sometimes // some metadata between parentheses, and boxed primitive content. const elements: ElementList = []; switch (d.type) { case "array": // If the constructor is "Array", it is hidden when collapsed. // Square brackets are used and they are always visible. // [1, 2, 3, 4, 5, foo: "bar"] // Array(3) [1, 2, 3, ...properties...] // Float32Array(30) [...] let ctorElements = [ <span class="cm-def">{ d.ctor }</span>, "(", <span class="cm-number">{ d.length }</span>, ") " ]; if (d.ctor === "Array") { ctorElements = addClass(ctorElements, "inspector--show-if-expanded"); } elements.push(...ctorElements, "[", list, "]"); break; case "box": // The class name is omitted when it is "Date" or "RegExp". // Number, Boolean, String are shown to distinguish from primitives. // Properties are wrapped in curly braces; these are hidden when // there are no properties.. // Number:42 {...properties...} // /abcd/i {...properties...} if (d.ctor !== "Date" && d.ctor !== "RegExp") { elements.push(<span class="cm-def">{ d.ctor }</span>, ":"); } elements.push( ...this.renderValue(d.primitive), ...this.renderPropListWithBraces(d, list) ); break; case "function": // Constructor name is only shown if it is nontrivial. // function() {...properties...} // class Foo // async function* bar() // MyFunction:function baz() if (!/^(Async)?(Generator)?Function$/.test(d.ctor)) { elements.push(<span class="cm-def">{ d.ctor }</span>, ":"); } elements.push( <span class="cm-keyword"> { d.async ? "async " : "" } { d.class ? "class" : "function"} { d.generator ? "*" : "" } </span>, d.name ? " " : "", d.name ? <span class="cm-def">{ d.name }</span> : "", d.class ? "" : "()", ...this.renderPropListWithBraces(d, list) ); break; case "tensor": // Tensor(float32) [1] // Tensor(float32 15) [1, 2, 3, ...etc...] // Tensor(float32 2✕2) [[1, 2], [3, 4]] // Tensor(uint32 3✕4✕4) [[[[...tensor...]]], foo: bar] const isScalar = d.shape.length === 0 || (d.shape.length === 1 && d.shape[0] === 1); elements.push( <span class="cm-def">{ d.ctor }</span>, "(", <span class="cm-string-2">{ d.dtype }</span> ); if (!isScalar) { for (const [dim, size] of d.shape.entries()) { elements.push( dim === 0 ? " " : "✕", <span class="cm-number">{ size }</span> ); } } elements.push(") [", list, "]"); break; case "object": // Constructor name is omitted when it's "Object", or when the // object doesn't have a prototype at all (ctor === null). // Curly braces are always shown, even when there are no properties. // {a: "hello", b: "world"} // MyObject {"#^%&": "something"} if (d.ctor !== null && d.ctor !== "Object") { elements.push(<span class="cm-def">{ d.ctor }</span>, " "); } elements.push("{", list, "}"); break; } // Pop cycle detection stack. this.parents.delete(d); return elements; } private renderPropListWithBraces(d: BaseObjectDescriptor, list?: ElementLike): ElementList { if (!list) return []; // If the list contains items that are visible in collapsed mode, always // show the curly braces. Otherwise show them only when expanded. const hasVisibleProps = d.props.some(prop => !prop.hidden); const braceClass = hasVisibleProps ? "" : "inspector--show-if-expanded"; return [ ...addClass([" {"], braceClass), list, ...addClass(["}"], braceClass), ]; } // Returns true if a descriptor needs an expand button. private isExpandable(d: ValueDescriptor): boolean { // If a reference is circular it can't be expanded. if (this.parents.has(d)) { return false; } // Tensors can be always expanded to show its values. if (d.type === "tensor") { return true; } // Objects can be expanded if they have properties. if ((d.type === "array" || d.type === "box" || d.type === "function" || d.type === "object") && d.props.length > 0) { return true; } return false; } private renderExpandButton(): ElementLike { // Use a simple <a href="javascript:"> link, so it "just works" on pages // that have been pre-rendered into static html. const id = randomString(); return <a id={ id } class="inspector__toggle" href={ `javascript:Inspector.toggle("${id}")` } />; } private renderProperty(prop: PropertyDescriptor, arrayIndex: number | null = null): ElementLike { const key = this.props.descriptors[prop.key]; const value = this.props.descriptors[prop.value]; const attr = { class: "inspector__li inspector__prop" }; if (prop.hidden) attr.class += " inspector__prop--hidden"; return ( <li { ...attr }> { this.isExpandable(value) && this.renderExpandButton() } <div class="inspector__content"> { ...this.renderKey(key, arrayIndex) } { ...this.renderValue(value) } </div> </li> ); } private renderRoot(): ElementLike { if (this.props.roots.length === 0) return ""; // Map root ids to descriptors. const descriptors = this.props.descriptors; const roots = this.props.roots.map(id => descriptors[id]); // Count the number of items with children. const rootsWithChildren = roots.map(d => +this.isExpandable(d)) .reduce((count, d) => count + d); let rootElement: ElementLike; if (rootsWithChildren <= 1) { // With at most one expandable item, place all roots in a single div. const elements = [].concat(...roots.map((d, index) => [ index > 0 ? " " : "", // Space between items. ...this.renderValue(d) ])); rootElement = <div class="inspector__content">{ ...elements }</div>; } else { // With more than one expandable root, place all of them in a separate. // list item. const listItems = roots.map(d => <li class="inspector__li inspector__root"> { this.isExpandable(d) && this.renderExpandButton() } <div class="inspector__content"> { ...this.renderValue(d) } </div> </li> ); rootElement = <div class="inspector__content"> <ul class="inspector__list"> { ...listItems } </ul> </div>; } // If there are expandable items, add a top-level expand button. if (rootsWithChildren > 0) { rootElement = <ul class="inspector__list"> <li class="inspector__li"> { this.renderExpandButton() } { rootElement } </li> </ul>; } return rootElement; } render(): JSX.Element { return <div class="inspector cm-s-syntax">{ this.renderRoot() }</div>; } static toggle(id: string): void { const el = document.getElementById(id); const parent = el.parentNode as HTMLElement; parent.classList.toggle("inspector__li--expanded"); } } // Helper function to attach a css class to a list of elements. // The element list may contain strings; they are converted to spans. function addClass(elements: ElementList, classes: string): ElementList { // Remove redundant whitespace from classes. classes = classes.split(/\s+/).filter(s => s !== "").join(); // Return early when no classes are added. if (classes === "") return elements; const result: ElementList = []; let stringBuffer = ""; for (const el of elements) { if (el === null) { // Remove empty elements. } else if (typeof el === "string") { // Merge adjacent strings so we don't create so many spans. stringBuffer += el; } else { if (stringBuffer) { // Wrap the buffered-up string in a <span> element and flush. result.push(<span class={ classes }>{ stringBuffer }</span>); stringBuffer = ""; } // Add our css class to the existing element. const elClass = el.attributes.class; el.attributes.class = elClass ? `${elClass} ${classes}` : classes; result.push(el); } } if (stringBuffer) { result.push(<span class={ classes }>{ stringBuffer }</span>); } return result; } // Make Inspector available on the global object. This allows expand button // to use a simple textual click handler, which survives serialization. // We make the property non-enumerable to minimize interaction with other // components. if (IS_WEB) { Object.defineProperty(window, "Inspector", { enumerable: false, value: Inspector }); }
the_stack
import { IAgentContext, IDIDManager, IKeyManager, IAgentPlugin, VerifiablePresentation } from '@veramo/core' import { IDataStoreORM, TClaimsColumns, FindArgs } from '@veramo/data-store' import { ICredentialIssuer } from '@veramo/credential-w3c' import { ICredentialsForSdr, IPresentationValidationResult, ISelectiveDisclosure, ICreateSelectiveDisclosureRequestArgs, IGetVerifiableCredentialsForSdrArgs, IValidatePresentationAgainstSdrArgs, ISelectiveDisclosureRequest, ICreateProfileCredentialsArgs, } from './types' import { schema } from './' import { createJWT } from 'did-jwt' import { blake2bHex } from 'blakejs' import Debug from 'debug' /** * This class adds support for creating * {@link https://github.com/uport-project/specs/blob/develop/flows/selectivedisclosure.md | Selective Disclosure} requests * and interpret the responses received. * * This implementation of the uPort protocol uses * {@link https://www.w3.org/TR/vc-data-model/#presentations | W3C Presentation} * as the response encoding instead of a `shareReq`. * * @beta */ export class SelectiveDisclosure implements IAgentPlugin { readonly methods: ISelectiveDisclosure readonly schema = schema.ISelectiveDisclosure constructor() { this.methods = { createSelectiveDisclosureRequest: this.createSelectiveDisclosureRequest, getVerifiableCredentialsForSdr: this.getVerifiableCredentialsForSdr, validatePresentationAgainstSdr: this.validatePresentationAgainstSdr, createProfilePresentation: this.createProfilePresentation, } } /** * Creates a Selective disclosure request, encoded as a JWT. * * @remarks See {@link https://github.com/uport-project/specs/blob/develop/flows/selectivedisclosure.md | Selective Disclosure} * * @param args - The param object with the properties necessary to create the request. See {@link ISelectiveDisclosureRequest} * @param context - *RESERVED* This is filled by the framework when the method is called. * * @beta */ async createSelectiveDisclosureRequest( args: ICreateSelectiveDisclosureRequestArgs, context: IAgentContext<IDIDManager & IKeyManager>, ): Promise<string> { try { const identifier = await context.agent.didManagerGet({ did: args.data.issuer }) const data: Partial<ISelectiveDisclosureRequest> = args.data delete data.issuer Debug('veramo:selective-disclosure:create-sdr')('Signing SDR with', identifier.did) const key = identifier.keys.find((k) => k.type === 'Secp256k1') if (!key) throw Error('Signing key not found') const signer = (data: string | Uint8Array) => { let dataString, encoding: 'base16' | undefined if (typeof data === 'string') { dataString = data encoding = undefined } else { ;(dataString = Buffer.from(data).toString('hex')), (encoding = 'base16') } return context.agent.keyManagerSign({ keyRef: key.kid, data: dataString, encoding }) } const jwt = await createJWT( { type: 'sdr', ...data, }, { signer, alg: 'ES256K', issuer: identifier.did, }, ) return jwt } catch (error) { return Promise.reject(error) } } /** * Gathers the required credentials necessary to fulfill a Selective Disclosure Request. * It uses the {@link @veramo/data-store#IDataStoreORM} plugin to query the local database for * the required credentials. * * @param args - Contains the Request to be fulfilled and the DID of the subject * @param context - *RESERVED* This is filled by the framework when the method is called. * * @beta */ async getVerifiableCredentialsForSdr( args: IGetVerifiableCredentialsForSdrArgs, context: IAgentContext<IDataStoreORM>, ): Promise<ICredentialsForSdr[]> { const result: ICredentialsForSdr[] = [] const findArgs: FindArgs<TClaimsColumns> = { where: [] } for (const credentialRequest of args.sdr.claims) { if (credentialRequest.claimType) { findArgs.where?.push({ column: 'type', value: [credentialRequest.claimType] }) } if (credentialRequest.claimValue) { findArgs.where?.push({ column: 'value', value: [credentialRequest.claimValue] }) } if (credentialRequest.issuers && credentialRequest.issuers.length > 0) { findArgs.where?.push({ column: 'issuer', value: credentialRequest.issuers.map((i) => i.did) }) } if (credentialRequest.credentialType) { findArgs.where?.push({ column: 'credentialType', value: ['%' + credentialRequest.credentialType + '%'], op: 'Like', }) } if (credentialRequest.credentialContext) { findArgs.where?.push({ column: 'context', value: ['%' + credentialRequest.credentialContext + '%'], op: 'Like', }) } if (args.did || args.sdr.subject) { findArgs.where?.push({ column: 'subject', value: ['' + (args.did || args.sdr.subject)] }) } const credentials = await context.agent.dataStoreORMGetVerifiableCredentialsByClaims(findArgs) result.push({ ...credentialRequest, credentials, }) } return result } /** * Validates a * {@link https://github.com/uport-project/specs/blob/develop/flows/selectivedisclosure.md | Selective Disclosure response} * encoded as a `Presentation` * * @param args - Contains the request and the response `Presentation` that needs to be checked. * @param context - *RESERVED* This is filled by the framework when the method is called. * * @beta */ async validatePresentationAgainstSdr( args: IValidatePresentationAgainstSdrArgs, context: IAgentContext<{}>, ): Promise<IPresentationValidationResult> { let valid = true let claims = [] for (const credentialRequest of args.sdr.claims) { let credentials = (args.presentation?.verifiableCredential || []).filter((credential) => { if ( credentialRequest.claimType && credentialRequest.claimValue && credential.credentialSubject[credentialRequest.claimType] !== credentialRequest.claimValue ) { return false } if ( credentialRequest.claimType && !credentialRequest.claimValue && credential.credentialSubject[credentialRequest.claimType] === undefined ) { return false } if ( credentialRequest.issuers && !credentialRequest.issuers.map((i) => i.did).includes(credential.issuer.id) ) { return false } if ( credentialRequest.credentialContext && !credential['@context'].includes(credentialRequest.credentialContext) ) { return false } if (credentialRequest.credentialType && !credential.type.includes(credentialRequest.credentialType)) { return false } return true }) if (credentialRequest.essential === true && credentials.length == 0) { valid = false } claims.push({ ...credentialRequest, credentials: credentials.map((vc) => ({ hash: blake2bHex(JSON.stringify(vc)), verifiableCredential: vc, })), }) } return { valid, claims } } /** * Creates profile credentials * * @beta */ async createProfilePresentation( args: ICreateProfileCredentialsArgs, context: IAgentContext<ICredentialIssuer & IDIDManager>, ): Promise<VerifiablePresentation> { const identifier = await context.agent.didManagerGet({ did: args.holder }) const credentials = [] if (args.name) { const credential = await context.agent.createVerifiableCredential({ credential: { issuer: { id: identifier.did }, '@context': ['https://www.w3.org/2018/credentials/v1'], type: ['VerifiableCredential', 'Profile'], issuanceDate: new Date().toISOString(), credentialSubject: { id: identifier.did, name: args.name, }, }, proofFormat: 'jwt', }) credentials.push(credential) } if (args.picture) { const credential = await context.agent.createVerifiableCredential({ credential: { issuer: { id: identifier.did }, '@context': ['https://www.w3.org/2018/credentials/v1'], type: ['VerifiableCredential', 'Profile'], issuanceDate: new Date().toISOString(), credentialSubject: { id: identifier.did, picture: args.picture, }, }, proofFormat: 'jwt', }) credentials.push(credential) } if (args.url) { const credential = await context.agent.createVerifiableCredential({ credential: { issuer: { id: identifier.did }, '@context': ['https://www.w3.org/2018/credentials/v1'], type: ['VerifiableCredential', 'Profile'], issuanceDate: new Date().toISOString(), credentialSubject: { id: identifier.did, url: args.url, }, }, proofFormat: 'jwt', }) credentials.push(credential) } const profile = await context.agent.createVerifiablePresentation({ presentation: { verifier: args.holder ? [args.holder] : [], holder: identifier.did, '@context': ['https://www.w3.org/2018/credentials/v1'], type: ['VerifiablePresentation', 'Profile'], issuanceDate: new Date().toISOString(), verifiableCredential: credentials, }, proofFormat: 'jwt', save: args.save, }) if (args.verifier && args.send) { await context.agent.sendMessageDIDCommAlpha1({ save: args.save, data: { from: identifier.did, to: args.verifier, type: 'jwt', body: profile.proof.jwt, }, }) } return profile } }
the_stack
import type { Context, Script } from 'vm'; import type { LegacyFakeTimers, ModernFakeTimers } from '@jest/fake-timers'; import type { Circus, Config, Global } from '@jest/types'; import jestMock = require('jest-mock'); declare type JestMockFn = typeof jestMock.fn; declare type JestMockSpyOn = typeof jestMock.spyOn; export declare type EnvironmentContext = Partial<{ console: Console; docblockPragmas: Record<string, string | Array<string>>; testPath: Config.Path; }>; export declare type ModuleWrapper = (this: Module['exports'], module: Module, exports: Module['exports'], require: Module['require'], __dirname: string, __filename: Module['filename'], global: Global.Global, jest?: Jest, ...extraGlobals: Array<Global.Global[keyof Global.Global]>) => unknown; export declare class JestEnvironment { constructor(config: Config.ProjectConfig, context?: EnvironmentContext); global: Global.Global; fakeTimers: LegacyFakeTimers<unknown> | null; fakeTimersModern: ModernFakeTimers | null; moduleMocker: jestMock.ModuleMocker | null; /** * @deprecated implement getVmContext instead */ runScript<T = unknown>(script: Script): T | null; getVmContext?(): Context | null; setup(): Promise<void>; teardown(): Promise<void>; handleTestEvent?(event: Circus.Event, state: Circus.State): void | Promise<void>; } export declare type Module = NodeModule; export interface Jest { /** * Provides a way to add Jasmine-compatible matchers into your Jest context. * * @deprecated Use `expect.extend` instead */ addMatchers(matchers: Record<string, unknown>): void; /** * Advances all timers by the needed milliseconds so that only the next timeouts/intervals will run. * Optionally, you can provide steps, so it will run steps amount of next timeouts/intervals. */ advanceTimersToNextTimer(steps?: number): void; /** * Disables automatic mocking in the module loader. */ autoMockOff(): Jest; /** * Enables automatic mocking in the module loader. */ autoMockOn(): Jest; /** * Clears the mock.calls and mock.instances properties of all mocks. * Equivalent to calling .mockClear() on every mocked function. */ clearAllMocks(): Jest; /** * Removes any pending timers from the timer system. If any timers have been * scheduled, they will be cleared and will never have the opportunity to * execute in the future. */ clearAllTimers(): void; /** * Indicates that the module system should never return a mocked version * of the specified module, including all of the specified module's * dependencies. */ deepUnmock(moduleName: string): Jest; /** * Disables automatic mocking in the module loader. * * After this method is called, all `require()`s will return the real * versions of each module (rather than a mocked version). */ disableAutomock(): Jest; /** * When using `babel-jest`, calls to mock will automatically be hoisted to * the top of the code block. Use this method if you want to explicitly avoid * this behavior. */ doMock(moduleName: string, moduleFactory?: () => unknown): Jest; /** * Indicates that the module system should never return a mocked version * of the specified module from require() (e.g. that it should always return * the real module). */ dontMock(moduleName: string): Jest; /** * Enables automatic mocking in the module loader. */ enableAutomock(): Jest; /** * Creates a mock function. Optionally takes a mock implementation. */ fn: JestMockFn; /** * Given the name of a module, use the automatic mocking system to generate a * mocked version of the module for you. * * This is useful when you want to create a manual mock that extends the * automatic mock's behavior. * * @deprecated Use `jest.createMockFromModule()` instead */ genMockFromModule(moduleName: string): unknown; /** * Given the name of a module, use the automatic mocking system to generate a * mocked version of the module for you. * * This is useful when you want to create a manual mock that extends the * automatic mock's behavior. */ createMockFromModule(moduleName: string): unknown; /** * Determines if the given function is a mocked function. */ isMockFunction(fn: (...args: Array<any>) => unknown): fn is ReturnType<JestMockFn>; /** * Mocks a module with an auto-mocked version when it is being required. */ mock(moduleName: string, moduleFactory?: () => unknown, options?: { virtual?: boolean; }): Jest; /** * Returns the actual module instead of a mock, bypassing all checks on * whether the module should receive a mock implementation or not. * * @example ``` jest.mock('../myModule', () => { // Require the original module to not be mocked... const originalModule = jest.requireActual(moduleName); return { __esModule: true, // Use it when dealing with esModules ...originalModule, getRandom: jest.fn().mockReturnValue(10), }; }); const getRandom = require('../myModule').getRandom; getRandom(); // Always returns 10 ``` */ requireActual: (moduleName: string) => unknown; /** * Returns a mock module instead of the actual module, bypassing all checks * on whether the module should be required normally or not. */ requireMock: (moduleName: string) => unknown; /** * Resets the state of all mocks. * Equivalent to calling .mockReset() on every mocked function. */ resetAllMocks(): Jest; /** * Resets the module registry - the cache of all required modules. This is * useful to isolate modules where local state might conflict between tests. * * @deprecated Use `jest.resetModules()` */ resetModuleRegistry(): Jest; /** * Resets the module registry - the cache of all required modules. This is * useful to isolate modules where local state might conflict between tests. */ resetModules(): Jest; /** * Restores all mocks back to their original value. Equivalent to calling * `.mockRestore` on every mocked function. * * Beware that jest.restoreAllMocks() only works when the mock was created with * jest.spyOn; other mocks will require you to manually restore them. */ restoreAllMocks(): Jest; /** * Runs failed tests n-times until they pass or until the max number of * retries is exhausted. This only works with `jest-circus`! */ retryTimes(numRetries: number): Jest; /** * Exhausts tasks queued by setImmediate(). * * > Note: This function is not available when using Lolex as fake timers implementation */ runAllImmediates(): void; /** * Exhausts the micro-task queue (usually interfaced in node via * process.nextTick). */ runAllTicks(): void; /** * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() * and setInterval()). */ runAllTimers(): void; /** * Executes only the macro-tasks that are currently pending (i.e., only the * tasks that have been queued by setTimeout() or setInterval() up to this * point). If any of the currently pending macro-tasks schedule new * macro-tasks, those new tasks will not be executed by this call. */ runOnlyPendingTimers(): void; /** * Advances all timers by msToRun milliseconds. All pending "macro-tasks" * that have been queued via setTimeout() or setInterval(), and would be * executed within this timeframe will be executed. */ advanceTimersByTime(msToRun: number): void; /** * Executes only the macro task queue (i.e. all tasks queued by setTimeout() * or setInterval() and setImmediate()). * * @deprecated Use `jest.advanceTimersByTime()` */ runTimersToTime(msToRun: number): void; /** * Returns the number of fake timers still left to run. */ getTimerCount(): number; /** * Explicitly supplies the mock object that the module system should return * for the specified module. * * Note It is recommended to use `jest.mock()` instead. The `jest.mock` * API's second argument is a module factory instead of the expected * exported module object. */ setMock(moduleName: string, moduleExports: unknown): Jest; /** * Set the default timeout interval for tests and before/after hooks in * milliseconds. * * Note: The default timeout interval is 5 seconds if this method is not * called. */ setTimeout(timeout: number): Jest; /** * Creates a mock function similar to `jest.fn` but also tracks calls to * `object[methodName]`. * * Note: By default, jest.spyOn also calls the spied method. This is * different behavior from most other test libraries. */ spyOn: JestMockSpyOn; /** * Indicates that the module system should never return a mocked version of * the specified module from require() (e.g. that it should always return the * real module). */ unmock(moduleName: string): Jest; /** * Instructs Jest to use fake versions of the standard timer functions. */ useFakeTimers(implementation?: 'modern' | 'legacy'): Jest; /** * Instructs Jest to use the real versions of the standard timer functions. */ useRealTimers(): Jest; /** * `jest.isolateModules(fn)` goes a step further than `jest.resetModules()` * and creates a sandbox registry for the modules that are loaded inside * the callback function. This is useful to isolate specific modules for * every test so that local module state doesn't conflict between tests. */ isolateModules(fn: () => void): Jest; /** * When mocking time, `Date.now()` will also be mocked. If you for some reason need access to the real current time, you can invoke this function. * * > Note: This function is only available when using Lolex as fake timers implementation */ getRealSystemTime(): number; /** * Set the current system time used by fake timers. Simulates a user changing the system clock while your program is running. It affects the current time but it does not in itself cause e.g. timers to fire; they will fire exactly as they would have done without the call to `jest.setSystemTime()`. * * > Note: This function is only available when using Lolex as fake timers implementation */ setSystemTime(now?: number | Date): void; } export {};
the_stack
import { deepEqual, deepStrictEqual, doesNotThrow, equal, strictEqual, throws } from 'assert'; import { ConfigurationTarget, Disposable, env, EnvironmentVariableMutator, EnvironmentVariableMutatorType, EventEmitter, ExtensionContext, extensions, ExtensionTerminalOptions, Pseudoterminal, Terminal, TerminalDimensions, TerminalOptions, TerminalState, UIKind, window, workspace } from 'vscode'; import { assertNoRpc } from '../utils'; // Disable terminal tests: // - Web https://github.com/microsoft/vscode/issues/92826 (env.uiKind === UIKind.Web ? suite.skip : suite)('vscode API - terminal', () => { let extensionContext: ExtensionContext; suiteSetup(async () => { // Trigger extension activation and grab the context as some tests depend on it await extensions.getExtension('vscode.vscode-api-tests')?.activate(); extensionContext = (global as any).testExtensionContext; const config = workspace.getConfiguration('terminal.integrated'); // Disable conpty in integration tests because of https://github.com/microsoft/vscode/issues/76548 await config.update('windowsEnableConpty', false, ConfigurationTarget.Global); // Disable exit alerts as tests may trigger then and we're not testing the notifications await config.update('showExitAlert', false, ConfigurationTarget.Global); // Canvas may cause problems when running in a container await config.update('gpuAcceleration', 'off', ConfigurationTarget.Global); // Disable env var relaunch for tests to prevent terminals relaunching themselves await config.update('environmentChangesRelaunch', false, ConfigurationTarget.Global); }); suite('Terminal', () => { let disposables: Disposable[] = []; teardown(() => { assertNoRpc(); disposables.forEach(d => d.dispose()); disposables.length = 0; }); test('sendText immediately after createTerminal should not throw', async () => { const terminal = window.createTerminal(); const result = await new Promise<Terminal>(r => { disposables.push(window.onDidOpenTerminal(t => { if (t === terminal) { r(t); } })); }); equal(result, terminal); doesNotThrow(terminal.sendText.bind(terminal, 'echo "foo"')); await new Promise<void>(r => { disposables.push(window.onDidCloseTerminal(t => { if (t === terminal) { r(); } })); terminal.dispose(); }); }); test('echo works in the default shell', async () => { const terminal = await new Promise<Terminal>(r => { disposables.push(window.onDidOpenTerminal(t => { if (t === terminal) { r(terminal); } })); // Use a single character to avoid winpty/conpty issues with injected sequences const terminal = window.createTerminal({ env: { TEST: '`' } }); terminal.show(); }); let data = ''; await new Promise<void>(r => { disposables.push(window.onDidWriteTerminalData(e => { if (e.terminal === terminal) { data += e.data; if (data.indexOf('`') !== 0) { r(); } } })); // Print an environment variable value so the echo statement doesn't get matched if (process.platform === 'win32') { terminal.sendText(`$env:TEST`); } else { terminal.sendText(`echo $TEST`); } }); await new Promise<void>(r => { terminal.dispose(); disposables.push(window.onDidCloseTerminal(t => { strictEqual(terminal, t); r(); })); }); }); test('onDidCloseTerminal event fires when terminal is disposed', async () => { const terminal = window.createTerminal(); const result = await new Promise<Terminal>(r => { disposables.push(window.onDidOpenTerminal(t => { if (t === terminal) { r(t); } })); }); equal(result, terminal); await new Promise<void>(r => { disposables.push(window.onDidCloseTerminal(t => { if (t === terminal) { r(); } })); terminal.dispose(); }); }); test('processId immediately after createTerminal should fetch the pid', async () => { const terminal = window.createTerminal(); const result = await new Promise<Terminal>(r => { disposables.push(window.onDidOpenTerminal(t => { if (t === terminal) { r(t); } })); }); equal(result, terminal); let pid = await result.processId; equal(true, pid && pid > 0); await new Promise<void>(r => { disposables.push(window.onDidCloseTerminal(t => { if (t === terminal) { r(); } })); terminal.dispose(); }); }); test('name in constructor should set terminal.name', async () => { const terminal = window.createTerminal('a'); const result = await new Promise<Terminal>(r => { disposables.push(window.onDidOpenTerminal(t => { if (t === terminal) { r(t); } })); }); equal(result, terminal); await new Promise<void>(r => { disposables.push(window.onDidCloseTerminal(t => { if (t === terminal) { r(); } })); terminal.dispose(); }); }); test('creationOptions should be set and readonly for TerminalOptions terminals', async () => { const options = { name: 'foo', hideFromUser: true }; const terminal = window.createTerminal(options); const terminalOptions = terminal.creationOptions as TerminalOptions; const result = await new Promise<Terminal>(r => { disposables.push(window.onDidOpenTerminal(t => { if (t === terminal) { r(t); } })); }); equal(result, terminal); await new Promise<void>(r => { disposables.push(window.onDidCloseTerminal(t => { if (t === terminal) { r(); } })); terminal.dispose(); }); throws(() => terminalOptions.name = 'bad', 'creationOptions should be readonly at runtime'); }); test('onDidOpenTerminal should fire when a terminal is created', async () => { const terminal = window.createTerminal('b'); const result = await new Promise<Terminal>(r => { disposables.push(window.onDidOpenTerminal(t => { if (t === terminal) { r(t); } })); }); equal(result, terminal); await new Promise<void>(r => { disposables.push(window.onDidCloseTerminal(t => { if (t === terminal) { r(); } })); terminal.dispose(); }); }); test('exitStatus.code should be set to undefined after a terminal is disposed', async () => { const terminal = window.createTerminal(); const result = await new Promise<Terminal>(r => { disposables.push(window.onDidOpenTerminal(t => { if (t === terminal) { r(t); } })); }); equal(result, terminal); await new Promise<void>(r => { disposables.push(window.onDidCloseTerminal(t => { if (t === terminal) { deepEqual(t.exitStatus, { code: undefined }); r(); } })); terminal.dispose(); }); }); test('onDidChangeTerminalState should fire after writing to a terminal', async () => { const terminal = window.createTerminal(); deepStrictEqual(terminal.state, { isInteractedWith: false }); const eventState = await new Promise<TerminalState>(r => { disposables.push(window.onDidChangeTerminalState(e => { if (e === terminal) { r(e.state); } })); terminal.sendText('test'); }); deepStrictEqual(eventState, { isInteractedWith: true }); deepStrictEqual(terminal.state, { isInteractedWith: true }); await new Promise<void>(r => { disposables.push(window.onDidCloseTerminal(t => { if (t === terminal) { r(); } })); terminal.dispose(); }); }); // test('onDidChangeActiveTerminal should fire when new terminals are created', (done) => { // const reg1 = window.onDidChangeActiveTerminal((active: Terminal | undefined) => { // equal(active, terminal); // equal(active, window.activeTerminal); // reg1.dispose(); // const reg2 = window.onDidChangeActiveTerminal((active: Terminal | undefined) => { // equal(active, undefined); // equal(active, window.activeTerminal); // reg2.dispose(); // done(); // }); // terminal.dispose(); // }); // const terminal = window.createTerminal(); // terminal.show(); // }); // test('onDidChangeTerminalDimensions should fire when new terminals are created', (done) => { // const reg1 = window.onDidChangeTerminalDimensions(async (event: TerminalDimensionsChangeEvent) => { // equal(event.terminal, terminal1); // equal(typeof event.dimensions.columns, 'number'); // equal(typeof event.dimensions.rows, 'number'); // ok(event.dimensions.columns > 0); // ok(event.dimensions.rows > 0); // reg1.dispose(); // let terminal2: Terminal; // const reg2 = window.onDidOpenTerminal((newTerminal) => { // // This is guarantees to fire before dimensions change event // if (newTerminal !== terminal1) { // terminal2 = newTerminal; // reg2.dispose(); // } // }); // let firstCalled = false; // let secondCalled = false; // const reg3 = window.onDidChangeTerminalDimensions((event: TerminalDimensionsChangeEvent) => { // if (event.terminal === terminal1) { // // The original terminal should fire dimension change after a split // firstCalled = true; // } else if (event.terminal !== terminal1) { // // The new split terminal should fire dimension change // secondCalled = true; // } // if (firstCalled && secondCalled) { // let firstDisposed = false; // let secondDisposed = false; // const reg4 = window.onDidCloseTerminal(term => { // if (term === terminal1) { // firstDisposed = true; // } // if (term === terminal2) { // secondDisposed = true; // } // if (firstDisposed && secondDisposed) { // reg4.dispose(); // done(); // } // }); // terminal1.dispose(); // terminal2.dispose(); // reg3.dispose(); // } // }); // await timeout(500); // commands.executeCommand('workbench.action.terminal.split'); // }); // const terminal1 = window.createTerminal({ name: 'test' }); // terminal1.show(); // }); suite('hideFromUser', () => { test('should be available to terminals API', async () => { const terminal = window.createTerminal({ name: 'bg', hideFromUser: true }); const result = await new Promise<Terminal>(r => { disposables.push(window.onDidOpenTerminal(t => { if (t === terminal) { r(t); } })); }); equal(result, terminal); equal(true, window.terminals.indexOf(terminal) !== -1); await new Promise<void>(r => { disposables.push(window.onDidCloseTerminal(t => { if (t === terminal) { r(); } })); terminal.dispose(); }); }); }); suite('window.onDidWriteTerminalData', () => { test('should listen to all future terminal data events', (done) => { const openEvents: string[] = []; const dataEvents: { name: string, data: string }[] = []; const closeEvents: string[] = []; disposables.push(window.onDidOpenTerminal(e => openEvents.push(e.name))); let resolveOnceDataWritten: (() => void) | undefined; let resolveOnceClosed: (() => void) | undefined; disposables.push(window.onDidWriteTerminalData(e => { dataEvents.push({ name: e.terminal.name, data: e.data }); resolveOnceDataWritten!(); })); disposables.push(window.onDidCloseTerminal(e => { closeEvents.push(e.name); try { if (closeEvents.length === 1) { deepEqual(openEvents, ['test1']); deepEqual(dataEvents, [{ name: 'test1', data: 'write1' }]); deepEqual(closeEvents, ['test1']); } else if (closeEvents.length === 2) { deepEqual(openEvents, ['test1', 'test2']); deepEqual(dataEvents, [{ name: 'test1', data: 'write1' }, { name: 'test2', data: 'write2' }]); deepEqual(closeEvents, ['test1', 'test2']); } resolveOnceClosed!(); } catch (e) { done(e); } })); const term1Write = new EventEmitter<string>(); const term1Close = new EventEmitter<void>(); window.createTerminal({ name: 'test1', pty: { onDidWrite: term1Write.event, onDidClose: term1Close.event, open: async () => { term1Write.fire('write1'); // Wait until the data is written await new Promise<void>(resolve => { resolveOnceDataWritten = resolve; }); term1Close.fire(); // Wait until the terminal is closed await new Promise<void>(resolve => { resolveOnceClosed = resolve; }); const term2Write = new EventEmitter<string>(); const term2Close = new EventEmitter<void>(); window.createTerminal({ name: 'test2', pty: { onDidWrite: term2Write.event, onDidClose: term2Close.event, open: async () => { term2Write.fire('write2'); // Wait until the data is written await new Promise<void>(resolve => { resolveOnceDataWritten = resolve; }); term2Close.fire(); // Wait until the terminal is closed await new Promise<void>(resolve => { resolveOnceClosed = resolve; }); done(); }, close: () => { } } }); }, close: () => { } } }); }); }); suite('Extension pty terminals', () => { test('should fire onDidOpenTerminal and onDidCloseTerminal', (done) => { disposables.push(window.onDidOpenTerminal(term => { try { equal(term.name, 'c'); } catch (e) { done(e); return; } disposables.push(window.onDidCloseTerminal(() => done())); term.dispose(); })); const pty: Pseudoterminal = { onDidWrite: new EventEmitter<string>().event, open: () => { }, close: () => { } }; window.createTerminal({ name: 'c', pty }); }); // The below tests depend on global UI state and each other // test('should not provide dimensions on start as the terminal has not been shown yet', (done) => { // const reg1 = window.onDidOpenTerminal(term => { // equal(terminal, term); // reg1.dispose(); // }); // const pty: Pseudoterminal = { // onDidWrite: new EventEmitter<string>().event, // open: (dimensions) => { // equal(dimensions, undefined); // const reg3 = window.onDidCloseTerminal(() => { // reg3.dispose(); // done(); // }); // // Show a terminal and wait a brief period before dispose, this will cause // // the panel to init it's dimenisons and be provided to following terminals. // // The following test depends on this. // terminal.show(); // setTimeout(() => terminal.dispose(), 200); // }, // close: () => {} // }; // const terminal = window.createTerminal({ name: 'foo', pty }); // }); // test('should provide dimensions on start as the terminal has been shown', (done) => { // const reg1 = window.onDidOpenTerminal(term => { // equal(terminal, term); // reg1.dispose(); // }); // const pty: Pseudoterminal = { // onDidWrite: new EventEmitter<string>().event, // open: (dimensions) => { // // This test depends on Terminal.show being called some time before such // // that the panel dimensions are initialized and cached. // ok(dimensions!.columns > 0); // ok(dimensions!.rows > 0); // const reg3 = window.onDidCloseTerminal(() => { // reg3.dispose(); // done(); // }); // terminal.dispose(); // }, // close: () => {} // }; // const terminal = window.createTerminal({ name: 'foo', pty }); // }); test('should respect dimension overrides', (done) => { disposables.push(window.onDidOpenTerminal(term => { try { equal(terminal, term); } catch (e) { done(e); return; } term.show(); disposables.push(window.onDidChangeTerminalDimensions(e => { // The default pty dimensions have a chance to appear here since override // dimensions happens after the terminal is created. If so just ignore and // wait for the right dimensions if (e.dimensions.columns === 10 || e.dimensions.rows === 5) { try { equal(e.terminal, terminal); } catch (e) { done(e); return; } disposables.push(window.onDidCloseTerminal(() => done())); terminal.dispose(); } })); })); const writeEmitter = new EventEmitter<string>(); const overrideDimensionsEmitter = new EventEmitter<TerminalDimensions>(); const pty: Pseudoterminal = { onDidWrite: writeEmitter.event, onDidOverrideDimensions: overrideDimensionsEmitter.event, open: () => overrideDimensionsEmitter.fire({ columns: 10, rows: 5 }), close: () => { } }; const terminal = window.createTerminal({ name: 'foo', pty }); }); test('should change terminal name', (done) => { disposables.push(window.onDidOpenTerminal(term => { try { equal(terminal, term); equal(terminal.name, 'foo'); } catch (e) { done(e); return; } disposables.push(window.onDidCloseTerminal(t => { try { equal(terminal, t); equal(terminal.name, 'bar'); } catch (e) { done(e); return; } done(); })); })); const changeNameEmitter = new EventEmitter<string>(); const closeEmitter = new EventEmitter<number | undefined>(); const pty: Pseudoterminal = { onDidWrite: new EventEmitter<string>().event, onDidChangeName: changeNameEmitter.event, onDidClose: closeEmitter.event, open: () => { changeNameEmitter.fire('bar'); closeEmitter.fire(undefined); }, close: () => { } }; const terminal = window.createTerminal({ name: 'foo', pty }); }); test('exitStatus.code should be set to the exit code (undefined)', (done) => { disposables.push(window.onDidOpenTerminal(term => { try { equal(terminal, term); equal(terminal.exitStatus, undefined); } catch (e) { done(e); return; } disposables.push(window.onDidCloseTerminal(t => { try { equal(terminal, t); deepEqual(terminal.exitStatus, { code: undefined }); } catch (e) { done(e); return; } done(); })); })); const writeEmitter = new EventEmitter<string>(); const closeEmitter = new EventEmitter<number | undefined>(); const pty: Pseudoterminal = { onDidWrite: writeEmitter.event, onDidClose: closeEmitter.event, open: () => closeEmitter.fire(undefined), close: () => { } }; const terminal = window.createTerminal({ name: 'foo', pty }); }); test('exitStatus.code should be set to the exit code (zero)', (done) => { disposables.push(window.onDidOpenTerminal(term => { try { equal(terminal, term); equal(terminal.exitStatus, undefined); } catch (e) { done(e); return; } disposables.push(window.onDidCloseTerminal(t => { try { equal(terminal, t); deepEqual(terminal.exitStatus, { code: 0 }); } catch (e) { done(e); return; } done(); })); })); const writeEmitter = new EventEmitter<string>(); const closeEmitter = new EventEmitter<number | undefined>(); const pty: Pseudoterminal = { onDidWrite: writeEmitter.event, onDidClose: closeEmitter.event, open: () => closeEmitter.fire(0), close: () => { } }; const terminal = window.createTerminal({ name: 'foo', pty }); }); test('exitStatus.code should be set to the exit code (non-zero)', (done) => { disposables.push(window.onDidOpenTerminal(term => { try { equal(terminal, term); equal(terminal.exitStatus, undefined); } catch (e) { done(e); return; } disposables.push(window.onDidCloseTerminal(t => { try { equal(terminal, t); deepEqual(terminal.exitStatus, { code: 22 }); } catch (e) { done(e); return; } done(); })); })); const writeEmitter = new EventEmitter<string>(); const closeEmitter = new EventEmitter<number | undefined>(); const pty: Pseudoterminal = { onDidWrite: writeEmitter.event, onDidClose: closeEmitter.event, open: () => { // Wait 500ms as any exits that occur within 500ms of terminal launch are // are counted as "exiting during launch" which triggers a notification even // when showExitAlerts is true setTimeout(() => closeEmitter.fire(22), 500); }, close: () => { } }; const terminal = window.createTerminal({ name: 'foo', pty }); }); test('creationOptions should be set and readonly for ExtensionTerminalOptions terminals', (done) => { disposables.push(window.onDidOpenTerminal(term => { try { equal(terminal, term); } catch (e) { done(e); return; } terminal.dispose(); disposables.push(window.onDidCloseTerminal(() => done())); })); const writeEmitter = new EventEmitter<string>(); const pty: Pseudoterminal = { onDidWrite: writeEmitter.event, open: () => { }, close: () => { } }; const options = { name: 'foo', pty }; const terminal = window.createTerminal(options); try { equal(terminal.name, 'foo'); const terminalOptions = terminal.creationOptions as ExtensionTerminalOptions; equal(terminalOptions.name, 'foo'); equal(terminalOptions.pty, pty); throws(() => terminalOptions.name = 'bad', 'creationOptions should be readonly at runtime'); } catch (e) { done(e); } }); }); suite('environmentVariableCollection', () => { test.skip('should have collection variables apply to terminals immediately after setting', (done) => { // Text to match on before passing the test const expectedText = [ '~a2~', 'b1~b2~', '~c2~c1' ]; let data = ''; disposables.push(window.onDidWriteTerminalData(e => { if (terminal !== e.terminal) { return; } data += sanitizeData(e.data); // Multiple expected could show up in the same data event while (expectedText.length > 0 && data.indexOf(expectedText[0]) >= 0) { expectedText.shift(); // Check if all string are found, if so finish the test if (expectedText.length === 0) { disposables.push(window.onDidCloseTerminal(() => done())); terminal.dispose(); } } })); const collection = extensionContext.environmentVariableCollection; disposables.push({ dispose: () => collection.clear() }); collection.replace('A', '~a2~'); collection.append('B', '~b2~'); collection.prepend('C', '~c2~'); const terminal = window.createTerminal({ env: { A: 'a1', B: 'b1', C: 'c1' } }); // Run both PowerShell and sh commands, errors don't matter we're just looking for // the correct output terminal.sendText('$env:A'); terminal.sendText('echo $A'); terminal.sendText('$env:B'); terminal.sendText('echo $B'); terminal.sendText('$env:C'); terminal.sendText('echo $C'); }); test('should have collection variables apply to environment variables that don\'t exist', (done) => { // Text to match on before passing the test const expectedText = [ '~a2~', '~b2~', '~c2~' ]; let data = ''; disposables.push(window.onDidWriteTerminalData(e => { if (terminal !== e.terminal) { return; } data += sanitizeData(e.data); // Multiple expected could show up in the same data event while (expectedText.length > 0 && data.indexOf(expectedText[0]) >= 0) { expectedText.shift(); // Check if all string are found, if so finish the test if (expectedText.length === 0) { disposables.push(window.onDidCloseTerminal(() => done())); terminal.dispose(); } } })); const collection = extensionContext.environmentVariableCollection; disposables.push({ dispose: () => collection.clear() }); collection.replace('A', '~a2~'); collection.append('B', '~b2~'); collection.prepend('C', '~c2~'); const terminal = window.createTerminal({ env: { A: null, B: null, C: null } }); // Run both PowerShell and sh commands, errors don't matter we're just looking for // the correct output terminal.sendText('$env:A'); terminal.sendText('echo $A'); terminal.sendText('$env:B'); terminal.sendText('echo $B'); terminal.sendText('$env:C'); terminal.sendText('echo $C'); }); test('should respect clearing entries', (done) => { // Text to match on before passing the test const expectedText = [ '~a1~', '~b1~' ]; let data = ''; disposables.push(window.onDidWriteTerminalData(e => { if (terminal !== e.terminal) { return; } data += sanitizeData(e.data); // Multiple expected could show up in the same data event while (expectedText.length > 0 && data.indexOf(expectedText[0]) >= 0) { expectedText.shift(); // Check if all string are found, if so finish the test if (expectedText.length === 0) { disposables.push(window.onDidCloseTerminal(() => done())); terminal.dispose(); } } })); const collection = extensionContext.environmentVariableCollection; disposables.push({ dispose: () => collection.clear() }); collection.replace('A', '~a2~'); collection.replace('B', '~a2~'); collection.clear(); const terminal = window.createTerminal({ env: { A: '~a1~', B: '~b1~' } }); // Run both PowerShell and sh commands, errors don't matter we're just looking for // the correct output terminal.sendText('$env:A'); terminal.sendText('echo $A'); terminal.sendText('$env:B'); terminal.sendText('echo $B'); }); test('should respect deleting entries', (done) => { // Text to match on before passing the test const expectedText = [ '~a1~', '~b2~' ]; let data = ''; disposables.push(window.onDidWriteTerminalData(e => { if (terminal !== e.terminal) { return; } data += sanitizeData(e.data); // Multiple expected could show up in the same data event while (expectedText.length > 0 && data.indexOf(expectedText[0]) >= 0) { expectedText.shift(); // Check if all string are found, if so finish the test if (expectedText.length === 0) { disposables.push(window.onDidCloseTerminal(() => done())); terminal.dispose(); } } })); const collection = extensionContext.environmentVariableCollection; disposables.push({ dispose: () => collection.clear() }); collection.replace('A', '~a2~'); collection.replace('B', '~b2~'); collection.delete('A'); const terminal = window.createTerminal({ env: { A: '~a1~', B: '~b2~' } }); // Run both PowerShell and sh commands, errors don't matter we're just looking for // the correct output terminal.sendText('$env:A'); terminal.sendText('echo $A'); terminal.sendText('$env:B'); terminal.sendText('echo $B'); }); test('get and forEach should work', () => { const collection = extensionContext.environmentVariableCollection; disposables.push({ dispose: () => collection.clear() }); collection.replace('A', '~a2~'); collection.append('B', '~b2~'); collection.prepend('C', '~c2~'); // Verify get deepEqual(collection.get('A'), { value: '~a2~', type: EnvironmentVariableMutatorType.Replace }); deepEqual(collection.get('B'), { value: '~b2~', type: EnvironmentVariableMutatorType.Append }); deepEqual(collection.get('C'), { value: '~c2~', type: EnvironmentVariableMutatorType.Prepend }); // Verify forEach const entries: [string, EnvironmentVariableMutator][] = []; collection.forEach((v, m) => entries.push([v, m])); deepEqual(entries, [ ['A', { value: '~a2~', type: EnvironmentVariableMutatorType.Replace }], ['B', { value: '~b2~', type: EnvironmentVariableMutatorType.Append }], ['C', { value: '~c2~', type: EnvironmentVariableMutatorType.Prepend }] ]); }); }); }); }); function sanitizeData(data: string): string { // Strip NL/CR so terminal dimensions don't impact tests data = data.replace(/[\r\n]/g, ''); // Strip escape sequences so winpty/conpty doesn't cause flakiness, do for all platforms for // consistency const terminalCodesRegex = /(?:\u001B|\u009B)[\[\]()#;?]*(?:(?:(?:[a-zA-Z0-9]*(?:;[a-zA-Z0-9]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-PR-TZcf-ntqry=><~]))/g; data = data.replace(terminalCodesRegex, ''); return data; }
the_stack
import { HttpClient, HttpResponse } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { buildHttpRequestOptions, HTTP_JSON_OPTIONS, HTTP_GET_OPTIONS, buildHttpRequestOptionsWithObserveResponse, HTTP_GET_OPTIONS_OBSERVE_RESPONSE, CURRENT_BASE_HREF } from "../units/utils"; import { ReplicationJob, ReplicationRule, ReplicationJobItem, ReplicationTasks } from "./interface"; import { RequestQueryParams } from "./RequestQueryParams"; import { map, catchError } from "rxjs/operators"; import { Observable, throwError as observableThrowError } from "rxjs"; /** * Define the service methods to handle the replication (rule and job) related things. * ** * @abstract * class ReplicationService */ export abstract class ReplicationService { /** * Get the replication rules. * Set the argument 'projectId' to limit the data scope to the specified project; * set the argument 'ruleName' to return the rule only match the name pattern; * if pagination needed, use the queryParams to add query parameters. * * @abstract * ** deprecated param {(number | string)} [projectId] * ** deprecated param {string} [ruleName] * ** deprecated param {RequestQueryParams} [queryParams] * returns {(Observable<ReplicationRule[]>)} * * @memberOf ReplicationService */ abstract getReplicationRules( projectId?: number | string, ruleName?: string, queryParams?: RequestQueryParams ): | Observable<ReplicationRule[]>; abstract getReplicationRulesResponse( ruleName?: string, page?: number , pageSize?: number, queryParams?: RequestQueryParams ): Observable<HttpResponse<ReplicationRule[]>>; /** * Get the specified replication rule. * * @abstract * ** deprecated param {(number | string)} ruleId * returns {(Observable<ReplicationRule>)} * * @memberOf ReplicationService */ abstract getReplicationRule( ruleId: number | string ): Observable<ReplicationRule>; /** * Get the specified replication task. * * @abstract * returns {(Observable<ReplicationRule>)} * * @memberOf ReplicationService */ abstract getReplicationTasks( executionId: number | string, queryParams?: RequestQueryParams ): Observable<ReplicationTasks>; /** * Create new replication rule. * * @abstract * ** deprecated param {ReplicationRule} replicationRule * returns {(Observable<any>)} * * @memberOf ReplicationService */ abstract createReplicationRule( replicationRule: ReplicationRule ): Observable<any>; /** * Update the specified replication rule. * * @abstract * ** deprecated param {ReplicationRule} replicationRule * returns {(Observable<any>)} * * @memberOf ReplicationService */ abstract updateReplicationRule( id: number, rep: ReplicationRule ): Observable<any>; /** * Delete the specified replication rule. * * @abstract * ** deprecated param {(number | string)} ruleId * returns {(Observable<any>)} * * @memberOf ReplicationService */ abstract deleteReplicationRule( ruleId: number | string ): Observable<any>; /** * Enable the specified replication rule. * * @abstract * ** deprecated param {(number | string)} ruleId * returns {(Observable<any>)} * * @memberOf ReplicationService */ abstract enableReplicationRule( ruleId: number | string, enablement: number ): Observable<any>; /** * Disable the specified replication rule. * * @abstract * ** deprecated param {(number | string)} ruleId * returns {(Observable<any>)} * * @memberOf ReplicationService */ abstract disableReplicationRule( ruleId: number | string ): Observable<any>; abstract replicateRule( ruleId: number | string ): Observable<any>; abstract getRegistryInfo(id: number): Observable<any>; /** * Get the jobs for the specified replication rule. * Set query parameters through 'queryParams', support: * - status * - repository * - startTime and endTime * - page * - pageSize * * @abstract * ** deprecated param {(number | string)} ruleId * ** deprecated param {RequestQueryParams} [queryParams] * returns {(Observable<ReplicationJob>)} * * @memberOf ReplicationService */ abstract getExecutions( ruleId: number | string, queryParams?: RequestQueryParams ): Observable<ReplicationJob>; /** * Get the specified execution. * * @abstract * ** deprecated param {(number | string)} endpointId * returns {(Observable<ReplicationJob> | ReplicationJob)} * * @memberOf ReplicationService */ abstract getExecutionById( executionId: number | string ): Observable<ReplicationJob>; /** * Get the log of the specified job. * * @abstract * ** deprecated param {(number | string)} jobId * returns {(Observable<string>)} * @memberof ReplicationService */ abstract getJobLog( jobId: number | string ): Observable<string>; abstract stopJobs( jobId: number | string ): Observable<string>; abstract getJobBaseUrl(): string; } /** * Implement default service for replication rule and job. * ** * class ReplicationDefaultService * extends {ReplicationService} */ @Injectable() export class ReplicationDefaultService extends ReplicationService { _ruleBaseUrl: string; _replicateUrl: string; _baseUrl: string; constructor( private http: HttpClient, ) { super(); this._ruleBaseUrl = CURRENT_BASE_HREF + "/replication/policies"; this._replicateUrl = CURRENT_BASE_HREF + "/replication"; this._baseUrl = CURRENT_BASE_HREF + ""; } // Private methods // Check if the rule object is valid _isValidRule(rule: ReplicationRule): boolean { return ( rule !== undefined && rule != null && rule.name !== undefined && rule.name.trim() !== "" && (!!rule.dest_registry || !!rule.src_registry) ); } public getRegistryInfo(id): Observable<any> { let requestUrl: string = `${this._baseUrl}/registries/${id}/info`; return this.http .get(requestUrl) .pipe(catchError(error => observableThrowError(error))); } public getJobBaseUrl() { return this._replicateUrl; } public getReplicationRules( projectId?: number | string, ruleName?: string, queryParams?: RequestQueryParams ): | Observable<ReplicationRule[]> { if (!queryParams) { queryParams = new RequestQueryParams(); } if (projectId) { queryParams = queryParams.set("project_id", "" + projectId); } if (ruleName) { queryParams = queryParams.set("name", ruleName); } return this.http .get(this._ruleBaseUrl, buildHttpRequestOptions(queryParams)) .pipe(map(response => response as ReplicationRule[]) , catchError(error => observableThrowError(error))); } public getReplicationRulesResponse( ruleName?: string, page?: number, pageSize?: number, queryParams?: RequestQueryParams): Observable<HttpResponse<ReplicationRule[]>> { if (!queryParams) { queryParams = new RequestQueryParams(); } if (ruleName) { queryParams = queryParams.set("name", ruleName); } if (page) { queryParams = queryParams.set("page", page + ""); } if (pageSize) { queryParams = queryParams.set("page_size", pageSize + ""); } return this.http .get<HttpResponse<ReplicationRule[]>>(this._ruleBaseUrl, buildHttpRequestOptionsWithObserveResponse(queryParams)) .pipe(map(response => response as HttpResponse<ReplicationRule[]>) , catchError(error => observableThrowError(error))); } public getReplicationRule( ruleId: number | string ): Observable<ReplicationRule> { if (!ruleId) { return observableThrowError("Bad argument"); } let url: string = `${this._ruleBaseUrl}/${ruleId}`; return this.http .get(url, HTTP_GET_OPTIONS) .pipe(map(response => response as ReplicationRule) , catchError(error => observableThrowError(error))); } public getReplicationTasks( executionId: number | string, queryParams?: RequestQueryParams ): Observable<ReplicationTasks> { if (!executionId) { return observableThrowError("Bad argument"); } let url: string = `${this._replicateUrl}/executions/${executionId}/tasks`; return this.http .get(url, buildHttpRequestOptionsWithObserveResponse(queryParams)) .pipe(map(response => response as ReplicationTasks) , catchError(error => observableThrowError(error))); } public createReplicationRule( replicationRule: ReplicationRule ): Observable<any> { if (!this._isValidRule(replicationRule)) { return observableThrowError("Bad argument"); } return this.http .post( this._ruleBaseUrl, JSON.stringify(replicationRule), HTTP_JSON_OPTIONS ) .pipe(map(response => response) , catchError(error => observableThrowError(error))); } public updateReplicationRule( id: number, rep: ReplicationRule ): Observable<any> { if (!this._isValidRule(rep)) { return observableThrowError("Bad argument"); } let url = `${this._ruleBaseUrl}/${id}`; return this.http .put(url, JSON.stringify(rep), HTTP_JSON_OPTIONS) .pipe(map(response => response) , catchError(error => observableThrowError(error))); } public deleteReplicationRule( ruleId: number | string ): Observable<any> { if (!ruleId || ruleId <= 0) { return observableThrowError("Bad argument"); } let url: string = `${this._ruleBaseUrl}/${ruleId}`; return this.http .delete(url, HTTP_JSON_OPTIONS) .pipe(map(response => response) , catchError(error => observableThrowError(error))); } public replicateRule( ruleId: number | string ): Observable<any> { if (!ruleId) { return observableThrowError("Bad argument"); } let url: string = `${this._replicateUrl}/executions`; return this.http .post(url, { policy_id: ruleId }, HTTP_JSON_OPTIONS) .pipe(map(response => response) , catchError(error => observableThrowError(error))); } public enableReplicationRule( ruleId: number | string, enablement: number ): Observable<any> { if (!ruleId || ruleId <= 0) { return observableThrowError("Bad argument"); } let url: string = `${this._ruleBaseUrl}/${ruleId}/enablement`; return this.http .put(url, { enabled: enablement }, HTTP_JSON_OPTIONS) .pipe(map(response => response) , catchError(error => observableThrowError(error))); } public disableReplicationRule( ruleId: number | string ): Observable<any> { if (!ruleId || ruleId <= 0) { return observableThrowError("Bad argument"); } let url: string = `${this._ruleBaseUrl}/${ruleId}/enablement`; return this.http .put(url, { enabled: 0 }, HTTP_JSON_OPTIONS) .pipe(map(response => response) , catchError(error => observableThrowError(error))); } public getExecutions( ruleId: number | string, queryParams?: RequestQueryParams ): Observable<ReplicationJob> { if (!ruleId || ruleId <= 0) { return observableThrowError("Bad argument"); } if (!queryParams) { queryParams = new RequestQueryParams(); } let url: string = `${this._replicateUrl}/executions`; queryParams = queryParams.set("policy_id", "" + ruleId); return this.http .get<HttpResponse<ReplicationJobItem[]>>(url, buildHttpRequestOptionsWithObserveResponse(queryParams)) .pipe(map(response => { let result: ReplicationJob = { metadata: { xTotalCount: 0 }, data: [] }; if (response && response.headers) { let xHeader: string = response.headers.get("X-Total-Count"); if (xHeader) { result.metadata.xTotalCount = parseInt(xHeader, 0); } } result.data = response.body as ReplicationJobItem[]; if (result.metadata.xTotalCount === 0) { if (result.data && result.data.length > 0) { result.metadata.xTotalCount = result.data.length; } } return result; }) , catchError(error => observableThrowError(error))); } public getExecutionById( executionId: number | string ): Observable<ReplicationJob> { if (!executionId || executionId <= 0) { return observableThrowError("Bad request argument."); } let requestUrl: string = `${this._replicateUrl}/executions/${executionId}`; return this.http .get<HttpResponse<ReplicationJobItem[]>>(requestUrl, HTTP_GET_OPTIONS_OBSERVE_RESPONSE) .pipe(map(response => { let result: ReplicationJob = { metadata: { xTotalCount: 0 }, data: [] }; if (response && response.headers) { let xHeader: string = response.headers.get("X-Total-Count"); if (xHeader) { result.metadata.xTotalCount = parseInt(xHeader, 0); } } result.data = response.body as ReplicationJobItem[]; if (result.metadata.xTotalCount === 0) { if (result.data && result.data.length > 0) { result.metadata.xTotalCount = result.data.length; } } return result; }) , catchError(error => observableThrowError(error))); } public getJobLog( jobId: number | string ): Observable<string> { if (!jobId || jobId <= 0) { return observableThrowError("Bad argument"); } let logUrl = `${this._replicateUrl}/${jobId}/log`; return this.http .get<string>(logUrl, HTTP_GET_OPTIONS) .pipe(catchError(error => observableThrowError(error))); } public stopJobs( jobId: number | string ): Observable<any> { if (!jobId || jobId <= 0) { return observableThrowError("Bad request argument."); } let requestUrl: string = `${this._replicateUrl}/executions/${jobId}`; return this.http .put( requestUrl, HTTP_JSON_OPTIONS ) .pipe(map(response => response) , catchError(error => observableThrowError(error))); } }
the_stack
import { isSafari } from 'vs/base/browser/browser'; import { IndexedDB } from 'vs/base/browser/indexedDB'; import { DeferredPromise, Promises } from 'vs/base/common/async'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { Emitter } from 'vs/base/common/event'; import { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { assertIsDefined } from 'vs/base/common/types'; import { InMemoryStorageDatabase, isStorageItemsChangeEvent, IStorage, IStorageDatabase, IStorageItemsChangeEvent, IUpdateRequest, Storage } from 'vs/base/parts/storage/common/storage'; import { ILogService } from 'vs/platform/log/common/log'; import { AbstractStorageService, IS_NEW_KEY, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { IUserDataProfile } from 'vs/platform/userDataProfile/common/userDataProfile'; import { IAnyWorkspaceIdentifier } from 'vs/platform/workspace/common/workspace'; export class BrowserStorageService extends AbstractStorageService { private static BROWSER_DEFAULT_FLUSH_INTERVAL = 5 * 1000; // every 5s because async operations are not permitted on shutdown private applicationStorage: IStorage | undefined; private applicationStorageDatabase: IIndexedDBStorageDatabase | undefined; private readonly applicationStoragePromise = new DeferredPromise<{ indededDb: IIndexedDBStorageDatabase; storage: IStorage }>(); private globalStorage: IStorage | undefined; private globalStorageDatabase: IIndexedDBStorageDatabase | undefined; private globalStorageProfile: IUserDataProfile; private readonly globalStorageDisposables = this._register(new DisposableStore()); private workspaceStorage: IStorage | undefined; private workspaceStorageDatabase: IIndexedDBStorageDatabase | undefined; get hasPendingUpdate(): boolean { return Boolean( this.applicationStorageDatabase?.hasPendingUpdate || this.globalStorageDatabase?.hasPendingUpdate || this.workspaceStorageDatabase?.hasPendingUpdate ); } constructor( private readonly payload: IAnyWorkspaceIdentifier, currentProfile: IUserDataProfile, @ILogService private readonly logService: ILogService, ) { super({ flushInterval: BrowserStorageService.BROWSER_DEFAULT_FLUSH_INTERVAL }); this.globalStorageProfile = currentProfile; } private getId(scope: StorageScope): string { switch (scope) { case StorageScope.APPLICATION: return 'global'; // use the default profile global DB for application scope case StorageScope.GLOBAL: if (this.globalStorageProfile.isDefault) { return 'global'; // default profile DB has a fixed name for backwards compatibility } else { return `global-${this.globalStorageProfile.id}`; } case StorageScope.WORKSPACE: return this.payload.id; } } protected async doInitialize(): Promise<void> { // Init storages await Promises.settled([ this.createApplicationStorage(), this.createGlobalStorage(this.globalStorageProfile), this.createWorkspaceStorage() ]); } private async createApplicationStorage(): Promise<void> { const applicationStorageIndexedDB = await IndexedDBStorageDatabase.create({ id: this.getId(StorageScope.APPLICATION), broadcastChanges: true }, this.logService); this.applicationStorageDatabase = this._register(applicationStorageIndexedDB); this.applicationStorage = this._register(new Storage(this.applicationStorageDatabase)); this._register(this.applicationStorage.onDidChangeStorage(key => this.emitDidChangeValue(StorageScope.APPLICATION, key))); await this.applicationStorage.init(); this.updateIsNew(this.applicationStorage); this.applicationStoragePromise.complete({ indededDb: applicationStorageIndexedDB, storage: this.applicationStorage }); } private async createGlobalStorage(profile: IUserDataProfile): Promise<void> { // First clear any previously associated disposables this.globalStorageDisposables.clear(); // Remember profile associated to global storage this.globalStorageProfile = profile; if (this.globalStorageProfile.isDefault) { // If we are in default profile, the global storage is // actually the same as application storage. As such we // avoid creating the storage library a second time on // the same DB. const { indededDb: applicationStorageIndexedDB, storage: applicationStorage } = await this.applicationStoragePromise.p; this.globalStorageDatabase = applicationStorageIndexedDB; this.globalStorage = applicationStorage; } else { const globalStorageIndexedDB = await IndexedDBStorageDatabase.create({ id: this.getId(StorageScope.GLOBAL), broadcastChanges: true }, this.logService); this.globalStorageDatabase = this.globalStorageDisposables.add(globalStorageIndexedDB); this.globalStorage = this.globalStorageDisposables.add(new Storage(this.globalStorageDatabase)); } this.globalStorageDisposables.add(this.globalStorage.onDidChangeStorage(key => this.emitDidChangeValue(StorageScope.GLOBAL, key))); await this.globalStorage.init(); this.updateIsNew(this.globalStorage); } private async createWorkspaceStorage(): Promise<void> { const workspaceStorageIndexedDB = await IndexedDBStorageDatabase.create({ id: this.getId(StorageScope.WORKSPACE) }, this.logService); this.workspaceStorageDatabase = this._register(workspaceStorageIndexedDB); this.workspaceStorage = this._register(new Storage(this.workspaceStorageDatabase)); this._register(this.workspaceStorage.onDidChangeStorage(key => this.emitDidChangeValue(StorageScope.WORKSPACE, key))); await this.workspaceStorage.init(); this.updateIsNew(this.workspaceStorage); } private updateIsNew(storage: IStorage): void { const firstOpen = storage.getBoolean(IS_NEW_KEY); if (firstOpen === undefined) { storage.set(IS_NEW_KEY, true); } else if (firstOpen) { storage.set(IS_NEW_KEY, false); } } protected getStorage(scope: StorageScope): IStorage | undefined { switch (scope) { case StorageScope.APPLICATION: return this.applicationStorage; case StorageScope.GLOBAL: return this.globalStorage; default: return this.workspaceStorage; } } protected getLogDetails(scope: StorageScope): string | undefined { return this.getId(scope); } protected async switchToProfile(toProfile: IUserDataProfile, preserveData: boolean): Promise<void> { const oldGlobalStorage = assertIsDefined(this.globalStorage); const oldItems = oldGlobalStorage.items; // Close old global storage but only if this is // different from application storage! if (oldGlobalStorage !== this.applicationStorage) { await oldGlobalStorage.close(); } // Create new global storage & init await this.createGlobalStorage(toProfile); // Handle data switch and eventing this.switchData(oldItems, assertIsDefined(this.globalStorage), StorageScope.GLOBAL, preserveData); } protected async switchToWorkspace(toWorkspace: IAnyWorkspaceIdentifier, preserveData: boolean): Promise<void> { throw new Error('Migrating storage is currently unsupported in Web'); } protected override shouldFlushWhenIdle(): boolean { // this flush() will potentially cause new state to be stored // since new state will only be created while the document // has focus, one optimization is to not run this when the // document has no focus, assuming that state has not changed // // another optimization is to not collect more state if we // have a pending update already running which indicates // that the connection is either slow or disconnected and // thus unhealthy. return document.hasFocus() && !this.hasPendingUpdate; } close(): void { // Safari: there is an issue where the page can hang on load when // a previous session has kept IndexedDB transactions running. // The only fix seems to be to cancel any pending transactions // (https://github.com/microsoft/vscode/issues/136295) // // On all other browsers, we keep the databases opened because // we expect data to be written when the unload happens. if (isSafari) { this.applicationStorage?.close(); this.globalStorageDatabase?.close(); this.workspaceStorageDatabase?.close(); } // Always dispose to ensure that no timeouts or callbacks // get triggered in this phase. this.dispose(); } async clear(): Promise<void> { // Clear key/values for (const scope of [StorageScope.APPLICATION, StorageScope.GLOBAL, StorageScope.WORKSPACE]) { for (const target of [StorageTarget.USER, StorageTarget.MACHINE]) { for (const key of this.keys(scope, target)) { this.remove(key, scope); } } await this.getStorage(scope)?.whenFlushed(); } // Clear databases await Promises.settled([ this.applicationStorageDatabase?.clear() ?? Promise.resolve(), this.globalStorageDatabase?.clear() ?? Promise.resolve(), this.workspaceStorageDatabase?.clear() ?? Promise.resolve() ]); } } interface IIndexedDBStorageDatabase extends IStorageDatabase, IDisposable { /** * Whether an update in the DB is currently pending * (either update or delete operation). */ readonly hasPendingUpdate: boolean; /** * For testing only. */ clear(): Promise<void>; } class InMemoryIndexedDBStorageDatabase extends InMemoryStorageDatabase implements IIndexedDBStorageDatabase { readonly hasPendingUpdate = false; async clear(): Promise<void> { (await this.getItems()).clear(); } dispose(): void { // No-op } } interface IndexedDBStorageDatabaseOptions { id: string; broadcastChanges?: boolean; } export class IndexedDBStorageDatabase extends Disposable implements IIndexedDBStorageDatabase { static async create(options: IndexedDBStorageDatabaseOptions, logService: ILogService): Promise<IIndexedDBStorageDatabase> { try { const database = new IndexedDBStorageDatabase(options, logService); await database.whenConnected; return database; } catch (error) { logService.error(`[IndexedDB Storage ${options.id}] create(): ${toErrorMessage(error, true)}`); return new InMemoryIndexedDBStorageDatabase(); } } private static readonly STORAGE_DATABASE_PREFIX = 'vscode-web-state-db-'; private static readonly STORAGE_OBJECT_STORE = 'ItemTable'; private static readonly STORAGE_BROADCAST_CHANNEL = 'vscode.web.state.changes'; private readonly _onDidChangeItemsExternal = this._register(new Emitter<IStorageItemsChangeEvent>()); readonly onDidChangeItemsExternal = this._onDidChangeItemsExternal.event; private broadcastChannel: BroadcastChannel | undefined; private pendingUpdate: Promise<boolean> | undefined = undefined; get hasPendingUpdate(): boolean { return !!this.pendingUpdate; } private readonly name: string; private readonly whenConnected: Promise<IndexedDB>; private constructor( options: IndexedDBStorageDatabaseOptions, private readonly logService: ILogService ) { super(); this.name = `${IndexedDBStorageDatabase.STORAGE_DATABASE_PREFIX}${options.id}`; this.broadcastChannel = options.broadcastChanges && ('BroadcastChannel' in window) ? new BroadcastChannel(IndexedDBStorageDatabase.STORAGE_BROADCAST_CHANNEL) : undefined; this.whenConnected = this.connect(); this.registerListeners(); } private registerListeners(): void { // Check for global storage change events from other // windows/tabs via `BroadcastChannel` mechanisms. if (this.broadcastChannel) { const listener = (event: MessageEvent) => { if (isStorageItemsChangeEvent(event.data)) { this._onDidChangeItemsExternal.fire(event.data); } }; this.broadcastChannel.addEventListener('message', listener); this._register(toDisposable(() => { this.broadcastChannel?.removeEventListener('message', listener); this.broadcastChannel?.close(); })); } } private async connect(): Promise<IndexedDB> { try { return await IndexedDB.create(this.name, undefined, [IndexedDBStorageDatabase.STORAGE_OBJECT_STORE]); } catch (error) { this.logService.error(`[IndexedDB Storage ${this.name}] connect() error: ${toErrorMessage(error)}`); throw error; } } async getItems(): Promise<Map<string, string>> { const db = await this.whenConnected; function isValid(value: unknown): value is string { return typeof value === 'string'; } return db.getKeyValues<string>(IndexedDBStorageDatabase.STORAGE_OBJECT_STORE, isValid); } async updateItems(request: IUpdateRequest): Promise<void> { // Run the update let didUpdate = false; this.pendingUpdate = this.doUpdateItems(request); try { didUpdate = await this.pendingUpdate; } finally { this.pendingUpdate = undefined; } // Broadcast changes to other windows/tabs if enabled // and only if we actually did update storage items. if (this.broadcastChannel && didUpdate) { const event: IStorageItemsChangeEvent = { changed: request.insert, deleted: request.delete }; this.broadcastChannel.postMessage(event); } } private async doUpdateItems(request: IUpdateRequest): Promise<boolean> { // Return early if the request is empty const toInsert = request.insert; const toDelete = request.delete; if ((!toInsert && !toDelete) || (toInsert?.size === 0 && toDelete?.size === 0)) { return false; } const db = await this.whenConnected; // Update `ItemTable` with inserts and/or deletes await db.runInTransaction(IndexedDBStorageDatabase.STORAGE_OBJECT_STORE, 'readwrite', objectStore => { const requests: IDBRequest[] = []; // Inserts if (toInsert) { for (const [key, value] of toInsert) { requests.push(objectStore.put(value, key)); } } // Deletes if (toDelete) { for (const key of toDelete) { requests.push(objectStore.delete(key)); } } return requests; }); return true; } async close(): Promise<void> { const db = await this.whenConnected; // Wait for pending updates to having finished await this.pendingUpdate; // Finally, close IndexedDB return db.close(); } async clear(): Promise<void> { const db = await this.whenConnected; await db.runInTransaction(IndexedDBStorageDatabase.STORAGE_OBJECT_STORE, 'readwrite', objectStore => objectStore.clear()); } }
the_stack
import * as child_process from "child_process"; import * as fs from "fs"; import * as iconv from "iconv-lite"; import * as os from "os"; import * as path from "path"; import * as properties from "properties"; import * as vscode from "vscode"; import * as WinReg from "winreg"; import { arduinoChannel } from "./outputChannel"; const encodingMapping: object = JSON.parse(fs.readFileSync(path.join(__dirname, "../../../misc", "codepageMapping.json"), "utf8")); /** * This function will detect the file existing in the sync mode. * @function fileExistsSync * @argument {string} filePath */ export function fileExistsSync(filePath: string): boolean { try { return fs.statSync(filePath).isFile(); } catch (e) { return false; } } /** * This function will detect the directoy existing in the sync mode. * @function directoryExistsSync * @argument {string} dirPath */ export function directoryExistsSync(dirPath: string): boolean { try { return fs.statSync(dirPath).isDirectory(); } catch (e) { return false; } } /** * This function will implement the same function as the fs.readdirSync, * besides it could filter out folders only when the second argument is true. * @function readdirSync * @argument {string} dirPath * @argument {boolean} folderOnly */ export function readdirSync(dirPath: string, folderOnly: boolean = false): string[] { const dirs = fs.readdirSync(dirPath); if (folderOnly) { return dirs.filter((subdir) => { return directoryExistsSync(path.join(dirPath, subdir)); }); } else { return dirs; } } /** * Recursively create directories. Equals to "mkdir -p" * @function mkdirRecursivelySync * @argument {string} dirPath */ export function mkdirRecursivelySync(dirPath: string): void { if (directoryExistsSync(dirPath)) { return; } const dirname = path.dirname(dirPath); if (path.normalize(dirname) === path.normalize(dirPath)) { fs.mkdirSync(dirPath); } else if (directoryExistsSync(dirname)) { fs.mkdirSync(dirPath); } else { mkdirRecursivelySync(dirname); fs.mkdirSync(dirPath); } } /** * Recursively delete files. Equals to "rm -rf" * @function rmdirRecursivelySync * @argument {string} rootPath */ export function rmdirRecursivelySync(rootPath: string): void { if (fs.existsSync(rootPath)) { fs.readdirSync(rootPath).forEach((file) => { const curPath = path.join(rootPath, file); if (fs.lstatSync(curPath).isDirectory()) { // recurse rmdirRecursivelySync(curPath); } else { // delete file fs.unlinkSync(curPath); } }); fs.rmdirSync(rootPath); } } function copyFileSync(src, dest, overwrite: boolean = true) { if (!fileExistsSync(src) || (!overwrite && fileExistsSync(dest))) { return; } const BUF_LENGTH = 64 * 1024; const buf = new Buffer(BUF_LENGTH); let lastBytes = BUF_LENGTH; let pos = 0; let srcFd = null; let destFd = null; try { srcFd = fs.openSync(src, "r"); } catch (error) { } try { destFd = fs.openSync(dest, "w"); } catch (error) { } try { while (lastBytes === BUF_LENGTH) { lastBytes = fs.readSync(srcFd, buf, 0, BUF_LENGTH, pos); fs.writeSync(destFd, buf, 0, lastBytes); pos += lastBytes; } } catch (error) { } if (srcFd) { fs.closeSync(srcFd); } if (destFd) { fs.closeSync(destFd); } } function copyFolderRecursivelySync(src, dest) { if (!directoryExistsSync(src)) { return; } if (!directoryExistsSync(dest)) { mkdirRecursivelySync(dest); } const items = fs.readdirSync(src); for (const item of items) { const fullPath = path.join(src, item); const targetPath = path.join(dest, item); if (directoryExistsSync(fullPath)) { copyFolderRecursivelySync(fullPath, targetPath); } else if (fileExistsSync(fullPath)) { copyFileSync(fullPath, targetPath); } } } /** * Copy files & directories recursively. Equals to "cp -r" * @argument {string} src * @argument {string} dest */ export function cp(src, dest) { if (fileExistsSync(src)) { let targetFile = dest; if (directoryExistsSync(dest)) { targetFile = path.join(dest, path.basename(src)); } if (path.relative(src, targetFile)) { // if the source and target file is the same, skip copying. return; } copyFileSync(src, targetFile); } else if (directoryExistsSync(src)) { copyFolderRecursivelySync(src, dest); } else { throw new Error(`No such file or directory: ${src}`); } } /** * Check if the specified file is an arduino file (*.ino, *.pde). * @argument {string} filePath */ export function isArduinoFile(filePath): boolean { return fileExistsSync(filePath) && (path.extname(filePath) === ".ino" || path.extname(filePath) === ".pde"); } /** * Send a command to arduino * @param {string} command - base command path (either Arduino IDE or CLI) * @param {vscode.OutputChannel} outputChannel - output display channel * @param {string[]} [args=[]] - arguments to pass to the command * @param {any} [options={}] - options and flags for the arguments * @param {(string) => {}} - callback for stdout text */ export function spawn( command: string, args: string[] = [], options: child_process.SpawnOptions = {}, output?: {channel?: vscode.OutputChannel, stdout?: (s: string) => void, stderr?: (s: string) => void}, ): Thenable<object> { return new Promise((resolve, reject) => { options.cwd = options.cwd || path.resolve(path.join(__dirname, "..")); const child = child_process.spawn(command, args, options); let codepage = "65001"; if (os.platform() === "win32") { try { const chcp = child_process.execSync("chcp.com"); codepage = chcp.toString().split(":").pop().trim(); } catch (error) { arduinoChannel.warning(`Defaulting to code page 850 because chcp.com failed.\ \rEnsure your path includes %SystemRoot%\\system32\r${error.message}`); codepage = "850"; } } if (output) { if (output.channel || output.stdout) { child.stdout.on("data", (data: Buffer) => { const decoded = decodeData(data, codepage); if (output.stdout) { output.stdout(decoded); } if (output.channel) { output.channel.append(decoded); } }); } if (output.channel || output.stderr) { child.stderr.on("data", (data: Buffer) => { const decoded = decodeData(data, codepage); if (output.stderr) { output.stderr(decoded); } if (output.channel) { output.channel.append(decoded); } }); } } child.on("error", (error) => reject({ error })); child.on("exit", (code) => { if (code === 0) { resolve({ code }); } else { reject({ code }); } }); }); } export function decodeData(data: Buffer, codepage: string): string { if (Object.prototype.hasOwnProperty.call(encodingMapping, codepage)) { return iconv.decode(data, encodingMapping[codepage]); } return data.toString(); } export function tryParseJSON(jsonString: string) { try { const jsonObj = JSON.parse(jsonString); if (jsonObj && typeof jsonObj === "object") { return jsonObj; } } catch (ex) { } return undefined; } export function isJunk(filename: string): boolean { // tslint:disable-next-line const re = /^npm-debug\.log$|^\..*\.swp$|^\.DS_Store$|^\.AppleDouble$|^\.LSOverride$|^Icon\r$|^\._.*|^\.Spotlight-V100(?:$|\/)|\.Trashes|^__MACOSX$|~$|^Thumbs\.db$|^ehthumbs\.db$|^Desktop\.ini$/; return re.test(filename); } export function filterJunk(files: any[]): any[] { return files.filter((file) => !isJunk(file)); } export function parseProperties(propertiesFile: string): Thenable<object> { return new Promise((resolve, reject) => { properties.parse(propertiesFile, { path: true }, (error, obj) => { if (error) { reject(error); } else { resolve(obj); } }); }); } export function formatVersion(version: string): string { if (!version) { return version; } const versions = String(version).split("."); if (versions.length < 2) { versions.push("0"); } if (versions.length < 3) { versions.push("0"); } return versions.join("."); } export function trim(value: any) { if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) { value[i] = trim(value[i]); } } else if (typeof value === "string") { value = value.trim(); } return value; } export function union(a: any[], b: any[], compare?: (item1, item2) => boolean) { const result = [].concat(a); b.forEach((item) => { const exist = result.find((element) => { return (compare ? compare(item, element) : Object.is(item, element)); }); if (!exist) { result.push(item); } }); return result; } /** * This method pads the current string with another string (repeated, if needed) * so that the resulting string reaches the given length. * The padding is applied from the start (left) of the current string. * @argument {string} sourceString * @argument {string} targetLength * @argument {string} padString */ export function padStart(sourceString: string, targetLength: number, padString?: string): string { if (!sourceString) { return sourceString; } if (!(String.prototype as any).padStart) { // https://github.com/uxitten/polyfill/blob/master/string.polyfill.js padString = String(padString || " "); if (sourceString.length > targetLength) { return sourceString; } else { targetLength = targetLength - sourceString.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length); // append to original to ensure we are longer than needed } return padString.slice(0, targetLength) + sourceString; } } else { return (sourceString as any).padStart(targetLength, padString); } } export function parseConfigFile(fullFileName, filterComment: boolean = true): Map<string, string> { const result = new Map<string, string>(); if (fileExistsSync(fullFileName)) { const rawText = fs.readFileSync(fullFileName, "utf8"); const lines = rawText.split("\n"); lines.forEach((line) => { if (line) { line = line.trim(); if (filterComment) { if (line.trim() && line.startsWith("#")) { return; } } const separator = line.indexOf("="); if (separator > 0) { const key = line.substring(0, separator).trim(); const value = line.substring(separator + 1, line.length).trim(); result.set(key, value); } } }); } return result; } export function getRegistryValues(hive: string, key: string, name: string): Promise<string> { return new Promise((resolve, reject) => { try { const regKey = new WinReg({ hive, key, }); regKey.valueExists(name, (e, exists) => { if (e) { return reject(e); } if (exists) { regKey.get(name, (err, result) => { if (!err) { resolve(result ? result.value : ""); } else { reject(err); } }); } else { resolve(""); } }); } catch (ex) { reject(ex); } }); } export function convertToHex(number, width = 0) { return padStart(number.toString(16), width, "0"); } /** * This will accept any Arduino*.app on Mac OS, * in case you named Arduino with a version number * @argument {string} arduinoPath */ export function resolveMacArduinoAppPath(arduinoPath: string, useArduinoCli = false): string { if (useArduinoCli || /Arduino.*\.app/.test(arduinoPath)) { return arduinoPath; } else { return path.join(arduinoPath, "Arduino.app"); } }
the_stack
import * as _ from 'lodash'; import { referenceForModel, apiVersionForModel } from '@console/internal/module/k8s'; import { ClusterTaskModel, PipelineRunModel, TaskModel, PipelineModel, ClusterTriggerBindingModel, TriggerBindingModel, } from '../../models'; import { pipelineTestData, DataState, PipelineExampleNames } from '../../test-data/pipeline-data'; import { PipelineKind } from '../../types'; import { getResources, augmentRunsToData, getTaskStatus, TaskStatus, getRunStatusColor, runStatus, getResourceModelFromTask, pipelineRefExists, getPipelineFromPipelineRun, totalPipelineRunTasks, getResourceModelFromTaskKind, getResourceModelFromBindingKind, shouldHidePipelineRunStop, } from '../pipeline-augment'; import { testData } from './pipeline-augment-test-data'; describe('PipelineAugment test getResources create correct resources for firehose', () => { it('expect resources to be null for no data', () => { const resources = getResources(testData[0].data); expect(resources.resources).toBe(null); expect(resources.propsReferenceForRuns).toBe(null); }); it('expect resources to be null for empty data array', () => { const resources = getResources(testData[1].data); expect(resources.resources).toBe(null); expect(resources.propsReferenceForRuns).toBe(null); }); it('expect resources to be of length 1 and have the following properties & childprops', () => { const resources = getResources(testData[2].data); expect(resources.resources.length).toBe(1); expect(resources.resources[0].kind).toBe(referenceForModel(PipelineRunModel)); expect(resources.resources[0].namespace).toBe(testData[2].data[0].metadata.namespace); expect(resources.propsReferenceForRuns.length).toBe(1); }); it('expect resources to be of length 2 and have the following properties & childprops', () => { const resources = getResources(testData[3].data); expect(resources.resources.length).toBe(2); expect(resources.resources[0].kind).toBe(referenceForModel(PipelineRunModel)); expect(resources.resources[1].kind).toBe(referenceForModel(PipelineRunModel)); expect(resources.resources[0].namespace).toBe(testData[3].data[0].metadata.namespace); expect(resources.resources[0].namespace).toBe(testData[3].data[1].metadata.namespace); expect(resources.propsReferenceForRuns.length).toBe(2); }); }); describe('PipelineAugment test correct data is augmented', () => { it('expect additional resources to be correctly added using augmentRunsToData', () => { const newData = augmentRunsToData( testData[2].data, testData[2].propsReferenceForRuns, testData[2].keyedRuns, ); expect(newData.length).toBe(1); expect(newData[0].latestRun.metadata.name).toBe( testData[2].keyedRuns.apple1Runs.data[0].metadata.name, ); }); it('expect additional resources to be added using latest run', () => { const newData = augmentRunsToData( testData[3].data, testData[3].propsReferenceForRuns, testData[3].keyedRuns, ); expect(newData.length).toBe(2); expect(newData[0].latestRun.metadata.name).toBe( testData[3].keyedRuns.apple1Runs.data[1].metadata.name, ); expect(newData[1].latestRun.metadata.name).toBe( testData[3].keyedRuns.apple2Runs.data[0].metadata.name, ); }); }); describe('PipelineAugment test getRunStatusColor handles all runStatus values', () => { it('expect all but PipelineNotStarted to produce a non-default result', () => { // Verify that we cover colour states for all the runStatus values const failCase = 'PipelineNotStarted'; const defaultCase = getRunStatusColor(runStatus[failCase]); const allOtherStatuses = Object.keys(runStatus) .filter((status) => status !== failCase) .map((status) => runStatus[status]); expect(allOtherStatuses).not.toHaveLength(0); allOtherStatuses.forEach((statusValue) => { const { message } = getRunStatusColor(statusValue); expect(defaultCase.message).not.toEqual(message); }); }); it('expect all status colors to return visible text to show as a descriptor of the colour', () => { const runStates = Object.values(runStatus); expect(runStates).not.toHaveLength(0); runStates.forEach((statusValue) => { const { message } = getRunStatusColor(statusValue); expect(message).not.toHaveLength(0); }); }); }); describe('PipelineAugment test correct task status state is pulled from pipeline/pipelineruns', () => { it('expect no arguments to produce a net-zero result', () => { // Null check + showcasing we get at least 1 value out of the function const emptyTaskStatus = getTaskStatus(null, null); expect(emptyTaskStatus).toEqual({ PipelineNotStarted: 1, Pending: 0, Running: 0, Succeeded: 0, Failed: 0, Cancelled: 0, Skipped: 0, }); }); const getExpectedTaskCount = (pipeline: PipelineKind): number => pipeline.spec.tasks.length + (pipeline.spec.finally?.length || 0); const sumTaskStatuses = (status: TaskStatus): number => Object.values(status).reduce((acc, v) => acc + v, 0); describe('Successfully completed Pipelines', () => { // Simply put, when a pipeline run is finished successfully, all tasks must have succeeded it('expect a simple pipeline to have task-count equal to Succeeded states', () => { const simpleTestData = pipelineTestData[PipelineExampleNames.SIMPLE_PIPELINE]; const expectedTaskCount = getExpectedTaskCount(simpleTestData.pipeline); const taskStatus = getTaskStatus( simpleTestData.pipelineRuns[DataState.SUCCESS], simpleTestData.pipeline, ); const taskCount = totalPipelineRunTasks(simpleTestData.pipeline); expect(taskStatus.Succeeded).toEqual(expectedTaskCount); expect(sumTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); it('expect a complex pipeline to have task-count equal to Succeeded states', () => { const complexTestData = pipelineTestData[PipelineExampleNames.COMPLEX_PIPELINE]; const expectedTaskCount = getExpectedTaskCount(complexTestData.pipeline); const taskStatus = getTaskStatus( complexTestData.pipelineRuns[DataState.SUCCESS], complexTestData.pipeline, ); const taskCount = totalPipelineRunTasks(complexTestData.pipeline); expect(taskStatus.Succeeded).toEqual(expectedTaskCount); expect(sumTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); it('expect a pipeline to consider finally tasks in task-count', () => { const finallyTestData = pipelineTestData[PipelineExampleNames.PIPELINE_WITH_FINALLY]; const expectedTaskCount = getExpectedTaskCount(finallyTestData.pipeline); const taskStatus = getTaskStatus( finallyTestData.pipelineRuns[DataState.SUCCESS], finallyTestData.pipeline, ); const taskCount = totalPipelineRunTasks(finallyTestData.pipeline); expect(taskStatus.Succeeded).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); }); describe('In Progress pipelines', () => { // There are various states to in progress, the status of a task is either: // - completed (with some left) // - currently running // - waiting to start const sumInProgressTaskStatuses = (status: TaskStatus): number => status.Succeeded + status.Running + status.Pending; it('expect a simple pipeline to have task-count equal to Pending, Running and Succeeded states', () => { const simpleTestData = pipelineTestData[PipelineExampleNames.SIMPLE_PIPELINE]; const expectedTaskCount = getExpectedTaskCount(simpleTestData.pipeline); const taskStatus = getTaskStatus( simpleTestData.pipelineRuns[DataState.IN_PROGRESS], simpleTestData.pipeline, ); const taskCount = totalPipelineRunTasks(simpleTestData.pipeline); expect(sumInProgressTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(sumTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); it('expect a complex pipeline to have task-count equal to Pending, Running and Succeeded states', () => { const complexTestData = pipelineTestData[PipelineExampleNames.COMPLEX_PIPELINE]; const expectedTaskCount = getExpectedTaskCount(complexTestData.pipeline); const taskStatus = getTaskStatus( complexTestData.pipelineRuns[DataState.IN_PROGRESS], complexTestData.pipeline, ); const taskCount = totalPipelineRunTasks(complexTestData.pipeline); expect(sumInProgressTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(sumTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); it('should not hide the pipelinerun stop action ', () => { const pipelineRun = pipelineTestData[PipelineExampleNames.EMBEDDED_TASK_SPEC_MOCK_APP].pipelineRuns[ DataState.IN_PROGRESS ]; expect(shouldHidePipelineRunStop(pipelineRun)).toEqual(false); }); it('should hide the pipelinerun stop action ', () => { const pipelineRun = pipelineTestData[PipelineExampleNames.EMBEDDED_TASK_SPEC_MOCK_APP].pipelineRuns[ DataState.SUCCESS ]; expect(shouldHidePipelineRunStop(pipelineRun)).toEqual(true); }); }); describe('Failed / Cancelled pipelines', () => { // When a pipeline run fails or is cancelled - all not-started tasks are cancelled and any on-going tasks fail const sumFailedTaskStatus = (status: TaskStatus): number => status.Failed; const sumCancelledTaskStatus = (status: TaskStatus): number => status.Cancelled; const sumSuccededTaskStatus = (status: TaskStatus): number => status.Succeeded; const complexTestData = pipelineTestData[PipelineExampleNames.COMPLEX_PIPELINE]; it('expect a partial pipeline to have task-count equal to Failed and Cancelled states', () => { const partialTestData = pipelineTestData[PipelineExampleNames.PARTIAL_PIPELINE]; const expectedTaskCount = getExpectedTaskCount(partialTestData.pipeline); const taskStatus = getTaskStatus( partialTestData.pipelineRuns[DataState.FAILED_BUT_COMPLETE], partialTestData.pipeline, ); const taskCount = totalPipelineRunTasks(partialTestData.pipeline); expect(sumFailedTaskStatus(taskStatus)).toEqual(0); expect(sumCancelledTaskStatus(taskStatus)).toEqual(expectedTaskCount); expect(sumTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); it(`expect correct task status for PipelineRun cancelled at beginning`, () => { const expected = { succeeded: 1, failed: 0, cancelled: 12 }; const expectedTaskCount = getExpectedTaskCount(complexTestData.pipeline); const taskStatus = getTaskStatus( complexTestData.pipelineRuns[DataState.CANCELLED1], complexTestData.pipeline, ); const taskCount = totalPipelineRunTasks(complexTestData.pipeline); expect(sumFailedTaskStatus(taskStatus)).toEqual(expected.failed); expect(sumSuccededTaskStatus(taskStatus)).toEqual(expected.succeeded); expect(sumCancelledTaskStatus(taskStatus)).toEqual(expected.cancelled); expect(sumTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); it(`expect correct task status for PipelineRun failed at beginning`, () => { const expected = { succeeded: 0, failed: 1, cancelled: 12 }; const expectedTaskCount = getExpectedTaskCount(complexTestData.pipeline); const taskStatus = getTaskStatus( complexTestData.pipelineRuns[DataState.FAILED1], complexTestData.pipeline, ); const taskCount = totalPipelineRunTasks(complexTestData.pipeline); expect(sumFailedTaskStatus(taskStatus)).toEqual(expected.failed); expect(sumSuccededTaskStatus(taskStatus)).toEqual(expected.succeeded); expect(sumCancelledTaskStatus(taskStatus)).toEqual(expected.cancelled); expect(sumTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); it(`expect correct task status for PLR cancelled at stage 2 parallel`, () => { const expected = { succeeded: 3, failed: 0, cancelled: 10 }; const expectedTaskCount = getExpectedTaskCount(complexTestData.pipeline); const taskStatus = getTaskStatus( complexTestData.pipelineRuns[DataState.CANCELLED2], complexTestData.pipeline, ); const taskCount = totalPipelineRunTasks(complexTestData.pipeline); expect(sumFailedTaskStatus(taskStatus)).toEqual(expected.failed); expect(sumSuccededTaskStatus(taskStatus)).toEqual(expected.succeeded); expect(sumCancelledTaskStatus(taskStatus)).toEqual(expected.cancelled); expect(sumTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); it(`expect correct task status for PLR failed at stage 2 parallel`, () => { const expected = { succeeded: 2, failed: 1, cancelled: 10 }; const expectedTaskCount = getExpectedTaskCount(complexTestData.pipeline); const taskStatus = getTaskStatus( complexTestData.pipelineRuns[DataState.FAILED2], complexTestData.pipeline, ); const taskCount = totalPipelineRunTasks(complexTestData.pipeline); expect(sumFailedTaskStatus(taskStatus)).toEqual(expected.failed); expect(sumSuccededTaskStatus(taskStatus)).toEqual(expected.succeeded); expect(sumCancelledTaskStatus(taskStatus)).toEqual(expected.cancelled); expect(sumTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); it(`expect correct task status for PLR cancelled at stage 3`, () => { const expected = { succeeded: 4, failed: 0, cancelled: 9 }; const expectedTaskCount = getExpectedTaskCount(complexTestData.pipeline); const taskStatus = getTaskStatus( complexTestData.pipelineRuns[DataState.CANCELLED3], complexTestData.pipeline, ); const taskCount = totalPipelineRunTasks(complexTestData.pipeline); expect(sumFailedTaskStatus(taskStatus)).toEqual(expected.failed); expect(sumSuccededTaskStatus(taskStatus)).toEqual(expected.succeeded); expect(sumCancelledTaskStatus(taskStatus)).toEqual(expected.cancelled); expect(sumTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); it(`expect correct task status for PLR failed at stage 3`, () => { const expected = { succeeded: 2, failed: 2, cancelled: 9 }; const expectedTaskCount = getExpectedTaskCount(complexTestData.pipeline); const taskStatus = getTaskStatus( complexTestData.pipelineRuns[DataState.FAILED3], complexTestData.pipeline, ); const taskCount = totalPipelineRunTasks(complexTestData.pipeline); expect(sumFailedTaskStatus(taskStatus)).toEqual(expected.failed); expect(sumSuccededTaskStatus(taskStatus)).toEqual(expected.succeeded); expect(sumCancelledTaskStatus(taskStatus)).toEqual(expected.cancelled); expect(sumTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); }); describe('Skipped pipelines', () => { // When a pipeline run skips certain task based on the when expression/condtion const sumSkippedTaskStatus = (status: TaskStatus): number => status.Skipped; const sumSuccededTaskStatus = (status: TaskStatus): number => status.Succeeded; const complexTestData = pipelineTestData[PipelineExampleNames.CONDITIONAL_PIPELINE]; it(`expect to return the skipped task status count if whenExpression is used`, () => { const expected = { succeeded: 1, skipped: 1 }; const expectedTaskCount = getExpectedTaskCount(complexTestData.pipeline); const taskStatus = getTaskStatus( complexTestData.pipelineRuns[DataState.SKIPPED], complexTestData.pipeline, ); const taskCount = totalPipelineRunTasks(complexTestData.pipeline); expect(sumSkippedTaskStatus(taskStatus)).toEqual(expected.skipped); expect(sumSuccededTaskStatus(taskStatus)).toEqual(expected.succeeded); expect(sumTaskStatuses(taskStatus)).toEqual(expectedTaskCount); expect(taskCount).toEqual(expectedTaskCount); }); }); }); describe('PipelineAugment test successfully determine Task type', () => { it('expect to always get back a model', () => { const model = getResourceModelFromTask({ name: null, taskRef: { name: null } }); expect(model).toBe(TaskModel); }); it('expect to get a TaskModel for normal tasks', () => { const complexTestData = pipelineTestData[PipelineExampleNames.COMPLEX_PIPELINE]; const model = getResourceModelFromTask(complexTestData.pipeline.spec.tasks[0]); expect(model).toBe(TaskModel); }); it('expect to get a ClusterTaskModel for tasks of a ClusterTask kind', () => { const complexTestData = pipelineTestData[PipelineExampleNames.CLUSTER_PIPELINE]; const model = getResourceModelFromTask(complexTestData.pipeline.spec.tasks[0]); expect(model).toBe(ClusterTaskModel); }); }); describe('Pipeline exists test to determine whether a pipeline is linked to a pipelinerun', () => { it('expect to return true if pipelineref is available in pipelinerun spec', () => { const pipelineRunWithPipelineRef = pipelineTestData[PipelineExampleNames.SIMPLE_PIPELINE].pipelineRuns[DataState.SUCCESS]; const pipelineFound = pipelineRefExists(pipelineRunWithPipelineRef); expect(pipelineFound).toBeTruthy(); }); it('expect to return false if pipelineref is missing in pipelinerun spec', () => { const pipelineRunWithoutPipelineRef = _.omit( pipelineTestData[PipelineExampleNames.SIMPLE_PIPELINE].pipelineRuns[DataState.SUCCESS], 'spec.pipelineRef', ); const pipelineFound = pipelineRefExists(pipelineRunWithoutPipelineRef); expect(pipelineFound).toBeFalsy(); }); }); describe('Pipelinerun graph to show the executed pipeline structure', () => { const testPipelineRun = pipelineTestData[PipelineExampleNames.SIMPLE_PIPELINE].pipelineRuns[DataState.SUCCESS]; it('expect to return null, if pipelinerun does not have a pipelineSpec field in status or spec', () => { const plrWithoutPipelineSpec = _.omit(testPipelineRun, ['status']); const executedPipeline = getPipelineFromPipelineRun(plrWithoutPipelineSpec); expect(executedPipeline).toEqual(null); }); it('expect to return null, if pipelinerun does not have pipeline labels or name in the metadata field', () => { const executedPipeline = getPipelineFromPipelineRun( _.omit(testPipelineRun, ['metadata.labels', 'metadata.name']), ); expect(executedPipeline).toBe(null); }); it('expect to return pipeline, if pipelinerun has pipelineSpec in spec field', () => { const plrWithEmbeddedPipeline = pipelineTestData[PipelineExampleNames.EMBEDDED_PIPELINE_SPEC].pipelineRuns[DataState.SUCCESS]; const executedPipeline = getPipelineFromPipelineRun(plrWithEmbeddedPipeline); expect(executedPipeline).not.toBe(null); expect(executedPipeline).toMatchObject({ apiVersion: apiVersionForModel(PipelineModel), kind: 'Pipeline', metadata: { name: plrWithEmbeddedPipeline.metadata.name, namespace: plrWithEmbeddedPipeline.metadata.namespace, }, spec: { ...plrWithEmbeddedPipeline.spec.pipelineSpec }, }); }); it('expect to return the pipeline, if pipelinerun has pipelineSpec in status field', () => { const executedPipeline = getPipelineFromPipelineRun(testPipelineRun); expect(executedPipeline).not.toBe(null); expect(executedPipeline).toMatchObject({ ...pipelineTestData[PipelineExampleNames.SIMPLE_PIPELINE].pipeline, apiVersion: apiVersionForModel(PipelineModel), }); }); }); describe('getResourceModelFromTaskKind', () => { it('should handle null', () => { expect(getResourceModelFromTaskKind(null)).toBe(null); }); it('should be able to find ClusterTaskModel', () => { expect(getResourceModelFromTaskKind('ClusterTask')).toBe(ClusterTaskModel); }); it('should be able to find TaskModel', () => { expect(getResourceModelFromTaskKind('Task')).toBe(TaskModel); }); it('should return the TaskModel for undefined', () => { expect(getResourceModelFromTaskKind(undefined)).toBe(TaskModel); }); it('should return null for any unknown value', () => { expect(getResourceModelFromTaskKind('EmbeddedTask')).toBe(null); expect(getResourceModelFromTaskKind('123%$^&asdf')).toBe(null); expect(getResourceModelFromTaskKind('Nothing special')).toBe(null); }); }); describe('getResourceModelFromBindingKind', () => { it('should handle null', () => { expect(getResourceModelFromBindingKind(null)).toBe(null); }); it('should be able to find ClusterTriggerBindingModel', () => { expect(getResourceModelFromBindingKind('ClusterTriggerBinding')).toBe( ClusterTriggerBindingModel, ); }); it('should be able to find TriggerBindingModel', () => { expect(getResourceModelFromBindingKind('TriggerBinding')).toBe(TriggerBindingModel); }); it('should return TriggerBindingModel for undefined', () => { expect(getResourceModelFromBindingKind(undefined)).toBe(TriggerBindingModel); }); it('should return null for any unknown value', () => { expect(getResourceModelFromBindingKind('EmbeddedBinding')).toBe(null); expect(getResourceModelFromBindingKind('123%$^&asdf')).toBe(null); expect(getResourceModelFromBindingKind('Nothing special')).toBe(null); }); });
the_stack
import { Link, Button, Spacer, Text, Card, Input, Row, Col, Tooltip, Loading, } from "@geist-ui/react"; import QuestionCircle from "@geist-ui/react-icons/questionCircle"; import { ethers } from "ethers"; import { useState } from "react"; import { Connection } from "./containers/Connection"; import { FlashbotsBundleProvider, FlashbotsBundleResolution, FlashbotsBundleTransaction, } from "@flashbots/ethers-provider-bundle"; import { checkSimulation, gasPriceToGwei, getTransactionsLog, } from "./engine/Utils"; import { Base } from "./engine/Base"; import { TransferENS } from "./engine/TransferENS"; import { parseUnits } from "ethers/lib/utils"; export enum TransferENSProgress { NotStarted, GetWETH, ApproveContract, SignTransaction, BroadcastingTransaction, Success, Failed, } export function ENS({ blocksInTheFuture, relayerURL, }: { blocksInTheFuture: string; relayerURL: string; }) { const { provider, signer } = Connection.useContainer(); const [compromisedPrivateKey, setCompromisedPrivateKey] = useState(""); const [ensDomain, setENSAddress] = useState(""); const [newENSOwner, setENSRecipient] = useState(""); const [ethBribeAmount, setEthBribeAmount] = useState("0.05"); const [rescuingState, setRescuingState] = useState<TransferENSProgress>( TransferENSProgress.NotStarted ); // eslint-disable-next-line const [_, setThreadId] = useState<NodeJS.Timeout | null>(null); const [invalidPrivateKey, setInvalidPrivateKey] = useState(false); const [invalidENSRecipient, setInvalidENSRecipient] = useState(false); const [successTxHash, setSuccessTxHash] = useState(""); const [failReason, setFailReason] = useState(""); const [failReasonVerbose, setFailReasonVerbose] = useState(""); const [lastBlockTried, setLastBlockTried] = useState(0); const [broadcastAttempts, setBroadcastAttempts] = useState(0); const validateInputs = () => { let valid = true; if (provider && signer) { try { new ethers.Wallet(compromisedPrivateKey, provider); setInvalidPrivateKey(false); } catch (e) { valid = false; setInvalidPrivateKey(true); } } if (!ethers.utils.isAddress(newENSOwner)) { setInvalidENSRecipient(true); valid = false; } else { setInvalidENSRecipient(false); } return valid; }; const rescueENS = async () => { if (provider && signer) { // Wallets const walletAuth = ethers.Wallet.createRandom(provider); const walletZeroGas = new ethers.Wallet(compromisedPrivateKey, provider); const signerAddress = await signer.getAddress(); const bribeAmount = parseUnits(ethBribeAmount); // Make sure sender has enough ETH and approved enough allowance to the contract // Check WETH Balance const wethContract = Base.wethContract.connect(signer); const balance = await wethContract.balanceOf(signerAddress); if (balance.lt(bribeAmount)) { setRescuingState(TransferENSProgress.GetWETH); const tx = await wethContract.deposit({ value: bribeAmount }); await tx.wait(); } // Check WETH allowance const allowance = await wethContract.allowance( signerAddress, Base.mevBriberContract.address ); // Not enough allowance, we need to approve it if (allowance.lt(bribeAmount)) { setRescuingState(TransferENSProgress.ApproveContract); const tx = await wethContract.approve( Base.mevBriberContract.address, bribeAmount ); await tx.wait(); } const flashbotsProvider = await FlashbotsBundleProvider.create( provider, walletAuth, relayerURL ); const engine = new TransferENS( provider, walletZeroGas, signer, ensDomain, newENSOwner ); let zeroGasTxs: FlashbotsBundleTransaction[]; try { zeroGasTxs = await engine.getZeroGasPriceTx(); } catch (e) { console.log(`Error: ${e.toString()}`); setRescuingState(TransferENSProgress.Failed); setFailReason("Failed to construct ENS transfer tx"); setFailReasonVerbose(e.toString()); return; } setRescuingState(TransferENSProgress.SignTransaction); const donorTx = await engine.getDonorTxWithWETH(bribeAmount); const bundleTransactions: Array<FlashbotsBundleTransaction> = [ ...zeroGasTxs, donorTx, ]; const signedBundle = await flashbotsProvider.signBundle( bundleTransactions ); const moreLogs = await getTransactionsLog( bundleTransactions, signedBundle ); console.log("moreLogs", moreLogs); try { const gasPrice = await checkSimulation(flashbotsProvider, signedBundle); console.log( `Gas price: ${gasPriceToGwei( gasPrice )} gwei\n${await engine.getDescription()}` ); } catch (e) { console.log(`Error: ${e.toString()}`); setRescuingState(TransferENSProgress.Failed); setFailReason( "Simulation failed, perhaps a non standard ENS transfer?" ); setFailReasonVerbose(e.toString()); return; } setBroadcastAttempts(0); setRescuingState(TransferENSProgress.BroadcastingTransaction); const keepSubmittingTx = async () => { const blockNumber = await provider.getBlockNumber(); setBroadcastAttempts((a) => a + 1); setLastBlockTried(blockNumber); let gasPrice; try { gasPrice = await checkSimulation(flashbotsProvider, signedBundle); console.log( `Gas price: ${gasPriceToGwei( gasPrice )} gwei\n${await engine.getDescription()}` ); } catch (e) { console.log("\n" + e.toString()); setRescuingState((prevState: TransferENSProgress) => { // Only update if we've succeeded if (prevState === TransferENSProgress.BroadcastingTransaction) { return TransferENSProgress.Failed; } return prevState; }); setFailReason("Transfer failed: Nonce too high"); setFailReasonVerbose( "Account nonce has changed since message signature" ); return; } const targetBlockNumber = blockNumber + parseInt(blocksInTheFuture); console.log( `Current Block Number: ${blockNumber}, Target Block Number:${targetBlockNumber}, gasPrice: ${gasPriceToGwei( gasPrice )} gwei` ); const bundleResponse = await flashbotsProvider.sendBundle( bundleTransactions, targetBlockNumber ); const bundleResolution = await bundleResponse.wait(); if (bundleResolution === FlashbotsBundleResolution.BundleIncluded) { console.log(`Congrats, included in ${targetBlockNumber}`); setRescuingState((prevState: TransferENSProgress) => { // Only update if we've succeeded if (prevState === TransferENSProgress.BroadcastingTransaction) { return TransferENSProgress.Success; } return prevState; }); setSuccessTxHash(bundleResponse.bundleTransactions[0].hash); setThreadId((curThreadId) => { if (curThreadId) { clearInterval(curThreadId); } return null; }); } else if ( bundleResolution === FlashbotsBundleResolution.BlockPassedWithoutInclusion ) { console.log(`Not included in ${targetBlockNumber}`); } else if ( bundleResolution === FlashbotsBundleResolution.AccountNonceTooHigh ) { console.log("Nonce too high, bailing"); setThreadId((curThreadId) => { if (curThreadId) { clearInterval(curThreadId); } return null; }); setRescuingState((prevState: TransferENSProgress) => { // Only update if we've succeeded if (prevState === TransferENSProgress.BroadcastingTransaction) { return TransferENSProgress.Failed; } return prevState; }); setFailReason("Transfer failed: Nonce too high"); setFailReasonVerbose( "Account nonce has changed since message signature" ); } }; keepSubmittingTx(); setThreadId(setInterval(keepSubmittingTx, 13000)); } }; const isRescuing = !( rescuingState === TransferENSProgress.NotStarted || rescuingState === TransferENSProgress.Failed || rescuingState === TransferENSProgress.Success ); return ( <Card> <Text h3>Gasless ENS Transfers</Text> <Text type="warning"> Only tested on native metamask accounts. Does not work with hardware wallets. </Text> <Row gap={0.8}> <Col> <Spacer y={1} /> <Input.Password status={invalidPrivateKey ? "error" : "default"} value={compromisedPrivateKey} onChange={(e) => setCompromisedPrivateKey(e.target.value)} placeholder="private key" width="100%" > <Text h5> Compromised Private Key&nbsp; <Tooltip type="secondary" text={ "Private key who owns the ENS domain, but does not have Ether" } > <QuestionCircle size={15} /> </Tooltip> <Text type="error"> Pasting sensitive information such as private keys online is not recommended. If possible, please{" "} <Link color href="http://github.com/kendricktan/flashbots.tools" > build </Link>{" "} and run this website locally. </Text> </Text> </Input.Password> <Spacer y={1} /> <Input value={ensDomain} onChange={(e) => setENSAddress(e.target.value)} placeholder="alice.eth" width="100%" > <Text h5> ENS Domain&nbsp; <Tooltip type="secondary" text={"ENS domain name. e.g. alice.eth"} > <QuestionCircle size={15} /> </Tooltip> </Text> </Input> <Spacer y={1} /> <Input status={invalidENSRecipient ? "error" : "default"} value={newENSOwner} onChange={(e) => setENSRecipient(e.target.value)} placeholder="ens recipient address" width="100%" > <Text h5> New ENS Owner Address&nbsp; <Tooltip type="secondary" text={"New owner of the ENS domain"}> <QuestionCircle size={15} /> </Tooltip> </Text> </Input> <Spacer y={1} /> <Input value={ethBribeAmount} onChange={(e) => setEthBribeAmount(e.target.value)} placeholder="amount" width="100%" > <Text h5> Eth Bribe Amount&nbsp; <Tooltip type="secondary" text={"Amount of ETH used to bribe miners"} > <QuestionCircle size={15} /> </Tooltip> </Text> </Input> </Col> <Col> <Row align="middle" justify="center" style={{ height: "100%" }}> <Col style={{ width: "100%", textAlign: "center" }}> {rescuingState === TransferENSProgress.NotStarted && ( <> <Text b>Rescue your ENS from a compromised wallet!</Text> <Spacer y={0.1} /> <Text small type="secondary"> Note: Connected metamask account will be paying for the bribes </Text> </> )} {rescuingState === TransferENSProgress.GetWETH && ( <> <Text b>Wrapping {ethBribeAmount} ETH into WETH</Text> <Spacer y={0.1} /> <Text small type="secondary"> 1/3 </Text> <Loading /> </> )} {rescuingState === TransferENSProgress.ApproveContract && ( <> <Text b> Approving {ethBribeAmount} WETH to be used by bribers </Text> <Spacer y={0.1} /> <Text small type="secondary"> 2/3 </Text> <Loading /> </> )} {rescuingState === TransferENSProgress.SignTransaction && ( <> <Text b>Sign tx to be broadcasted</Text> <Spacer y={0.1} /> <Text small type="secondary"> 3/3 </Text> <Spacer y={0.1} /> <Loading /> </> )} {rescuingState === TransferENSProgress.BroadcastingTransaction && ( <> <Text b> Broadcasting transaction ({broadcastAttempts} tries) </Text> <Spacer y={0.1} /> <Text small type="secondary"> Attempting to mine tx on block {lastBlockTried} </Text> <Spacer y={1} /> <Text small type="secondary"> Do <strong>not</strong> close this window until this is successful. <br /> If this takes too long, increase Eth bribe amount. </Text> <Loading /> </> )} {rescuingState === TransferENSProgress.Success && ( <> <Text b> <Link color href={`http://etherscan.io/tx/${successTxHash}`} > Transaction successful </Link> </Text> <Spacer y={0.1} /> <Text small type="secondary"> TxHash: {successTxHash} </Text> </> )} {rescuingState === TransferENSProgress.Failed && ( <> <Text b type="error"> Transaction failed {failReason} </Text> <Spacer y={0.1} /> <Text small type="secondary"> {failReasonVerbose} </Text> </> )} </Col> </Row> </Col> </Row> <Spacer y={1} /> <Row> <Col> <Button onClick={async () => { if (validateInputs()) { await rescueENS(); } }} disabled={true} type="secondary" style={{ width: "100%" }} > {isRescuing ? "Rescuing..." : "Rescue ENS"} </Button> </Col> </Row> </Card> ); }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type SaleBelowTheFoldQueryVariables = { saleID?: string | null | undefined; }; export type SaleBelowTheFoldQueryResponse = { readonly unfilteredSaleArtworksConnection: { readonly counts: { readonly total: number | null; } | null; readonly " $fragmentRefs": FragmentRefs<"SaleLotsList_unfilteredSaleArtworksConnection">; } | null; readonly " $fragmentRefs": FragmentRefs<"SaleLotsList_saleArtworksConnection">; }; export type SaleBelowTheFoldQuery = { readonly response: SaleBelowTheFoldQueryResponse; readonly variables: SaleBelowTheFoldQueryVariables; }; /* query SaleBelowTheFoldQuery( $saleID: ID ) { ...SaleLotsList_saleArtworksConnection_nfIph unfilteredSaleArtworksConnection: saleArtworksConnection(saleID: $saleID, aggregations: [TOTAL]) { ...SaleLotsList_unfilteredSaleArtworksConnection counts { total } } } fragment ArtworkGridItem_artwork on Artwork { title date saleMessage slug internalID artistNames href sale { isAuction isClosed displayTimelyAt endAt id } saleArtwork { counts { bidderPositions } currentBid { display } lotLabel id } partner { name id } image { url(version: "large") aspectRatio } } fragment InfiniteScrollArtworksGrid_connection on ArtworkConnectionInterface { __isArtworkConnectionInterface: __typename pageInfo { hasNextPage startCursor endCursor } edges { __typename node { slug id image { aspectRatio } ...ArtworkGridItem_artwork } ... on Node { __isNode: __typename id } } } fragment SaleArtworkListItem_artwork on Artwork { artistNames date href image { small: url(version: "small") aspectRatio height width } saleMessage slug title internalID sale { isAuction isClosed displayTimelyAt endAt id } saleArtwork { counts { bidderPositions } currentBid { display } lotLabel id } } fragment SaleArtworkList_connection on ArtworkConnectionInterface { __isArtworkConnectionInterface: __typename edges { __typename node { id ...SaleArtworkListItem_artwork } ... on Node { __isNode: __typename id } } } fragment SaleLotsList_saleArtworksConnection_nfIph on Query { saleArtworksConnection(saleID: $saleID, artistIDs: [], geneIDs: [], aggregations: [FOLLOWED_ARTISTS, ARTIST, MEDIUM, TOTAL], estimateRange: "", first: 10, includeArtworksByFollowedArtists: false, sort: "position") { aggregations { slice counts { count name value } } counts { followedArtists total } edges { node { id __typename } cursor id } ...SaleArtworkList_connection ...InfiniteScrollArtworksGrid_connection pageInfo { endCursor hasNextPage } } } fragment SaleLotsList_unfilteredSaleArtworksConnection on SaleArtworksConnection { counts { total } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "defaultValue": null, "kind": "LocalArgument", "name": "saleID" } ], v1 = { "kind": "Variable", "name": "saleID", "variableName": "saleID" }, v2 = [ { "kind": "Literal", "name": "aggregations", "value": [ "TOTAL" ] }, (v1/*: any*/) ], v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "total", "storageKey": null }, v4 = { "alias": null, "args": null, "concreteType": "FilterSaleArtworksCounts", "kind": "LinkedField", "name": "counts", "plural": false, "selections": [ (v3/*: any*/) ], "storageKey": null }, v5 = [ { "kind": "Literal", "name": "aggregations", "value": [ "FOLLOWED_ARTISTS", "ARTIST", "MEDIUM", "TOTAL" ] }, { "kind": "Literal", "name": "artistIDs", "value": ([]/*: any*/) }, { "kind": "Literal", "name": "estimateRange", "value": "" }, { "kind": "Literal", "name": "first", "value": 10 }, { "kind": "Literal", "name": "geneIDs", "value": ([]/*: any*/) }, { "kind": "Literal", "name": "includeArtworksByFollowedArtists", "value": false }, (v1/*: any*/), { "kind": "Literal", "name": "sort", "value": "position" } ], v6 = { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, v7 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v8 = { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }; return { "fragment": { "argumentDefinitions": (v0/*: any*/), "kind": "Fragment", "metadata": null, "name": "SaleBelowTheFoldQuery", "selections": [ { "alias": "unfilteredSaleArtworksConnection", "args": (v2/*: any*/), "concreteType": "SaleArtworksConnection", "kind": "LinkedField", "name": "saleArtworksConnection", "plural": false, "selections": [ (v4/*: any*/), { "args": null, "kind": "FragmentSpread", "name": "SaleLotsList_unfilteredSaleArtworksConnection" } ], "storageKey": null }, { "args": [ (v1/*: any*/) ], "kind": "FragmentSpread", "name": "SaleLotsList_saleArtworksConnection" } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": (v0/*: any*/), "kind": "Operation", "name": "SaleBelowTheFoldQuery", "selections": [ { "alias": null, "args": (v5/*: any*/), "concreteType": "SaleArtworksConnection", "kind": "LinkedField", "name": "saleArtworksConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "SaleArtworksAggregationResults", "kind": "LinkedField", "name": "aggregations", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "slice", "storageKey": null }, { "alias": null, "args": null, "concreteType": "AggregationCount", "kind": "LinkedField", "name": "counts", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "count", "storageKey": null }, (v6/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "value", "storageKey": null } ], "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "FilterSaleArtworksCounts", "kind": "LinkedField", "name": "counts", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "followedArtists", "storageKey": null }, (v3/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v7/*: any*/), (v8/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "cursor", "storageKey": null }, (v7/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "PageInfo", "kind": "LinkedField", "name": "pageInfo", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "endCursor", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "hasNextPage", "storageKey": null } ], "storageKey": null }, { "kind": "InlineFragment", "selections": [ { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ (v8/*: any*/), { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "date", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": "small", "args": [ { "kind": "Literal", "name": "version", "value": "small" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"small\")" }, { "alias": null, "args": null, "kind": "ScalarField", "name": "aspectRatio", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "height", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "width", "storageKey": null }, { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "large" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"large\")" } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "saleMessage", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "slug", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "isAuction", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "isClosed", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "displayTimelyAt", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "endAt", "storageKey": null }, (v7/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "saleArtwork", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "SaleArtworkCounts", "kind": "LinkedField", "name": "counts", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "bidderPositions", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtworkCurrentBid", "kind": "LinkedField", "name": "currentBid", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "lotLabel", "storageKey": null }, (v7/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Partner", "kind": "LinkedField", "name": "partner", "plural": false, "selections": [ (v6/*: any*/), (v7/*: any*/) ], "storageKey": null } ], "storageKey": null }, { "kind": "TypeDiscriminator", "abstractKey": "__isNode" } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "PageInfo", "kind": "LinkedField", "name": "pageInfo", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "startCursor", "storageKey": null } ], "storageKey": null } ], "type": "ArtworkConnectionInterface", "abstractKey": "__isArtworkConnectionInterface" } ], "storageKey": null }, { "alias": null, "args": (v5/*: any*/), "filters": [ "saleID", "artistIDs", "geneIDs", "aggregations", "estimateRange", "includeArtworksByFollowedArtists", "sort" ], "handle": "connection", "key": "SaleLotsList_saleArtworksConnection", "kind": "LinkedHandle", "name": "saleArtworksConnection" }, { "alias": "unfilteredSaleArtworksConnection", "args": (v2/*: any*/), "concreteType": "SaleArtworksConnection", "kind": "LinkedField", "name": "saleArtworksConnection", "plural": false, "selections": [ (v4/*: any*/) ], "storageKey": null } ] }, "params": { "id": "c0e4b1a325a6ccdd5d1b1f8bea518661", "metadata": {}, "name": "SaleBelowTheFoldQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '3441478a75aa2b99a08059e5634fe553'; export default node;
the_stack
import '@clayui/css/lib/css/atlas.css'; import '@clayui/css/src/scss/cadmin.scss'; import Button from '@clayui/button'; const spritemap = require('@clayui/css/lib/images/icons/icons.svg'); import {ClayDropDownWithItems as DropDownWithItems} from '@clayui/drop-down'; import {ClayCheckbox as Checkbox, ClayInput as Input} from '@clayui/form'; import Icon from '@clayui/icon'; import {Provider} from '@clayui/provider'; import Sticker from '@clayui/sticker'; import {storiesOf} from '@storybook/react'; import React, {useMemo, useState} from 'react'; import {TreeView} from '../src/tree-view'; import largeData from './tree-data.mock.json'; interface IItem { children?: Array<IItem>; name: string; status?: string; type?: string; } const ITEMS_DRIVE = [ { children: [ { children: [ { children: [{name: 'Research 1'}], name: 'Research', }, { children: [{name: 'News 1'}], name: 'News', }, ], name: 'Blogs', }, { children: [ { children: [ { name: 'Instructions.pdf', status: 'success', type: 'pdf', }, ], name: 'PDF', }, { children: [ { name: 'Treeview review.docx', status: 'success', type: 'document', }, { name: 'Heuristics Evaluation.docx', status: 'success', type: 'document', }, ], name: 'Word', }, ], name: 'Documents and Media', }, ], name: 'Liferay Drive', type: 'cloud', }, { children: [{name: 'Blogs'}, {name: 'Documents and Media'}], name: 'Repositories', type: 'repository', }, { children: [{name: 'PDF'}, {name: 'Word'}], name: 'Documents and Media', status: 'warning', }, ]; const cache = new Map(); // This method is just a simulation of filtering a tree but don't consider // using it in production. This is not performative at runtime because it // will traverse the entire tree and create a copy. function createFilter<T extends Array<any>>( tree: T, nestedKey: string, key: string ) { function applyFilter(value: string, tree: T) { tree = tree .map((item) => { const immutableItem = {...item}; if (Array.isArray(immutableItem[nestedKey])) { immutableItem[nestedKey] = applyFilter( value, immutableItem[nestedKey] ); } if (immutableItem[key].includes(value.toLowerCase())) { return immutableItem; } return false; }) .filter(Boolean) as T; return tree; } return { applyFilter: (value: string) => { const result = cache.get(value); if (result) { return result; } if (cache.size === 20) { cache.clear(); } const filtered = applyFilter(value, [...tree] as T); cache.set(value, filtered); return filtered; }, }; } let nodeId = 0; type Node = { children: Array<Node>; id: number; name: string; }; const createNode = ( lenght: number, depth: number, currentDepth: number = 0 ) => { const node: Node = { children: [], id: nodeId, name: `node-${nodeId}`, }; nodeId += 1; if (currentDepth === depth) { return node; } for (let i = 0; i < lenght; i++) { node.children.push(createNode(lenght, depth, currentDepth + 1)); } return node; }; storiesOf('Components|ClayTreeView', module) .add('light', () => ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView displayType="light"> <TreeView.Item> <TreeView.ItemStack> <Icon symbol="folder" /> Root </TreeView.ItemStack> <TreeView.Group> <TreeView.Item>Item</TreeView.Item> </TreeView.Group> </TreeView.Item> </TreeView> </Provider> )) .add('dark', () => ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView className="bg-dark" displayType="dark"> <TreeView.Item> <TreeView.ItemStack> <Icon symbol="folder" /> Root </TreeView.ItemStack> <TreeView.Group> <TreeView.Item>Item</TreeView.Item> </TreeView.Group> </TreeView.Item> </TreeView> </Provider> )) .add('actions', () => ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView> <TreeView.Item actions={ <> <Button displayType={null} monospaced> <Icon symbol="times" /> </Button> <DropDownWithItems items={[ {label: 'One'}, {label: 'Two'}, {label: 'Three'}, ]} trigger={ <Button displayType={null} monospaced> <Icon symbol="ellipsis-v" /> </Button> } /> </> } > <TreeView.ItemStack> <Icon symbol="folder" /> Folder 1 </TreeView.ItemStack> <TreeView.Group> <TreeView.Item>Item 1</TreeView.Item> <TreeView.Item>Item 2</TreeView.Item> <TreeView.Item>Item 3</TreeView.Item> </TreeView.Group> </TreeView.Item> <TreeView.Item actions={ <> <Button displayType={null} monospaced> <Icon symbol="times" /> </Button> <DropDownWithItems items={[ {label: 'Four'}, {label: 'Five'}, {label: 'Six'}, ]} trigger={ <Button displayType={null} monospaced> <Icon symbol="ellipsis-v" /> </Button> } /> </> } > <TreeView.ItemStack> <Icon symbol="folder" /> Folder 2 </TreeView.ItemStack> <TreeView.Group> <TreeView.Item>Item 4</TreeView.Item> <TreeView.Item>Item 5</TreeView.Item> <TreeView.Item>Item 6</TreeView.Item> </TreeView.Group> </TreeView.Item> </TreeView> </Provider> )) .add('dynamic', () => ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView dragAndDrop items={[ { children: [ {name: 'Blogs'}, {name: 'Documents and Media'}, ], name: 'Liferay Drive', }, { children: [ {name: 'Blogs'}, {name: 'Documents and Media'}, ], name: 'Repositories', }, { children: [ {name: 'PDF'}, {name: 'Word'}, {name: 'Google Drive'}, {name: 'Figma'}, ], name: 'Documents and Media', }, ]} nestedKey="children" onRenameItem={(item) => { return new Promise((resolve) => { setTimeout(() => { item.name += `-${Date.now()}`; resolve(item); }, 500); }); }} > {(item) => ( <TreeView.Item> <TreeView.ItemStack> <Icon symbol="folder" /> {item.name} </TreeView.ItemStack> <TreeView.Group items={item.children}> {(item) => ( <TreeView.Item>{item.name}</TreeView.Item> )} </TreeView.Group> </TreeView.Item> )} </TreeView> </Provider> )) .add('nested', () => { const TYPES_TO_SYMBOLS = { document: 'document-text', pdf: 'document-pdf', success: 'check-circle-full', warning: 'warning-full', } as Record<string, string>; const TYPES_TO_COLORS = { document: 'text-primary', pdf: 'text-danger', success: 'text-success', warning: 'text-warning', } as Record<string, string>; return ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView dragAndDrop items={ITEMS_DRIVE} nestedKey="children" onRenameItem={(item) => { return new Promise((resolve) => { setTimeout(() => { item.name += `-${Date.now()}`; resolve(item); }, 500); }); }} > {(item: IItem) => ( <TreeView.Item> <TreeView.ItemStack> <Icon symbol={item.type ?? 'folder'} /> {item.name} {item.status && ( <Icon className={TYPES_TO_COLORS[item.status]} symbol={TYPES_TO_SYMBOLS[item.status]} /> )} </TreeView.ItemStack> <TreeView.Group items={item.children}> {({name, status, type}: IItem) => ( <TreeView.Item> {type && ( <Icon className={ TYPES_TO_COLORS[type] } symbol={TYPES_TO_SYMBOLS[type]} /> )} {name} {status && ( <Icon className={ TYPES_TO_COLORS[status] } symbol={ TYPES_TO_SYMBOLS[status] } /> )} </TreeView.Item> )} </TreeView.Group> </TreeView.Item> )} </TreeView> </Provider> ); }) .add('sticker', () => ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView dragAndDrop showExpanderOnHover={false}> <TreeView.Item> <TreeView.ItemStack> <Sticker displayType="primary" shape="user-icon" size="sm" > JH </Sticker> Juan Hidalgo </TreeView.ItemStack> <TreeView.Group> <TreeView.Item key="Victor Valle"> <TreeView.ItemStack> <Sticker displayType="primary" shape="user-icon" size="sm" > VV </Sticker> Victor Valle </TreeView.ItemStack> <TreeView.Group> <TreeView.Item key="susana-vázquez"> <Sticker displayType="primary" shape="user-icon" size="sm" > SV </Sticker> Susana Vázquez </TreeView.Item> <TreeView.Item key="myriam-manso"> <Sticker displayType="primary" shape="user-icon" size="sm" > MM </Sticker> Myriam Manso </TreeView.Item> </TreeView.Group> </TreeView.Item> <TreeView.Item key="emily-young"> <Sticker displayType="primary" shape="user-icon" size="sm" > EY </Sticker> Emily Young </TreeView.Item> </TreeView.Group> </TreeView.Item> </TreeView> </Provider> )) .add('page elements', () => { const TYPES_TO_SYMBOLS = { container: 'container', editable: 'text', 'fragment-image': 'picture', 'fragment-text': 'h1', paragraph: 'paragraph', row: 'table', } as Record<string, string>; const items = [ { children: [ { children: [ { children: [ { children: [ { children: [ { id: 11, name: 'element-text', type: 'editable', }, ], id: 12, name: 'Heading', type: 'fragment-text', }, { children: [ { id: 10, name: 'element-text', type: 'editable', }, ], id: 13, name: 'Paragraph', type: 'paragraph', }, ], id: 5, name: 'Module', }, { children: [ { children: [ { id: 9, name: 'image-squere', type: 'editable', }, ], id: 6, name: 'Image', type: 'fragment-image', }, ], id: 4, name: 'Module', }, ], id: 3, name: 'Grid', type: 'row', }, ], id: 2, name: 'Container', type: 'container', }, ], id: 1, name: 'Container', type: 'container', }, ]; const [expandedKeys, setExpandedKeys] = useState<Set<React.Key>>( new Set(['1', '2', '3', '4', '5']) ); return ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView expandedKeys={expandedKeys} expanderIcons={{ close: <Icon symbol="hr" />, open: <Icon symbol="plus" />, }} items={items} nestedKey="children" onExpandedChange={(keys) => setExpandedKeys(keys)} showExpanderOnHover={false} > {(item) => ( <TreeView.Item> <TreeView.ItemStack> {item.type && ( <Icon symbol={TYPES_TO_SYMBOLS[item.type]} /> )} {item.name} </TreeView.ItemStack> <TreeView.Group items={item.children}> {({name, type}) => ( <TreeView.Item> <Icon symbol={TYPES_TO_SYMBOLS[type]} /> {name} </TreeView.Item> )} </TreeView.Group> </TreeView.Item> )} </TreeView> </Provider> ); }) .add('selection', () => { const [selectedKeys, setSelectionChange] = useState<Set<React.Key>>( new Set() ); // Just to avoid TypeScript error with required props const OptionalCheckbox = (props: any) => <Checkbox {...props} />; OptionalCheckbox.displayName = 'ClayCheckbox'; return ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView dragAndDrop items={ITEMS_DRIVE} nestedKey="children" onSelectionChange={(keys) => setSelectionChange(keys)} selectedKeys={selectedKeys} showExpanderOnHover={false} > {(item) => ( <TreeView.Item> <TreeView.ItemStack> <OptionalCheckbox /> <Icon symbol="folder" /> {item.name} </TreeView.ItemStack> <TreeView.Group items={item.children}> {(item) => ( <TreeView.Item> <OptionalCheckbox /> <Icon symbol="folder" /> {item.name} </TreeView.Item> )} </TreeView.Group> </TreeView.Item> )} </TreeView> </Provider> ); }) .add('selection w/async load', () => { const [selectedKeys, setSelectionChange] = useState<Set<React.Key>>( new Set() ); // Just to avoid TypeScript error with required props const OptionalCheckbox = (props: any) => <Checkbox {...props} />; OptionalCheckbox.displayName = 'ClayCheckbox'; return ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView items={ITEMS_DRIVE} nestedKey="children" onLoadMore={async (item) => { // Delay to simulate loading of new data await new Promise((resolve) => { setTimeout(() => resolve(''), 1000); }); return [ { id: Math.random(), name: `${item.name} ${Math.random()}`, }, { id: Math.random(), name: `${item.name} ${Math.random()}`, }, { id: Math.random(), name: `${item.name} ${Math.random()}`, }, ]; }} onSelectionChange={(keys) => setSelectionChange(keys)} selectedKeys={selectedKeys} showExpanderOnHover={false} > {(item) => ( <TreeView.Item> <TreeView.ItemStack> <OptionalCheckbox /> <Icon symbol="folder" /> {item.name} </TreeView.ItemStack> <TreeView.Group items={item.children}> {(item) => ( <TreeView.Item> <OptionalCheckbox /> <Icon symbol="folder" /> {item.name} </TreeView.Item> )} </TreeView.Group> </TreeView.Item> )} </TreeView> </Provider> ); }) .add('expand on check', () => { const [selectedKeys, setSelectionChange] = useState<Set<React.Key>>( new Set() ); // Just to avoid TypeScript error with required props const OptionalCheckbox = (props: any) => <Checkbox {...props} />; OptionalCheckbox.displayName = 'ClayCheckbox'; return ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView dragAndDrop expandOnCheck items={ITEMS_DRIVE} nestedKey="children" onSelectionChange={(keys) => setSelectionChange(keys)} selectedKeys={selectedKeys} showExpanderOnHover={false} > {(item) => ( <TreeView.Item> <TreeView.ItemStack> <OptionalCheckbox /> <Icon symbol="folder" /> {item.name} </TreeView.ItemStack> <TreeView.Group items={item.children}> {(item) => ( <TreeView.Item> <OptionalCheckbox /> <Icon symbol="folder" /> {item.name} </TreeView.Item> )} </TreeView.Group> </TreeView.Item> )} </TreeView> </Provider> ); }) .add('expand on check w/single selection', () => { const [selectedKeys, setSelectionChange] = useState<Set<React.Key>>( new Set() ); // Just to avoid TypeScript error with required props const OptionalCheckbox = (props: any) => <Checkbox {...props} />; OptionalCheckbox.displayName = 'ClayCheckbox'; return ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView dragAndDrop expandOnCheck items={ITEMS_DRIVE} nestedKey="children" onSelectionChange={(keys) => setSelectionChange(keys)} selectedKeys={selectedKeys} selectionMode="single" showExpanderOnHover={false} > {(item) => ( <TreeView.Item> <TreeView.ItemStack> <OptionalCheckbox /> <Icon symbol="folder" /> {item.name} </TreeView.ItemStack> <TreeView.Group items={item.children}> {(item) => ( <TreeView.Item> <OptionalCheckbox /> <Icon symbol="folder" /> {item.name} </TreeView.Item> )} </TreeView.Group> </TreeView.Item> )} </TreeView> </Provider> ); }) .add('single selection', () => { const [selectedKeys, setSelectionChange] = useState<Set<React.Key>>( new Set() ); // Just to avoid TypeScript error with required props const OptionalCheckbox = (props: any) => <Checkbox {...props} />; OptionalCheckbox.displayName = 'ClayCheckbox'; return ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView items={ITEMS_DRIVE} nestedKey="children" onSelectionChange={(keys) => setSelectionChange(keys)} selectedKeys={selectedKeys} selectionMode="single" showExpanderOnHover={false} > {(item) => ( <TreeView.Item> <TreeView.ItemStack> <OptionalCheckbox /> <Icon symbol="folder" /> {item.name} </TreeView.ItemStack> <TreeView.Group items={item.children}> {(item) => ( <TreeView.Item> <OptionalCheckbox /> <Icon symbol="folder" /> {item.name} </TreeView.Item> )} </TreeView.Group> </TreeView.Item> )} </TreeView> </Provider> ); }) .add('large data', () => { const rootNode = createNode(10, 5); return ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView items={[rootNode]} nestedKey="children" showExpanderOnHover={false} > {(item) => ( <TreeView.Item> <TreeView.ItemStack>{item.name}</TreeView.ItemStack> <TreeView.Group items={item.children}> {(item: typeof rootNode) => ( <TreeView.Item>{item.name}</TreeView.Item> )} </TreeView.Group> </TreeView.Item> )} </TreeView> </Provider> ); }) .add('async load', () => { return ( <Provider spritemap={spritemap} theme="cadmin"> <TreeView items={ITEMS_DRIVE} nestedKey="children" onLoadMore={async (item) => { // Delay to simulate loading of new data await new Promise((resolve) => { setTimeout(() => resolve(''), 1000); }); return [ { id: Math.random(), name: `${item.name} ${Math.random()}`, }, { id: Math.random(), name: `${item.name} ${Math.random()}`, }, { id: Math.random(), name: `${item.name} ${Math.random()}`, }, ]; }} > {(item) => ( <TreeView.Item> <TreeView.ItemStack> <Icon symbol="folder" /> {item.name} </TreeView.ItemStack> <TreeView.Group items={item.children}> {(item) => ( <TreeView.Item> <Icon symbol="folder" /> {item.name} </TreeView.Item> )} </TreeView.Group> </TreeView.Item> )} </TreeView> </Provider> ); }) .add('performance', () => { const [selectedKeys, setSelectionChange] = useState<Set<React.Key>>( new Set() ); type Item = { label: string; itemSubtypes: Array<{label: string}>; }; type Data = Array<Item>; const [items, setItems] = useState(largeData as Data); const [value, setValue] = useState(''); // Just to avoid TypeScript error with required props const OptionalCheckbox = (props: any) => <Checkbox {...props} />; OptionalCheckbox.displayName = 'ClayCheckbox'; const itemsFiltered = useMemo<Data>(() => { if (!value) { return items; } const filter = createFilter(items, 'itemSubtypes', 'label'); return filter.applyFilter(value); }, [items, value]); return ( <Provider spritemap={spritemap} theme="cadmin"> <Input onChange={(event) => setValue(event.target.value)} placeholder="Search..." value={value} /> <TreeView<Item> items={itemsFiltered} nestedKey="itemSubtypes" onItemsChange={(data) => setItems(data as Data)} onLoadMore={async () => { const items = (largeData as Data).map((node) => ({ label: node.label + Math.random().toFixed(3), })); return Promise.resolve([...items]); }} onSelectionChange={(keys) => setSelectionChange(keys)} selectedKeys={selectedKeys} showExpanderOnHover={false} > {(item) => ( <TreeView.Item> <TreeView.ItemStack> <OptionalCheckbox /> {item.label} </TreeView.ItemStack> <TreeView.Group items={item.itemSubtypes}> {(item) => ( <TreeView.Item> <OptionalCheckbox /> {item.label} </TreeView.Item> )} </TreeView.Group> </TreeView.Item> )} </TreeView> </Provider> ); });
the_stack
import {Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChange, SimpleChanges} from '@angular/core'; import {TranslationUnit} from '../model/translation-unit'; import {MatDialog, MatSnackBar} from '@angular/material'; import {NormalizedMessage} from '../model/normalized-message'; import {FormBuilder, FormGroup} from '@angular/forms'; import {Observable} from 'rxjs/Observable'; import {TranslateUnitWarningConfirmDialogComponent} from '../translate-unit-warning-confirm-dialog/translate-unit-warning-confirm-dialog.component'; import {TranslationFileView} from '../model/translation-file-view'; import {WorkflowType} from '../model/translation-project'; import {STATE_FINAL, STATE_TRANSLATED} from 'ngx-i18nsupport-lib/dist'; import {AutoTranslateServiceAPI} from '../model/auto-translate-service-api'; import {isNullOrUndefined} from 'util'; export enum NavigationDirection { NEXT, PREV, STAY } export interface TranslateUnitChange { changedUnit?: TranslationUnit; navigationDirection: NavigationDirection; } /** * Component to input a new translation. * It shows the source and allows to input the target text. */ @Component({ selector: 'app-translate-unit', templateUrl: './translate-unit.component.html', styleUrls: ['./translate-unit.component.css'] }) export class TranslateUnitComponent implements OnInit, OnChanges { @Input() translationFileView: TranslationFileView; @Input() translationUnit: TranslationUnit; @Input() workflowType: WorkflowType; @Input() showNormalized = true; @Input() reviewMode = false; /** * Emitted, when translation is changed and/or the user wants to navigate to next/prev unit. * If changedUnit is null, there is no change, but only navigation. * @type {EventEmitter<TranslateUnitChange>} */ @Output() changed: EventEmitter<TranslateUnitChange> = new EventEmitter(); form: FormGroup; private _editedTargetMessage: NormalizedMessage; private _editableTargetMessage: NormalizedMessage; private isMarkedAsTranslated = false; private isMarkedAsReviewed = false; constructor(private formBuilder: FormBuilder, private dialog: MatDialog, private _snackbar: MatSnackBar, private autoTranslateService: AutoTranslateServiceAPI) { } ngOnInit() { this.initForm(); this.form.valueChanges.subscribe(formValue => {this.valueChanged(formValue); }); } private valueChanged(v: any) { this._editedTargetMessage = v._editedTargetMessage; this.showNormalized = v.showNormalized; } ngOnChanges(changes: SimpleChanges) { this.initForm(); const changedTranslationUnit: SimpleChange = changes['translationUnit']; if (changedTranslationUnit) { if (changedTranslationUnit.currentValue) { this._editedTargetMessage = changedTranslationUnit.currentValue.targetContentNormalized(); } else { this._editedTargetMessage = null; } this._editableTargetMessage = null; } } private initForm() { if (!this.form) { this.form = this.formBuilder.group({ _editedTargetMessage: [this.editedTargetContentNormalized()], showNormalized: [this.showNormalized], }); } } public transUnitID(): string { if (this.translationUnit) { return this.translationUnit.id(); } else { return ''; } } public targetState(): string { if (this.translationUnit) { return this.translationUnit.targetState(); } else { return ''; } } public targetLanguage(): string { if (this.translationUnit) { return this.translationUnit.translationFile().targetLanguage(); } else { return ''; } } public sourceContent(): string { if (this.translationUnit) { return this.translationUnit.sourceContent(); } else { return ''; } } public sourceContentNormalized(): NormalizedMessage { if (this.translationUnit) { return this.translationUnit.sourceContentNormalized(); } else { return null; } } public editedTargetContentNormalized(): NormalizedMessage { if (isNullOrUndefined(this._editableTargetMessage)) { if (this.translationUnit) { this._editableTargetMessage = this.translationUnit.targetContentNormalized(); } } return this._editableTargetMessage; } public sourceLanguage(): string { if (this.translationUnit) { return this.translationUnit.translationFile().sourceLanguage(); } else { return ''; } } public sourceDescription(): string { if (this.translationUnit) { return this.translationUnit.description(); } else { return ''; } } public sourceMeaning(): string { if (this.translationUnit) { return this.translationUnit.meaning(); } else { return ''; } } public sourceRef(): string { if (this.translationUnit) { const refs = this.translationUnit.sourceReferences(); if (refs.length > 0) { return refs[0].sourcefile + ':' + refs[0].linenumber; } } else { return null; } } /** * Open a snackbar to show source ref */ public showSourceRefInfo() { const sourceRefMessage = 'Original message position: ' + this.sourceRef(); // TODO i18n it this._snackbar.open(sourceRefMessage, 'OK', {duration: 5000}); // TODO i18n it } /** * Open a snackbar to show units ID */ public showTransUnitID() { const message = 'ID: ' + this.transUnitID(); this._snackbar.open(message, 'OK', {duration: 5000}); } errors(): any[] { if (!this._editedTargetMessage) { return []; } const errors = this._editedTargetMessage.validate(this.showNormalized); if (errors) { return Object.keys(errors).map(key => errors[key]); } else { return []; } } warnings(): any[] { if (!this._editedTargetMessage) { return []; } const errors = this._editedTargetMessage.validateWarnings(this.showNormalized); if (errors) { return Object.keys(errors).map(key => errors[key]); } else { return []; } } commitChanges(navigationDirection: NavigationDirection) { if (this.translationUnit) { if (this.isTranslationChanged() || this.isMarkedAsTranslated || this.isMarkedAsReviewed) { this.translationUnit.translate(this._editedTargetMessage); switch (this.workflowType) { case WorkflowType.SINGLE_USER: this.translationUnit.setTargetState(STATE_FINAL); break; case WorkflowType.WITH_REVIEW: if (this.isMarkedAsReviewed) { this.translationUnit.setTargetState(STATE_FINAL); } else { this.translationUnit.setTargetState(STATE_TRANSLATED); } break; } this.changed.emit({changedUnit: this.translationUnit, navigationDirection: navigationDirection}); this.isMarkedAsTranslated = false; this.isMarkedAsReviewed = false; } else { this.changed.emit({navigationDirection: navigationDirection}); } } } public isTranslationChanged(): boolean { const original = this.translationUnit.targetContent(); if (isNullOrUndefined(this._editedTargetMessage)) { return false; } return original !== this._editedTargetMessage.nativeString(); } markTranslated() { this.openConfirmWarningsDialog().subscribe(result => { switch (result) { case 'cancel': break; case 'discard': break; case 'accept': this.isMarkedAsTranslated = true; this.commitChanges(NavigationDirection.STAY); break; } }); } undo() { this._editableTargetMessage = this.translationUnit.targetContentNormalized().copy(); this._editedTargetMessage = this._editableTargetMessage; this.changed.emit({changedUnit: this.translationUnit, navigationDirection: NavigationDirection.STAY}); } markReviewed() { this.isMarkedAsReviewed = true; this.commitChanges(NavigationDirection.STAY); } /** * If there are errors or warnings, open a dialog to conform what to do. * There are 3 possible results: * 'cancel': do not do anything, stay on this trans unit. * 'discard': do not translate, leave transunit unchanged, but go to the next/prev unit. * 'accept': translate tu as given, ignoring warnings (errors cannot be ignored). * @return {any} */ openConfirmWarningsDialog(): Observable<any> { const warnings = this.warnings(); const errors = this.errors(); if (warnings.length === 0 && errors.length === 0) { // everything good, we don´t need a dialog then. return Observable.of('accept'); } else if (!this.isTranslationChanged()) { return Observable.of('accept'); } else { const dialogRef = this.dialog.open(TranslateUnitWarningConfirmDialogComponent, { data: {errors: errors, warnings: warnings}, disableClose: true } ); return dialogRef.afterClosed(); } } /** * Go to the next trans unit. */ public next() { if (this.translationUnit) { this.openConfirmWarningsDialog().subscribe(result => { switch (result) { case 'cancel': break; case 'discard': if (this.translationFileView.hasNext()) { this.changed.emit({navigationDirection: NavigationDirection.NEXT}); } break; case 'accept': const direction = (this.translationFileView.hasNext()) ? NavigationDirection.NEXT : NavigationDirection.STAY; this.commitChanges(direction); break; } }); } } /** * Check, wether there is a next trans unit. * @return {boolean} */ public hasNext(): boolean { if (this.translationUnit) { return this.translationFileView.hasNext(); } else { return false; } } public prev() { if (this.translationUnit) { this.openConfirmWarningsDialog().subscribe(result => { switch (result) { case 'cancel': break; case 'discard': if (this.translationFileView.hasPrev()) { this.changed.emit({navigationDirection: NavigationDirection.PREV}); } break; case 'accept': const direction = (this.translationFileView.hasPrev()) ? NavigationDirection.PREV : NavigationDirection.STAY; this.commitChanges(direction); break; } }); } } public hasPrev(): boolean { if (this.translationUnit) { return this.translationFileView.hasPrev(); } else { return false; } } /** * Auto translate this unit using Google Translate. */ autoTranslate() { this.sourceContentNormalized().autoTranslateUsingService( this.autoTranslateService, this.sourceLanguage(), this.targetLanguage() ).subscribe((translatedMessage: NormalizedMessage) => { this._editableTargetMessage = translatedMessage; this._editedTargetMessage = translatedMessage; this.changed.emit({changedUnit: this.translationUnit, navigationDirection: NavigationDirection.STAY}); }); } autoTranslateDisabled(): Observable<boolean> { if (!this.translationUnit) { return Observable.of(true); } return this.autoTranslateService.canAutoTranslate( this.translationUnit.translationFile().sourceLanguage(), this.translationUnit.translationFile().targetLanguage()).map(val => !val); } }
the_stack
import { isFunction, isVariable, Symbol, SYMBOL_FLAG_CONVERT_INSTANCE_TO_GLOBAL, SYMBOL_FLAG_IS_BINARY_OPERATOR, SYMBOL_FLAG_IS_GENERIC, SYMBOL_FLAG_IS_REFERENCE, SYMBOL_FLAG_IS_TEMPLATE, SYMBOL_FLAG_IS_UNARY_OPERATOR, SYMBOL_FLAG_IS_UNSIGNED, SYMBOL_FLAG_NATIVE_DOUBLE, SYMBOL_FLAG_NATIVE_FLOAT, SYMBOL_FLAG_NATIVE_INTEGER, SYMBOL_FLAG_NATIVE_LONG, SYMBOL_FLAG_USED, SymbolKind, SymbolState } from "../core/symbol"; import {ConversionKind, Type} from "../core/type"; import { createboolean, createCall, createDouble, createFloat, createInt, createLong, createMemberReference, createName, createNull, createReturn, createSymbolReference, createType, createVariable, createVariables, isBinary, isExpression, isUnary, Node, NODE_FLAG_DECLARE, NODE_FLAG_EXPORT, NODE_FLAG_GENERIC, NODE_FLAG_GET, NODE_FLAG_LIBRARY, NODE_FLAG_PRIVATE, NODE_FLAG_PROTECTED, NODE_FLAG_PUBLIC, NODE_FLAG_SET, NODE_FLAG_UNSIGNED_OPERATOR, NodeKind, rangeForFlag } from "../core/node"; import {CompileTarget} from "../compile-target"; import {Log, SourceRange, spanRanges} from "../../utils/log"; import {FindNested, Scope, ScopeHint} from "../core/scope"; import {alignToNextMultipleOf, isPositivePowerOf2} from "../../utils/utils"; import {MAX_INT32_VALUE, MAX_UINT32_VALUE, MIN_INT32_VALUE} from "../const"; import {assert} from "../../utils/assert"; import {Compiler} from "../compiler"; import {Terminal} from "../../utils/terminal"; /** * Author : Nidin Vinayakan */ export class CheckContext { log: Log; target: CompileTarget; pointerByteSize: int32; isUnsafeAllowed: boolean; enclosingModule: Symbol; enclosingClass: Symbol; currentReturnType: Type; nextGlobalVariableOffset: int32; //Foreign type anyType: Type; // Native types booleanType: Type; int8Type: Type; errorType: Type; int32Type: Type; int64Type: Type; float32Type: Type; float64Type: Type; nullType: Type; undefinedType: Type; int16Type: Type; stringType: Type; uint8Type: Type; uint32Type: Type; uint64Type: Type; uint16Type: Type; voidType: Type; allocateGlobalVariableOffset(sizeOf: int32, alignmentOf: int32): int32 { let offset = alignToNextMultipleOf(this.nextGlobalVariableOffset, alignmentOf); this.nextGlobalVariableOffset = offset + sizeOf; return offset; } } export function addScopeToSymbol(symbol: Symbol, parentScope: Scope): void { let scope = new Scope(); scope.parent = parentScope; scope.symbol = symbol; symbol.scope = scope; } export function linkSymbolToNode(symbol: Symbol, node: Node): void { node.symbol = symbol; node.scope = symbol.scope; symbol.range = node.internalRange != null ? node.internalRange : node.range; symbol.node = node; } export enum CheckMode { NORMAL, INITIALIZE, } export function initialize(context: CheckContext, node: Node, parentScope: Scope, mode: CheckMode): void { let kind = node.kind; if (node.parent != null) { let parentKind = node.parent.kind; // Validate node placement if (kind != NodeKind.IMPORTS && kind != NodeKind.VARIABLE && kind != NodeKind.VARIABLES && (kind != NodeKind.FUNCTION || parentKind != NodeKind.CLASS) && (parentKind == NodeKind.FILE || parentKind == NodeKind.GLOBAL) != ( parentKind == NodeKind.MODULE || kind == NodeKind.MODULE || kind == NodeKind.CLASS || kind == NodeKind.ENUM || kind == NodeKind.FUNCTION || kind == NodeKind.CONSTANTS ) ) { context.log.error(node.range, "This statement is not allowed here"); } } // Module if (kind == NodeKind.MODULE) { assert(node.symbol == null); let symbol = new Symbol(); symbol.kind = SymbolKind.TYPE_MODULE; symbol.name = node.stringValue; symbol.resolvedType = new Type(); symbol.resolvedType.symbol = symbol; symbol.flags = SYMBOL_FLAG_IS_REFERENCE; addScopeToSymbol(symbol, parentScope); linkSymbolToNode(symbol, node); parentScope.define(context.log, symbol, ScopeHint.NORMAL); parentScope = symbol.scope; } // Class if (kind == NodeKind.CLASS || kind == NodeKind.ENUM) { assert(node.symbol == null); let symbol = new Symbol(); symbol.kind = kind == NodeKind.CLASS ? SymbolKind.TYPE_CLASS : SymbolKind.TYPE_ENUM; symbol.name = node.stringValue; symbol.resolvedType = new Type(); symbol.resolvedType.symbol = symbol; symbol.flags = SYMBOL_FLAG_IS_REFERENCE; addScopeToSymbol(symbol, parentScope); linkSymbolToNode(symbol, node); parentScope.define(context.log, symbol, ScopeHint.NORMAL); parentScope = symbol.scope; if (node.parameterCount() > 0) { //Class has generic parameters. convert it to class template symbol.kind = SymbolKind.TYPE_TEMPLATE; symbol.flags |= SYMBOL_FLAG_IS_TEMPLATE; //TODO: Lift generic parameter limit from 1 to many let genericType = node.firstGenericType(); let genericSymbol = new Symbol(); genericSymbol.kind = SymbolKind.TYPE_GENERIC; genericSymbol.name = genericType.stringValue; genericSymbol.resolvedType = new Type(); genericSymbol.resolvedType.symbol = genericSymbol; genericSymbol.flags = SYMBOL_FLAG_IS_GENERIC; genericType.flags = NODE_FLAG_GENERIC; addScopeToSymbol(genericSymbol, parentScope); linkSymbolToNode(genericSymbol, genericType); parentScope.define(context.log, genericSymbol, ScopeHint.NORMAL); } } // Function else if (kind == NodeKind.FUNCTION) { assert(node.symbol == null); let symbol = new Symbol(); symbol.kind = node.parent.kind == NodeKind.CLASS ? SymbolKind.FUNCTION_INSTANCE : SymbolKind.FUNCTION_GLOBAL; symbol.name = node.stringValue; if (node.isOperator()) { if (symbol.name == "+" || symbol.name == "-") { if (node.functionFirstArgument() == node.functionReturnType()) { symbol.flags = SYMBOL_FLAG_IS_UNARY_OPERATOR; symbol.rename = symbol.name == "+" ? "op_positive" : "op_negative"; } else { symbol.flags = SYMBOL_FLAG_IS_BINARY_OPERATOR; symbol.rename = symbol.name == "+" ? "op_add" : "op_subtract"; } } else { symbol.rename = symbol.name == "%" ? "op_remainder" : symbol.name == "&" ? "op_and" : symbol.name == "*" ? "op_multiply" : symbol.name == "**" ? "op_exponent" : symbol.name == "++" ? "op_increment" : symbol.name == "--" ? "op_decrement" : symbol.name == "/" ? "op_divide" : symbol.name == "<" ? "op_lessThan" : symbol.name == "<<" ? "op_shiftLeft" : symbol.name == "==" ? "op_equals" : symbol.name == ">" ? "op_greaterThan" : symbol.name == ">>" ? "op_shiftRight" : symbol.name == "[]" ? "op_get" : symbol.name == "[]=" ? "op_set" : symbol.name == "^" ? "op_xor" : symbol.name == "|" ? "op_or" : symbol.name == "~" ? "op_complement" : null; } } if (symbol.name == "constructor") { symbol.rename = "_ctr"; } addScopeToSymbol(symbol, parentScope); linkSymbolToNode(symbol, node); parentScope.define(context.log, symbol, symbol.isSetter() ? ScopeHint.NOT_GETTER : symbol.isGetter() ? ScopeHint.NOT_SETTER : symbol.isBinaryOperator() ? ScopeHint.NOT_UNARY : symbol.isUnaryOperator() ? ScopeHint.NOT_BINARY : ScopeHint.NORMAL); parentScope = symbol.scope; // All instance functions have a special "this" type if (symbol.kind == SymbolKind.FUNCTION_INSTANCE) { let parent = symbol.parent(); initializeSymbol(context, parent); if (symbol.name == "constructor") { let body = node.functionBody(); if (body !== null) { let variablesNode = body.firstChild; if (variablesNode === undefined) { let _variablesNode = createVariables(); body.appendChild(_variablesNode); variablesNode = _variablesNode; } else if (variablesNode.kind !== NodeKind.VARIABLES) { let _variablesNode = createVariables(); body.insertChildBefore(variablesNode, _variablesNode); variablesNode = _variablesNode; } let firstVariable = variablesNode.firstChild; if (firstVariable !== undefined) { if (firstVariable.stringValue !== "this") { variablesNode.insertChildBefore(firstVariable, createVariable("this", createType(parent.resolvedType), null)); } else if (firstVariable.stringValue === "this" && firstVariable.firstChild.resolvedType === undefined) { firstVariable.firstChild.resolvedType = parent.resolvedType; } } else { variablesNode.appendChild(createVariable("this", createType(parent.resolvedType), null)); } // All constructors have special return "this" type let returnNode: Node = createReturn(createName("this")); if (node.lastChild.lastChild && node.lastChild.lastChild.kind == NodeKind.RETURN) { node.lastChild.lastChild.remove(); } node.lastChild.appendChild(returnNode); } } else { let firstArgument = node.functionFirstArgument(); if (firstArgument.stringValue !== "this") { node.insertChildBefore(firstArgument, createVariable("this", createType(parent.resolvedType), null)); } else if (firstArgument.stringValue === "this" && firstArgument.firstChild.resolvedType === undefined) { firstArgument.firstChild.resolvedType = parent.resolvedType; } } } } // Variable else if (kind == NodeKind.VARIABLE) { assert(node.symbol == null); let symbol = new Symbol(); symbol.kind = node.parent.kind == NodeKind.CLASS ? SymbolKind.VARIABLE_INSTANCE : node.parent.kind == NodeKind.FUNCTION ? SymbolKind.VARIABLE_ARGUMENT : node.parent.kind == NodeKind.CONSTANTS || node.parent.kind == NodeKind.ENUM ? SymbolKind.VARIABLE_CONSTANT : node.parent.kind == NodeKind.VARIABLES && node.parent.parent.kind == NodeKind.FILE ? SymbolKind.VARIABLE_GLOBAL : SymbolKind.VARIABLE_LOCAL; symbol.name = node.stringValue; symbol.scope = parentScope; linkSymbolToNode(symbol, node); parentScope.define(context.log, symbol, ScopeHint.NORMAL); } // Block else if (kind == NodeKind.BLOCK) { if (node.parent.kind != NodeKind.FUNCTION) { let scope = new Scope(); scope.parent = parentScope; parentScope = scope; } node.scope = parentScope; } // Children let child = node.firstChild; while (child != null) { if (mode == CheckMode.INITIALIZE) { child.flags |= NODE_FLAG_LIBRARY; } initialize(context, child, parentScope, mode); child = child.nextSibling; } if (kind == NodeKind.FILE && mode == CheckMode.INITIALIZE) { context.booleanType = parentScope.findLocal("boolean", ScopeHint.NORMAL).resolvedType; context.uint8Type = parentScope.findLocal("uint8", ScopeHint.NORMAL).resolvedType; context.int32Type = parentScope.findLocal("int32", ScopeHint.NORMAL).resolvedType; context.int64Type = parentScope.findLocal("int64", ScopeHint.NORMAL).resolvedType; context.int8Type = parentScope.findLocal("int8", ScopeHint.NORMAL).resolvedType; context.int16Type = parentScope.findLocal("int16", ScopeHint.NORMAL).resolvedType; context.stringType = parentScope.findLocal("string", ScopeHint.NORMAL).resolvedType; context.uint32Type = parentScope.findLocal("uint32", ScopeHint.NORMAL).resolvedType; context.uint64Type = parentScope.findLocal("uint64", ScopeHint.NORMAL).resolvedType; context.uint16Type = parentScope.findLocal("uint16", ScopeHint.NORMAL).resolvedType; context.float32Type = parentScope.findLocal("float32", ScopeHint.NORMAL).resolvedType; context.float64Type = parentScope.findLocal("float64", ScopeHint.NORMAL).resolvedType; prepareNativeType(context.booleanType, 1, 0); prepareNativeType(context.uint8Type, 1, SYMBOL_FLAG_NATIVE_INTEGER | SYMBOL_FLAG_IS_UNSIGNED); prepareNativeType(context.int8Type, 1, SYMBOL_FLAG_NATIVE_INTEGER); prepareNativeType(context.int16Type, 2, SYMBOL_FLAG_NATIVE_INTEGER); prepareNativeType(context.uint16Type, 2, SYMBOL_FLAG_NATIVE_INTEGER | SYMBOL_FLAG_IS_UNSIGNED); prepareNativeType(context.int32Type, 4, SYMBOL_FLAG_NATIVE_INTEGER); prepareNativeType(context.int64Type, 8, SYMBOL_FLAG_NATIVE_LONG); prepareNativeType(context.uint32Type, 4, SYMBOL_FLAG_NATIVE_INTEGER | SYMBOL_FLAG_IS_UNSIGNED); prepareNativeType(context.uint64Type, 8, SYMBOL_FLAG_NATIVE_LONG | SYMBOL_FLAG_IS_UNSIGNED); prepareNativeType(context.stringType, 4, SYMBOL_FLAG_IS_REFERENCE); prepareNativeType(context.float32Type, 4, SYMBOL_FLAG_NATIVE_FLOAT); prepareNativeType(context.float64Type, 8, SYMBOL_FLAG_NATIVE_DOUBLE); } } function prepareNativeType(type: Type, byteSizeAndMaxAlignment: int32, flags: int32): void { let symbol = type.symbol; symbol.kind = SymbolKind.TYPE_NATIVE; symbol.byteSize = byteSizeAndMaxAlignment; symbol.maxAlignment = byteSizeAndMaxAlignment; symbol.flags = flags; } export function forbidFlag(context: CheckContext, node: Node, flag: int32, text: string): void { if ((node.flags & flag) != 0) { let range = rangeForFlag(node.firstFlag, flag); if (range != null) { node.flags = node.flags & ~flag; context.log.error(range, text); } } } export function requireFlag(context: CheckContext, node: Node, flag: int32, text: string): void { if ((node.flags & flag) == 0) { node.flags = node.flags | flag; context.log.error(node.range, text); } } export function initializeSymbol(context: CheckContext, symbol: Symbol): void { if (symbol.state == SymbolState.INITIALIZED) { assert(symbol.resolvedType != null); return; } assert(symbol.state == SymbolState.UNINITIALIZED); symbol.state = SymbolState.INITIALIZING; // Most flags aren't supported yet let node = symbol.node; // forbidFlag(context, node, NODE_FLAG_EXPORT, "Unsupported flag 'export'"); forbidFlag(context, node, NODE_FLAG_PROTECTED, "Unsupported flag 'protected'"); //forbidFlag(context, node, NODE_FLAG_STATIC, "Unsupported flag 'static'"); // Module if (symbol.kind == SymbolKind.TYPE_MODULE) { forbidFlag(context, node, NODE_FLAG_GET, "Cannot use 'get' on a namespace"); forbidFlag(context, node, NODE_FLAG_SET, "Cannot use 'set' on a namespace"); forbidFlag(context, node, NODE_FLAG_PUBLIC, "Cannot use 'public' on a namespace"); forbidFlag(context, node, NODE_FLAG_PRIVATE, "Cannot use 'private' on a namespace"); } // Class else if (symbol.kind == SymbolKind.TYPE_CLASS || symbol.kind == SymbolKind.TYPE_NATIVE || symbol.kind == SymbolKind.TYPE_GENERIC || symbol.kind == SymbolKind.TYPE_TEMPLATE) { forbidFlag(context, node, NODE_FLAG_GET, "Cannot use 'get' on a class"); forbidFlag(context, node, NODE_FLAG_SET, "Cannot use 'set' on a class"); forbidFlag(context, node, NODE_FLAG_PUBLIC, "Cannot use 'public' on a class"); forbidFlag(context, node, NODE_FLAG_PRIVATE, "Cannot use 'private' on a class"); } // Interface else if (symbol.kind == SymbolKind.TYPE_INTERFACE) { forbidFlag(context, node, NODE_FLAG_GET, "Cannot use 'get' on a interface"); forbidFlag(context, node, NODE_FLAG_SET, "Cannot use 'set' on a interface"); forbidFlag(context, node, NODE_FLAG_PUBLIC, "Cannot use 'public' on a interface"); forbidFlag(context, node, NODE_FLAG_PRIVATE, "Cannot use 'private' on a interface"); } // Enum else if (symbol.kind == SymbolKind.TYPE_ENUM) { forbidFlag(context, node, NODE_FLAG_GET, "Cannot use 'get' on an enum"); forbidFlag(context, node, NODE_FLAG_SET, "Cannot use 'set' on an enum"); forbidFlag(context, node, NODE_FLAG_PUBLIC, "Cannot use 'public' on an enum"); forbidFlag(context, node, NODE_FLAG_PRIVATE, "Cannot use 'private' on an enum"); symbol.resolvedType = new Type(); symbol.resolvedType.symbol = symbol; let underlyingSymbol = symbol.resolvedType.underlyingType(context).symbol; symbol.byteSize = underlyingSymbol.byteSize; symbol.maxAlignment = underlyingSymbol.maxAlignment; } // Function else if (isFunction(symbol.kind)) { let body = node.functionBody(); let returnType = node.functionReturnType(); let oldUnsafeAllowed = context.isUnsafeAllowed; context.isUnsafeAllowed = node.isUnsafe(); resolveAsType(context, returnType, symbol.scope.parent); if (returnType.resolvedType.isClass() && returnType.hasParameters() && node.parent != returnType.resolvedType.symbol.node) { deriveConcreteClass(context, returnType, [returnType.firstChild.firstChild], returnType.resolvedType.symbol.scope); } let argumentCount = 0; let child = node.functionFirstArgument(); while (child != returnType) { assert(child.kind == NodeKind.VARIABLE); assert(child.symbol.kind == SymbolKind.VARIABLE_ARGUMENT); initializeSymbol(context, child.symbol); child.symbol.offset = argumentCount; argumentCount = argumentCount + 1; child = child.nextSibling; } if (symbol.kind != SymbolKind.FUNCTION_INSTANCE) { forbidFlag(context, node, NODE_FLAG_GET, "Cannot use 'get' here"); forbidFlag(context, node, NODE_FLAG_SET, "Cannot use 'set' here"); forbidFlag(context, node, NODE_FLAG_PUBLIC, "Cannot use 'public' here"); forbidFlag(context, node, NODE_FLAG_PRIVATE, "Cannot use 'private' here"); } else if (node.isGet()) { forbidFlag(context, node, NODE_FLAG_SET, "Cannot use both 'get' and 'set'"); // Validate argument count including "this" if (argumentCount != 1) { context.log.error(symbol.range, "Getters must not have any argumentVariables"); } } else if (node.isSet()) { symbol.rename = `set_${symbol.name}`; // Validate argument count including "this" if (argumentCount != 2) { context.log.error(symbol.range, "Setters must have exactly one argument"); } } // Validate operator argument counts including "this" else if (node.isOperator()) { if (symbol.name == "~" || symbol.name == "++" || symbol.name == "--") { if (argumentCount != 1) { context.log.error(symbol.range, `Operator '${symbol.name}' must not have any arguments`); } } else if (symbol.name == "+" || symbol.name == "-") { if (argumentCount > 2) { context.log.error(symbol.range, `Operator '${symbol.name}' must have at most one argument`); } } else if (symbol.name == "[]=") { if (argumentCount < 2) { context.log.error(symbol.range, "Operator '[]=' must have at least one argument"); } } else if (argumentCount != 2) { context.log.error(symbol.range, `Operator '${symbol.name}' must have exactly one argument`); } } symbol.resolvedType = new Type(); symbol.resolvedType.symbol = symbol; if (symbol.kind == SymbolKind.FUNCTION_INSTANCE) { let parent = symbol.parent(); let shouldConvertInstanceToGlobal = false; forbidFlag(context, node, NODE_FLAG_EXPORT, "Cannot use 'export' on an instance function"); forbidFlag(context, node, NODE_FLAG_DECLARE, "Cannot use 'declare' on an instance function"); // Functions inside declared classes are automatically declared if (parent.node.isDeclare()) { if (body == null) { node.flags = node.flags | NODE_FLAG_DECLARE; } else { shouldConvertInstanceToGlobal = true; } } // Require implementations for functions not on declared classes else { if (body == null) { context.log.error(node.lastChild.range, "Must implement this function"); } // Functions inside export classes are automatically export if (parent.node.isExport()) { node.flags = node.flags | NODE_FLAG_EXPORT; } } // Rewrite this symbol as a global function instead of an instance function if (shouldConvertInstanceToGlobal) { symbol.kind = SymbolKind.FUNCTION_GLOBAL; symbol.flags = symbol.flags | SYMBOL_FLAG_CONVERT_INSTANCE_TO_GLOBAL; symbol.rename = `${parent.name}_${symbol.rename != null ? symbol.rename : symbol.name}`; let argument = node.functionFirstArgument(); assert(argument.symbol.name == "this"); argument.symbol.rename = "__this"; } } // Imported functions require a modifier for consistency with TypeScript else if (body == null) { forbidFlag(context, node, NODE_FLAG_EXPORT, "Cannot use 'export' on an unimplemented function"); if (!node.parent || !node.parent.isDeclare()) { requireFlag(context, node, NODE_FLAG_DECLARE, "Declared functions must be prefixed with 'declare'"); } } else { forbidFlag(context, node, NODE_FLAG_DECLARE, "Cannot use 'declare' on a function with an implementation"); } context.isUnsafeAllowed = oldUnsafeAllowed; } // Variable else if (isVariable(symbol.kind)) { forbidFlag(context, node, NODE_FLAG_GET, "Cannot use 'get' on a variable"); forbidFlag(context, node, NODE_FLAG_SET, "Cannot use 'set' on a variable"); let type = node.variableType(); let value = node.variableValue(); let oldUnsafeAllowed = context.isUnsafeAllowed; context.isUnsafeAllowed = context.isUnsafeAllowed || node.isUnsafe(); if (symbol.kind != SymbolKind.VARIABLE_INSTANCE) { forbidFlag(context, node, NODE_FLAG_PUBLIC, "Cannot use 'public' here"); forbidFlag(context, node, NODE_FLAG_PRIVATE, "Cannot use 'private' here"); } if (type != null) { resolveAsType(context, type, symbol.scope); if (type.resolvedType.isTemplate() && type.hasParameters() && node.parent != type.resolvedType.symbol.node) { deriveConcreteClass(context, type, [type.firstChild.firstChild], type.resolvedType.symbol.scope); } symbol.resolvedType = type.resolvedType; } else if (value != null) { resolveAsExpression(context, value, symbol.scope); if (value.resolvedType.isTemplate() && value.hasParameters() && node.parent != value.resolvedType.symbol.node) { deriveConcreteClass(context, value, [value.firstChild.firstChild], value.resolvedType.symbol.scope); } symbol.resolvedType = value.resolvedType; } else { context.log.error(node.internalRange, "Cannot create untyped variables"); symbol.resolvedType = context.errorType; } // Validate the variable type if (symbol.resolvedType == context.voidType || symbol.resolvedType == context.nullType) { context.log.error(node.internalRange, `Cannot create a variable with type '${symbol.resolvedType.toString()}'`); symbol.resolvedType = context.errorType; } // Resolve constant values at initialization time if (symbol.kind == SymbolKind.VARIABLE_CONSTANT) { if (value != null) { resolveAsExpression(context, value, symbol.scope); checkConversion(context, value, symbol.resolvedTypeUnderlyingIfEnumValue(context), ConversionKind.IMPLICIT); if (value.kind == NodeKind.INT32 || value.kind == NodeKind.INT64 || value.kind == NodeKind.BOOLEAN) { symbol.offset = value.intValue; } else if (value.kind == NodeKind.FLOAT32 || value.kind == NodeKind.FLOAT64) { symbol.offset = value.floatValue; } else if (value.resolvedType != context.errorType) { context.log.error(value.range, "Invalid constant initializer"); symbol.resolvedType = context.errorType; } } // Automatically initialize enum values using the previous enum else if (symbol.isEnumValue()) { if (node.previousSibling != null) { let previousSymbol = node.previousSibling.symbol; initializeSymbol(context, previousSymbol); symbol.offset = previousSymbol.offset + 1; } else { symbol.offset = 0; } } else { context.log.error(node.internalRange, "Constants must be initialized"); } } // Disallow shadowing at function scope if (symbol.scope.symbol == null) { let scope = symbol.scope.parent; while (scope != null) { let shadowed = scope.findLocal(symbol.name, ScopeHint.NORMAL); if (shadowed != null) { context.log.error( node.internalRange, `The symbol '${symbol.name}' shadows another symbol with the same name in a parent scope` ); break; } // Stop when we pass through a function scope if (scope.symbol != null) { break; } scope = scope.parent; } } context.isUnsafeAllowed = oldUnsafeAllowed; } else { assert(false); } assert(symbol.resolvedType != null); symbol.state = SymbolState.INITIALIZED; } /** * Derive a concrete class from class template type * @param context * @param type * @param parameters * @param scope * @returns {Symbol} */ function deriveConcreteClass(context: CheckContext, type: Node, parameters: any[], scope: Scope) { let templateNode: Node = type.resolvedType.pointerTo ? type.resolvedType.pointerTo.symbol.node : type.resolvedType.symbol.node; let templateName = templateNode.stringValue; let typeName = templateNode.stringValue + `<${parameters[0].stringValue}>`; let rename = templateNode.stringValue + `_${parameters[0].stringValue}`; let symbol = scope.parent.findNested(typeName, ScopeHint.NORMAL, FindNested.NORMAL); if (symbol) { // resolve(context, type.firstChild.firstChild, scope.parent); let genericSymbol = scope.parent.findNested(type.firstChild.firstChild.stringValue, ScopeHint.NORMAL, FindNested.NORMAL); type.firstChild.firstChild.symbol = genericSymbol; if (genericSymbol.resolvedType.pointerTo) { type.firstChild.firstChild.resolvedType = genericSymbol.resolvedType.pointerType(); } else { type.firstChild.firstChild.resolvedType = genericSymbol.resolvedType; } type.symbol = symbol; if (type.resolvedType.pointerTo) { type.resolvedType = symbol.resolvedType.pointerType(); } else { type.resolvedType = symbol.resolvedType; } return; } let node: Node = templateNode.clone(); // node.parent = templateNode.parent; node.stringValue = typeName; cloneChildren(templateNode.firstChild.nextSibling, node, parameters, templateName, typeName); node.offset = null;//FIXME: we cannot take offset from class template node initialize(context, node, scope.parent, CheckMode.NORMAL); resolve(context, node, scope.parent); node.symbol.flags |= SYMBOL_FLAG_USED; node.constructorFunctionNode.symbol.flags |= SYMBOL_FLAG_USED; type.symbol = node.symbol; node.symbol.rename = rename; if (type.resolvedType.pointerTo) { type.resolvedType = node.symbol.resolvedType.pointerType(); } else { type.resolvedType = node.symbol.resolvedType; } if (templateNode.parent) { templateNode.replaceWith(node); } else { let prevNode = templateNode.derivedNodes[templateNode.derivedNodes.length - 1]; prevNode.parent.insertChildAfter(prevNode, node); } if (templateNode.derivedNodes === undefined) { templateNode.derivedNodes = []; } templateNode.derivedNodes.push(node); //Leave the parameter for the emitter to identify the type type.firstChild.firstChild.kind = NodeKind.NAME; resolve(context, type.firstChild.firstChild, scope.parent); type.stringValue = node.symbol.name; return; } function cloneChildren(child: Node, parentNode: Node, parameters: any[], templateName: string, typeName: string): void { let firstChildNode: Node = null; let lastChildNode: Node = null; while (child) { if (child.stringValue == "this" && child.parent.symbol && child.parent.symbol.kind == SymbolKind.FUNCTION_INSTANCE && child.kind == NodeKind.TYPE) { child = child.nextSibling; continue; } let childNode: Node; if (child.kind == NodeKind.PARAMETERS || child.kind == NodeKind.PARAMETER) { child = child.nextSibling; continue; } if (child.isGeneric()) { let offset = child.offset; if (child.resolvedType) { offset = child.resolvedType.pointerTo ? child.resolvedType.pointerTo.symbol.node.offset : child.resolvedType.symbol.node.offset; } if (child.symbol && isVariable(child.symbol.kind)) { childNode = child.clone(); } else { childNode = parameters[offset].clone(); } childNode.kind = NodeKind.NAME; } else { if (child.stringValue == "T") { Terminal.write("Generic type escaped!"); Terminal.write(child); } childNode = child.clone(); if (childNode.stringValue == templateName) { childNode.stringValue = typeName; } } childNode.parent = parentNode; if (childNode.stringValue == "constructor" && childNode.parent.kind == NodeKind.CLASS) { childNode.parent.constructorFunctionNode = childNode; } if (!firstChildNode) { firstChildNode = childNode; } if (lastChildNode) { lastChildNode.nextSibling = childNode; childNode.previousSibling = lastChildNode; } if (child.firstChild) { cloneChildren(child.firstChild, childNode, parameters, templateName, typeName); } lastChildNode = childNode; child = child.nextSibling; } if (firstChildNode != null) parentNode.firstChild = firstChildNode; if (lastChildNode != null) parentNode.lastChild = lastChildNode; } export function resolveChildren(context: CheckContext, node: Node, parentScope: Scope): void { let child = node.firstChild; while (child != null) { resolve(context, child, parentScope); assert(child.resolvedType != null); child = child.nextSibling; } } export function resolveChildrenAsExpressions(context: CheckContext, node: Node, parentScope: Scope): void { let child = node.firstChild; while (child != null) { resolveAsExpression(context, child, parentScope); child = child.nextSibling; } } export function resolveAsExpression(context: CheckContext, node: Node, parentScope: Scope): void { assert(isExpression(node)); resolve(context, node, parentScope); assert(node.resolvedType != null); if (node.resolvedType != context.errorType) { if (node.isType()) { context.log.error(node.range, "Expected expression but found type"); node.resolvedType = context.errorType; } else if (node.resolvedType == context.voidType && node.parent.kind != NodeKind.EXPRESSION) { context.log.error(node.range, "This expression does not return a value"); node.resolvedType = context.errorType; } } } export function resolveAsType(context: CheckContext, node: Node, parentScope: Scope): void { assert(isExpression(node)); resolve(context, node, parentScope); assert(node.resolvedType != null); if (node.resolvedType != context.errorType && !node.isType()) { context.log.error(node.range, "Expected type but found expression"); node.resolvedType = context.errorType; } } export function canConvert(context: CheckContext, node: Node, to: Type, kind: ConversionKind): boolean { let from = node.resolvedType; assert(isExpression(node)); assert(from != null); assert(to != null); //Generic always accept any types if (from.isGeneric() || to.isGeneric()) { return true; } // Early-out if the types are identical or errors if (from == to || from == context.errorType || to == context.errorType) { return true; } // Allow conversions from null else if (from == context.nullType/* && to.isReference()*/) { return true; } // Allow explicit conversions between references in unsafe mode else if (/*context.isUnsafeAllowed && */(from.isReference() || to.isReference())) { if (kind == ConversionKind.EXPLICIT) { return true; } } // Allow conversions from boolean else if (from == context.booleanType) { return true; } // Check integer conversions else if (from.isInteger() && to.isInteger()) { let mask = to.integerBitMask(context); if (from.isUnsigned() && to.isUnsigned()) { return true; } // Allow implicit conversions between enums and int32 if (from.isEnum() && to == from.underlyingType(context)) { return true; } if (!node.intValue) { return true; } // Only allow lossless conversions implicitly if (kind == ConversionKind.EXPLICIT || from.symbol.byteSize < to.symbol.byteSize || node.kind == NodeKind.INT32 && (to.isUnsigned() ? node.intValue >= 0 && node.intValue <= MAX_UINT32_VALUE : node.intValue >= MIN_INT32_VALUE && node.intValue <= MAX_INT32_VALUE)) { return true; } return false; } else if ( from.isInteger() && to.isFloat() || from.isInteger() && to.isDouble() || from.isLong() && to.isInteger() || from.isLong() && to.isFloat() || from.isLong() && to.isDouble() || from.isFloat() && to.isInteger() || from.isFloat() && to.isLong() || from.isDouble() && to.isInteger() || from.isDouble() && to.isLong() || from.isDouble() && to.isFloat() ) { if (kind == ConversionKind.IMPLICIT) { return false; } return true; } else if ( from.isInteger() && to.isLong() || from.isFloat() && to.isDouble() || from.isFloat() && to.isFloat() || from.isDouble() && to.isDouble() ) { return true; } return false; } export function checkConversion(context: CheckContext, node: Node, to: Type, kind: ConversionKind): void { if (!canConvert(context, node, to, kind)) { context.log.error(node.range, `Cannot convert from type '${node.resolvedType.toString()}' to type '${to.toString()}' ${ kind == ConversionKind.IMPLICIT && canConvert(context, node, to, ConversionKind.EXPLICIT) ? "without a cast" : ""}` ); node.resolvedType = context.errorType; } } export function checkStorage(context: CheckContext, target: Node): void { assert(isExpression(target)); if (target.resolvedType != context.errorType && target.kind != NodeKind.INDEX && target.kind != NodeKind.POINTER_INDEX && target.kind != NodeKind.DEREFERENCE && ( target.kind != NodeKind.NAME && target.kind != NodeKind.DOT || target.symbol != null && ( !isVariable(target.symbol.kind) || target.symbol.kind == SymbolKind.VARIABLE_CONSTANT ) ) ) { context.log.error(target.range, "Cannot store to this location"); target.resolvedType = context.errorType; } } export function createDefaultValueForType(context: CheckContext, type: Type): Node { if (type.isLong()) { return createLong(0); } else if (type.isInteger()) { return createInt(0); } else if (type.isDouble()) { return createDouble(0); } else if (type.isFloat()) { return createFloat(0); } if (type == context.booleanType) { return createboolean(false); } if (type.isClass()) { return createNull(); } if (type.isGeneric()) { return createNull(); } assert(type.isReference()); return createNull(); } export function simplifyBinary(node: Node): void { let left = node.binaryLeft(); let right = node.binaryRight(); // Canonicalize commutative operators if ((node.kind == NodeKind.ADD || node.kind == NodeKind.MULTIPLY || node.kind == NodeKind.BITWISE_AND || node.kind == NodeKind.BITWISE_OR || node.kind == NodeKind.BITWISE_XOR) && left.kind == NodeKind.INT32 && right.kind != NodeKind.INT32) { node.appendChild(left.remove()); left = node.binaryLeft(); right = node.binaryRight(); } // Convert multiplication or division by a power of 2 into a shift if ((node.kind == NodeKind.MULTIPLY || (node.kind == NodeKind.DIVIDE || node.kind == NodeKind.REMAINDER) && node.resolvedType.isUnsigned()) && right.kind == NodeKind.INT32 && isPositivePowerOf2(right.intValue)) { // Extract the shift from the value let shift = -1; let value = right.intValue; while (value != 0) { value = value >> 1; shift = shift + 1; } // "x * 16" => "x << 4" if (node.kind == NodeKind.MULTIPLY) { node.kind = NodeKind.SHIFT_LEFT; right.intValue = shift; } // "x / 16" => "x >> 4" when x is unsigned else if (node.kind == NodeKind.DIVIDE) { node.kind = NodeKind.SHIFT_RIGHT; right.intValue = shift; } // "x % 16" => "x & 15" when x is unsigned else if (node.kind == NodeKind.REMAINDER) { node.kind = NodeKind.BITWISE_AND; right.intValue = right.intValue - 1; } else { assert(false); } } // Flip addition with negation into subtraction else if (node.kind == NodeKind.ADD && right.kind == NodeKind.NEGATIVE) { node.kind = NodeKind.SUBTRACT; right.replaceWith(right.unaryValue().remove()); } // Flip addition with negative constants into subtraction else if (node.kind == NodeKind.ADD && right.isNegativeInteger()) { node.kind = NodeKind.SUBTRACT; right.intValue = -right.intValue; } } export function binaryHasUnsignedArguments(node: Node): boolean { let left = node.binaryLeft(); let right = node.binaryRight(); let leftType = left.resolvedType; let rightType = right.resolvedType; return leftType.isUnsigned() && rightType.isUnsigned() || leftType.isUnsigned() && right.isNonNegativeInteger() || left.isNonNegativeInteger() && rightType.isUnsigned(); } export function isBinaryLong(node: Node): boolean { let left = node.binaryLeft(); let right = node.binaryRight(); let leftType = left.resolvedType; let rightType = right.resolvedType; return leftType.isLong() || rightType.isLong(); } export function isBinaryDouble(node: Node): boolean { let left = node.binaryLeft(); let right = node.binaryRight(); let leftType = left.resolvedType; let rightType = right.resolvedType; return leftType.isDouble() || rightType.isDouble(); } export function isSymbolAccessAllowed(context: CheckContext, symbol: Symbol, node: Node, range: SourceRange): boolean { if (symbol.isUnsafe() && !context.isUnsafeAllowed) { context.log.error(range, `Cannot use symbol '${symbol.name}' outside an 'unsafe' block`); return false; } if (symbol.node != null && symbol.node.isPrivate()) { let parent = symbol.parent(); if (parent != null && context.enclosingClass != parent) { context.log.error(range, `Cannot access private symbol '${symbol.name}' here`); return false; } } if (isFunction(symbol.kind) && (symbol.isSetter() ? !node.isAssignTarget() : !node.isCallValue())) { if (symbol.isSetter()) { context.log.error(range, `Cannot use setter '${symbol.name}' here`); } else { context.log.error(range, `Must call function '${symbol.name}'`); } return false; } return true; } export function resolve(context: CheckContext, node: Node, parentScope: Scope): void { let kind = node.kind; assert(kind == NodeKind.FILE || parentScope != null); if (node.resolvedType != null) { return; } node.resolvedType = context.errorType; if (kind == NodeKind.FILE || kind == NodeKind.GLOBAL) { resolveChildren(context, node, parentScope); } else if (kind == NodeKind.MODULE) { let oldEnclosingModule = context.enclosingModule; initializeSymbol(context, node.symbol); context.enclosingModule = node.symbol; resolveChildren(context, node, node.scope); context.enclosingModule = oldEnclosingModule; } else if (kind == NodeKind.IMPORT || kind == NodeKind.IMPORT_FROM) { //ignore imports } else if (kind == NodeKind.CLASS) { let oldEnclosingClass = context.enclosingClass; initializeSymbol(context, node.symbol); context.enclosingClass = node.symbol; resolveChildren(context, node, node.scope); if (!node.isDeclare() && node.constructorFunctionNode === undefined) { node.constructorFunctionNode = node.createEmptyConstructor(); node.appendChild(node.constructorFunctionNode); initialize(context, node.constructorFunctionNode, node.scope, CheckMode.NORMAL); // let firstFunction = node.firstInstanceFunction(); // if(firstFunction === undefined){ // node.insertChildBefore(firstFunction, node.constructorFunctionNode); // } else { // node.insertChildBefore(firstFunction, node.constructorFunctionNode); // } resolve(context, node.constructorFunctionNode, node.scope); } if (node.symbol.kind == SymbolKind.TYPE_CLASS) { node.symbol.determineClassLayout(context); } context.enclosingClass = oldEnclosingClass; } else if (kind == NodeKind.ENUM) { initializeSymbol(context, node.symbol); resolveChildren(context, node, node.scope); } else if (kind == NodeKind.FUNCTION) { let body = node.functionBody(); initializeSymbol(context, node.symbol); if (node.stringValue == "constructor" && node.parent.kind == NodeKind.CLASS) { node.parent.constructorFunctionNode = node; } if (body != null) { let oldReturnType = context.currentReturnType; let oldUnsafeAllowed = context.isUnsafeAllowed; let returnType = node.functionReturnType(); if (returnType.resolvedType.isTemplate() && returnType.hasParameters() && node.parent != returnType.resolvedType.symbol.node) { deriveConcreteClass(context, returnType, [returnType.firstChild.firstChild], returnType.resolvedType.symbol.scope); } context.currentReturnType = returnType.resolvedType; context.isUnsafeAllowed = node.isUnsafe(); resolveChildren(context, body, node.scope); if (oldReturnType && oldReturnType.isTemplate() && returnType.hasParameters() && node.parent != oldReturnType.symbol.node) { deriveConcreteClass(context, returnType, [returnType.firstChild.firstChild], oldReturnType.symbol.scope); } // if (oldReturnType && oldReturnType.isTemplate() && !oldReturnType.symbol.node.hasParameters()) { // deriveConcreteClass(context, oldReturnType.symbol.node, [oldReturnType.symbol.node.firstChild], oldReturnType.symbol.scope); // } context.currentReturnType = oldReturnType; context.isUnsafeAllowed = oldUnsafeAllowed; } } else if (kind == NodeKind.PARAMETER) { let symbol = node.symbol; } else if (kind == NodeKind.VARIABLE) { let symbol = node.symbol; initializeSymbol(context, symbol); let oldUnsafeAllowed = context.isUnsafeAllowed; context.isUnsafeAllowed = context.isUnsafeAllowed || node.isUnsafe(); let value = node.variableValue(); if (value != null) { resolveAsExpression(context, value, parentScope); checkConversion(context, value, symbol.resolvedTypeUnderlyingIfEnumValue(context), ConversionKind.IMPLICIT); if (symbol.resolvedType != value.resolvedType) { value.becomeValueTypeOf(symbol, context); } // Variable initializers must be compile-time constants if (symbol.kind == SymbolKind.VARIABLE_GLOBAL && value.kind != NodeKind.INT32 && value.kind != NodeKind.BOOLEAN && value.kind != NodeKind.NULL) { //context.log.error(value.range, "Global initializers must be compile-time constants"); } } else if (symbol.resolvedType != context.errorType) { value = createDefaultValueForType(context, symbol.resolvedType); resolveAsExpression(context, value, parentScope); node.appendChild(value); } // Allocate global variables if (symbol.kind == SymbolKind.VARIABLE_GLOBAL && symbol.resolvedType != context.errorType) { symbol.offset = context.allocateGlobalVariableOffset(symbol.resolvedType.variableSizeOf(context), symbol.resolvedType.variableAlignmentOf(context)); } context.isUnsafeAllowed = oldUnsafeAllowed; } else if (kind == NodeKind.BREAK || kind == NodeKind.CONTINUE) { let found = false; let n = node; while (n != null) { if (n.kind == NodeKind.WHILE) { found = true; break; } n = n.parent; } if (!found) { context.log.error(node.range, "Cannot use this statement outside of a loop"); } } else if (kind == NodeKind.BLOCK) { let oldUnsafeAllowed = context.isUnsafeAllowed; if (node.isUnsafe()) context.isUnsafeAllowed = true; resolveChildren(context, node, node.scope); context.isUnsafeAllowed = oldUnsafeAllowed; } else if (kind == NodeKind.IMPORTS || kind == NodeKind.CONSTANTS || kind == NodeKind.VARIABLES) { resolveChildren(context, node, parentScope); } else if (kind == NodeKind.ANY) { //imported functions have anyType node.kind = NodeKind.TYPE; node.resolvedType = context.anyType; } else if (kind == NodeKind.INT32) { // Use the positive flag to differentiate between -2147483648 and 2147483648 node.resolvedType = node.intValue < 0 && !node.isPositive() ? context.uint32Type : context.int32Type; } else if (kind == NodeKind.INT64) { node.resolvedType = node.intValue < 0 && !node.isPositive() ? context.uint64Type : context.int64Type; } else if (kind == NodeKind.FLOAT32) { node.resolvedType = context.float32Type; } else if (kind == NodeKind.FLOAT64) { node.resolvedType = context.float64Type; } else if (kind == NodeKind.STRING) { node.resolvedType = context.stringType; } else if (kind == NodeKind.BOOLEAN) { node.resolvedType = context.booleanType; } else if (kind == NodeKind.NULL) { node.resolvedType = context.nullType; } else if (kind == NodeKind.INDEX) { resolveChildrenAsExpressions(context, node, parentScope); let target = node.indexTarget(); let type = target.resolvedType; if (type != context.errorType) { let symbol = type.hasInstanceMembers() ? type.findMember("[]", ScopeHint.NORMAL) : null; if (symbol == null) { if (target.resolvedType.pointerTo !== undefined) { // convert index to pinter index node.kind = NodeKind.POINTER_INDEX; node.resolvedType = target.resolvedType.pointerTo.symbol.resolvedType; } else { context.log.error(node.internalRange, `Cannot index into type '${target.resolvedType.toString()}'`); } } else { assert(symbol.kind == SymbolKind.FUNCTION_INSTANCE || symbol.kind == SymbolKind.FUNCTION_GLOBAL && symbol.shouldConvertInstanceToGlobal()); // Convert to a regular function call and resolve that instead node.kind = NodeKind.CALL; target.remove(); node.insertChildBefore(node.firstChild, createMemberReference(target, symbol)); node.resolvedType = null; resolveAsExpression(context, node, parentScope); } } } else if (kind == NodeKind.ALIGN_OF) { let type = node.alignOfType(); resolveAsType(context, type, parentScope); node.resolvedType = context.int32Type; if (type.resolvedType != context.errorType) { node.becomeIntegerConstant(type.resolvedType.allocationAlignmentOf(context)); } } else if (kind == NodeKind.SIZE_OF) { let type = node.sizeOfType(); resolveAsType(context, type, parentScope); node.resolvedType = context.int32Type; if (type.resolvedType != context.errorType) { node.becomeIntegerConstant(type.resolvedType.allocationSizeOf(context)); } } else if (kind == NodeKind.THIS) { let symbol = parentScope.findNested("this", ScopeHint.NORMAL, FindNested.NORMAL); if (symbol == null) { context.log.error(node.range, "Cannot use 'this' here"); } else { node.becomeSymbolReference(symbol); } } else if (kind == NodeKind.PARSE_ERROR) { node.resolvedType = context.errorType; } else if (kind == NodeKind.NAME) { let name = node.stringValue; let symbol = parentScope.findNested(name, ScopeHint.NORMAL, FindNested.NORMAL); if (symbol == null) { let errorMessage = `No symbol named '${name}' here`; // In JavaScript, "this." before instance symbols is required symbol = parentScope.findNested(name, ScopeHint.NORMAL, FindNested.ALLOW_INSTANCE_ERRORS); if (symbol != null) { errorMessage += `, did you mean 'this.${symbol.name}'?`; } // People may try to use types from TypeScript else if (name == "number") { // TODO: convert to float64 automatically errorMessage += ", you cannot use generic number type from TypeScript!"; } else if (name == "bool") { errorMessage += ", did you mean 'boolean'?"; } context.log.error(node.range, errorMessage); } else if (symbol.state == SymbolState.INITIALIZING) { context.log.error(node.range, `Cyclic reference to symbol '${name}' here`); } else if (isSymbolAccessAllowed(context, symbol, node, node.range)) { initializeSymbol(context, symbol); node.symbol = symbol; node.resolvedType = symbol.resolvedType; if (node.resolvedType.isGeneric()) { node.flags |= NODE_FLAG_GENERIC; } // Inline constants if (symbol.kind == SymbolKind.VARIABLE_CONSTANT) { if (symbol.resolvedType == context.booleanType) { node.becomeBooleanConstant(symbol.offset != 0); } else if (symbol.resolvedType == context.float32Type) { node.becomeFloatConstant(symbol.offset); } else if (symbol.resolvedType == context.float64Type) { node.becomeDoubleConstant(symbol.offset); } else if (symbol.resolvedType == context.int64Type) { node.becomeLongConstant(symbol.offset); } else { node.becomeIntegerConstant(symbol.offset); } } } } else if (kind == NodeKind.CAST) { let value = node.castValue(); let type = node.castType(); resolveAsExpression(context, value, parentScope); resolveAsType(context, type, parentScope); let castedType = type.resolvedType; checkConversion(context, value, castedType, ConversionKind.EXPLICIT); node.resolvedType = castedType; // Automatically fold constants if (value.kind == NodeKind.INT32 && castedType.isInteger()) { let result = value.intValue; let shift = 32 - castedType.integerBitCount(context); node.becomeIntegerConstant(castedType.isUnsigned() ? castedType.integerBitMask(context) & result : result << shift >> shift); } //i32 to f32 else if (value.kind == NodeKind.INT32 && castedType.isFloat()) { node.becomeFloatConstant(value.intValue); } //i32 to f64 else if (value.kind == NodeKind.INT32 && castedType.isDouble()) { node.becomeDoubleConstant(value.intValue); } //f32 to i32 else if (value.kind == NodeKind.FLOAT32 && castedType.isInteger()) { node.becomeIntegerConstant(Math.round(value.floatValue)); } } else if (kind == NodeKind.DOT) { let target = node.dotTarget(); resolve(context, target, parentScope); if (target.resolvedType != context.errorType) { if (target.isType() && (target.resolvedType.isEnum() || target.resolvedType.hasInstanceMembers()) || !target.isType() && target.resolvedType.hasInstanceMembers()) { let name = node.stringValue; // Empty names are left over from parse errors that have already been reported if (name.length > 0) { let symbol = target.resolvedType.findMember(name, node.isAssignTarget() ? ScopeHint.PREFER_SETTER : ScopeHint.PREFER_GETTER); if (symbol == null) { context.log.error( node.internalRange, `No member named '${name}' on type '${target.resolvedType.toString()}'` ); } // Automatically call getters else if (symbol.isGetter()) { if (node.parent.stringValue === node.stringValue && node.parent.kind === NodeKind.CALL) { node.parent.resolvedType = null; node.symbol = symbol; node.resolvedType = symbol.resolvedType; resolveAsExpression(context, node.parent, parentScope); } else { node.kind = NodeKind.CALL; node.appendChild(createMemberReference(target.remove(), symbol)); node.resolvedType = null; resolveAsExpression(context, node, parentScope); } return; } else if (isSymbolAccessAllowed(context, symbol, node, node.internalRange)) { initializeSymbol(context, symbol); node.symbol = symbol; node.resolvedType = symbol.resolvedType; // Inline constants if (symbol.kind == SymbolKind.VARIABLE_CONSTANT) { node.becomeIntegerConstant(symbol.offset); } } } } else { context.log.error( node.internalRange, `The type '${target.resolvedType.toString()}' has no members` ); } } } else if (kind == NodeKind.CALL) { let value = node.callValue(); resolveAsExpression(context, value, parentScope); if (value.resolvedType != context.errorType) { let symbol = value.symbol; // Only functions are callable if (symbol == null || !isFunction(symbol.kind)) { context.log.error( value.range, `Cannot call value of type '${value.resolvedType.toString()}'`); } else { initializeSymbol(context, symbol); if (symbol.shouldConvertInstanceToGlobal()) { let name = createSymbolReference(symbol); node.insertChildBefore(value, name.withRange(value.internalRange)); node.insertChildBefore(value, value.dotTarget().remove()); value.remove(); value = name; } if (symbol.name === "malloc") { Compiler.mallocRequired = true; } let returnType = symbol.node.functionReturnType(); let argumentVariable = symbol.node.functionFirstArgumentIgnoringThis(); let argumentValue = value.nextSibling; // Match argument values with variables while (argumentVariable != returnType && argumentValue != null) { resolveAsExpression(context, argumentValue, parentScope); checkConversion(context, argumentValue, argumentVariable.symbol.resolvedType, ConversionKind.IMPLICIT); argumentVariable = argumentVariable.nextSibling; argumentValue = argumentValue.nextSibling; } // Not enough argumentVariables? if (returnType.resolvedType != context.anyType) { if (argumentVariable != returnType && !argumentVariable.hasVariableValue()) { context.log.error( node.internalRange, `Not enough arguments for function '${symbol.name}'`); } // Too many argumentVariables? else if (argumentValue != null) { while (argumentValue != null) { resolveAsExpression(context, argumentValue, parentScope); argumentValue = argumentValue.nextSibling; } context.log.error( node.internalRange, `Too many arguments for function '${symbol.name}'`); } } if (returnType.resolvedType.isArray()) { Terminal.write(returnType); } // Pass the return type along node.resolvedType = returnType.resolvedType; } } } else if (kind == NodeKind.DELETE) { let value = node.deleteType(); if (value != null) { resolveAsExpression(context, value, parentScope); if (value.resolvedType == null || value.resolvedType == context.voidType) { context.log.error(value.range, "Unexpected delete value 'void'"); } } else { context.log.error( node.range, `Expected delete value '${context.currentReturnType.toString()}'` ); } } else if (kind == NodeKind.RETURN) { let value = node.returnValue(); if (value != null) { resolveAsExpression(context, value, parentScope); if (context.currentReturnType != null) { if (context.currentReturnType != context.voidType) { if (value.resolvedType.isTemplate() && value.hasParameters() && node.parent != value.resolvedType.symbol.node) { deriveConcreteClass(context, value, [value.firstChild.firstChild], value.resolvedType.symbol.scope); } checkConversion(context, value, context.currentReturnType, ConversionKind.IMPLICIT); } else { context.log.error(value.range, "Unexpected return value in function returning 'void'"); } } node.parent.returnNode = node; } else if (context.currentReturnType != null && context.currentReturnType != context.voidType) { context.log.error( node.range, `Expected return value in function returning '${context.currentReturnType.toString()}'` ); } } else if (kind == NodeKind.EMPTY) { } else if (kind == NodeKind.PARAMETERS) { // resolveAsType(context, node.genericType(), parentScope); // resolveAsExpression(context, node.expressionValue(), parentScope); // context.log.error(node.range, "Generics are not implemented yet"); } else if (kind == NodeKind.EXTENDS) { resolveAsType(context, node.extendsType(), parentScope); //context.log.error(node.range, "Subclassing is not implemented yet"); } else if (kind == NodeKind.IMPLEMENTS) { let child = node.firstChild; while (child != null) { resolveAsType(context, child, parentScope); child = child.nextSibling; } context.log.error(node.range, "Interfaces are not implemented yet"); } else if (kind == NodeKind.EXPRESSIONS) { let child = node.firstChild; while (child) { resolveAsExpression(context, child.expressionValue(), parentScope); child = child.nextSibling; } } else if (kind == NodeKind.EXPRESSION) { resolveAsExpression(context, node.expressionValue(), parentScope); } else if (kind == NodeKind.WHILE) { let value = node.whileValue(); let body = node.whileBody(); resolveAsExpression(context, value, parentScope); checkConversion(context, value, context.booleanType, ConversionKind.IMPLICIT); resolve(context, body, parentScope); } else if (kind == NodeKind.FOR) { let initializationStmt = node.forInitializationStatement(); let terminationStmt = node.forTerminationStatement(); let updateStmts = node.forUpdateStatements(); let body = node.forBody(); resolve(context, initializationStmt, parentScope); resolveAsExpression(context, terminationStmt, parentScope); resolve(context, updateStmts, parentScope); checkConversion(context, terminationStmt, context.booleanType, ConversionKind.IMPLICIT); resolve(context, body, parentScope); } else if (kind == NodeKind.IF) { let value = node.ifValue(); let yes = node.ifTrue(); let no = node.ifFalse(); resolveAsExpression(context, value, parentScope); checkConversion(context, value, context.booleanType, ConversionKind.IMPLICIT); resolve(context, yes, parentScope); if (no != null) { resolve(context, no, parentScope); } } else if (kind == NodeKind.HOOK) { let value = node.hookValue(); let yes = node.hookTrue(); let no = node.hookFalse(); resolveAsExpression(context, value, parentScope); checkConversion(context, value, context.booleanType, ConversionKind.IMPLICIT); resolve(context, yes, parentScope); resolve(context, no, parentScope); checkConversion(context, yes, no.resolvedType, ConversionKind.IMPLICIT); let commonType = (yes.resolvedType == context.nullType ? no : yes).resolvedType; if (yes.resolvedType != commonType && (yes.resolvedType != context.nullType || !commonType.isReference()) && no.resolvedType != commonType && (no.resolvedType != context.nullType || !commonType.isReference())) { context.log.error( spanRanges(yes.range, no.range), `Type '${yes.resolvedType.toString()}' is not the same as type '${no.resolvedType.toString()}'` ); } node.resolvedType = commonType; } else if (kind == NodeKind.ASSIGN) { let left = node.binaryLeft(); let right = node.binaryRight(); if (left.kind == NodeKind.INDEX) { resolveChildrenAsExpressions(context, left, parentScope); let target = left.indexTarget(); let type = target.resolvedType; if (type != context.errorType) { let symbol = type.hasInstanceMembers() ? type.findMember("[]=", ScopeHint.NORMAL) : null; if (symbol == null) { if (target.resolvedType.pointerTo != undefined) { left.kind = NodeKind.POINTER_INDEX; left.resolvedType = target.resolvedType.pointerTo.symbol.resolvedType; } else { context.log.error( left.internalRange, `Cannot index into type '${target.resolvedType.toString()}'` ); } } else { assert(symbol.kind == SymbolKind.FUNCTION_INSTANCE); // Convert to a regular function call and resolve that instead node.kind = NodeKind.CALL; target.remove(); left.remove(); while (left.lastChild != null) { node.insertChildBefore(node.firstChild, left.lastChild.remove()); } node.insertChildBefore(node.firstChild, createMemberReference(target, symbol)); node.internalRange = spanRanges(left.internalRange, right.range); node.resolvedType = null; resolveAsExpression(context, node, parentScope); return; } } } if (!left.resolvedType) { resolveAsExpression(context, left, parentScope); } // Automatically call setters if (left.symbol != null && left.symbol.isSetter()) { node.kind = NodeKind.CALL; node.internalRange = left.internalRange; node.resolvedType = null; resolveAsExpression(context, node, parentScope); return; } resolveAsExpression(context, right, parentScope); checkConversion(context, right, left.resolvedType, ConversionKind.IMPLICIT); checkStorage(context, left); node.resolvedType = left.resolvedType; } else if (kind == NodeKind.NEW) { Compiler.mallocRequired = true; let type = node.newType(); resolveAsType(context, type, parentScope); if (type.resolvedType.isTemplate() && type.hasParameters() && node.parent != type.resolvedType.symbol.node) { deriveConcreteClass(context, type, [type.firstChild.firstChild], type.resolvedType.symbol.scope); } if (type.resolvedType != context.errorType) { if (!type.resolvedType.isClass()) { context.log.error( type.range, `Cannot construct type '${type.resolvedType.toString()}'` ); } else { node.resolvedType = type.resolvedType; } } //Constructors argumentVariables let child = type.nextSibling; let constructorNode = node.constructorNode(); if (constructorNode !== undefined) { let argumentVariable = constructorNode.functionFirstArgument(); while (child != null) { resolveAsExpression(context, child, parentScope); checkConversion(context, child, argumentVariable.symbol.resolvedType, ConversionKind.IMPLICIT); child = child.nextSibling; argumentVariable = argumentVariable.nextSibling; } } // Match argument values with variables // while (argumentVariable != returnType && argumentValue != null) { // resolveAsExpression(context, argumentValue, parentScope); // checkConversion(context, argumentValue, argumentVariable.symbol.resolvedType, ConversionKind.IMPLICIT); // argumentVariable = argumentVariable.nextSibling; // argumentValue = argumentValue.nextSibling; // } } else if (kind == NodeKind.POINTER_TYPE) { let value = node.unaryValue(); resolveAsType(context, value, parentScope); if (context.target == CompileTarget.JAVASCRIPT) { context.log.error(node.internalRange, "Cannot use pointers when compiling to JavaScript"); } /*else if (!context.isUnsafeAllowed) { context.log.error(node.internalRange, "Cannot use pointers outside an 'unsafe' block"); }*/ else { let type = value.resolvedType; if (type != context.errorType) { node.resolvedType = type.pointerType(); } } } else if (kind == NodeKind.POINTER_INDEX) { debugger } else if (kind == NodeKind.DEREFERENCE) { let value = node.unaryValue(); resolveAsExpression(context, value, parentScope); let type = value.resolvedType; if (type != context.errorType) { if (type.pointerTo == null) { context.log.error(node.internalRange, `Cannot dereference type '${type.toString()}'`); } else { node.resolvedType = type.pointerTo; } } } else if (kind == NodeKind.ADDRESS_OF) { let value = node.unaryValue(); resolveAsExpression(context, value, parentScope); context.log.error(node.internalRange, "The address-of operator is not supported"); } else if (isUnary(kind)) { let value = node.unaryValue(); resolveAsExpression(context, value, parentScope); // Operator "!" is hard-coded if (kind == NodeKind.NOT) { checkConversion(context, value, context.booleanType, ConversionKind.IMPLICIT); node.resolvedType = context.booleanType; } // Special-case long types else if (value.resolvedType.isLong()) { if (value.resolvedType.isUnsigned()) { node.flags = node.flags | NODE_FLAG_UNSIGNED_OPERATOR; node.resolvedType = context.uint64Type; } else { node.resolvedType = context.int64Type; } // Automatically fold constants if (value.kind == NodeKind.INT64) { let input = value.longValue; let output = input; if (kind == NodeKind.COMPLEMENT) output = ~input; else if (kind == NodeKind.NEGATIVE) output = -input; node.becomeLongConstant(output); } } // Special-case integer types else if (value.resolvedType.isInteger()) { if (value.resolvedType.isUnsigned()) { node.flags = node.flags | NODE_FLAG_UNSIGNED_OPERATOR; node.resolvedType = context.uint32Type; } else { node.resolvedType = context.int32Type; } // Automatically fold constants if (value.kind == NodeKind.INT32) { let input = value.intValue; let output = input; if (kind == NodeKind.COMPLEMENT) output = ~input; else if (kind == NodeKind.NEGATIVE) output = -input; node.becomeIntegerConstant(output); } } // Special-case double types else if (value.resolvedType.isDouble()) { node.resolvedType = context.float64Type; // Automatically fold constants if (value.kind == NodeKind.FLOAT64) { let input = value.doubleValue; let output = input; if (kind == NodeKind.COMPLEMENT) output = ~input; else if (kind == NodeKind.NEGATIVE) output = -input; node.becomeDoubleConstant(output); } } // Special-case float types else if (value.resolvedType.isFloat()) { node.resolvedType = context.float32Type; // Automatically fold constants if (value.kind == NodeKind.FLOAT32) { let input = value.floatValue; let output = input; if (kind == NodeKind.COMPLEMENT) output = ~input; else if (kind == NodeKind.NEGATIVE) output = -input; node.becomeFloatConstant(output); } } // Support custom operators else if (value.resolvedType != context.errorType) { let name = node.internalRange.toString(); let symbol = value.resolvedType.findMember(name, ScopeHint.NOT_BINARY); // Automatically call the function if (symbol != null) { node.appendChild(createMemberReference(value.remove(), symbol).withRange(node.range).withInternalRange(node.internalRange)); node.kind = NodeKind.CALL; node.resolvedType = null; resolveAsExpression(context, node, parentScope); } else { context.log.error(node.internalRange, `Cannot use unary operator '${name}' with type '${value.resolvedType.toString()}'`); } } } else if (isBinary(kind)) { let left = node.binaryLeft(); let right = node.binaryRight(); resolveAsExpression(context, left, parentScope); resolveAsExpression(context, right, parentScope); let leftType = left.resolvedType; if ((leftType.isDouble() && right.resolvedType.isFloat()) || (leftType.isLong() && right.resolvedType.isInteger())) { right.becomeTypeOf(left, context); } let rightType = right.resolvedType; // Operators "&&" and "||" are hard-coded if (kind == NodeKind.LOGICAL_OR || kind == NodeKind.LOGICAL_AND) { checkConversion(context, left, context.booleanType, ConversionKind.IMPLICIT); checkConversion(context, right, context.booleanType, ConversionKind.IMPLICIT); node.resolvedType = context.booleanType; } // Special-case pointer types (it's the emitter's job to scale the integer delta by the size of the pointer target) else if (kind == NodeKind.ADD && leftType.pointerTo != null && rightType.isInteger()) { node.resolvedType = leftType; } // Special-case pointer types else if ((kind == NodeKind.LESS_THAN || kind == NodeKind.LESS_THAN_EQUAL || kind == NodeKind.GREATER_THAN || kind == NodeKind.GREATER_THAN_EQUAL) && ( leftType.pointerTo != null || rightType.pointerTo != null)) { node.resolvedType = context.booleanType; // Both pointer types must be exactly the same if (leftType != rightType) { context.log.error(node.internalRange, `Cannot compare type '${leftType.toString()}' with type '${rightType.toString()}'`); } } // Operators for integers and floats are hard-coded else if ( ( leftType.isInteger() || leftType.isLong() || leftType.isFloat() || leftType.isDouble() || (leftType.isGeneric() && rightType.isGeneric()) ) && kind != NodeKind.EQUAL && kind != NodeKind.NOT_EQUAL) { let isFloat: boolean = false; let isFloat64: boolean = false; if (leftType.isFloat() || leftType.isDouble()) { isFloat = true; isFloat64 = leftType.isDouble(); } let isUnsigned = binaryHasUnsignedArguments(node); // Arithmetic operators if (kind == NodeKind.ADD || kind == NodeKind.SUBTRACT || kind == NodeKind.MULTIPLY || kind == NodeKind.DIVIDE || kind == NodeKind.REMAINDER || kind == NodeKind.BITWISE_AND || kind == NodeKind.BITWISE_OR || kind == NodeKind.BITWISE_XOR || kind == NodeKind.SHIFT_LEFT || kind == NodeKind.SHIFT_RIGHT) { let isLong = isBinaryLong(node); let commonType; if (isFloat) { commonType = isBinaryDouble(node) ? context.float64Type : context.float32Type; } else { commonType = isUnsigned ? (isLong ? context.uint64Type : context.uint32Type) : (isLong ? context.int64Type : context.int32Type); } if (isUnsigned) { node.flags = node.flags | NODE_FLAG_UNSIGNED_OPERATOR; } checkConversion(context, left, commonType, ConversionKind.IMPLICIT); checkConversion(context, right, commonType, ConversionKind.IMPLICIT); node.resolvedType = commonType; // Signature conversion if (commonType == context.int64Type) { if (left.kind == NodeKind.INT32) { left.kind = NodeKind.INT64; left.resolvedType = context.int64Type; } else if (right.kind == NodeKind.INT32) { right.kind = NodeKind.INT64; right.resolvedType = context.int64Type; } } // Automatically fold constants if ((left.kind == NodeKind.INT32 || left.kind == NodeKind.INT64) && (right.kind == NodeKind.INT32 || right.kind == NodeKind.INT64)) { let inputLeft = left.intValue; let inputRight = right.intValue; let output = 0; if (kind == NodeKind.ADD) output = inputLeft + inputRight; else if (kind == NodeKind.BITWISE_AND) output = inputLeft & inputRight; else if (kind == NodeKind.BITWISE_OR) output = inputLeft | inputRight; else if (kind == NodeKind.BITWISE_XOR) output = inputLeft ^ inputRight; else if (kind == NodeKind.DIVIDE) output = inputLeft / inputRight; else if (kind == NodeKind.MULTIPLY) output = inputLeft * inputRight; else if (kind == NodeKind.REMAINDER) output = inputLeft % inputRight; else if (kind == NodeKind.SHIFT_LEFT) output = inputLeft << inputRight; else if (kind == NodeKind.SHIFT_RIGHT) output = isUnsigned ? ((inputLeft) >> (inputRight)) : inputLeft >> inputRight; else if (kind == NodeKind.SUBTRACT) output = inputLeft - inputRight; else return; if (left.kind == NodeKind.INT32) { node.becomeIntegerConstant(output); } else { node.becomeLongConstant(output); } } else if ((left.kind == NodeKind.FLOAT32 || left.kind == NodeKind.FLOAT64) && (right.kind == NodeKind.FLOAT32 || right.kind == NodeKind.FLOAT64)) { let inputLeft = left.floatValue; let inputRight = right.floatValue; let output = 0; if (kind == NodeKind.ADD) output = inputLeft + inputRight; else if (kind == NodeKind.BITWISE_AND) output = inputLeft & inputRight; else if (kind == NodeKind.BITWISE_OR) output = inputLeft | inputRight; else if (kind == NodeKind.BITWISE_XOR) output = inputLeft ^ inputRight; else if (kind == NodeKind.DIVIDE) output = inputLeft / inputRight; else if (kind == NodeKind.MULTIPLY) output = inputLeft * inputRight; else if (kind == NodeKind.REMAINDER) output = inputLeft % inputRight; else if (kind == NodeKind.SHIFT_LEFT) output = inputLeft << inputRight; else if (kind == NodeKind.SHIFT_RIGHT) output = inputLeft >> inputRight; else if (kind == NodeKind.SUBTRACT) output = inputLeft - inputRight; else return; if (left.kind == NodeKind.FLOAT32) { node.becomeFloatConstant(output); } else { node.becomeDoubleConstant(output); } } else { simplifyBinary(node); } } // Comparison operators else if ( kind == NodeKind.LESS_THAN || kind == NodeKind.LESS_THAN_EQUAL || kind == NodeKind.GREATER_THAN || kind == NodeKind.GREATER_THAN_EQUAL) { let expectedType = isFloat ? (isFloat64 ? context.float64Type : context.float32Type) : (isUnsigned ? context.uint32Type : context.int32Type); if (isUnsigned) { node.flags = node.flags | NODE_FLAG_UNSIGNED_OPERATOR; } if (leftType != rightType) { checkConversion(context, left, expectedType, ConversionKind.IMPLICIT); checkConversion(context, right, expectedType, ConversionKind.IMPLICIT); } node.resolvedType = context.booleanType; } else { context.log.error(node.internalRange, "This operator is not currently supported"); } } // Support custom operators else if (leftType != context.errorType) { let name = node.internalRange.toString(); let symbol = leftType.findMember( kind == NodeKind.NOT_EQUAL ? "==" : kind == NodeKind.LESS_THAN_EQUAL ? ">" : kind == NodeKind.GREATER_THAN_EQUAL ? "<" : name, ScopeHint.NOT_UNARY); // Automatically call the function if (symbol != null) { left = createMemberReference(left.remove(), symbol).withRange(node.range).withInternalRange(node.internalRange); right.remove(); if (kind == NodeKind.NOT_EQUAL || kind == NodeKind.LESS_THAN_EQUAL || kind == NodeKind.GREATER_THAN_EQUAL) { let call = createCall(left); call.appendChild(right); node.kind = NodeKind.NOT; node.appendChild(call.withRange(node.range).withInternalRange(node.range)); } else { node.appendChild(left); node.appendChild(right); node.kind = NodeKind.CALL; } node.resolvedType = null; resolveAsExpression(context, node, parentScope); } // Automatically implement equality operators else if (kind == NodeKind.EQUAL || kind == NodeKind.NOT_EQUAL) { node.resolvedType = context.booleanType; if ( leftType != context.errorType && rightType != context.errorType && leftType != rightType && !canConvert(context, right, leftType, ConversionKind.IMPLICIT) && !canConvert(context, left, rightType, ConversionKind.IMPLICIT) ) { context.log.error(node.internalRange, `Cannot compare type '${leftType.toString()}' with type '${rightType.toString()}'`); } } else { context.log.error(node.internalRange, `Cannot use binary operator '${name}' with type '${leftType.toString()}'`); } } } else if (kind == NodeKind.TYPE) { //ignore types } else { Terminal.error(`Unexpected kind: ${NodeKind[kind]}`); assert(false); } }
the_stack
import { EventListener } from '@fluentui/react-component-event-listener' import * as React from 'react' import * as ReactDOM from 'react-dom' import * as PropTypes from 'prop-types' import * as _ from 'lodash' import getElementType from '../utils/getElementType' import getUnhandledProps from '../utils/getUnhandledProps' import { getNextElement, getFirstTabbable, getLastTabbable, getWindow, getDocument, focusAsync, HIDDEN_FROM_ACC_TREE, } from './focusUtilities' import { FocusTrapZoneProps } from './FocusTrapZone.types' /** FocusTrapZone is used to trap the focus in any html element placed in body * and hide other elements outside of Focus Trap Zone from accessibility tree. * Pressing tab will circle focus within the inner focusable elements of the FocusTrapZone. */ export default class FocusTrapZone extends React.Component<FocusTrapZoneProps, {}> { static _focusStack: FocusTrapZone[] = [] _root: { current: HTMLElement | null } = { current: null } _previouslyFocusedElementOutsideTrapZone: HTMLElement _previouslyFocusedElementInTrapZone?: HTMLElement _firstBumper = React.createRef<HTMLDivElement>() _lastBumper = React.createRef<HTMLDivElement>() _hasFocus: boolean = false windowRef = React.createRef<Window>() as React.MutableRefObject<Window> // @ts-ignore createRef = elem => { this._root.current = ReactDOM.findDOMNode(elem) as HTMLElement // @ts-ignore this.windowRef.current = getWindow(this._root.current) } shouldHandleOutsideClick = () => !this.props.isClickableOutsideFocusTrap || !this.props.focusTriggerOnOutsideClick static propTypes = { as: PropTypes.elementType, className: PropTypes.string, elementToFocusOnDismiss: PropTypes.object, ariaLabelledBy: PropTypes.string, isClickableOutsideFocusTrap: PropTypes.bool, ignoreExternalFocusing: PropTypes.bool, forceFocusInsideTrapOnOutsideFocus: PropTypes.bool, forceFocusInsideTrapOnComponentUpdate: PropTypes.bool, firstFocusableSelector: PropTypes.string, disableFirstFocus: PropTypes.bool, focusPreviouslyFocusedInnerElement: PropTypes.bool, focusTriggerOnOutsideClick: PropTypes.bool, } static defaultProps: FocusTrapZoneProps = { as: 'div', isClickableOutsideFocusTrap: true, forceFocusInsideTrapOnOutsideFocus: false, } componentDidMount(): void { this._enableFocusTrapZone() } componentDidUpdate(prevProps: FocusTrapZoneProps): void { const { forceFocusInsideTrapOnComponentUpdate, forceFocusInsideTrapOnOutsideFocus, disabled, } = this.props const doc = getDocument(this._root.current) // @ts-ignore const activeElement = doc.activeElement as HTMLElement // if after componentDidUpdate focus is not inside the focus trap, bring it back if ( !disabled && // @ts-ignore !this._root.current.contains(activeElement) && forceFocusInsideTrapOnComponentUpdate ) { this._bringFocusIntoZone() return } const prevForceFocusInsideTrap = prevProps.forceFocusInsideTrapOnOutsideFocus !== undefined ? prevProps.forceFocusInsideTrapOnOutsideFocus : true const newForceFocusInsideTrap = forceFocusInsideTrapOnOutsideFocus !== undefined ? forceFocusInsideTrapOnOutsideFocus : true const prevDisabled = prevProps.disabled !== undefined ? prevProps.disabled : false const newDisabled = disabled !== undefined ? disabled : false if ((!prevForceFocusInsideTrap && newForceFocusInsideTrap) || (prevDisabled && !newDisabled)) { // Transition from forceFocusInsideTrap / FTZ disabled to enabled. // Emulate what happens when a FocusTrapZone gets mounted. this._enableFocusTrapZone() } else if ( (prevForceFocusInsideTrap && !newForceFocusInsideTrap) || (!prevDisabled && newDisabled) ) { // Transition from forceFocusInsideTrap / FTZ enabled to disabled. // Emulate what happens when a FocusTrapZone gets unmounted. this._releaseFocusTrapZone() } } componentWillUnmount(): void { // don't handle return focus unless forceFocusInsideTrapOnOutsideFocus is true or focus is still within FocusTrapZone const doc = getDocument(this._root.current) if ( !this.props.disabled || this.props.forceFocusInsideTrapOnOutsideFocus || // @ts-ignore !this._root.current.contains(doc.activeElement as HTMLElement) ) { this._releaseFocusTrapZone() } // Dispose of element references so the DOM Nodes can be garbage-collected delete this._previouslyFocusedElementInTrapZone delete this._previouslyFocusedElementOutsideTrapZone } render(): JSX.Element { const { className, forceFocusInsideTrapOnOutsideFocus, ariaLabelledBy, disabled = false, } = this.props const unhandledProps = getUnhandledProps(_.keys(FocusTrapZone.propTypes) as any, this.props) const ElementType = getElementType(this.props) const bumperProps = { style: { pointerEvents: 'none', position: 'fixed', // 'fixed' prevents browsers from scrolling to bumpers when viewport does not contain them }, tabIndex: disabled ? -1 : 0, // make bumpers tabbable only when enabled 'data-is-visible': true, } as React.HTMLAttributes<HTMLDivElement> return ( <> <ElementType {...unhandledProps} className={className} ref={this.createRef} aria-labelledby={ariaLabelledBy} onKeyDown={this._onKeyboardHandler} onFocusCapture={this._onFocusCapture} onFocus={this._onRootFocus} onBlur={this._onRootBlur} > <div {...bumperProps} ref={this._firstBumper} onFocus={this._onFirstBumperFocus} /> {this.props.children} <div {...bumperProps} ref={this._lastBumper} onFocus={this._onLastBumperFocus} /> </ElementType> {forceFocusInsideTrapOnOutsideFocus && ( <EventListener capture listener={this._handleOutsideFocus} targetRef={this.windowRef} type="focus" /> )} {this.shouldHandleOutsideClick() && ( <EventListener capture listener={this._handleOutsideClick} targetRef={this.windowRef} type="click" /> )} </> ) } _onRootFocus = (ev: React.FocusEvent<HTMLDivElement>) => { if (this.props.onFocus) { this.props.onFocus(ev) } this._hasFocus = true } _onRootBlur = (ev: React.FocusEvent<HTMLDivElement>) => { if (this.props.onBlur) { this.props.onBlur(ev) } let relatedTarget = ev.relatedTarget if (ev.relatedTarget === null) { // In IE11, due to lack of support, event.relatedTarget is always // null making every onBlur call to be "outside" of the ComboBox // even when it's not. Using document.activeElement is another way // for us to be able to get what the relatedTarget without relying // on the event const doc = getDocument(this._root.current) // @ts-ignore relatedTarget = doc.activeElement as Element } // @ts-ignore if (!this._root.current.contains(relatedTarget as HTMLElement)) { this._hasFocus = false } } _onFirstBumperFocus = () => { this._onBumperFocus(true) } _onLastBumperFocus = () => { this._onBumperFocus(false) } _isBumper(element: HTMLElement): boolean { return element === this._firstBumper.current || element === this._lastBumper.current } _onBumperFocus = (isFirstBumper: boolean) => { if (!this._root.current) { return } const currentBumper = (isFirstBumper === this._hasFocus ? this._lastBumper.current : this._firstBumper.current) as HTMLElement const nextFocusable = isFirstBumper === this._hasFocus ? getLastTabbable(this._root.current, currentBumper, true, false) : getFirstTabbable(this._root.current, currentBumper, true, false) if (nextFocusable) { if (this._isBumper(nextFocusable)) { // This can happen when FTZ contains no tabbable elements. Focus will take care of finding a focusable element in FTZ. this._findElementAndFocusAsync() } else { nextFocusable.focus() } } } _focusAsync(element: HTMLElement): void { if (!this._isBumper(element)) { focusAsync(element) } } _enableFocusTrapZone = () => { const { disabled = false } = this.props if (disabled) { return } FocusTrapZone._focusStack.push(this) this._bringFocusIntoZone() this._hideContentFromAccessibilityTree() } _bringFocusIntoZone = () => { const { disableFirstFocus = false } = this.props this._previouslyFocusedElementOutsideTrapZone = this._getPreviouslyFocusedElementOutsideTrapZone() if ( // @ts-ignore !this._root.current.contains(this._previouslyFocusedElementOutsideTrapZone) && !disableFirstFocus ) { this._findElementAndFocusAsync() } } _releaseFocusTrapZone = () => { const { ignoreExternalFocusing } = this.props FocusTrapZone._focusStack = FocusTrapZone._focusStack.filter((value: FocusTrapZone) => { return this !== value }) // try to focus element which triggered FocusTrapZone - prviously focused element outside trap zone const doc = getDocument(this._root.current) // @ts-ignore const activeElement = doc.activeElement as HTMLElement if ( !ignoreExternalFocusing && this._previouslyFocusedElementOutsideTrapZone && // @ts-ignore (this._root.current.contains(activeElement) || activeElement === doc.body) ) { this._focusAsync(this._previouslyFocusedElementOutsideTrapZone) } // if last active focus trap zone is going to be released - show previously hidden content in accessibility tree const lastActiveFocusTrap = FocusTrapZone._focusStack.length && FocusTrapZone._focusStack[FocusTrapZone._focusStack.length - 1] if (!lastActiveFocusTrap) { this._showContentInAccessibilityTree() } else if ( lastActiveFocusTrap._root.current && lastActiveFocusTrap._root.current.hasAttribute(HIDDEN_FROM_ACC_TREE) ) { lastActiveFocusTrap._root.current.removeAttribute(HIDDEN_FROM_ACC_TREE) lastActiveFocusTrap._root.current.removeAttribute('aria-hidden') } } _findElementAndFocusAsync = () => { if (!this._root.current) { return } const { focusPreviouslyFocusedInnerElement, firstFocusableSelector } = this.props if ( focusPreviouslyFocusedInnerElement && this._previouslyFocusedElementInTrapZone && this._root.current.contains(this._previouslyFocusedElementInTrapZone) ) { // focus on the last item that had focus in the zone before we left the zone this._focusAsync(this._previouslyFocusedElementInTrapZone) return } const focusSelector = firstFocusableSelector && (typeof firstFocusableSelector === 'string' ? firstFocusableSelector : firstFocusableSelector()) let firstFocusableChild: HTMLElement | null = null if (focusSelector) { firstFocusableChild = this._root.current.querySelector(focusSelector) } // Fall back to first element if query selector did not match any elements. if (!firstFocusableChild) { firstFocusableChild = getNextElement( this._root.current, this._root.current.firstChild as HTMLElement, false, false, false, true, ) } firstFocusableChild && this._focusAsync(firstFocusableChild) } _onFocusCapture = (ev: React.FocusEvent<HTMLDivElement>) => { this.props.onFocusCapture && this.props.onFocusCapture(ev) if (ev.target !== ev.currentTarget && !this._isBumper(ev.target)) { // every time focus changes within the trap zone, remember the focused element so that // it can be restored if focus leaves the pane and returns via keystroke (i.e. via a call to this.focus(true)) this._previouslyFocusedElementInTrapZone = ev.target as HTMLElement } } _forceFocusInTrap = (ev: Event, triggeredElement: HTMLElement) => { if ( FocusTrapZone._focusStack.length && this === FocusTrapZone._focusStack[FocusTrapZone._focusStack.length - 1] ) { // @ts-ignore if (!this._root.current.contains(triggeredElement)) { this._findElementAndFocusAsync() ev.preventDefault() ev.stopPropagation() } } } _handleOutsideFocus = (ev: FocusEvent): void => { const doc = getDocument(this._root.current) // @ts-ignore const focusedElement = doc.activeElement as HTMLElement focusedElement && this._forceFocusInTrap(ev, focusedElement) } _handleOutsideClick = (ev: MouseEvent): void => { const clickedElement = ev.target as HTMLElement const { isClickableOutsideFocusTrap, focusTriggerOnOutsideClick } = this.props if (!isClickableOutsideFocusTrap) { clickedElement && this._forceFocusInTrap(ev, clickedElement) } else if (!focusTriggerOnOutsideClick) { const isOutsideFocusTrapZone = this._root.current && !this._root.current.contains(clickedElement) const isOutsideTriggerElement = this._previouslyFocusedElementOutsideTrapZone && !this._previouslyFocusedElementOutsideTrapZone.contains(clickedElement) if (isOutsideFocusTrapZone && isOutsideTriggerElement) { // set it to NULL, so the trigger will not be focused on componentWillUnmount // @ts-ignore this._previouslyFocusedElementOutsideTrapZone = null } } } _onKeyboardHandler = (ev: React.KeyboardEvent<HTMLDivElement>): void => { if (this.props.onKeyDown) { this.props.onKeyDown(ev) } // do not propogate keyboard events outside focus trap zone // https://github.com/microsoft/fluent-ui-react/pull/1180 ev.stopPropagation() } _getPreviouslyFocusedElementOutsideTrapZone = () => { const { elementToFocusOnDismiss } = this.props let previouslyFocusedElement = this._previouslyFocusedElementOutsideTrapZone if (elementToFocusOnDismiss && previouslyFocusedElement !== elementToFocusOnDismiss) { previouslyFocusedElement = elementToFocusOnDismiss } else if (!previouslyFocusedElement) { const doc = getDocument(this._root.current) // @ts-ignore previouslyFocusedElement = doc.activeElement as HTMLElement } return previouslyFocusedElement } _hideContentFromAccessibilityTree = () => { const doc = getDocument(this._root.current) // @ts-ignore const bodyChildren = (doc.body && doc.body.children) || [] // @ts-ignore if (bodyChildren.length && !doc.body.contains(this._root.current)) { // In case popup render options will change /* eslint-disable-next-line no-console */ console.warn( 'Body element does not contain trap zone element. Please, ensure the trap zone element is placed inside body, so it will work properly.', ) } for (let index = 0; index < bodyChildren.length; index++) { const currentChild = bodyChildren[index] as HTMLElement const isOrHasFocusTrapZone = currentChild === this._root.current || currentChild.contains(this._root.current) const isAriaLiveRegion = currentChild.hasAttribute('aria-live') if ( !isOrHasFocusTrapZone && !isAriaLiveRegion && currentChild.getAttribute('aria-hidden') !== 'true' ) { currentChild.setAttribute('aria-hidden', 'true') currentChild.setAttribute(HIDDEN_FROM_ACC_TREE, 'true') } } } _showContentInAccessibilityTree = () => { const doc = getDocument(this._root.current) // @ts-ignore const hiddenElements = doc.querySelectorAll(`[${HIDDEN_FROM_ACC_TREE}="true"]`) for (let index = 0; index < hiddenElements.length; index++) { const element = hiddenElements[index] element.removeAttribute('aria-hidden') element.removeAttribute(HIDDEN_FROM_ACC_TREE) } } }
the_stack
import {File} from './file'; import {ApiError, ErrorCode} from './api_error'; import {FileSystem, BFSOneArgCallback, BFSCallback, BFSThreeArgCallback} from './file_system'; import {FileFlag} from './file_flag'; import * as path from 'path'; import Stats from './node_fs_stats'; import setImmediate from '../generic/setImmediate'; // Typing info only. import * as _fs from 'fs'; /** Used for unit testing. Defaults to a NOP. */ let wrapCbHook = function<T>(cb: T, numArgs: number): T { return cb; }; /** * Wraps a callback function, ensuring it is invoked through setImmediate. * @hidden */ function wrapCb<T extends Function>(cb: T, numArgs: number): T { if (typeof cb !== 'function') { throw new Error('Callback must be a function.'); } const hookedCb = wrapCbHook(cb, numArgs); // We could use `arguments`, but Function.call/apply is expensive. And we only // need to handle 1-3 arguments switch (numArgs) { case 1: return <any> function(arg1: any) { setImmediate(function() { return hookedCb(arg1); }); }; case 2: return <any> function(arg1: any, arg2: any) { setImmediate(function() { return hookedCb(arg1, arg2); }); }; case 3: return <any> function(arg1: any, arg2: any, arg3: any) { setImmediate(function() { return hookedCb(arg1, arg2, arg3); }); }; default: throw new Error('Invalid invocation of wrapCb.'); } } /** * @hidden */ function assertRoot(fs?: FileSystem | null): FileSystem { if (fs) { return fs; } throw new ApiError(ErrorCode.EIO, `Initialize BrowserFS with a file system using BrowserFS.initialize(filesystem)`); } /** * @hidden */ function normalizeMode(mode: number | string | null | undefined, def: number): number { switch (typeof mode) { case 'number': // (path, flag, mode, cb?) return <number> mode; case 'string': // (path, flag, modeString, cb?) const trueMode = parseInt(<string> mode, 8); if (!isNaN(trueMode)) { return trueMode; } // Invalid string. return def; default: return def; } } /** * @hidden */ function normalizeTime(time: number | Date): Date { if (time instanceof Date) { return time; } else if (typeof time === 'number') { return new Date(time * 1000); } else { throw new ApiError(ErrorCode.EINVAL, `Invalid time.`); } } /** * @hidden */ function normalizePath(p: string): string { // Node doesn't allow null characters in paths. if (p.indexOf('\u0000') >= 0) { throw new ApiError(ErrorCode.EINVAL, 'Path must be a string without null bytes.'); } else if (p === '') { throw new ApiError(ErrorCode.EINVAL, 'Path must not be empty.'); } return path.resolve(p); } /** * @hidden */ function normalizeOptions(options: any, defEnc: string | null, defFlag: string, defMode: number | null): {encoding: string; flag: string; mode: number} { // typeof null === 'object' so special-case handing is needed. switch (options === null ? 'null' : typeof options) { case 'object': return { encoding: typeof options['encoding'] !== 'undefined' ? options['encoding'] : defEnc, flag: typeof options['flag'] !== 'undefined' ? options['flag'] : defFlag, mode: normalizeMode(options['mode'], defMode!) }; case 'string': return { encoding: options, flag: defFlag, mode: defMode! }; case 'null': case 'undefined': case 'function': return { encoding: defEnc!, flag: defFlag, mode: defMode! }; default: throw new TypeError(`"options" must be a string or an object, got ${typeof options} instead.`); } } /** * The default callback is a NOP. * @hidden * @private */ function nopCb() { // NOP. } /** * The node frontend to all filesystems. * This layer handles: * * * Sanity checking inputs. * * Normalizing paths. * * Resetting stack depth for asynchronous operations which may not go through * the browser by wrapping all input callbacks using `setImmediate`. * * Performing the requested operation through the filesystem or the file * descriptor, as appropriate. * * Handling optional arguments and setting default arguments. * @see http://nodejs.org/api/fs.html */ export default class FS { /* tslint:disable:variable-name */ // Exported fs.Stats. public static Stats = Stats; /* tslint:enable:variable-name */ public F_OK: number = 0; public R_OK: number = 4; public W_OK: number = 2; public X_OK: number = 1; private root: FileSystem | null = null; private fdMap: {[fd: number]: File} = {}; private nextFd = 100; public initialize(rootFS: FileSystem): FileSystem { if (!(<any> rootFS).constructor.isAvailable()) { throw new ApiError(ErrorCode.EINVAL, 'Tried to instantiate BrowserFS with an unavailable file system.'); } return this.root = rootFS; } /** * converts Date or number to a fractional UNIX timestamp * Grabbed from NodeJS sources (lib/fs.js) */ public _toUnixTimestamp(time: Date | number): number { if (typeof time === 'number') { return time; } else if (time instanceof Date) { return time.getTime() / 1000; } throw new Error("Cannot parse time: " + time); } /** * **NONSTANDARD**: Grab the FileSystem instance that backs this API. * @return [BrowserFS.FileSystem | null] Returns null if the file system has * not been initialized. */ public getRootFS(): FileSystem | null { if (this.root) { return this.root; } else { return null; } } // FILE OR DIRECTORY METHODS /** * Asynchronous rename. No arguments other than a possible exception are given * to the completion callback. * @param oldPath * @param newPath * @param callback */ public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { assertRoot(this.root).rename(normalizePath(oldPath), normalizePath(newPath), newCb); } catch (e) { newCb(e); } } /** * Synchronous rename. * @param oldPath * @param newPath */ public renameSync(oldPath: string, newPath: string): void { assertRoot(this.root).renameSync(normalizePath(oldPath), normalizePath(newPath)); } /** * Test whether or not the given path exists by checking with the file system. * Then call the callback argument with either true or false. * @example Sample invocation * fs.exists('/etc/passwd', function (exists) { * util.debug(exists ? "it's there" : "no passwd!"); * }); * @param path * @param callback */ public exists(path: string, cb: (exists: boolean) => any = nopCb): void { const newCb = wrapCb(cb, 1); try { return assertRoot(this.root).exists(normalizePath(path), newCb); } catch (e) { // Doesn't return an error. If something bad happens, we assume it just // doesn't exist. return newCb(false); } } /** * Test whether or not the given path exists by checking with the file system. * @param path * @return [boolean] */ public existsSync(path: string): boolean { try { return assertRoot(this.root).existsSync(normalizePath(path)); } catch (e) { // Doesn't return an error. If something bad happens, we assume it just // doesn't exist. return false; } } /** * Asynchronous `stat`. * @param path * @param callback */ public stat(path: string, cb: BFSCallback<Stats> = nopCb): void { const newCb = wrapCb(cb, 2); try { return assertRoot(this.root).stat(normalizePath(path), false, newCb); } catch (e) { return newCb(e); } } /** * Synchronous `stat`. * @param path * @return [BrowserFS.node.fs.Stats] */ public statSync(path: string): Stats { return assertRoot(this.root).statSync(normalizePath(path), false); } /** * Asynchronous `lstat`. * `lstat()` is identical to `stat()`, except that if path is a symbolic link, * then the link itself is stat-ed, not the file that it refers to. * @param path * @param callback */ public lstat(path: string, cb: BFSCallback<Stats> = nopCb): void { const newCb = wrapCb(cb, 2); try { return assertRoot(this.root).stat(normalizePath(path), true, newCb); } catch (e) { return newCb(e); } } /** * Synchronous `lstat`. * `lstat()` is identical to `stat()`, except that if path is a symbolic link, * then the link itself is stat-ed, not the file that it refers to. * @param path * @return [BrowserFS.node.fs.Stats] */ public lstatSync(path: string): Stats { return assertRoot(this.root).statSync(normalizePath(path), true); } // FILE-ONLY METHODS /** * Asynchronous `truncate`. * @param path * @param len * @param callback */ public truncate(path: string, cb?: BFSOneArgCallback): void; public truncate(path: string, len: number, cb?: BFSOneArgCallback): void; public truncate(path: string, arg2: any = 0, cb: BFSOneArgCallback = nopCb): void { let len = 0; if (typeof arg2 === 'function') { cb = arg2; } else if (typeof arg2 === 'number') { len = arg2; } const newCb = wrapCb(cb, 1); try { if (len < 0) { throw new ApiError(ErrorCode.EINVAL); } return assertRoot(this.root).truncate(normalizePath(path), len, newCb); } catch (e) { return newCb(e); } } /** * Synchronous `truncate`. * @param path * @param len */ public truncateSync(path: string, len: number = 0): void { if (len < 0) { throw new ApiError(ErrorCode.EINVAL); } return assertRoot(this.root).truncateSync(normalizePath(path), len); } /** * Asynchronous `unlink`. * @param path * @param callback */ public unlink(path: string, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { return assertRoot(this.root).unlink(normalizePath(path), newCb); } catch (e) { return newCb(e); } } /** * Synchronous `unlink`. * @param path */ public unlinkSync(path: string): void { return assertRoot(this.root).unlinkSync(normalizePath(path)); } /** * Asynchronous file open. * Exclusive mode ensures that path is newly created. * * `flags` can be: * * * `'r'` - Open file for reading. An exception occurs if the file does not exist. * * `'r+'` - Open file for reading and writing. An exception occurs if the file does not exist. * * `'rs'` - Open file for reading in synchronous mode. Instructs the filesystem to not cache writes. * * `'rs+'` - Open file for reading and writing, and opens the file in synchronous mode. * * `'w'` - Open file for writing. The file is created (if it does not exist) or truncated (if it exists). * * `'wx'` - Like 'w' but opens the file in exclusive mode. * * `'w+'` - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). * * `'wx+'` - Like 'w+' but opens the file in exclusive mode. * * `'a'` - Open file for appending. The file is created if it does not exist. * * `'ax'` - Like 'a' but opens the file in exclusive mode. * * `'a+'` - Open file for reading and appending. The file is created if it does not exist. * * `'ax+'` - Like 'a+' but opens the file in exclusive mode. * * @see http://www.manpagez.com/man/2/open/ * @param path * @param flags * @param mode defaults to `0644` * @param callback */ public open(path: string, flag: string, cb?: BFSCallback<number>): void; public open(path: string, flag: string, mode: number|string, cb?: BFSCallback<number>): void; public open(path: string, flag: string, arg2?: any, cb: BFSCallback<number> = nopCb): void { const mode = normalizeMode(arg2, 0x1a4); cb = typeof arg2 === 'function' ? arg2 : cb; const newCb = wrapCb(cb, 2); try { assertRoot(this.root).open(normalizePath(path), FileFlag.getFileFlag(flag), mode, (e: ApiError, file?: File) => { if (file) { newCb(e, this.getFdForFile(file)); } else { newCb(e); } }); } catch (e) { newCb(e); } } /** * Synchronous file open. * @see http://www.manpagez.com/man/2/open/ * @param path * @param flags * @param mode defaults to `0644` * @return [BrowserFS.File] */ public openSync(path: string, flag: string, mode: number|string = 0x1a4): number { return this.getFdForFile( assertRoot(this.root).openSync(normalizePath(path), FileFlag.getFileFlag(flag), normalizeMode(mode, 0x1a4))); } /** * Asynchronously reads the entire contents of a file. * @example Usage example * fs.readFile('/etc/passwd', function (err, data) { * if (err) throw err; * console.log(data); * }); * @param filename * @param options * @option options [String] encoding The string encoding for the file contents. Defaults to `null`. * @option options [String] flag Defaults to `'r'`. * @param callback If no encoding is specified, then the raw buffer is returned. */ public readFile(filename: string, cb: BFSCallback<Buffer>): void; public readFile(filename: string, options: { flag?: string; }, callback?: BFSCallback<Buffer>): void; public readFile(filename: string, options: { encoding: string; flag?: string; }, callback?: BFSCallback<string>): void; public readFile(filename: string, encoding: string, cb: BFSCallback<string>): void; public readFile(filename: string, arg2: any = {}, cb: BFSCallback<any> = nopCb) { const options = normalizeOptions(arg2, null, 'r', null); cb = typeof arg2 === 'function' ? arg2 : cb; const newCb = wrapCb(cb, 2); try { const flag = FileFlag.getFileFlag(options['flag']); if (!flag.isReadable()) { return newCb(new ApiError(ErrorCode.EINVAL, 'Flag passed to readFile must allow for reading.')); } return assertRoot(this.root).readFile(normalizePath(filename), options.encoding, flag, newCb); } catch (e) { return newCb(e); } } /** * Synchronously reads the entire contents of a file. * @param filename * @param options * @option options [String] encoding The string encoding for the file contents. Defaults to `null`. * @option options [String] flag Defaults to `'r'`. * @return [String | BrowserFS.node.Buffer] */ public readFileSync(filename: string, options?: { flag?: string; }): Buffer; public readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; public readFileSync(filename: string, encoding: string): string; public readFileSync(filename: string, arg2: any = {}): any { const options = normalizeOptions(arg2, null, 'r', null); const flag = FileFlag.getFileFlag(options.flag); if (!flag.isReadable()) { throw new ApiError(ErrorCode.EINVAL, 'Flag passed to readFile must allow for reading.'); } return assertRoot(this.root).readFileSync(normalizePath(filename), options.encoding, flag); } /** * Asynchronously writes data to a file, replacing the file if it already * exists. * * The encoding option is ignored if data is a buffer. * * @example Usage example * fs.writeFile('message.txt', 'Hello Node', function (err) { * if (err) throw err; * console.log('It\'s saved!'); * }); * @param filename * @param data * @param options * @option options [String] encoding Defaults to `'utf8'`. * @option options [Number] mode Defaults to `0644`. * @option options [String] flag Defaults to `'w'`. * @param callback */ public writeFile(filename: string, data: any, cb?: BFSOneArgCallback): void; public writeFile(filename: string, data: any, encoding?: string, cb?: BFSOneArgCallback): void; public writeFile(filename: string, data: any, options?: { encoding?: string; mode?: string | number; flag?: string; }, cb?: BFSOneArgCallback): void; public writeFile(filename: string, data: any, arg3: any = {}, cb: BFSOneArgCallback = nopCb): void { const options = normalizeOptions(arg3, 'utf8', 'w', 0x1a4); cb = typeof arg3 === 'function' ? arg3 : cb; const newCb = wrapCb(cb, 1); try { const flag = FileFlag.getFileFlag(options.flag); if (!flag.isWriteable()) { return newCb(new ApiError(ErrorCode.EINVAL, 'Flag passed to writeFile must allow for writing.')); } return assertRoot(this.root).writeFile(normalizePath(filename), data, options.encoding, flag, options.mode, newCb); } catch (e) { return newCb(e); } } /** * Synchronously writes data to a file, replacing the file if it already * exists. * * The encoding option is ignored if data is a buffer. * @param filename * @param data * @param options * @option options [String] encoding Defaults to `'utf8'`. * @option options [Number] mode Defaults to `0644`. * @option options [String] flag Defaults to `'w'`. */ public writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number | string; flag?: string; }): void; public writeFileSync(filename: string, data: any, encoding?: string): void; public writeFileSync(filename: string, data: any, arg3?: any): void { const options = normalizeOptions(arg3, 'utf8', 'w', 0x1a4); const flag = FileFlag.getFileFlag(options.flag); if (!flag.isWriteable()) { throw new ApiError(ErrorCode.EINVAL, 'Flag passed to writeFile must allow for writing.'); } return assertRoot(this.root).writeFileSync(normalizePath(filename), data, options.encoding, flag, options.mode); } /** * Asynchronously append data to a file, creating the file if it not yet * exists. * * @example Usage example * fs.appendFile('message.txt', 'data to append', function (err) { * if (err) throw err; * console.log('The "data to append" was appended to file!'); * }); * @param filename * @param data * @param options * @option options [String] encoding Defaults to `'utf8'`. * @option options [Number] mode Defaults to `0644`. * @option options [String] flag Defaults to `'a'`. * @param callback */ public appendFile(filename: string, data: any, cb?: BFSOneArgCallback): void; public appendFile(filename: string, data: any, options?: { encoding?: string; mode?: number|string; flag?: string; }, cb?: BFSOneArgCallback): void; public appendFile(filename: string, data: any, encoding?: string, cb?: BFSOneArgCallback): void; public appendFile(filename: string, data: any, arg3?: any, cb: BFSOneArgCallback = nopCb): void { const options = normalizeOptions(arg3, 'utf8', 'a', 0x1a4); cb = typeof arg3 === 'function' ? arg3 : cb; const newCb = wrapCb(cb, 1); try { const flag = FileFlag.getFileFlag(options.flag); if (!flag.isAppendable()) { return newCb(new ApiError(ErrorCode.EINVAL, 'Flag passed to appendFile must allow for appending.')); } assertRoot(this.root).appendFile(normalizePath(filename), data, options.encoding, flag, options.mode, newCb); } catch (e) { newCb(e); } } /** * Asynchronously append data to a file, creating the file if it not yet * exists. * * @example Usage example * fs.appendFile('message.txt', 'data to append', function (err) { * if (err) throw err; * console.log('The "data to append" was appended to file!'); * }); * @param filename * @param data * @param options * @option options [String] encoding Defaults to `'utf8'`. * @option options [Number] mode Defaults to `0644`. * @option options [String] flag Defaults to `'a'`. */ public appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number | string; flag?: string; }): void; public appendFileSync(filename: string, data: any, encoding?: string): void; public appendFileSync(filename: string, data: any, arg3?: any): void { const options = normalizeOptions(arg3, 'utf8', 'a', 0x1a4); const flag = FileFlag.getFileFlag(options.flag); if (!flag.isAppendable()) { throw new ApiError(ErrorCode.EINVAL, 'Flag passed to appendFile must allow for appending.'); } return assertRoot(this.root).appendFileSync(normalizePath(filename), data, options.encoding, flag, options.mode); } // FILE DESCRIPTOR METHODS /** * Asynchronous `fstat`. * `fstat()` is identical to `stat()`, except that the file to be stat-ed is * specified by the file descriptor `fd`. * @param fd * @param callback */ public fstat(fd: number, cb: BFSCallback<Stats> = nopCb): void { const newCb = wrapCb(cb, 2); try { const file = this.fd2file(fd); file.stat(newCb); } catch (e) { newCb(e); } } /** * Synchronous `fstat`. * `fstat()` is identical to `stat()`, except that the file to be stat-ed is * specified by the file descriptor `fd`. * @param fd * @return [BrowserFS.node.fs.Stats] */ public fstatSync(fd: number): Stats { return this.fd2file(fd).statSync(); } /** * Asynchronous close. * @param fd * @param callback */ public close(fd: number, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { this.fd2file(fd).close((e: ApiError) => { if (!e) { this.closeFd(fd); } newCb(e); }); } catch (e) { newCb(e); } } /** * Synchronous close. * @param fd */ public closeSync(fd: number): void { this.fd2file(fd).closeSync(); this.closeFd(fd); } /** * Asynchronous ftruncate. * @param fd * @param len * @param callback */ public ftruncate(fd: number, cb?: BFSOneArgCallback): void; public ftruncate(fd: number, len?: number, cb?: BFSOneArgCallback): void; public ftruncate(fd: number, arg2?: any, cb: BFSOneArgCallback = nopCb): void { const length = typeof arg2 === 'number' ? arg2 : 0; cb = typeof arg2 === 'function' ? arg2 : cb; const newCb = wrapCb(cb, 1); try { const file = this.fd2file(fd); if (length < 0) { throw new ApiError(ErrorCode.EINVAL); } file.truncate(length, newCb); } catch (e) { newCb(e); } } /** * Synchronous ftruncate. * @param fd * @param len */ public ftruncateSync(fd: number, len: number = 0): void { const file = this.fd2file(fd); if (len < 0) { throw new ApiError(ErrorCode.EINVAL); } file.truncateSync(len); } /** * Asynchronous fsync. * @param fd * @param callback */ public fsync(fd: number, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { this.fd2file(fd).sync(newCb); } catch (e) { newCb(e); } } /** * Synchronous fsync. * @param fd */ public fsyncSync(fd: number): void { this.fd2file(fd).syncSync(); } /** * Asynchronous fdatasync. * @param fd * @param callback */ public fdatasync(fd: number, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { this.fd2file(fd).datasync(newCb); } catch (e) { newCb(e); } } /** * Synchronous fdatasync. * @param fd */ public fdatasyncSync(fd: number): void { this.fd2file(fd).datasyncSync(); } /** * Write buffer to the file specified by `fd`. * Note that it is unsafe to use fs.write multiple times on the same file * without waiting for the callback. * @param fd * @param buffer Buffer containing the data to write to * the file. * @param offset Offset in the buffer to start reading data from. * @param length The amount of bytes to write to the file. * @param position Offset from the beginning of the file where this * data should be written. If position is null, the data will be written at * the current position. * @param callback The number specifies the number of bytes written into the file. */ public write(fd: number, buffer: Buffer, offset: number, length: number, cb?: BFSThreeArgCallback<number, Buffer>): void; public write(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, cb?: BFSThreeArgCallback<number, Buffer>): void; public write(fd: number, data: any, cb?: BFSThreeArgCallback<number, string>): void; public write(fd: number, data: any, position: number | null, cb?: BFSThreeArgCallback<number, string>): void; public write(fd: number, data: any, position: number | null, encoding: string, cb?: BFSThreeArgCallback<number, string>): void; public write(fd: number, arg2: any, arg3?: any, arg4?: any, arg5?: any, cb: BFSThreeArgCallback<number, any> = nopCb): void { let buffer: Buffer, offset: number, length: number, position: number | null = null; if (typeof arg2 === 'string') { // Signature 1: (fd, string, [position?, [encoding?]], cb?) let encoding = 'utf8'; switch (typeof arg3) { case 'function': // (fd, string, cb) cb = arg3; break; case 'number': // (fd, string, position, encoding?, cb?) position = arg3; encoding = typeof arg4 === 'string' ? arg4 : 'utf8'; cb = typeof arg5 === 'function' ? arg5 : cb; break; default: // ...try to find the callback and get out of here! cb = typeof arg4 === 'function' ? arg4 : typeof arg5 === 'function' ? arg5 : cb; return cb(new ApiError(ErrorCode.EINVAL, 'Invalid arguments.')); } buffer = Buffer.from(arg2, encoding); offset = 0; length = buffer.length; } else { // Signature 2: (fd, buffer, offset, length, position?, cb?) buffer = arg2; offset = arg3; length = arg4; position = typeof arg5 === 'number' ? arg5 : null; cb = typeof arg5 === 'function' ? arg5 : cb; } const newCb = wrapCb(cb, 3); try { const file = this.fd2file(fd); if (position === undefined || position === null) { position = file.getPos()!; } file.write(buffer, offset, length, position, newCb); } catch (e) { newCb(e); } } /** * Write buffer to the file specified by `fd`. * Note that it is unsafe to use fs.write multiple times on the same file * without waiting for it to return. * @param fd * @param buffer Buffer containing the data to write to * the file. * @param offset Offset in the buffer to start reading data from. * @param length The amount of bytes to write to the file. * @param position Offset from the beginning of the file where this * data should be written. If position is null, the data will be written at * the current position. */ public writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): number; public writeSync(fd: number, data: string, position?: number | null, encoding?: string): number; public writeSync(fd: number, arg2: any, arg3?: any, arg4?: any, arg5?: any): number { let buffer: Buffer, offset: number = 0, length: number, position: number | null; if (typeof arg2 === 'string') { // Signature 1: (fd, string, [position?, [encoding?]]) position = typeof arg3 === 'number' ? arg3 : null; const encoding = typeof arg4 === 'string' ? arg4 : 'utf8'; offset = 0; buffer = Buffer.from(arg2, encoding); length = buffer.length; } else { // Signature 2: (fd, buffer, offset, length, position?) buffer = arg2; offset = arg3; length = arg4; position = typeof arg5 === 'number' ? arg5 : null; } const file = this.fd2file(fd); if (position === undefined || position === null) { position = file.getPos()!; } return file.writeSync(buffer, offset, length, position); } /** * Read data from the file specified by `fd`. * @param buffer The buffer that the data will be * written to. * @param offset The offset within the buffer where writing will * start. * @param length An integer specifying the number of bytes to read. * @param position An integer specifying where to begin reading from * in the file. If position is null, data will be read from the current file * position. * @param callback The number is the number of bytes read */ public read(fd: number, length: number, position: number | null, encoding: string, cb?: BFSThreeArgCallback<string, number>): void; public read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, cb?: BFSThreeArgCallback<number, Buffer>): void; public read(fd: number, arg2: any, arg3: any, arg4: any, arg5?: any, cb: BFSThreeArgCallback<string, number> | BFSThreeArgCallback<number, Buffer> = nopCb): void { let position: number | null, offset: number, length: number, buffer: Buffer, newCb: BFSThreeArgCallback<number, Buffer>; if (typeof arg2 === 'number') { // legacy interface // (fd, length, position, encoding, callback) length = arg2; position = arg3; const encoding = arg4; cb = typeof arg5 === 'function' ? arg5 : cb; offset = 0; buffer = Buffer.alloc(length); // XXX: Inefficient. // Wrap the cb so we shelter upper layers of the API from these // shenanigans. newCb = wrapCb((err?: ApiError | null, bytesRead?: number, buf?: Buffer) => { if (err) { return (<Function> cb)(err); } (<BFSThreeArgCallback<string, number>> cb)(err, buf!.toString(encoding), bytesRead!); }, 3); } else { buffer = arg2; offset = arg3; length = arg4; position = arg5; newCb = wrapCb(<BFSThreeArgCallback<number, Buffer>> cb, 3); } try { const file = this.fd2file(fd); if (position === undefined || position === null) { position = file.getPos()!; } file.read(buffer, offset, length, position, newCb); } catch (e) { newCb(e); } } /** * Read data from the file specified by `fd`. * @param fd * @param buffer The buffer that the data will be * written to. * @param offset The offset within the buffer where writing will * start. * @param length An integer specifying the number of bytes to read. * @param position An integer specifying where to begin reading from * in the file. If position is null, data will be read from the current file * position. * @return [Number] */ public readSync(fd: number, length: number, position: number, encoding: string): string; public readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; public readSync(fd: number, arg2: any, arg3: any, arg4: any, arg5?: any): any { let shenanigans = false; let buffer: Buffer, offset: number, length: number, position: number, encoding: string = 'utf8'; if (typeof arg2 === 'number') { length = arg2; position = arg3; encoding = arg4; offset = 0; buffer = Buffer.alloc(length); shenanigans = true; } else { buffer = arg2; offset = arg3; length = arg4; position = arg5; } const file = this.fd2file(fd); if (position === undefined || position === null) { position = file.getPos()!; } const rv = file.readSync(buffer, offset, length, position); if (!shenanigans) { return rv; } else { return [buffer.toString(encoding), rv]; } } /** * Asynchronous `fchown`. * @param fd * @param uid * @param gid * @param callback */ public fchown(fd: number, uid: number, gid: number, callback: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(callback, 1); try { this.fd2file(fd).chown(uid, gid, newCb); } catch (e) { newCb(e); } } /** * Synchronous `fchown`. * @param fd * @param uid * @param gid */ public fchownSync(fd: number, uid: number, gid: number): void { this.fd2file(fd).chownSync(uid, gid); } /** * Asynchronous `fchmod`. * @param fd * @param mode * @param callback */ public fchmod(fd: number, mode: string | number, cb: BFSOneArgCallback): void { const newCb = wrapCb(cb, 1); try { const numMode = typeof mode === 'string' ? parseInt(mode, 8) : mode; this.fd2file(fd).chmod(numMode, newCb); } catch (e) { newCb(e); } } /** * Synchronous `fchmod`. * @param fd * @param mode */ public fchmodSync(fd: number, mode: number | string): void { const numMode = typeof mode === 'string' ? parseInt(mode, 8) : mode; this.fd2file(fd).chmodSync(numMode); } /** * Change the file timestamps of a file referenced by the supplied file * descriptor. * @param fd * @param atime * @param mtime * @param callback */ public futimes(fd: number, atime: number | Date, mtime: number | Date, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { const file = this.fd2file(fd); if (typeof atime === 'number') { atime = new Date(atime * 1000); } if (typeof mtime === 'number') { mtime = new Date(mtime * 1000); } file.utimes(atime, mtime, newCb); } catch (e) { newCb(e); } } /** * Change the file timestamps of a file referenced by the supplied file * descriptor. * @param fd * @param atime * @param mtime */ public futimesSync(fd: number, atime: number | Date, mtime: number | Date): void { this.fd2file(fd).utimesSync(normalizeTime(atime), normalizeTime(mtime)); } // DIRECTORY-ONLY METHODS /** * Asynchronous `rmdir`. * @param path * @param callback */ public rmdir(path: string, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { path = normalizePath(path); assertRoot(this.root).rmdir(path, newCb); } catch (e) { newCb(e); } } /** * Synchronous `rmdir`. * @param path */ public rmdirSync(path: string): void { path = normalizePath(path); return assertRoot(this.root).rmdirSync(path); } /** * Asynchronous `mkdir`. * @param path * @param mode defaults to `0777` * @param callback */ public mkdir(path: string, mode?: any, cb: BFSOneArgCallback = nopCb): void { if (typeof mode === 'function') { cb = mode; mode = 0x1ff; } const newCb = wrapCb(cb, 1); try { path = normalizePath(path); assertRoot(this.root).mkdir(path, mode, newCb); } catch (e) { newCb(e); } } /** * Synchronous `mkdir`. * @param path * @param mode defaults to `0777` */ public mkdirSync(path: string, mode?: number | string): void { assertRoot(this.root).mkdirSync(normalizePath(path), normalizeMode(mode, 0x1ff)); } /** * Asynchronous `readdir`. Reads the contents of a directory. * The callback gets two arguments `(err, files)` where `files` is an array of * the names of the files in the directory excluding `'.'` and `'..'`. * @param path * @param callback */ public readdir(path: string, cb: BFSCallback<string[]> = nopCb): void { const newCb = <(err: ApiError, files?: string[]) => void> wrapCb(cb, 2); try { path = normalizePath(path); assertRoot(this.root).readdir(path, newCb); } catch (e) { newCb(e); } } /** * Synchronous `readdir`. Reads the contents of a directory. * @param path * @return [String[]] */ public readdirSync(path: string): string[] { path = normalizePath(path); return assertRoot(this.root).readdirSync(path); } // SYMLINK METHODS /** * Asynchronous `link`. * @param srcpath * @param dstpath * @param callback */ public link(srcpath: string, dstpath: string, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { srcpath = normalizePath(srcpath); dstpath = normalizePath(dstpath); assertRoot(this.root).link(srcpath, dstpath, newCb); } catch (e) { newCb(e); } } /** * Synchronous `link`. * @param srcpath * @param dstpath */ public linkSync(srcpath: string, dstpath: string): void { srcpath = normalizePath(srcpath); dstpath = normalizePath(dstpath); return assertRoot(this.root).linkSync(srcpath, dstpath); } /** * Asynchronous `symlink`. * @param srcpath * @param dstpath * @param type can be either `'dir'` or `'file'` (default is `'file'`) * @param callback */ public symlink(srcpath: string, dstpath: string, cb?: BFSOneArgCallback): void; public symlink(srcpath: string, dstpath: string, type?: string, cb?: BFSOneArgCallback): void; public symlink(srcpath: string, dstpath: string, arg3?: any, cb: BFSOneArgCallback = nopCb): void { const type = typeof arg3 === 'string' ? arg3 : 'file'; cb = typeof arg3 === 'function' ? arg3 : cb; const newCb = wrapCb(cb, 1); try { if (type !== 'file' && type !== 'dir') { return newCb(new ApiError(ErrorCode.EINVAL, "Invalid type: " + type)); } srcpath = normalizePath(srcpath); dstpath = normalizePath(dstpath); assertRoot(this.root).symlink(srcpath, dstpath, type, newCb); } catch (e) { newCb(e); } } /** * Synchronous `symlink`. * @param srcpath * @param dstpath * @param type can be either `'dir'` or `'file'` (default is `'file'`) */ public symlinkSync(srcpath: string, dstpath: string, type?: string): void { if (!type) { type = 'file'; } else if (type !== 'file' && type !== 'dir') { throw new ApiError(ErrorCode.EINVAL, "Invalid type: " + type); } srcpath = normalizePath(srcpath); dstpath = normalizePath(dstpath); return assertRoot(this.root).symlinkSync(srcpath, dstpath, type); } /** * Asynchronous readlink. * @param path * @param callback */ public readlink(path: string, cb: BFSCallback<string> = nopCb): void { const newCb = wrapCb(cb, 2); try { path = normalizePath(path); assertRoot(this.root).readlink(path, newCb); } catch (e) { newCb(e); } } /** * Synchronous readlink. * @param path * @return [String] */ public readlinkSync(path: string): string { path = normalizePath(path); return assertRoot(this.root).readlinkSync(path); } // PROPERTY OPERATIONS /** * Asynchronous `chown`. * @param path * @param uid * @param gid * @param callback */ public chown(path: string, uid: number, gid: number, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { path = normalizePath(path); assertRoot(this.root).chown(path, false, uid, gid, newCb); } catch (e) { newCb(e); } } /** * Synchronous `chown`. * @param path * @param uid * @param gid */ public chownSync(path: string, uid: number, gid: number): void { path = normalizePath(path); assertRoot(this.root).chownSync(path, false, uid, gid); } /** * Asynchronous `lchown`. * @param path * @param uid * @param gid * @param callback */ public lchown(path: string, uid: number, gid: number, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { path = normalizePath(path); assertRoot(this.root).chown(path, true, uid, gid, newCb); } catch (e) { newCb(e); } } /** * Synchronous `lchown`. * @param path * @param uid * @param gid */ public lchownSync(path: string, uid: number, gid: number): void { path = normalizePath(path); assertRoot(this.root).chownSync(path, true, uid, gid); } /** * Asynchronous `chmod`. * @param path * @param mode * @param callback */ public chmod(path: string, mode: number | string, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { const numMode = normalizeMode(mode, -1); if (numMode < 0) { throw new ApiError(ErrorCode.EINVAL, `Invalid mode.`); } assertRoot(this.root).chmod(normalizePath(path), false, numMode, newCb); } catch (e) { newCb(e); } } /** * Synchronous `chmod`. * @param path * @param mode */ public chmodSync(path: string, mode: string | number): void { const numMode = normalizeMode(mode, -1); if (numMode < 0) { throw new ApiError(ErrorCode.EINVAL, `Invalid mode.`); } path = normalizePath(path); assertRoot(this.root).chmodSync(path, false, numMode); } /** * Asynchronous `lchmod`. * @param path * @param mode * @param callback */ public lchmod(path: string, mode: number | string, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { const numMode = normalizeMode(mode, -1); if (numMode < 0) { throw new ApiError(ErrorCode.EINVAL, `Invalid mode.`); } assertRoot(this.root).chmod(normalizePath(path), true, numMode, newCb); } catch (e) { newCb(e); } } /** * Synchronous `lchmod`. * @param path * @param mode */ public lchmodSync(path: string, mode: number | string): void { const numMode = normalizeMode(mode, -1); if (numMode < 1) { throw new ApiError(ErrorCode.EINVAL, `Invalid mode.`); } assertRoot(this.root).chmodSync(normalizePath(path), true, numMode); } /** * Change file timestamps of the file referenced by the supplied path. * @param path * @param atime * @param mtime * @param callback */ public utimes(path: string, atime: number | Date, mtime: number | Date, cb: BFSOneArgCallback = nopCb): void { const newCb = wrapCb(cb, 1); try { assertRoot(this.root).utimes(normalizePath(path), normalizeTime(atime), normalizeTime(mtime), newCb); } catch (e) { newCb(e); } } /** * Change file timestamps of the file referenced by the supplied path. * @param path * @param atime * @param mtime */ public utimesSync(path: string, atime: number | Date, mtime: number | Date): void { assertRoot(this.root).utimesSync(normalizePath(path), normalizeTime(atime), normalizeTime(mtime)); } /** * Asynchronous `realpath`. The callback gets two arguments * `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. * * @example Usage example * let cache = {'/etc':'/private/etc'}; * fs.realpath('/etc/passwd', cache, function (err, resolvedPath) { * if (err) throw err; * console.log(resolvedPath); * }); * * @param path * @param cache An object literal of mapped paths that can be used to * force a specific path resolution or avoid additional `fs.stat` calls for * known real paths. * @param callback */ public realpath(path: string, cb?: BFSCallback<string>): void; public realpath(path: string, cache: {[path: string]: string}, cb: BFSCallback<string>): void; public realpath(path: string, arg2?: any, cb: BFSCallback<string> = nopCb): void { const cache = typeof(arg2) === 'object' ? arg2 : {}; cb = typeof(arg2) === 'function' ? arg2 : nopCb; const newCb = <(err: ApiError, resolvedPath?: string) => any> wrapCb(cb, 2); try { path = normalizePath(path); assertRoot(this.root).realpath(path, cache, newCb); } catch (e) { newCb(e); } } /** * Synchronous `realpath`. * @param path * @param cache An object literal of mapped paths that can be used to * force a specific path resolution or avoid additional `fs.stat` calls for * known real paths. * @return [String] */ public realpathSync(path: string, cache: {[path: string]: string} = {}): string { path = normalizePath(path); return assertRoot(this.root).realpathSync(path, cache); } public watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; public watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; public watchFile(filename: string, arg2: any, listener: (curr: Stats, prev: Stats) => void = nopCb): void { throw new ApiError(ErrorCode.ENOTSUP); } public unwatchFile(filename: string, listener: (curr: Stats, prev: Stats) => void = nopCb): void { throw new ApiError(ErrorCode.ENOTSUP); } public watch(filename: string, listener?: (event: string, filename: string) => any): _fs.FSWatcher; public watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): _fs.FSWatcher; public watch(filename: string, arg2: any, listener: (event: string, filename: string) => any = nopCb): _fs.FSWatcher { throw new ApiError(ErrorCode.ENOTSUP); } public access(path: string, callback: (err: ApiError) => void): void; public access(path: string, mode: number, callback: (err: ApiError) => void): void; public access(path: string, arg2: any, cb: (e: ApiError) => void = nopCb): void { throw new ApiError(ErrorCode.ENOTSUP); } public accessSync(path: string, mode?: number): void { throw new ApiError(ErrorCode.ENOTSUP); } public createReadStream(path: string, options?: { flags?: string; encoding?: string; fd?: number; mode?: number; autoClose?: boolean; }): _fs.ReadStream { throw new ApiError(ErrorCode.ENOTSUP); } public createWriteStream(path: string, options?: { flags?: string; encoding?: string; fd?: number; mode?: number; }): _fs.WriteStream { throw new ApiError(ErrorCode.ENOTSUP); } /** * For unit testing. Passes all incoming callbacks to cbWrapper for wrapping. */ public wrapCallbacks(cbWrapper: (cb: Function, args: number) => Function) { wrapCbHook = <any> cbWrapper; } private getFdForFile(file: File): number { const fd = this.nextFd++; this.fdMap[fd] = file; return fd; } private fd2file(fd: number): File { const rv = this.fdMap[fd]; if (rv) { return rv; } else { throw new ApiError(ErrorCode.EBADF, 'Invalid file descriptor.'); } } private closeFd(fd: number): void { delete this.fdMap[fd]; } } export interface FSModule extends FS { /** * The FS constructor. */ FS: typeof FS; /** * The FS.Stats constructor. */ Stats: typeof Stats; /** * Retrieve the FS object backing the fs module. */ getFSModule(): FS; /** * Set the FS object backing the fs module. */ changeFSModule(newFs: FS): void; }
the_stack
import * as vscode from 'vscode'; import {Substitution, UglyRevelation, LanguageEntry, PrettyCursor, PrettyStyleProperties, PrettyStyle, assignStyleProperties, HideTextMethod} from './configuration'; import {RangeSet} from './RangeSet'; import {DisjointRangeSet} from './DisjointRangeSet'; import * as drangeset from './DisjointRangeSet'; import * as textUtil from './text-util'; import * as tm from './text-mate'; import {MatchResult, iterateMatches, iterateMatchArray, mapIterator} from './regexp-iteration'; import * as decorations from './decorations'; const debugging = false; const activeEditorDecorationTimeout = 20; const inactiveEditorDecorationTimeout = 200; interface PrettySubstitution { ugly: RegExp, pretty: string, decorationType: vscode.TextEditorDecorationType, ranges: DisjointRangeSet, index: number, scope?: string, } export interface DocumentModel { getText: (r: vscode.Range) => string; getLine: (line: number) => string; getLineRange: (line: number) => vscode.Range; getLineCount: () => number; validateRange: (r: vscode.Range) => vscode.Range; } export interface UpdateDecorationEntry { decoration: vscode.TextEditorDecorationType, ranges: vscode.Range[], } export interface UpdateDecorationInstanceEntry { decoration: vscode.DecorationInstanceRenderOptions, ranges: DisjointRangeSet, } export class PrettyModel implements vscode.Disposable { private prettyDecorations : {scoped: PrettySubstitution[], unscoped: PrettySubstitution[]} = {scoped: [], unscoped: []}; /** matches all of the target substitutions that ignore grammar scopes */ private uglyUnscoped = new RegExp("","g"); /** condictional ranges: tracks ranges where any edit within the range should cause the entire range to be reparsed */ private conditionalRanges = new RangeSet(); /** ranges of hidden text */ private uglyDecorationRanges = new DisjointRangeSet(); // /** ranges of non-hidden, styled text */ // private styledDecorationRanges = new DisjointRangeSet(); /** things to dispose of at the end */ private subscriptions : vscode.Disposable[] = []; private changedUglies = false; // flag used to determine if the uglies have been updated // hides a "ugly" decorations private uglyDecoration: vscode.TextEditorDecorationType = null; // reveals the "ugly" decorations; is applied on top of uglyDecoration and should take priority private revealedUglyDecoration: vscode.TextEditorDecorationType = null; // draws a box around a pretty symbol private boxedSymbolDecoration: vscode.DecorationInstanceRenderOptions = null; // Stores the state for each line private grammarState : tm.StackElement[] = []; private grammar : null|tm.IGrammar = null; public constructor(doc: DocumentModel, settings: LanguageEntry, options: {hideTextMethod: HideTextMethod, textMateGrammar?: tm.IGrammar|null}, private document = doc, private revealStrategy = settings.revealOn, private prettyCursor = settings.prettyCursor, private hideTextMethod = options.hideTextMethod, private combineIdenticalScopes = settings.combineIdenticalScopes, ) { this.grammar = options.textMateGrammar || null; this.loadDecorations(settings.substitutions); // Parse whole document const docRange = new vscode.Range(0,0,this.document.getLineCount(),0); this.reparsePretties(docRange); } public dispose() { this.unloadDecorations(); this.debugDecorations.forEach((val) => val.dec.dispose()); this.subscriptions.forEach((s) => s.dispose()); } public getDecorationsList() : UpdateDecorationEntry[] { const decs : UpdateDecorationEntry[] = []; if(this.uglyDecoration) decs.push({decoration: this.uglyDecoration, ranges: this.uglyDecorationRanges.getRanges()}); for(const subst of this.prettyDecorations.unscoped) decs.push({decoration: subst.decorationType, ranges: subst.ranges.getRanges()}); for(const subst of this.prettyDecorations.scoped) decs.push({decoration: subst.decorationType, ranges: subst.ranges.getRanges()}); if(debugging) this.debugDecorations.forEach((val) => decs.push({decoration: val.dec, ranges: val.ranges})); return decs; } private unloadDecorations() { if(this.uglyDecoration) this.uglyDecoration.dispose(); if(this.revealedUglyDecoration) this.revealedUglyDecoration.dispose(); this.conditionalRanges = new RangeSet(); this.uglyDecorationRanges = new DisjointRangeSet(); // this.styledDecorationRanges = new DisjointRangeSet(); for(const subst of this.prettyDecorations.unscoped) subst.ranges = new DisjointRangeSet(); for(const subst of this.prettyDecorations.scoped) subst.ranges = new DisjointRangeSet(); this.debugDecorations.forEach((val) => val.ranges = []); for(const oldDecoration of this.prettyDecorations.unscoped) oldDecoration.decorationType.dispose(); for(const oldDecoration of this.prettyDecorations.scoped) oldDecoration.decorationType.dispose(); } private regexpOptionalGroup(re: string) { if(re) return `(?:${re})`; else return ""; } private loadDecorations(prettySubstitutions: Substitution[]) { this.unloadDecorations(); let dec : {uglyDecoration: vscode.TextEditorDecorationType, revealedUglyDecoration: vscode.TextEditorDecorationType, boxedSymbolDecoration: vscode.DecorationInstanceRenderOptions} if(this.hideTextMethod === "hack-fontSize") dec = decorations.makeDecorations_fontSize_hack(); else if(this.hideTextMethod === "hack-letterSpacing") dec = decorations.makeDecorations_letterSpacing_hack(); else dec = decorations.makeDecorations_none(); this.uglyDecoration = dec.uglyDecoration; this.revealedUglyDecoration = dec.revealedUglyDecoration; this.boxedSymbolDecoration = dec.boxedSymbolDecoration; this.prettyDecorations.scoped = []; this.prettyDecorations.unscoped = []; const uglyAllUnscopedStrings = []; for(const prettySubst of prettySubstitutions) { const pre = (prettySubst.scope && prettySubst.pre===undefined) ? "^" : this.regexpOptionalGroup(prettySubst.pre); const post = (prettySubst.scope && prettySubst.post===undefined) ? "$" : this.regexpOptionalGroup(prettySubst.post); const uglyStr = pre + "(" + prettySubst.ugly + ")" + post; try { const re = new RegExp(uglyStr, "g"); if(re.test("")) { console.warn(`Substitution ignored because it matches the empty string: "${uglyStr}" --> "${prettySubst.pretty}"`); continue; } let decoration = undefined; if(!prettySubst.pretty) decoration = decorations.makePrettyDecoration_noPretty(prettySubst); else if(this.hideTextMethod === "hack-fontSize") decoration = decorations.makePrettyDecoration_fontSize_hack(prettySubst); else if(this.hideTextMethod === "hack-letterSpacing") decoration = decorations.makePrettyDecoration_letterSpacing_hack(prettySubst); else decoration = decorations.makePrettyDecoration_noHide(prettySubst); if(prettySubst.scope) { this.prettyDecorations.scoped.push({ ugly: re, pretty: prettySubst.pretty, ranges: new DisjointRangeSet(), decorationType: decoration, index: this.prettyDecorations.scoped.length, scope: prettySubst.scope, }); } else { this.prettyDecorations.unscoped.push({ ugly: re, pretty: prettySubst.pretty, ranges: new DisjointRangeSet(), decorationType: decoration, index: this.prettyDecorations.scoped.length, }); uglyAllUnscopedStrings.push(`(?:${uglyStr})`); } } catch(e) { console.warn(`Could not add rule "${uglyStr}" --> "${prettySubst.pretty}"; invalid regular expression`) } } this.uglyUnscoped = new RegExp(uglyAllUnscopedStrings.join('|'), 'g'); } // helper function to determine which ugly has been matched private getUglyFromMatch(match: RegExpExecArray, line: number) { const matches = match .map((value,idx) => ({index:idx,match:value})) .filter((value) => value.match !== undefined); if(matches.length <= 1) return undefined; const matchIdx = matches[matches.length-1].index; const matchStr = match[matchIdx]; const matchStart = match.index; const matchEnd = matchStart + match[0].length; const start = matchStart + match[0].indexOf(matchStr); const end = start + matchStr.length; const uglyRange = new vscode.Range(line,start,line,end); return {range: uglyRange, prettyIndex: matchIdx-1, lastIndex: end}; } private refreshTokensOnLine(line: string, lineNumber: number) : {tokens: tm.IToken[], invalidated: boolean} { if(!this.grammar) return {tokens: [], invalidated: false}; try { const prevState = this.grammarState[lineNumber-1] || null; const lineTokens = this.grammar.tokenizeLine(line, prevState); const invalidated = !this.grammarState[lineNumber] || !lineTokens.ruleStack.equals(this.grammarState[lineNumber]) this.grammarState[lineNumber] = lineTokens.ruleStack; return {tokens: lineTokens.tokens, invalidated: invalidated}; } catch (error) { return {tokens: [], invalidated: false}; } } /** Iterates over all the uglies that match within a scoped token * @returns an iterator; `next` accepts a new offset within the string to jump to */ private *iterateScopedUglies(line: string, tokens: tm.IToken[]) : IterableIterator<MatchResult> { let jumpOffset : number|undefined = undefined; nextToken: for(let tokenIdx = 0; tokenIdx < tokens.length; ++tokenIdx) { const token = tokens[tokenIdx]; if(token.startIndex < jumpOffset || token.endIndex===token.startIndex) continue nextToken; // advance to the next offset we're interested in const tokenStr = line.substring(token.startIndex,token.endIndex); let matchScopes = this.prettyDecorations.scoped .filter(s => tm.matchScope(s.scope, token.scopes)); let matchIter = iterateMatchArray(tokenStr, matchScopes.map(ms => ms.ugly)) let match = matchIter.next(); for(; !match.done; match = matchIter.next(jumpOffset!==undefined ? jumpOffset - token.startIndex : undefined)) { const newOffset = yield { start: token.startIndex + match.value.start, end: token.startIndex + match.value.end, matchStart: token.startIndex, matchEnd: token.endIndex, id: matchScopes[match.value.id].index}; if(typeof newOffset === 'number') { jumpOffset = newOffset; if(newOffset < token.startIndex) // start over and search for the correct token tokenIdx = -1; } } } } private *iterateUnscopedUglies(line: string) : IterableIterator<MatchResult> { yield *iterateMatches(line, this.uglyUnscoped); } private *iterateLineUglies(line: string, tokens: tm.IToken[]) : IterableIterator<MatchResult & {type: "scoped"|"unscoped"}> { type T = "scoped" | "unscoped"; let offset = 0; const tokensOld = tokens; if(this.combineIdenticalScopes) tokens = tm.combineIdenticalTokenScopes(tokens); const scopedUgliesIter = this.iterateScopedUglies(line, tokens); const unscopedUgliesIter = this.iterateUnscopedUglies(line); let matchScoped = scopedUgliesIter.next(); let matchUnscoped = unscopedUgliesIter.next(); while(!matchScoped.done && !matchUnscoped.done) { const s = matchScoped.value; const u = matchUnscoped.value; if(s.end <= u.start) {// process scoped; sctrictly first yield Object.assign(s, {type: "scoped" as T}); matchScoped = scopedUgliesIter.next(); } else if(u.end <= s.start) {// process unscoped; strictly first yield Object.assign(u, {type: "unscoped" as T}); matchUnscoped = unscopedUgliesIter.next(); } else {// overlap: consume the scoped ugly and discard the unscoped ugly yield Object.assign(s, {type: "scoped" as T}); matchScoped = scopedUgliesIter.next(); matchUnscoped = unscopedUgliesIter.next(s.end /* discard current match and start looking after the scoped match */); } } if(!matchScoped.done) yield *mapIterator(scopedUgliesIter, (x) => Object.assign(x, {type: "scoped" as T}), matchScoped) else if(!matchUnscoped.done) yield *mapIterator(unscopedUgliesIter, (x) => Object.assign(x, {type: "unscoped" as T}), matchUnscoped) } /** Reparses the given range; assumes that the range has already been cleared by `clearPretties` * Updates: * this.prettyDecorations.scoped[x].ranges -- adds new ranges for each pretty x encountered * this.prettyDecorations.unscoped[x].ranges -- adds new ranges for each pretty x encountered * this.uglyDecorationRanges -- all new uglies [to be hidden] are added * @returns the range that was acutally reparsed */ private reparsePretties(range: vscode.Range) : vscode.Range { range = this.document.validateRange(range); const startCharacter = 0; const newUglyRanges = new DisjointRangeSet(); const newStyledRanges = new DisjointRangeSet(); const newScopedRanges : DisjointRangeSet[] = []; const newUnscopedRanges : DisjointRangeSet[] = []; const newConditionalRanges = new RangeSet(); // initialize an empty range set for every id this.prettyDecorations.unscoped.forEach(() => newUnscopedRanges.push(new DisjointRangeSet())); this.prettyDecorations.scoped.forEach(() => newScopedRanges.push(new DisjointRangeSet())); let invalidatedTokenState = false; // Collect new pretties const lineCount = this.document.getLineCount(); let lineIdx; for(lineIdx = range.start.line; lineIdx <= range.end.line || (invalidatedTokenState && lineIdx < lineCount); ++lineIdx) { const line = this.document.getLine(lineIdx); const {tokens: tokens, invalidated: invalidated} = this.refreshTokensOnLine(line, lineIdx); invalidatedTokenState = invalidated; for(let ugly of this.iterateLineUglies(line, tokens)) { const uglyRange = new vscode.Range(lineIdx, ugly.start, lineIdx, ugly.end); newConditionalRanges.add(new vscode.Range(lineIdx, ugly.matchStart, lineIdx, ugly.matchEnd)); if(ugly.type === "scoped") { if(this.prettyDecorations.scoped[ugly.id].pretty) newUglyRanges.insert(uglyRange); else newStyledRanges.insert(uglyRange); newScopedRanges[ugly.id].insert(uglyRange); } else if(ugly.type === "unscoped") { if(this.prettyDecorations.unscoped[ugly.id].pretty) newUglyRanges.insert(uglyRange); else newStyledRanges.insert(uglyRange); newUnscopedRanges[ugly.id].insert(uglyRange); } } } if(lineIdx-1 > range.end.line) { // console.info('Aditional tokens reparsed: ' + (lineIdx-range.end.line) + ' lines'); range = range.with({end: range.end.with({line: lineIdx, character: 0})}); } // compute the total reparsed range // use this to clear any preexisting substitutions const newUglyTotalRange = newUglyRanges.getTotalRange(); const newStyledTotalRange = newStyledRanges.getTotalRange(); let hiddenOverlap = range.with({start:range.start.with({character: startCharacter})}); let styledOverlap = range.with({start:range.start.with({character: startCharacter})}); if(!newUglyTotalRange.isEmpty) hiddenOverlap = hiddenOverlap.union(newUglyRanges.getTotalRange()); if(!newStyledTotalRange.isEmpty) styledOverlap =styledOverlap.union(newStyledRanges.getTotalRange()); const overlap = hiddenOverlap.union(styledOverlap); this.conditionalRanges.removeOverlapping(overlap, {includeTouchingStart: false, includeTouchingEnd: false}); this.uglyDecorationRanges.removeOverlapping(hiddenOverlap); // this.styledDecorationRanges.removeOverlapping(styledOverlap); this.prettyDecorations.unscoped.forEach(r => r.ranges.removeOverlapping(overlap)); this.prettyDecorations.scoped.forEach(r => r.ranges.removeOverlapping(overlap)); // add the new pretties & ugly ducklings newConditionalRanges.getRanges().forEach(r => this.conditionalRanges.add(r)); this.uglyDecorationRanges.insertRanges(newUglyRanges); this.prettyDecorations.unscoped.forEach((pretty,idx) => pretty.ranges.insertRanges(newUnscopedRanges[idx])); this.prettyDecorations.scoped.forEach((pretty,idx) => { pretty.ranges.insertRanges(newScopedRanges[idx]) }); if(!newStyledRanges.isEmpty() || !newUglyRanges.isEmpty()) this.changedUglies = true; return hiddenOverlap.union(styledOverlap); } private debugDecorations : {dec:vscode.TextEditorDecorationType, ranges: vscode.Range[]}[] = [ {dec: vscode.window.createTextEditorDecorationType({textDecoration: 'line-through'}), ranges: []} // affected uglies , {dec: vscode.window.createTextEditorDecorationType({backgroundColor: 'yellow',}), ranges: []} // reparsed text , {dec: vscode.window.createTextEditorDecorationType({outlineColor: 'black', outlineStyle: 'solid', outlineWidth: '1pt'}), ranges: []} // editRange ]; /** * @returns true if the decorations were invalidated/updated */ public applyChanges(changes: {range: vscode.Range, text: string}[]) : boolean { // this.cachedLines = []; if(debugging) this.debugDecorations.forEach((val) => val.ranges = []); // const startTime = new Date().getTime(); this.changedUglies = false; // assume no changes need to be made for now const sortedChanges = changes.sort((change1,change2) => change1.range.start.isAfter(change2.range.start) ? -1 : 1) const adjustedReparseRanges = new RangeSet(); for(const change of sortedChanges) { try { const delta = textUtil.toRangeDelta(change.range, change.text); const editRange = textUtil.rangeDeltaNewRange(delta); adjustedReparseRanges.shiftDelta(delta); const reparseRanges = this.conditionalRanges.removeOverlapping(change.range,{includeTouchingStart:true,includeTouchingEnd:true}); this.conditionalRanges.shiftDelta(delta); const reparseRange = reparseRanges.length > 0 ? new vscode.Range(reparseRanges[0].start, reparseRanges[reparseRanges.length-1].end) : change.range; // note: take the union to make sure that each edit location is reparsed, even if there were no preeexisting uglies (i.e. allow searching for new uglies) adjustedReparseRanges.add(textUtil.rangeTranslate(reparseRange, delta).union(editRange)); const removed = this.uglyDecorationRanges.removeOverlapping(reparseRange,{includeTouchingStart:true,includeTouchingEnd:true}); const affected = this.uglyDecorationRanges.shiftRangeDelta(delta); if(removed.length > 0) this.changedUglies = true; for(const subst of this.prettyDecorations.unscoped) { subst.ranges.removeOverlapping(reparseRange,{includeTouchingStart:true,includeTouchingEnd:true}); subst.ranges.shiftRangeDelta(delta); } for(const subst of this.prettyDecorations.scoped) { subst.ranges.removeOverlapping(reparseRange,{includeTouchingStart:true,includeTouchingEnd:true}); subst.ranges.shiftRangeDelta(delta); } if(debugging) { this.debugDecorations[0].ranges.push(affected); this.debugDecorations[2].ranges.push(reparseRange); } } catch(e) { console.error(e); } } for(let range of adjustedReparseRanges.getRanges()) { const reparsed = this.reparsePretties(range); this.debugDecorations[1].ranges.push(reparsed); } // else if(debugging) // this.debugDecorations.forEach((val) => this.getEditors().forEach((e) => e.setDecorations(val.dec,val.ranges))); // this.refresh(); // const endTime = new Date().getTime(); // console.log(endTime - startTime + "ms") return this.changedUglies; } /** reparses the document and recreates the highlights for all editors */ public recomputeDecorations() { this.uglyDecorationRanges = new DisjointRangeSet(); this.grammarState = []; for(const subst of this.prettyDecorations.unscoped) subst.ranges = new DisjointRangeSet(); for(const subst of this.prettyDecorations.scoped) subst.ranges = new DisjointRangeSet(); this.debugDecorations.forEach((val) => val.ranges = []) const docRange = new vscode.Range(0,0,this.document.getLineCount(),0); this.reparsePretties(docRange); } private findSymbolAt(pos: vscode.Position, options: {excludeStart?: boolean, includeEnd?: boolean} = {excludeStart: false, includeEnd: false}) { return this.uglyDecorationRanges.find(pos,options); } private findSymbolsIn(range: vscode.Range) { return this.uglyDecorationRanges.getOverlap(range); } public getPrettySubstitutionsRanges() : vscode.Range[] { return this.uglyDecorationRanges.getRanges(); } /** * Returns what the contents of the document would appear to be after decorations (i.e. with substitutions applied to the text) */ public getDecoratedText(range : vscode.Range) : string { range = this.document.validateRange(range); const text = this.document.getText(range); const substitutions : {start: number, end: number, subst: string}[] = [] for(let subst of this.prettyDecorations.unscoped) { if(!subst.pretty) continue; const substRanges = subst.ranges.getOverlapRanges(range); for(let sr of substRanges) { const start = textUtil.relativeOffsetAtAbsolutePosition(text, range.start, sr.start); const end = textUtil.relativeOffsetAtAbsolutePosition(text, range.start, sr.end); substitutions.push({start: start, end: end, subst: subst.pretty}) } } for(let subst of this.prettyDecorations.scoped) { if(!subst.pretty) continue; const substRanges = subst.ranges.getOverlapRanges(range); for(let sr of substRanges) { const start = textUtil.relativeOffsetAtAbsolutePosition(text, range.start, sr.start); const end = textUtil.relativeOffsetAtAbsolutePosition(text, range.start, sr.end); substitutions.push({start: start, end: end, subst: subst.pretty}) } } // reverse order: later substs first const sortedSubst = substitutions.sort((a,b) => a.start < b.start ? 1 : a.start === b.start ? 0 : -1); let result = text; for(let subst of sortedSubst) { result = result.slice(0,subst.start) + subst.subst + result.slice(subst.end); } return result } public revealSelections(selections: vscode.Selection[]) : UpdateDecorationEntry { const revealUgly = (getRange: (sel:vscode.Selection) => vscode.Range) : UpdateDecorationEntry => { const cursorRevealedRanges = new DisjointRangeSet(); for(const selection of selections) { const ugly = getRange(selection); if(ugly) cursorRevealedRanges.insert(ugly); } // reveal the uglies and hide the pretties return {decoration: this.revealedUglyDecoration, ranges: cursorRevealedRanges.getRanges()}; } const revealUglies = (getRanges: (sel:vscode.Selection) => DisjointRangeSet) : UpdateDecorationEntry => { const cursorRevealedRanges = new DisjointRangeSet(); for(const selection of selections) { const ugly = getRanges(selection); if(ugly) cursorRevealedRanges.insertRanges(ugly); } // reveal the uglies and hide the pretties return {decoration: this.revealedUglyDecoration, ranges: cursorRevealedRanges.getRanges()}; } // add the new intersections switch(this.revealStrategy) { case 'cursor': return revealUgly((sel) => this.findSymbolAt(sel.active,{includeEnd: true})); case 'cursor-inside': return revealUgly((sel) => this.findSymbolAt(sel.active,{excludeStart: true})); case 'active-line': return revealUglies((sel) => this.findSymbolsIn(this.document.getLineRange(sel.active.line))); case 'selection': return revealUglies((sel) => this.findSymbolsIn(new vscode.Range(sel.start, sel.end))); default: return {decoration: this.revealedUglyDecoration, ranges: []}; } } public renderPrettyCursor(selections: vscode.Selection[]) : UpdateDecorationInstanceEntry|null { switch(this.prettyCursor) { case 'boxed': { const boxPretty = (getRange: (sel:vscode.Selection) => vscode.Range) : UpdateDecorationInstanceEntry|null => { try { const cursorBoxRanges = new DisjointRangeSet(); for(const selection of selections) { const pretty = getRange(selection); if(pretty) cursorBoxRanges.insert(pretty); } // reveal the uglies and hide the pretties return {decoration: this.boxedSymbolDecoration, ranges: cursorBoxRanges}; } catch(err) { console.error(err); console.error('\n'); return null; } } return boxPretty((sel) => this.findSymbolAt(sel.active)); } default: return null; } } }
the_stack
import * as colorUtils from '../utils/color_utils'; import * as mathUtils from '../utils/math_utils'; import {Cam16} from './cam16'; import {ViewingConditions} from './viewing_conditions'; // libmonet is designed to have a consistent API across platforms // and modular components that can be moved around easily. Using a class as a // namespace facilitates this. // // tslint:disable:class-as-namespace /** * A class that solves the HCT equation. */ export class HctSolver { static SCALED_DISCOUNT_FROM_LINRGB = [ [ 0.001200833568784504, 0.002389694492170889, 0.0002795742885861124, ], [ 0.0005891086651375999, 0.0029785502573438758, 0.0003270666104008398, ], [ 0.00010146692491640572, 0.0005364214359186694, 0.0032979401770712076, ], ]; static LINRGB_FROM_SCALED_DISCOUNT = [ [ 1373.2198709594231, -1100.4251190754821, -7.278681089101213, ], [ -271.815969077903, 559.6580465940733, -32.46047482791194, ], [ 1.9622899599665666, -57.173814538844006, 308.7233197812385, ], ]; static Y_FROM_LINRGB = [0.2126, 0.7152, 0.0722]; static CRITICAL_PLANES = [ 0.015176349177441876, 0.045529047532325624, 0.07588174588720938, 0.10623444424209313, 0.13658714259697685, 0.16693984095186062, 0.19729253930674434, 0.2276452376616281, 0.2579979360165119, 0.28835063437139563, 0.3188300904430532, 0.350925934958123, 0.3848314933096426, 0.42057480301049466, 0.458183274052838, 0.4976837250274023, 0.5391024159806381, 0.5824650784040898, 0.6277969426914107, 0.6751227633498623, 0.7244668422128921, 0.775853049866786, 0.829304845476233, 0.8848452951698498, 0.942497089126609, 1.0022825574869039, 1.0642236851973577, 1.1283421258858297, 1.1946592148522128, 1.2631959812511864, 1.3339731595349034, 1.407011200216447, 1.4823302800086415, 1.5599503113873272, 1.6398909516233677, 1.7221716113234105, 1.8068114625156377, 1.8938294463134073, 1.9832442801866852, 2.075074464868551, 2.1693382909216234, 2.2660538449872063, 2.36523901573795, 2.4669114995532007, 2.5710888059345764, 2.6777882626779785, 2.7870270208169257, 2.898822059350997, 3.0131901897720907, 3.1301480604002863, 3.2497121605402226, 3.3718988244681087, 3.4967242352587946, 3.624204428461639, 3.754355295633311, 3.887192587735158, 4.022731918402185, 4.160988767090289, 4.301978482107941, 4.445716283538092, 4.592217266055746, 4.741496401646282, 4.893568542229298, 5.048448422192488, 5.20615066083972, 5.3666897647573375, 5.5300801301023865, 5.696336044816294, 5.865471690767354, 6.037501145825082, 6.212438385869475, 6.390297286737924, 6.571091626112461, 6.7548350853498045, 6.941541251256611, 7.131223617812143, 7.323895587840543, 7.5195704746346665, 7.7182615035334345, 7.919981813454504, 8.124744458384042, 8.332562408825165, 8.543448553206703, 8.757415699253682, 8.974476575321063, 9.194643831691977, 9.417930041841839, 9.644347703669503, 9.873909240696694, 10.106627003236781, 10.342513269534024, 10.58158024687427, 10.8238400726681, 11.069304815507364, 11.317986476196008, 11.569896988756009, 11.825048221409341, 12.083451977536606, 12.345119996613247, 12.610063955123938, 12.878295467455942, 13.149826086772048, 13.42466730586372, 13.702830557985108, 13.984327217668513, 14.269168601521828, 14.55736596900856, 14.848930523210871, 15.143873411576273, 15.44220572664832, 15.743938506781891, 16.04908273684337, 16.35764934889634, 16.66964922287304, 16.985093187232053, 17.30399201960269, 17.62635644741625, 17.95219714852476, 18.281524751807332, 18.614349837764564, 18.95068293910138, 19.290534541298456, 19.633915083172692, 19.98083495742689, 20.331304511189067, 20.685334046541502, 21.042933821039977, 21.404114048223256, 21.76888489811322, 22.137256497705877, 22.50923893145328, 22.884842241736916, 23.264076429332462, 23.6469514538663, 24.033477234264016, 24.42366364919083, 24.817520537484558, 25.21505769858089, 25.61628489293138, 26.021211842414342, 26.429848230738664, 26.842203703840827, 27.258287870275353, 27.678110301598522, 28.10168053274597, 28.529008062403893, 28.96010235337422, 29.39497283293396, 29.83362889318845, 30.276079891419332, 30.722335150426627, 31.172403958865512, 31.62629557157785, 32.08401920991837, 32.54558406207592, 33.010999283389665, 33.4802739966603, 33.953417292456834, 34.430438229418264, 34.911345834551085, 35.39614910352207, 35.88485700094671, 36.37747846067349, 36.87402238606382, 37.37449765026789, 37.87891309649659, 38.38727753828926, 38.89959975977785, 39.41588851594697, 39.93615253289054, 40.460400508064545, 40.98864111053629, 41.520882981230194, 42.05713473317016, 42.597404951718396, 43.141702194811224, 43.6900349931913, 44.24241185063697, 44.798841244188324, 45.35933162437017, 45.92389141541209, 46.49252901546552, 47.065252796817916, 47.64207110610409, 48.22299226451468, 48.808024568002054, 49.3971762874833, 49.9904556690408, 50.587870934119984, 51.189430279724725, 51.79514187861014, 52.40501387947288, 53.0190544071392, 53.637271562750364, 54.259673423945976, 54.88626804504493, 55.517063457223934, 56.15206766869424, 56.79128866487574, 57.43473440856916, 58.08241284012621, 58.734331877617365, 59.39049941699807, 60.05092333227251, 60.715611475655585, 61.38457167773311, 62.057811747619894, 62.7353394731159, 63.417162620860914, 64.10328893648692, 64.79372614476921, 65.48848194977529, 66.18756403501224, 66.89098006357258, 67.59873767827808, 68.31084450182222, 69.02730813691093, 69.74813616640164, 70.47333615344107, 71.20291564160104, 71.93688215501312, 72.67524319850172, 73.41800625771542, 74.16517879925733, 74.9167682708136, 75.67278210128072, 76.43322770089146, 77.1981124613393, 77.96744375590167, 78.74122893956174, 79.51947534912904, 80.30219030335869, 81.08938110306934, 81.88105503125999, 82.67721935322541, 83.4778813166706, 84.28304815182372, 85.09272707154808, 85.90692527145302, 86.72564993000343, 87.54890820862819, 88.3767072518277, 89.2090541872801, 90.04595612594655, 90.88742016217518, 91.73345337380438, 92.58406282226491, 93.43925555268066, 94.29903859396902, 95.16341895893969, 96.03240364439274, 96.9059996312159, 97.78421388448044, 98.6670533535366, 99.55452497210776, ]; /** * Sanitizes a small enough angle in radians. * * @param angle An angle in radians; must not deviate too much * from 0. * @return A coterminal angle between 0 and 2pi. */ private static sanitizeRadians(angle: number): number { return (angle + Math.PI * 8) % (Math.PI * 2); } /** * Delinearizes an RGB component, returning a floating-point * number. * * @param rgbComponent 0.0 <= rgb_component <= 100.0, represents * linear R/G/B channel * @return 0.0 <= output <= 255.0, color channel converted to * regular RGB space */ private static trueDelinearized(rgbComponent: number): number { const normalized = rgbComponent / 100.0; let delinearized = 0.0; if (normalized <= 0.0031308) { delinearized = normalized * 12.92; } else { delinearized = 1.055 * Math.pow(normalized, 1.0 / 2.4) - 0.055; } return delinearized * 255.0; } private static chromaticAdaptation(component: number): number { const af = Math.pow(Math.abs(component), 0.42); return mathUtils.signum(component) * 400.0 * af / (af + 27.13); } /** * Returns the hue of a linear RGB color in CAM16. * * @param linrgb The linear RGB coordinates of a color. * @return The hue of the color in CAM16, in radians. */ private static hueOf(linrgb: number[]): number { const scaledDiscount = mathUtils.matrixMultiply(linrgb, HctSolver.SCALED_DISCOUNT_FROM_LINRGB); const rA = HctSolver.chromaticAdaptation(scaledDiscount[0]); const gA = HctSolver.chromaticAdaptation(scaledDiscount[1]); const bA = HctSolver.chromaticAdaptation(scaledDiscount[2]); // redness-greenness const a = (11.0 * rA + -12.0 * gA + bA) / 11.0; // yellowness-blueness const b = (rA + gA - 2.0 * bA) / 9.0; return Math.atan2(b, a); } private static areInCyclicOrder(a: number, b: number, c: number): boolean { const deltaAB = HctSolver.sanitizeRadians(b - a); const deltaAC = HctSolver.sanitizeRadians(c - a); return deltaAB < deltaAC; } /** * Solves the lerp equation. * * @param source The starting number. * @param mid The number in the middle. * @param target The ending number. * @return A number t such that lerp(source, target, t) = mid. */ private static intercept(source: number, mid: number, target: number): number { return (mid - source) / (target - source); } private static lerpPoint(source: number[], t: number, target: number[]): number[] { return [ source[0] + (target[0] - source[0]) * t, source[1] + (target[1] - source[1]) * t, source[2] + (target[2] - source[2]) * t, ]; } /** * Intersects a segment with a plane. * * @param source The coordinates of point A. * @param coordinate The R-, G-, or B-coordinate of the plane. * @param target The coordinates of point B. * @param axis The axis the plane is perpendicular with. (0: R, 1: * G, 2: B) * @return The intersection point of the segment AB with the plane * R=coordinate, G=coordinate, or B=coordinate */ private static setCoordinate( source: number[], coordinate: number, target: number[], axis: number, ): number[] { const t = HctSolver.intercept(source[axis], coordinate, target[axis]); return HctSolver.lerpPoint(source, t, target); } private static isBounded(x: number): boolean { return 0.0 <= x && x <= 100.0; } /** * Returns the nth possible vertex of the polygonal intersection. * * @param y The Y value of the plane. * @param n The zero-based index of the point. 0 <= n <= 11. * @return The nth possible vertex of the polygonal intersection * of the y plane and the RGB cube, in linear RGB coordinates, if * it exists. If this possible vertex lies outside of the cube, * [-1.0, -1.0, -1.0] is returned. */ private static nthVertex(y: number, n: number): number[] { const kR = HctSolver.Y_FROM_LINRGB[0]; const kG = HctSolver.Y_FROM_LINRGB[1]; const kB = HctSolver.Y_FROM_LINRGB[2]; const coordA = n % 4 <= 1 ? 0.0 : 100.0; const coordB = n % 2 === 0 ? 0.0 : 100.0; if (n < 4) { const g = coordA; const b = coordB; const r = (y - g * kG - b * kB) / kR; if (HctSolver.isBounded(r)) { return [r, g, b]; } else { return [-1.0, -1.0, -1.0]; } } else if (n < 8) { const b = coordA; const r = coordB; const g = (y - r * kR - b * kB) / kG; if (HctSolver.isBounded(g)) { return [r, g, b]; } else { return [-1.0, -1.0, -1.0]; } } else { const r = coordA; const g = coordB; const b = (y - r * kR - g * kG) / kB; if (HctSolver.isBounded(b)) { return [r, g, b]; } else { return [-1.0, -1.0, -1.0]; } } } /** * Finds the segment containing the desired color. * * @param y The Y value of the color. * @param targetHue The hue of the color. * @return A list of two sets of linear RGB coordinates, each * corresponding to an endpoint of the segment containing the * desired color. */ private static bisectToSegment(y: number, targetHue: number): number[][] { let left = [-1.0, -1.0, -1.0]; let right = left; let leftHue = 0.0; let rightHue = 0.0; let initialized = false; let uncut = true; for (let n = 0; n < 12; n++) { const mid = HctSolver.nthVertex(y, n); if (mid[0] < 0) { continue; } const midHue = HctSolver.hueOf(mid); if (!initialized) { left = mid; right = mid; leftHue = midHue; rightHue = midHue; initialized = true; continue; } if (uncut || HctSolver.areInCyclicOrder(leftHue, midHue, rightHue)) { uncut = false; if (HctSolver.areInCyclicOrder(leftHue, targetHue, midHue)) { right = mid; rightHue = midHue; } else { left = mid; leftHue = midHue; } } } return [left, right]; } private static midpoint(a: number[], b: number[]): number[] { return [ (a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2, ]; } private static criticalPlaneBelow(x: number): number { return Math.floor(x - 0.5); } private static criticalPlaneAbove(x: number): number { return Math.ceil(x - 0.5); } /** * Finds a color with the given Y and hue on the boundary of the * cube. * * @param y The Y value of the color. * @param targetHue The hue of the color. * @return The desired color, in linear RGB coordinates. */ private static bisectToLimit(y: number, targetHue: number): number[] { const segment = HctSolver.bisectToSegment(y, targetHue); let left = segment[0]; let leftHue = HctSolver.hueOf(left); let right = segment[1]; for (let axis = 0; axis < 3; axis++) { if (left[axis] !== right[axis]) { let lPlane = -1; let rPlane = 255; if (left[axis] < right[axis]) { lPlane = HctSolver.criticalPlaneBelow( HctSolver.trueDelinearized(left[axis])); rPlane = HctSolver.criticalPlaneAbove( HctSolver.trueDelinearized(right[axis])); } else { lPlane = HctSolver.criticalPlaneAbove( HctSolver.trueDelinearized(left[axis])); rPlane = HctSolver.criticalPlaneBelow( HctSolver.trueDelinearized(right[axis])); } for (let i = 0; i < 8; i++) { if (Math.abs(rPlane - lPlane) <= 1) { break; } else { const mPlane = Math.floor((lPlane + rPlane) / 2.0); const midPlaneCoordinate = HctSolver.CRITICAL_PLANES[mPlane]; const mid = HctSolver.setCoordinate(left, midPlaneCoordinate, right, axis); const midHue = HctSolver.hueOf(mid); if (HctSolver.areInCyclicOrder(leftHue, targetHue, midHue)) { right = mid; rPlane = mPlane; } else { left = mid; leftHue = midHue; lPlane = mPlane; } } } } } return HctSolver.midpoint(left, right); } private static inverseChromaticAdaptation(adapted: number): number { const adaptedAbs = Math.abs(adapted); const base = Math.max(0, 27.13 * adaptedAbs / (400.0 - adaptedAbs)); return mathUtils.signum(adapted) * Math.pow(base, 1.0 / 0.42); } /** * Finds a color with the given hue, chroma, and Y. * * @param hueRadians The desired hue in radians. * @param chroma The desired chroma. * @param y The desired Y. * @return The desired color as a hexadecimal integer, if found; 0 * otherwise. */ private static findResultByJ(hueRadians: number, chroma: number, y: number): number { // Initial estimate of j. let j = Math.sqrt(y) * 11.0; // =========================================================== // Operations inlined from Cam16 to avoid repeated calculation // =========================================================== const viewingConditions = ViewingConditions.DEFAULT; const tInnerCoeff = 1 / Math.pow(1.64 - Math.pow(0.29, viewingConditions.n), 0.73); const eHue = 0.25 * (Math.cos(hueRadians + 2.0) + 3.8); const p1 = eHue * (50000.0 / 13.0) * viewingConditions.nc * viewingConditions.ncb; const hSin = Math.sin(hueRadians); const hCos = Math.cos(hueRadians); for (let iterationRound = 0; iterationRound < 5; iterationRound++) { // =========================================================== // Operations inlined from Cam16 to avoid repeated calculation // =========================================================== const jNormalized = j / 100.0; const alpha = chroma === 0.0 || j === 0.0 ? 0.0 : chroma / Math.sqrt(jNormalized); const t = Math.pow(alpha * tInnerCoeff, 1.0 / 0.9); const ac = viewingConditions.aw * Math.pow( jNormalized, 1.0 / viewingConditions.c / viewingConditions.z, ); const p2 = ac / viewingConditions.nbb; const gamma = 23.0 * (p2 + 0.305) * t / (23.0 * p1 + 11 * t * hCos + 108.0 * t * hSin); const a = gamma * hCos; const b = gamma * hSin; const rA = (460.0 * p2 + 451.0 * a + 288.0 * b) / 1403.0; const gA = (460.0 * p2 - 891.0 * a - 261.0 * b) / 1403.0; const bA = (460.0 * p2 - 220.0 * a - 6300.0 * b) / 1403.0; const rCScaled = HctSolver.inverseChromaticAdaptation(rA); const gCScaled = HctSolver.inverseChromaticAdaptation(gA); const bCScaled = HctSolver.inverseChromaticAdaptation(bA); const linrgb = mathUtils.matrixMultiply( [rCScaled, gCScaled, bCScaled], HctSolver.LINRGB_FROM_SCALED_DISCOUNT, ); // =========================================================== // Operations inlined from Cam16 to avoid repeated calculation // =========================================================== if (linrgb[0] < 0 || linrgb[1] < 0 || linrgb[2] < 0) { return 0; } const kR = HctSolver.Y_FROM_LINRGB[0]; const kG = HctSolver.Y_FROM_LINRGB[1]; const kB = HctSolver.Y_FROM_LINRGB[2]; const fnj = kR * linrgb[0] + kG * linrgb[1] + kB * linrgb[2]; if (fnj <= 0) { return 0; } if (iterationRound === 4 || Math.abs(fnj - y) < 0.002) { if (linrgb[0] > 100.01 || linrgb[1] > 100.01 || linrgb[2] > 100.01) { return 0; } return colorUtils.argbFromLinrgb(linrgb); } // Iterates with Newton method, // Using 2 * fn(j) / j as the approximation of fn'(j) j = j - (fnj - y) * j / (2 * fnj); } return 0; } /** * Finds an sRGB color with the given hue, chroma, and L*, if * possible. * * @param hueDegrees The desired hue, in degrees. * @param chroma The desired chroma. * @param lstar The desired L*. * @return A hexadecimal representing the sRGB color. The color * has sufficiently close hue, chroma, and L* to the desired * values, if possible; otherwise, the hue and L* will be * sufficiently close, and chroma will be maximized. */ static solveToInt(hueDegrees: number, chroma: number, lstar: number): number { if (chroma < 0.0001 || lstar < 0.0001 || lstar > 99.9999) { return colorUtils.argbFromLstar(lstar); } hueDegrees = mathUtils.sanitizeDegreesDouble(hueDegrees); const hueRadians = hueDegrees / 180 * Math.PI; const y = colorUtils.yFromLstar(lstar); const exactAnswer = HctSolver.findResultByJ(hueRadians, chroma, y); if (exactAnswer !== 0) { return exactAnswer; } const linrgb = HctSolver.bisectToLimit(y, hueRadians); return colorUtils.argbFromLinrgb(linrgb); } /** * Finds an sRGB color with the given hue, chroma, and L*, if * possible. * * @param hueDegrees The desired hue, in degrees. * @param chroma The desired chroma. * @param lstar The desired L*. * @return An CAM16 object representing the sRGB color. The color * has sufficiently close hue, chroma, and L* to the desired * values, if possible; otherwise, the hue and L* will be * sufficiently close, and chroma will be maximized. */ static solveToCam(hueDegrees: number, chroma: number, lstar: number): Cam16 { return Cam16.fromInt(HctSolver.solveToInt(hueDegrees, chroma, lstar)); } }
the_stack
import { cliArguments } from 'cli-argument-parser' import { expect } from 'chai' import { RedisModules } from '../modules/redis-modules' import { FTParsedSearchResponse, FTSearchArrayResponse } from '../modules/redisearch/redisearch.types' import * as fs from 'fs'; let redis: RedisModules const index = 'idx' const query = '@text:name' const alias = 'alias' const sug = { key: 'k', string: 'str', score: 11 } const dict = { name: 'dictX', term: 'termY' } describe('RediSearch Module testing', async function () { before(async () => { redis = new RedisModules({ host: cliArguments.host, port: parseInt(cliArguments.port) }, { showDebugLogs: true }) await redis.connect() }) after(async () => { await redis.redis.flushdb(); await redis.disconnect() }) it('create function', async () => { let response = await redis.search_module_create(index, 'HASH', [{ name: 'name', type: 'TEXT' }]) expect(response).to.equal('OK', 'The response of the FT.CREATE command') response = await redis.search_module_create(`${index}1`, 'HASH', [{ name: 'name', type: 'TEXT' }, { name: 'name2', type: 'TEXT', sortable: true, weight: 2 }]) expect(response).to.equal('OK', 'The response of the FT.CREATE command') response = await redis.search_module_create(`${index}-json`, 'JSON', [{ name: '$.name', type: 'TEXT', as: 'name' }]) expect(response).to.equal('OK', 'The response of the FT.CREATE command') await redis.search_module_dropindex(`${index}1`) }) it('search function on JSON', async () => { let response = await redis.search_module_search(index, query) expect(response).to.equal(0, 'The response of the FT.SEARCH command') //FIXME: JSON Needs more tests, also I couldn't find anything related to `RETURN AS` so that also needs tests response = await redis.search_module_search(`${index}-json`, query, { return: { num: 3, fields: [ { field: '$.name', as: 'name' } ] } }) expect(response).to.equal(0, 'The response of the FT.SEARCH command') await redis.search_module_dropindex(`${index}-json`) }) it('search function response test (creation phase)', async () => { await redis.search_module_create(`${index}-searchtest`, 'HASH', [{ name: 'name', type: 'TEXT' }, { name: 'age', type: 'NUMERIC' }, { name: 'salary', type: 'NUMERIC' }, { name: 'introduction', type: 'TEXT' }], { prefix: { prefixes: ["doc", "alma"] } }) await redis.redis.hset( 'doc:1', { name: 'John Doe', age: 25, salary: 2500, introduction: 'John Doe is a developer at somekind of company.' } ) await redis.redis.hset( 'doc:2', { name: 'Jane Doe', age: 30, salary: 5000, introduction: 'Jane Doe is John Doe\'s sister. She is not a developer, she is a hairstylist.' } ) await redis.redis.hset( 'doc:3', { name: 'Sarah Brown', age: 80, salary: 10000, introduction: 'Sarah Brown is retired with an unusually high "salary".' } ) }) it('Simple search test with field specified in query', async () => { const [count, ...result] = await redis.search_module_search(`${index}-searchtest`, '@name:Doe') as FTSearchArrayResponse; expect(count).to.equal(2, 'Total number of returining document of FT.SEARCH command') expect((result[0] as {[key: string]: string}).key).to.equal('doc:1', 'first document key') }) it('Simple search tests with field specified using inFields', async () => { let res = await redis.search_module_search( `${index}-searchtest`, 'Doe', { inFields: { fields: ['age', 'salary'] } } ) expect(res).to.equal(0, 'Total number of returining document of FT.SEARCH command') res = await redis.search_module_search( `${index}-searchtest`, 'Doe', { inFields: { fields: ['name'] } } ) expect(res[0]).to.equal(2, 'Total number of returining document of FT.SEARCH command') }) it('Search test with inkeys', async () => { let res = await redis.search_module_search( `${index}-searchtest`, 'Doe', { inKeys: { keys: ['doc:1', 'doc:2'] } } ) expect(res[0]).to.equal(2, 'Total number of returining document of FT.SEARCH command') res = await redis.search_module_search( `${index}-searchtest`, 'Doe', { inKeys: { keys: ['doc:3'] } } ) expect(res).to.equal(0, 'Total number of returining document of FT.SEARCH command') }) it('Search tests with filter', async () => { let res = await redis.search_module_search( `${index}-searchtest`, '*', { filter: [{ field: 'age', min: 0, max: 35 }] } ) expect(res[0]).to.equal(2, 'Total number of returining document of FT.SEARCH command') res = await redis.search_module_search( `${index}-searchtest`, '*', { filter: [ { field: 'age', min: 0, max: 35, }, { field: 'salary', min: 0, max: 2500, } ] } ) expect(res[0]).to.equal(1, 'Total number of returining document of FT.SEARCH command') }) it('Search tests with return', async () => { let res = await redis.search_module_search( `${index}-searchtest`, '*', { return: { fields: [{ field: 'age', }] } } ) expect(res[0]).to.equal(3, 'Total number of returining document of FT.SEARCH command') expect(Object.keys(res[1]).length).to.equal(2, 'Total number of returned key-values') expect(Object.keys(res[1]).includes('age')).to.equal(true, 'Age must be returned') expect(Object.keys(res[1]).includes('salary')).to.equal(false, 'Salary must not be returned') expect(Object.keys(res[1]).includes('name')).to.equal(false, 'Name must not be returned') expect(Object.keys(res[2]).length).to.equal(2, 'Total number of returned key-values') expect(Object.keys(res[3]).length).to.equal(2, 'Total number of returned key-values') res = await redis.search_module_search( `${index}-searchtest`, 'Sarah', { return: { fields: [ { field: 'age', }, { field: 'salary', } ] } } ) expect(res[0]).to.equal(1, 'Total number of returining document of FT.SEARCH command') expect(Object.keys(res[1]).includes('age')).to.equal(true, 'Age must be returned') expect(Object.keys(res[1]).includes('salary')).to.equal(true, 'Salary must be returned') expect(Object.keys(res[1]).includes('name')).to.equal(false, 'Name must not be returned') res = await redis.search_module_search( `${index}-searchtest`, '*', { return: { fields: [] } } ) as FTSearchArrayResponse; expect(res.length).to.equal(4, 'Only keys should be returned (+count of them)') }) it('Search test with summarize', async () => { const res = await redis.search_module_search( `${index}-searchtest`, 'De*', { //! specifying fields in summarize while return is also specified will cause redis (edge version) to crash //! Crash in redis image fabe0b38e273 // return: ['introduction'], summarize: { fields: { fields: ['introduction'] }, frags: 1, len: 3, separator: ' !?!' } } ) expect(res[0]).to.equal(2, 'Total number of returining document of FT.SEARCH command') expect((res[1] as {[key: string]: string}).introduction.endsWith('!?!')).to.equal(true, 'Custom summarize separator') expect((res[1] as {[key: string]: string}).introduction.endsWith('!?!')).to.equal(true, 'Custom summarize separator') }) it('Search tests with highlight', async () => { const res = await redis.search_module_search( `${index}-searchtest`, 'Do*|De*', { highlight: { fields: { fields: ['introduction'] }, tags: { open: '**', close: '**' } } } ) expect(res[0]).to.equal(2, 'Total number of returining document of FT.SEARCH command') expect((res[1] as {[key: string]: string}).name.includes('**')).to.equal(false, 'Name mustn\'t be highlighted') expect((res[1] as {[key: string]: string}).introduction.includes('**developer**')).to.equal(true, 'Introduction must be highlighted') }) it('Search test with sortby ', async () => { const res = await redis.search_module_search( `${index}-searchtest`, '*', { return: { fields: [{ field: 'age' }] }, sortBy: { field: 'age', sort: 'ASC' } } ) expect(res[0]).to.equal(3, 'Total number of returining document of FT.SEARCH command') expect((res[1] as {[key: string]: string}).age).to.equal('25', 'Ages should be returned in ascending order') expect((res[2] as {[key: string]: string}).age).to.equal('30', 'Ages should be returned in ascending order') expect((res[3] as {[key: string]: string}).age).to.equal('80', 'Ages should be returned in ascending order') }) it('Search test with limit', async () => { const res = await redis.search_module_search( `${index}-searchtest`, '*', { limit: { first: 0, num: 1 } } ) as FTSearchArrayResponse; expect(res[0]).to.equal(3, 'Total number of returining document of FT.SEARCH command') expect(res.length).to.equal(2, 'Only one item should be returned') }) it('aggregate function', async () => { const response = await redis.search_module_aggregate(index, query) expect(response.numberOfItems).to.equal(0, 'The response of the FT.AGGREGATE command') }) it('aggregate function response', async () => { await redis.search_module_create(`${index}-aggreagtetest`, 'HASH', [{ name: 'name', type: 'TEXT' }, { name: 'city', type: 'TEXT' }, { name: 'gender', type: 'TAG' }, { name: 'timestamp', type: 'NUMERIC', sortable: true } ], { prefix: {prefixes: ['person']} }) const time = new Date() await redis.redis.hset('person:1', { name: 'John Doe', city: 'London', gender: 'male', timestamp: (time.getTime() / 1000).toFixed(0) }) await redis.redis.hset('person:2', { name: 'Jane Doe', city: 'London', gender: 'female', timestamp: (time.getTime() / 1000).toFixed(0) }) time.setHours(time.getHours() - 3) await redis.redis.hset('person:3', { name: 'Sarah Brown', city: 'New York', gender: 'female', timestamp: (time.getTime() / 1000).toFixed(0) }) await redis.redis.hset('person:3', { name: 'Michael Doe', city: 'New York', gender: 'male', timestamp: (time.getTime() / 1000).toFixed(0) }) let response = await redis.search_module_aggregate(`${index}-aggreagtetest`, 'Doe', { groupby: { properties: ['@city'], nargs: '1' } }) expect(response.numberOfItems).to.equal(2, 'Total number of the FT.AGGREGATE command result') expect(response.items[0].name).to.equal('city', 'Aggreagated prop of the FT.AGGREGATE command result') response = await redis.search_module_aggregate(`${index}-aggreagtetest`, '*', { apply: [{ expression: 'hour(@timestamp)', as: 'hour' }], groupby: { properties: ['@hour'], nargs: '1' } }) expect(response.numberOfItems).to.equal(2, 'Total number of the FT.AGGREGATE command result') expect(response.items[0].name).to.equal('hour', 'Aggreagated apply prop of the FT.AGGREGATE command result') await redis.search_module_dropindex(`${index}-aggreagtetest`) }) it('explain function', async () => { const response = await redis.search_module_explain(index, query) expect(response).to.contain('@NULL:UNION', 'The response of the FT.EXPLAIN command') }) it('explainCLI function', async () => { const response = await redis.search_module_explainCLI(index, query) expect(response).to.equal('@NULL:UNION { @NULL:name @NULL:+name(expanded)}', 'The response of the FT.EXPLAINCLI command') }) it('alter function', async () => { const response = await redis.search_module_alter(index, 'tags', 'TAG') expect(response).to.equal('OK', 'The response of the FT.ALTER command') }) it('aliasadd function', async () => { const response = await redis.search_module_aliasadd(alias, index) expect(response).to.equal('OK', 'The response of the FT.ALIASADD command') }) it('aliasupdate function', async () => { const response = await redis.search_module_aliasupdate(alias, index) expect(response).to.equal('OK', 'The response of the FT.ALIASUPDATE command') }) it('aliasdel function', async () => { const response = await redis.search_module_aliasdel(alias) expect(response).to.equal('OK', 'The response of the FT.ALIASDEL command') }) it('sugadd function', async () => { const response = await redis.search_module_sugadd(sug.key, sug.string, sug.score) expect(response).to.equal(1, 'The response of the FT.SUGADD command') }) it('sugget function', async () => { const response = await redis.search_module_sugget(sug.key, sug.string) expect(response).to.equal('str', 'The response of the FT.SUGGET command') }) it('suglen function', async () => { const response = await redis.search_module_suglen(sug.key) expect(response).to.equal(1, 'The response of the FT.SUGLEN command') }) it('sugdel function', async () => { const response = await redis.search_module_sugdel(sug.key, sug.string) expect(response).to.equal(1, 'The response of the FT.SUGDEL command') }) it('tagvalgs function', async () => { const response = await redis.search_module_tagvals(index, 'tags') expect(response.length).to.equal(0, 'The response of the FT.TAGVALS command') }) it('synupdate function', async () => { const response = await redis.search_module_synupdate(index, 0, ['term1']) expect(response).to.equal('OK', 'The response of the FT.SYNUPDATE command') }) it('syndump function', async () => { const response = await redis.search_module_syndump(index) expect(response.term1).to.equal('0', 'The response of the FT.SYNDUMP command') }) it('spellcheck function', async () => { await redis.search_module_create(`${index}-spellcheck`, 'HASH', [{ name: "content", type: "TEXT", }], { prefix: { prefixes: 'colors:' } }); await redis.redis.hset('colors:1', { content: 'red green blue yellow mellon' }) let response = await redis.search_module_spellcheck(`${index}-spellcheck`, "redis") expect(response[0].suggestions.length).to.equal(0, 'No suggestion should be found') response = await redis.search_module_spellcheck(`${index}-spellcheck`, "mellow blua") expect(response.length).to.equal(2, 'Both word should be spellchecked') }) it('dictadd function', async () => { const response = await redis.search_module_dictadd(dict.name, [dict.term]) expect(response).to.equal(1, 'The response of the FT.DICTADD command') }) it('dictdel function', async () => { await redis.search_module_dictadd(dict.name, [dict.term]) const response = await redis.search_module_dictdel(dict.name, [dict.term]) expect(response).to.equal(1, 'The response of the FT.DICDEL command') }) it('dictdump function', async () => { await redis.search_module_dictadd(`${dict.name}1`, [`${dict.term}1`]) const response = await redis.search_module_dictdump(`${dict.name}1`) expect(response).to.equal('termY1', 'The response of the FT.DICTDUMP command') await redis.search_module_dictdel(`${dict.name}1`, [`${dict.term}1`]) }) it('info function', async () => { const response = await redis.search_module_info(index) expect(response.index_name).to.equal(index, 'The index name') }) it('config function', async () => { const response = await redis.search_module_config('GET', '*') expect(response.EXTLOAD).to.equal(null, 'The EXTLOAD value') }) it('dropindex function', async () => { await redis.search_module_create(`${index}-droptest`, 'HASH', [{ name: 'name', type: 'TEXT' }]) const response = await redis.search_module_dropindex(`${index}-droptest`) expect(response).to.equal('OK', 'The response of the FT.DROPINDEX command') }) it('Testing the parse of search function as JSON', async () => { const json = fs.readFileSync('tests/data/models/sample1.json', { encoding: 'utf-8'}); const parsedJSON = JSON.parse(json); await redis.search_module_create('li-index', 'JSON', [{ name: '$.title', type: 'TEXT', }, { name: '$.description', type: 'TEXT', }]); await Promise.all(parsedJSON.map(async (p: { id: number; }) => await redis.rejson_module_set(`li:${p.id}`, '$', JSON.stringify(p)))); const result = await redis.search_module_search('li-index', 'KAS', { limit: { first: 0, num: 20 }, withScores: true }) as FTParsedSearchResponse; const { resultsCount } = result; expect(resultsCount).to.equal(1, 'The count of the results'); }) })
the_stack
"use strict"; import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore"; import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration"; import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem"; import { IPlugin, ITelemetryPlugin } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin"; import { GetExtCfgMergeType, IBaseProcessingContext, IProcessTelemetryContext, IProcessTelemetryUnloadContext, IProcessTelemetryUpdateContext } from "../JavaScriptSDK.Interfaces/IProcessTelemetryContext"; import { ITelemetryPluginChain } from "../JavaScriptSDK.Interfaces/ITelemetryPluginChain"; import { safeGetLogger, _throwInternal } from "./DiagnosticLogger"; import { arrForEach, isArray, isFunction, isNullOrUndefined, isObject, isUndefined, objExtend, objForEachKey, objFreeze, objKeys, proxyFunctions } from "./HelperFuncs"; import { doPerf } from "./PerfManager"; import { eLoggingSeverity, _eInternalMessageId } from "../JavaScriptSDK.Enums/LoggingEnums"; import { dumpObj } from "./EnvUtils"; import { strCore, strDisabled, strEmpty, strIsInitialized, strTeardown, strUpdate } from "./InternalConstants"; import { IDiagnosticLogger } from "../JavaScriptSDK.Interfaces/IDiagnosticLogger"; import { ITelemetryUnloadState } from "../JavaScriptSDK.Interfaces/ITelemetryUnloadState"; import { ITelemetryUpdateState } from "../JavaScriptSDK.Interfaces/ITelemetryUpdateState"; import { _getPluginState } from "./TelemetryHelpers"; const strTelemetryPluginChain = "TelemetryPluginChain"; const strHasRunFlags = "_hasRun"; const strGetTelCtx = "_getTelCtx"; let _chainId = 0; interface OnCompleteCallback { func: () => void; self: any; // This for the function args: any[]; // Additional arguments for the function } interface IInternalTelemetryPluginChain extends ITelemetryPluginChain { _id: string; _setNext: (nextPlugin: IInternalTelemetryPluginChain) => void; } interface IInternalContext<T extends IBaseProcessingContext> { _next: () => ITelemetryPluginChain, // The public context that will be exposed ctx: T } function _getNextProxyStart<T, C = IConfiguration>(proxy: ITelemetryPluginChain, core: IAppInsightsCore, startAt: IPlugin): ITelemetryPluginChain { while (proxy) { if (proxy.getPlugin() === startAt) { return proxy; } proxy = proxy.getNext(); } // This wasn't found in the existing chain so create an isolated one with just this plugin return createTelemetryProxyChain([startAt], core.config || {}, core); } /** * @ignore * @param telemetryChain * @param config * @param core * @param startAt - Identifies the next plugin to execute, if null there is no "next" plugin and if undefined it should assume the start of the chain * @returns */ function _createInternalContext<T extends IBaseProcessingContext>(telemetryChain: ITelemetryPluginChain, config: IConfiguration, core: IAppInsightsCore, startAt?: IPlugin): IInternalContext<T> { // We have a special case where we want to start execution from this specific plugin // or we simply reuse the existing telemetry plugin chain (normal execution case) let _nextProxy: ITelemetryPluginChain | null = null; // By Default set as no next plugin let _onComplete: OnCompleteCallback[] = []; if (startAt !== null) { // There is no next element (null) vs not defined (undefined) so use the full chain _nextProxy = startAt ? _getNextProxyStart(telemetryChain, core, startAt) : telemetryChain; } let context: IInternalContext<T> = { _next: _moveNext, ctx: { core: () => { return core }, diagLog: () => { return safeGetLogger(core, config); }, getCfg: () => { return config; }, getExtCfg: _getExtCfg, getConfig: _getConfig, hasNext: () => { return !!_nextProxy; }, getNext: () => { return _nextProxy; }, setNext: (nextPlugin:ITelemetryPluginChain) => { _nextProxy = nextPlugin; }, iterate: _iterateChain, onComplete: _addOnComplete } as T }; function _addOnComplete(onComplete: () => void, that?: any, ...args: any[]) { if (onComplete) { _onComplete.push({ func: onComplete, self: !isUndefined(that) ? that : context.ctx, args: args }); } } function _moveNext() { let nextProxy = _nextProxy; // Automatically move to the next plugin _nextProxy = nextProxy ? nextProxy.getNext() : null; if (!nextProxy) { let onComplete = _onComplete; if (onComplete && onComplete.length > 0) { arrForEach(onComplete, (completeDetails) => { try { completeDetails.func.call(completeDetails.self, completeDetails.args); } catch (e) { _throwInternal( core.logger, eLoggingSeverity.WARNING, _eInternalMessageId.PluginException, "Unexpected Exception during onComplete - " + dumpObj(e)); } }); _onComplete = []; } } return nextProxy; } function _getExtCfg<T>(identifier: string, defaultValue: T|any = {}, mergeDefault: GetExtCfgMergeType = GetExtCfgMergeType.None) { let theConfig: T; if (config) { let extConfig = config.extensionConfig; if (extConfig && identifier) { theConfig = extConfig[identifier]; } } if (!theConfig) { // Just use the defaults theConfig = defaultValue as T; } else if (isObject(defaultValue)) { if (mergeDefault !== GetExtCfgMergeType.None) { // Merge the defaults and configured values let newConfig = objExtend(true, defaultValue, theConfig); if (config && mergeDefault === GetExtCfgMergeType.MergeDefaultFromRootOrDefault) { // Enumerate over the defaultValues and if not already populated attempt to // find a value from the root config objForEachKey(defaultValue, (field) => { // for each unspecified field, set the default value if (isNullOrUndefined(newConfig[field])) { let cfgValue = config[field]; if (!isNullOrUndefined(cfgValue)) { newConfig[field] = cfgValue; } } }); } theConfig = newConfig; } } return theConfig; } function _getConfig(identifier:string, field: string, defaultValue: number | string | boolean | string[] | RegExp[] | Function = false) { let theValue; let extConfig = _getExtCfg(identifier, null); if (extConfig && !isNullOrUndefined(extConfig[field])) { theValue = extConfig[field]; } else if (config && !isNullOrUndefined(config[field])) { theValue = config[field]; } return !isNullOrUndefined(theValue) ? theValue : defaultValue; } function _iterateChain<T extends ITelemetryPlugin = ITelemetryPlugin>(cb: (plugin: T) => void) { // Keep processing until we reach the end of the chain let nextPlugin: ITelemetryPluginChain; while(!!(nextPlugin = context._next())) { let plugin = nextPlugin.getPlugin(); if (plugin) { // callback with the current on cb(plugin as T); } } } return context; } /** * Creates a new Telemetry Item context with the current config, core and plugin execution chain * @param plugins - The plugin instances that will be executed * @param config - The current config * @param core - The current core instance * @param startAt - Identifies the next plugin to execute, if null there is no "next" plugin and if undefined it should assume the start of the chain */ export function createProcessTelemetryContext(telemetryChain: ITelemetryPluginChain | null, config: IConfiguration, core:IAppInsightsCore, startAt?: IPlugin): IProcessTelemetryContext { let internalContext: IInternalContext<IProcessTelemetryContext> = _createInternalContext<IProcessTelemetryContext>(telemetryChain, config, core, startAt); let context = internalContext.ctx; function _processNext(env: ITelemetryItem) { let nextPlugin: ITelemetryPluginChain = internalContext._next(); // Run the next plugin which will call "processNext()" nextPlugin && nextPlugin.processTelemetry(env, context); return !nextPlugin; } function _createNew(plugins: IPlugin[] | ITelemetryPluginChain | null = null, startAt?: IPlugin) { if (isArray(plugins)) { plugins = createTelemetryProxyChain(plugins, config, core, startAt); } return createProcessTelemetryContext(plugins || context.getNext(), config, core, startAt); } context.processNext = _processNext; context.createNew = _createNew; return context; } /** * Creates a new Telemetry Item context with the current config, core and plugin execution chain for handling the unloading of the chain * @param plugins - The plugin instances that will be executed * @param config - The current config * @param core - The current core instance * @param startAt - Identifies the next plugin to execute, if null there is no "next" plugin and if undefined it should assume the start of the chain */ export function createProcessTelemetryUnloadContext(telemetryChain: ITelemetryPluginChain, core: IAppInsightsCore, startAt?: IPlugin): IProcessTelemetryUnloadContext { let config = core.config || {}; let internalContext: IInternalContext<IProcessTelemetryUnloadContext> = _createInternalContext<IProcessTelemetryUnloadContext>(telemetryChain, config, core, startAt); let context = internalContext.ctx; function _processNext(unloadState: ITelemetryUnloadState) { let nextPlugin: ITelemetryPluginChain = internalContext._next(); nextPlugin && nextPlugin.unload(context, unloadState); return !nextPlugin; } function _createNew(plugins: IPlugin[] | ITelemetryPluginChain = null, startAt?: IPlugin): IProcessTelemetryUnloadContext { if (isArray(plugins)) { plugins = createTelemetryProxyChain(plugins, config, core, startAt); } return createProcessTelemetryUnloadContext(plugins || context.getNext(), core, startAt); } context.processNext = _processNext; context.createNew = _createNew return context; } /** * Creates a new Telemetry Item context with the current config, core and plugin execution chain for updating the configuration * @param plugins - The plugin instances that will be executed * @param config - The current config * @param core - The current core instance * @param startAt - Identifies the next plugin to execute, if null there is no "next" plugin and if undefined it should assume the start of the chain */ export function createProcessTelemetryUpdateContext(telemetryChain: ITelemetryPluginChain, core: IAppInsightsCore, startAt?: IPlugin): IProcessTelemetryUpdateContext { let config = core.config || {}; let internalContext: IInternalContext<IProcessTelemetryUpdateContext> = _createInternalContext<IProcessTelemetryUpdateContext>(telemetryChain, config, core, startAt); let context = internalContext.ctx; function _processNext(updateState: ITelemetryUpdateState) { return context.iterate((plugin) => { if (isFunction(plugin.update)) { plugin.update(context, updateState); } }); } function _createNew(plugins: IPlugin[] | ITelemetryPluginChain = null, startAt?: IPlugin) { if (isArray(plugins)) { plugins = createTelemetryProxyChain(plugins, config, core, startAt); } return createProcessTelemetryUpdateContext(plugins || context.getNext(), core, startAt); } context.processNext = _processNext; context.createNew = _createNew; return context; } /** * Creates an execution chain from the array of plugins * @param plugins - The array of plugins that will be executed in this order * @param defItemCtx - The default execution context to use when no telemetry context is passed to processTelemetry(), this * should be for legacy plugins only. Currently, only used for passing the current core instance and to provide better error * reporting (hasRun) when errors occur. */ export function createTelemetryProxyChain(plugins: IPlugin[], config: IConfiguration, core: IAppInsightsCore, startAt?: IPlugin): ITelemetryPluginChain { let firstProxy: ITelemetryPluginChain = null; let add = startAt ? false : true; if (isArray(plugins) && plugins.length > 0) { // Create the proxies and wire up the next plugin chain let lastProxy: IInternalTelemetryPluginChain = null; arrForEach(plugins, (thePlugin: ITelemetryPlugin) => { if (!add && startAt === thePlugin) { add = true; } if (add && thePlugin && isFunction(thePlugin.processTelemetry)) { // Only add plugins that are processors let newProxy = createTelemetryPluginProxy(thePlugin, config, core); if (!firstProxy) { firstProxy = newProxy; } if (lastProxy) { // Set this new proxy as the next for the previous one lastProxy._setNext(newProxy as IInternalTelemetryPluginChain); } lastProxy = newProxy as IInternalTelemetryPluginChain; } }); } if (startAt && !firstProxy) { // Special case where the "startAt" was not in the original list of plugins return createTelemetryProxyChain([startAt], config, core); } return firstProxy; } /** * Create the processing telemetry proxy instance, the proxy is used to abstract the current plugin to allow monitoring and * execution plugins while passing around the dynamic execution state (IProcessTelemetryContext), the proxy instance no longer * contains any execution state and can be reused between requests (this was not the case for 2.7.2 and earlier with the * TelemetryPluginChain class). * @param plugin - The plugin instance to proxy * @param config - The default execution context to use when no telemetry context is passed to processTelemetry(), this * should be for legacy plugins only. Currently, only used for passing the current core instance and to provide better error * reporting (hasRun) when errors occur. * @returns */ export function createTelemetryPluginProxy(plugin: ITelemetryPlugin, config: IConfiguration, core: IAppInsightsCore): ITelemetryPluginChain { let nextProxy: IInternalTelemetryPluginChain = null; let hasProcessTelemetry = isFunction(plugin.processTelemetry); let hasSetNext = isFunction(plugin.setNextPlugin); let chainId: string; if (plugin) { chainId = plugin.identifier + "-" + plugin.priority + "-" + _chainId++; } else { chainId = "Unknown-0-" + _chainId++; } let proxyChain: IInternalTelemetryPluginChain = { getPlugin: () => { return plugin; }, getNext: () => { return nextProxy; }, processTelemetry: _processTelemetry, unload: _unloadPlugin, update: _updatePlugin, _id: chainId, _setNext: (nextPlugin: IInternalTelemetryPluginChain) => { nextProxy = nextPlugin; } }; function _getTelCtx() { let itemCtx: IProcessTelemetryContext; // Looks like a plugin didn't pass the (optional) context, so create a new one if (plugin && isFunction(plugin[strGetTelCtx])) { // This plugin extends from the BaseTelemetryPlugin so lets use it itemCtx = plugin[strGetTelCtx](); } if (!itemCtx) { // Create a temporary one itemCtx = createProcessTelemetryContext(proxyChain, config, core); } return itemCtx; } function _processChain<T extends IBaseProcessingContext>( itemCtx: T, processPluginFn: (itemCtx: T) => boolean, name: string, details: () => any, isAsync: boolean) { let hasRun = false; let identifier = plugin ? plugin.identifier : strTelemetryPluginChain; let hasRunContext = itemCtx[strHasRunFlags]; if (!hasRunContext) { // Assign and populate hasRunContext = itemCtx[strHasRunFlags] = {}; } // Ensure that we keep the context in sync itemCtx.setNext(nextProxy); if (plugin) { doPerf(itemCtx[strCore](), () => identifier + ":" + name, () => { // Mark this component as having run hasRunContext[chainId] = true; try { // Set a flag on the next plugin so we know if it was attempted to be executed let nextId = nextProxy ? nextProxy._id : strEmpty; if (nextId) { hasRunContext[nextId] = false; } hasRun = processPluginFn(itemCtx); } catch (error) { let hasNextRun = nextProxy ? hasRunContext[nextProxy._id] : true; if (hasNextRun) { // The next plugin after us has already run so set this one as complete hasRun = true; } if (!nextProxy || !hasNextRun) { // Either we have no next plugin or the current one did not attempt to call the next plugin // Which means the current one is the root of the failure so log/report this failure _throwInternal( itemCtx.diagLog(), eLoggingSeverity.CRITICAL, _eInternalMessageId.PluginException, "Plugin [" + identifier + "] failed during " + name + " - " + dumpObj(error) + ", run flags: " + dumpObj(hasRunContext)); } } }, details, isAsync); } return hasRun; } function _processTelemetry(env: ITelemetryItem, itemCtx: IProcessTelemetryContext) { itemCtx = itemCtx || _getTelCtx(); function _callProcessTelemetry(itemCtx: IProcessTelemetryContext) { if (!plugin || !hasProcessTelemetry) { return false; } let pluginState = _getPluginState(plugin); if (pluginState.teardown || pluginState[strDisabled]) { return false; } // Ensure that we keep the context in sync (for processNext()), just in case a plugin // doesn't calls processTelemetry() instead of itemContext.processNext() or some // other form of error occurred if (hasSetNext) { // Backward compatibility setting the next plugin on the instance plugin.setNextPlugin(nextProxy); } plugin.processTelemetry(env, itemCtx); // Process Telemetry is expected to call itemCtx.processNext() or nextPlugin.processTelemetry() return true; } if (!_processChain(itemCtx, _callProcessTelemetry, "processTelemetry", () => ({ item: env }), !((env as any).sync))) { // The underlying plugin is either not defined, not enabled or does not have a processTelemetry implementation // so we still want the next plugin to be executed. itemCtx.processNext(env); } } function _unloadPlugin(unloadCtx: IProcessTelemetryUnloadContext, unloadState: ITelemetryUnloadState) { function _callTeardown() { // Setting default of hasRun as false so the proxyProcessFn() is called as teardown() doesn't have to exist or call unloadNext(). let hasRun = false; if (plugin) { let pluginState = _getPluginState(plugin); let pluginCore = plugin[strCore] || pluginState.core; // Only teardown the plugin if it was initialized by the current core (i.e. It's not a shared plugin) if (plugin && (!pluginCore || pluginCore === unloadCtx[strCore]()) && !pluginState[strTeardown]) { // Handle plugins that don't extend from the BaseTelemetryPlugin pluginState[strCore] = null; pluginState[strTeardown] = true; pluginState[strIsInitialized] = false; if (plugin[strTeardown] && plugin[strTeardown](unloadCtx, unloadState) === true) { // plugin told us that it was going to (or has) call unloadCtx.processNext() hasRun = true; } } } return hasRun; } if (!_processChain(unloadCtx, _callTeardown, "unload", () => {}, unloadState.isAsync)) { // Only called if we hasRun was not true unloadCtx.processNext(unloadState); } } function _updatePlugin(updateCtx: IProcessTelemetryUpdateContext, updateState: ITelemetryUpdateState) { function _callUpdate() { // Setting default of hasRun as false so the proxyProcessFn() is called as teardown() doesn't have to exist or call unloadNext(). let hasRun = false; if (plugin) { let pluginState = _getPluginState(plugin); let pluginCore = plugin[strCore] || pluginState.core; // Only update the plugin if it was initialized by the current core (i.e. It's not a shared plugin) if (plugin && (!pluginCore || pluginCore === updateCtx[strCore]()) && !pluginState[strTeardown]) { if (plugin[strUpdate] && plugin[strUpdate](updateCtx, updateState) === true) { // plugin told us that it was going to (or has) call unloadCtx.processNext() hasRun = true; } } } return hasRun; } if (!_processChain(updateCtx, _callUpdate, "update", () => {}, false)) { // Only called if we hasRun was not true updateCtx.processNext(updateState); } } return objFreeze(proxyChain); } /** * This class will be removed! * @deprecated use createProcessTelemetryContext() instead */ export class ProcessTelemetryContext implements IProcessTelemetryContext { /** * Gets the current core config instance */ public getCfg: () => IConfiguration; public getExtCfg: <T>(identifier:string, defaultValue?:T|any) => T; public getConfig: (identifier:string, field: string, defaultValue?: number | string | boolean | string[] | RegExp[] | Function) => number | string | boolean | string[] | RegExp[] | Function; /** * Returns the IAppInsightsCore instance for the current request */ public core: () => IAppInsightsCore; /** * Returns the current IDiagnosticsLogger for the current request */ public diagLog: () => IDiagnosticLogger; /** * Helper to allow inherited classes to check and possibly shortcut executing code only * required if there is a nextPlugin */ public hasNext: () => boolean; /** * Returns the next configured plugin proxy */ public getNext: () => ITelemetryPluginChain; /** * Helper to set the next plugin proxy */ public setNext: (nextCtx:ITelemetryPluginChain) => void; /** * Call back for telemetry processing before it it is sent * @param env - This is the current event being reported * @param itemCtx - This is the context for the current request, ITelemetryPlugin instances * can optionally use this to access the current core instance or define / pass additional information * to later plugins (vs appending items to the telemetry item) * @returns boolean (true) if there is no more plugins to process otherwise false or undefined (void) */ public processNext: (env: ITelemetryItem) => boolean | void; /** * Synchronously iterate over the context chain running the callback for each plugin, once * every plugin has been executed via the callback, any associated onComplete will be called. * @param callback - The function call for each plugin in the context chain */ public iterate: <T extends ITelemetryPlugin = ITelemetryPlugin>(callback: (plugin: T) => void) => void; /** * Create a new context using the core and config from the current instance * @param plugins - The execution order to process the plugins, if null or not supplied * then the current execution order will be copied. * @param startAt - The plugin to start processing from, if missing from the execution * order then the next plugin will be NOT set. */ public createNew: (plugins?:IPlugin[]|ITelemetryPluginChain, startAt?:IPlugin) => IProcessTelemetryContext; /** * Set the function to call when the current chain has executed all processNext or unloadNext items. */ public onComplete: (onComplete: () => void) => void; /** * Creates a new Telemetry Item context with the current config, core and plugin execution chain * @param plugins - The plugin instances that will be executed * @param config - The current config * @param core - The current core instance */ constructor(pluginChain: ITelemetryPluginChain, config: IConfiguration, core: IAppInsightsCore, startAt?:IPlugin) { let _self = this; let context = createProcessTelemetryContext(pluginChain, config, core, startAt); // Proxy all functions of the context to this object proxyFunctions(_self, context, objKeys(context) as any); } }
the_stack
import { BalancedLoadBalancingStrategy } from "../../src/loadBalancerStrategies/balancedStrategy"; import { GreedyLoadBalancingStrategy } from "../../src/loadBalancerStrategies/greedyStrategy"; import { PartitionOwnership } from "../../src"; import { UnbalancedLoadBalancingStrategy } from "../../src/loadBalancerStrategies/unbalancedStrategy"; import chai from "chai"; import { testWithServiceTypes } from "../public/utils/testWithServiceTypes"; const should = chai.should(); testWithServiceTypes(() => { describe("LoadBalancingStrategy", () => { function createOwnershipMap( partitionToOwner: Record<string, string> ): Map<string, PartitionOwnership> { const ownershipMap = new Map<string, PartitionOwnership>(); for (const partitionId in partitionToOwner) { ownershipMap.set(partitionId, { consumerGroup: "$Default", eventHubName: "eventhubname1", fullyQualifiedNamespace: "fqdn", ownerId: partitionToOwner[partitionId], partitionId: partitionId, etag: "etag", lastModifiedTimeInMs: Date.now() }); } return ownershipMap; } describe("UnbalancedLoadBalancingStrategy", () => { it("all", () => { const m = new Map<string, PartitionOwnership>(); const lb = new UnbalancedLoadBalancingStrategy(); lb.getPartitionsToCliam("ownerId", m, ["1", "2", "3"]).should.deep.eq(["1", "2", "3"]); should.equal(m.size, 0); }); it("claim partitions we already own", () => { const m = new Map<string, PartitionOwnership>(); m.set("1", { consumerGroup: "", fullyQualifiedNamespace: "", eventHubName: "", // we already own this so we won't // try to reclaim it. ownerId: "ownerId", partitionId: "" }); m.set("2", { consumerGroup: "", fullyQualifiedNamespace: "", eventHubName: "", // owned by someone else - we'll steal this // partition ownerId: "someOtherOwnerId", partitionId: "" }); const lb = new UnbalancedLoadBalancingStrategy(); lb.getPartitionsToCliam("ownerId", m, ["1", "2", "3"]).should.deep.eq(["1", "2", "3"]); }); }); describe("BalancedLoadBalancingStrategy", () => { const lb = new BalancedLoadBalancingStrategy(1000 * 60); it("odd number of partitions per processor", () => { const allPartitions = ["0", "1", "2"]; // at this point 'a' has it's fair share of partitions (there are 3 total) // and it's okay to have 1 extra. let partitionsToOwn = lb.getPartitionsToCliam( "a", createOwnershipMap({ "1": "b", "2": "a", "3": "a" }), allPartitions ); partitionsToOwn.sort(); partitionsToOwn.should.be.deep.equal( [], "we've gotten our fair share, shouldn't claim anything new" ); // now the other side of this is when we're fighting for the ownership of an // extra partition partitionsToOwn = lb.getPartitionsToCliam( "a", createOwnershipMap({ "1": "b", "2": "a" }), allPartitions ); partitionsToOwn.sort(); partitionsToOwn.should.be.deep.equal( ["0"], "we had our minimum fair share (1) but there's still one extra (uneven number of partitions per processor) and we should snag it" ); }); it("even number of partitions per processor", () => { const allPartitions = ["0", "1", "2", "3"]; // at this point 'a' has it's fair share of partitions (there are 4 total) // so it'll stop claiming additional partitions. let partitionsToOwn = lb.getPartitionsToCliam( "a", createOwnershipMap({ "1": "b", "2": "a", "3": "a" }), allPartitions ); partitionsToOwn.sort(); partitionsToOwn.should.be.deep.equal( [], "we've gotten our fair share, shouldn't claim anything new" ); partitionsToOwn = lb.getPartitionsToCliam( "a", createOwnershipMap({ "0": "b", "1": "b", "2": "a", "3": "a" }), allPartitions ); partitionsToOwn.sort(); partitionsToOwn.should.be.deep.equal([], "load is balanced, won't grab any more."); }); // when there are no freely available partitions (partitions that have either expired or are literally unowned) // we'll need to steal from an existing processor. // This can happen in a few ways: // 1. we were simply racing against other processors // 2. we're coming in later after all partitions have been allocated (ie, scaling out) // 3. timing issues, death of a processor, etc... it("stealing", () => { // something like this could happen if 'a' were just the only processor // and now we're spinning up 'b' let partitionsToOwn = lb.getPartitionsToCliam( "b", createOwnershipMap({ "0": "a", "1": "a", "2": "a" }), ["0", "1", "2"] ); partitionsToOwn.sort(); // we'll attempt to steal a partition from 'a'. partitionsToOwn.length.should.equal( 1, "stealing with an odd number of partitions per processor" ); // and now the same case as above, but with an even number of partitions per processor. partitionsToOwn = lb.getPartitionsToCliam( "b", createOwnershipMap({ "0": "a", "1": "a", "2": "a", "3": "a" }), ["0", "1", "2", "3"] ); partitionsToOwn.sort(); // we'll attempt to steal a partition from 'a'. partitionsToOwn.length.should.equal( 1, "stealing with an even number of partitions per processor" ); }); it("don't steal when you can just wait", () => { // @chradek's case: let's say we have this partition layout: // AAAABBBCCD // // Before, we'd let 'C' steal from 'A' - we see that we don't have enough // +1 processors(exact match) and so 'C' attempts to become one. This can // lead to some unnecessary thrash as 'A' loses partitions to a processor // that has technically already met it's quota. // // Instead, we treat 'A' is a +1-ish specifically for when we ('C') // are checking if we want to grab more partitions. // // This allows 'A' to just naturally decline as _actual_ processors grab // their minimum required partitions rather than forcing it and possibly // having a partition have to juggle between partitions as they try to // meet the minimum. const partitions = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; const lbs = new BalancedLoadBalancingStrategy(1000 * 60); // we'll do 4 consumers const initialOwnershipMap = createOwnershipMap({ "0": "a", "1": "a", "2": "a", "3": "a", "4": "b", "5": "b", "6": "b", "7": "c", "8": "c", "9": "d" }); const requestedPartitions = lbs.getPartitionsToCliam("c", initialOwnershipMap, partitions); requestedPartitions.sort(); requestedPartitions.should.deep.equal( [], "c will not steal one partition since it sees that, eventually, 'a' will lose its partitions and become a +1 processor on it's own" ); }); it("avoid thrash", () => { // this is a case where we shouldn't steal - we have // the minimum number of partitions and stealing at this // point will just keep thrashing both processors. const partitionsToOwn = lb.getPartitionsToCliam( "b", createOwnershipMap({ "0": "a", "1": "b", "2": "a" }), ["0", "1", "2"] ); partitionsToOwn.sort(); partitionsToOwn.should.deep.equal([], "should not re-steal when things are balanced"); }); it("general cases", () => { const allPartitions = ["0", "1", "2", "3"]; // in the presence of no owners we claim a random partition let partitionsToOwn = lb.getPartitionsToCliam("a", createOwnershipMap({}), allPartitions); partitionsToOwn.length.should.be.equal(1, "nothing is owned, claim one"); // if there are other owners we should claim up to #partitions/#owners partitionsToOwn = lb.getPartitionsToCliam( "a", createOwnershipMap({ "1": "b", "3": "a" }), allPartitions ); partitionsToOwn.length.should.be.equal(1, "1 and 1 with another owner, should claim one"); // better not try to claim 'b's partition when there are unowned partitions partitionsToOwn.filter((p) => p === "1").length.should.equal(0); // 'b' should claim the last unowned partition partitionsToOwn = lb.getPartitionsToCliam( "b", createOwnershipMap({ "1": "b", "2": "a", "3": "a" }), allPartitions ); partitionsToOwn.sort(); partitionsToOwn.should.be.deep.equal(["0"], "b grabbed the last available partition"); // we're balanced - processors now only grab the partitions that they own partitionsToOwn = lb.getPartitionsToCliam( "b", createOwnershipMap({ "0": "b", "1": "a", "2": "b", "3": "a" }), allPartitions ); partitionsToOwn.sort(); partitionsToOwn.should.be.deep.equal([], "balanced: b should not grab anymore partitions"); }); it("honors the partitionOwnershipExpirationIntervalInMs", () => { const intervalInMs = 1000; const lbs = new BalancedLoadBalancingStrategy(intervalInMs); const allPartitions = ["0", "1"]; const ownershipMap = createOwnershipMap({ "0": "b", "1": "a" }); // At this point, 'a' has its fair share of partitions, and none should be returned. let partitionsToOwn = lbs.getPartitionsToCliam("a", ownershipMap, allPartitions); partitionsToOwn.length.should.equal(0, "Expected to not claim any new partitions."); // Change the ownership of partition "0" so it is older than the interval. const ownership = ownershipMap.get("0")!; ownership.lastModifiedTimeInMs = Date.now() - (intervalInMs + 1); // Add 1 to the interval to ensure it has just expired. partitionsToOwn = lbs.getPartitionsToCliam("a", ownershipMap, allPartitions); partitionsToOwn.should.deep.equal(["0"]); }); }); describe("GreedyLoadBalancingStrategy", () => { const lb = new GreedyLoadBalancingStrategy(1000 * 60); it("odd number of partitions per processor", () => { const allPartitions = ["0", "1", "2"]; // at this point 'a' has it's fair share of partitions (there are 3 total) // and it's okay to have 1 extra. let partitionsToOwn = lb.getPartitionsToCliam( "a", createOwnershipMap({ "1": "b", "2": "a", "3": "a" }), allPartitions ); partitionsToOwn.sort(); partitionsToOwn.should.be.deep.equal( [], "we've gotten our fair share, shouldn't claim anything new" ); // now the other side of this is when we're fighting for the ownership of an // extra partition partitionsToOwn = lb.getPartitionsToCliam( "a", createOwnershipMap({ "1": "b", "2": "a" }), allPartitions ); partitionsToOwn.sort(); partitionsToOwn.should.be.deep.equal( ["0"], "we had our minimum fair share (1) but there's still one extra (uneven number of partitions per processor) and we should snag it" ); }); it("even number of partitions per processor", () => { const allPartitions = ["0", "1", "2", "3"]; // at this point 'a' has it's fair share of partitions (there are 4 total) // so it'll stop claiming additional partitions. let partitionsToOwn = lb.getPartitionsToCliam( "a", createOwnershipMap({ "1": "b", "2": "a", "3": "a" }), allPartitions ); partitionsToOwn.sort(); partitionsToOwn.should.be.deep.equal( [], "we've gotten our fair share, shouldn't claim anything new" ); partitionsToOwn = lb.getPartitionsToCliam( "a", createOwnershipMap({ "0": "b", "1": "b", "2": "a", "3": "a" }), allPartitions ); partitionsToOwn.sort(); partitionsToOwn.should.be.deep.equal([], "load is balanced, won't grab any more."); }); // when there are no freely available partitions (partitions that have either expired or are literally unowned) // we'll need to steal from an existing processor. // This can happen in a few ways: // 1. we were simply racing against other processors // 2. we're coming in later after all partitions have been allocated (ie, scaling out) // 3. timing issues, death of a processor, etc... it("stealing", () => { // something like this could happen if 'a' were just the only processor // and now we're spinning up 'b' let partitionsToOwn = lb.getPartitionsToCliam( "b", createOwnershipMap({ "0": "a", "1": "a", "2": "a" }), ["0", "1", "2"] ); partitionsToOwn.sort(); // we'll attempt to steal a partition from 'a'. partitionsToOwn.length.should.equal( 1, "stealing with an odd number of partitions per processor" ); // and now the same case as above, but with an even number of partitions per processor. partitionsToOwn = lb.getPartitionsToCliam( "b", createOwnershipMap({ "0": "a", "1": "a", "2": "a", "3": "a" }), ["0", "1", "2", "3"] ); partitionsToOwn.sort(); // we'll attempt to steal a partition from 'a'. partitionsToOwn.length.should.equal( 2, "stealing with an even number of partitions per processor" ); }); it("claims unowned then steals", () => { const allPartitions = []; for (let i = 0; i < 8; i++) { allPartitions.push(`${i}`); } const partitionsToOwn = lb.getPartitionsToCliam( "a", createOwnershipMap({ "0": "", // skip 1, 2 "3": "b", "4": "b", "5": "b", "6": "b", "7": "b" }), allPartitions ); partitionsToOwn.sort(); // "a" should have 4 partitions in order to be balanced. // Partitions "0", "1", "2" should be chosen before any are stolen. partitionsToOwn.length.should.equal(4, "should have claimed half of the partitions."); partitionsToOwn .slice(0, 3) .should.deep.equal(["0", "1", "2"], "should have claimed unclaimed partitions first."); }); it("don't steal when you can just wait", () => { // @chradek's case: let's say we have this partition layout: // AAAABBBCCD // // Before, we'd let 'C' steal from 'A' - we see that we don't have enough // +1 processors(exact match) and so 'C' attempts to become one. This can // lead to some unnecessary thrash as 'A' loses partitions to a processor // that has technically already met it's quota. // // Instead, we treat 'A' is a +1-ish specifically for when we ('C') // are checking if we want to grab more partitions. // // This allows 'A' to just naturally decline as _actual_ processors grab // their minimum required partitions rather than forcing it and possibly // having a partition have to juggle between partitions as they try to // meet the minimum. const partitions = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; const lbs = new BalancedLoadBalancingStrategy(1000 * 60); // we'll do 4 consumers const initialOwnershipMap = createOwnershipMap({ "0": "a", "1": "a", "2": "a", "3": "a", "4": "b", "5": "b", "6": "b", "7": "c", "8": "c", "9": "d" }); const requestedPartitions = lbs.getPartitionsToCliam("c", initialOwnershipMap, partitions); requestedPartitions.sort(); requestedPartitions.should.deep.equal( [], "c will not steal one partition since it sees that, eventually, 'a' will lose its partitions and become a +1 processor on it's own" ); }); it("avoid thrash", () => { // this is a case where we shouldn't steal - we have // the minimum number of partitions and stealing at this // point will just keep thrashing both processors. const partitionsToOwn = lb.getPartitionsToCliam( "b", createOwnershipMap({ "0": "a", "1": "b", "2": "a" }), ["0", "1", "2"] ); partitionsToOwn.sort(); partitionsToOwn.should.deep.equal([], "should not re-steal when things are balanced"); }); it("general cases", () => { const allPartitions = ["0", "1", "2", "3"]; // in the presence of no owners we claim a random partition let partitionsToOwn = lb.getPartitionsToCliam("a", createOwnershipMap({}), allPartitions); partitionsToOwn.length.should.be.equal(4, "nothing is owned, claim all"); // if there are other owners we should claim up to #partitions/#owners partitionsToOwn = lb.getPartitionsToCliam( "a", createOwnershipMap({ "1": "b", "3": "a" }), allPartitions ); partitionsToOwn.length.should.be.equal(1, "1 and 1 with another owner, should claim one"); // better not try to claim 'b's partition when there are unowned partitions partitionsToOwn.filter((p) => p === "1").length.should.equal(0); // 'b' should claim the last unowned partition partitionsToOwn = lb.getPartitionsToCliam( "b", createOwnershipMap({ "1": "b", "2": "a", "3": "a" }), allPartitions ); partitionsToOwn.sort(); partitionsToOwn.should.be.deep.equal(["0"], "b grabbed the last available partition"); // we're balanced - processors now only grab the partitions that they own partitionsToOwn = lb.getPartitionsToCliam( "b", createOwnershipMap({ "0": "b", "1": "a", "2": "b", "3": "a" }), allPartitions ); partitionsToOwn.sort(); partitionsToOwn.should.be.deep.equal([], "balanced: b should not grab anymore partitions"); }); it("honors the partitionOwnershipExpirationIntervalInMs", () => { const intervalInMs = 1000; const lbs = new GreedyLoadBalancingStrategy(intervalInMs); const allPartitions = ["0", "1", "2", "3"]; const ownershipMap = createOwnershipMap({ "0": "b", "1": "a" }); // At this point, "a" should only grab 1 partition since both "a" and "b" should end up with 2 partitions each. let partitionsToOwn = lbs.getPartitionsToCliam("a", ownershipMap, allPartitions); partitionsToOwn.length.should.equal(1, "Expected to claim 1 new partitions."); // Change the ownership of partition "0" so it is older than the interval. const ownership = ownershipMap.get("0")!; ownership.lastModifiedTimeInMs = Date.now() - (intervalInMs + 1); // Add 1 to the interval to ensure it has just expired. // At this point, "a" should grab partitions 0, 2, and 3. // This is because "b" only owned 1 partition and that claim is expired, // so "a" as treated as if it is the only owner. partitionsToOwn = lbs.getPartitionsToCliam("a", ownershipMap, allPartitions); partitionsToOwn.sort(); partitionsToOwn.should.deep.equal(["0", "2", "3"]); }); }); }); });
the_stack
import { dependentKeyCompat } from '@ember/object/compat'; import { DEBUG } from '@glimmer/env'; import { cached, tracked } from '@glimmer/tracking'; import { resolve } from 'rsvp'; import type { ManyRelationship } from '@ember-data/record-data/-private'; import { assertPolymorphicType } from '@ember-data/store/-debug'; import { CollectionResourceDocument, ExistingResourceObject, SingleResourceDocument, } from '../../ts-interfaces/ember-data-json-api'; import { StableRecordIdentifier } from '../../ts-interfaces/identifier'; import CoreStore from '../core-store'; import { NotificationType, unsubscribe } from '../record-notification-manager'; import { internalModelFactoryFor, recordIdentifierFor } from '../store/internal-model-factory'; import RecordReference from './record'; import Reference, { internalModelForReference } from './reference'; /** @module @ember-data/store */ /** A `HasManyReference` is a low-level API that allows users and addon authors to perform meta-operations on a has-many relationship. @class HasManyReference @public @extends Reference */ export default class HasManyReference extends Reference { declare key: string; declare hasManyRelationship: ManyRelationship; declare type: string; declare parent: RecordReference; declare parentIdentifier: StableRecordIdentifier; // unsubscribe tokens given to us by the notification manager #token!: Object; #relatedTokenMap!: Map<StableRecordIdentifier, Object>; @tracked _ref = 0; constructor( store: CoreStore, parentIdentifier: StableRecordIdentifier, hasManyRelationship: ManyRelationship, key: string ) { super(store, parentIdentifier); this.key = key; this.hasManyRelationship = hasManyRelationship; this.type = hasManyRelationship.definition.type; this.parent = internalModelFactoryFor(store).peek(parentIdentifier)!.recordReference; this.#token = store._notificationManager.subscribe( parentIdentifier, (_: StableRecordIdentifier, bucket: NotificationType, notifiedKey?: string) => { if ((bucket === 'relationships' || bucket === 'property') && notifiedKey === key) { this._ref++; } } ); this.#relatedTokenMap = new Map(); // TODO inverse } destroy() { unsubscribe(this.#token); this.#relatedTokenMap.forEach((token) => { unsubscribe(token); }); this.#relatedTokenMap.clear(); } @cached @dependentKeyCompat get _relatedIdentifiers(): StableRecordIdentifier[] { this._ref; // consume the tracked prop let resource = this._resource(); this.#relatedTokenMap.forEach((token) => { unsubscribe(token); }); this.#relatedTokenMap.clear(); if (resource && resource.data) { return resource.data.map((resourceIdentifier) => { const identifier = this.store.identifierCache.getOrCreateRecordIdentifier(resourceIdentifier); const token = this.store._notificationManager.subscribe( identifier, (_: StableRecordIdentifier, bucket: NotificationType, notifiedKey?: string) => { if (bucket === 'identity' || ((bucket === 'attributes' || bucket === 'property') && notifiedKey === 'id')) { this._ref++; } } ); this.#relatedTokenMap.set(identifier, token); return identifier; }); } return []; } _resource() { return this.recordData.getHasMany(this.key); } /** This returns a string that represents how the reference will be looked up when it is loaded. If the relationship has a link it will use the "link" otherwise it defaults to "id". Example ```app/models/post.js import Model, { hasMany } from '@ember-data/model'; export default class PostModel extends Model { @hasMany({ async: true }) comments; } ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); // get the identifier of the reference if (commentsRef.remoteType() === "ids") { let ids = commentsRef.ids(); } else if (commentsRef.remoteType() === "link") { let link = commentsRef.link(); } ``` @method remoteType @public @return {String} The name of the remote type. This should either be `link` or `ids` */ remoteType(): 'link' | 'ids' { let value = this._resource(); if (value && value.links && value.links.related) { return 'link'; } return 'ids'; } /** `ids()` returns an array of the record IDs in this relationship. Example ```app/models/post.js import Model, { hasMany } from '@ember-data/model'; export default class PostModel extends Model { @hasMany({ async: true }) comments; } ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); commentsRef.ids(); // ['1'] ``` @method ids @public @return {Array} The ids in this has-many relationship */ ids(): Array<string | null> { return this._relatedIdentifiers.map((identifier) => identifier.id); } /** `push` can be used to update the data in the relationship and Ember Data will treat the new data as the canonical value of this relationship on the backend. Example ```app/models/post.js import Model, { hasMany } from '@ember-data/model'; export default class PostModel extends Model { @hasMany({ async: true }) comments; } ``` ``` let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); commentsRef.ids(); // ['1'] commentsRef.push([ [{ type: 'comment', id: 2 }], [{ type: 'comment', id: 3 }], ]) commentsRef.ids(); // ['2', '3'] ``` @method push @public @param {Array|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship. @return {ManyArray} */ async push( objectOrPromise: ExistingResourceObject[] | CollectionResourceDocument | { data: SingleResourceDocument[] } ): Promise<any> { const payload = await resolve(objectOrPromise); let array: Array<ExistingResourceObject | SingleResourceDocument>; if (!Array.isArray(payload) && typeof payload === 'object' && Array.isArray(payload.data)) { array = payload.data; } else { array = payload as ExistingResourceObject[]; } const internalModel = internalModelForReference(this)!; const { store } = this; let identifiers = array.map((obj) => { let record; if ('data' in obj) { // TODO deprecate pushing non-valid JSON:API here record = store.push(obj); } else { record = store.push({ data: obj }); } if (DEBUG) { let relationshipMeta = this.hasManyRelationship.definition; let identifier = this.hasManyRelationship.identifier; assertPolymorphicType(identifier, relationshipMeta, recordIdentifierFor(record), store); } return recordIdentifierFor(record); }); const { graph, identifier } = this.hasManyRelationship; store._backburner.join(() => { graph.push({ op: 'replaceRelatedRecords', record: identifier, field: this.key, value: identifiers, }); }); // TODO IGOR it seems wrong that we were returning the many array here return internalModel.getHasMany(this.key); } _isLoaded() { let hasRelationshipDataProperty = this.hasManyRelationship.state.hasReceivedData; if (!hasRelationshipDataProperty) { return false; } let members = this.hasManyRelationship.currentState; //TODO Igor cleanup return members.every((identifier) => { let internalModel = this.store._internalModelForResource(identifier); return internalModel.currentState.isLoaded === true; }); } /** `value()` synchronously returns the current value of the has-many relationship. Unlike `record.get('relationshipName')`, calling `value()` on a reference does not trigger a fetch if the async relationship is not yet loaded. If the relationship is not loaded it will always return `null`. Example ```app/models/post.js import Model, { hasMany } from '@ember-data/model'; export default class PostModel extends Model { @hasMany({ async: true }) comments; } ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); post.get('comments').then(function(comments) { commentsRef.value() === comments }) ``` @method value @public @return {ManyArray} */ value() { let internalModel = internalModelForReference(this)!; if (this._isLoaded()) { return internalModel.getManyArray(this.key); } return null; } /** Loads the relationship if it is not already loaded. If the relationship is already loaded this method does not trigger a new load. This causes a request to the specified relationship link or reloads all items currently in the relationship. Example ```app/models/post.js import Model, { hasMany } from '@ember-data/model'; export default class PostModel extends Model { @hasMany({ async: true }) comments; } ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); commentsRef.load().then(function(comments) { //... }); ``` You may also pass in an options object whose properties will be fed forward. This enables you to pass `adapterOptions` into the request given to the adapter via the reference. Example ```javascript commentsRef.load({ adapterOptions: { isPrivate: true } }) .then(function(comments) { //... }); ``` ```app/adapters/comment.js export default ApplicationAdapter.extend({ findMany(store, type, id, snapshots) { // In the adapter you will have access to adapterOptions. let adapterOptions = snapshots[0].adapterOptions; } }); ``` @method load @public @param {Object} options the options to pass in. @return {Promise} a promise that resolves with the ManyArray in this has-many relationship. */ load(options) { let internalModel = internalModelForReference(this)!; return internalModel.getHasMany(this.key, options); } /** Reloads this has-many relationship. This causes a request to the specified relationship link or reloads all items currently in the relationship. Example ```app/models/post.js import Model, { hasMany } from '@ember-data/model'; export default class PostModel extends Model { @hasMany({ async: true }) comments; } ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); commentsRef.reload().then(function(comments) { //... }); ``` You may also pass in an options object whose properties will be fed forward. This enables you to pass `adapterOptions` into the request given to the adapter via the reference. A full example can be found in the `load` method. Example ```javascript commentsRef.reload({ adapterOptions: { isPrivate: true } }) ``` @method reload @public @param {Object} options the options to pass in. @return {Promise} a promise that resolves with the ManyArray in this has-many relationship. */ reload(options) { let internalModel = internalModelForReference(this)!; return internalModel.reloadHasMany(this.key, options); } }
the_stack
import { GameProps, Texture, Device, DeviceSize, Context } from "@replay/core"; import { replayCore, ReplayPlatform } from "@replay/core/dist/core"; import { CustomSprite, makeSprite, Sprite } from "@replay/core/dist/sprite"; import { TextTexture } from "@replay/core/dist/t"; import { getParentCoordsForSprite } from "./coords"; import { NativeSpriteMock } from "./nativeSpriteMock"; import { AssetMap } from "@replay/core/dist/device"; interface Timer { id: string; callback: () => void; timeRemainingMs: number; isPaused: boolean; } export interface TestSpriteOptions<I> { initInputs?: I; /** * A mapping function to adjust an input's (x, y) coordinate to its relative * value within a Sprite */ mapInputCoordinates?: ( globalToLocalCoords: (globalCoords: { x: number; y: number; }) => { x: number; y: number; }, inputs: I ) => I; /** * Array of tuples of context and the value to inject */ contexts?: ContextTuple<any>[]; /** * Same as setRandomNumbers but for init call */ initRandom?: number[]; /** * Set device size */ size?: DeviceSize; /** * Set initial storage value */ initStore?: Record<string, string | undefined>; /** * Mock responses for url by request type */ networkResponses?: { get?: { [url: string]: () => unknown; }; put?: { [url: string]: (body: unknown) => unknown; }; post?: { [url: string]: (body: unknown) => unknown; }; delete?: { [url: string]: () => unknown; }; }; /** * For ok / cancel alert, which choice is chosen. Default true (OK). */ initAlertResponse?: boolean; /** * A list of Native Sprite names to mock */ nativeSpriteNames?: string[]; /** * Test as a touch screen? * * @default false */ isTouchScreen?: boolean; /** * Should errors be thrown if an asset isn't loaded? * * @default true */ throwAssetErrors?: boolean; } interface TestSpriteUtils<I> { nextFrame: () => void; jumpToFrame: ( condition: () => boolean | Texture, maxFrames?: number ) => Promise<void>; setRandomNumbers: (numbers: number[]) => void; updateInputs: (newInputs: I) => void; getTextures: () => Texture[]; getTexture: (testId: string) => Texture; textureExists: (testId: string) => boolean; getByText: (text: string) => TextTexture[]; log: jest.Mock<any, any>; resolvePromises: () => Promise<void>; audio: { getPosition: jest.Mock<number>; play: jest.Mock<any, any>; pause: jest.Mock<any, any>; getStatus: jest.Mock<string>; getVolume: jest.Mock<number>; setVolume: jest.Mock<any, [string, number]>; getDuration: jest.Mock<number>; }; network: { get: jest.Mock<any, [string, (data: unknown) => void]>; post: jest.Mock<any, [string, unknown, (data: unknown) => void]>; put: jest.Mock<any, [string, unknown, (data: unknown) => void]>; delete: jest.Mock<any, [string, (data: unknown) => void]>; }; store: Record<string, string | undefined>; alert: { ok: jest.Mock<any, [string, (() => void) | undefined]>; okCancel: jest.Mock<any, [string, (wasOk: boolean) => void]>; }; updateAlertResponse: (isOk: boolean) => void; clipboard: { copy: jest.Mock<any, [string, (error?: Error | undefined) => void]>; }; } /** * `testSprite` provides a way of testing your gameplay with helper functions to * play and record the game. */ export function testSprite<P, S, I>( sprite: CustomSprite<P, S, I>, gameProps: GameProps, options: TestSpriteOptions<I> = {} ): TestSpriteUtils<I> { const { initInputs = {} as I, contexts: contextTuples = [], initRandom = [0.5], size = { width: "width" in gameProps.size ? gameProps.size.width : gameProps.size.landscape.width, height: "height" in gameProps.size ? gameProps.size.height : gameProps.size.landscape.height, widthMargin: 0, heightMargin: 0, deviceWidth: 1000, deviceHeight: 500, }, initStore = {}, networkResponses = {}, mapInputCoordinates = (_, inputs) => inputs, initAlertResponse = true, nativeSpriteNames = [], isTouchScreen = false, throwAssetErrors = true, } = options; /** * Mock function for device log. */ const log = jest.fn(); /** * Mock functions for audio. Note the test platform will add the audio * filename as the first argument, followed by any other arguments to the * function. */ const audio = { getPosition: jest.fn((_filename: string) => 120), play: jest.fn(), pause: jest.fn(), getStatus: jest.fn((_filename: string) => "playing" as const), getVolume: jest.fn(), setVolume: jest.fn(), getDuration: jest.fn(), }; /** * Mock functions for network calls. Pass in the responses as a parameter to * testSprite. */ const network: TestSpriteUtils<I>["network"] = { get: jest.fn((url, cb) => { if (!networkResponses.get || !networkResponses.get[url]) { throw Error(`No GET response defined for url: ${url}`); } return cb(networkResponses.get[url]()); }), put: jest.fn((url, body, cb) => { if (!networkResponses.put || !networkResponses.put[url]) { throw Error(`No PUT response defined for url: ${url}`); } return cb(networkResponses.put[url](body)); }), post: jest.fn((url, body, cb) => { if (!networkResponses.post || !networkResponses.post[url]) { throw Error(`No POST response defined for url: ${url}`); } return cb(networkResponses.post[url](body)); }), delete: jest.fn((url, cb) => { if (!networkResponses.delete || !networkResponses.delete[url]) { throw Error(`No DELETE response defined for url: ${url}`); } return cb(networkResponses.delete[url]()); }), }; const okCancelValue = { ref: initAlertResponse }; /** * Mock functions for alerts. */ const alert: TestSpriteUtils<I>["alert"] = { ok: jest.fn((_, onResponse) => { onResponse?.(); }), okCancel: jest.fn((_, onResponse) => { onResponse(okCancelValue.ref); }), }; /** * Update whether okCancel alert chooses ok or cancel */ function updateAlertResponse(isOk: boolean) { okCancelValue.ref = isOk; } /** * Mock functions for clipboard. */ const clipboard: TestSpriteUtils<I>["clipboard"] = { copy: jest.fn((_, onComplete) => { onComplete(); }), }; let inputs: I = { ...initInputs }; /** * Update the current input state in the game. */ function updateInputs(newInputs: I) { inputs = { ...newInputs }; } /** * How far game has progressed in milliseconds within tests, calculated by * assuming callback is called at 60 FPS. */ let gameTime = 0.01; const randomNumbers = initRandom; let randomIndex = 0; /** * An array of random numbers the game will loop through, to ensure * predictability in random parts of gameplay. By default, all random numbers * will be 0.5. */ function setRandomNumbers(numbers: number[]) { randomNumbers.length = 0; numbers.forEach((n) => { randomNumbers.push(n); }); randomIndex = 0; } const random = () => { const randomNumber = randomNumbers[randomIndex]; randomIndex += 1; if (randomIndex === randomNumbers.length) { randomIndex = 0; } return randomNumber; }; const audioFn: Device["audio"] = (filename) => { if (throwAssetErrors) { const audioElement = audioElements[filename]; if (!audioElement) { throw Error(`Audio file "${filename}" was not preloaded`); } const { data } = audioElements[filename]; if ("then" in data) { throw Error( `Audio file "${filename}" did not finish loading before it was used` ); } } return { getPosition: () => audio.getPosition(filename), play: (fromPositionOrSettings) => { if (fromPositionOrSettings === undefined) { audio.play(filename); } else { audio.play(filename, fromPositionOrSettings); } }, pause: () => audio.pause(filename), getStatus: () => audio.getStatus(filename), getVolume: () => audio.getVolume(filename), setVolume: (volume) => audio.setVolume(filename, volume), getDuration: () => audio.getDuration(filename), }; }; const timer: Device["timer"] = { start: (callback, ms) => { // Get a unique ID let id = ""; let i = timers.length; while (!id || timers.map((t) => t.id).includes(id)) { i++; id = `ID00${i}`; } timers.push({ id, callback, timeRemainingMs: ms, isPaused: false, }); return id; }, pause: (id) => { const timer = timers.find((t) => t.id === id); if (!timer) return; timer.isPaused = true; }, resume: (id) => { const timer = timers.find((t) => t.id === id); if (!timer) return; timer.isPaused = false; }, cancel: (id) => { const timerIndex = timers.findIndex((t) => t.id === id); if (timerIndex === -1) return; timers.splice(timerIndex, 1); }, }; const store = { ...initStore }; const storage: Device["storage"] = { getItem(key) { return Promise.resolve(store[key] ?? null); }, setItem(key, value) { return Promise.resolve().then(() => { if (value === null) { delete store[key]; return; } store[key] = value; }); }, }; const textures: Texture[] = []; const timers: Timer[] = []; /** * Resolve promises such as `preloadFiles` and storage. */ const resolvePromises = () => new Promise(setImmediate); const audioElements: AssetMap<Record<string, string>> = {}; const imageElements: AssetMap<Record<string, string>> = {}; type Pos = { x: number; y: number; rotation: number }; /** * Keep a stack of functions mapping local to global coords */ const getPosStack: ((localCoords: Pos) => Pos)[] = []; const testPlatform: ReplayPlatform<I> = { getInputs: (globalToLocalCoords) => mapInputCoordinates(globalToLocalCoords, inputs), mutDevice: { isTouchScreen, size, log, random, timer, now: () => new Date(Date.UTC(2000, 1, 1)), audio: audioFn, assetUtils: { audioElements, imageElements, loadAudioFile: (fileName) => { return Promise.resolve().then(() => { return { [fileName]: "*audioData*" }; }); }, loadImageFile: (fileName) => { return Promise.resolve().then(() => { return { [fileName]: "*imageData*" }; }); }, cleanupAudioFile: () => null, cleanupImageFile: () => null, }, network, storage, alert, clipboard, }, render: { newFrame: () => { textures.length = 0; }, startRenderSprite: (baseProps) => { const getParentCoords = getParentCoordsForSprite(baseProps); const getParentPos = ({ x, y, rotation }: Pos) => ({ ...getParentCoords({ x, y }), rotation: rotation + baseProps.rotation, }); getPosStack.unshift(getParentPos); }, endRenderSprite: () => { getPosStack.shift(); }, renderTexture: (texture) => { if ( throwAssetErrors && (texture.type === "image" || texture.type === "spriteSheet") ) { const fileName = texture.props.fileName; const imageElement = imageElements[fileName]; if (!imageElement) { throw Error(`Image file "${fileName}" was not preloaded`); } if ("then" in imageElement.data) { throw Error( `Image file "${fileName}" did not finish loading before it was used` ); } } // Go through all functions mapping position const { x, y, rotation } = getPosStack.reduce( (pos, posFn) => posFn(pos), texture.props as Pos ); textures.push({ ...texture, props: { ...texture.props, x: Math.round(x), y: Math.round(y), rotation: Math.round(rotation), }, } as Texture); }, }, }; const TestContainer = makeSprite<GameProps>({ render() { return [ // Wrap sprite with contexts passed in options contextTuples.reduce<Sprite>((prevSprite, [context, contextValue]) => { return context.Sprite({ context: contextValue, sprites: [prevSprite], }); }, sprite), ]; }, }); const { runNextFrame } = replayCore( testPlatform, { // Mock the Native Sprites passed in to avoid errors when looked up nativeSpriteMap: nativeSpriteNames.reduce( (map, name) => ({ ...map, [name]: NativeSpriteMock }), {} ), nativeSpriteUtils: { scale: 1, didResize: false, gameXToPlatformX: (x) => x, gameYToPlatformY: (y) => y, }, }, TestContainer(gameProps) ); function checkTimers() { // remove timer and call callback if its time is reached const removeIndexes: number[] = []; timers.forEach((timer, i) => { if (!timer.isPaused) { timer.timeRemainingMs -= 1000 / 60; if (timer.timeRemainingMs <= 0) { timer.callback(); removeIndexes.push(i); } } }); removeIndexes.forEach((i) => { timers.splice(i, 1); }); } /** * Synchronously progress to the next frame of the game. */ function nextFrame() { gameTime += 1000 / 60; checkTimers(); runNextFrame(gameTime, jest.fn()); } /** * Asynchronously progress frames of the game until condition is met and no * errors are thrown. Condition can also return a Texture (useful for throwing * methods like `getTexture`). Rejects if 30 gameplay seconds (1800 frames) * pass and condition not met / still errors. * * Note that this will run at almost synchronous speed, but doesn't block the * event loop. */ async function jumpToFrame( condition: () => boolean | Texture, maxFrames = 1800 ) { let lastErrorMsg: string | null = null; // Keep this for improved error stack reporting const stackObj: Error = {} as Error; Error.captureStackTrace(stackObj); await new Promise<void>((res, rej) => { let i = 0; function loop() { nextFrame(); try { if (condition()) { res(); return; } } catch (e) { lastErrorMsg = (e as Error)?.message; // continue trying } i++; if (i < maxFrames) { setImmediate(loop); return; } let errMessage = `Timeout of ${Math.round( maxFrames / 60 )} gameplay seconds reached on jumpToFrame`; if (lastErrorMsg) { errMessage += ` with error:\n\n${lastErrorMsg}`; } const error = new Error(errMessage); // Only keep stack trace relevant to user's test code error.stack = removeStackLines( stackObj.stack || "", "at jumpToFrame (" ); rej(error); } loop(); }); } function getTextures() { return textures; } /** * Get a texture with matching test id. If multiple textures found, return the * first one. Throws if no matches found. */ function getTexture(testId: string) { const match = textures.find((texture) => texture.props.testId === testId); if (!match) { throw Error(`No textures found with test id "${testId}"`); } return match; } /** * Test if a texture exists, useful for checking if a texture has spawned or is * removed. */ function textureExists(testId: string) { try { getTexture(testId); return true; } catch (e) { return false; } } function isTextTexture(texture: Texture): texture is TextTexture { return texture.type === "text"; } /** * Get an array of text textures which include text content. Case insensitive. * Returns empty array if no matches found. */ function getByText(text: string) { return textures .filter(isTextTexture) .filter((texture) => texture.props.text.toLowerCase().includes(text.toLowerCase()) ); } return { nextFrame, jumpToFrame, setRandomNumbers, updateInputs, getTextures, getTexture, textureExists, getByText, resolvePromises, log, audio, network, store, alert, updateAlertResponse, clipboard, }; } /** * Stack is of format: * ``` Error: at jumpToFrame (.../replay/packages/replay-test/src/index.ts:475:11) at Object.<anonymous> (.../replay/packages/replay-test/src/__tests__/replay-test.test.ts:506:11) ... ``` We only want lines after `at jumpToFrame` */ function removeStackLines(stack: string, removeLineContaining: string) { const stackLines = stack.split("\n"); if (!stackLines) return stack; const jumpToFrameLine = stackLines.findIndex((line) => line.includes(removeLineContaining) ); if (jumpToFrameLine === -1) return stack; return [stackLines[0], ...stackLines.slice(jumpToFrameLine + 1)].join("\n"); } type ContextTuple<T> = [Context<T>, T]; export function mockContext<T>( context: Context<T>, mockValue: T ): ContextTuple<T> { return [context, mockValue]; }
the_stack
import { Shader } from './shader'; import imageVertexSource from './shaders/image-vertex.glsl'; import imageFragmentSource from './shaders/image-fragment.glsl'; import { BatchCommand } from './batch'; import { DrawCommandType, DrawImageCommand } from './draw-image-command'; import { Graphic } from '../Graphic'; import { ensurePowerOfTwo } from './webgl-util'; import { BatchRenderer } from './renderer'; import { WebGLGraphicsContextInfo } from './ExcaliburGraphicsContextWebGL'; import { TextureLoader } from './texture-loader'; import { HTMLImageSource } from './ExcaliburGraphicsContext'; import { Color } from '../../Color'; import { Vector } from '../..'; export class BatchImage extends BatchCommand<DrawImageCommand> { public textures: WebGLTexture[] = []; public commands: DrawImageCommand[] = []; private _graphicMap: { [id: string]: Graphic } = {}; constructor(public maxDraws: number, public maxTextures: number) { super(maxDraws); } isFull() { if (this.commands.length >= this.maxDraws) { return true; } if (this.textures.length >= this.maxTextures) { return true; } return false; } canAdd() { if (this.commands.length >= this.maxDraws) { return false; } if (this.textures.length < this.maxTextures) { return true; } return false; } private _isCommandFull() { return this.commands.length >= this.maxDraws; } private _isTextureFull() { return this.textures.length >= this.maxTextures; } private _wouldAddTexture(command: DrawImageCommand) { return !this._graphicMap[command.image.id]; } maybeAdd(command: DrawImageCommand): boolean { if ((this._isCommandFull() || this._isTextureFull()) && this._wouldAddTexture(command)) { return false; } this.add(command); return true; } add(command: DrawImageCommand) { if (command.type === DrawCommandType.Image) { const texture = TextureLoader.load(command.image); if (this.textures.indexOf(texture) === -1) { this.textures.push(texture); } } this.commands.push(command); } bindTextures(gl: WebGLRenderingContext) { // Bind textures in the correct order for (let i = 0; i < this.maxTextures; i++) { gl.activeTexture(gl.TEXTURE0 + i); gl.bindTexture(gl.TEXTURE_2D, this.textures[i] || this.textures[0]); } } getBatchTextureId(command: DrawImageCommand) { if (command.image) { return this.textures.indexOf(TextureLoader.get(command.image)); } return -1; } dispose() { this.clear(); return this; } clear() { this.commands.length = 0; this.textures.length = 0; this._graphicMap = {}; } } export class ImageRenderer extends BatchRenderer<DrawImageCommand> { constructor(gl: WebGLRenderingContext, private _contextInfo: WebGLGraphicsContextInfo) { super({ gl, command: DrawImageCommand, // 6 verts per quad verticesPerCommand: 6, maxCommandsPerBatch: 2000, batchFactory: () => new BatchImage(2000, gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS)) }); TextureLoader.registerContext(gl); this.init(); } buildShader(gl: WebGLRenderingContext): Shader { // Initialilze default batch rendering shader const maxGPUTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); const shader = new Shader(gl, imageVertexSource, this._transformFragmentSource(imageFragmentSource, maxGPUTextures)); shader.addAttribute('a_position', 3, gl.FLOAT); shader.addAttribute('a_texcoord', 2, gl.FLOAT); shader.addAttribute('a_textureIndex', 1, gl.FLOAT); shader.addAttribute('a_opacity', 1, gl.FLOAT); shader.addAttribute('a_color', 4, gl.FLOAT); shader.addUniformMatrix('u_matrix', this._contextInfo.matrix.data); // Initialize texture slots to [0, 1, 2, 3, 4, .... maxGPUTextures] shader.addUniformIntegerArray( 'u_textures', [...Array(maxGPUTextures)].map((_, i) => i) ); return shader; } private _transformFragmentSource(source: string, maxTextures: number): string { let newSource = source.replace('%%count%%', maxTextures.toString()); let texturePickerBuilder = ''; for (let i = 0; i < maxTextures; i++) { if (i === 0) { texturePickerBuilder += `if (v_textureIndex <= ${i}.5) {\n`; } else { texturePickerBuilder += ` else if (v_textureIndex <= ${i}.5) {\n`; } texturePickerBuilder += ` color = texture2D(u_textures[${i}], v_texcoord);\n`; texturePickerBuilder += ` }\n`; } newSource = newSource.replace('%%texture_picker%%', texturePickerBuilder); return newSource; } public addCircle(pos: Vector, radius: number, color: Color) { const command = this.commands.get().initCircle(pos, radius, color); command.applyTransform(this._contextInfo.transform.current, this._contextInfo.state.current.opacity); this.addCommand(command); } public addRectangle(color: Color, pos: Vector, width: number, height: number) { const command = this.commands.get().initRect(color, pos, width, height); command.applyTransform(this._contextInfo.transform.current, this._contextInfo.state.current.opacity); this.addCommand(command); } public addLine(color: Color, start: Vector, end: Vector, thickness = 1) { const command = this.commands.get().initLine(color, start, end, thickness); command.applyTransform(this._contextInfo.transform.current, this._contextInfo.state.current.opacity); this.addCommand(command); } public addImage( graphic: HTMLImageSource, sx: number, sy: number, swidth?: number, sheight?: number, dx?: number, dy?: number, dwidth?: number, dheight?: number ) { const command = this.commands.get().init(graphic, sx, sy, swidth, sheight, dx, dy, dwidth, dheight); command.applyTransform(this._contextInfo.transform.current, this._contextInfo.state.current.opacity); this.addCommand(command); } public renderBatch(gl: WebGLRenderingContext, batch: BatchImage, vertexCount: number) { // Bind textures in the correct order batch.bindTextures(gl); // draw the quads gl.drawArrays(gl.TRIANGLES, 0, vertexCount); } buildBatchVertices(vertexBuffer: Float32Array, batch: BatchImage): number { let vertIndex = 0; let sx: number = 0; let sy: number = 0; let sw: number = 0; let sh: number = 0; let potWidth: number = 1; let potHeight: number = 1; let textureId = 0; let commandColor = Color.Transparent; for (const command of batch.commands) { sx = command.view[0]; sy = command.view[1]; sw = command.view[2]; sh = command.view[3]; potWidth = ensurePowerOfTwo(command.image?.width || command.width); potHeight = ensurePowerOfTwo(command.image?.height || command.height); textureId = batch.getBatchTextureId(command); if (command.type === DrawCommandType.Line || command.type === DrawCommandType.Rectangle) { textureId = -1; // sentinel for no image rect commandColor = command.color; } if (command.type === DrawCommandType.Circle) { textureId = -2; // sentinel for circle commandColor = command.color; } // potential optimization when divding by 2 (bitshift) // Modifying the images to poweroftwo images warp the UV coordinates let uvx0 = sx / potWidth; let uvy0 = sy / potHeight; let uvx1 = (sx + sw) / potWidth; let uvy1 = (sy + sh) / potHeight; if (textureId === -2) { uvx0 = 0; uvy0 = 0; uvx1 = 1; uvy1 = 1; } // Quad update // (0, 0, z) z-index doesn't work in batch rendering between batches vertexBuffer[vertIndex++] = command.geometry[0][0]; // x + 0 * width; vertexBuffer[vertIndex++] = command.geometry[0][1]; //y + 0 * height; vertexBuffer[vertIndex++] = 0; // UV coords vertexBuffer[vertIndex++] = uvx0; // 0; vertexBuffer[vertIndex++] = uvy0; // 0; // texture id vertexBuffer[vertIndex++] = textureId; // opacity vertexBuffer[vertIndex++] = command.opacity; // color vertexBuffer[vertIndex++] = commandColor.r / 255; vertexBuffer[vertIndex++] = commandColor.g / 255; vertexBuffer[vertIndex++] = commandColor.b / 255; vertexBuffer[vertIndex++] = commandColor.a; // (0, 1) vertexBuffer[vertIndex++] = command.geometry[1][0]; // x + 0 * width; vertexBuffer[vertIndex++] = command.geometry[1][1]; // y + 1 * height; vertexBuffer[vertIndex++] = 0; // UV coords vertexBuffer[vertIndex++] = uvx0; // 0; vertexBuffer[vertIndex++] = uvy1; // 1; // texture id vertexBuffer[vertIndex++] = textureId; // opacity vertexBuffer[vertIndex++] = command.opacity; // color vertexBuffer[vertIndex++] = commandColor.r / 255; vertexBuffer[vertIndex++] = commandColor.g / 255; vertexBuffer[vertIndex++] = commandColor.b / 255; vertexBuffer[vertIndex++] = commandColor.a; // (1, 0) vertexBuffer[vertIndex++] = command.geometry[2][0]; // x + 1 * width; vertexBuffer[vertIndex++] = command.geometry[2][1]; // y + 0 * height; vertexBuffer[vertIndex++] = 0; // UV coords vertexBuffer[vertIndex++] = uvx1; //1; vertexBuffer[vertIndex++] = uvy0; //0; // texture id vertexBuffer[vertIndex++] = textureId; // opacity vertexBuffer[vertIndex++] = command.opacity; // color vertexBuffer[vertIndex++] = commandColor.r / 255; vertexBuffer[vertIndex++] = commandColor.g / 255; vertexBuffer[vertIndex++] = commandColor.b / 255; vertexBuffer[vertIndex++] = commandColor.a; // (1, 0) vertexBuffer[vertIndex++] = command.geometry[3][0]; // x + 1 * width; vertexBuffer[vertIndex++] = command.geometry[3][1]; // y + 0 * height; vertexBuffer[vertIndex++] = 0; // UV coords vertexBuffer[vertIndex++] = uvx1; //1; vertexBuffer[vertIndex++] = uvy0; //0; // texture id vertexBuffer[vertIndex++] = textureId; // opacity vertexBuffer[vertIndex++] = command.opacity; // color vertexBuffer[vertIndex++] = commandColor.r / 255; vertexBuffer[vertIndex++] = commandColor.g / 255; vertexBuffer[vertIndex++] = commandColor.b / 255; vertexBuffer[vertIndex++] = commandColor.a; // (0, 1) vertexBuffer[vertIndex++] = command.geometry[4][0]; // x + 0 * width; vertexBuffer[vertIndex++] = command.geometry[4][1]; // y + 1 * height vertexBuffer[vertIndex++] = 0; // UV coords vertexBuffer[vertIndex++] = uvx0; // 0; vertexBuffer[vertIndex++] = uvy1; // 1; // texture id vertexBuffer[vertIndex++] = textureId; // opacity vertexBuffer[vertIndex++] = command.opacity; // color vertexBuffer[vertIndex++] = commandColor.r / 255; vertexBuffer[vertIndex++] = commandColor.g / 255; vertexBuffer[vertIndex++] = commandColor.b / 255; vertexBuffer[vertIndex++] = commandColor.a; // (1, 1) vertexBuffer[vertIndex++] = command.geometry[5][0]; // x + 1 * width; vertexBuffer[vertIndex++] = command.geometry[5][1]; // y + 1 * height; vertexBuffer[vertIndex++] = 0; // UV coords vertexBuffer[vertIndex++] = uvx1; // 1; vertexBuffer[vertIndex++] = uvy1; // 1; // texture id vertexBuffer[vertIndex++] = textureId; // opacity vertexBuffer[vertIndex++] = command.opacity; // color vertexBuffer[vertIndex++] = commandColor.r / 255; vertexBuffer[vertIndex++] = commandColor.g / 255; vertexBuffer[vertIndex++] = commandColor.b / 255; vertexBuffer[vertIndex++] = commandColor.a; } return vertIndex / this.vertexSize; } }
the_stack
* Used for stock event calculations. */ import { StockChart } from '../stock-chart'; import { StockEventsSettingsModel } from '../model/base-model'; import { Series, Points } from '../../chart/series/chart-series'; import { FlagType } from '../../common/utils/enum'; import { BorderModel } from '../../common/model/base-model'; import { withIn, PointData, textElement, getElement, valueToCoefficient, drawSymbol, ChartLocation } from '../../common/utils/helper'; import { BaseTooltip } from '../../common/user-interaction/tooltip'; import { Tooltip, PathOption, TextOption, measureText, Size } from '@syncfusion/ej2-svg-base'; import { createElement, remove } from '@syncfusion/ej2-base'; import { DataUtil } from '@syncfusion/ej2-data'; import { IStockEventRenderArgs } from '../model/base'; import { stockEventRender } from '../../common/model/constants'; import { SvgRenderer } from '@syncfusion/ej2-svg-base'; /** * @private */ export class StockEvents extends BaseTooltip { constructor(stockChart: StockChart) { super(stockChart.chart); this.stockChart = stockChart; this.chartId = this.stockChart.element.id; } private stockChart: StockChart; private chartId: string; /** @private */ public stockEventTooltip: Tooltip; /** @private */ public symbolLocations: ChartLocation[][] = []; private pointIndex: number; private seriesIndex: number; /** * To render stock events in chart * * @returns {Element} Stock event element * @private */ public renderStockEvents(): Element { const sChart: StockChart = this.stockChart; let stockEvent: StockEventsSettingsModel; let stockEventElement: Element; let textSize: Size; // Creation of group elements for stock events const stockEventsElementGroup: Element = sChart.renderer.createGroup({ id: this.chartId + '_StockEvents' }); this.symbolLocations = initialArray(sChart.series.length, sChart.stockEvents.length, new ChartLocation(0, 0)); for (let i: number = 0; i < sChart.stockEvents.length; i++) { stockEvent = this.stockChart.stockEvents[i]; for (const series of sChart.chart.series as Series[]) { const argsData: IStockEventRenderArgs = { name: stockEventRender, stockChart: sChart, text: stockEvent.text, type: stockEvent.type, cancel: false, series: series }; sChart.trigger(stockEventRender, argsData); stockEvent.text = argsData.text; stockEvent.type = argsData.type; textSize = measureText(stockEvent.text + 'W', stockEvent.textStyle); if (!argsData.cancel) { stockEventElement = sChart.renderer.createGroup( { id: this.chartId + '_Series_' + series.index + '_StockEvents_' + i } ); const stockEventDate: number = this.dateParse(stockEvent.date).getTime(); if (withIn(stockEventDate , series.xAxis.visibleRange)) { if (stockEvent.seriesIndexes.length > 0) { for (let j: number = 0; j < stockEvent.seriesIndexes.length; j++) { if (stockEvent.seriesIndexes[j] === series.index) { stockEventsElementGroup.appendChild( this.creatEventGroup(stockEventElement, series, stockEvent, i, textSize)); } } } else { stockEventsElementGroup.appendChild( this.creatEventGroup(stockEventElement, series, stockEvent, i, textSize)); } } } } } return stockEventsElementGroup; } private creatEventGroup(stockEventElement: Element, series: Series, stockEvent: StockEventsSettingsModel, i: number, textSize: Size): Element { const symbolLocation: ChartLocation = this.findClosePoint(series, stockEvent); if (!stockEvent.showOnSeries) { symbolLocation.y = series.yAxis.rect.y + series.yAxis.rect.height; } this.symbolLocations[series.index][i] = symbolLocation; this.createStockElements(stockEventElement, stockEvent, series, i, symbolLocation, textSize); return stockEventElement; } private findClosePoint(series: Series, sEvent: StockEventsSettingsModel): ChartLocation { const stockEventDate: number = this.dateParse(sEvent.date).getTime(); const closeIndex: number = this.getClosest(series, stockEventDate ); let pointData: PointData; let point: Points; let yPixel: number; for (let k: number = 0; k < series.points.length; k++) { point = series.points[k]; if (closeIndex === point.xValue && point.visible) { pointData = new PointData(point, series); } else if (k !== 0 && k !== series.points.length) { if (closeIndex > series.points[k - 1].xValue && closeIndex < series.points[k + 1].xValue) { pointData = new PointData(point, series); } } } const xPixel: number = series.xAxis.rect.x + valueToCoefficient(pointData.point.xValue, series.xAxis) * series.xAxis.rect.width; yPixel = valueToCoefficient(pointData.point[sEvent.placeAt] as number, series.yAxis) * series.yAxis.rect.height; yPixel = (yPixel * -1) + (series.yAxis.rect.y + series.yAxis.rect.height); return new ChartLocation(xPixel, yPixel); } private createStockElements(stockEventElement: Element, stockEve: StockEventsSettingsModel, series: Series, i: number, symbolLocation: ChartLocation, textSize: Size): void { const result: Size = new Size(textSize.width > 20 ? textSize.width : 20, textSize.height > 20 ? textSize.height : 20); let pathString: string; let pathOption: PathOption; const lx: number = symbolLocation.x; const ly: number = symbolLocation.y; const stockId: string = this.chartId + '_Series_' + series.index + '_StockEvents_' + i; const border: BorderModel = stockEve.border; switch (stockEve.type) { case 'Flag': case 'Circle': case 'Square': stockEventElement.appendChild( drawSymbol( new ChartLocation(lx, ly), 'Circle', new Size(2, 2), '', new PathOption( stockId + '_Circle', 'transparent', border.width, border.color), this.dateParse(stockEve.date).toISOString() ) ); stockEventElement.appendChild( drawSymbol( new ChartLocation(lx, ly - 5), 'VerticalLine', new Size(9, 9), '', new PathOption(stockId + '_Path', border.color, border.width, border.color), this.dateParse(stockEve.date).toISOString() ) ); stockEventElement.appendChild( drawSymbol( new ChartLocation(stockEve.type !== 'Flag' ? lx : lx + result.width / 2, ly - result.height), stockEve.type, result, '', new PathOption(stockId + '_Shape', stockEve.background, border.width, border.color), this.dateParse(stockEve.date).toISOString() ) ); textElement( this.stockChart.renderer as unknown as SvgRenderer, new TextOption(stockId + '_Text', stockEve.type !== 'Flag' ? symbolLocation.x : symbolLocation.x + result.width / 2, (symbolLocation.y - result.height), 'middle', stockEve.text, '', 'middle'), stockEve.textStyle, stockEve.textStyle.color, stockEventElement ); break; case 'ArrowUp': case 'ArrowDown': case 'ArrowRight': case 'ArrowLeft': pathString = 'M' + ' ' + lx + ' ' + ly + ' ' + this.findArrowpaths(stockEve.type); pathOption = new PathOption(stockId + '_Shape', stockEve.background, border.width, border.color, 1, '', pathString); stockEventElement.appendChild(this.stockChart.renderer.drawPath(pathOption)); break; case 'Triangle': case 'InvertedTriangle': result.height = 3 * textSize.height; result.width = textSize.width + (1.5 * textSize.width); stockEventElement.appendChild( drawSymbol( new ChartLocation(symbolLocation.x, symbolLocation.y), stockEve.type, new Size(20, 20), '', new PathOption(stockId + '_Shape', stockEve.background, border.width, border.color), this.dateParse(stockEve.date).toISOString() ) ); textElement( this.stockChart.renderer as unknown as SvgRenderer, new TextOption(stockId + '_Text', symbolLocation.x, symbolLocation.y, 'middle', stockEve.text, '', 'middle'), stockEve.textStyle, stockEve.textStyle.color, stockEventElement ); break; case 'Text': textSize.height += 8; //padding for text height pathString = 'M' + ' ' + (lx) + ' ' + (ly) + ' ' + 'L' + ' ' + (lx - 5) + ' ' + (ly - 5) + ' ' + 'L' + ' ' + (lx - ((textSize.width ) / 2)) + ' ' + (ly - 5) + ' ' + 'L' + ' ' + (lx - ((textSize.width ) / 2)) + ' ' + (ly - textSize.height) + ' ' + 'L' + ' ' + (lx + ((textSize.width ) / 2)) + ' ' + (ly - textSize.height) + ' ' + 'L' + ' ' + (lx + ((textSize.width ) / 2)) + ' ' + (ly - 5) + ' ' + 'L' + ' ' + (lx + 5) + ' ' + (ly - 5) + ' ' + 'Z'; pathOption = new PathOption(stockId + '_Shape', stockEve.background, border.width, border.color, 1, '', pathString); stockEventElement.appendChild(this.stockChart.renderer.drawPath(pathOption)); textElement( this.stockChart.renderer as unknown as SvgRenderer, new TextOption(stockId + '_Text', lx, ly - (textSize.height / 2), 'middle', stockEve.text, '', 'middle'), stockEve.textStyle, stockEve.textStyle.color, stockEventElement ); break; default: //pin type calculation. pathString = 'M' + ' ' + lx + ' ' + ly + ' ' + 'L' + ' ' + (lx - ((textSize.width) / 2)) + ' ' + (ly - textSize.height / 3) + ' ' + 'L' + ' ' + (lx - ((textSize.width) / 2)) + ' ' + (ly - textSize.height) + ' ' + 'L' + ' ' + (lx + ((textSize.width) / 2)) + ' ' + (ly - textSize.height) + ' ' + 'L' + ' ' + (lx + ((textSize.width) / 2)) + ' ' + (ly - textSize.height / 3) + ' ' + 'Z'; pathOption = new PathOption(stockId + '_Shape', stockEve.background, border.width, border.color, 1, '', pathString); stockEventElement.appendChild(this.stockChart.renderer.drawPath(pathOption)); //append text element textElement( this.stockChart.renderer as unknown as SvgRenderer, new TextOption(stockId + '_Text', lx, ly - (textSize.height / 2), 'middle', stockEve.text, '', 'middle'), stockEve.textStyle, stockEve.textStyle.color, stockEventElement ); } } public renderStockEventTooltip(targetId: string): void { const seriesIndex: number = parseInt((targetId.split('_StockEvents_')[0]).split(this.chartId + '_Series_')[1], 10); const pointIndex: number = parseInt(targetId.split('_StockEvents_')[1].replace(/\D+/g, ''), 10); const updatedLocation: ChartLocation = this.symbolLocations[seriesIndex][pointIndex]; const pointLocation: ChartLocation = new ChartLocation( updatedLocation.x, updatedLocation.y + this.stockChart.toolbarHeight + this.stockChart.titleSize.height); this.applyHighLights(pointIndex, seriesIndex); //title size and toolbar height is added location for placing tooltip const svgElement: HTMLElement = this.getElement(this.chartId + '_StockEvents_Tooltip_svg'); const isTooltip: boolean = (svgElement && parseInt(svgElement.getAttribute('opacity'), 10) > 0); if (!isTooltip) { if (getElement(this.chartId + '_StockEvents_Tooltip_svg')) { remove(getElement(this.chartId + '_StockEvents_Tooltip')); } const tooltipElement: Element = createElement('div', { id: this.chartId + '_StockEvents_Tooltip', className: 'ejSVGTooltip', attrs: { 'style': 'pointer-events:none; position:absolute;z-index: 1' } }); getElement(this.chartId + '_Secondary_Element').appendChild(tooltipElement); this.stockEventTooltip = new Tooltip( { opacity: 1, header: '', content: [(this.stockChart.stockEvents[pointIndex].description)], enableAnimation: true, location: pointLocation, theme: this.stockChart.theme, inverted: true, areaBounds: this.stockChart.chart.chartAxisLayoutPanel.seriesClipRect }); this.stockEventTooltip.areaBounds.y += this.stockChart.toolbarHeight + this.stockChart.titleSize.height; this.stockEventTooltip.appendTo('#' + tooltipElement.id); } else { this.stockEventTooltip.content = [(this.stockChart.stockEvents[pointIndex].description)]; this.stockEventTooltip.location = pointLocation; this.stockEventTooltip.dataBind(); } } /** * Remove the stock event tooltip * * @param {number} duration tooltip timeout duration * @returns {void} */ public removeStockEventTooltip(duration: number): void { const tooltipElement: HTMLElement = this.getElement(this.chartId + '_StockEvents_Tooltip'); this.stopAnimation(); if (tooltipElement && this.stockEventTooltip) { this.toolTipInterval = +setTimeout( (): void => { this.stockEventTooltip.fadeOut(); this.removeHighLights(); }, duration); } } private findArrowpaths(type: FlagType): string { let arrowString: string = ''; switch (type) { case 'ArrowUp': arrowString = 'l -10 10 l 5 0 l 0 10 l 10 0 l 0 -10 l 5 0 z'; break; case 'ArrowDown': arrowString = 'l -10 -10 l 5 0 l 0 -10 l 10 0 l 0 10 l 5 0 z'; break; case 'ArrowLeft': arrowString = 'l -10 -10 l 0 5 l -10 0 l 0 10 l 10 0 l 0 5 z'; break; case 'ArrowRight': arrowString = 'l 10 -10 l 0 5 l 10 0 l 0 10 l -10 0 l 0 5 z'; break; } return arrowString; } private applyHighLights(pointIndex: number, seriesIndex: number): void { if (this.pointIndex !== pointIndex || this.seriesIndex !== seriesIndex) { this.removeHighLights(); } this.pointIndex = pointIndex; this.seriesIndex = seriesIndex; const stockId: string = this.chartId + '_Series_' + seriesIndex + '_StockEvents_' + pointIndex; this.setOpacity(stockId + '_Shape', 0.5); this.setOpacity(stockId + '_Text', 0.5); } private removeHighLights(): void { const stockId: string = this.chartId + '_Series_' + this.seriesIndex + '_StockEvents_' + this.pointIndex; this.setOpacity(stockId + '_Shape', 1); this.setOpacity(stockId + '_Text', 1); } private setOpacity(elementId: string, opacity: number): void { if (getElement(elementId)) { getElement(elementId).setAttribute('opacity', opacity.toString()); } } /** * To convert the c# or javascript date formats into js format * refer chart control's dateTime processing. * * @param {Date | string} value date or string value * @returns {Date} date format value */ private dateParse(value: Date | string): Date { const dateParser: Function = this.chart.intl.getDateParser({ skeleton: 'full', type: 'dateTime' }); const dateFormatter: Function = this.chart.intl.getDateFormat({ skeleton: 'full', type: 'dateTime' }); return new Date((Date.parse(dateParser(dateFormatter(new Date(DataUtil.parse.parseJson({ val: value }).val)))))); } } // eslint-disable-next-line valid-jsdoc /** * To initialthe array * * @param {number} numrows numrows * @param {number} numcols numcols * @param {ChartLocation} initial initial * @returns {ChartLocation[][]} ChartLocation */ function initialArray(numrows: number, numcols: number, initial: ChartLocation): ChartLocation[][] { const arr: ChartLocation[][] = []; for (let i: number = 0; i < numrows; ++i) { const columns: ChartLocation[] = []; for (let j: number = 0; j < numcols; ++j) { columns[j] = initial; } arr[i] = columns; } return arr; }
the_stack
import { clone } from 'lodash'; import React, { useEffect } from 'react'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiDraggable, EuiIconTip, EuiSpacer, EuiAccordion, EuiToolTip, EuiButtonIcon, EuiButtonIconProps } from '@elastic/eui'; import { NumberInputOption, SelectOption } from '../../../../src/plugins/charts/public'; import { SwitchOption } from './switch'; import { TextInputOption } from './text_input'; export interface ComputedColumn { label: string; formula: string; computeTotalUsingFormula: boolean; format: string; pattern: string; datePattern: string; alignment: string; applyAlignmentOnTitle: boolean; applyAlignmentOnTotal: boolean; applyTemplate: boolean; applyTemplateOnTotal: boolean; template: string; cellComputedCss: string; customColumnPosition: number | '' | undefined; enabled: boolean; brandNew?: boolean; } function setComputedColumnParam(paramName: string, paramValue: any, computedColumns: ComputedColumn[], computedColumnToUpdate: ComputedColumn, setComputedColumns) { const newList = computedColumns.map(computedColumn => { if (computedColumn === computedColumnToUpdate) { const updatedComputedColumn = clone(computedColumnToUpdate); updatedComputedColumn[paramName] = paramValue; return updatedComputedColumn; } else { return computedColumn; } }); setComputedColumns(newList); } function removeComputedColumn(computedColumns: ComputedColumn[], computedColumnToRemove: ComputedColumn, setComputedColumns) { const newList = computedColumns.filter(computedColumn => computedColumn !== computedColumnToRemove); setComputedColumns(newList); } function renderButtons (computedColumn, computedColumns, showError, setValue, setComputedColumns, dragHandleProps) { const actionIcons = []; if (showError) { actionIcons.push({ id: 'hasErrors', color: 'danger', type: 'alert', tooltip: i18n.translate('visTypeEnhancedTable.params.computedColumns.errorsAriaLabel', { defaultMessage: 'Computed column has errors', }) }); } if (computedColumn.enabled) { actionIcons.push({ id: 'disableComputedColumn', color: 'text', disabled: false, type: 'eye', onClick: () => setValue('enabled', false), tooltip: i18n.translate('visTypeEnhancedTable.params.computedColumns.disableColumnButtonTooltip', { defaultMessage: 'Disable column', }) }); } if (!computedColumn.enabled) { actionIcons.push({ id: 'enableComputedColumn', color: 'text', type: 'eyeClosed', onClick: () => setValue('enabled', true), tooltip: i18n.translate('visTypeEnhancedTable.params.computedColumns.enableColumnButtonTooltip', { defaultMessage: 'Enable column', }) }); } if (computedColumns.length > 1) { actionIcons.push({ id: 'dragHandle', type: 'grab', tooltip: i18n.translate('visTypeEnhancedTable.params.computedColumns.modifyPriorityButtonTooltip', { defaultMessage: 'Modify order by dragging', }) }); } actionIcons.push({ id: 'removeComputedColumn', color: 'danger', type: 'cross', onClick: () => removeComputedColumn(computedColumns, computedColumn, setComputedColumns), tooltip: i18n.translate('visTypeEnhancedTable.params.computedColumns.removeColumnButtonTooltip', { defaultMessage: 'Remove column', }) }); return ( <div {...dragHandleProps}> {actionIcons.map(icon => { if (icon.id === 'dragHandle') { return ( <EuiIconTip key={icon.id} type={icon.type} content={icon.tooltip} iconProps={{ ['aria-label']: icon.tooltip }} position="bottom" /> ); } return ( <EuiToolTip key={icon.id} position="bottom" content={icon.tooltip}> <EuiButtonIcon disabled={icon.disabled} iconType={icon.type} color={icon.color as EuiButtonIconProps['color']} onClick={icon.onClick} aria-label={icon.tooltip} /> </EuiToolTip> ); })} </div> ); } function formatOptions() { return [ { value: 'number', text: i18n.translate('visTypeEnhancedTable.params.computedColumns.formatOptions.number', { defaultMessage: 'Number', }), }, { value: 'string', text: i18n.translate('visTypeEnhancedTable.params.computedColumns.formatOptions.string', { defaultMessage: 'String', }), }, { value: 'date', text: i18n.translate('visTypeEnhancedTable.params.computedColumns.formatOptions.date', { defaultMessage: 'Date', }), } ]; } function alignmentOptions() { return [ { value: 'left', text: i18n.translate('visTypeEnhancedTable.params.computedColumns.alignmentOptions.left', { defaultMessage: 'left', }), }, { value: 'right', text: i18n.translate('visTypeEnhancedTable.params.computedColumns.alignmentOptions.right', { defaultMessage: 'right', }), }, { value: 'center', text: i18n.translate('visTypeEnhancedTable.params.computedColumns.alignmentOptions.center', { defaultMessage: 'center', }), }, { value: 'justify', text: i18n.translate('visTypeEnhancedTable.params.computedColumns.alignmentOptions.justify', { defaultMessage: 'justify', }), }, ]; } function ComputedColumnEditor({ computedColumns, computedColumn, index, setComputedColumns, setValidity }) { const setValue = (paramName, paramValue) => setComputedColumnParam(paramName, paramValue, computedColumns, computedColumn, setComputedColumns); const [isEditorOpen, setIsEditorOpen] = React.useState(computedColumn.brandNew); const [validState, setValidState] = React.useState(true); const showDescription = !isEditorOpen && validState; const showError = !isEditorOpen && !validState; const isFormulaValid = computedColumn.formula !== ''; const isCustomColumnPositionValid = (computedColumn.customColumnPosition === undefined || computedColumn.customColumnPosition === '' || computedColumn.customColumnPosition >= 0); if (computedColumn.brandNew) { computedColumn.brandNew = undefined; } const buttonContent = ( <> Computed col {showDescription && <span>{computedColumn.label || computedColumn.formula}</span>} </> ); const onToggle = React.useCallback( (isOpen: boolean) => { setIsEditorOpen(isOpen); }, [] ); useEffect(() => { setValidity(isFormulaValid, isCustomColumnPositionValid); setValidState(isFormulaValid && isCustomColumnPositionValid); }, [isFormulaValid, isCustomColumnPositionValid, setValidity, setValidState]); return ( <> <EuiDraggable key={index} index={index} draggableId={`enhanced_table_computed_columns_draggable_${index}`} customDragHandle={true} > {provided => ( <EuiAccordion id={`enhanced_table_computed_columns_accordion_${index}`} initialIsOpen={isEditorOpen} buttonContent={buttonContent} buttonClassName="eui-textTruncate" buttonContentClassName="visEditorSidebar__aggGroupAccordionButtonContent eui-textTruncate" className="visEditorSidebar__section visEditorSidebar__collapsible visEditorSidebar__collapsible--marginBottom" aria-label={i18n.translate('visTypeEnhancedTable.params.computedColumns.toggleEditorButtonAriaLabel', { defaultMessage: 'Toggle computed column editor' })} extraAction={renderButtons(computedColumn, computedColumns, showError, setValue, setComputedColumns, provided.dragHandleProps)} onToggle={onToggle} > <> <EuiSpacer size="m" /> <TextInputOption label={i18n.translate('visTypeEnhancedTable.params.computedColumns.label', { defaultMessage: 'Label', })} paramName="label" value={computedColumn.label} setValue={setValue} /> <TextInputOption label={ <> <FormattedMessage id="visTypeEnhancedTable.params.computedColumns.formula" defaultMessage="Formula" /> &nbsp;( <a href="https://github.com/fbaligand/kibana-enhanced-table/blob/master/README.md#computed-settings-documentation" target="_blank">documentation</a> ) </> } isInvalid={!isFormulaValid} paramName="formula" value={computedColumn.formula} setValue={setValue} /> <SwitchOption label={i18n.translate('visTypeEnhancedTable.params.computedColumns.computeTotalUsingFormula', { defaultMessage: 'Compute total using formula', })} paramName="computeTotalUsingFormula" value={computedColumn.computeTotalUsingFormula} setValue={setValue} /> <SelectOption label={i18n.translate('visTypeTable.params.computedColumns.format', { defaultMessage: 'Format', })} options={formatOptions()} paramName="format" value={computedColumn.format} setValue={setValue} /> {computedColumn.format === 'number' && <TextInputOption label={ <> <FormattedMessage id="visTypeEnhancedTable.params.computedColumns.pattern" defaultMessage="Pattern" /> &nbsp;( <a href="http://numeraljs.com/#format" target="_blank">Numeral.js</a> &nbsp;syntax) </> } paramName="pattern" value={computedColumn.pattern} setValue={setValue} /> } {computedColumn.format === 'date' && <TextInputOption label={ <> <FormattedMessage id="visTypeEnhancedTable.params.computedColumns.datePattern" defaultMessage="Pattern" /> &nbsp;( <a href="http://momentjs.com/docs/#/displaying/format/" target="_blank">Moment.js</a> &nbsp;syntax) </> } paramName="datePattern" value={computedColumn.datePattern} setValue={setValue} /> } <SelectOption label={i18n.translate('visTypeTable.params.computedColumns.alignment', { defaultMessage: 'Alignment', })} options={alignmentOptions()} paramName="alignment" value={computedColumn.alignment} setValue={setValue} /> {computedColumn.alignment !== 'left' && <SwitchOption label={i18n.translate('visTypeEnhancedTable.params.computedColumns.applyAlignmentOnTitle', { defaultMessage: 'Apply alignment on title', })} paramName="applyAlignmentOnTitle" value={computedColumn.applyAlignmentOnTitle} setValue={setValue} /> } {computedColumn.alignment !== 'left' && <SwitchOption label={i18n.translate('visTypeEnhancedTable.params.computedColumns.applyAlignmentOnTotal', { defaultMessage: 'Apply alignment on total', })} paramName="applyAlignmentOnTotal" value={computedColumn.applyAlignmentOnTotal} setValue={setValue} /> } <SwitchOption label={i18n.translate('visTypeEnhancedTable.params.computedColumns.applyTemplate', { defaultMessage: 'Apply template', })} paramName="applyTemplate" value={computedColumn.applyTemplate} setValue={setValue} /> {computedColumn.applyTemplate && <SwitchOption label={i18n.translate('visTypeEnhancedTable.params.computedColumns.applyTemplateOnTotal', { defaultMessage: 'Apply template on total', })} paramName="applyTemplateOnTotal" value={computedColumn.applyTemplateOnTotal} setValue={setValue} /> } {computedColumn.applyTemplate && <TextInputOption label={ <> <FormattedMessage id="visTypeEnhancedTable.params.computedColumns.template" defaultMessage="Template" /> &nbsp;( <a ng-href="https://handlebarsjs.com/guide/expressions.html" target="_blank">Handlebars</a> &nbsp;syntax) </> } paramName="template" value={computedColumn.template} setValue={setValue} /> } <TextInputOption label={ <> <FormattedMessage id="visTypeEnhancedTable.params.computedColumns.cellComputedCss" defaultMessage="Cell computed CSS" /> &nbsp;( <a href="https://github.com/fbaligand/kibana-enhanced-table/blob/master/README.md#computed-settings-documentation" target="_blank">documentation</a> )&nbsp; <EuiIconTip content="This option lets to define dynamically table cell CSS (like background-color CSS property), based on this column value and previous column values" position="right" /> </> } placeholder="value < 0 ? &quot;background-color: red&quot; : &quot;&quot;" paramName="cellComputedCss" value={computedColumn.cellComputedCss} setValue={setValue} /> <NumberInputOption label={ <> <FormattedMessage id="visTypeEnhancedTable.params.computedColumns.customColumnPosition" defaultMessage="Custom column position" />{' '} <EuiIconTip content="You can change here the computed column target position to a previous position. For example, '0' will move this column at first position. Despite 'target' column position, formula can reference any previous column to the 'declared' column position, including classic and computed columns." position="right" /> </> } isInvalid={!isCustomColumnPositionValid} min={0} paramName="customColumnPosition" value={computedColumn.customColumnPosition} setValue={setValue} /> </> </EuiAccordion> )} </EuiDraggable> </> ); } export { ComputedColumnEditor };
the_stack
import { Decimal } from 'decimal.js'; import { FcalError } from '../fcal'; import { NumberSystem } from './numberSystem'; import { UnitMeta } from './units'; import toFormat from 'toformat'; toFormat(Decimal); export enum DATATYPE { NUMBER, UNIT, PERCENTAGE, } export enum TYPE_RANK { PERCENTAGE, NUMBER, UNIT, } abstract class Type { public static typeVsStr: { [index in DATATYPE]: string } = { 0: 'number', 1: 'unit', 2: 'percentage' }; public abstract TYPE: DATATYPE; public abstract TYPE_RANK: TYPE_RANK; public abstract print(): string; public abstract toFormat(): string; public abstract toNumber(): number; public abstract trusty(): boolean; public toString(): string { return this.print(); } } /** * Represents a type of variable or value */ namespace Type { export abstract class Numeric extends Type { public n: Decimal; public lf: boolean; public ns: NumberSystem; constructor(value: string | Decimal | number) { super(); if (value instanceof Decimal) { this.n = value; } else { this.n = new Decimal(value); } this.ns = NumberSystem.dec; this.lf = false; } public format(): string { return (this.n as any).toFormat(); } public setSystem(numberSys: NumberSystem): Numeric { this.ns = numberSys; return this; } public toNumericString(): string { return this.ns.to(this.n); } public print(): string { return this.toNumericString(); } public GT(value: Numeric): Numeric { this.lf = true; if (this.TYPE >= value.TYPE) { return this.gt(value); } return value.gt(this); } public GTE(value: Numeric): Numeric { this.lf = true; if (this.TYPE >= value.TYPE) { return this.gte(value); } return value.gte(this); } public LT(value: Numeric): Numeric { this.lf = true; if (this.TYPE >= value.TYPE) { return this.lt(value); } return value.lt(this); } public LTE(value: Numeric): Numeric { this.lf = true; if (this.TYPE >= value.TYPE) { return this.lte(value); } return value.lte(this); } public EQ(value: Numeric): Numeric { this.lf = true; if (this.TYPE >= value.TYPE) { return this.eq(value); } return value.eq(this); } public NEQ(value: Numeric): Numeric { this.lf = true; if (this.TYPE >= value.TYPE) { return this.nEq(value); } return value.nEq(this); } public Add(value: Numeric): Numeric { if (!this.n.isFinite() && !value.n.isFinite()) { if (!((this.n.isNegative() && value.n.isNegative()) || (this.n.isPositive() && value.n.isPositive()))) { // console.log(left.number, right.number); throw new FcalError('Subtraction between Infinity is indeterminate'); } } // check type to see which datatype operation // if both type is same na right variable operation this.lf = true; if (this.TYPE >= value.TYPE) { // check type rank to see which will be the return type if (this.TYPE_RANK <= value.TYPE_RANK) { return value.New(this.plus(value).n); } return this.plus(value); } if (value.TYPE_RANK >= this.TYPE_RANK) { return value.plus(this); } return this.New(value.plus(this).n); } public Sub(value: Numeric): Numeric { return this.Add(value.negated()); } public times(value: Numeric): Numeric { // check type to see which datatype operation // if both type is same na right variable operation this.lf = true; if (this.TYPE >= value.TYPE) { // check type rank to see which will be the return type if (this.TYPE_RANK <= value.TYPE_RANK) { return value.New(this.mul(value).n); } return this.mul(value); } if (value.TYPE_RANK >= this.TYPE_RANK) { return value.mul(this); } return this.New(value.mul(this).n); } public divide(value: Numeric): Numeric { if (!this.n.isFinite() && !value.n.isFinite()) { throw new FcalError('Division between Infinity is indeterminate'); } // check type to see which datatype operation // if both type is same na right variable operation this.lf = true; if (this.TYPE >= value.TYPE) { // check type rank to see which will be the return type if (this.TYPE_RANK <= value.TYPE_RANK) { if (this.TYPE_RANK === value.TYPE_RANK) { return this.div(value); } return value.New(this.div(value).n); } return this.div(value); } if (value.TYPE_RANK >= this.TYPE_RANK) { return value.div(this); } return this.New(value.div(this).n); } public power(value: Numeric): Numeric { if (this.isNegative()) { if (!value.n.isInt()) { throw new FcalError(`Pow of operation results in complex number and complex number is not supported yet`); } } // console.log(`CAP ${this.number.toString()} ${value.number.toString()}`); // check type to see which datatype operation // if both type is same na right variable operation this.lf = true; if (this.TYPE >= value.TYPE) { // check type rank to see which will be the return type if (this.TYPE_RANK <= value.TYPE_RANK) { if (this.TYPE_RANK === value.TYPE_RANK) { return this.New(this.pow(value).n); } return value.New(this.pow(value).n); } return this.pow(value); } if (value.TYPE_RANK >= this.TYPE_RANK) { return value.pow(this); } return this.New(value.pow(this).n); } public modulo(value: Numeric): Numeric { if (!this.n.isFinite()) { throw new FcalError('Modulus with Infinity is indeterminate'); } if (value.isZero()) { return new Type.BNumber('Infinity'); } // check type to see which datatype operation // if both type is same na right variable operation this.lf = true; if (this.TYPE >= value.TYPE) { // check type rank to see which will be the return type if (this.TYPE_RANK <= value.TYPE_RANK) { if (this.TYPE_RANK === value.TYPE_RANK) { return this.New(this.mod(value).n); } return value.New(this.mod(value).n); } return this.mod(value); } if (value.TYPE_RANK >= this.TYPE_RANK) { return value.mod(this); } return this.New(value.mod(this).n); } public toNumber(): number { return this.n.toNumber(); } public trusty(): boolean { return !this.n.isZero(); } public not(): Numeric { return new FcalBoolean(this.n).not(); } public abstract New(value: Decimal): Numeric; public abstract isZero(): boolean; public abstract isNegative(): boolean; public abstract negated(): Numeric; public abstract plus(value: Numeric): Numeric; public abstract mul(value: Numeric): Numeric; public abstract div(value: Numeric): Numeric; public abstract pow(value: Numeric): Numeric; public abstract mod(value: Numeric): Numeric; public abstract gt(value: Numeric): Numeric; public abstract gte(value: Numeric): Numeric; public abstract lt(value: Numeric): Numeric; public abstract lte(value: Numeric): Numeric; public abstract eq(value: Numeric): Numeric; public abstract nEq(value: Numeric): Numeric; } /** * Basic Number type */ export class BNumber extends Numeric { public toFormat(): string { return this.format(); } public static ZERO = BNumber.New(new Decimal(0)); public static New(value: string | Decimal | number) { return new BNumber(value); } public TYPE_RANK: TYPE_RANK; public TYPE: DATATYPE; constructor(value: string | Decimal | number) { super(value); this.TYPE = DATATYPE.NUMBER; this.TYPE_RANK = TYPE_RANK.NUMBER; } public gt(value: Numeric): Numeric { return new FcalBoolean(this.n.gt(value.n)); } public gte(value: Numeric): Numeric { return new FcalBoolean(this.n.gte(value.n)); } public lt(value: Numeric): Numeric { return new FcalBoolean(this.n.lt(value.n)); } public lte(value: Numeric): Numeric { return new FcalBoolean(this.n.lte(value.n)); } public eq(value: Numeric): Numeric { return new FcalBoolean(this.n.eq(value.n)); } public nEq(value: Numeric): Numeric { return this.eq(value).not(); } public isZero(): boolean { return this.n.isZero(); } public isNegative(): boolean { return this.n.isNegative(); } public negated(): Numeric { return BNumber.New(this.n.negated()); } public div(value: Numeric): Numeric { return BNumber.New(this.n.div(value.n)); } public pow(value: Numeric): Numeric { return BNumber.New(this.n.pow(value.n)); } public mod(value: Numeric): Numeric { return BNumber.New(this.n.modulo(value.n)); } public mul(value: Numeric): Numeric { return BNumber.New(this.n.mul(value.n)); } public plus(value: Numeric): Numeric { return BNumber.New(this.n.plus(value.n)); } public New(value: Decimal): Numeric { return BNumber.New(value); } } /** * Percentage type */ export class Percentage extends Numeric { public toFormat(): string { return `% ${this.format()}`; } public static New(value: string | Decimal | number): Percentage { return new Percentage(value); } private static base = new Decimal(100); public TYPE: DATATYPE; public TYPE_RANK: TYPE_RANK; constructor(value: string | Decimal | number) { super(value); this.TYPE = DATATYPE.PERCENTAGE; this.TYPE_RANK = TYPE_RANK.PERCENTAGE; } public gt(value: Numeric): Numeric { if (value.TYPE === DATATYPE.PERCENTAGE) { return new FcalBoolean(this.n.gt(value.n)); } if (value.lf) { return new FcalBoolean(value.n.gt(this.percentageValue(value.n))); } return new FcalBoolean(this.percentageValue(value.n).gt(value.n)); } public gte(value: Numeric): Numeric { if (value.TYPE === DATATYPE.PERCENTAGE) { return new FcalBoolean(this.n.gte(value.n)); } if (value.lf) { return new FcalBoolean(value.n.gte(this.percentageValue(value.n))); } return new FcalBoolean(this.percentageValue(value.n).gte(value.n)); } public lt(value: Numeric): Numeric { if (value.TYPE === DATATYPE.PERCENTAGE) { return new FcalBoolean(this.n.lt(value.n)); } if (value.lf) { return new FcalBoolean(value.n.lt(this.percentageValue(value.n))); } return new FcalBoolean(this.percentageValue(value.n).lt(value.n)); } public lte(value: Numeric): Numeric { if (value.TYPE === DATATYPE.PERCENTAGE) { return new FcalBoolean(this.n.lte(value.n)); } if (value.lf) { return new FcalBoolean(value.n.lte(this.percentageValue(value.n))); } return new FcalBoolean(this.percentageValue(value.n).lte(value.n)); } public eq(value: Numeric): Numeric { if (value.TYPE === DATATYPE.PERCENTAGE) { return new FcalBoolean(this.n.eq(value.n)); } return new FcalBoolean(value.n.eq(this.percentageValue(value.n))); } public nEq(value: Numeric): Numeric { return this.eq(value).not(); } public isZero(): boolean { return this.n.isZero(); } public isNegative(): boolean { return this.n.isNegative(); } public negated(): Numeric { return Percentage.New(this.n.negated()); } public plus(value: Numeric): Numeric { if (value.TYPE === DATATYPE.PERCENTAGE) { return Percentage.New(this.n.plus(value.n)); } return Percentage.New(value.n.plus(this.percentageValue(value.n))); } public mul(value: Numeric): Numeric { if (value.TYPE === DATATYPE.PERCENTAGE) { return Percentage.New(this.n.mul(value.n)); } return Percentage.New(value.n.mul(this.percentageValue(value.n))); } public div(value: Numeric): Numeric { if (value.TYPE === DATATYPE.PERCENTAGE) { return Percentage.New(this.n.div(value.n)); } if (value.lf) { return Percentage.New(value.n.div(this.percentageValue(value.n))); } return Percentage.New(this.percentageValue(value.n).div(value.n)); } public pow(value: Numeric): Numeric { if (value.TYPE === DATATYPE.PERCENTAGE) { return Percentage.New(this.n.pow(value.n)); } if (value.lf) { return Percentage.New(value.n.pow(this.percentageValue(value.n))); } return Percentage.New(this.percentageValue(value.n).pow(value.n)); } public mod(value: Numeric): Numeric { if (value.TYPE === DATATYPE.PERCENTAGE) { return Percentage.New(this.n.mod(value.n)); } if (value.lf) { return Percentage.New(value.n.mod(this.percentageValue(value.n))); } return Percentage.New(this.percentageValue(value.n).mod(value.n)); } public percentageValue(value: Decimal): Decimal { return value.mul(this.n.div(Percentage.base)); } public print(): string { return `% ${this.toNumericString()}`; } public New(value: Decimal): Numeric { return Percentage.New(value); } } /** * Number with unit */ export class UnitNumber extends Numeric { public toFormat(): string { if (this.n.lessThanOrEqualTo(1) && !this.n.isNegative()) { return `${this.format()} ${this.unit.singular}`; } return `${this.format()} ${this.unit.plural}`; } public static New(value: string | Decimal | number, unit: UnitMeta): UnitNumber { return new UnitNumber(value, unit); } public static convertToUnit(value: Numeric, unit: UnitMeta): UnitNumber { if (value instanceof UnitNumber) { const value2 = value as UnitNumber; if (value2.unit.id === unit.id && value2.unit.unitType !== unit.unitType) { return UnitNumber.New(value2.convert(unit.ratio, unit.bias), unit).setSystem(value.ns) as UnitNumber; } } return UnitNumber.New(value.n, unit).setSystem(value.ns) as UnitNumber; } public TYPE: DATATYPE; public TYPE_RANK: TYPE_RANK; public unit: UnitMeta; constructor(value: string | Decimal | number, unit: UnitMeta) { super(value); this.unit = unit; this.TYPE = DATATYPE.UNIT; this.TYPE_RANK = TYPE_RANK.UNIT; } public New(value: Decimal): Numeric { return new UnitNumber(value, this.unit); } public isZero(): boolean { return this.n.isZero(); } public isNegative(): boolean { return this.n.isNegative(); } public negated(): Numeric { return this.New(this.n.negated()); } public gt(value: Numeric): Numeric { let left: Numeric; let right: Numeric; [left, right] = this.lf ? [this, value] : [value, this]; if (value instanceof UnitNumber) { const left1: UnitNumber = left as UnitNumber; const right1: UnitNumber = right as UnitNumber; if (left1.unit.id === right1.unit.id) { return new FcalBoolean(left1.convert(right1.ratio(), right1.bias()).gt(right1.n)); } } return new FcalBoolean(left.n.gt(right.n)); } public gte(value: Numeric): Numeric { let left: Numeric; let right: Numeric; [left, right] = this.lf ? [this, value] : [value, this]; if (value instanceof UnitNumber) { const left1: UnitNumber = left as UnitNumber; const right1: UnitNumber = right as UnitNumber; if (left1.unit.id === right1.unit.id) { return new FcalBoolean(left1.convert(right1.ratio(), right1.bias()).gte(right1.n)); } } return new FcalBoolean(left.n.gte(right.n)); } public lt(value: Numeric): Numeric { let left: Numeric; let right: Numeric; [left, right] = this.lf ? [this, value] : [value, this]; if (value instanceof UnitNumber) { const left1: UnitNumber = left as UnitNumber; const right1: UnitNumber = right as UnitNumber; if (left1.unit.id === right1.unit.id) { return new FcalBoolean(left1.convert(right1.ratio(), right1.bias()).lt(right1.n)); } } return new FcalBoolean(left.n.lt(right.n)); } public lte(value: Numeric): Numeric { let left: Numeric; let right: Numeric; [left, right] = this.lf ? [this, value] : [value, this]; if (value instanceof UnitNumber) { const left1: UnitNumber = left as UnitNumber; const right1: UnitNumber = right as UnitNumber; if (left1.unit.id === right1.unit.id) { return new FcalBoolean(left1.convert(right1.ratio(), right1.bias()).lte(right1.n)); } } return new FcalBoolean(left.n.lte(right.n)); } public eq(value: Numeric): Numeric { let left: Numeric; let right: Numeric; [left, right] = this.lf ? [this, value] : [value, this]; if (value instanceof UnitNumber) { const left1: UnitNumber = left as UnitNumber; const right1: UnitNumber = right as UnitNumber; if (left1.unit.id === right1.unit.id) { return new FcalBoolean(left1.convert(right1.ratio(), right1.bias()).eq(right1.n)); } } return new FcalBoolean(left.n.eq(right.n)); } public nEq(value: Numeric): Numeric { return this.eq(value).not(); } public plus(value: Numeric): Numeric { if (value instanceof UnitNumber) { const right = value as UnitNumber; if (this.unit.id === value.unit.id) { return right.New(this.convert(right.ratio(), right.bias()).add(right.n)); } return value.New(this.n.plus(value.n)); } return this.New(this.n.plus(value.n)); } public mul(value: Numeric): Numeric { if (value instanceof UnitNumber) { const right = value as UnitNumber; if (this.unit.id === value.unit.id) { return right.New(this.convert(right.ratio(), right.bias()).mul(right.n)); } return value.New(this.n.mul(value.n)); } return this.New(this.n.mul(value.n)); } public div(value: Numeric): Numeric { let left: Numeric; let right: Numeric; [left, right] = this.lf ? [this, value] : [value, this]; if (value instanceof UnitNumber) { const left1: UnitNumber = left as UnitNumber; const right1: UnitNumber = right as UnitNumber; if (left1.unit.unitType === right1.unit.unitType) { return new Type.BNumber(left1.n.div(right1.n)); } if (left1.unit.id !== right1.unit.id) { return left1.New(left1.n.div(right.n)); } return new Type.BNumber(left1.n.div(right1.convert(left1.ratio(), left1.bias()))); } return this.New(left.n.div(right.n)); } public pow(value: Numeric): Numeric { let left: Numeric; let right: Numeric; [left, right] = this.lf ? [this, value] : [value, this]; if (value instanceof UnitNumber) { const left1: UnitNumber = left as UnitNumber; const right1: UnitNumber = right as UnitNumber; if (left1.unit.unitType === right1.unit.unitType) { return left1.New(left1.n.pow(right1.n)); } if (left1.unit.id !== right1.unit.id) { return left1.New(left1.n.pow(right.n)); } return left1.New(left1.n.pow(right1.convert(left1.ratio(), left1.bias()))); } return this.New(left.n.pow(right.n)); } public mod(value: Numeric): Numeric { let left: Numeric; let right: Numeric; [left, right] = this.lf ? [this, value] : [value, this]; if (value instanceof UnitNumber) { const left1: UnitNumber = left as UnitNumber; const right1: UnitNumber = right as UnitNumber; if (left1.unit.id !== right1.unit.id) { return left1.New(left1.n.mod(right1.n)); } if (left1.unit.unitType === right1.unit.unitType) { return left1.New(left1.n.mod(right1.n)); } return left1.New(left1.n.mod(right1.convert(left1.ratio(), left1.bias()))); } return this.New(left.n.mod(right.n)); } public convert(ratio: Decimal, bias: Decimal): Decimal { return this.n .mul(this.ratio()) .add(this.bias()) .minus(bias) .div(ratio); } public ratio(): Decimal { return this.unit.ratio; } public bias(): Decimal { return this.unit.bias; } public print(): string { if (this.n.lessThanOrEqualTo(1) && !this.n.isNegative()) { return `${this.toNumericString()} ${this.unit.singular}`; } return `${this.toNumericString()} ${this.unit.plural}`; } } export class FcalBoolean extends BNumber { public toFormat(): string { throw new Error('Method not implemented.'); } public static TRUE: FcalBoolean = new FcalBoolean(1); public static FALSE: FcalBoolean = new FcalBoolean(0); private v: boolean; constructor(value: string | number | Decimal | boolean) { if (typeof value === 'boolean') { super(value ? 1 : 0); this.v = value; return; } super(value); this.v = !this.n.isZero(); } public print(): string { return this.v + ''; } public not(): BNumber { return this.v ? FcalBoolean.FALSE : FcalBoolean.TRUE; } } } export { Type };
the_stack
import Bluebird from 'bluebird' import chai from 'chai' import http from 'http' import https from 'https' import net from 'net' import sinon from 'sinon' import sinonChai from 'sinon-chai' import tls from 'tls' import url from 'url' import DebuggingProxy from '@cypress/debugging-proxy' import request from '@cypress/request-promise' import * as socketIo from '@packages/socket' import { buildConnectReqHead, createProxySock, isRequestHttps, isResponseStatusCode200, regenerateRequestHead, CombinedAgent, clientCertificateStore, } from '../../lib/agent' import { allowDestroy } from '../../lib/allow-destroy' import { AsyncServer, Servers } from '../support/servers' import { UrlClientCertificates, ClientCertificates, PemKey } from '../../lib/client-certificates' import Forge from 'node-forge' const { pki } = Forge const expect = chai.expect chai.use(sinonChai) const PROXY_PORT = 31000 const HTTP_PORT = 31080 const HTTPS_PORT = 31443 function createCertAndKey (): [object, object] { let keys = pki.rsa.generateKeyPair(2048) let cert = pki.createCertificate() cert.publicKey = keys.publicKey cert.serialNumber = '01' cert.validity.notBefore = new Date() cert.validity.notAfter = new Date() cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1) let attrs = [ { name: 'commonName', value: 'example.org', }, { name: 'countryName', value: 'US', }, { shortName: 'ST', value: 'California', }, { name: 'localityName', value: 'San Fran', }, { name: 'organizationName', value: 'Test', }, { shortName: 'OU', value: 'Test', }, ] cert.setSubject(attrs) cert.setIssuer(attrs) cert.sign(keys.privateKey) return [cert, keys.privateKey] } describe('lib/agent', function () { beforeEach(function () { process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0' }) afterEach(function () { process.env.NO_PROXY = process.env.HTTP_PROXY = process.env.HTTPS_PROXY = '' sinon.restore() }) context('CombinedAgent', function () { before(function () { this.servers = new Servers() return this.servers.start(HTTP_PORT, HTTPS_PORT) }) after(function () { return this.servers.stop() }) ;[ { name: 'with no upstream', }, { name: 'with an HTTP upstream', proxyUrl: `http://localhost:${PROXY_PORT}`, }, { name: 'with an HTTPS upstream', proxyUrl: `https://localhost:${PROXY_PORT}`, httpsProxy: true, }, { name: 'with an HTTP upstream requiring auth', proxyUrl: `http://foo:bar@localhost:${PROXY_PORT}`, proxyAuth: true, }, { name: 'with an HTTPS upstream requiring auth', proxyUrl: `https://foo:bar@localhost:${PROXY_PORT}`, httpsProxy: true, proxyAuth: true, }, ].slice().map((testCase) => { context(testCase.name, function () { beforeEach(function () { if (testCase.proxyUrl) { // PROXY vars should override npm_config vars, so set them to cause failures if they are used // @see https://github.com/cypress-io/cypress/pull/8295 process.env.npm_config_proxy = process.env.npm_config_https_proxy = 'http://erroneously-used-npm-proxy.invalid' process.env.npm_config_noproxy = 'just,some,nonsense' process.env.HTTP_PROXY = process.env.HTTPS_PROXY = testCase.proxyUrl process.env.NO_PROXY = '' } this.agent = new CombinedAgent() this.request = request.defaults({ proxy: null, agent: this.agent, }) if (testCase.proxyUrl) { let options: any = { keepRequests: true, https: false, auth: false, } if (testCase.httpsProxy) { options.https = this.servers.https } if (testCase.proxyAuth) { options.auth = { username: 'foo', password: 'bar', } } this.debugProxy = new DebuggingProxy(options) return this.debugProxy.start(PROXY_PORT) } }) afterEach(function () { if (testCase.proxyUrl) { this.debugProxy.stop() } }) it('HTTP pages can be loaded', function () { return this.request({ url: `http://localhost:${HTTP_PORT}/get`, }).then((body) => { expect(body).to.eq('It worked!') if (this.debugProxy) { expect(this.debugProxy.requests[0]).to.include({ url: `http://localhost:${HTTP_PORT}/get`, }) } }) }) it('HTTPS pages can be loaded', function () { return this.request({ url: `https://localhost:${HTTPS_PORT}/get`, }).then((body) => { expect(body).to.eq('It worked!') if (this.debugProxy) { expect(this.debugProxy.requests[0]).to.include({ https: true, url: `localhost:${HTTPS_PORT}`, }) } }) }) it('HTTP errors are catchable', function () { return this.request({ url: `http://localhost:${HTTP_PORT}/empty-response`, }) .then(() => { throw new Error('Shouldn\'t reach this') }) .catch((err) => { if (this.debugProxy) { expect(this.debugProxy.requests[0]).to.include({ url: `http://localhost:${HTTP_PORT}/empty-response`, }) expect(err.statusCode).to.eq(502) } else { expect(err.message).to.eq('Error: socket hang up') } }) }) it('HTTPS errors are catchable', function () { return this.request({ url: `https://localhost:${HTTPS_PORT}/empty-response`, }) .then(() => { throw new Error('Shouldn\'t reach this') }) .catch((err) => { expect(err.message).to.eq('Error: socket hang up') }) }) it('HTTP websocket connections can be established and used', function () { const socket = socketIo.client(`http://localhost:${HTTP_PORT}`, { agent: this.agent, transports: ['websocket'], rejectUnauthorized: false, }) return new Bluebird((resolve) => { socket.on('message', resolve) }) .then((msg) => { expect(msg).to.eq('It worked!') if (this.debugProxy) { expect(this.debugProxy.requests[0].ws).to.be.true expect(this.debugProxy.requests[0].url).to.include('http://localhost:31080') } socket.close() }) }) it('HTTPS websocket connections can be established and used', function () { const socket = socketIo.client(`https://localhost:${HTTPS_PORT}`, { agent: this.agent, transports: ['websocket'], rejectUnauthorized: false, }) return new Bluebird((resolve) => { socket.on('message', resolve) }) .then((msg) => { expect(msg).to.eq('It worked!') if (this.debugProxy) { expect(this.debugProxy.requests[0]).to.include({ url: 'localhost:31443', }) } socket.close() }) }) // https://github.com/cypress-io/cypress/issues/5729 it('does not warn when making a request to an IP address', function () { const warningStub = sinon.spy(process, 'emitWarning') return this.request({ url: `https://127.0.0.1:${HTTPS_PORT}/get`, }) .then(() => { expect(warningStub).to.not.be.called }) }) }) }) context('HttpsAgent', function () { beforeEach(function () { this.agent = new CombinedAgent() this.request = request.defaults({ agent: this.agent as any, proxy: null, }) }) it('#createUpstreamProxyConnection does not go to proxy if domain in NO_PROXY', function () { const spy = sinon.spy(this.agent.httpsAgent, 'createUpstreamProxyConnection') process.env.HTTP_PROXY = process.env.HTTPS_PROXY = 'http://0.0.0.0:0' process.env.NO_PROXY = 'mtgox.info,example.com,homestarrunner.com,' return this.request({ url: 'https://example.com/', }) .then(() => { expect(spy).to.not.be.called return this.request({ url: 'https://example.org/', }) .then(() => { throw new Error('should not be able to connect') }) .catch({ message: 'Error: A connection to the upstream proxy could not be established: connect ECONNREFUSED 0.0.0.0' }, () => { expect(spy).to.be.calledOnce }) }) }) it('#createUpstreamProxyConnection calls to super for caching, TLS-ifying', function () { const spy = sinon.spy(https.Agent.prototype, 'createConnection') const proxy = new DebuggingProxy() const proxyPort = PROXY_PORT + 1 process.env.HTTP_PROXY = process.env.HTTPS_PROXY = `http://localhost:${proxyPort}` process.env.NO_PROXY = '' return proxy.start(proxyPort) .then(() => { return this.request({ url: `https://localhost:${HTTPS_PORT}/get`, }) }) .then(() => { const options = spy.getCall(0).args[0] const session = this.agent.httpsAgent._sessionCache.map[options._agentKey] expect(spy).to.be.calledOnce expect(this.agent.httpsAgent._sessionCache.list).to.have.length(1) expect(session).to.not.be.undefined return proxy.stop() }) }) it('#createUpstreamProxyConnection throws when connection is accepted then closed', function () { const proxy = Bluebird.promisifyAll( allowDestroy( net.createServer((socket) => { socket.end() }), ), ) as net.Server & AsyncServer const proxyPort = PROXY_PORT + 2 process.env.HTTP_PROXY = process.env.HTTPS_PROXY = `http://localhost:${proxyPort}` process.env.NO_PROXY = '' return proxy.listenAsync(proxyPort) .then(() => { return this.request({ url: `https://localhost:${HTTPS_PORT}/get`, }) }) .then(() => { throw new Error('should not succeed') }) .catch((e) => { expect(e.message).to.eq('Error: A connection to the upstream proxy could not be established: ERR_EMPTY_RESPONSE: The upstream proxy closed the socket after connecting but before sending a response.') return proxy.destroyAsync() }) }) }) context('HttpAgent', function () { beforeEach(function () { this.agent = new CombinedAgent() this.request = request.defaults({ agent: this.agent as any, proxy: null, }) }) it('#addRequest does not go to proxy if domain in NO_PROXY', function () { const spy = sinon.spy(this.agent.httpAgent, '_addProxiedRequest') process.env.HTTP_PROXY = process.env.HTTPS_PROXY = 'http://0.0.0.0:0' process.env.NO_PROXY = 'mtgox.info,example.com,homestarrunner.com,' return this.request({ url: 'http://example.com/', }) .then(() => { expect(spy).to.not.be.called return this.request({ url: 'http://example.org/', }) .then(() => { throw new Error('should not be able to connect') }) .catch({ message: 'Error: connect ECONNREFUSED 0.0.0.0' }, () => { expect(spy).to.be.calledOnce }) }) }) }) }) context('CombinedAgent with client certificates', function () { const proxyUrl = `https://localhost:${PROXY_PORT}` before(function () { this.servers = new Servers() return this.servers.start(HTTP_PORT, HTTPS_PORT) }) after(function () { return this.servers.stop() }) ;[ { name: 'should present a client certificate', peresentClientCertificate: true, }, { name: 'should present not a client certificate', peresentClientCertificate: false, }, ].slice().map((testCase) => { context(testCase.name, function () { beforeEach(function () { // PROXY vars should override npm_config vars, so set them to cause failures if they are used // @see https://github.com/cypress-io/cypress/pull/8295 process.env.npm_config_proxy = process.env.npm_config_https_proxy = 'http://erroneously-used-npm-proxy.invalid' process.env.npm_config_noproxy = 'just,some,nonsense' process.env.HTTP_PROXY = process.env.HTTPS_PROXY = proxyUrl process.env.NO_PROXY = '' this.agent = new CombinedAgent() this.request = request.defaults({ proxy: null, agent: this.agent, }) let options: any = { keepRequests: true, https: this.servers.https, auth: false, } if (testCase.peresentClientCertificate) { clientCertificateStore.clear() const certAndKey = createCertAndKey() const pemCert = pki.certificateToPem(certAndKey[0]) this.clientCert = pemCert const testCerts = new UrlClientCertificates(`https://localhost`) testCerts.clientCertificates = new ClientCertificates() testCerts.clientCertificates.cert.push(pemCert) testCerts.clientCertificates.key.push(new PemKey(pki.privateKeyToPem(certAndKey[1]), undefined)) clientCertificateStore.addClientCertificatesForUrl(testCerts) } this.debugProxy = new DebuggingProxy(options) return this.debugProxy.start(PROXY_PORT) }) afterEach(function () { this.debugProxy.stop() }) it('Client certificate presneted if appropriate', function () { return this.request({ url: `https://localhost:${HTTPS_PORT}/get`, }).then((body) => { expect(body).to.eq('It worked!') if (this.debugProxy) { expect(this.debugProxy.requests[0]).to.include({ https: true, url: `localhost:${HTTPS_PORT}`, }) } const socketKey = Object.keys(this.agent.httpsAgent.sockets).filter((key) => key.includes(`localhost:${HTTPS_PORT}`)) expect(socketKey.length).to.eq(1, 'There should only be a single localhost TLS Socket') // If a client cert has been assigned to a TLS connection, the key for the TLSSocket // will include the public certificate if (this.clientCert) { expect(socketKey[0]).to.contain(this.clientCert, 'A client cert should be used for the TLS Socket') } else { expect(socketKey[0]).not.to.contain(this.clientCert, 'A client cert should not be used for the TLS Socket') } }) }) }) }) }) context('.buildConnectReqHead', function () { it('builds the correct request', function () { const head = buildConnectReqHead('foo.bar', '1234', {}) expect(head).to.eq([ 'CONNECT foo.bar:1234 HTTP/1.1', 'Host: foo.bar:1234', '', '', ].join('\r\n')) }) it('can do Proxy-Authorization', function () { const head = buildConnectReqHead('foo.bar', '1234', { auth: 'baz:quux', }) expect(head).to.eq([ 'CONNECT foo.bar:1234 HTTP/1.1', 'Host: foo.bar:1234', 'Proxy-Authorization: basic YmF6OnF1dXg=', '', '', ].join('\r\n')) }) }) context('.createProxySock', function () { it('creates a `net` socket for an http url', function (done) { sinon.spy(net, 'connect') const proxy = url.parse('http://foo.bar:1234') createProxySock({ proxy }, () => { expect(net.connect).to.be.calledWith({ host: 'foo.bar', port: 1234 }) done() }) }) it('creates a `tls` socket for an https url', function (done) { sinon.spy(tls, 'connect') const proxy = url.parse('https://foo.bar:1234') createProxySock({ proxy }, () => { expect(tls.connect).to.be.calledWith({ host: 'foo.bar', port: 1234 }) done() }) }) it('throws on unsupported proxy protocol', function (done) { const proxy = url.parse('socksv5://foo.bar:1234') createProxySock({ proxy }, (err) => { expect(err.message).to.eq('Unsupported proxy protocol: socksv5:') done() }) }) }) context('.isRequestHttps', function () { [ { protocol: 'http', agent: http.globalAgent, expect: false, }, { protocol: 'https', agent: https.globalAgent, expect: true, }, ].map((testCase) => { it(`detects correctly from ${testCase.protocol} requests`, () => { const spy = sinon.spy(testCase.agent, 'addRequest') return request({ url: `${testCase.protocol}://foo.bar.baz.invalid`, agent: testCase.agent, }) .then(() => { throw new Error('Shouldn\'t succeed') }) .catch(() => { const requestOptions = spy.getCall(0).args[1] expect(isRequestHttps(requestOptions)).to.equal(testCase.expect) }) }) it(`detects correctly from ${testCase.protocol} websocket requests`, () => { const spy = sinon.spy(testCase.agent, 'addRequest') const socket = socketIo.client(`${testCase.protocol}://foo.bar.baz.invalid`, { agent: <any>testCase.agent, transports: ['websocket'], timeout: 1, rejectUnauthorized: false, }) return new Bluebird((resolve, reject) => { socket.on('message', reject) socket.io.on('error', resolve) }) .then(() => { const requestOptions = spy.getCall(0).args[1] expect(isRequestHttps(requestOptions)).to.equal(testCase.expect) socket.close() }) }) }) }) context('.isResponseStatusCode200', function () { it('matches a 200 OK response correctly', function () { const result = isResponseStatusCode200('HTTP/1.1 200 Connection established') expect(result).to.be.true }) it('matches a 500 error response correctly', function () { const result = isResponseStatusCode200('HTTP/1.1 500 Internal Server Error') expect(result).to.be.false }) }) context('.regenerateRequestHead', function () { it('regenerates changed request head', () => { const spy = sinon.spy(http.globalAgent, 'createSocket') return request({ url: 'http://foo.bar.baz.invalid', agent: http.globalAgent, }) .then(() => { throw new Error('this should fail') }) .catch(() => { const req = spy.getCall(0).args[0] expect(req._header).to.equal([ 'GET / HTTP/1.1', 'host: foo.bar.baz.invalid', 'Connection: close', '', '', ].join('\r\n')) // now change some stuff, regen, and expect it to work delete req._header // @ts-ignore req.path = 'http://quuz.quux.invalid/abc?def=123' req.setHeader('Host', 'foo.fleem.invalid') req.setHeader('bing', 'bang') regenerateRequestHead(req) expect(req._header).to.equal([ 'GET http://quuz.quux.invalid/abc?def=123 HTTP/1.1', 'Host: foo.fleem.invalid', 'bing: bang', 'Connection: close', '', '', ].join('\r\n')) }) }) }) })
the_stack