text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import Vue from 'vue'
import { VNode, VNodeDirective } from 'vue/types'
import { VuetifyIcon } from 'vuetify/types/services/icons'
import { DataTableCompareFunction, SelectItemKey, ItemGroup } from 'vuetify/types'
export function createSimpleFunctional (
c: string,
el = 'div',
name?: string
) {
return Vue.extend({
name: name || c.replace(/__/g, '-'),
functional: true,
render (h, { data, children }): VNode {
data.staticClass = (`${c} ${data.staticClass || ''}`).trim()
return h(el, data, children)
},
})
}
export type BindingConfig = Pick<VNodeDirective, 'arg' | 'modifiers' | 'value'>
export function directiveConfig (binding: BindingConfig, defaults = {}): VNodeDirective {
return {
...defaults,
...binding.modifiers,
value: binding.arg,
...(binding.value || {}),
}
}
export function addOnceEventListener (
el: EventTarget,
eventName: string,
cb: (event: Event) => void,
options: boolean | AddEventListenerOptions = false
): void {
var once = (event: Event) => {
cb(event)
el.removeEventListener(eventName, once, options)
}
el.addEventListener(eventName, once, options)
}
let passiveSupported = false
try {
if (typeof window !== 'undefined') {
const testListenerOpts = Object.defineProperty({}, 'passive', {
get: () => {
passiveSupported = true
},
})
window.addEventListener('testListener', testListenerOpts, testListenerOpts)
window.removeEventListener('testListener', testListenerOpts, testListenerOpts)
}
} catch (e) { console.warn(e) }
export { passiveSupported }
export function addPassiveEventListener (
el: EventTarget,
event: string,
cb: EventHandlerNonNull | (() => void),
options: {}
): void {
el.addEventListener(event, cb, passiveSupported ? options : false)
}
export function getNestedValue (obj: any, path: (string | number)[], fallback?: any): any {
const last = path.length - 1
if (last < 0) return obj === undefined ? fallback : obj
for (let i = 0; i < last; i++) {
if (obj == null) {
return fallback
}
obj = obj[path[i]]
}
if (obj == null) return fallback
return obj[path[last]] === undefined ? fallback : obj[path[last]]
}
export function deepEqual (a: any, b: any): boolean {
if (a === b) return true
if (
a instanceof Date &&
b instanceof Date &&
a.getTime() !== b.getTime()
) {
// If the values are Date, compare them as timestamps
return false
}
if (a !== Object(a) || b !== Object(b)) {
// If the values aren't objects, they were already checked for equality
return false
}
const props = Object.keys(a)
if (props.length !== Object.keys(b).length) {
// Different number of props, don't bother to check
return false
}
return props.every(p => deepEqual(a[p], b[p]))
}
export function getObjectValueByPath (obj: any, path: string, fallback?: any): any {
// credit: http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key#comment55278413_6491621
if (obj == null || !path || typeof path !== 'string') return fallback
if (obj[path] !== undefined) return obj[path]
path = path.replace(/\[(\w+)\]/g, '.$1') // convert indexes to properties
path = path.replace(/^\./, '') // strip a leading dot
return getNestedValue(obj, path.split('.'), fallback)
}
export function getPropertyFromItem (
item: object,
property: SelectItemKey,
fallback?: any
): any {
if (property == null) return item === undefined ? fallback : item
if (item !== Object(item)) return fallback === undefined ? item : fallback
if (typeof property === 'string') return getObjectValueByPath(item, property, fallback)
if (Array.isArray(property)) return getNestedValue(item, property, fallback)
if (typeof property !== 'function') return fallback
const value = property(item, fallback)
return typeof value === 'undefined' ? fallback : value
}
export function createRange (length: number): number[] {
return Array.from({ length }, (v, k) => k)
}
export function getZIndex (el?: Element | null): number {
if (!el || el.nodeType !== Node.ELEMENT_NODE) return 0
const index = +window.getComputedStyle(el).getPropertyValue('z-index')
if (!index) return getZIndex(el.parentNode as Element)
return index
}
const tagsToReplace = {
'&': '&',
'<': '<',
'>': '>',
} as any
export function escapeHTML (str: string): string {
return str.replace(/[&<>]/g, tag => tagsToReplace[tag] || tag)
}
export function filterObjectOnKeys<T, K extends keyof T> (obj: T, keys: K[]): { [N in K]: T[N] } {
const filtered = {} as { [N in K]: T[N] }
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
if (typeof obj[key] !== 'undefined') {
filtered[key] = obj[key]
}
}
return filtered
}
export function convertToUnit (str: string | number | null | undefined, unit = 'px'): string | undefined {
if (str == null || str === '') {
return undefined
} else if (isNaN(+str!)) {
return String(str)
} else {
return `${Number(str)}${unit}`
}
}
export function kebabCase (str: string): string {
return (str || '').replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
}
export function isObject (obj: any): obj is object {
return obj !== null && typeof obj === 'object'
}
// KeyboardEvent.keyCode aliases
export const keyCodes = Object.freeze({
enter: 13,
tab: 9,
delete: 46,
esc: 27,
space: 32,
up: 38,
down: 40,
left: 37,
right: 39,
end: 35,
home: 36,
del: 46,
backspace: 8,
insert: 45,
pageup: 33,
pagedown: 34,
})
/**
* This remaps internal names like '$cancel' or '$vuetify.icons.cancel'
* to the current name or component for that icon.
*/
export function remapInternalIcon (vm: Vue, iconName: string): VuetifyIcon {
// Look for custom component in the configuration
const component = vm.$vuetify.icons.component
// Look for overrides
if (iconName.startsWith('$')) {
// Get the target icon name
const iconPath = `$vuetify.icons.values.${iconName.split('$').pop()!.split('.').pop()}`
// Now look up icon indirection name,
// e.g. '$vuetify.icons.values.cancel'
const override = getObjectValueByPath(vm, iconPath, iconName)
if (typeof override === 'string') iconName = override
else return override
}
if (component == null) {
return iconName
}
return {
component,
props: {
icon: iconName,
},
}
}
export function keys<O> (o: O) {
return Object.keys(o) as (keyof O)[]
}
/**
* Camelize a hyphen-delimited string.
*/
const camelizeRE = /-(\w)/g
export const camelize = (str: string): string => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
}
/**
* Returns the set difference of B and A, i.e. the set of elements in B but not in A
*/
export function arrayDiff (a: any[], b: any[]): any[] {
const diff: any[] = []
for (let i = 0; i < b.length; i++) {
if (a.indexOf(b[i]) < 0) diff.push(b[i])
}
return diff
}
/**
* Makes the first character of a string uppercase
*/
export function upperFirst (str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1)
}
export function groupItems<T extends any = any> (
items: T[],
groupBy: string[],
groupDesc: boolean[]
): ItemGroup<T>[] {
const key = groupBy[0]
const groups: ItemGroup<T>[] = []
let current
for (var i = 0; i < items.length; i++) {
const item = items[i]
const val = getObjectValueByPath(item, key, null)
if (current !== val) {
current = val
groups.push({
name: val ?? '',
items: [],
})
}
groups[groups.length - 1].items.push(item)
}
return groups
}
export function wrapInArray<T> (v: T | T[] | null | undefined): T[] { return v != null ? Array.isArray(v) ? v : [v] : [] }
export function sortItems<T extends any = any> (
items: T[],
sortBy: string[],
sortDesc: boolean[],
locale: string,
customSorters?: Record<string, DataTableCompareFunction<T>>
): T[] {
if (sortBy === null || !sortBy.length) return items
const stringCollator = new Intl.Collator(locale, { sensitivity: 'accent', usage: 'sort' })
return items.sort((a, b) => {
for (let i = 0; i < sortBy.length; i++) {
const sortKey = sortBy[i]
let sortA = getObjectValueByPath(a, sortKey)
let sortB = getObjectValueByPath(b, sortKey)
if (sortDesc[i]) {
[sortA, sortB] = [sortB, sortA]
}
if (customSorters && customSorters[sortKey]) {
const customResult = customSorters[sortKey](sortA, sortB)
if (!customResult) continue
return customResult
}
// Check if both cannot be evaluated
if (sortA === null && sortB === null) {
continue
}
[sortA, sortB] = [sortA, sortB].map(s => (s || '').toString().toLocaleLowerCase())
if (sortA !== sortB) {
if (!isNaN(sortA) && !isNaN(sortB)) return Number(sortA) - Number(sortB)
return stringCollator.compare(sortA, sortB)
}
}
return 0
})
}
export function defaultFilter (value: any, search: string | null, item: any) {
return value != null &&
search != null &&
typeof value !== 'boolean' &&
value.toString().toLocaleLowerCase().indexOf(search.toLocaleLowerCase()) !== -1
}
export function searchItems<T extends any = any> (items: T[], search: string): T[] {
if (!search) return items
search = search.toString().toLowerCase()
if (search.trim() === '') return items
return items.filter((item: any) => Object.keys(item).some(key => defaultFilter(getObjectValueByPath(item, key), search, item)))
}
/**
* Returns:
* - 'normal' for old style slots - `<template slot="default">`
* - 'scoped' for old style scoped slots (`<template slot="default" slot-scope="data">`) or bound v-slot (`#default="data"`)
* - 'v-slot' for unbound v-slot (`#default`) - only if the third param is true, otherwise counts as scoped
*/
export function getSlotType<T extends boolean = false> (vm: Vue, name: string, split?: T): (T extends true ? 'v-slot' : never) | 'normal' | 'scoped' | void {
if (vm.$slots[name] && vm.$scopedSlots[name] && (vm.$scopedSlots[name] as any).name) {
return split ? 'v-slot' as any : 'scoped'
}
if (vm.$slots[name]) return 'normal'
if (vm.$scopedSlots[name]) return 'scoped'
}
export function debounce (fn: Function, delay: number) {
let timeoutId = 0 as any
return (...args: any[]) => {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => fn(...args), delay)
}
}
export function throttle<T extends (...args: any[]) => any> (fn: T, limit: number) {
let throttling = false
return (...args: Parameters<T>): void | ReturnType<T> => {
if (!throttling) {
throttling = true
setTimeout(() => throttling = false, limit)
return fn(...args)
}
}
}
export function getPrefixedScopedSlots (prefix: string, scopedSlots: any) {
return Object.keys(scopedSlots).filter(k => k.startsWith(prefix)).reduce((obj: any, k: string) => {
obj[k.replace(prefix, '')] = scopedSlots[k]
return obj
}, {})
}
export function getSlot (vm: Vue, name = 'default', data?: object | (() => object), optional = false) {
if (vm.$scopedSlots[name]) {
return vm.$scopedSlots[name]!(data instanceof Function ? data() : data)
} else if (vm.$slots[name] && (!data || optional)) {
return vm.$slots[name]
}
return undefined
}
export function clamp (value: number, min = 0, max = 1) {
return Math.max(min, Math.min(max, value))
}
export function padEnd (str: string, length: number, char = '0') {
return str + char.repeat(Math.max(0, length - str.length))
}
export function chunk (str: string, size = 1) {
const chunked: string[] = []
let index = 0
while (index < str.length) {
chunked.push(str.substr(index, size))
index += size
}
return chunked
}
export function humanReadableFileSize (bytes: number, binary = false): string {
const base = binary ? 1024 : 1000
if (bytes < base) {
return `${bytes} B`
}
const prefix = binary ? ['Ki', 'Mi', 'Gi'] : ['k', 'M', 'G']
let unit = -1
while (Math.abs(bytes) >= base && unit < prefix.length - 1) {
bytes /= base
++unit
}
return `${bytes.toFixed(1)} ${prefix[unit]}B`
}
export function camelizeObjectKeys (obj: Record<string, any> | null | undefined) {
if (!obj) return {}
return Object.keys(obj).reduce((o: any, key: string) => {
o[camelize(key)] = obj[key]
return o
}, {})
}
export function mergeDeep (
source: Dictionary<any> = {},
target: Dictionary<any> = {}
) {
for (const key in target) {
const sourceProperty = source[key]
const targetProperty = target[key]
// Only continue deep merging if
// both properties are objects
if (
isObject(sourceProperty) &&
isObject(targetProperty)
) {
source[key] = mergeDeep(sourceProperty, targetProperty)
continue
}
source[key] = targetProperty
}
return source
}
export function fillArray<T> (length: number, obj: T) {
return Array(length).fill(obj)
} | the_stack |
import { RetornoProcessamentoNF, Empresa, Endereco, NFCeDocumento, NFeDocumento, DocumentoFiscal, Destinatario, Transporte, Pagamento, Produto, Total,
InfoAdicional, DetalhesProduto, Imposto, Icms, Cofins, Pis, IcmsTot, IssqnTot, DetalhePagamento, DetalhePgtoCartao, RetornoContingenciaOffline, ResponsavelTecnico, ServicosSefaz, II, PisST, Ipi, CofinsST, IcmsUfDest, impostoDevol
} from '../interface/nfe';
import { WebServiceHelper, WebProxy } from "../webservices/webserviceHelper";
import * as schema from '../schema/index';
import { XmlHelper } from '../xmlHelper';
import * as Utils from '../utils/utils';
import { Signature } from '../signature';
import { SefazNFCe } from '../webservices/sefazNfce';
import { SefazNFe } from '../webservices/sefazNfe';
const sha1 = require('sha1');
let soapAutorizacao: any = null;
let soapRetAutorizacao: any = null;
function log(msg: string, processo?: string) {
console.log(`[node-dfe][${processo || 'log'}]->${msg}`);
}
function jsonOneLevel(obj: any): string {
const result: any = {}
for(const k of Object.keys(obj)) {
let logStr = obj[k].toString() || "null";
if(logStr.length > 500) {
logStr = logStr.substring(0, 499)
}
result[k] = logStr
}
return JSON.stringify(result)
}
/**
* Classe para processamento de NFe/NFCe
*/
export class NFeProcessor {
constructor(
private empresa: Empresa,
private responsavelTecnico?: ResponsavelTecnico,
private webProxy?: WebProxy) { }
/**
* Metodo para realizar o processamento de documento(s) do tipo 55 ou 65 de forma sincrona
* @param documento Array de documentos modelo 55 ou 1 documento modelo 65
*/
public async processarDocumento(documento: NFeDocumento | NFCeDocumento) {
let result = <RetornoProcessamentoNF>{
success: false
};
try {
this.configuraUrlsSefaz(documento.docFiscal.modelo, documento.docFiscal.ambiente);
let doc = this.gerarXml(documento);
let xmlAssinado = Signature.signXmlX509(doc.xml, 'infNFe', this.empresa.certificado);
if (documento.docFiscal.modelo == '65') {
let appendQRCode = this.appendQRCodeXML(documento, xmlAssinado);
xmlAssinado = appendQRCode.xml;
doc.nfe.infNFeSupl = appendQRCode.qrCode;
}
let xmlLote = this.gerarXmlLote(xmlAssinado, false);
if (documento.docFiscal.modelo == '65' && documento.docFiscal.isContingenciaOffline) {
result.retornoContingenciaOffline = <RetornoContingenciaOffline>{};
result.success = true;
result.retornoContingenciaOffline.xml_gerado = xmlLote;
} else {
result = await this.transmitirXml(xmlLote, documento.docFiscal.modelo, documento.docFiscal.ambiente, doc.nfe);
}
} catch (ex) {
result.success = false;
result.error = ex;
}
return result;
}
/**
* Metodo para realizar o processamento de documento(s) do tipo 55 ou 65 de forma assincrona
* @param documento Array de documentos modelo 55 ou 1 documento modelo 65
*/
public async processarDocumentoAsync(documento: NFeDocumento | NFCeDocumento) {
let result = <RetornoProcessamentoNF>{
success: false
};
try {
this.configuraUrlsSefaz(documento.docFiscal.modelo, documento.docFiscal.ambiente);
let doc = this.gerarXml(documento);
let xmlAssinado = Signature.signXmlX509(doc.xml, 'infNFe', this.empresa.certificado);
if (documento.docFiscal.modelo == '65') {
let appendQRCode = this.appendQRCodeXML(documento, xmlAssinado);
xmlAssinado = appendQRCode.xml;
doc.nfe.infNFeSupl = appendQRCode.qrCode;
}
let xmlLote = this.gerarXmlLote(xmlAssinado, true);
if (documento.docFiscal.modelo == '65' && documento.docFiscal.isContingenciaOffline) {
result.retornoContingenciaOffline = <RetornoContingenciaOffline>{};
result.success = true;
result.retornoContingenciaOffline.xml_gerado = xmlLote;
} else {
result = await this.transmitirXml(xmlLote, documento.docFiscal.modelo, documento.docFiscal.ambiente, doc.nfe);
}
} catch (ex) {
result.success = false;
result.error = ex;
}
return result;
}
private configuraUrlsSefaz(modelo: string, ambiente: string) {
if (!soapAutorizacao || !soapRetAutorizacao) {
let Sefaz = modelo == '65' ? SefazNFCe : SefazNFe;
soapAutorizacao = Sefaz.getSoapInfo(this.empresa.endereco.uf, ambiente, ServicosSefaz.autorizacao);
soapRetAutorizacao = Sefaz.getSoapInfo(this.empresa.endereco.uf, ambiente, ServicosSefaz.retAutorizacao);
}
}
private appendQRCodeXML(documento: NFCeDocumento, xmlAssinado: string){
let qrCode = null;
let xmlAssinadoObj = XmlHelper.deserializeXml(xmlAssinado, { explicitArray: false });
let chave = Object(xmlAssinadoObj).NFe.infNFe.$.Id.replace('NFe', '');
if (documento.docFiscal.isContingenciaOffline) {
let diaEmissao = documento.docFiscal.dhEmissao.substring(8,10);
let valorTotal = documento.total.icmsTot.vNF;
let digestValue = Object(xmlAssinadoObj).NFe.Signature.SignedInfo.Reference.DigestValue;
qrCode = this.gerarQRCodeNFCeOffline(soapAutorizacao.urlQRCode, chave, '2', documento.docFiscal.ambiente, diaEmissao, valorTotal, digestValue, this.empresa.idCSC, this.empresa.CSC);
} else {
qrCode = this.gerarQRCodeNFCeOnline(soapAutorizacao.urlQRCode, chave, '2', documento.docFiscal.ambiente, this.empresa.idCSC, this.empresa.CSC);
}
let qrCodeObj = <schema.TNFeInfNFeSupl>{
qrCode: '<' + qrCode + '>',
urlChave: soapAutorizacao.urlChave
};
let qrCodeXml = XmlHelper.serializeXml(qrCodeObj, 'infNFeSupl').replace('>]]>', ']]>').replace('<![CDATA[<', '<![CDATA[');
return {
qrCode: qrCodeObj,
xml: xmlAssinado.replace('</infNFe><Signature', '</infNFe>' + qrCodeXml + '<Signature')
};
}
public async transmitirXml(xmlLote: string, modelo: string, ambiente: string, nfeObj: Object){
let result = <RetornoProcessamentoNF>{
success: false,
nfe: nfeObj
};
try {
let retEnviNFe = null;
if (!nfeObj) {
let xmlObj = XmlHelper.deserializeXml(xmlLote, { explicitArray: false });
result.nfe = Object(xmlObj).enviNFe.NFe;
}
this.configuraUrlsSefaz(modelo, ambiente);
let retornoEnvio = await this.enviarNF(xmlLote, this.empresa.certificado);
try {
log(jsonOneLevel({
success: !!retornoEnvio ? retornoEnvio.success : false,
retornoEnvio: !!retornoEnvio,
data: !retornoEnvio ? false : !!retornoEnvio.data
}), 'retornoEnvio.exists')
log(jsonOneLevel(retornoEnvio), 'retornoEnvio.full');
} catch(e) {
log(`ja deu erro pra logar.......${e.toString()}`, 'retornoEnvio')
}
if (retornoEnvio && retornoEnvio.data) {
const data = Object(retornoEnvio.data);
if (data.retEnviNFe) {
retEnviNFe = data.retEnviNFe;
}
} else {
throw new Error('Erro ao realizar requisição');
}
console.log(retEnviNFe && retEnviNFe.cStat == '104' && retEnviNFe.protNFe.infProt.cStat == '100');
console.log(retEnviNFe && retEnviNFe.cStat == '103');
result.envioNF = retornoEnvio;
if (retEnviNFe && retEnviNFe.cStat == '104' && retEnviNFe.protNFe.infProt.cStat == '100') {
// retorno síncrono
result.success = true;
} else if (retEnviNFe && retEnviNFe.cStat == '103') {
let recibo = retEnviNFe.infRec.nRec;
let xmlConRecNFe = this.gerarXmlConsultaProc(ambiente, recibo);
let retornoConsulta = null;
let retConsReciNFe = null;
let cStat = '105';
do {
retornoConsulta = await this.consultarProc(xmlConRecNFe, this.empresa.certificado);
try {
log(jsonOneLevel({
retornoConsulta: !!retornoConsulta,
data: !retornoConsulta ? false : !!retornoConsulta.data
}), 'retornoConsulta.exists')
log(jsonOneLevel(retornoConsulta), 'retornoConsulta.data');
} catch(e) {
log('ja deu erro pra logar.......', 'retornoConsulta')
}
retConsReciNFe = Object(retornoConsulta.data).retConsReciNFe;
cStat = retConsReciNFe.cStat;
} while (cStat == '105'); // nota em processamento, realiza a consulta novamente até obter um status diferente.
result.consultaProc = retornoConsulta;
if (cStat == '104' && retConsReciNFe.protNFe.infProt.cStat == '100') {
result.success = true;
}
} else {
result.success = false;
}
} catch (ex) {
result.success = false;
result.error = ex;
}
return result;
}
private async consultarProc(xml:string, cert: any) {
return await WebServiceHelper.makeSoapRequest(
xml, cert, soapRetAutorizacao, this.webProxy
);
}
private async enviarNF(xml: string, cert: any) {
return await WebServiceHelper.makeSoapRequest(
xml, cert, soapAutorizacao, this.webProxy
);
}
private gerarXmlConsultaProc(ambiente: string, recibo: string){
let consulta = <schema.TConsReciNFe> {
$: {versao: '4.00', xmlns: 'http://www.portalfiscal.inf.br/nfe'},
tpAmb: ambiente,
nRec: recibo
};
return XmlHelper.serializeXml(consulta, 'consReciNFe');
}
private gerarXmlLote(xml: string, isAsync: boolean){
//TODO: ajustar para receber uma lista de xmls...
let loteId = Utils.randomInt(1,999999999999999).toString();
let enviNFe = <schema.TEnviNFe>{
$: { versao: '4.00', xmlns: 'http://www.portalfiscal.inf.br/nfe'},
idLote: loteId,
indSinc: isAsync ? schema.TEnviNFeIndSinc.Item0 : schema.TEnviNFeIndSinc.Item1,
_: '[XMLS]'
};
let xmlLote = XmlHelper.serializeXml(enviNFe, 'enviNFe');
return xmlLote.replace('[XMLS]', xml);
}
private gerarXml(documento: NFeDocumento | NFCeDocumento) {
if (documento.docFiscal.modelo == '65' && documento.docFiscal.isContingenciaOffline)
documento.docFiscal.tipoEmissao = '9';
let dadosChave = this.gerarChaveNF(this.empresa, documento.docFiscal);
let NFe = <schema.TNFe> {
$: {
xmlns: 'http://www.portalfiscal.inf.br/nfe'
},
infNFe: documento.docFiscal.modelo == '65' ? this.gerarNFCe(documento as NFCeDocumento, dadosChave) : this.gerarNFe(documento as NFeDocumento, dadosChave)
};
Utils.removeSelfClosedFields(NFe);
return {
nfe: NFe,
xml: XmlHelper.serializeXml(NFe, 'NFe')
};
}
private gerarChaveNF(empresa: Empresa, docFiscal: DocumentoFiscal){
let chave = '';
let ano = docFiscal.dhEmissao.substring(2,4);
let mes = docFiscal.dhEmissao.substring(5,7);
chave += (docFiscal.codUF.padStart(2,'0'));
chave += (ano + mes);
chave += (empresa.cnpj.padStart(14,'0'));
chave += (docFiscal.modelo.padStart(2,'0'));
chave += (docFiscal.serie.padStart(3,'0'));
chave += (docFiscal.numeroNota.toString().padStart(9, '0'));
chave += (docFiscal.tipoEmissao);
let cnf = (Utils.randomInt(10000000, 99999999)).toString();
chave += cnf;
let digitoVerificador = this.obterDigitoVerificador(chave);
chave += digitoVerificador;
return {
chave: chave,
cnf: cnf,
dv: digitoVerificador
};
}
private obterDigitoVerificador(chave: any) {
let soma = 0;
let mod = -1;
let dv = -1;
let peso = 2;
let chaveArr = chave.split('');
for (let i = chaveArr.length - 1; i !== -1; i--)
{
let ch = Number(chaveArr[i].toString());
soma += ch*peso;
if (peso < 9)
peso += 1;
else
peso = 2;
}
mod = soma%11;
if (mod === 0 || mod === 1)
dv = 0;
else
dv = 11 - mod;
return dv.toString();
}
private gerarQRCodeNFCeOnline(urlQRCode: string, chave: string, versaoQRCode: string, ambiente: string, idCSC: string, CSC: string) {
let s = '|';
let concat = [chave, versaoQRCode, ambiente, Number(idCSC)].join(s);
let hash = sha1(concat + CSC).toUpperCase();
return urlQRCode + '?p=' + concat + s + hash;
}
private gerarQRCodeNFCeOffline(urlQRCode: string, chave: string, versaoQRCode: string, ambiente: string, diaEmissao: string, valorTotal:string, digestValue: string, idCSC: string, CSC: string) {
let s = '|';
let hexDigestValue = Buffer.from(digestValue).toString('hex');
let concat = [chave, versaoQRCode, ambiente, diaEmissao, valorTotal, hexDigestValue, Number(idCSC)].join(s);
let hash = sha1(concat + CSC).toUpperCase();
return urlQRCode + '?p=' + concat + s + hash;
}
private gerarNFe(documento: NFeDocumento, dadosChave: any) {
let nfe = <schema.TNFeInfNFe> {
$: { versao: '4.00', Id: 'NFe' + dadosChave.chave }
};
nfe.ide = this.getIde(documento.docFiscal, dadosChave);
nfe.emit = this.getEmit(this.empresa);
//nfe.avulsa = ;
nfe.dest = this.getDest(documento.destinatario, documento.docFiscal.ambiente);
//nfe.retirada = ;
//nfe.entrega = ;
//nfe.autXML = ;
nfe.det = this.getDet(documento.produtos, documento.docFiscal.ambiente, documento.docFiscal.modelo, );
nfe.total = this.getTotal(documento.total);
nfe.transp = this.getTransp(documento.transporte);
//nfe.cobr =
nfe.pag = this.getPag(documento.pagamento);
nfe.infAdic = this.getInfoAdic(documento.infoAdicional);
//nfe.exporta = ;
//nfe.compra = ;
//nfe.cana = ;
if (this.responsavelTecnico)
nfe.infRespTec = this.getResponsavelTecnico(this.responsavelTecnico, dadosChave.chave);
return nfe;
}
private gerarNFCe(documento: NFCeDocumento, dadosChave: any) {
let nfce = <schema.TNFeInfNFe> {
$: { versao: '4.00', Id: 'NFe' + dadosChave.chave }
};
nfce.ide = this.getIde(documento.docFiscal, dadosChave);
nfce.emit = this.getEmit(this.empresa);
if (documento.destinatario)
nfce.dest = this.getDest(documento.destinatario, documento.docFiscal.ambiente);
nfce.det = this.getDet(documento.produtos, documento.docFiscal.ambiente, documento.docFiscal.modelo);
nfce.total = this.getTotal(documento.total);
nfce.transp = this.getTransp(documento.transporte);
nfce.pag = this.getPag(documento.pagamento);
nfce.infAdic = this.getInfoAdic(documento.infoAdicional);
if (this.responsavelTecnico)
nfce.infRespTec = this.getResponsavelTecnico(this.responsavelTecnico, dadosChave.chave);
return nfce;
}
private getIde(documento: DocumentoFiscal, dadosChave: any) {
let ide = <schema.TNFeInfNFeIde> {
cUF: Utils.getEnumByValue(schema.TCodUfIBGE, documento.codUF),
cNF: dadosChave.cnf,
natOp: documento.naturezaOperacao,
mod: Utils.getEnumByValue(schema.TMod, documento.modelo),
serie: documento.serie,
nNF: documento.numeroNota,
dhEmi: documento.dhEmissao,
tpNF: Utils.getEnumByValue(schema.TNFeInfNFeIdeTpNF, documento.tipoDocumentoFiscal),
idDest: Utils.getEnumByValue(schema.TNFeInfNFeIdeIdDest, documento.identificadorDestinoOperacao),
cMunFG: documento.codIbgeFatoGerador,
tpImp: Utils.getEnumByValue(schema.TNFeInfNFeIdeTpImp, documento.tipoImpressao),
tpEmis: Utils.getEnumByValue(schema.TNFeInfNFeIdeTpEmis, documento.tipoEmissao),
cDV: dadosChave.dv,
tpAmb: Utils.getEnumByValue(schema.TAmb, documento.ambiente),
finNFe: Utils.getEnumByValue(schema.TFinNFe, documento.finalidadeEmissao),
indFinal: Utils.getEnumByValue(schema.TNFeInfNFeIdeIndFinal, documento.indConsumidorFinal),
indPres: Utils.getEnumByValue(schema.TNFeInfNFeIdeIndPres, documento.indPresenca),
procEmi: Utils.getEnumByValue(schema.TProcEmi, documento.processoEmissao),
verProc: documento.versaoAplicativoEmissao,
dhSaiEnt: documento.dhSaiEnt,
dhCont: documento.dhContingencia,
xJust: documento.justificativaContingencia,
//nFref: schema.TNFeInfNFeIdeNFref[],
};
return ide;
}
private getEmit(empresa: Empresa) {
return <schema.TNFeInfNFeEmit> {
CNPJ: empresa.cnpj,
xNome: empresa.razaoSocial,
xFant: empresa.nomeFantasia,
enderEmit: this.getEnderEmit(empresa.endereco),
IE: empresa.inscricaoEstadual,
IM: empresa.inscricaoMunicipal,
CRT: empresa.codRegimeTributario,
iEST: empresa.inscricaoEstadualST,
CNAE: empresa.CNAE
}
}
private getEnderEmit(endereco: Endereco){
return <schema.TEnderEmi>{
xLgr: endereco.logradouro,
nro: endereco.numero,
xCpl: endereco.complemento,
xBairro: endereco.bairro,
cMun: endereco.codMunicipio,
xMun: endereco.municipio,
UF: Utils.getEnumByValue(schema.TUfEmi, endereco.uf),
CEP: endereco.cep,
cPais: schema.TEnderEmiCPais.Item1058,
xPais: schema.TEnderEmiXPais.BRASIL,
fone: endereco.telefone,
}
}
private getEnderDest(endereco: Endereco){
return <schema.TEndereco>{
xLgr: endereco.logradouro,
nro: endereco.numero,
xCpl: endereco.complemento,
xBairro: endereco.bairro,
cMun: endereco.codMunicipio,
xMun: endereco.municipio,
UF: Utils.getEnumByValue(schema.TUf, endereco.uf),
CEP: endereco.cep,
cPais: endereco.codPais,
xPais: endereco.pais,
fone: endereco.telefone,
}
}
private getDest(destinatario: Destinatario, ambiente: string) {
let dest = <schema.TNFeInfNFeDest>{};
if (destinatario.isEstrangeiro)
dest.idEstrangeiro = destinatario.documento;
if (destinatario.documento.length == 14)
dest.CNPJ = destinatario.documento;
else
dest.CPF = destinatario.documento;
dest.xNome = ambiente == '2' ? 'NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL' : destinatario.nome;
if (destinatario.endereco)
dest.enderDest = this.getEnderDest(destinatario.endereco);
dest.indIEDest = Utils.getEnumByValue(schema.TNFeInfNFeDestIndIEDest, destinatario.indicadorIEDestinario);
dest.IE = destinatario.inscricaoEstadual;
dest.ISUF = destinatario.inscricaoSuframa;
dest.IM = destinatario.inscricaoMunicipal;
dest.email = destinatario.email;
return dest;
}
private getDet(produtos: Produto[], ambiente: string, modelo: string) {
let det_list = [];
for (let i = 0; i < produtos.length; i++){
det_list.push(<schema.TNFeInfNFeDet>{
$: {nItem: produtos[i].numeroItem},
prod: this.getDetProd(produtos[i].prod, ambiente, i == 0),
imposto: this.getDetImposto(produtos[i].imposto, modelo, produtos[i].prod.CFOP ),
infAdProd: produtos[i].infoAdicional,
impostoDevol: (produtos[i].prod.percentualDevolucao && (produtos[i].prod.percentualDevolucao > 0)) ? this.getImpostoDevolucao({ pDevol: produtos[i].prod.percentualDevolucao, vIPIDevol: produtos[i].prod.valorIPIDevolucao }) : undefined
});
}
return det_list;
}
private getDetProd(produto: DetalhesProduto, ambiente: string, isPrimeiroProduto: boolean) {
return <schema.TNFeInfNFeDetProd>{
cProd: produto.codigo,
cEAN: produto.cEAN,
xProd: (ambiente == '2' && isPrimeiroProduto) ? 'NOTA FISCAL EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL' : produto.descricao,
NCM: produto.NCM,
//nVE: string[];
CEST: produto.cest,
//indEscala: TNFeInfNFeDetProdIndEscala;
cNPJFab: produto.cNPJFab,
cBenef: produto.cBenef,
eXTIPI: produto.eXTIPI,
CFOP: produto.CFOP,
uCom: produto.unidadeComercial,
qCom: produto.quantidadeComercial,
vUnCom: produto.valorUnitarioComercial,
vProd: produto.valorTotal,
cEANTrib: produto.cEANTrib,
uTrib: produto.unidadeTributavel,
qTrib: produto.quantidadeTributavel,
vUnTrib: produto.valorUnitarioTributavel,
vFrete: produto.valorFrete,
vSeg: produto.valorSeguro,
vDesc: produto.valorDesconto,
vOutro: produto.valorOutro,
indTot: produto.indicadorTotal,
//di: TNFeInfNFeDetProdDI[];
//detExport: TNFeInfNFeDetProdDetExport[];
xPed: produto.numeroPedido,
nItemPed: produto.numeroItemPedido,
//nFCI: string;
//rastro: TNFeInfNFeDetProdRastro[];
//arma
//comb
//med
//nRECOPI
//veicProd
}
}
private getDetImposto(imposto: Imposto, modelo: string, cfop: string) {
let detImposto = <schema.TNFeInfNFeDetImposto>{
vTotTrib: imposto.valorAproximadoTributos,
ICMS: [this.getImpostoIcms(imposto.icms)],
PIS: [this.getImpostoPIS(imposto.pis, modelo)],
COFINS: [this.getImpostoCOFINS(imposto.cofins, modelo)],
PISST: [this.getImpostoPISST(imposto.pisst)],
COFINSST: [this.getImpostoCOFINSST(imposto.cofinsst)],
IPI: [this.getImpostoIPI(imposto.ipi, modelo)],
II: [this.getImpostoII(imposto.ii, cfop)],
ICMSUFDest: [this.getIcmsUfDest(imposto.icmsUfDest)],
ISSQN: '',
};
return detImposto;
}
private getImpostoIcms(icms: Icms) {
let result;
if (icms.CST && icms.CST !== '') {
switch (icms.CST) {
case '00':
result = {
ICMS00: <schema.TNFeInfNFeDetImpostoICMSICMS00> {
orig: icms.orig,
CST: icms.CST,
modBC: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMS00ModBC, icms.modBC),
vBC: icms.vBC,
pICMS: icms.pICMS,
vICMS: icms.vICMS,
pFCP: icms.pFCP,
vFCP: icms.vFCP
}
}
break;
case '10':
// partilha icms
if (icms.UFST && icms.UFST !== '' && icms.pBCOp && icms.pBCOp !== '') {
result = {
ICMS10: <schema.TNFeInfNFeDetImpostoICMSICMSPart> {
orig: icms.orig,
CST: icms.CST,
modBC: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMSPartModBC, icms.modBC),
vBC: icms.vBC,
pRedBC: icms.pRedBC,
pICMS: icms.pICMS,
vICMS: icms.vICMS,
modBCST: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMSPartModBCST, icms.modBCST),
pMVAST: icms.pMVAST,
pRedBCST: icms.pRedBCST,
vBCST: icms.vBCST,
pICMSST: icms.pICMSST,
vICMSST: icms.vICMSST,
pBCOp: icms.pBCOp,
UFST: Utils.getEnumByValue(schema.TUf, icms.UFST),
}
}
} else {
result = {
ICMS10: <schema.TNFeInfNFeDetImpostoICMSICMS10> {
orig: icms.orig,
CST: icms.CST,
modBC: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMS10ModBC, icms.modBC),
pICMS: icms.pICMS,
vBC: icms.vBC,
vICMS: icms.vICMS,
pFCP: icms.pFCP,
vFCP: icms.vFCP,
modBCST: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMS10ModBCST, icms.modBCST),
pFCPST: icms.pFCPST,
pICMSST: icms.pICMSST,
pMVAST: icms.pMVAST,
pRedBCST: icms.pRedBCST,
vBCFCP: icms.vBCFCP,
vBCFCPST: icms.vBCFCPST,
vBCST: icms.vBCST,
vFCPST: icms.vFCPST,
vICMSST: icms.vICMSST,
}
}
}
break;
case '20':
result = {
ICMS20: <schema.TNFeInfNFeDetImpostoICMSICMS20>{
orig: icms.orig,
CST: icms.CST,
modBC: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMS20ModBC, icms.modBC),
pRedBC: icms.pRedBC,
vBC: icms.vBC,
pICMS: icms.pICMS,
vICMS: icms.vICMS,
vBCFCP: icms.vBCFCP,
pFCP: icms.pFCP,
vFCP: icms.vFCP,
vICMSDeson: icms.vICMSDeson,
motDesICMS: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMS20MotDesICMS, icms.motDesICMS)
}
}
break;
case '30':
result = {
ICMS30: <schema.TNFeInfNFeDetImpostoICMSICMS30> {
orig: icms.orig,
CST: icms.CST,
modBCST: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMS30ModBCST, icms.modBCST),
pMVAST: icms.pMVAST,
pRedBCST: icms.pRedBCST,
vBCST: icms.vBCST,
pICMSST: icms.pICMSST,
vICMSST: icms.vICMSST,
motDesICMS: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMS30MotDesICMS, icms.motDesICMS),
vICMSDeson: icms.vICMSDeson,
vBCFCPST: icms.vBCFCPST,
pFCPST: icms.pFCPST,
vFCPST: icms.vFCPST
}
}
break;
case '40':
case '50':
result = {
ICMS40: <schema.TNFeInfNFeDetImpostoICMSICMS40> {
orig: icms.orig,
CST: icms.CST,
motDesICMS : Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMS40MotDesICMS, icms.motDesICMS),
vICMSDeson: icms.vICMSDeson
}
}
break;
case '41':
if (icms.vBCSTRet && icms.vBCSTRet !== '') {
result = {
ICMS41: <schema.TNFeInfNFeDetImpostoICMSICMSST> {
orig: icms.orig,
CST: icms.CST,
vBCSTRet: icms.vBCSTRet,
vICMSSTRet: icms.vICMSSTRet,
vBCSTDest: icms.vBCSTDest,
vICMSSTDest: icms.vICMSSTDest,
//pFCPSTRet: '',
//pST: '',
//vBCFCPSTRet: '',
//vFCPSTRet: '',
pRedBCEfet: icms.pRedBCEfet,
vBCEfet: icms.vBCEfet,
pICMSEfet: icms.pICMSEfet,
vICMSEfet: icms.vICMSEfet,
//vICMSSubstituto: '',
}
}
} else {
result = {
ICMS40: <schema.TNFeInfNFeDetImpostoICMSICMS40> {
orig: icms.orig,
CST: icms.CST,
motDesICMS : Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMS40MotDesICMS, icms.motDesICMS),
vICMSDeson: icms.vICMSDeson
}
}
}
break;
case '51':
result = {
ICMS51: <schema.TNFeInfNFeDetImpostoICMSICMS51> {
orig: icms.orig,
CST: icms.CST,
modBC: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMS51ModBC,icms.modBC),
vBC: icms.vBC,
pRedBC: icms.pRedBC,
pICMS: icms.pICMS,
vICMS: icms.vICMS,
pDif: icms.pDif,
vICMSDif: icms.vICMSDif,
vICMSOp: icms.vICMSOp,
vBCFCP: icms.vBCFCP,
pFCP: icms.pFCP,
vFCP: icms.vFCP
}
}
break;
case '60':
result = {
ICMS60: <schema.TNFeInfNFeDetImpostoICMSICMS60> {
orig: icms.orig,
CST: icms.CST,
vBCSTRet: icms.vBCSTRet,
vICMSSTRet: icms.vICMSSTRet,
pST: icms.pST,
vBCFCPSTRet: icms.vBCFCPSTRet,
pFCPSTRet: icms.pFCPSTRet,
vFCPSTRet: icms.vFCPSTRet,
pRedBCEfet: icms.pRedBCEfet,
vBCEfet: icms.vBCEfet,
pICMSEfet: icms.pICMSEfet,
vICMSEfet: icms.vICMSEfet,
//vICMSSubstituto: '',
}
}
break;
case '70':
result = {
ICMS70: <schema.TNFeInfNFeDetImpostoICMSICMS70> {
orig: icms.orig,
CST: icms.CST,
modBC: icms.modBC,
vBC: icms.vBC,
pRedBC: icms.pRedBC,
pICMS: icms.pICMS,
vICMS: icms.vICMS,
modBCST: icms.modBCST,
pMVAST: icms.pMVAST,
pRedBCST: icms.pRedBCST,
vBCST: icms.vBCST,
pICMSST: icms.pICMSST,
vICMSST: icms.vICMSST,
motDesICMS: icms.motDesICMS,
vICMSDeson: icms.vICMSDeson,
vBCFCP: icms.vBCFCP,
pFCP: icms.pFCP,
vFCP: icms.vFCP,
vBCFCPST: icms.vBCFCPST,
pFCPST: icms.pFCPST,
vFCPST: icms.vFCPST,
}
}
break;
case '90':
// partilha icms
if (icms.UFST && icms.UFST !== '' && icms.pBCOp && icms.pBCOp !== '') {
result = {
ICMS90: <schema.TNFeInfNFeDetImpostoICMSICMSPart> {
orig: icms.orig,
CST: icms.CST,
modBC: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMSPartModBC, icms.modBC),
vBC: icms.vBC,
pRedBC: icms.pRedBC,
pICMS: icms.pICMS,
vICMS: icms.vICMS,
modBCST: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMSPartModBCST, icms.modBCST),
pMVAST: icms.pMVAST,
pRedBCST: icms.pRedBCST,
vBCST: icms.vBCST,
pICMSST: icms.pICMSST,
vICMSST: icms.vICMSST,
pBCOp: icms.pBCOp,
UFST: Utils.getEnumByValue(schema.TUf, icms.UFST)
}
}
} else {
result = {
ICMS90: <schema.TNFeInfNFeDetImpostoICMSICMS90> {
orig: icms.orig,
CST: icms.CST,
modBC: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMS90ModBC, icms.modBC),
vBC: icms.vBC,
pRedBC: icms.pRedBC,
pICMS: icms.pICMS,
vICMS: icms.vICMS,
modBCST: icms.modBCST,
pMVAST: icms.pMVAST,
pRedBCST: icms.pRedBCST,
vBCST: icms.vBCST,
pICMSST: icms.pICMSST,
vICMSST: icms.vICMSST,
motDesICMS: Utils.getEnumByValue(schema.TNFeInfNFeDetImpostoICMSICMS90MotDesICMS, icms.motDesICMS),
vICMSDeson: icms.vICMSDeson,
vBCFCP: icms.vBCFCP,
pFCP: icms.pFCP,
vFCP: icms.vFCP,
vBCFCPST: icms.vBCFCPST,
vFCPST: icms.vFCPST,
}
}
}
break;
default:
//throw exception?
break;
}
} else {
// Simples Nacional
switch(icms.CSOSN) {
case '101':
result = {
ICMSSN101: <schema.TNFeInfNFeDetImpostoICMSICMSSN101> {
orig: icms.orig,
CSOSN: icms.CSOSN,
pCredSN: icms.pCredSN,
vCredICMSSN: icms.vCredICMSSN
}
}
break;
case '102':
case '103':
case '300':
case '400':
result = {
ICMSSN102: <schema.TNFeInfNFeDetImpostoICMSICMSSN102> {
orig: icms.orig,
CSOSN: icms.CSOSN
}
}
break;
case '201':
result = {
ICMSSN201: <schema.TNFeInfNFeDetImpostoICMSICMSSN201> {
orig: icms.orig,
CSOSN: icms.CSOSN,
modBCST: icms.modBCST,
pMVAST: icms.pMVAST,
pRedBCST: icms.pRedBCST,
vBCST: icms.vBCST,
pICMSST: icms.pICMSST,
vICMSST: icms.vICMSST,
pCredSN: icms.pCredSN,
vCredICMSSN: icms.vCredICMSSN,
vBCFCPST: icms.vBCFCPST,
pFCPST: icms.pFCPST,
vFCPST: icms.vFCPST
}
}
break;
case '202':
case '203':
result = {
ICMSSN202: <schema.TNFeInfNFeDetImpostoICMSICMSSN202> {
orig: icms.orig,
CSOSN: icms.CSOSN,
modBCST: icms.modBCST,
pMVAST: icms.pMVAST,
pRedBCST: icms.pRedBCST,
vBCST: icms.vBCST,
pICMSST: icms.pICMSST,
vICMSST: icms.vICMSST,
vBCFCPST: icms.vBCFCPST,
pFCPST: icms.pFCPST,
vFCPST: icms.vFCPST
}
}
break;
case '500':
result = {
ICMSSN500: <schema.TNFeInfNFeDetImpostoICMSICMSSN500>{
orig: icms.orig,
CSOSN: icms.CSOSN,
vBCSTRet: icms.vBCSTRet,
vICMSSTRet: icms.vICMSSTRet,
vBCFCPSTRet: icms.vBCFCPSTRet,
pFCPSTRet: icms.pFCPSTRet,
vFCPSTRet: icms.vFCPSTRet,
pRedBCEfet: icms.pRedBCEfet,
vBCEfet: icms.vBCEfet,
pICMSEfet: icms.pICMSEfet,
vICMSEfet: icms.vICMSEfet,
}
}
break;
case '900':
result = {
ICMSSN900: <schema.TNFeInfNFeDetImpostoICMSICMSSN900> {
orig: icms.orig,
CSOSN: icms.CSOSN,
modBC: icms.modBC,
vBC: icms.vBC,
pRedBC: icms.pRedBC,
pICMS: icms.pICMS,
vICMS: icms.vICMS,
modBCST: icms.modBCST,
pMVAST: icms.pMVAST,
pRedBCST: icms.pRedBCST,
vBCST: icms.vBCST,
pICMSST: icms.pICMSST,
vICMSST: icms.vICMSST,
pCredSN: icms.pCredSN,
vCredICMSSN: icms.vCredICMSSN,
vBCFCPST: icms.vBCFCPST,
pFCPST: icms.pFCPST,
vFCPST: icms.vFCPST
}
}
break;
}
}
return result;
}
// private getImpostoII() {
// return <schema.TNFeInfNFeDetImpostoII> {
// vBC: '',
// vDespAdu: '',
// vII: '',
// vIOF: ''
// }
// }
private getImpostoISSQN() {
return <schema.TNFeInfNFeDetImpostoISSQN> {
vBC: '',
vAliq: '',
vISSQN: '',
cMunFG: '',
cListServ: schema.TCListServ.Item0101,
vDeducao: '',
vOutro: '',
vDescIncond: '',
vDescCond: '',
vISSRet: '',
indISS: schema.TNFeInfNFeDetImpostoISSQNIndISS.Item1,
cServico: '',
cMun: '',
cPais: '',
nProcesso: '',
indIncentivo: schema.TNFeInfNFeDetImpostoISSQNIndIncentivo.Item1
}
}
private getImpostoIPI(ipi: Ipi, modelo: string) {
let result;
if (modelo != '55' || !ipi) return; //não deve gerar grupo IPI para NFCe
// if (!GerarTagIPIparaNaoTributado) && (!['00', '49', '50', '99'].includes(ipi.CST)) return;
//se valores padrão de quando não foi preenchido a TAG IPI
if ((ipi.cEnq = '') && (ipi.CST = '00') && (ipi.vBC = 0) && (ipi.qUnid = 0) && (ipi.vUnid = 0) && (ipi.pIPI = 0) && (ipi.vIPI = 0)) return;
if ((ipi.vBC + ipi.pIPI > 0) && (ipi.qUnid + ipi.vUnid > 0)) throw 'As TAG <vBC> e <pIPI> não podem ser informadas em conjunto com as TAG <qUnid> e <vUnid>';
result = {
IPI: <schema.TIpi> {
CNPJProd: ipi.CNPJProd,
cSelo: ipi.cSelo,
qSelo: ipi.qSelo,
cEnq: ipi.cEnq || '999',
}
}
if (ipi.qUnid + ipi.vUnid > 0) {
result.IPI.IPITrib = <schema.TIpiIPITrib> {
CST: ipi.CST,
qUnid: ipi.qUnid,
vUnid: ipi.vUnid,
vIPI: ipi.vIPI,
}
} else {
result.IPI.IPITrib = <schema.TIpiIPITrib> {
CST: ipi.CST,
vBC: ipi.vBC,
pIPI: ipi.pIPI,
vIPI: ipi.vIPI,
}
}
// result.IPI.IPINT = { CST: ipi.CST }
return result;
}
private getImpostoII(ii: II, cfop: string) {
if (!ii) return;
if ((ii.vBC > 0) || (ii.vDespAdu > 0) || (ii.vII > 0) || (ii.vIOF > 0) || (cfop[0] === '3')) {
return {
vBC: ii.vBC,
vDespAdu: ii.vDespAdu,
vII: ii.vII,
vIOF: ii.vIOF
};
}
return ;
}
private getImpostoPIS(pis: Pis, modelo: string) {
let result;
if ((modelo != '55') &&
((pis.vBC == 0) && (pis.pPIS = 0) && (pis.vPIS = 0) &&
(pis.qBCProd = 0) && (pis.vAliqProd = 0) &&
(!['04', '05', '06', '07', '08', '09', '49', '99'].includes(pis.CST)))) return undefined;
if (!pis && modelo == '55') throw 'NF-e sem grupo do PIS'
switch (pis.CST) {
case '01':
case '02':
result = {
PISAliq: <schema.TNFeInfNFeDetImpostoPIS> {
CST: pis.CST,
vBC: pis.vBC,
pPIS: pis.pPIS,
vPIS: pis.vPIS,
}
};
break;
case '03':
result = {
PISQtde: <schema.TNFeInfNFeDetImpostoPIS> {
CST: pis.CST,
vBCProd: pis.vBCProd,
vAliqProd: pis.vAliqProd,
vPIS: pis.vPIS,
}
}
break;
case '04':
case '05':
case '06':
case '07':
case '08':
case '09':
result = {
PISNT: <schema.TNFeInfNFeDetImpostoPIS> {
CST: pis.CST
}
}
case '49':
case '50':
case '51':
case '52':
case '53':
case '54':
case '55':
case '56':
case '60':
case '61':
case '62':
case '63':
case '64':
case '65':
case '66':
case '67':
case '70':
case '71':
case '72':
case '73':
case '74':
case '75':
case '98':
case '99':
if ((pis.vBC + pis.pPIS > 0) && (pis.qBCProd + pis.vAliqProd > 0)) throw 'As TAG <vBC> e <pPIS> não podem ser informadas em conjunto com as TAG <qBCProd> e <vAliqProd>'
if (pis.qBCProd + pis.vAliqProd <= 0) return undefined;
result = {
PISOutr: <schema.TNFeInfNFeDetImpostoPIS> {
CST: pis.CST,
qBCProd: pis.qBCProd,
vAliqProd: pis.vAliqProd,
vPIS: pis.vPIS
}
}
default:
result = {
PISOutr: <schema.TNFeInfNFeDetImpostoPIS> {
CST: pis.CST,
vBC: pis.vBC,
pPIS: pis.pPIS,
vPIS: pis.vPIS
}
}
break;
}
return result;
}
private getImpostoCOFINS(cofins: Cofins, modelo: string) {
let result;
if ((modelo != '55') &&
((cofins.vBC == 0) && (cofins.pCOFINS = 0) && (cofins.vCOFINS = 0) &&
(cofins.qBCProd = 0) && (cofins.vAliqProd = 0) &&
(!['04', '05', '06', '07', '08', '09', '49', '99'].includes(cofins.CST)))) return undefined;
//No caso da NFC-e, o grupo de tributação do PIS e o grupo de tributação da COFINS são opcionais.
if (!cofins && modelo == '55') throw 'NF-e sem grupo do COFINS'
switch (cofins.CST) {
case '01':
case '02':
result = {
COFINSAliq: <schema.TNFeInfNFeDetImpostoCOFINS> {
CST: cofins.CST,
vBC: cofins.vBC,
pCOFINS: cofins.pCOFINS,
vCOFINS: cofins.vCOFINS,
}
};
break;
case '03':
result = {
COFINSQtde: <schema.TNFeInfNFeDetImpostoCOFINS> {
CST: cofins.CST,
qBCProd: cofins.qBCProd,
vAliqProd: cofins.vAliqProd,
vCOFINS: cofins.vCOFINS
}
}
break;
case '04':
case '05':
case '06':
case '07':
case '08':
case '09':
result = {
COFINSNT: <schema.TNFeInfNFeDetImpostoCOFINS> {
CST: cofins.CST
}
}
break;
case '49':
case '50':
case '51':
case '52':
case '53':
case '54':
case '55':
case '56':
case '60':
case '61':
case '62':
case '63':
case '64':
case '65':
case '66':
case '67':
case '70':
case '71':
case '72':
case '73':
case '74':
case '75':
case '98':
case '99':
if ((cofins.vBC + cofins.pCOFINS > 0) && (cofins.qBCProd + cofins.vAliqProd > 0)) throw 'As TAG <vBC> e <pCOFINS> não podem ser informadas em conjunto com as TAG <qBCProd> e <vAliqProd>'
if (cofins.qBCProd + cofins.vAliqProd <= 0) return undefined;
result = {
COFINSOutr: <schema.TNFeInfNFeDetImpostoCOFINS> {
CST: cofins.CST,
qBCProd: cofins.qBCProd,
vAliqProd: cofins.vAliqProd,
vCOFINS: cofins.vCOFINS
}
}
break
default:
result = {
COFINSOutr: <schema.TNFeInfNFeDetImpostoCOFINS> {
CST: cofins.CST,
vBC: cofins.vBC,
pCOFINS: cofins.pCOFINS,
vCOFINS: cofins.vCOFINS
}
}
break;
}
return result;
}
private getImpostoPISST(PISST: PisST) {
let result;
if (!PISST) return ;
if ((PISST.vBC > 0) || (PISST.pPIS > 0) || (PISST.qBCProd > 0) || (PISST.vAliqProd > 0) || (PISST.vPIS > 0)) {
if ((PISST.vBC + PISST.pPIS > 0) && (PISST.qBCProd + PISST.vAliqProd > 0)) throw 'As TAG <vBC> e <pPIS> não podem ser informadas em conjunto com as TAG <qBCProd> e <vAliqProd>';
if (PISST.vBC + PISST.pPIS > 0) {
result = {
PISST: <schema.TNFeInfNFeDetImpostoPISST> {
vBC: PISST.vBC,
pPIS: PISST.pPIS,
vPIS: PISST.vPIS,
}
};
}
if (PISST.qBCProd + PISST.vAliqProd > 0) {
result = {
PISST: <schema.TNFeInfNFeDetImpostoPISST> {
qBCProd: PISST.qBCProd,
vAliqProd: PISST.vAliqProd,
vPIS: PISST.vPIS,
}
};
}
}
return result;
}
private getImpostoCOFINSST(COFINSST: CofinsST) {
let result;
if (!COFINSST) return;
if ((COFINSST.vBC > 0) && (COFINSST.pCOFINS > 0) && (COFINSST.qBCProd > 0) && (COFINSST.vAliqProd > 0) && (COFINSST.vCOFINS > 0)) {
if ((COFINSST.vBC + COFINSST.pCOFINS > 0) && (COFINSST.qBCProd + COFINSST.vAliqProd > 0)) throw 'As TAG <vBC> e <pCOFINS> não podem ser informadas em conjunto com as TAG <qBCProd> e <vAliqProd>';
if (COFINSST.vBC + COFINSST.pCOFINS > 0) {
result = {
COFINSST: <schema.TNFeInfNFeDetImpostoCOFINSST> {
vBC: COFINSST.vBC,
pCOFINS: COFINSST.pCOFINS,
vCOFINS: COFINSST.vCOFINS,
}
};
}
if (COFINSST.qBCProd + COFINSST.vAliqProd > 0) {
result = {
COFINSST: <schema.TNFeInfNFeDetImpostoCOFINSST> {
qBCProd: COFINSST.qBCProd,
vAliqProd: COFINSST.vAliqProd,
vCOFINS: COFINSST.vCOFINS,
}
};
}
}
return result;
}
private getImpostoDevolucao(devol: impostoDevol) {
return {
impostoDevol: <schema.TNFeInfNFeDetImpostoDevol> {
pDevol: devol.pDevol,
IPI: {
vIPIDevol: devol.vIPIDevol
}
}
}
}
private getIcmsUfDest(icmsUfDest: IcmsUfDest) {
if (!icmsUfDest) return;
if (icmsUfDest.pICMSInterPart <= 0) return;
return {
ICMSUFDest: <schema.TNFeInfNFeDetImpostoICMSUFDest> {
vBCUFDest: icmsUfDest.vBCUFDest,
vBCFCPUFDest: icmsUfDest.vBCFCPUFDest,
pFCPUFDest: icmsUfDest.pFCPUFDest,
pICMSUFDest: icmsUfDest.pICMSUFDest,
pICMSInter: icmsUfDest.pICMSInter,
pICMSInterPart: icmsUfDest.pICMSInterPart,
vFCPUFDest: icmsUfDest.vFCPUFDest,
vICMSUFDest: icmsUfDest.vICMSUFDest,
vICMSUFRemet: icmsUfDest.vICMSUFRemet,
}
}
}
private getTotal(total: Total) {
return <schema.TNFeInfNFeTotal>{
ICMSTot: total.icmsTot
}
}
private getIcmsTot(icmsTot: IcmsTot) {
return icmsTot;
}
private getTransp(transp: Transporte) {
return <schema.TNFeInfNFeTransp>{
modFrete: transp.modalidateFrete
/**
* transporta: TNFeInfNFeTranspTransporta;
retTransp: TNFeInfNFeTranspRetTransp;
//balsa
//reboque
//vagao
//veicTransp
items: object[];
itemsElementName: ItemsChoiceType5[];
vol: TNFeInfNFeTranspVol[];
*/
}
}
private getPag(pagamento: Pagamento) {
let pag = <schema.TNFeInfNFePag>{};
pag.detPag = this.getDetalhamentoPagamentos(pagamento.pagamentos);
pag.vTroco = pagamento.valorTroco;
return pag;
}
private getDetalhamentoPagamentos(pagamentos: DetalhePagamento[]){
let listPagamentos = [];
let detPag;
for (const pag of pagamentos) {
detPag = <schema.TNFeInfNFePagDetPag>{};
detPag.indPag = Utils.getEnumByValue(schema.TNFeInfNFePagDetPagIndPag, pag.indicadorFormaPagamento);
detPag.tPag = Utils.getEnumByValue(schema.TNFeInfNFePagDetPagTPag, pag.formaPagamento);
detPag.vPag = pag.valor;
if (pag.dadosCartao) {
detPag.card = this.getDetalhamentoCartao(pag.dadosCartao);
}
listPagamentos.push(detPag);
}
return listPagamentos;
}
private getDetalhamentoCartao(dadosCartao: DetalhePgtoCartao) {
return <schema.TNFeInfNFePagDetPagCard>{
tpIntegra: Utils.getEnumByValue(schema.TNFeInfNFePagDetPagCardTpIntegra, dadosCartao.tipoIntegracao),
CNPJ: dadosCartao.cnpj,
tBand: Utils.getEnumByValue(schema.TNFeInfNFePagDetPagCardTBand, dadosCartao.bandeira),
cAut: dadosCartao.codAutorizacao
}
}
private getInfoAdic(info: InfoAdicional) {
return <schema.TNFeInfNFeInfAdic>{
infCpl: info.infoComplementar,
infAdFisco: info.infoFisco
}
}
private getResponsavelTecnico(respTec: ResponsavelTecnico, chave: string) {
const result: any = {
CNPJ: respTec.cnpj,
xContato: respTec.contato,
email: respTec.email,
fone: respTec.fone,
}
if (respTec.CSRT != null && respTec.CSRT != "") {
result.idCSRT = respTec.idCSRT;
result.hashCSRT = this.gerarHashCSRT(chave, respTec.CSRT);
}
return result;
/*
return <schema.TInfRespTec> {
CNPJ: respTec.cnpj,
xContato: respTec.contato,
email: respTec.email,
fone: respTec.fone,
idCSRT: respTec.idCSRT,
hashCSRT: this.gerarHashCSRT(chave, respTec.CSRT)
}
*/
}
private gerarHashCSRT(chave: string, CSRT: string) {
return Buffer.from(sha1(CSRT+chave), 'hex').toString('base64');
}
} | the_stack |
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types";
/**
* <p>Specifies the EBS volume upgrade information. The broker identifier must be set to the keyword ALL. This means the changes apply to all the brokers in the cluster.</p>
*/
export interface BrokerEBSVolumeInfo {
/**
* <p>The ID of the broker to update.</p>
*/
KafkaBrokerNodeId: string | undefined;
/**
* <p>Size of the EBS volume to update.</p>
*/
VolumeSizeGB: number | undefined;
}
export namespace BrokerEBSVolumeInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: BrokerEBSVolumeInfo): any => ({
...obj,
});
}
export enum BrokerAZDistribution {
DEFAULT = "DEFAULT",
}
/**
* <p>Contains information about the EBS storage volumes attached to Kafka broker nodes.</p>
*/
export interface EBSStorageInfo {
/**
* <p>The size in GiB of the EBS volume for the data drive on each broker node.</p>
*/
VolumeSize?: number;
}
export namespace EBSStorageInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: EBSStorageInfo): any => ({
...obj,
});
}
/**
* <p>Contains information about storage volumes attached to MSK broker nodes.</p>
*/
export interface StorageInfo {
/**
* <p>EBS volume information.</p>
*/
EbsStorageInfo?: EBSStorageInfo;
}
export namespace StorageInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: StorageInfo): any => ({
...obj,
});
}
/**
* <p>Describes the setup to be used for Kafka broker nodes in the cluster.</p>
*/
export interface BrokerNodeGroupInfo {
/**
* <p>The distribution of broker nodes across Availability Zones. This is an optional parameter. If you don't specify it, Amazon MSK gives it the value DEFAULT. You can also explicitly set this parameter to the value DEFAULT. No other values are currently allowed.</p>
* <p>Amazon MSK distributes the broker nodes evenly across the Availability Zones that correspond to the subnets you provide when you create the cluster.</p>
*/
BrokerAZDistribution?: BrokerAZDistribution | string;
/**
* <p>The list of subnets to connect to in the client virtual private cloud (VPC). AWS creates elastic network interfaces inside these subnets. Client applications use elastic network interfaces to produce and consume data. Client subnets can't be in Availability Zone us-east-1e.</p>
*/
ClientSubnets: string[] | undefined;
/**
* <p>The type of Amazon EC2 instances to use for Kafka brokers. The following instance types are allowed: kafka.m5.large, kafka.m5.xlarge, kafka.m5.2xlarge,
* kafka.m5.4xlarge, kafka.m5.12xlarge, and kafka.m5.24xlarge.</p>
*/
InstanceType: string | undefined;
/**
* <p>The AWS security groups to associate with the elastic network interfaces in order to specify who can connect to and communicate with the Amazon MSK cluster. If you don't specify a security group, Amazon MSK uses the default security group associated with the VPC.</p>
*/
SecurityGroups?: string[];
/**
* <p>Contains information about storage volumes attached to MSK broker nodes.</p>
*/
StorageInfo?: StorageInfo;
}
export namespace BrokerNodeGroupInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: BrokerNodeGroupInfo): any => ({
...obj,
});
}
/**
* <p>Details for IAM access control.</p>
*/
export interface Iam {
/**
* <p>Indicates whether IAM access control is enabled.</p>
*/
Enabled?: boolean;
}
export namespace Iam {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Iam): any => ({
...obj,
});
}
/**
* <p>Details for SASL/SCRAM client authentication.</p>
*/
export interface Scram {
/**
* <p>SASL/SCRAM authentication is enabled or not.</p>
*/
Enabled?: boolean;
}
export namespace Scram {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Scram): any => ({
...obj,
});
}
/**
* <p>Details for client authentication using SASL.</p>
*/
export interface Sasl {
/**
* <p>Details for SASL/SCRAM client authentication.</p>
*/
Scram?: Scram;
/**
* <p>Indicates whether IAM access control is enabled.</p>
*/
Iam?: Iam;
}
export namespace Sasl {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Sasl): any => ({
...obj,
});
}
/**
* <p>Details for client authentication using TLS.</p>
*/
export interface Tls {
/**
* <p>List of ACM Certificate Authority ARNs.</p>
*/
CertificateAuthorityArnList?: string[];
/**
* <p>Specifies whether you want to enable or disable TLS authentication.</p>
*/
Enabled?: boolean;
}
export namespace Tls {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Tls): any => ({
...obj,
});
}
export interface Unauthenticated {
/**
* <p>Specifies whether you want to enable or disable unauthenticated traffic to your cluster.</p>
*/
Enabled?: boolean;
}
export namespace Unauthenticated {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Unauthenticated): any => ({
...obj,
});
}
/**
* <p>Includes all client authentication information.</p>
*/
export interface ClientAuthentication {
/**
* <p>Details for ClientAuthentication using SASL.</p>
*/
Sasl?: Sasl;
/**
* <p>Details for ClientAuthentication using TLS.</p>
*/
Tls?: Tls;
/**
* <p>Contains information about unauthenticated traffic to the cluster.</p>
*/
Unauthenticated?: Unauthenticated;
}
export namespace ClientAuthentication {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ClientAuthentication): any => ({
...obj,
});
}
/**
* <p>Information about the current software installed on the cluster.</p>
*/
export interface BrokerSoftwareInfo {
/**
* <p>The Amazon Resource Name (ARN) of the configuration used for the cluster. This field isn't visible in this preview release.</p>
*/
ConfigurationArn?: string;
/**
* <p>The revision of the configuration to use. This field isn't visible in this preview release.</p>
*/
ConfigurationRevision?: number;
/**
* <p>The version of Apache Kafka.</p>
*/
KafkaVersion?: string;
}
export namespace BrokerSoftwareInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: BrokerSoftwareInfo): any => ({
...obj,
});
}
/**
* <p>The data-volume encryption details.</p>
*/
export interface EncryptionAtRest {
/**
* <p>The ARN of the AWS KMS key for encrypting data at rest. If you don't specify a KMS key, MSK creates one for you and uses it.</p>
*/
DataVolumeKMSKeyId: string | undefined;
}
export namespace EncryptionAtRest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: EncryptionAtRest): any => ({
...obj,
});
}
export enum ClientBroker {
PLAINTEXT = "PLAINTEXT",
TLS = "TLS",
TLS_PLAINTEXT = "TLS_PLAINTEXT",
}
/**
* <p>The settings for encrypting data in transit.</p>
*/
export interface EncryptionInTransit {
/**
* <p>Indicates the encryption setting for data in transit between clients and brokers. The following are the possible values.</p>
* <p>
* TLS means that client-broker communication is enabled with TLS only.</p>
* <p>
* TLS_PLAINTEXT means that client-broker communication is enabled for both TLS-encrypted, as well as plaintext data.</p>
* <p>
* PLAINTEXT means that client-broker communication is enabled in plaintext only.</p>
* <p>The default value is TLS_PLAINTEXT.</p>
*/
ClientBroker?: ClientBroker | string;
/**
* <p>When set to true, it indicates that data communication among the broker nodes of the cluster is encrypted. When set to false, the communication happens in plaintext.</p>
* <p>The default value is true.</p>
*/
InCluster?: boolean;
}
export namespace EncryptionInTransit {
/**
* @internal
*/
export const filterSensitiveLog = (obj: EncryptionInTransit): any => ({
...obj,
});
}
/**
* <p>Includes encryption-related information, such as the AWS KMS key used for encrypting data at rest and whether you want MSK to encrypt your data in transit.</p>
*/
export interface EncryptionInfo {
/**
* <p>The data-volume encryption details.</p>
*/
EncryptionAtRest?: EncryptionAtRest;
/**
* <p>The details for encryption in transit.</p>
*/
EncryptionInTransit?: EncryptionInTransit;
}
export namespace EncryptionInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: EncryptionInfo): any => ({
...obj,
});
}
export enum EnhancedMonitoring {
DEFAULT = "DEFAULT",
PER_BROKER = "PER_BROKER",
PER_TOPIC_PER_BROKER = "PER_TOPIC_PER_BROKER",
PER_TOPIC_PER_PARTITION = "PER_TOPIC_PER_PARTITION",
}
export interface CloudWatchLogs {
Enabled: boolean | undefined;
LogGroup?: string;
}
export namespace CloudWatchLogs {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CloudWatchLogs): any => ({
...obj,
});
}
export interface Firehose {
DeliveryStream?: string;
Enabled: boolean | undefined;
}
export namespace Firehose {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Firehose): any => ({
...obj,
});
}
export interface S3 {
Bucket?: string;
Enabled: boolean | undefined;
Prefix?: string;
}
export namespace S3 {
/**
* @internal
*/
export const filterSensitiveLog = (obj: S3): any => ({
...obj,
});
}
export interface BrokerLogs {
CloudWatchLogs?: CloudWatchLogs;
Firehose?: Firehose;
S3?: S3;
}
export namespace BrokerLogs {
/**
* @internal
*/
export const filterSensitiveLog = (obj: BrokerLogs): any => ({
...obj,
});
}
export interface LoggingInfo {
BrokerLogs: BrokerLogs | undefined;
}
export namespace LoggingInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: LoggingInfo): any => ({
...obj,
});
}
/**
* <p>Indicates whether you want to enable or disable the JMX Exporter.</p>
*/
export interface JmxExporter {
/**
* <p>Indicates whether you want to enable or disable the JMX Exporter.</p>
*/
EnabledInBroker: boolean | undefined;
}
export namespace JmxExporter {
/**
* @internal
*/
export const filterSensitiveLog = (obj: JmxExporter): any => ({
...obj,
});
}
/**
* <p>Indicates whether you want to enable or disable the Node Exporter.</p>
*/
export interface NodeExporter {
/**
* <p>Indicates whether you want to enable or disable the Node Exporter.</p>
*/
EnabledInBroker: boolean | undefined;
}
export namespace NodeExporter {
/**
* @internal
*/
export const filterSensitiveLog = (obj: NodeExporter): any => ({
...obj,
});
}
/**
* <p>Prometheus settings.</p>
*/
export interface Prometheus {
/**
* <p>Indicates whether you want to enable or disable the JMX Exporter.</p>
*/
JmxExporter?: JmxExporter;
/**
* <p>Indicates whether you want to enable or disable the Node Exporter.</p>
*/
NodeExporter?: NodeExporter;
}
export namespace Prometheus {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Prometheus): any => ({
...obj,
});
}
/**
* <p>JMX and Node monitoring for the MSK cluster.</p>
*/
export interface OpenMonitoring {
/**
* <p>Prometheus settings.</p>
*/
Prometheus: Prometheus | undefined;
}
export namespace OpenMonitoring {
/**
* @internal
*/
export const filterSensitiveLog = (obj: OpenMonitoring): any => ({
...obj,
});
}
export enum ClusterState {
ACTIVE = "ACTIVE",
CREATING = "CREATING",
DELETING = "DELETING",
FAILED = "FAILED",
HEALING = "HEALING",
MAINTENANCE = "MAINTENANCE",
REBOOTING_BROKER = "REBOOTING_BROKER",
UPDATING = "UPDATING",
}
export interface StateInfo {
Code?: string;
Message?: string;
}
export namespace StateInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: StateInfo): any => ({
...obj,
});
}
/**
* <p>Returns information about a cluster.</p>
*/
export interface ClusterInfo {
/**
* <p>Arn of active cluster operation.</p>
*/
ActiveOperationArn?: string;
/**
* <p>Information about the broker nodes.</p>
*/
BrokerNodeGroupInfo?: BrokerNodeGroupInfo;
/**
* <p>Includes all client authentication information.</p>
*/
ClientAuthentication?: ClientAuthentication;
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>The name of the cluster.</p>
*/
ClusterName?: string;
/**
* <p>The time when the cluster was created.</p>
*/
CreationTime?: Date;
/**
* <p>Information about the version of software currently deployed on the Kafka brokers in the cluster.</p>
*/
CurrentBrokerSoftwareInfo?: BrokerSoftwareInfo;
/**
* <p>The current version of the MSK cluster.</p>
*/
CurrentVersion?: string;
/**
* <p>Includes all encryption-related information.</p>
*/
EncryptionInfo?: EncryptionInfo;
/**
* <p>Specifies which metrics are gathered for the MSK cluster. This property has the following possible values: DEFAULT, PER_BROKER, PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION. For a list of the metrics associated with each of these levels of monitoring, see <a href="https://docs.aws.amazon.com/msk/latest/developerguide/monitoring.html">Monitoring</a>.</p>
*/
EnhancedMonitoring?: EnhancedMonitoring | string;
/**
* <p>Settings for open monitoring using Prometheus.</p>
*/
OpenMonitoring?: OpenMonitoring;
LoggingInfo?: LoggingInfo;
/**
* <p>The number of broker nodes in the cluster.</p>
*/
NumberOfBrokerNodes?: number;
/**
* <p>The state of the cluster. The possible states are ACTIVE, CREATING, DELETING, FAILED, HEALING, MAINTENANCE, REBOOTING_BROKER, and UPDATING.</p>
*/
State?: ClusterState | string;
StateInfo?: StateInfo;
/**
* <p>Tags attached to the cluster.</p>
*/
Tags?: { [key: string]: string };
/**
* <p>The connection string to use to connect to the Apache ZooKeeper cluster.</p>
*/
ZookeeperConnectString?: string;
/**
* <p>The connection string to use to connect to zookeeper cluster on Tls port.</p>
*/
ZookeeperConnectStringTls?: string;
}
export namespace ClusterInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ClusterInfo): any => ({
...obj,
});
}
/**
* <p>Returns information about an error state of the cluster.</p>
*/
export interface ErrorInfo {
/**
* <p>A number describing the error programmatically.</p>
*/
ErrorCode?: string;
/**
* <p>An optional field to provide more details about the error.</p>
*/
ErrorString?: string;
}
export namespace ErrorInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ErrorInfo): any => ({
...obj,
});
}
/**
* <p>State information about the operation step.</p>
*/
export interface ClusterOperationStepInfo {
/**
* <p>The steps current status.</p>
*/
StepStatus?: string;
}
export namespace ClusterOperationStepInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ClusterOperationStepInfo): any => ({
...obj,
});
}
/**
* <p>Step taken during a cluster operation.</p>
*/
export interface ClusterOperationStep {
/**
* <p>Information about the step and its status.</p>
*/
StepInfo?: ClusterOperationStepInfo;
/**
* <p>The name of the step.</p>
*/
StepName?: string;
}
export namespace ClusterOperationStep {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ClusterOperationStep): any => ({
...obj,
});
}
/**
* <p>Specifies the configuration to use for the brokers.</p>
*/
export interface ConfigurationInfo {
/**
* <p>ARN of the configuration to use.</p>
*/
Arn: string | undefined;
/**
* <p>The revision of the configuration to use.</p>
*/
Revision: number | undefined;
}
export namespace ConfigurationInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ConfigurationInfo): any => ({
...obj,
});
}
/**
* <p>Information about cluster attributes that can be updated via update APIs.</p>
*/
export interface MutableClusterInfo {
/**
* <p>Specifies the size of the EBS volume and the ID of the associated broker.</p>
*/
BrokerEBSVolumeInfo?: BrokerEBSVolumeInfo[];
/**
* <p>Information about the changes in the configuration of the brokers.</p>
*/
ConfigurationInfo?: ConfigurationInfo;
/**
* <p>The number of broker nodes in the cluster.</p>
*/
NumberOfBrokerNodes?: number;
/**
* <p>Specifies which Apache Kafka metrics Amazon MSK gathers and sends to Amazon CloudWatch for this cluster.</p>
*/
EnhancedMonitoring?: EnhancedMonitoring | string;
/**
* <p>The settings for open monitoring.</p>
*/
OpenMonitoring?: OpenMonitoring;
/**
* <p>The Kafka version.</p>
*/
KafkaVersion?: string;
/**
* <p>You can configure your MSK cluster to send broker logs to different destination types. This is a container for the configuration details related to broker logs.</p>
*/
LoggingInfo?: LoggingInfo;
/**
* <p>Information about the Amazon MSK broker type.</p>
*/
InstanceType?: string;
/**
* <p>Includes all client authentication information.</p>
*/
ClientAuthentication?: ClientAuthentication;
/**
* <p>Includes all encryption-related information.</p>
*/
EncryptionInfo?: EncryptionInfo;
}
export namespace MutableClusterInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: MutableClusterInfo): any => ({
...obj,
});
}
/**
* <p>Returns information about a cluster operation.</p>
*/
export interface ClusterOperationInfo {
/**
* <p>The ID of the API request that triggered this operation.</p>
*/
ClientRequestId?: string;
/**
* <p>ARN of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>The time that the operation was created.</p>
*/
CreationTime?: Date;
/**
* <p>The time at which the operation finished.</p>
*/
EndTime?: Date;
/**
* <p>Describes the error if the operation fails.</p>
*/
ErrorInfo?: ErrorInfo;
/**
* <p>ARN of the cluster operation.</p>
*/
OperationArn?: string;
/**
* <p>State of the cluster operation.</p>
*/
OperationState?: string;
/**
* <p>Steps completed during the operation.</p>
*/
OperationSteps?: ClusterOperationStep[];
/**
* <p>Type of the cluster operation.</p>
*/
OperationType?: string;
/**
* <p>Information about cluster attributes before a cluster is updated.</p>
*/
SourceClusterInfo?: MutableClusterInfo;
/**
* <p>Information about cluster attributes after a cluster is updated.</p>
*/
TargetClusterInfo?: MutableClusterInfo;
}
export namespace ClusterOperationInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ClusterOperationInfo): any => ({
...obj,
});
}
/**
* <p>Contains source Kafka versions and compatible target Kafka versions.</p>
*/
export interface CompatibleKafkaVersion {
/**
* <p>A Kafka version.</p>
*/
SourceVersion?: string;
/**
* <p>A list of Kafka versions.</p>
*/
TargetVersions?: string[];
}
export namespace CompatibleKafkaVersion {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CompatibleKafkaVersion): any => ({
...obj,
});
}
/**
* <p>Describes a configuration revision.</p>
*/
export interface ConfigurationRevision {
/**
* <p>The time when the configuration revision was created.</p>
*/
CreationTime: Date | undefined;
/**
* <p>The description of the configuration revision.</p>
*/
Description?: string;
/**
* <p>The revision number.</p>
*/
Revision: number | undefined;
}
export namespace ConfigurationRevision {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ConfigurationRevision): any => ({
...obj,
});
}
export enum ConfigurationState {
ACTIVE = "ACTIVE",
DELETE_FAILED = "DELETE_FAILED",
DELETING = "DELETING",
}
/**
* <p>Represents an MSK Configuration.</p>
*/
export interface Configuration {
/**
* <p>The Amazon Resource Name (ARN) of the configuration.</p>
*/
Arn: string | undefined;
/**
* <p>The time when the configuration was created.</p>
*/
CreationTime: Date | undefined;
/**
* <p>The description of the configuration.</p>
*/
Description: string | undefined;
/**
* <p>An array of the versions of Apache Kafka with which you can use this MSK configuration. You can use this configuration for an MSK cluster only if the Apache Kafka version specified for the cluster appears in this array.</p>
*/
KafkaVersions: string[] | undefined;
/**
* <p>Latest revision of the configuration.</p>
*/
LatestRevision: ConfigurationRevision | undefined;
/**
* <p>The name of the configuration.</p>
*/
Name: string | undefined;
/**
* <p>The state of the configuration. The possible states are ACTIVE, DELETING, and DELETE_FAILED. </p>
*/
State: ConfigurationState | string | undefined;
}
export namespace Configuration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Configuration): any => ({
...obj,
});
}
export enum KafkaVersionStatus {
ACTIVE = "ACTIVE",
DEPRECATED = "DEPRECATED",
}
export interface KafkaVersion {
Version?: string;
Status?: KafkaVersionStatus | string;
}
export namespace KafkaVersion {
/**
* @internal
*/
export const filterSensitiveLog = (obj: KafkaVersion): any => ({
...obj,
});
}
/**
* <p>BrokerNodeInfo</p>
*/
export interface BrokerNodeInfo {
/**
* <p>The attached elastic network interface of the broker.</p>
*/
AttachedENIId?: string;
/**
* <p>The ID of the broker.</p>
*/
BrokerId?: number;
/**
* <p>The client subnet to which this broker node belongs.</p>
*/
ClientSubnet?: string;
/**
* <p>The virtual private cloud (VPC) of the client.</p>
*/
ClientVpcIpAddress?: string;
/**
* <p>Information about the version of software currently deployed on the Kafka brokers in the cluster.</p>
*/
CurrentBrokerSoftwareInfo?: BrokerSoftwareInfo;
/**
* <p>Endpoints for accessing the broker.</p>
*/
Endpoints?: string[];
}
export namespace BrokerNodeInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: BrokerNodeInfo): any => ({
...obj,
});
}
export enum NodeType {
BROKER = "BROKER",
}
/**
* <p>Zookeeper node information.</p>
*/
export interface ZookeeperNodeInfo {
/**
* <p>The attached elastic network interface of the broker.</p>
*/
AttachedENIId?: string;
/**
* <p>The virtual private cloud (VPC) IP address of the client.</p>
*/
ClientVpcIpAddress?: string;
/**
* <p>Endpoints for accessing the ZooKeeper.</p>
*/
Endpoints?: string[];
/**
* <p>The role-specific ID for Zookeeper.</p>
*/
ZookeeperId?: number;
/**
* <p>The version of Zookeeper.</p>
*/
ZookeeperVersion?: string;
}
export namespace ZookeeperNodeInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ZookeeperNodeInfo): any => ({
...obj,
});
}
/**
* <p>The node information object.</p>
*/
export interface NodeInfo {
/**
* <p>The start time.</p>
*/
AddedToClusterTime?: string;
/**
* <p>The broker node info.</p>
*/
BrokerNodeInfo?: BrokerNodeInfo;
/**
* <p>The instance type.</p>
*/
InstanceType?: string;
/**
* <p>The Amazon Resource Name (ARN) of the node.</p>
*/
NodeARN?: string;
/**
* <p>The node type.</p>
*/
NodeType?: NodeType | string;
/**
* <p>The ZookeeperNodeInfo.</p>
*/
ZookeeperNodeInfo?: ZookeeperNodeInfo;
}
export namespace NodeInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: NodeInfo): any => ({
...obj,
});
}
/**
* <p>Error info for scram secret associate/disassociate failure.</p>
*/
export interface UnprocessedScramSecret {
/**
* <p>Error code for associate/disassociate failure.</p>
*/
ErrorCode?: string;
/**
* <p>Error message for associate/disassociate failure.</p>
*/
ErrorMessage?: string;
/**
* <p>AWS Secrets Manager secret ARN.</p>
*/
SecretArn?: string;
}
export namespace UnprocessedScramSecret {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UnprocessedScramSecret): any => ({
...obj,
});
}
/**
* <p>Returns information about an error.</p>
*/
export interface BadRequestException extends __SmithyException, $MetadataBearer {
name: "BadRequestException";
$fault: "client";
/**
* <p>The parameter that caused the error.</p>
*/
InvalidParameter?: string;
/**
* <p>The description of the error.</p>
*/
Message?: string;
}
export namespace BadRequestException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: BadRequestException): any => ({
...obj,
});
}
/**
* <p>Associates sasl scram secrets to cluster.</p>
*/
export interface BatchAssociateScramSecretRequest {
/**
* <p>The Amazon Resource Name (ARN) of the cluster to be updated.</p>
*/
ClusterArn: string | undefined;
/**
* <p>List of AWS Secrets Manager secret ARNs.</p>
*/
SecretArnList: string[] | undefined;
}
export namespace BatchAssociateScramSecretRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: BatchAssociateScramSecretRequest): any => ({
...obj,
});
}
export interface BatchAssociateScramSecretResponse {
/**
* <p>The Amazon Resource Name (ARN) of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>List of errors when associating secrets to cluster.</p>
*/
UnprocessedScramSecrets?: UnprocessedScramSecret[];
}
export namespace BatchAssociateScramSecretResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: BatchAssociateScramSecretResponse): any => ({
...obj,
});
}
/**
* <p>Returns information about an error.</p>
*/
export interface ForbiddenException extends __SmithyException, $MetadataBearer {
name: "ForbiddenException";
$fault: "client";
/**
* <p>The parameter that caused the error.</p>
*/
InvalidParameter?: string;
/**
* <p>The description of the error.</p>
*/
Message?: string;
}
export namespace ForbiddenException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ForbiddenException): any => ({
...obj,
});
}
/**
* <p>Returns information about an error.</p>
*/
export interface InternalServerErrorException extends __SmithyException, $MetadataBearer {
name: "InternalServerErrorException";
$fault: "server";
/**
* <p>The parameter that caused the error.</p>
*/
InvalidParameter?: string;
/**
* <p>The description of the error.</p>
*/
Message?: string;
}
export namespace InternalServerErrorException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InternalServerErrorException): any => ({
...obj,
});
}
/**
* <p>Returns information about an error.</p>
*/
export interface NotFoundException extends __SmithyException, $MetadataBearer {
name: "NotFoundException";
$fault: "client";
/**
* <p>The parameter that caused the error.</p>
*/
InvalidParameter?: string;
/**
* <p>The description of the error.</p>
*/
Message?: string;
}
export namespace NotFoundException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: NotFoundException): any => ({
...obj,
});
}
/**
* <p>Returns information about an error.</p>
*/
export interface ServiceUnavailableException extends __SmithyException, $MetadataBearer {
name: "ServiceUnavailableException";
$fault: "server";
/**
* <p>The parameter that caused the error.</p>
*/
InvalidParameter?: string;
/**
* <p>The description of the error.</p>
*/
Message?: string;
}
export namespace ServiceUnavailableException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ServiceUnavailableException): any => ({
...obj,
});
}
/**
* <p>Returns information about an error.</p>
*/
export interface TooManyRequestsException extends __SmithyException, $MetadataBearer {
name: "TooManyRequestsException";
$fault: "client";
/**
* <p>The parameter that caused the error.</p>
*/
InvalidParameter?: string;
/**
* <p>The description of the error.</p>
*/
Message?: string;
}
export namespace TooManyRequestsException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TooManyRequestsException): any => ({
...obj,
});
}
/**
* <p>Returns information about an error.</p>
*/
export interface UnauthorizedException extends __SmithyException, $MetadataBearer {
name: "UnauthorizedException";
$fault: "client";
/**
* <p>The parameter that caused the error.</p>
*/
InvalidParameter?: string;
/**
* <p>The description of the error.</p>
*/
Message?: string;
}
export namespace UnauthorizedException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UnauthorizedException): any => ({
...obj,
});
}
/**
* <p>Disassociates sasl scram secrets to cluster.</p>
*/
export interface BatchDisassociateScramSecretRequest {
/**
* <p>The Amazon Resource Name (ARN) of the cluster to be updated.</p>
*/
ClusterArn: string | undefined;
/**
* <p>List of AWS Secrets Manager secret ARNs.</p>
*/
SecretArnList: string[] | undefined;
}
export namespace BatchDisassociateScramSecretRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: BatchDisassociateScramSecretRequest): any => ({
...obj,
});
}
export interface BatchDisassociateScramSecretResponse {
/**
* <p>The Amazon Resource Name (ARN) of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>List of errors when disassociating secrets to cluster.</p>
*/
UnprocessedScramSecrets?: UnprocessedScramSecret[];
}
export namespace BatchDisassociateScramSecretResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: BatchDisassociateScramSecretResponse): any => ({
...obj,
});
}
/**
* <p>Returns information about an error.</p>
*/
export interface ConflictException extends __SmithyException, $MetadataBearer {
name: "ConflictException";
$fault: "client";
/**
* <p>The parameter that caused the error.</p>
*/
InvalidParameter?: string;
/**
* <p>The description of the error.</p>
*/
Message?: string;
}
export namespace ConflictException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ConflictException): any => ({
...obj,
});
}
/**
* <p>Indicates whether you want to enable or disable the JMX Exporter.</p>
*/
export interface JmxExporterInfo {
/**
* <p>Indicates whether you want to enable or disable the JMX Exporter.</p>
*/
EnabledInBroker: boolean | undefined;
}
export namespace JmxExporterInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: JmxExporterInfo): any => ({
...obj,
});
}
/**
* <p>Indicates whether you want to enable or disable the Node Exporter.</p>
*/
export interface NodeExporterInfo {
/**
* <p>Indicates whether you want to enable or disable the Node Exporter.</p>
*/
EnabledInBroker: boolean | undefined;
}
export namespace NodeExporterInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: NodeExporterInfo): any => ({
...obj,
});
}
/**
* <p>Prometheus settings.</p>
*/
export interface PrometheusInfo {
/**
* <p>Indicates whether you want to enable or disable the JMX Exporter.</p>
*/
JmxExporter?: JmxExporterInfo;
/**
* <p>Indicates whether you want to enable or disable the Node Exporter.</p>
*/
NodeExporter?: NodeExporterInfo;
}
export namespace PrometheusInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: PrometheusInfo): any => ({
...obj,
});
}
/**
* <p>JMX and Node monitoring for the MSK cluster.</p>
*/
export interface OpenMonitoringInfo {
/**
* <p>Prometheus settings.</p>
*/
Prometheus: PrometheusInfo | undefined;
}
export namespace OpenMonitoringInfo {
/**
* @internal
*/
export const filterSensitiveLog = (obj: OpenMonitoringInfo): any => ({
...obj,
});
}
export interface CreateClusterRequest {
/**
* <p>Information about the broker nodes in the cluster.</p>
*/
BrokerNodeGroupInfo: BrokerNodeGroupInfo | undefined;
/**
* <p>Includes all client authentication related information.</p>
*/
ClientAuthentication?: ClientAuthentication;
/**
* <p>The name of the cluster.</p>
*/
ClusterName: string | undefined;
/**
* <p>Represents the configuration that you want MSK to use for the brokers in a cluster.</p>
*/
ConfigurationInfo?: ConfigurationInfo;
/**
* <p>Includes all encryption-related information.</p>
*/
EncryptionInfo?: EncryptionInfo;
/**
* <p>Specifies the level of monitoring for the MSK cluster. The possible values are DEFAULT, PER_BROKER, PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION.</p>
*/
EnhancedMonitoring?: EnhancedMonitoring | string;
/**
* <p>The settings for open monitoring.</p>
*/
OpenMonitoring?: OpenMonitoringInfo;
/**
* <p>The version of Apache Kafka.</p>
*/
KafkaVersion: string | undefined;
LoggingInfo?: LoggingInfo;
/**
* <p>The number of broker nodes in the cluster.</p>
*/
NumberOfBrokerNodes: number | undefined;
/**
* <p>Create tags when creating the cluster.</p>
*/
Tags?: { [key: string]: string };
}
export namespace CreateClusterRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateClusterRequest): any => ({
...obj,
});
}
export interface CreateClusterResponse {
/**
* <p>The Amazon Resource Name (ARN) of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>The name of the MSK cluster.</p>
*/
ClusterName?: string;
/**
* <p>The state of the cluster. The possible states are ACTIVE, CREATING, DELETING, FAILED, HEALING, MAINTENANCE, REBOOTING_BROKER, and UPDATING.</p>
*/
State?: ClusterState | string;
}
export namespace CreateClusterResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateClusterResponse): any => ({
...obj,
});
}
export interface CreateConfigurationRequest {
/**
* <p>The description of the configuration.</p>
*/
Description?: string;
/**
* <p>The versions of Apache Kafka with which you can use this MSK configuration.</p>
*/
KafkaVersions?: string[];
/**
* <p>The name of the configuration.</p>
*/
Name: string | undefined;
/**
* <p>Contents of the <filename>server.properties</filename> file. When using the API, you must ensure that the contents of the file are base64 encoded.
* When using the AWS Management Console, the SDK, or the AWS CLI, the contents of <filename>server.properties</filename> can be in plaintext.</p>
*/
ServerProperties: Uint8Array | undefined;
}
export namespace CreateConfigurationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateConfigurationRequest): any => ({
...obj,
});
}
export interface CreateConfigurationResponse {
/**
* <p>The Amazon Resource Name (ARN) of the configuration.</p>
*/
Arn?: string;
/**
* <p>The time when the configuration was created.</p>
*/
CreationTime?: Date;
/**
* <p>Latest revision of the configuration.</p>
*/
LatestRevision?: ConfigurationRevision;
/**
* <p>The name of the configuration.</p>
*/
Name?: string;
/**
* <p>The state of the configuration. The possible states are ACTIVE, DELETING, and DELETE_FAILED. </p>
*/
State?: ConfigurationState | string;
}
export namespace CreateConfigurationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateConfigurationResponse): any => ({
...obj,
});
}
export interface DeleteClusterRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the cluster.</p>
*/
ClusterArn: string | undefined;
/**
* <p>The current version of the MSK cluster.</p>
*/
CurrentVersion?: string;
}
export namespace DeleteClusterRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteClusterRequest): any => ({
...obj,
});
}
export interface DeleteClusterResponse {
/**
* <p>The Amazon Resource Name (ARN) of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>The state of the cluster. The possible states are ACTIVE, CREATING, DELETING, FAILED, HEALING, MAINTENANCE, REBOOTING_BROKER, and UPDATING.</p>
*/
State?: ClusterState | string;
}
export namespace DeleteClusterResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteClusterResponse): any => ({
...obj,
});
}
export interface DeleteConfigurationRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies an MSK configuration.</p>
*/
Arn: string | undefined;
}
export namespace DeleteConfigurationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteConfigurationRequest): any => ({
...obj,
});
}
export interface DeleteConfigurationResponse {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies an MSK configuration.</p>
*/
Arn?: string;
/**
* <p>The state of the configuration. The possible states are ACTIVE, DELETING, and DELETE_FAILED. </p>
*/
State?: ConfigurationState | string;
}
export namespace DeleteConfigurationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteConfigurationResponse): any => ({
...obj,
});
}
export interface DescribeClusterRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the cluster.</p>
*/
ClusterArn: string | undefined;
}
export namespace DescribeClusterRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeClusterRequest): any => ({
...obj,
});
}
export interface DescribeClusterResponse {
/**
* <p>The cluster information.</p>
*/
ClusterInfo?: ClusterInfo;
}
export namespace DescribeClusterResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeClusterResponse): any => ({
...obj,
});
}
export interface DescribeClusterOperationRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the MSK cluster operation.</p>
*/
ClusterOperationArn: string | undefined;
}
export namespace DescribeClusterOperationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeClusterOperationRequest): any => ({
...obj,
});
}
export interface DescribeClusterOperationResponse {
/**
* <p>Cluster operation information</p>
*/
ClusterOperationInfo?: ClusterOperationInfo;
}
export namespace DescribeClusterOperationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeClusterOperationResponse): any => ({
...obj,
});
}
export interface DescribeConfigurationRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies an MSK configuration and all of its revisions.</p>
*/
Arn: string | undefined;
}
export namespace DescribeConfigurationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeConfigurationRequest): any => ({
...obj,
});
}
export interface DescribeConfigurationResponse {
/**
* <p>The Amazon Resource Name (ARN) of the configuration.</p>
*/
Arn?: string;
/**
* <p>The time when the configuration was created.</p>
*/
CreationTime?: Date;
/**
* <p>The description of the configuration.</p>
*/
Description?: string;
/**
* <p>The versions of Apache Kafka with which you can use this MSK configuration.</p>
*/
KafkaVersions?: string[];
/**
* <p>Latest revision of the configuration.</p>
*/
LatestRevision?: ConfigurationRevision;
/**
* <p>The name of the configuration.</p>
*/
Name?: string;
/**
* <p>The state of the configuration. The possible states are ACTIVE, DELETING, and DELETE_FAILED. </p>
*/
State?: ConfigurationState | string;
}
export namespace DescribeConfigurationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeConfigurationResponse): any => ({
...obj,
});
}
export interface DescribeConfigurationRevisionRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies an MSK configuration and all of its revisions.</p>
*/
Arn: string | undefined;
/**
* <p>A string that uniquely identifies a revision of an MSK configuration.</p>
*/
Revision: number | undefined;
}
export namespace DescribeConfigurationRevisionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeConfigurationRevisionRequest): any => ({
...obj,
});
}
export interface DescribeConfigurationRevisionResponse {
/**
* <p>The Amazon Resource Name (ARN) of the configuration.</p>
*/
Arn?: string;
/**
* <p>The time when the configuration was created.</p>
*/
CreationTime?: Date;
/**
* <p>The description of the configuration.</p>
*/
Description?: string;
/**
* <p>The revision number.</p>
*/
Revision?: number;
/**
* <p>Contents of the <filename>server.properties</filename> file. When using the API, you must ensure that the contents of the file are base64 encoded.
* When using the AWS Management Console, the SDK, or the AWS CLI, the contents of <filename>server.properties</filename> can be in plaintext.</p>
*/
ServerProperties?: Uint8Array;
}
export namespace DescribeConfigurationRevisionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeConfigurationRevisionResponse): any => ({
...obj,
});
}
export interface GetBootstrapBrokersRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the cluster.</p>
*/
ClusterArn: string | undefined;
}
export namespace GetBootstrapBrokersRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetBootstrapBrokersRequest): any => ({
...obj,
});
}
export interface GetBootstrapBrokersResponse {
/**
* <p>A string containing one or more hostname:port pairs.</p>
*/
BootstrapBrokerString?: string;
/**
* <p>A string containing one or more DNS names (or IP) and TLS port pairs.</p>
*/
BootstrapBrokerStringTls?: string;
/**
* <p>A string containing one or more DNS names (or IP) and Sasl Scram port pairs.</p>
*/
BootstrapBrokerStringSaslScram?: string;
/**
* <p>A string that contains one or more DNS names (or IP addresses) and SASL IAM port pairs.</p>
*/
BootstrapBrokerStringSaslIam?: string;
}
export namespace GetBootstrapBrokersResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetBootstrapBrokersResponse): any => ({
...obj,
});
}
export interface GetCompatibleKafkaVersionsRequest {
/**
* <p>The Amazon Resource Name (ARN) of the cluster check.</p>
*/
ClusterArn?: string;
}
export namespace GetCompatibleKafkaVersionsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetCompatibleKafkaVersionsRequest): any => ({
...obj,
});
}
export interface GetCompatibleKafkaVersionsResponse {
/**
* <p>A list of CompatibleKafkaVersion objects.</p>
*/
CompatibleKafkaVersions?: CompatibleKafkaVersion[];
}
export namespace GetCompatibleKafkaVersionsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetCompatibleKafkaVersionsResponse): any => ({
...obj,
});
}
export interface ListClusterOperationsRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the cluster.</p>
*/
ClusterArn: string | undefined;
/**
* <p>The maximum number of results to return in the response. If there are more results, the response includes a NextToken parameter.</p>
*/
MaxResults?: number;
/**
* <p>The paginated results marker. When the result of the operation is truncated, the call returns NextToken in the response.
* To get the next batch, provide this token in your next request.</p>
*/
NextToken?: string;
}
export namespace ListClusterOperationsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListClusterOperationsRequest): any => ({
...obj,
});
}
export interface ListClusterOperationsResponse {
/**
* <p>An array of cluster operation information objects.</p>
*/
ClusterOperationInfoList?: ClusterOperationInfo[];
/**
* <p>If the response of ListClusterOperations is truncated, it returns a NextToken in the response. This Nexttoken should be sent in the subsequent request to ListClusterOperations.</p>
*/
NextToken?: string;
}
export namespace ListClusterOperationsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListClusterOperationsResponse): any => ({
...obj,
});
}
export interface ListClustersRequest {
/**
* <p>Specify a prefix of the name of the clusters that you want to list. The service lists all the clusters whose names start with this prefix.</p>
*/
ClusterNameFilter?: string;
/**
* <p>The maximum number of results to return in the response. If there are more results, the response includes a NextToken parameter.</p>
*/
MaxResults?: number;
/**
* <p>The paginated results marker. When the result of the operation is truncated, the call returns NextToken in the response.
* To get the next batch, provide this token in your next request.</p>
*/
NextToken?: string;
}
export namespace ListClustersRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListClustersRequest): any => ({
...obj,
});
}
export interface ListClustersResponse {
/**
* <p>Information on each of the MSK clusters in the response.</p>
*/
ClusterInfoList?: ClusterInfo[];
/**
* <p>The paginated results marker. When the result of a ListClusters operation is truncated, the call returns NextToken in the response.
* To get another batch of clusters, provide this token in your next request.</p>
*/
NextToken?: string;
}
export namespace ListClustersResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListClustersResponse): any => ({
...obj,
});
}
export interface ListConfigurationRevisionsRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies an MSK configuration and all of its revisions.</p>
*/
Arn: string | undefined;
/**
* <p>The maximum number of results to return in the response. If there are more results, the response includes a NextToken parameter.</p>
*/
MaxResults?: number;
/**
* <p>The paginated results marker. When the result of the operation is truncated, the call returns NextToken in the response.
* To get the next batch, provide this token in your next request.</p>
*/
NextToken?: string;
}
export namespace ListConfigurationRevisionsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListConfigurationRevisionsRequest): any => ({
...obj,
});
}
export interface ListConfigurationRevisionsResponse {
/**
* <p>Paginated results marker.</p>
*/
NextToken?: string;
/**
* <p>List of ConfigurationRevision objects.</p>
*/
Revisions?: ConfigurationRevision[];
}
export namespace ListConfigurationRevisionsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListConfigurationRevisionsResponse): any => ({
...obj,
});
}
export interface ListConfigurationsRequest {
/**
* <p>The maximum number of results to return in the response. If there are more results, the response includes a NextToken parameter.</p>
*/
MaxResults?: number;
/**
* <p>The paginated results marker. When the result of the operation is truncated, the call returns NextToken in the response.
* To get the next batch, provide this token in your next request.</p>
*/
NextToken?: string;
}
export namespace ListConfigurationsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListConfigurationsRequest): any => ({
...obj,
});
}
export interface ListConfigurationsResponse {
/**
* <p>An array of MSK configurations.</p>
*/
Configurations?: Configuration[];
/**
* <p>The paginated results marker. When the result of a ListConfigurations operation is truncated, the call returns NextToken in the response.
* To get another batch of configurations, provide this token in your next request.</p>
*/
NextToken?: string;
}
export namespace ListConfigurationsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListConfigurationsResponse): any => ({
...obj,
});
}
export interface ListKafkaVersionsRequest {
/**
* <p>The maximum number of results to return in the response. If there are more results, the response includes a NextToken parameter.</p>
*/
MaxResults?: number;
/**
* <p>The paginated results marker. When the result of the operation is truncated, the call returns NextToken in the response. To get the next batch, provide this token in your next request.</p>
*/
NextToken?: string;
}
export namespace ListKafkaVersionsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListKafkaVersionsRequest): any => ({
...obj,
});
}
export interface ListKafkaVersionsResponse {
KafkaVersions?: KafkaVersion[];
NextToken?: string;
}
export namespace ListKafkaVersionsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListKafkaVersionsResponse): any => ({
...obj,
});
}
export interface ListNodesRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the cluster.</p>
*/
ClusterArn: string | undefined;
/**
* <p>The maximum number of results to return in the response. If there are more results, the response includes a NextToken parameter.</p>
*/
MaxResults?: number;
/**
* <p>The paginated results marker. When the result of the operation is truncated, the call returns NextToken in the response.
* To get the next batch, provide this token in your next request.</p>
*/
NextToken?: string;
}
export namespace ListNodesRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListNodesRequest): any => ({
...obj,
});
}
export interface ListNodesResponse {
/**
* <p>The paginated results marker. When the result of a ListNodes operation is truncated, the call returns NextToken in the response.
* To get another batch of nodes, provide this token in your next request.</p>
*/
NextToken?: string;
/**
* <p>List containing a NodeInfo object.</p>
*/
NodeInfoList?: NodeInfo[];
}
export namespace ListNodesResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListNodesResponse): any => ({
...obj,
});
}
export interface ListScramSecretsRequest {
/**
* <p>The arn of the cluster.</p>
*/
ClusterArn: string | undefined;
/**
* <p>The maxResults of the query.</p>
*/
MaxResults?: number;
/**
* <p>The nextToken of the query.</p>
*/
NextToken?: string;
}
export namespace ListScramSecretsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListScramSecretsRequest): any => ({
...obj,
});
}
export interface ListScramSecretsResponse {
/**
* <p>Paginated results marker.</p>
*/
NextToken?: string;
/**
* <p>The list of scram secrets associated with the cluster.</p>
*/
SecretArnList?: string[];
}
export namespace ListScramSecretsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListScramSecretsResponse): any => ({
...obj,
});
}
export interface ListTagsForResourceRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the resource that's associated with the tags.</p>
*/
ResourceArn: string | undefined;
}
export namespace ListTagsForResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({
...obj,
});
}
export interface ListTagsForResourceResponse {
/**
* <p>The key-value pair for the resource tag.</p>
*/
Tags?: { [key: string]: string };
}
export namespace ListTagsForResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTagsForResourceResponse): any => ({
...obj,
});
}
/**
* Reboots a node.
*/
export interface RebootBrokerRequest {
/**
* <p>The list of broker IDs to be rebooted. The reboot-broker operation supports rebooting one broker at a time.</p>
*/
BrokerIds: string[] | undefined;
/**
* <p>The Amazon Resource Name (ARN) of the cluster to be updated.</p>
*/
ClusterArn: string | undefined;
}
export namespace RebootBrokerRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: RebootBrokerRequest): any => ({
...obj,
});
}
export interface RebootBrokerResponse {
/**
* <p>The Amazon Resource Name (ARN) of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>The Amazon Resource Name (ARN) of the cluster operation.</p>
*/
ClusterOperationArn?: string;
}
export namespace RebootBrokerResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: RebootBrokerResponse): any => ({
...obj,
});
}
export interface TagResourceRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the resource that's associated with the tags.</p>
*/
ResourceArn: string | undefined;
/**
* <p>The key-value pair for the resource tag.</p>
*/
Tags: { [key: string]: string } | undefined;
}
export namespace TagResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TagResourceRequest): any => ({
...obj,
});
}
export interface UntagResourceRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the resource that's associated with the tags.</p>
*/
ResourceArn: string | undefined;
/**
* <p>Tag keys must be unique for a given cluster. In addition, the following restrictions apply:</p>
* <ul>
* <li>
* <p>Each tag key must be unique. If you add a tag with a key that's already in
* use, your new tag overwrites the existing key-value pair. </p>
* </li>
* <li>
* <p>You can't start a tag key with aws: because this prefix is reserved for use
* by AWS. AWS creates tags that begin with this prefix on your behalf, but
* you can't edit or delete them.</p>
* </li>
* <li>
* <p>Tag keys must be between 1 and 128 Unicode characters in length.</p>
* </li>
* <li>
* <p>Tag keys must consist of the following characters: Unicode letters, digits,
* white space, and the following special characters: _ . / = + -
* @.</p>
* </li>
* </ul>
*/
TagKeys: string[] | undefined;
}
export namespace UntagResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({
...obj,
});
}
export interface UpdateBrokerCountRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the cluster.</p>
*/
ClusterArn: string | undefined;
/**
* <p>The version of cluster to update from. A successful operation will then generate a new version.</p>
*/
CurrentVersion: string | undefined;
/**
* <p>The number of broker nodes that you want the cluster to have after this operation completes successfully.</p>
*/
TargetNumberOfBrokerNodes: number | undefined;
}
export namespace UpdateBrokerCountRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateBrokerCountRequest): any => ({
...obj,
});
}
export interface UpdateBrokerCountResponse {
/**
* <p>The Amazon Resource Name (ARN) of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>The Amazon Resource Name (ARN) of the cluster operation.</p>
*/
ClusterOperationArn?: string;
}
export namespace UpdateBrokerCountResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateBrokerCountResponse): any => ({
...obj,
});
}
export interface UpdateBrokerStorageRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the cluster.</p>
*/
ClusterArn: string | undefined;
/**
* <p>The version of cluster to update from. A successful operation will then generate a new version.</p>
*/
CurrentVersion: string | undefined;
/**
* <p>Describes the target volume size and the ID of the broker to apply the update to.</p>
*/
TargetBrokerEBSVolumeInfo: BrokerEBSVolumeInfo[] | undefined;
}
export namespace UpdateBrokerStorageRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateBrokerStorageRequest): any => ({
...obj,
});
}
export interface UpdateBrokerStorageResponse {
/**
* <p>The Amazon Resource Name (ARN) of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>The Amazon Resource Name (ARN) of the cluster operation.</p>
*/
ClusterOperationArn?: string;
}
export namespace UpdateBrokerStorageResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateBrokerStorageResponse): any => ({
...obj,
});
}
export interface UpdateBrokerTypeRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the cluster.</p>
*/
ClusterArn: string | undefined;
/**
* <p>The cluster version that you want to change. After this operation completes successfully, the cluster will have a new version.</p>
*/
CurrentVersion: string | undefined;
/**
* <p>The Amazon MSK broker type that you want all of the brokers in this cluster to be.</p>
*/
TargetInstanceType: string | undefined;
}
export namespace UpdateBrokerTypeRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateBrokerTypeRequest): any => ({
...obj,
});
}
export interface UpdateBrokerTypeResponse {
/**
* <p>The Amazon Resource Name (ARN) of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>The Amazon Resource Name (ARN) of the cluster operation.</p>
*/
ClusterOperationArn?: string;
}
export namespace UpdateBrokerTypeResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateBrokerTypeResponse): any => ({
...obj,
});
}
export interface UpdateClusterConfigurationRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the cluster.</p>
*/
ClusterArn: string | undefined;
/**
* <p>Represents the configuration that you want MSK to use for the brokers in a cluster.</p>
*/
ConfigurationInfo: ConfigurationInfo | undefined;
/**
* <p>The version of the cluster that needs to be updated.</p>
*/
CurrentVersion: string | undefined;
}
export namespace UpdateClusterConfigurationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateClusterConfigurationRequest): any => ({
...obj,
});
}
export interface UpdateClusterConfigurationResponse {
/**
* <p>The Amazon Resource Name (ARN) of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>The Amazon Resource Name (ARN) of the cluster operation.</p>
*/
ClusterOperationArn?: string;
}
export namespace UpdateClusterConfigurationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateClusterConfigurationResponse): any => ({
...obj,
});
}
export interface UpdateClusterKafkaVersionRequest {
/**
* <p>The Amazon Resource Name (ARN) of the cluster to be updated.</p>
*/
ClusterArn: string | undefined;
/**
* <p>The custom configuration that should be applied on the new version of cluster.</p>
*/
ConfigurationInfo?: ConfigurationInfo;
/**
* <p>Current cluster version.</p>
*/
CurrentVersion: string | undefined;
/**
* <p>Target Kafka version.</p>
*/
TargetKafkaVersion: string | undefined;
}
export namespace UpdateClusterKafkaVersionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateClusterKafkaVersionRequest): any => ({
...obj,
});
}
export interface UpdateClusterKafkaVersionResponse {
/**
* <p>The Amazon Resource Name (ARN) of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>The Amazon Resource Name (ARN) of the cluster operation.</p>
*/
ClusterOperationArn?: string;
}
export namespace UpdateClusterKafkaVersionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateClusterKafkaVersionResponse): any => ({
...obj,
});
}
export interface UpdateConfigurationRequest {
/**
* <p>The Amazon Resource Name (ARN) of the configuration.</p>
*/
Arn: string | undefined;
/**
* <p>The description of the configuration revision.</p>
*/
Description?: string;
/**
* <p>Contents of the <filename>server.properties</filename> file. When using the API, you must ensure that the contents of the file are base64 encoded.
* When using the AWS Management Console, the SDK, or the AWS CLI, the contents of <filename>server.properties</filename> can be in plaintext.</p>
*/
ServerProperties: Uint8Array | undefined;
}
export namespace UpdateConfigurationRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateConfigurationRequest): any => ({
...obj,
});
}
export interface UpdateConfigurationResponse {
/**
* <p>The Amazon Resource Name (ARN) of the configuration.</p>
*/
Arn?: string;
/**
* <p>Latest revision of the configuration.</p>
*/
LatestRevision?: ConfigurationRevision;
}
export namespace UpdateConfigurationResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateConfigurationResponse): any => ({
...obj,
});
}
/**
* Request body for UpdateMonitoring.
*/
export interface UpdateMonitoringRequest {
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the cluster.</p>
*/
ClusterArn: string | undefined;
/**
* <p>The version of the MSK cluster to update. Cluster versions aren't simple numbers. You can describe an MSK cluster to find its version. When this update operation is successful, it generates a new cluster version.</p>
*/
CurrentVersion: string | undefined;
/**
* <p>Specifies which Apache Kafka metrics Amazon MSK gathers and sends to Amazon CloudWatch for this cluster.</p>
*/
EnhancedMonitoring?: EnhancedMonitoring | string;
/**
* <p>The settings for open monitoring.</p>
*/
OpenMonitoring?: OpenMonitoringInfo;
LoggingInfo?: LoggingInfo;
}
export namespace UpdateMonitoringRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateMonitoringRequest): any => ({
...obj,
});
}
export interface UpdateMonitoringResponse {
/**
* <p>The Amazon Resource Name (ARN) of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>The Amazon Resource Name (ARN) of the cluster operation.</p>
*/
ClusterOperationArn?: string;
}
export namespace UpdateMonitoringResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateMonitoringResponse): any => ({
...obj,
});
}
export interface UpdateSecurityRequest {
/**
* <p>Includes all client authentication related information.</p>
*/
ClientAuthentication?: ClientAuthentication;
/**
* <p>The Amazon Resource Name (ARN) that uniquely identifies the cluster.</p>
*/
ClusterArn: string | undefined;
/**
* <p>The version of the MSK cluster to update. Cluster versions aren't simple numbers. You can describe an MSK cluster to find its version. When this update operation is successful, it generates a new cluster version.</p>
*/
CurrentVersion: string | undefined;
/**
* <p>Includes all encryption-related information.</p>
*/
EncryptionInfo?: EncryptionInfo;
}
export namespace UpdateSecurityRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateSecurityRequest): any => ({
...obj,
});
}
export interface UpdateSecurityResponse {
/**
* <p>The Amazon Resource Name (ARN) of the cluster.</p>
*/
ClusterArn?: string;
/**
* <p>The Amazon Resource Name (ARN) of the cluster operation.</p>
*/
ClusterOperationArn?: string;
}
export namespace UpdateSecurityResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateSecurityResponse): any => ({
...obj,
});
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { FailoverGroups } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { SqlManagementClient } from "../sqlManagementClient";
import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro";
import { LroImpl } from "../lroImpl";
import {
FailoverGroup,
FailoverGroupsListByServerNextOptionalParams,
FailoverGroupsListByServerOptionalParams,
FailoverGroupsGetOptionalParams,
FailoverGroupsGetResponse,
FailoverGroupsCreateOrUpdateOptionalParams,
FailoverGroupsCreateOrUpdateResponse,
FailoverGroupsDeleteOptionalParams,
FailoverGroupUpdate,
FailoverGroupsUpdateOptionalParams,
FailoverGroupsUpdateResponse,
FailoverGroupsListByServerResponse,
FailoverGroupsFailoverOptionalParams,
FailoverGroupsFailoverResponse,
FailoverGroupsForceFailoverAllowDataLossOptionalParams,
FailoverGroupsForceFailoverAllowDataLossResponse,
FailoverGroupsListByServerNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing FailoverGroups operations. */
export class FailoverGroupsImpl implements FailoverGroups {
private readonly client: SqlManagementClient;
/**
* Initialize a new instance of the class FailoverGroups class.
* @param client Reference to the service client
*/
constructor(client: SqlManagementClient) {
this.client = client;
}
/**
* Lists the failover groups in a server.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param options The options parameters.
*/
public listByServer(
resourceGroupName: string,
serverName: string,
options?: FailoverGroupsListByServerOptionalParams
): PagedAsyncIterableIterator<FailoverGroup> {
const iter = this.listByServerPagingAll(
resourceGroupName,
serverName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByServerPagingPage(
resourceGroupName,
serverName,
options
);
}
};
}
private async *listByServerPagingPage(
resourceGroupName: string,
serverName: string,
options?: FailoverGroupsListByServerOptionalParams
): AsyncIterableIterator<FailoverGroup[]> {
let result = await this._listByServer(
resourceGroupName,
serverName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByServerNext(
resourceGroupName,
serverName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByServerPagingAll(
resourceGroupName: string,
serverName: string,
options?: FailoverGroupsListByServerOptionalParams
): AsyncIterableIterator<FailoverGroup> {
for await (const page of this.listByServerPagingPage(
resourceGroupName,
serverName,
options
)) {
yield* page;
}
}
/**
* Gets a failover group.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param failoverGroupName The name of the failover group.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
serverName: string,
failoverGroupName: string,
options?: FailoverGroupsGetOptionalParams
): Promise<FailoverGroupsGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serverName, failoverGroupName, options },
getOperationSpec
);
}
/**
* Creates or updates a failover group.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param failoverGroupName The name of the failover group.
* @param parameters The failover group parameters.
* @param options The options parameters.
*/
async beginCreateOrUpdate(
resourceGroupName: string,
serverName: string,
failoverGroupName: string,
parameters: FailoverGroup,
options?: FailoverGroupsCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<FailoverGroupsCreateOrUpdateResponse>,
FailoverGroupsCreateOrUpdateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<FailoverGroupsCreateOrUpdateResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, serverName, failoverGroupName, parameters, options },
createOrUpdateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Creates or updates a failover group.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param failoverGroupName The name of the failover group.
* @param parameters The failover group parameters.
* @param options The options parameters.
*/
async beginCreateOrUpdateAndWait(
resourceGroupName: string,
serverName: string,
failoverGroupName: string,
parameters: FailoverGroup,
options?: FailoverGroupsCreateOrUpdateOptionalParams
): Promise<FailoverGroupsCreateOrUpdateResponse> {
const poller = await this.beginCreateOrUpdate(
resourceGroupName,
serverName,
failoverGroupName,
parameters,
options
);
return poller.pollUntilDone();
}
/**
* Deletes a failover group.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param failoverGroupName The name of the failover group.
* @param options The options parameters.
*/
async beginDelete(
resourceGroupName: string,
serverName: string,
failoverGroupName: string,
options?: FailoverGroupsDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, serverName, failoverGroupName, options },
deleteOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Deletes a failover group.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param failoverGroupName The name of the failover group.
* @param options The options parameters.
*/
async beginDeleteAndWait(
resourceGroupName: string,
serverName: string,
failoverGroupName: string,
options?: FailoverGroupsDeleteOptionalParams
): Promise<void> {
const poller = await this.beginDelete(
resourceGroupName,
serverName,
failoverGroupName,
options
);
return poller.pollUntilDone();
}
/**
* Updates a failover group.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param failoverGroupName The name of the failover group.
* @param parameters The failover group parameters.
* @param options The options parameters.
*/
async beginUpdate(
resourceGroupName: string,
serverName: string,
failoverGroupName: string,
parameters: FailoverGroupUpdate,
options?: FailoverGroupsUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<FailoverGroupsUpdateResponse>,
FailoverGroupsUpdateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<FailoverGroupsUpdateResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, serverName, failoverGroupName, parameters, options },
updateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Updates a failover group.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param failoverGroupName The name of the failover group.
* @param parameters The failover group parameters.
* @param options The options parameters.
*/
async beginUpdateAndWait(
resourceGroupName: string,
serverName: string,
failoverGroupName: string,
parameters: FailoverGroupUpdate,
options?: FailoverGroupsUpdateOptionalParams
): Promise<FailoverGroupsUpdateResponse> {
const poller = await this.beginUpdate(
resourceGroupName,
serverName,
failoverGroupName,
parameters,
options
);
return poller.pollUntilDone();
}
/**
* Lists the failover groups in a server.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param options The options parameters.
*/
private _listByServer(
resourceGroupName: string,
serverName: string,
options?: FailoverGroupsListByServerOptionalParams
): Promise<FailoverGroupsListByServerResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serverName, options },
listByServerOperationSpec
);
}
/**
* Fails over from the current primary server to this server.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param failoverGroupName The name of the failover group.
* @param options The options parameters.
*/
async beginFailover(
resourceGroupName: string,
serverName: string,
failoverGroupName: string,
options?: FailoverGroupsFailoverOptionalParams
): Promise<
PollerLike<
PollOperationState<FailoverGroupsFailoverResponse>,
FailoverGroupsFailoverResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<FailoverGroupsFailoverResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, serverName, failoverGroupName, options },
failoverOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Fails over from the current primary server to this server.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param failoverGroupName The name of the failover group.
* @param options The options parameters.
*/
async beginFailoverAndWait(
resourceGroupName: string,
serverName: string,
failoverGroupName: string,
options?: FailoverGroupsFailoverOptionalParams
): Promise<FailoverGroupsFailoverResponse> {
const poller = await this.beginFailover(
resourceGroupName,
serverName,
failoverGroupName,
options
);
return poller.pollUntilDone();
}
/**
* Fails over from the current primary server to this server. This operation might result in data loss.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param failoverGroupName The name of the failover group.
* @param options The options parameters.
*/
async beginForceFailoverAllowDataLoss(
resourceGroupName: string,
serverName: string,
failoverGroupName: string,
options?: FailoverGroupsForceFailoverAllowDataLossOptionalParams
): Promise<
PollerLike<
PollOperationState<FailoverGroupsForceFailoverAllowDataLossResponse>,
FailoverGroupsForceFailoverAllowDataLossResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<FailoverGroupsForceFailoverAllowDataLossResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, serverName, failoverGroupName, options },
forceFailoverAllowDataLossOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Fails over from the current primary server to this server. This operation might result in data loss.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param failoverGroupName The name of the failover group.
* @param options The options parameters.
*/
async beginForceFailoverAllowDataLossAndWait(
resourceGroupName: string,
serverName: string,
failoverGroupName: string,
options?: FailoverGroupsForceFailoverAllowDataLossOptionalParams
): Promise<FailoverGroupsForceFailoverAllowDataLossResponse> {
const poller = await this.beginForceFailoverAllowDataLoss(
resourceGroupName,
serverName,
failoverGroupName,
options
);
return poller.pollUntilDone();
}
/**
* ListByServerNext
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server containing the failover group.
* @param nextLink The nextLink from the previous successful call to the ListByServer method.
* @param options The options parameters.
*/
private _listByServerNext(
resourceGroupName: string,
serverName: string,
nextLink: string,
options?: FailoverGroupsListByServerNextOptionalParams
): Promise<FailoverGroupsListByServerNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serverName, nextLink, options },
listByServerNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/failoverGroups/{failoverGroupName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FailoverGroup
},
default: {}
},
queryParameters: [Parameters.apiVersion3],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.failoverGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/failoverGroups/{failoverGroupName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.FailoverGroup
},
201: {
bodyMapper: Mappers.FailoverGroup
},
202: {
bodyMapper: Mappers.FailoverGroup
},
204: {
bodyMapper: Mappers.FailoverGroup
},
default: {}
},
requestBody: Parameters.parameters19,
queryParameters: [Parameters.apiVersion3],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.failoverGroupName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/failoverGroups/{failoverGroupName}",
httpMethod: "DELETE",
responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: {} },
queryParameters: [Parameters.apiVersion3],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.failoverGroupName
],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/failoverGroups/{failoverGroupName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.FailoverGroup
},
201: {
bodyMapper: Mappers.FailoverGroup
},
202: {
bodyMapper: Mappers.FailoverGroup
},
204: {
bodyMapper: Mappers.FailoverGroup
},
default: {}
},
requestBody: Parameters.parameters20,
queryParameters: [Parameters.apiVersion3],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.failoverGroupName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listByServerOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/failoverGroups",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FailoverGroupListResult
},
default: {}
},
queryParameters: [Parameters.apiVersion3],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName
],
headerParameters: [Parameters.accept],
serializer
};
const failoverOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/failoverGroups/{failoverGroupName}/failover",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.FailoverGroup
},
201: {
bodyMapper: Mappers.FailoverGroup
},
202: {
bodyMapper: Mappers.FailoverGroup
},
204: {
bodyMapper: Mappers.FailoverGroup
},
default: {}
},
queryParameters: [Parameters.apiVersion3],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.failoverGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const forceFailoverAllowDataLossOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/failoverGroups/{failoverGroupName}/forceFailoverAllowDataLoss",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.FailoverGroup
},
201: {
bodyMapper: Mappers.FailoverGroup
},
202: {
bodyMapper: Mappers.FailoverGroup
},
204: {
bodyMapper: Mappers.FailoverGroup
},
default: {}
},
queryParameters: [Parameters.apiVersion3],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.failoverGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const listByServerNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FailoverGroupListResult
},
default: {}
},
queryParameters: [Parameters.apiVersion3],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
var path = require('path')
import * as tl from 'azure-pipelines-task-lib/task';
import * as engine from 'artifact-engine/Engine';
import * as providers from 'artifact-engine/Providers';
import * as httpc from 'typed-rest-client/HttpClient';
var packagejson = require('./package.json');
tl.setResourcePath(path.join(__dirname, 'task.json'));
var taskJson = require('./task.json');
const area: string = 'DownloadGitHubRelease';
const userAgent: string = 'download-github-release-task-' + packagejson.version;
const defaultRetryLimit: number = 4;
interface Release {
Id: number;
Name: string;
}
function getDefaultProps() {
var hostType = (tl.getVariable('SYSTEM.HOSTTYPE') || "").toLowerCase();
return {
hostType: hostType,
definitionName: '[NonEmail:' + (hostType === 'release' ? tl.getVariable('RELEASE.DEFINITIONNAME') : tl.getVariable('BUILD.DEFINITIONNAME')) + ']',
processId: hostType === 'release' ? tl.getVariable('RELEASE.RELEASEID') : tl.getVariable('BUILD.BUILDID'),
processUrl: hostType === 'release' ? tl.getVariable('RELEASE.RELEASEWEBURL') : (tl.getVariable('SYSTEM.TEAMFOUNDATIONSERVERURI') + tl.getVariable('SYSTEM.TEAMPROJECT') + '/_build?buildId=' + tl.getVariable('BUILD.BUILDID')),
taskDisplayName: tl.getVariable('TASK.DISPLAYNAME'),
jobid: tl.getVariable('SYSTEM.JOBID'),
agentVersion: tl.getVariable('AGENT.VERSION'),
agentOS: tl.getVariable('AGENT.OS'),
agentName: tl.getVariable('AGENT.NAME'),
version: taskJson.version
};
}
function publishTelemetry(feature, properties: any): void {
try {
var splitVersion = (process.env.AGENT_VERSION || '').split('.');
var major = parseInt(splitVersion[0] || '0');
var minor = parseInt(splitVersion[1] || '0');
let telemetry = '';
if (major > 2 || (major == 2 && minor >= 120)) {
telemetry = `##vso[telemetry.publish area=${area};feature=${feature}]${JSON.stringify(Object.assign(getDefaultProps(), properties))}`;
}
else {
if (feature === 'reliability') {
let reliabilityData = properties;
telemetry = "##vso[task.logissue type=error;code=" + reliabilityData.issueType + ";agentVersion=" + tl.getVariable('Agent.Version') + ";taskId=" + area + "-" + JSON.stringify(taskJson.version) + ";]" + reliabilityData.errorMessage
}
}
console.log(telemetry);;
}
catch (err) {
tl.warning("Failed to log telemetry, error: " + err);
}
}
async function getLatestRelease(repositoryName: string, handler): Promise<Release> {
var promise = new Promise<Release>((resolve, reject) => {
let httpClient: httpc.HttpClient = new httpc.HttpClient(userAgent, [handler]);
let latestReleaseUrl = "https://api.github.com/repos/" + repositoryName + "/releases/latest";
latestReleaseUrl = latestReleaseUrl.replace(/([^:]\/)\/+/g, "$1");
httpClient.get(latestReleaseUrl).then((res) => {
res.readBody().then((body) => {
let response = JSON.parse(body);
let release: Release = {
Id: response["id"],
Name: response["tag_name"]
}
resolve(release);
});
}, (reason) => {
reject(reason);
});
});
return promise;
}
async function getTaggedRelease(repositoryName: string, tag: string, handler): Promise<Release> {
var promise = new Promise<Release>((resolve, reject) => {
let httpClient: httpc.HttpClient = new httpc.HttpClient(userAgent, [handler]);
let taggedReleaseUrl = "https://api.github.com/repos/" + repositoryName + "/releases/tags/" + tag;
taggedReleaseUrl = taggedReleaseUrl.replace(/([^:]\/)\/+/g, "$1");
httpClient.get(taggedReleaseUrl).then((res) => {
res.readBody().then((body) => {
let response = JSON.parse(body);
let release: Release = {
Id: response["id"],
Name: response["tag_name"]
}
resolve(release);
});
}, (reason) => {
reject(reason);
});
});
return promise;
}
async function getSpecificRelease(repositoryName: string, version: string, handler): Promise<Release> {
var promise = new Promise<Release>((resolve, reject) => {
let httpClient: httpc.HttpClient = new httpc.HttpClient(userAgent, [handler]);
let taggedReleaseUrl = "https://api.github.com/repos/" + repositoryName + "/releases/" + version;
taggedReleaseUrl = taggedReleaseUrl.replace(/([^:]\/)\/+/g, "$1");
httpClient.get(taggedReleaseUrl).then((res) => {
res.readBody().then((body) => {
let response = JSON.parse(body);
let release: Release = {
Id: response["id"],
Name: !!(response["name"]) ? response["name"] : response["tag_name"]
}
resolve(release);
});
}, (reason) => {
reject(reason);
});
});
return promise;
}
async function main(): Promise<void> {
var promise = new Promise<void>(async (resolve, reject) => {
let connection = tl.getInput("connection", true);
let repositoryName = tl.getInput("userRepository", true);
let defaultVersionType = tl.getInput("defaultVersionType", true);
let itemPattern = tl.getInput("itemPattern", false);
let downloadPath = tl.getInput("downloadPath", true);
let version = tl.getInput("version", false);
let release: Release = null;
if (!defaultVersionType) {
defaultVersionType = "latest";
}
var token = tl.getEndpointAuthorizationParameter(connection, 'AccessToken', false);
var retryLimit = parseInt(tl.getVariable("VSTS_HTTP_RETRY")) ? parseInt(tl.getVariable("VSTS_HTTP_RETRY")) : defaultRetryLimit;
// Required to prevent typed-rest-client from adding additional 'Authorization' in header on redirect to AWS
var customCredentialHandler = {
canHandleAuthentication: () => false,
handleAuthentication: () => { },
prepareRequest: (options) => {
//To handle single auth being used at a time, add Auth header only when X-AMZ is not used
if (options.host.indexOf("amazonaws") == -1 && options.path.indexOf("X-Amz-Algorithm") == -1) {
options.headers['Authorization'] = 'Bearer ' + token;
}
else {
if (!!options.headers['Authorization']) {
let updatedHeaders = {};
for (var key in options.headers) {
if (key.toLowerCase() != "authorization") {
updatedHeaders[key] = options.headers[key];
}
}
options.headers = updatedHeaders;
}
}
}
}
if (defaultVersionType.toLowerCase() == 'specificversion') {
release = await executeWithRetries("getSpecificRelease", () => getSpecificRelease(repositoryName, version, customCredentialHandler), retryLimit).catch((reason) => { reject(reason); });
}
else if (defaultVersionType.toLowerCase() == 'specifictag') {
release = await executeWithRetries("getTaggedRelease", () => getTaggedRelease(repositoryName, version, customCredentialHandler), retryLimit).catch((reason) => { reject(reason); });
}
else {
if (!!version) {
release = await executeWithRetries("getTaggedRelease", () => getTaggedRelease(repositoryName, version, customCredentialHandler), retryLimit).catch((reason) => { reject(reason); });
}
else {
release = await executeWithRetries("getLatestRelease", () => getLatestRelease(repositoryName, customCredentialHandler), retryLimit).catch((reason) => { reject(reason); });
}
}
if (!release || !release.Id) {
reject(tl.loc("InvalidRelease", version));
return;
}
var itemsUrl = "https://api.github.com/repos/" + repositoryName + "/releases/" + release.Id + "/assets";
itemsUrl = itemsUrl.replace(/([^:]\/)\/+/g, "$1");
console.log(tl.loc("DownloadArtifacts", release.Name, itemsUrl));
var templatePath = path.join(__dirname, 'githubrelease.handlebars.txt');
var gitHubReleaseVariables = {
"endpoint": {
"url": "https://api.github.com/"
}
};
var webProvider = new providers.WebProvider(itemsUrl, templatePath, gitHubReleaseVariables, customCredentialHandler);
var fileSystemProvider = new providers.FilesystemProvider(downloadPath);
var parallelLimit: number = +tl.getVariable("release.artifact.download.parallellimit");
var downloader = new engine.ArtifactEngine();
var downloaderOptions = new engine.ArtifactEngineOptions();
downloaderOptions.itemPattern = itemPattern ? itemPattern : '**';
var debugMode = tl.getVariable('System.Debug');
downloaderOptions.verbose = debugMode ? debugMode.toLowerCase() != 'false' : false;
if (parallelLimit) {
downloaderOptions.parallelProcessingLimit = parallelLimit;
}
await downloader.processItems(webProvider, fileSystemProvider, downloaderOptions).then((result) => {
console.log(tl.loc('ArtifactsSuccessfullyDownloaded', downloadPath));
resolve();
}).catch((error) => {
reject(error);
});
});
return promise;
}
function executeWithRetries(operationName: string, operation: () => Promise<any>, retryCount): Promise<any> {
var executePromise = new Promise((resolve, reject) => {
executeWithRetriesImplementation(operationName, operation, retryCount, resolve, reject);
});
return executePromise;
}
function executeWithRetriesImplementation(operationName: string, operation: () => Promise<any>, currentRetryCount, resolve, reject) {
operation().then((result) => {
resolve(result);
}).catch((error) => {
if (currentRetryCount <= 0) {
tl.error(tl.loc("OperationFailed", operationName, error));
reject(error);
}
else {
console.log(tl.loc('RetryingOperation', operationName, currentRetryCount));
currentRetryCount = currentRetryCount - 1;
setTimeout(() => executeWithRetriesImplementation(operationName, operation, currentRetryCount, resolve, reject), 4 * 1000);
}
});
}
main()
.then((result) => {
tl.setResult(tl.TaskResult.Succeeded, "");
})
.catch((err) => {
publishTelemetry('reliability', { issueType: 'error', errorMessage: JSON.stringify(err, Object.getOwnPropertyNames(err)) });
tl.setResult(tl.TaskResult.Failed, err);
}); | the_stack |
import Snackbar from '@material-ui/core/Snackbar';
import Typography from '@material-ui/core/Typography';
import MuiAlert, { AlertProps } from '@material-ui/lab/Alert';
import { ButtonFilled, ButtonOutlined } from 'litmus-ui';
import React, { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import { LitmusStepper } from '../../../../components/LitmusStepper';
import Loader from '../../../../components/Loader';
import Row from '../../../../containers/layouts/Row';
import { DashboardDetails } from '../../../../models/dashboardsData';
import { ListDataSourceResponse } from '../../../../models/graphql/dataSourceDetails';
import useActions from '../../../../redux/actions';
import * as AlertActions from '../../../../redux/actions/alert';
import { RootState } from '../../../../redux/reducers';
import { getProjectRole } from '../../../../utils/getSearchParams';
import ChooseADashboardType from '../Steps/ChooseADashboardType';
import ConfigureDashboardMetadata from '../Steps/ConfigureDashboardMetadata';
import SelectTheMetrics from '../Steps/SelectTheMetrics';
import TuneTheQueries from '../Steps/TuneTheQueries';
import useStyles from './styles';
interface ChildRef {
onNext: () => void;
}
interface AlertBoxProps {
message: string;
}
function Alert(props: AlertProps) {
return <MuiAlert elevation={6} variant="filled" {...props} />;
}
interface DashboardStepperProps {
configure: boolean;
activePanelID: string;
existingDashboardVars: DashboardDetails;
dataSourceList: ListDataSourceResponse[];
}
const DashboardStepper: React.FC<DashboardStepperProps> = ({
configure,
activePanelID,
existingDashboardVars,
dataSourceList,
}) => {
const classes = useStyles();
const { t } = useTranslation();
const stepsArray: string[] = [
`${t('monitoringDashboard.monitoringDashboards.stepper.steps.step1')}`,
`${t('monitoringDashboard.monitoringDashboards.stepper.steps.step2')}`,
`${t('monitoringDashboard.monitoringDashboards.stepper.steps.step3')}`,
`${t('monitoringDashboard.monitoringDashboards.stepper.steps.step4')}`,
];
const childRef = useRef<ChildRef>();
const [loading, setLoading] = React.useState<boolean>(false);
const [activeStep, setActiveStep] = React.useState<number>(
configure && activePanelID !== '' ? 1 : 0
);
const [dashboardVars, setDashboardVars] = React.useState<DashboardDetails>({
id: !configure ? '' : existingDashboardVars.id ?? '',
name: !configure ? '' : existingDashboardVars.name ?? '',
dashboardTypeID: !configure
? ''
: existingDashboardVars.dashboardTypeID ?? '',
dashboardTypeName: !configure
? ''
: existingDashboardVars.dashboardTypeName ?? '',
dataSourceType: !configure
? ''
: existingDashboardVars.dataSourceType ?? '',
dataSourceID: !configure
? dataSourceList.length !== 0
? dataSourceList[0].ds_id
: ''
: existingDashboardVars.dataSourceID ?? '',
dataSourceURL: !configure
? dataSourceList.length !== 0
? dataSourceList[0].ds_url
: ''
: existingDashboardVars.dataSourceURL ?? '',
chaosEventQueryTemplate: !configure
? ''
: existingDashboardVars.chaosEventQueryTemplate ?? '',
chaosVerdictQueryTemplate: !configure
? ''
: existingDashboardVars.chaosVerdictQueryTemplate ?? '',
agentID: !configure ? '' : existingDashboardVars.agentID ?? '',
information: !configure ? '' : existingDashboardVars.information ?? '',
panelGroupMap: !configure ? [] : existingDashboardVars.panelGroupMap ?? [],
panelGroups: !configure ? [] : existingDashboardVars.panelGroups ?? [],
selectedPanelGroupMap: [],
applicationMetadataMap: !configure
? []
: existingDashboardVars.applicationMetadataMap ?? [],
});
const [disabledNext, setDisabledNext] = React.useState<boolean>(true);
let steps = stepsArray;
if (configure) {
steps = steps.filter(
(step: string) =>
step !==
`${t(
'monitoringDashboard.monitoringDashboards.stepper.steps.step1'
)}` &&
step !==
`${t('monitoringDashboard.monitoringDashboards.stepper.steps.step3')}`
);
} else if (dashboardVars.dashboardTypeID === 'custom') {
steps = steps.filter(
(step: string) =>
step !==
`${t('monitoringDashboard.monitoringDashboards.stepper.steps.step3')}`
);
}
// Checks if the button is in loading state or not
const isButtonLoading = (status: boolean) => setLoading(status);
const handleNext = () => {
if (childRef.current && childRef.current.onNext()) {
setActiveStep((prevActiveStep) => prevActiveStep + 1);
}
};
function getStepContent(
stepIndex: number,
childRef: React.MutableRefObject<ChildRef | undefined>
): React.ReactNode {
switch (stepIndex) {
case !configure ? 0 : -1:
return <ChooseADashboardType ref={childRef} handleNext={handleNext} />;
case !configure ? 1 : 0:
return (
<ConfigureDashboardMetadata
ref={childRef}
configure={configure}
dashboardVars={dashboardVars}
dataSourceList={dataSourceList}
handleMetadataUpdate={(dashboardMetadata: DashboardDetails) => {
setDashboardVars({
...dashboardVars,
id: dashboardMetadata.id ?? '',
name: dashboardMetadata.name ?? '',
dashboardTypeID: dashboardMetadata.dashboardTypeID ?? '',
dashboardTypeName: dashboardMetadata.dashboardTypeName ?? '',
dataSourceType: dashboardMetadata.dataSourceType ?? '',
dataSourceID: dashboardMetadata.dataSourceID ?? '',
dataSourceURL: dashboardMetadata.dataSourceURL ?? '',
chaosEventQueryTemplate:
dashboardMetadata.chaosEventQueryTemplate ?? '',
chaosVerdictQueryTemplate:
dashboardMetadata.chaosVerdictQueryTemplate ?? '',
agentID: dashboardMetadata.agentID ?? '',
information: dashboardMetadata.information ?? '',
panelGroupMap: dashboardMetadata.panelGroupMap ?? [],
panelGroups: dashboardMetadata.panelGroups ?? [],
applicationMetadataMap:
dashboardMetadata.applicationMetadataMap ?? [],
});
}}
setDisabledNext={(next: boolean) => {
setDisabledNext(next);
}}
/>
);
case !configure
? dashboardVars.dashboardTypeID !== 'custom'
? 2
: -1
: -1:
return (
<SelectTheMetrics
ref={childRef}
dashboardVars={dashboardVars}
handleMetricsUpdate={(dashboardMetrics: DashboardDetails) => {
setDashboardVars({
...dashboardVars,
selectedPanelGroupMap:
dashboardMetrics.selectedPanelGroupMap ?? [],
});
}}
setDisabledNext={(next: boolean) => {
setDisabledNext(next);
}}
/>
);
case !configure
? dashboardVars.dashboardTypeID !== 'custom'
? 3
: 2
: 1:
return (
<TuneTheQueries
ref={childRef}
configure={configure}
isLoading={isButtonLoading}
activeEditPanelID={activePanelID}
dashboardVars={dashboardVars}
/>
);
default:
return <ChooseADashboardType ref={childRef} handleNext={handleNext} />;
}
}
const isAlertOpen = useSelector(
(state: RootState) => state.alert.isAlertOpen
);
const alert = useActions(AlertActions);
const handleBack = () => {
if (activeStep === 1 && !configure) {
setDashboardVars({
id: '',
name: '',
dashboardTypeID: '',
dashboardTypeName: '',
dataSourceType: '',
dataSourceID: '',
dataSourceURL: '',
chaosEventQueryTemplate: '',
chaosVerdictQueryTemplate: '',
agentID: '',
information: '',
panelGroupMap: [],
panelGroups: [],
selectedPanelGroupMap: [],
applicationMetadataMap: [],
});
}
setActiveStep((prevActiveStep) => prevActiveStep - 1);
};
/**
Control Buttons
------------------------------------------------------------------------------
When active step is zero (First Step) there won't be a Back button
When active step is the last step in the stepper the button will change to Finish
All steps in the middle will have next and back buttons
* */
const ControlButton: React.FC = () => {
return (
<>
{activeStep === steps.length - 1 ? ( // Show Save changes button at Bottom for Last Step
<div
className={classes.headerButtonWrapper}
aria-label="buttons"
style={{ width: 'fit-content' }}
>
{!loading && (
<ButtonOutlined
onClick={() => handleBack()}
style={{ marginRight: '1rem' }}
>
<Typography>
{t(
'monitoringDashboard.monitoringDashboards.stepper.buttons.back'
)}
</Typography>
</ButtonOutlined>
)}
<ButtonFilled disabled={loading} onClick={() => handleNext()}>
{!loading && (
<img
src="./icons/save-changes.svg"
alt="Info icon"
className={classes.icon}
/>
)}
<Typography className={classes.buttonText}>
{!loading
? `${t(
'monitoringDashboard.monitoringDashboards.stepper.buttons.saveChanges'
)}`
: configure
? `${t(
'monitoringDashboard.monitoringDashboards.stepper.buttons.status.updating'
)}`
: `${t(
'monitoringDashboard.monitoringDashboards.stepper.buttons.status.creating'
)}`}
</Typography>
{loading && <Loader size={20} />}
</ButtonFilled>
</div>
) : (activeStep !== 0 && !configure) ||
(activeStep === 0 && configure) ? ( // Apply headerButtonWrapper style for top button's div
<div className={classes.headerButtonWrapper} aria-label="buttons">
{!(activeStep === 0 && configure) && (
<ButtonOutlined
onClick={() => handleBack()}
style={{ marginRight: '1rem' }}
>
<Typography>
{t(
'monitoringDashboard.monitoringDashboards.stepper.buttons.back'
)}
</Typography>
</ButtonOutlined>
)}
<ButtonFilled onClick={() => handleNext()} disabled={disabledNext}>
<Typography>
{t(
'monitoringDashboard.monitoringDashboards.stepper.buttons.next'
)}
</Typography>
</ButtonFilled>
</div>
) : (
<></>
)}
</>
);
};
/**
Alert
------------------------------------------------------------------------------
Displays a snackbar with the appropriate message whenever a condition is not satisfied
* */
const AlertBox: React.FC<AlertBoxProps> = ({ message }) => {
return (
<div>
{isAlertOpen ? (
<Snackbar
open={isAlertOpen}
autoHideDuration={6000}
onClose={() => alert.changeAlertState(false)}
>
<Alert
onClose={() => alert.changeAlertState(false)}
severity="error"
>
{message}
</Alert>
</Snackbar>
) : (
<></>
)}
</div>
);
};
function getAlertMessage(stepNumber: number) {
switch (stepNumber) {
case !configure ? 0 : -1:
if (getProjectRole() === 'Viewer') {
return t(
'monitoringDashboard.monitoringDashboards.stepper.errors.step1.messageViewer'
);
}
return t(
'monitoringDashboard.monitoringDashboards.stepper.errors.step1.message'
);
case !configure ? 1 : 0:
return t(
'monitoringDashboard.monitoringDashboards.stepper.errors.step2.messageViewer'
);
case !configure
? dashboardVars.dashboardTypeID !== 'custom'
? 2
: -1
: -1:
return t(
'monitoringDashboard.monitoringDashboards.stepper.errors.step3.message'
);
case !configure
? dashboardVars.dashboardTypeID !== 'custom'
? 3
: 2
: 1:
return configure
? t(
'monitoringDashboard.monitoringDashboards.stepper.errors.step4.messageConfigure'
)
: t(
'monitoringDashboard.monitoringDashboards.stepper.errors.step4.messageCreate'
);
default:
return '';
}
}
useEffect(() => {
if (configure) {
setDashboardVars({
...existingDashboardVars,
});
}
}, [existingDashboardVars]);
return (
<div className={classes.root}>
{/* Alert */}
<AlertBox message={getAlertMessage(activeStep)} />
{/* Header */}
<div className={classes.headWrapper}>
<Row justifyContent="space-between">
<Typography className={classes.header}>
{!configure
? t('monitoringDashboard.monitoringDashboards.createHeader')
: `${t(
'monitoringDashboard.monitoringDashboards.configureHeader'
)} / ${dashboardVars.name}`}
</Typography>
<ControlButton />
</Row>
</div>
<br />
{/* Stepper */}
<LitmusStepper
steps={steps}
activeStep={activeStep}
handleBack={handleBack}
loader={loading}
hideNext={!configure ? !activeStep : false}
disableNext={
configure && activeStep === steps.length - 1 ? loading : disabledNext
}
handleNext={() => handleNext()}
finishAction={() => {}}
finishButtonText={
<>
{!loading && (
<img
src="./icons/save-changes.svg"
alt="Info icon"
className={classes.icon}
/>
)}
<Typography>
{!loading
? `${t(
'monitoringDashboard.monitoringDashboards.stepper.buttons.saveChanges'
)}`
: configure
? `${t(
'monitoringDashboard.monitoringDashboards.stepper.buttons.status.updating'
)}`
: `${t(
'monitoringDashboard.monitoringDashboards.stepper.buttons.status.creating'
)}`}
</Typography>
</>
}
>
{getStepContent(activeStep, childRef)}
</LitmusStepper>
</div>
);
};
export default DashboardStepper; | the_stack |
import {TestOptions, Test, Spec, Report} from "@swim/unit";
import {Slot, Value, Record, Num, Selector} from "@swim/structure";
import {ReconExam} from "../ReconExam";
export class ReconOperatorParserSpec extends Spec {
override createExam(report: Report, name: string, options: TestOptions): ReconExam {
return new ReconExam(report, this, name, options);
}
@Test
parseConditionalOperator(exam: ReconExam): void {
exam.parses("$a ? $b : $c", Selector.get("a").conditional(Selector.get("b"), Selector.get("c")));
exam.parses("$a ? $b : $c ? $d : $e", Selector.get("a").conditional(Selector.get("b"), Selector.get("c").conditional(Selector.get("d"), Selector.get("e"))));
}
@Test
parseLogicalOrOperator(exam: ReconExam): void {
exam.parses("$a || $b", Selector.get("a").or(Selector.get("b")));
exam.parses("$a || $b || $c", Selector.get("a").or(Selector.get("b")).or(Selector.get("c")));
}
@Test
parseLogicalAndOperator(exam: ReconExam): void {
exam.parses("$a && $b", Selector.get("a").and(Selector.get("b")));
exam.parses("$a && $b && $c", Selector.get("a").and(Selector.get("b")).and(Selector.get("c")));
}
@Test
parseLogicalNotOperator(exam: ReconExam): void {
exam.parses("!$a", Selector.get("a").not());
}
@Test
parseLogicalOperators(exam: ReconExam): void {
exam.parses("$a && $b || $c", Selector.get("a").and(Selector.get("b")).or(Selector.get("c")));
exam.parses("$a || $b && $c", Selector.get("a").or(Selector.get("b").and(Selector.get("c"))));
exam.parses("$a && $b || $c && $d", Selector.get("a").and(Selector.get("b")).or(Selector.get("c").and(Selector.get("d"))));
}
@Test
parseAssociatedLogicalOperators(exam: ReconExam): void {
exam.parses("$a && ($b || $c) && $d", Selector.get("a").and(Selector.get("b").or(Selector.get("c"))).and(Selector.get("d")));
exam.parses("!($a && $b) || $c && $d", Selector.get("a").and(Selector.get("b")).not().or(Selector.get("c").and(Selector.get("d"))));
exam.parses("$a && $b || !($c && $d)", Selector.get("a").and(Selector.get("b")).or(Selector.get("c").and(Selector.get("d")).not()));
exam.parses("!($a && $b) || !($c && $d)", Selector.get("a").and(Selector.get("b")).not().or(Selector.get("c").and(Selector.get("d")).not()));
exam.parses("!($a && $b || $c && $d)", Selector.get("a").and(Selector.get("b")).or(Selector.get("c").and(Selector.get("d"))).not());
exam.parses("$a && !($b || $c) && $d", Selector.get("a").and(Selector.get("b").or(Selector.get("c")).not()).and(Selector.get("d")));
}
@Test
parseBitwiseOrOperator(exam: ReconExam): void {
exam.parses("$a | $b", Selector.get("a").bitwiseOr(Selector.get("b")));
exam.parses("$a | $b | $c", Selector.get("a").bitwiseOr(Selector.get("b")).bitwiseOr(Selector.get("c")));
}
@Test
parseBitwiseXorOperator(exam: ReconExam): void {
exam.parses("$a ^ $b", Selector.get("a").bitwiseXor(Selector.get("b")));
exam.parses("$a ^ $b ^ $c", Selector.get("a").bitwiseXor(Selector.get("b")).bitwiseXor(Selector.get("c")));
}
@Test
parseBitwiseAndOperator(exam: ReconExam): void {
exam.parses("$a & $b", Selector.get("a").bitwiseAnd(Selector.get("b")));
exam.parses("$a & $b & $c", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseAnd(Selector.get("c")));
}
@Test
parseBitwiseNotOperator(exam: ReconExam): void {
exam.parses("~$a", Selector.get("a").bitwiseNot());
}
@Test
parseBitwiseOperators(exam: ReconExam): void {
exam.parses("$a & $b | $c", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseOr(Selector.get("c")));
exam.parses("$a | $b & $c", Selector.get("a").bitwiseOr(Selector.get("b").bitwiseAnd(Selector.get("c"))));
exam.parses("$a & $b | $c & $d", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseOr(Selector.get("c").bitwiseAnd(Selector.get("d"))));
exam.parses("$a & $b ^ $c", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseXor(Selector.get("c")));
exam.parses("$a ^ $b & $c", Selector.get("a").bitwiseXor(Selector.get("b").bitwiseAnd(Selector.get("c"))));
exam.parses("$a & $b ^ $c & $d", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseXor(Selector.get("c").bitwiseAnd(Selector.get("d"))));
exam.parses("$a ^ $b | $c", Selector.get("a").bitwiseXor(Selector.get("b")).bitwiseOr(Selector.get("c")));
exam.parses("$a | $b ^ $c", Selector.get("a").bitwiseOr(Selector.get("b").bitwiseXor(Selector.get("c"))));
exam.parses("$a ^ $b | $c ^ $d", Selector.get("a").bitwiseXor(Selector.get("b")).bitwiseOr(Selector.get("c").bitwiseXor(Selector.get("d"))));
}
@Test
parseAssociatedBitwiseOperators(exam: ReconExam): void {
exam.parses("$a & ($b | $c) & $d", Selector.get("a").bitwiseAnd(Selector.get("b").bitwiseOr(Selector.get("c"))).bitwiseAnd(Selector.get("d")));
exam.parses("~($a & $b) | $c & $d", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseNot().bitwiseOr(Selector.get("c").bitwiseAnd(Selector.get("d"))));
exam.parses("$a & $b | ~($c & $d)", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseOr(Selector.get("c").bitwiseAnd(Selector.get("d")).bitwiseNot()));
exam.parses("~($a & $b) | ~($c & $d)", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseNot().bitwiseOr(Selector.get("c").bitwiseAnd(Selector.get("d")).bitwiseNot()));
exam.parses("~($a & $b | $c & $d)", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseOr(Selector.get("c").bitwiseAnd(Selector.get("d"))).bitwiseNot());
exam.parses("$a & ~($b | $c) & $d", Selector.get("a").bitwiseAnd(Selector.get("b").bitwiseOr(Selector.get("c")).bitwiseNot()).bitwiseAnd(Selector.get("d")));
exam.parses("$a & ($b ^ $c) & $d", Selector.get("a").bitwiseAnd(Selector.get("b").bitwiseXor(Selector.get("c"))).bitwiseAnd(Selector.get("d")));
exam.parses("~($a & $b) ^ $c & $d", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseNot().bitwiseXor(Selector.get("c").bitwiseAnd(Selector.get("d"))));
exam.parses("$a & $b ^ ~($c & $d)", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseXor(Selector.get("c").bitwiseAnd(Selector.get("d")).bitwiseNot()));
exam.parses("~($a & $b) ^ ~($c & $d)", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseNot().bitwiseXor(Selector.get("c").bitwiseAnd(Selector.get("d")).bitwiseNot()));
exam.parses("~($a & $b ^ $c & $d)", Selector.get("a").bitwiseAnd(Selector.get("b")).bitwiseXor(Selector.get("c").bitwiseAnd(Selector.get("d"))).bitwiseNot());
exam.parses("$a & ~($b ^ $c) & $d", Selector.get("a").bitwiseAnd(Selector.get("b").bitwiseXor(Selector.get("c")).bitwiseNot()).bitwiseAnd(Selector.get("d")));
exam.parses("$a ^ ($b | $c) ^ $d", Selector.get("a").bitwiseXor(Selector.get("b").bitwiseOr(Selector.get("c"))).bitwiseXor(Selector.get("d")));
exam.parses("~($a ^ $b) | $c ^ $d", Selector.get("a").bitwiseXor(Selector.get("b")).bitwiseNot().bitwiseOr(Selector.get("c").bitwiseXor(Selector.get("d"))));
exam.parses("$a ^ $b | ~($c ^ $d)", Selector.get("a").bitwiseXor(Selector.get("b")).bitwiseOr(Selector.get("c").bitwiseXor(Selector.get("d")).bitwiseNot()));
exam.parses("~($a ^ $b) | ~($c ^ $d)", Selector.get("a").bitwiseXor(Selector.get("b")).bitwiseNot().bitwiseOr(Selector.get("c").bitwiseXor(Selector.get("d")).bitwiseNot()));
exam.parses("~($a ^ $b | $c ^ $d)", Selector.get("a").bitwiseXor(Selector.get("b")).bitwiseOr(Selector.get("c").bitwiseXor(Selector.get("d"))).bitwiseNot());
exam.parses("$a ^ ~($b | $c) ^ $d", Selector.get("a").bitwiseXor(Selector.get("b").bitwiseOr(Selector.get("c")).bitwiseNot()).bitwiseXor(Selector.get("d")));
}
@Test
parseBitwiseLogicalOperators(exam: ReconExam): void {
exam.parses("$a || $b && $c | $d ^ $e & $f", Selector.get("a").or(Selector.get("b").and(Selector.get("c").bitwiseOr(Selector.get("d").bitwiseXor(Selector.get("e").bitwiseAnd(Selector.get("f")))))));
exam.parses("$f & $e ^ $d | $c && $b || $a", Selector.get("f").bitwiseAnd(Selector.get("e")).bitwiseXor(Selector.get("d")).bitwiseOr(Selector.get("c")).and(Selector.get("b")).or(Selector.get("a")));
}
@Test
parseLtOperator(exam: ReconExam): void {
exam.parses("$a < 42", Selector.get("a").lt(Num.from(42)));
exam.parses("$a < $b", Selector.get("a").lt(Selector.get("b")));
}
@Test
parseLeOperator(exam: ReconExam): void {
exam.parses("$a <= 42", Selector.get("a").le(Num.from(42)));
exam.parses("$a <= $b", Selector.get("a").le(Selector.get("b")));
}
@Test
parseEqOperator(exam: ReconExam): void {
exam.parses("$a == 42", Selector.get("a").eq(Num.from(42)));
exam.parses("$a == $b", Selector.get("a").eq(Selector.get("b")));
}
@Test
parseNeOperator(exam: ReconExam): void {
exam.parses("$a != 42", Selector.get("a").ne(Num.from(42)));
exam.parses("$a != $b", Selector.get("a").ne(Selector.get("b")));
}
@Test
parseGeOperator(exam: ReconExam): void {
exam.parses("$a >= 42", Selector.get("a").ge(Num.from(42)));
exam.parses("$a >= $b", Selector.get("a").ge(Selector.get("b")));
}
@Test
parseGtOperator(exam: ReconExam): void {
exam.parses("$a > 42", Selector.get("a").gt(Num.from(42)));
exam.parses("$a > $b", Selector.get("a").gt(Selector.get("b")));
}
@Test
parsePlusOperator(exam: ReconExam): void {
exam.parses("$b + 2", Selector.get("b").plus(Num.from(2)));
exam.parses("2 + $b", Num.from(2).plus(Selector.get("b")));
exam.parses("$a + $b", Selector.get("a").plus(Selector.get("b")));
exam.parses("$a + $b + $c", Selector.get("a").plus(Selector.get("b")).plus(Selector.get("c")));
}
@Test
parseMinusOperator(exam: ReconExam): void {
exam.parses("$b - 2", Selector.get("b").minus(Num.from(2)));
exam.parses("2 - $b", Num.from(2).minus(Selector.get("b")));
exam.parses("$a - $b", Selector.get("a").minus(Selector.get("b")));
exam.parses("$a - $b - $c", Selector.get("a").minus(Selector.get("b")).minus(Selector.get("c")));
}
@Test
parseNegativeOperator(exam: ReconExam): void {
exam.parses("-$a", Selector.get("a").negative());
}
@Test
parsePositiveOperator(exam: ReconExam): void {
exam.parses("+$a", Selector.get("a").positive());
}
@Test
parseTimesOperator(exam: ReconExam): void {
exam.parses("$b * 2", Selector.get("b").times(Num.from(2)));
exam.parses("2 * $b", Num.from(2).times(Selector.get("b")));
exam.parses("$a * $b", Selector.get("a").times(Selector.get("b")));
exam.parses("$a * $b * $c", Selector.get("a").times(Selector.get("b")).times(Selector.get("c")));
}
@Test
parseDivideOperator(exam: ReconExam): void {
exam.parses("$b / 2", Selector.get("b").divide(Num.from(2)));
exam.parses("2 / $b", Num.from(2).divide(Selector.get("b")));
exam.parses("$a / $b", Selector.get("a").divide(Selector.get("b")));
exam.parses("$a / $b / $c", Selector.get("a").divide(Selector.get("b")).divide(Selector.get("c")));
}
@Test
parseModuloOperator(exam: ReconExam): void {
exam.parses("$b % 2", Selector.get("b").modulo(Num.from(2)));
exam.parses("2 % $b", Num.from(2).modulo(Selector.get("b")));
exam.parses("$a % $b", Selector.get("a").modulo(Selector.get("b")));
exam.parses("$a % $b % $c", Selector.get("a").modulo(Selector.get("b")).modulo(Selector.get("c")));
}
@Test
parseArithmeticOperators(exam: ReconExam): void {
exam.parses("$a * $b + $c", Selector.get("a").times(Selector.get("b")).plus(Selector.get("c")));
exam.parses("$a + $b * $c", Selector.get("a").plus(Selector.get("b").times(Selector.get("c"))));
exam.parses("$a * $b + $c * $d", Selector.get("a").times(Selector.get("b")).plus(Selector.get("c").times(Selector.get("d"))));
}
@Test
parseAssociatedArithmeticOperators(exam: ReconExam): void {
exam.parses("$a * ($b + $c) * $d", Selector.get("a").times(Selector.get("b").plus(Selector.get("c"))).times(Selector.get("d")));
exam.parses("-($a * $b) + $c * $d", Selector.get("a").times(Selector.get("b")).negative().plus(Selector.get("c").times(Selector.get("d"))));
exam.parses("$a * $b + -($c * $d)", Selector.get("a").times(Selector.get("b")).plus(Selector.get("c").times(Selector.get("d")).negative()));
exam.parses("-($a * $b) + -($c * $d)", Selector.get("a").times(Selector.get("b")).negative().plus(Selector.get("c").times(Selector.get("d")).negative()));
exam.parses("-($a * $b + $c * $d)", Selector.get("a").times(Selector.get("b")).plus(Selector.get("c").times(Selector.get("d"))).negative());
exam.parses("$a * -($b + $c) * $d", Selector.get("a").times(Selector.get("b").plus(Selector.get("c")).negative()).times(Selector.get("d")));
}
@Test
parseInvokeOperator(exam: ReconExam): void {
exam.parses("$foo()", Selector.get("foo").invoke(Value.extant()));
exam.parses("$bar($x)", Selector.get("bar").invoke(Selector.get("x")));
exam.parses("$baz($x, $y)", Selector.get("baz").invoke(Record.of(Selector.get("x"), Selector.get("y"))));
}
@Test
parseRecordsWithOperators(exam: ReconExam): void {
exam.parses("{a: $foo + 2, b: 2 + $bar}", Record.of(Slot.of("a", Selector.get("foo").plus(Num.from(2))), Slot.of("b", Num.from(2).plus(Selector.get("bar")))));
}
} | the_stack |
import { Vector3, Object3D, Euler } from "three";
import MeshVolume from "./MeshVolume";
import RayMarchedAtlasVolume from "./RayMarchedAtlasVolume";
import PathTracedVolume from "./PathTracedVolume";
import { LUT_ARRAY_LENGTH } from "./Histogram";
import Volume from "./Volume";
import { VolumeDisplayOptions, VolumeChannelDisplayOptions } from "./types";
import { Bounds, FuseChannel } from "./types";
import { ThreeJsPanel } from "./ThreeJsPanel";
import { Light } from "./Light";
import Channel from "./Channel";
// A renderable multichannel volume image with 8-bits per channel intensity values.
export default class VolumeDrawable {
public PT: boolean;
public volume: Volume;
private onChannelDataReadyCallback?: () => void;
private translation: Vector3;
private rotation: Euler;
private flipX: number;
private flipY: number;
private flipZ: number;
private maskChannelIndex: number;
private maskAlpha: number;
private gammaMin: number;
private gammaLevel: number;
private gammaMax: number;
private channelColors: [number, number, number][];
private channelOptions: VolumeChannelDisplayOptions[];
private fusion: FuseChannel[];
public specular: [number, number, number][];
public emissive: [number, number, number][];
public glossiness: number[];
public sceneRoot: Object3D;
private meshVolume: MeshVolume;
private primaryRayStepSize: number;
private secondaryRayStepSize: number;
private showBoundingBox: boolean;
private boundingBoxColor: [number, number, number];
// these two should never coexist simultaneously. always one or the other is present
// a polymorphic interface implementation might be a better way to deal with this.
// this is a remnant of a pre-typescript world
private pathTracedVolume?: PathTracedVolume;
private rayMarchedAtlasVolume?: RayMarchedAtlasVolume;
private volumeRendering: PathTracedVolume | RayMarchedAtlasVolume;
private bounds: Bounds;
private scale: Vector3;
private currentScale: Vector3;
private renderUpdateListener?: (number) => void;
private density: number;
private brightness: number;
constructor(volume: Volume, options: VolumeDisplayOptions) {
this.PT = !!options.renderMode;
// THE VOLUME DATA
this.volume = volume;
this.onChannelDataReadyCallback = undefined;
this.translation = new Vector3(0, 0, 0);
this.rotation = new Euler();
this.flipX = 1;
this.flipY = 1;
this.flipZ = 1;
this.maskChannelIndex = -1;
this.maskAlpha = 1.0;
this.gammaMin = 0.0;
this.gammaLevel = 1.0;
this.gammaMax = 1.0;
// TODO verify that these are reasonable
this.density = 0;
this.brightness = 0;
this.showBoundingBox = false;
this.boundingBoxColor = [1.0, 1.0, 0.0];
this.channelColors = this.volume.channel_colors_default.slice();
this.channelOptions = new Array(this.volume.num_channels).fill({});
this.fusion = this.channelColors.map((col, index) => {
let rgbColor;
// take copy of original channel color
if (col[0] === 0 && col[1] === 0 && col[2] === 0) {
rgbColor = 0;
} else {
rgbColor = [col[0], col[1], col[2]];
}
return {
chIndex: index,
lut: new Uint8Array(LUT_ARRAY_LENGTH),
rgbColor: rgbColor,
};
});
this.specular = new Array(this.volume.num_channels).fill([0, 0, 0]);
this.emissive = new Array(this.volume.num_channels).fill([0, 0, 0]);
this.glossiness = new Array(this.volume.num_channels).fill(0);
this.sceneRoot = new Object3D(); //create an empty container
this.meshVolume = new MeshVolume(this.volume);
this.primaryRayStepSize = 1.0;
this.secondaryRayStepSize = 1.0;
if (this.PT) {
this.volumeRendering = new PathTracedVolume(this.volume);
this.pathTracedVolume = this.volumeRendering;
} else {
this.volumeRendering = new RayMarchedAtlasVolume(this.volume);
this.rayMarchedAtlasVolume = this.volumeRendering;
}
// draw meshes first, and volume last, for blending and depth test reasons with raymarch
!this.PT && this.sceneRoot.add(this.meshVolume.get3dObject());
this.sceneRoot.add(this.volumeRendering.get3dObject());
// draw meshes last (as overlay) for pathtrace? (or not at all?)
//this.PT && this.sceneRoot.add(this.meshVolume.get3dObject());
this.bounds = {
bmin: new Vector3(-0.5, -0.5, -0.5),
bmax: new Vector3(0.5, 0.5, 0.5),
};
this.sceneRoot.position.set(0, 0, 0);
this.scale = new Vector3(1, 1, 1);
this.currentScale = new Vector3(1, 1, 1);
this.setScale(this.volume.scale);
// apply the volume's default transformation
this.setTranslation(new Vector3().fromArray(this.volume.getTranslation()));
this.setRotation(new Euler().fromArray(this.volume.getRotation()));
this.setOptions(options);
}
setOptions(options: VolumeDisplayOptions): void {
options = options || {};
if (options.maskChannelIndex !== undefined) {
this.setChannelAsMask(options.maskChannelIndex);
}
if (options.maskAlpha !== undefined) {
this.setMaskAlpha(options.maskAlpha);
}
if (options.clipBounds !== undefined) {
this.bounds = {
bmin: new Vector3(options.clipBounds[0], options.clipBounds[2], options.clipBounds[4]),
bmax: new Vector3(options.clipBounds[1], options.clipBounds[3], options.clipBounds[5]),
};
// note: dropping isOrthoAxis argument
this.setAxisClip(0, options.clipBounds[0], options.clipBounds[1]);
this.setAxisClip(1, options.clipBounds[2], options.clipBounds[3]);
this.setAxisClip(2, options.clipBounds[4], options.clipBounds[5]);
}
if (options.scale !== undefined) {
this.setScale(new Vector3().fromArray(options.scale));
}
if (options.translation !== undefined) {
this.setTranslation(new Vector3().fromArray(options.translation));
}
if (options.rotation !== undefined) {
this.setRotation(new Euler().fromArray(options.rotation));
}
if (options.renderMode !== undefined) {
this.setVolumeRendering(!!options.renderMode);
}
if (options.primaryRayStepSize !== undefined || options.secondaryRayStepSize !== undefined) {
this.setRayStepSizes(options.primaryRayStepSize, options.secondaryRayStepSize);
}
if (options.showBoundingBox !== undefined) {
this.setShowBoundingBox(options.showBoundingBox);
}
if (options.boundingBoxColor !== undefined) {
this.setBoundingBoxColor(options.boundingBoxColor);
}
if (options.channels !== undefined) {
// store channel options here!
this.channelOptions = options.channels;
this.channelOptions.forEach((channelOptions, channelIndex) => {
this.setChannelOptions(channelIndex, channelOptions);
});
}
}
setChannelOptions(channelIndex: number, options: VolumeChannelDisplayOptions): void {
// merge to current channel options
this.channelOptions[channelIndex] = Object.assign(this.channelOptions[channelIndex], options);
if (Object.hasOwnProperty.call(options, "enabled")) {
this.setVolumeChannelEnabled(channelIndex, options.enabled);
}
if (Object.hasOwnProperty.call(options, "color")) {
this.updateChannelColor(channelIndex, options.color);
}
if (Object.hasOwnProperty.call(options, "isosurfaceEnabled")) {
const hasIso = this.hasIsosurface(channelIndex);
if (hasIso !== options.isosurfaceEnabled) {
if (hasIso && !options.isosurfaceEnabled) {
this.destroyIsosurface(channelIndex);
} else if (!hasIso && options.isosurfaceEnabled) {
// 127 is half of the intensity range 0..255
let isovalue = 127;
if (Object.hasOwnProperty.call(options, "isovalue")) {
isovalue = options.isovalue;
}
// 1.0 is fully opaque
let isosurfaceOpacity = 1.0;
if (Object.hasOwnProperty.call(options, "isosurfaceOpacity")) {
isosurfaceOpacity = options.isosurfaceOpacity;
}
this.createIsosurface(channelIndex, isovalue, isosurfaceOpacity, isosurfaceOpacity < 1.0);
}
} else if (options.isosurfaceEnabled) {
if (Object.hasOwnProperty.call(options, "isovalue")) {
this.updateIsovalue(channelIndex, options.isovalue);
}
if (Object.hasOwnProperty.call(options, "isosurfaceOpacity")) {
this.updateOpacity(channelIndex, options.isosurfaceOpacity);
}
}
} else {
if (Object.hasOwnProperty.call(options, "isovalue")) {
this.updateIsovalue(channelIndex, options.isovalue);
}
if (Object.hasOwnProperty.call(options, "isosurfaceOpacity")) {
this.updateOpacity(channelIndex, options.isosurfaceOpacity);
}
}
}
setRayStepSizes(primary?: number, secondary?: number): void {
if (primary !== undefined) {
this.primaryRayStepSize = primary;
}
if (secondary !== undefined) {
this.secondaryRayStepSize = secondary;
}
this.volumeRendering.setRayStepSizes(this.primaryRayStepSize, this.secondaryRayStepSize);
}
setScale(scale: Vector3): void {
this.scale = scale;
this.currentScale = scale.clone();
this.meshVolume.setScale(scale);
this.volumeRendering.setScale(scale);
}
setOrthoScale(value: number): void {
this.volumeRendering.setOrthoScale(value);
}
setResolution(viewObj: ThreeJsPanel): void {
const x = viewObj.getWidth();
const y = viewObj.getHeight();
this.volumeRendering.setResolution(x, y);
this.meshVolume.setResolution(x, y);
}
// Set clipping range (between -0.5 and 0.5) for a given axis.
// Calling this allows the rendering to compensate for changes in thickness in orthographic views that affect how bright the volume is.
// @param {number} axis 0, 1, or 2 for x, y, or z axis
// @param {number} minval -0.5..0.5, should be less than maxval
// @param {number} maxval -0.5..0.5, should be greater than minval
// @param {boolean} isOrthoAxis is this an orthographic projection or just a clipping of the range for perspective view
setAxisClip(axis: number, minval: number, maxval: number, isOrthoAxis?: boolean): void {
this.bounds.bmax[axis] = maxval;
this.bounds.bmin[axis] = minval;
!this.PT && this.meshVolume.setAxisClip(axis, minval, maxval, !!isOrthoAxis);
this.volumeRendering.setAxisClip(axis, minval, maxval, isOrthoAxis || false);
}
// Tell this image that it needs to be drawn in an orthographic mode
// @param {boolean} isOrtho is this an orthographic projection or a perspective view
setIsOrtho(isOrtho: boolean): void {
this.volumeRendering.setIsOrtho(isOrtho);
}
setOrthoThickness(value: number): void {
!this.PT && this.meshVolume.setOrthoThickness(value);
this.volumeRendering.setOrthoThickness(value);
}
// Set parameters for gamma curve for volume rendering.
// @param {number} gmin 0..1
// @param {number} glevel 0..1
// @param {number} gmax 0..1, should be > gmin
setGamma(gmin: number, glevel: number, gmax: number): void {
this.gammaMin = gmin;
this.gammaLevel = glevel;
this.gammaMax = gmax;
this.volumeRendering.setGamma(gmin, glevel, gmax);
}
setFlipAxes(flipX: number, flipY: number, flipZ: number): void {
this.flipX = flipX;
this.flipY = flipY;
this.flipZ = flipZ;
this.volumeRendering.setFlipAxes(flipX, flipY, flipZ);
this.meshVolume.setFlipAxes(flipX, flipY, flipZ);
}
setMaxProjectMode(isMaxProject: boolean): void {
!this.PT && this.rayMarchedAtlasVolume && this.rayMarchedAtlasVolume.setMaxProjectMode(isMaxProject);
}
onAnimate(canvas: ThreeJsPanel): void {
// TODO: this is inefficient, as this work is duplicated by threejs.
// we need camera matrix up to date before giving the 3d objects a chance to use it.
canvas.camera.updateMatrixWorld(true);
canvas.camera.matrixWorldInverse.copy(canvas.camera.matrixWorld).invert();
// TODO confirm sequence
this.volumeRendering.doRender(canvas);
!this.PT && this.meshVolume.doRender(canvas);
}
// If an isosurface exists, update its isovalue and regenerate the surface. Otherwise do nothing.
updateIsovalue(channel: number, value: number): void {
this.meshVolume.updateIsovalue(channel, value);
}
getIsovalue(channel: number): number | undefined {
return this.meshVolume.getIsovalue(channel);
}
// Set opacity for isosurface
updateOpacity(channel: number, value: number): void {
this.meshVolume.updateOpacity(channel, value);
}
hasIsosurface(channel: number): boolean {
return this.meshVolume.hasIsosurface(channel);
}
// If an isosurface is not already created, then create one. Otherwise do nothing.
createIsosurface(channel: number, value: number, alpha: number, transp: boolean): void {
this.meshVolume.createIsosurface(channel, this.channelColors[channel], value, alpha, transp);
}
// If an isosurface exists for this channel, destroy it now. Don't just hide it - assume we can free up some resources.
destroyIsosurface(channel: number): void {
this.meshVolume.destroyIsosurface(channel);
}
fuse(): void {
if (!this.volume) {
return;
}
if (this.PT) {
if (this.pathTracedVolume) {
this.pathTracedVolume.updateActiveChannels(this);
}
} else {
if (this.rayMarchedAtlasVolume) {
this.rayMarchedAtlasVolume.fuse(this.fusion, this.volume.channels);
}
}
}
setRenderUpdateListener(callback?: (iteration: number) => void): void {
this.renderUpdateListener = callback;
if (this.PT && this.pathTracedVolume) {
this.pathTracedVolume.setRenderUpdateListener(callback);
}
}
updateShadingMethod(isbrdf: boolean): void {
if (this.PT && this.pathTracedVolume) {
this.pathTracedVolume.updateShadingMethod(isbrdf ? 1 : 0);
}
}
updateMaterial(): void {
this.PT && this.pathTracedVolume && this.pathTracedVolume.updateMaterial(this);
!this.PT && this.rayMarchedAtlasVolume && this.rayMarchedAtlasVolume.fuse(this.fusion, this.volume.channels);
}
updateLuts(): void {
this.PT && this.pathTracedVolume && this.pathTracedVolume.updateLuts(this);
!this.PT && this.rayMarchedAtlasVolume && this.rayMarchedAtlasVolume.fuse(this.fusion, this.volume.channels);
}
setVoxelSize(values: number[]): void {
this.volume.setVoxelSize(values);
this.setScale(this.volume.scale);
}
cleanup(): void {
this.meshVolume.cleanup();
this.volumeRendering.cleanup();
}
getChannel(channelIndex: number): Channel {
return this.volume.getChannel(channelIndex);
}
onChannelLoaded(batch: number[]): void {
this.volumeRendering.onChannelData(batch);
this.meshVolume.onChannelData(batch);
for (let j = 0; j < batch.length; ++j) {
const idx = batch[j];
this.setChannelOptions(idx, this.channelOptions[idx]);
}
// let the outside world have a chance
if (this.onChannelDataReadyCallback) {
this.onChannelDataReadyCallback();
}
}
onChannelAdded(newChannelIndex: number): void {
this.channelColors[newChannelIndex] = this.volume.channel_colors_default[newChannelIndex];
this.fusion[newChannelIndex] = {
chIndex: newChannelIndex,
lut: new Uint8Array[LUT_ARRAY_LENGTH](),
rgbColor: [
this.channelColors[newChannelIndex][0],
this.channelColors[newChannelIndex][1],
this.channelColors[newChannelIndex][2],
],
};
this.specular[newChannelIndex] = [0, 0, 0];
this.emissive[newChannelIndex] = [0, 0, 0];
this.glossiness[newChannelIndex] = 0;
}
// Save a channel's isosurface as a triangle mesh to either STL or GLTF2 format. File will be named automatically, using image name and channel name.
// @param {string} type Either 'GLTF' or 'STL'
saveChannelIsosurface(channelIndex: number, type: string): void {
this.meshVolume.saveChannelIsosurface(channelIndex, type, this.volume.name);
}
// Hide or display volume data for a channel
setVolumeChannelEnabled(channelIndex: number, enabled: boolean): void {
// flip the color to the "null" value
this.fusion[channelIndex].rgbColor = enabled ? this.channelColors[channelIndex] : 0;
// if all are nulled out, then hide the volume element from the scene.
if (this.fusion.every((elem) => elem.rgbColor === 0)) {
this.volumeRendering.setVisible(false);
} else {
this.volumeRendering.setVisible(true);
}
}
isVolumeChannelEnabled(channelIndex: number): boolean {
// the zero value for the fusion rgbColor is the indicator that a channel is hidden.
return this.fusion[channelIndex].rgbColor !== 0;
}
// Set the color for a channel
// @param {Array.<number>} colorrgb [r,g,b]
updateChannelColor(channelIndex: number, colorrgb: [number, number, number]): void {
if (!this.channelColors[channelIndex]) {
return;
}
this.channelColors[channelIndex] = colorrgb;
// if volume channel is zero'ed out, then don't update it until it is switched on again.
if (this.fusion[channelIndex].rgbColor !== 0) {
this.fusion[channelIndex].rgbColor = colorrgb;
}
this.meshVolume.updateMeshColors(this.channelColors);
}
// TODO remove this from public interface?
updateMeshColors(): void {
this.meshVolume.updateMeshColors(this.channelColors);
}
// Get the color for a channel
// @return {Array.<number>} The color as array of [r,g,b]
getChannelColor(channelIndex: number): [number, number, number] {
return this.channelColors[channelIndex];
}
// Set the material for a channel
// @param {number} channelIndex
// @param {Array.<number>} colorrgb [r,g,b]
// @param {Array.<number>} specularrgb [r,g,b]
// @param {Array.<number>} emissivergb [r,g,b]
// @param {number} glossiness
updateChannelMaterial(
channelIndex: number,
colorrgb: [number, number, number],
specularrgb: [number, number, number],
emissivergb: [number, number, number],
glossiness: number
): void {
if (!this.channelColors[channelIndex]) {
return;
}
this.updateChannelColor(channelIndex, colorrgb);
this.specular[channelIndex] = specularrgb;
this.emissive[channelIndex] = emissivergb;
this.glossiness[channelIndex] = glossiness;
}
setDensity(density: number): void {
this.density = density;
this.volumeRendering.setDensity(density);
}
/**
* Get the global density of the volume data
*/
getDensity(): number {
return this.density;
}
setBrightness(brightness: number): void {
this.brightness = brightness;
this.volumeRendering.setBrightness(brightness);
}
getBrightness(): number {
return this.brightness;
}
setChannelAsMask(channelIndex: number): boolean {
if (!this.volume.channels[channelIndex] || !this.volume.channels[channelIndex].loaded) {
return false;
}
this.maskChannelIndex = channelIndex;
return this.volumeRendering.setChannelAsMask(channelIndex);
}
setMaskAlpha(maskAlpha: number): void {
this.maskAlpha = maskAlpha;
this.volumeRendering.setMaskAlpha(maskAlpha);
}
setShowBoundingBox(showBoundingBox: boolean): void {
this.showBoundingBox = showBoundingBox;
this.volumeRendering.setShowBoundingBox(showBoundingBox);
}
setBoundingBoxColor(color: [number, number, number]): void {
this.boundingBoxColor = color;
this.volumeRendering.setBoundingBoxColor(color);
}
getIntensity(c: number, x: number, y: number, z: number): number {
return this.volume.getIntensity(c, x, y, z);
}
onStartControls(): void {
this.PT && this.pathTracedVolume && this.pathTracedVolume.onStartControls();
}
onChangeControls(): void {
this.PT && this.pathTracedVolume && this.pathTracedVolume.onChangeControls();
}
onEndControls(): void {
this.PT && this.pathTracedVolume && this.pathTracedVolume.onEndControls();
}
onResetCamera(): void {
this.volumeRendering.viewpointMoved();
}
onCameraChanged(fov: number, focalDistance: number, apertureSize: number): void {
this.PT && this.pathTracedVolume && this.pathTracedVolume.updateCamera(fov, focalDistance, apertureSize);
}
// values are in 0..1 range
updateClipRegion(xmin: number, xmax: number, ymin: number, ymax: number, zmin: number, zmax: number): void {
this.bounds.bmin = new Vector3(xmin - 0.5, ymin - 0.5, zmin - 0.5);
this.bounds.bmax = new Vector3(xmax - 0.5, ymax - 0.5, zmax - 0.5);
this.volumeRendering.updateClipRegion(xmin, xmax, ymin, ymax, zmin, zmax);
this.meshVolume.updateClipRegion(xmin, xmax, ymin, ymax, zmin, zmax);
}
updateLights(state: Light[]): void {
this.PT && this.pathTracedVolume && this.pathTracedVolume.updateLights(state);
}
setPixelSamplingRate(value: number): void {
this.volumeRendering.setPixelSamplingRate(value);
}
setVolumeRendering(isPathtrace: boolean): void {
if (isPathtrace === this.PT) {
return;
}
// remove old 3d object from scene
isPathtrace && this.sceneRoot.remove(this.meshVolume.get3dObject());
this.sceneRoot.remove(this.volumeRendering.get3dObject());
// destroy old resources.
this.volumeRendering.cleanup();
// create new
if (isPathtrace) {
this.volumeRendering = new PathTracedVolume(this.volume);
this.pathTracedVolume = this.volumeRendering;
this.rayMarchedAtlasVolume = undefined;
this.volumeRendering.setRenderUpdateListener(this.renderUpdateListener);
} else {
this.volumeRendering = new RayMarchedAtlasVolume(this.volume);
this.pathTracedVolume = undefined;
this.rayMarchedAtlasVolume = this.volumeRendering;
for (let i = 0; i < this.volume.num_channels; ++i) {
if (this.volume.getChannel(i).loaded) {
this.rayMarchedAtlasVolume.onChannelData([i]);
}
}
if (this.renderUpdateListener) {
this.renderUpdateListener(0);
}
}
// ensure transforms on new volume representation are up to date
this.volumeRendering.setTranslation(this.translation);
this.volumeRendering.setRotation(this.rotation);
this.PT = isPathtrace;
this.setChannelAsMask(this.maskChannelIndex);
this.setMaskAlpha(this.maskAlpha);
this.setScale(this.volume.scale);
this.setBrightness(this.getBrightness());
this.setDensity(this.getDensity());
this.setGamma(this.gammaMin, this.gammaLevel, this.gammaMax);
this.setFlipAxes(this.flipX, this.flipY, this.flipZ);
// reset clip bounds
this.setAxisClip(0, this.bounds.bmin.x, this.bounds.bmax.x);
this.setAxisClip(1, this.bounds.bmin.y, this.bounds.bmax.y);
this.setAxisClip(2, this.bounds.bmin.z, this.bounds.bmax.z);
this.updateClipRegion(
this.bounds.bmin.x + 0.5,
this.bounds.bmax.x + 0.5,
this.bounds.bmin.y + 0.5,
this.bounds.bmax.y + 0.5,
this.bounds.bmin.z + 0.5,
this.bounds.bmax.z + 0.5
);
this.setRayStepSizes(this.primaryRayStepSize, this.secondaryRayStepSize);
this.setShowBoundingBox(this.showBoundingBox);
this.setBoundingBoxColor(this.boundingBoxColor);
// add new 3d object to scene
!this.PT && this.sceneRoot.add(this.meshVolume.get3dObject());
this.sceneRoot.add(this.volumeRendering.get3dObject());
this.fuse();
}
setTranslation(xyz: Vector3): void {
this.translation.copy(xyz);
this.volumeRendering.setTranslation(this.translation);
this.meshVolume.setTranslation(this.translation);
}
setRotation(eulerXYZ: Euler): void {
this.rotation.copy(eulerXYZ);
this.volumeRendering.setRotation(this.rotation);
this.meshVolume.setRotation(this.rotation);
}
} | the_stack |
import {
commands,
events,
ExtensionContext,
FloatFactory,
LanguageClient,
LanguageClientOptions,
RevealOutputChannelOn,
StatusBarItem,
workspace,
WorkspaceConfiguration,
} from "coc.nvim";
import {
checkDottyIde,
fetchMetals,
getJavaConfig,
getJavaHome,
getServerOptions,
JavaConfig,
restartServer,
MetalsInitializationOptions,
ClientCommands,
ServerCommands,
MetalsStatus,
ExecuteClientCommand,
MetalsDidFocus,
MetalsInputBox,
InputBoxOptions,
MetalsQuickPick,
MetalsQuickPickParams,
} from "metals-languageclient";
import * as path from "path";
import {
ExecuteCommandRequest,
Location,
} from "vscode-languageserver-protocol";
import { Commands } from "./commands";
import DecorationProvider from "./decoration";
import { makeVimDoctor } from "./embeddedDoctor";
import {
DecorationsRangesDidChange,
PublishDecorationsParams,
} from "./metalsProtocol";
import { TreeViewController } from "./tvp/controller";
import { TreeViewFeature } from "./tvp/feature";
import { TreeViewsManager } from "./tvp/treeviews";
import {
checkServerVersion,
detectLaunchConfigurationChanges,
toggleLogs,
trackDownloadProgress,
wait,
} from "./utils";
import { DebuggingFeature } from "./DebuggingFeature";
import WannaBeStatusBarItem from "./WannaBeStatusBarItem";
export async function activate(context: ExtensionContext) {
const config: WorkspaceConfiguration = workspace.getConfiguration("metals");
if (config.get<boolean>("enable")) {
detectLaunchConfigurationChanges();
checkServerVersion(config);
getJavaHome(config.get<string>("javaHome")).then(
(javaHome) => fetchAndLaunchMetals(config, context, javaHome),
() => {
const message =
"Unable to find a Java 8 or Java 11 installation on this computer. " +
"To fix this problem, update the 'metals.javaHome' setting to point to a Java 8 or Java 11 home directory";
const openSettings = "Open Settings";
const ignore = "Ignore for now";
workspace
.showQuickpick([openSettings, ignore], message)
.then((choice) => {
if (choice === 0) {
workspace.nvim.command(Commands.OPEN_COC_CONFIG, true);
}
});
}
);
}
}
function fetchAndLaunchMetals(
config: WorkspaceConfiguration,
context: ExtensionContext,
javaHome: string
) {
const dottyIde = checkDottyIde(workspace.workspaceFolder?.uri);
if (dottyIde.enabled) {
workspace.showMessage(
`Metals will not start since Dotty is enabled for this workspace. ` +
`To enable Metals, remove the file ${dottyIde.path} and run ':CocCommand metals.restartServer'`,
"warning"
);
return;
}
const serverVersionConfig = config.get<string>("serverVersion");
const defaultServerVersion = config.inspect<string>("serverVersion")!
.defaultValue!;
const serverVersion = serverVersionConfig
? serverVersionConfig
: defaultServerVersion;
const serverProperties = config.get<string[]>("serverProperties")!;
const customRepositories = config.get<string[]>("customRepositories")!;
const javaConfig = getJavaConfig({
workspaceRoot: workspace.workspaceFolder?.uri,
javaHome,
customRepositories,
extensionPath: context.extensionPath,
});
const fetchProcess = fetchMetals({
serverVersion,
serverProperties,
javaConfig,
});
const statusBarEnabled = config.get<boolean>("statusBarEnabled");
const progress: StatusBarItem = statusBarEnabled
? workspace.createStatusBarItem(0, { progress: true })
: new WannaBeStatusBarItem(0, true, "Preparing Metals");
const title = `Downloading Metals v${serverVersion}`;
trackDownloadProgress(title, fetchProcess, progress).then(
(classpath) => {
launchMetals(
context,
classpath,
serverProperties,
javaConfig,
progress,
statusBarEnabled
);
},
() => {
const msg = (() => {
const proxy =
`See https://scalameta.org/metals/docs/build-tools/proxy.html for instructions ` +
`if you are using an HTTP proxy.`;
if (serverVersion === defaultServerVersion) {
return (
`Failed to download Metals, make sure you have an internet connection and ` +
`the Java Home '${javaHome}' is valid. You can configure the Java Home in the settings.` +
proxy
);
} else {
return (
`Failed to download Metals, make sure you have an internet connection, ` +
`the Metals version '${serverVersion}' is correct and the Java Home '${javaHome}' is valid. ` +
`You can configure the Metals version and Java Home in the settings.` +
proxy
);
}
})();
workspace.showPrompt(`${msg}\n Open Settings?`).then((choice) => {
if (choice) workspace.nvim.command(Commands.OPEN_COC_CONFIG, true);
});
}
);
}
async function launchMetals(
context: ExtensionContext,
metalsClasspath: string,
serverProperties: string[],
javaConfig: JavaConfig,
progress: StatusBarItem,
statusBarEnabled: boolean | undefined
) {
const serverOptions = getServerOptions({
metalsClasspath,
serverProperties,
javaConfig,
});
const initializationOptions: MetalsInitializationOptions = {
compilerOptions: {
completionCommand: "editor.action.triggerSuggest",
overrideDefFormat: "unicode",
parameterHintsCommand: "editor.action.triggerParameterHints",
},
debuggingProvider:
workspace.isNvim &&
(await workspace.nvim.getVar("loaded_vimpector")) === 1,
decorationProvider: workspace.isNvim,
didFocusProvider: true,
doctorProvider: "json",
executeClientCommandProvider: true,
inputBoxProvider: true,
quickPickProvider: true,
slowTaskProvider: true,
statusBarProvider: statusBarEnabled ? "on" : "show-message",
treeViewProvider: true,
};
const clientOptions: LanguageClientOptions = {
documentSelector: [{ scheme: "file", language: "scala" }],
synchronize: {
configurationSection: "metals",
},
revealOutputChannelOn: RevealOutputChannelOn.Never,
initializationOptions,
};
const client = new LanguageClient(
"metals",
"Metals",
serverOptions,
clientOptions
);
const treeViewFeature = new TreeViewFeature(client);
client.registerFeature(treeViewFeature);
if (clientOptions.initializationOptions.debuggingProvider) {
const debuggingFeature = new DebuggingFeature(workspace.nvim, client);
client.registerFeature(debuggingFeature);
}
const floatFactory = new FloatFactory(
workspace.nvim,
workspace.env,
false,
100,
100,
true
);
const decorationProvider = new DecorationProvider(floatFactory);
const treeViewsManager = new TreeViewsManager(workspace.nvim, context.logger);
const treeViewController = new TreeViewController(
treeViewFeature,
treeViewsManager
);
context.subscriptions.push(
treeViewFeature,
treeViewsManager,
treeViewController
);
function registerCommand(command: string, callback: (...args: any[]) => any) {
context.subscriptions.push(commands.registerCommand(command, callback));
}
registerCommand("metals.restartServer", restartServer(client, workspace));
context.subscriptions.push(client.start());
client.onReady().then((_) => {
progress.isProgress = false;
progress.text = "Metals is Ready!";
progress.show();
const commands = [
ServerCommands.AmmoniteStart,
ServerCommands.AmmoniteStop,
ServerCommands.BspSwitch,
ServerCommands.BuildConnect,
ServerCommands.BuildDisconnect,
ServerCommands.BuildImport,
ServerCommands.BuildRestart,
ServerCommands.CancelCompilation,
ServerCommands.CascadeCompile,
ServerCommands.CleanCompile,
ServerCommands.DoctorRun,
ServerCommands.GenerateBspConfig,
ServerCommands.NewScalaProject,
ServerCommands.ResetChoice,
ServerCommands.SourcesScan,
];
commands.forEach((command) => {
registerCommand("metals." + command, async () => {
client.sendRequest(ExecuteCommandRequest.type, { command });
});
});
registerCommand(`metals.${ServerCommands.AnalyzeStacktrace}`, async () => {
if (workspace.isVim) {
workspace.showMessage(
"Analyze stacktrace functionality isn't support in Vim. Please use Nvim if you'd like to use this.",
"warning"
);
} else {
const trace: string = await workspace.nvim.call("getreg", "*");
if (trace.trim().length < 1) {
workspace.showMessage(
"No text found in your register. Copy your stacktrace to your register and retry.",
"warning"
);
} else {
client.sendRequest(ExecuteCommandRequest.type, {
command: ServerCommands.AnalyzeStacktrace,
arguments: [trace],
});
}
}
});
registerCommand("metals.logs-toggle", () => {
toggleLogs();
});
if (workspace.isNvim) {
context.subscriptions.push(
workspace.registerKeymap(
["n"],
"metals-expand-decoration",
() => {
decorationProvider.showHover();
},
{ sync: false }
)
);
}
registerCommand(`metals.${ServerCommands.NewScalaFile}`, async () => {
const currentDoc = await workspace.document;
const currentPath = currentDoc.uri;
const parentDir = path.dirname(currentPath);
client.sendRequest(ExecuteCommandRequest.type, {
command: ServerCommands.NewScalaFile,
arguments: [parentDir],
});
});
registerCommand(`metals.quick-worksheet`, async () => {
const currentDoc = await workspace.document;
const currentPath = currentDoc.uri;
const parentDir = path.dirname(currentPath);
const name = path.basename(parentDir);
client.sendRequest(ExecuteCommandRequest.type, {
command: ServerCommands.NewScalaFile,
arguments: [parentDir, name, "worksheet"],
});
});
registerCommand(
`metals.${ServerCommands.CopyWorksheetOutput}`,
async () => {
const currentDoc = await workspace.document;
const currentPath = currentDoc.uri;
const response = await client.sendRequest(ExecuteCommandRequest.type, {
command: ServerCommands.CopyWorksheetOutput,
arguments: [currentPath],
});
if (response.value) {
workspace.nvim.call("setreg", ["+", response.value]);
workspace.showMessage("Copied worksheet to to your +register");
}
}
);
registerCommand(`metals.${ServerCommands.GotoSuperMethod}`, async () => {
const currentDoc = await workspace.document;
const position = await workspace.getCursorPosition();
client.sendRequest(ExecuteCommandRequest.type, {
command: ServerCommands.GotoSuperMethod,
arguments: [
{
document: currentDoc.uri,
position,
},
],
});
});
registerCommand(
`metals.${ServerCommands.SuperMethodHierarchy}`,
async () => {
const currentDoc = await workspace.document;
const position = await workspace.getCursorPosition();
client.sendRequest(ExecuteCommandRequest.type, {
command: ServerCommands.SuperMethodHierarchy,
arguments: [
{
document: currentDoc.uri,
position,
},
],
});
}
);
client.onNotification(ExecuteClientCommand.type, async (params) => {
switch (params.command) {
case ClientCommands.GotoLocation:
const location =
params.arguments && (params.arguments[0] as Location);
if (location) {
await treeViewsManager.prepareWindowForGoto();
// It seems this line fixes weird issue with "returned a response with an unknown
// request id" after executing commands several times.
await wait(10);
await workspace.jumpTo(location.uri, location.range.start);
}
break;
case ClientCommands.RunDoctor:
const doctorJson: string = params.arguments && params.arguments[0];
makeVimDoctor(JSON.parse(doctorJson));
break;
case ClientCommands.ReloadDoctor:
workspace.nvim.call(Commands.HAS_PREVIEW).then((preview) => {
if (preview > 0) {
const doctorJson: string =
params.arguments && params.arguments[0];
makeVimDoctor(JSON.parse(doctorJson));
}
});
break;
case ClientCommands.FocusDiagnostics:
workspace.nvim.command("CocList diagnostics");
break;
case ClientCommands.ToggleLogs:
toggleLogs();
break;
case ClientCommands.RefreshModel:
// CodeLensManager from coc.nvim reloads codeLens on this event
events.fire("BufEnter", [workspace.bufnr]);
break;
default:
workspace.showMessage(`Recieved unknown command: ${params.command}`);
}
});
events.on("BufWinEnter", (bufnr: number) => {
const currentDocument = workspace.documents.find(
(document) => document.bufnr === bufnr
);
// For now I'm just checking for scala since both scala and sc files will be marked
// as scala, and this is only relevant for decorations anyways.
if (currentDocument && currentDocument.filetype === "scala") {
client.sendNotification(MetalsDidFocus.type, currentDocument.uri);
}
});
client.onRequest(MetalsInputBox.type, (options: InputBoxOptions) => {
return workspace
.callAsync<string>("input", [
`${options.prompt}: `,
options.value ? options.value : "",
])
.then(MetalsInputBox.handleInput);
});
client.onRequest(MetalsQuickPick.type, (params: MetalsQuickPickParams, _) =>
workspace
.showQuickpick(
params.items.map((item) => item.label),
params.placeHolder
)
.then((answer) => {
if (answer === -1) {
return { cancelled: true };
} else {
return { itemId: params.items[answer].id };
}
})
);
if (statusBarEnabled) {
const statusItem = workspace.createStatusBarItem(0);
client.onNotification(MetalsStatus.type, (params) => {
if (params.show) {
statusItem.text = params.text;
} else if (params.hide) {
statusItem.text = "Metals";
}
statusItem.show();
});
}
if (workspace.isNvim) {
client.onNotification(
DecorationsRangesDidChange.type,
(params: PublishDecorationsParams) => {
if (workspace.uri && workspace.uri === params.uri) {
decorationProvider.setDecorations(params);
}
}
);
events.on("BufWinLeave", (bufnr: number) => {
const previousDocument = workspace.documents.find(
(document) => document.bufnr === bufnr
);
if (
previousDocument &&
previousDocument.uri.endsWith(".worksheet.sc")
) {
decorationProvider.clearDecorations(bufnr);
}
});
}
});
} | the_stack |
import assert from "assert";
import AccountManager = require("../script/management-sdk");
import adapterTypes = require("../utils/adapter/adapter-types");
var request = require("superagent");
var manager: AccountManager;
const testUser: adapterTypes.UserProfile = {
id: "testId",
avatar_url: "testAvatarUrl",
can_change_password: false,
display_name: "testDisplayName",
email: "testEmail",
name: "testUserName",
permissions: ["manager"],
}
const testDeployment: adapterTypes.Deployment = {
createdTime: 123,
name: "testDeployment1",
key: "testKey1"
};
const testDeployment2: adapterTypes.Deployment = {
createdTime: 123,
name: "testDeployment2",
key: "testKey2"
};
const testApp: adapterTypes.App = {
name: "testAppName",
owner: { ...testUser, type: "user" }
}
const codePushRelease: adapterTypes.CodePushRelease = {
description: "testDescription",
target_binary_range: "testTargetBinaryRange",
upload_time: 123456789,
blob_url: "testBlobUrl",
size: 123456789
}
describe("Management SDK", () => {
beforeEach(() => {
manager = new AccountManager(/*accessKey=*/ "dummyAccessKey", /*customHeaders=*/ null, /*serverUrl=*/ "http://localhost");
});
after(() => {
// Prevent an exception that occurs due to how superagent-mock overwrites methods
request.Request.prototype._callback = function () { };
});
it("methods reject the promise with status code info when an error occurs", (done: Mocha.Done) => {
mockReturn("Text", 404);
var methodsWithErrorHandling: any[] = [
manager.addApp.bind(manager, "appName", "iOS", "Cordova"),
manager.getApp.bind(manager, "appName"),
manager.renameApp.bind(manager, "appName", {}),
manager.removeApp.bind(manager, "appName"),
manager.transferApp.bind(manager, "appName", "email1"),
manager.addDeployment.bind(manager, "appName", "deploymentName"),
manager.getDeployment.bind(manager, "appName", "deploymentName"),
manager.getDeployments.bind(manager, "appName"),
manager.renameDeployment.bind(manager, "appName", "deploymentName", { name: "newDeploymentName" }),
manager.removeDeployment.bind(manager, "appName", "deploymentName"),
manager.addCollaborator.bind(manager, "appName", "email1"),
manager.getCollaborators.bind(manager, "appName"),
manager.removeCollaborator.bind(manager, "appName", "email1"),
manager.patchRelease.bind(manager, "appName", "deploymentName", "label", { description: "newDescription" }),
manager.promote.bind(manager, "appName", "deploymentName", "newDeploymentName", { description: "newDescription" }),
manager.rollback.bind(manager, "appName", "deploymentName", "targetReleaseLabel")
];
var result = Promise.resolve(null);
methodsWithErrorHandling.forEach(function (f) {
result = result.then(() => {
return testErrors(f);
});
});
result.then(() => {
done();
});
// Test that the proper error code and text is passed through on a server error
function testErrors(method: any): Promise<void> {
return new Promise<void>((resolve: any, reject: any) => {
method().then(() => {
assert.fail("Should have thrown an error");
reject();
}, (error: any) => {
assert.equal(error.message, "Text");
assert(error.statusCode);
resolve();
});
});
}
});
describe("isAuthenticated", () => {
it("isAuthenticated handles successful auth", (done: Mocha.Done) => {
mockReturn(JSON.stringify(testUser), 200);
manager.isAuthenticated()
.then((authenticated: boolean) => {
assert(authenticated, "Should be authenticated");
done();
});
});
it("isAuthenticated handles unsuccessful auth", (done: Mocha.Done) => {
mockReturn("Unauthorized", 401);
manager.isAuthenticated()
.then((authenticated: boolean) => {
assert(!authenticated, "Should not be authenticated");
done();
});
});
it("isAuthenticated handles unsuccessful auth with promise rejection", (done: Mocha.Done) => {
mockReturn("Unauthorized", 401);
// use optional parameter to ask for rejection of the promise if not authenticated
manager.isAuthenticated(true)
.then((authenticated: boolean) => {
assert.fail("isAuthenticated should have rejected the promise");
done();
}, (err) => {
assert.equal(err.message, "Unauthorized", "Error message should be 'Unauthorized'");
done();
});
});
it("isAuthenticated handles unexpected status codes", (done: Mocha.Done) => {
mockReturn("Not Found", 404);
manager.isAuthenticated()
.then((authenticated: boolean) => {
assert.fail("isAuthenticated should have rejected the promise");
done();
}, (err) => {
assert.equal(err.message, "Not Found", "Error message should be 'Not Found'");
done();
});
});
});
describe("addApp", () => {
it("addApp handles successful response", (done: Mocha.Done) => {
mockReturn(JSON.stringify(testApp), 201, null, { location: "/appName" });
manager.addApp("appName", "iOS", "React-Native")
.then((obj) => {
assert.ok(obj);
done();
}, rejectHandler);
});
it("addApp handles error response", (done: Mocha.Done) => {
mockReturn(JSON.stringify({ success: false }), 404);
manager.addApp("appName", "iOS", "React-Native")
.then((obj) => {
throw new Error("Call should not complete successfully");
}, (error: Error) => done());
});
});
describe("getApp", () => {
it("getApp handles JSON response", (done: Mocha.Done) => {
mockReturn(JSON.stringify(testApp), 200);
mockUser();
mockReturn(JSON.stringify([testDeployment, testDeployment2]), 200, `/apps/${testUser.name}/${testApp.name}/deployments/`)
manager.getApp("appName")
.then((obj: any) => {
assert.ok(obj);
done();
}, rejectHandler);
});
});
describe("updateApp", () => {
it("updateApp handles success response", (done: Mocha.Done) => {
mockReturn(JSON.stringify(testApp), 200);
manager.renameApp("appName", "newAppName")
.then((obj: any) => {
assert.ok(!obj);
done();
}, rejectHandler);
});
});
describe("removeApp", () => {
it("removeApp handles success response", (done: Mocha.Done) => {
mockReturn("", 200);
mockUser();
manager.removeApp("appName")
.then((obj: any) => {
assert.ok(!obj);
done();
}, rejectHandler);
});
});
describe("transferApp", () => {
it("transferApp handles successful response", (done: Mocha.Done) => {
mockReturn("", 201);
mockUser();
manager.transferApp("appName", "email1")
.then(
() => done(),
rejectHandler
);
});
});
describe("addDeployment", () => {
it("addDeployment handles success response", (done: Mocha.Done) => {
const testDeploymentWithoutPackage: adapterTypes.Deployment = { ...testDeployment, latest_release: null }
mockReturn(JSON.stringify(testDeploymentWithoutPackage), 201, null, { location: "/deploymentName" });
manager.addDeployment("appName", "deploymentName")
.then((obj: any) => {
assert.ok(obj);
done();
}, rejectHandler);
});
});
describe("getDeployment", () => {
it("getDeployment handles JSON response", (done: Mocha.Done) => {
mockReturn(JSON.stringify(testDeployment), 200);
mockUser();
manager.getDeployment("appName", "deploymentName")
.then((obj: any) => {
assert.ok(obj);
done();
}, rejectHandler);
});
});
describe("getDeployments", () => {
it("getDeployments handles JSON response", (done: Mocha.Done) => {
mockReturn(JSON.stringify([testDeployment, testDeployment2]), 200);
mockUser();
manager.getDeployments("appName")
.then((obj: any) => {
assert.ok(obj);
done();
}, rejectHandler);
});
});
describe("renameDeployment", () => {
it("renameDeployment handles success response", (done: Mocha.Done) => {
mockReturn(JSON.stringify(testApp), 200);
manager.renameDeployment("appName", "deploymentName", "newDeploymentName")
.then((obj: any) => {
assert.ok(!obj);
done();
}, rejectHandler);
});
});
describe("removeDeployment", () => {
it("removeDeployment handles success response", (done: Mocha.Done) => {
mockReturn("", 200);
mockUser();
manager.removeDeployment("appName", "deploymentName")
.then((obj: any) => {
assert.ok(!obj);
done();
}, rejectHandler);
});
});
describe("getDeploymentHistory", () => {
it("getDeploymentHistory handles success response with no packages", (done: Mocha.Done) => {
mockReturn(JSON.stringify([]), 200);
mockUser();
manager.getDeploymentHistory("appName", "deploymentName")
.then((obj: any) => {
assert.ok(obj);
assert.equal(obj.length, 0);
done();
}, rejectHandler);
});
it("getDeploymentHistory handles success response with two packages", (done: Mocha.Done) => {
const release: adapterTypes.CodePushRelease = { ...codePushRelease, label: "v1" };
const release2: adapterTypes.CodePushRelease = { ...codePushRelease, label: "v2" };
mockReturn(JSON.stringify([release, release2]), 200);
mockUser();
manager.getDeploymentHistory("appName", "deploymentName")
.then((obj: any) => {
assert.ok(obj);
assert.equal(obj.length, 2);
assert.equal(obj[0].label, "v1");
assert.equal(obj[1].label, "v2");
done();
}, rejectHandler);
});
it("getDeploymentHistory handles error response", (done: Mocha.Done) => {
mockReturn("", 404);
manager.getDeploymentHistory("appName", "deploymentName")
.then((obj: any) => {
throw new Error("Call should not complete successfully");
}, (error: Error) => done());
});
});
describe("clearDeploymentHistory", () => {
it("clearDeploymentHistory handles success response", (done: Mocha.Done) => {
mockReturn("", 204);
mockUser();
manager.clearDeploymentHistory("appName", "deploymentName")
.then((obj: any) => {
assert.ok(!obj);
done();
}, rejectHandler);
});
it("clearDeploymentHistory handles error response", (done: Mocha.Done) => {
mockReturn("", 404);
manager.clearDeploymentHistory("appName", "deploymentName")
.then((obj: any) => {
throw new Error("Call should not complete successfully");
}, (error: Error) => done());
});
});
describe("addCollaborator", () => {
it("addCollaborator handles successful response", (done: Mocha.Done) => {
mockReturn("", 201, null, { location: "/collaborators" });
mockUser();
manager.addCollaborator("appName", "email1")
.then(
() => done(),
rejectHandler
);
});
it("addCollaborator handles error response", (done: Mocha.Done) => {
mockReturn("", 404);
manager.addCollaborator("appName", "email1")
.then(
() => { throw new Error("Call should not complete successfully") },
() => done()
);
});
});
describe("getCollaborators", () => {
it("getCollaborators handles success response with no collaborators", (done: Mocha.Done) => {
mockReturn(JSON.stringify([]), 200);
mockUser();
manager.getCollaborators("appName")
.then((obj: any) => {
assert.ok(obj);
assert.equal(Object.keys(obj).length, 0);
done();
}, rejectHandler);
});
it("getCollaborators handles success response with multiple collaborators", (done: Mocha.Done) => {
const testUser2: adapterTypes.UserProfile = {
...testUser,
email: "testEmail2",
permissions: ["developer"]
}
mockReturn(JSON.stringify([testUser, testUser2]), 200);
mockUser();
manager.getCollaborators("appName")
.then((obj: any) => {
assert.ok(obj);
assert.equal(obj[testUser.email].permission, "Owner");
assert.equal(obj[testUser2.email].permission, "Collaborator");
done();
}, rejectHandler);
});
});
describe("removeCollaborator", () => {
it("removeCollaborator handles success response", (done: Mocha.Done) => {
mockReturn("", 200);
mockUser();
manager.removeCollaborator("appName", "email1")
.then((obj: any) => {
assert.ok(!obj);
done();
}, rejectHandler);
});
});
describe("patchRelease", () => {
it("patchRelease handles success response", (done: Mocha.Done) => {
const newReleasePackage: adapterTypes.CodePushRelease = { ...codePushRelease, description: "newDescription" };
mockReturn(JSON.stringify(newReleasePackage), 200);
manager.patchRelease("appName", "deploymentName", "label", { description: "newDescription" })
.then((obj: any) => {
assert.ok(!obj);
done();
}, rejectHandler);
});
it("patchRelease handles error response", (done: Mocha.Done) => {
mockReturn("", 400);
manager.patchRelease("appName", "deploymentName", "label", {})
.then((obj: any) => {
throw new Error("Call should not complete successfully");
}, (error: Error) => done());
});
});
describe("promote", () => {
it("promote handles success response", (done: Mocha.Done) => {
const newReleasePackage: adapterTypes.CodePushRelease = { ...codePushRelease, description: "newDescription" };
mockReturn(JSON.stringify(newReleasePackage), 200);
manager.promote("appName", "deploymentName", "newDeploymentName", { description: "newDescription" })
.then((obj: any) => {
assert.ok(obj);
assert.equal(obj.description, "newDescription")
done();
}, rejectHandler);
});
it("promote handles error response", (done: Mocha.Done) => {
mockReturn("", 400);
manager.promote("appName", "deploymentName", "newDeploymentName", { rollout: 123 })
.then((obj: any) => {
throw new Error("Call should not complete successfully");
}, (error: Error) => done());
});
});
describe("rollback", () => {
it("rollback handles success response", (done: Mocha.Done) => {
mockReturn(JSON.stringify(codePushRelease), 200);
manager.rollback("appName", "deploymentName", "v1")
.then((obj: any) => {
assert.ok(!obj);
done();
}, rejectHandler);
});
it("rollback handles error response", (done: Mocha.Done) => {
mockReturn("", 400);
manager.rollback("appName", "deploymentName", "v1")
.then((obj: any) => {
throw new Error("Call should not complete successfully");
}, (error: Error) => done());
});
});
});
// Helper method that is used everywhere that an assert.fail() is needed in a promise handler
function rejectHandler(val: any): void {
assert.fail();
}
function mockUser(): void {
mockReturn(JSON.stringify(testUser), 200, "/user");
}
// Wrapper for superagent-mock that abstracts away information not needed for SDK tests
function mockReturn(bodyText: string, statusCode: number, pattern?: string, header = {}): void {
require("superagent-mock")(request, [{
pattern: "http://localhost" + (pattern ? pattern : "/(\\w+)/?"),
fixtures: function (match: any, params: any): any {
var isOk = statusCode >= 200 && statusCode < 300;
if (!isOk) {
var err: any = new Error(bodyText);
err.status = statusCode;
throw err;
}
return { text: bodyText, status: statusCode, ok: isOk, header: header, headers: {} };
},
callback: function (match: any, data: any): any { return data; }
}]);
} | the_stack |
import {
inject,
onBeforeMount,
onMounted,
onUnmounted,
InjectionKey,
getCurrentInstance,
isRef
} from 'vue'
import {
isEmptyObject,
isBoolean,
warn,
makeSymbol,
createEmitter,
assign
} from '@intlify/shared'
import { createComposer } from './composer'
import { createVueI18n } from './legacy'
import { I18nWarnCodes, getWarnMessage } from './warnings'
import { I18nErrorCodes, createI18nError } from './errors'
import {
EnableEmitter,
DisableEmitter,
InejctWithOption,
LegacyInstanceSymbol,
__VUE_I18N_BRIDGE__
} from './symbols'
import { apply as applyNext } from './plugin/next'
import { apply as applyBridge } from './plugin/bridge'
import { defineMixin as defineMixinNext } from './mixins/next'
import { defineMixin as defineMixinBridge } from './mixins/bridge'
import { enableDevTools, addTimelineEvent } from './devtools'
import {
isLegacyVueI18n,
getComponentOptions,
adjustI18nResources
} from './utils'
import type { ComponentInternalInstance, App } from 'vue'
import type {
Locale,
FallbackLocale,
SchemaParams,
LocaleParams
} from '@intlify/core-base'
import type {
VueDevToolsEmitter,
VueDevToolsEmitterEvents
} from '@intlify/vue-devtools'
import type {
VueMessageType,
DefaultLocaleMessageSchema,
DefaultDateTimeFormatSchema,
DefaultNumberFormatSchema,
Composer,
ComposerOptions,
ComposerInternalOptions
} from './composer'
import type { VueI18n, VueI18nOptions, VueI18nInternal } from './legacy'
declare module 'vue' {
// eslint-disable-next-line
interface App<HostElement = any> {
__VUE_I18N__?: I18n & I18nInternal
__VUE_I18N_SYMBOL__?: InjectionKey<I18n> | string
}
}
// for bridge
let _legacyVueI18n: any = /* #__PURE__*/ null // eslint-disable-line @typescript-eslint/no-explicit-any
let _legacyI18n: I18n | null = /* #__PURE__*/ null // eslint-disable-line @typescript-eslint/no-explicit-any
/**
* I18n Options for `createI18n`
*
* @remarks
* `I18nOptions` is inherited {@link I18nAdditionalOptions}, {@link ComposerOptions} and {@link VueI18nOptions},
* so you can specify these options.
*
* @VueI18nGeneral
*/
export type I18nOptions<
Schema extends {
message?: unknown
datetime?: unknown
number?: unknown
} = {
message: DefaultLocaleMessageSchema
datetime: DefaultDateTimeFormatSchema
number: DefaultNumberFormatSchema
},
Locales extends
| {
messages: unknown
datetimeFormats: unknown
numberFormats: unknown
}
| string = Locale,
Options extends
| ComposerOptions<Schema, Locales>
| VueI18nOptions<Schema, Locales> =
| ComposerOptions<Schema, Locales>
| VueI18nOptions<Schema, Locales>
> = I18nAdditionalOptions & Options
/**
* I18n Additional Options
*
* @remarks
* Specific options for {@link createI18n}
*
* @VueI18nGeneral
*/
export interface I18nAdditionalOptions {
/**
* Whether vue-i18n Legacy API mode use on your Vue App
*
* @remarks
* The default is to use the Legacy API mode. If you want to use the Composition API mode, you need to set it to `false`.
*
* @VueI18nSee [Composition API](../guide/advanced/composition)
*
* @defaultValue `true`
*/
legacy?: boolean
/**
* Whether to inject global properties & functions into for each component.
*
* @remarks
* If set to `true`, then properties and methods prefixed with `$` are injected into Vue Component.
*
* @VueI18nSee [Implicit with injected properties and functions](../guide/advanced/composition#implicit-with-injected-properties-and-functions)
* @VueI18nSee [ComponentCustomProperties](injection#componentcustomproperties)
*
* @defaultValue `false`
*/
globalInjection?: boolean
}
/**
* Vue I18n API mode
*
* @VueI18nSee [I18n#mode](general#mode)
*
* @VueI18nGeneral
*/
export type I18nMode = 'legacy' | 'composition'
/**
* I18n instance
*
* @remarks
* The instance required for installation as the Vue plugin
*
* @VueI18nGeneral
*/
export interface I18n<
Messages = {},
DateTimeFormats = {},
NumberFormats = {},
OptionLocale = Locale,
Legacy = boolean
> {
/**
* Vue I18n API mode
*
* @remarks
* If you specified `legacy: true` option in `createI18n`, return `legacy`, else `composition`
*
* @defaultValue `'composition'`
*/
readonly mode: I18nMode
// prettier-ignore
/**
* The property accessible to the global Composer instance or VueI18n instance
*
* @remarks
* If the [I18n#mode](general#mode) is `'legacy'`, then you can access to a global {@link VueI18n} instance, else then [I18n#mode](general#mode) is `'composition' `, you can access to the global {@link Composer} instance.
*
* An instance of this property is **global scope***.
*/
readonly global: Legacy extends true
? VueI18n<Messages, DateTimeFormats, NumberFormats, OptionLocale>
: Legacy extends false
? Composer<Messages, DateTimeFormats, NumberFormats, OptionLocale>
: unknown
/**
* Install entry point
*
* @param app - A target Vue app instance
* @param options - An install options
*/
install(app: App, ...options: unknown[]): void
}
/**
* I18n interface for internal usage
*
* @internal
*/
export interface I18nInternal<
Messages = {},
DateTimeFormats = {},
NumberFormats = {},
OptionLocale = Locale
> {
__instances: Map<
ComponentInternalInstance,
| VueI18n<Messages, DateTimeFormats, NumberFormats, OptionLocale>
| Composer<Messages, DateTimeFormats, NumberFormats, OptionLocale>
>
__getInstance<
Instance extends
| VueI18n<Messages, DateTimeFormats, NumberFormats, OptionLocale>
| Composer<Messages, DateTimeFormats, NumberFormats, OptionLocale>
>(
component: ComponentInternalInstance
): Instance | null
__setInstance<
Instance extends
| VueI18n<Messages, DateTimeFormats, NumberFormats, OptionLocale>
| Composer<Messages, DateTimeFormats, NumberFormats, OptionLocale>
>(
component: ComponentInternalInstance,
instance: Instance
): void
__deleteInstance(component: ComponentInternalInstance): void
}
/**
* I18n Scope
*
* @VueI18nSee [ComposerAdditionalOptions#useScope](composition#usescope)
* @VueI18nSee [useI18n](composition#usei18n)
*
* @VueI18nGeneral
*/
export type I18nScope = 'local' | 'parent' | 'global'
/**
* I18n Options for `useI18n`
*
* @remarks
* `UseI18nOptions` is inherited {@link ComposerAdditionalOptions} and {@link ComposerOptions}, so you can specify these options.
*
* @VueI18nSee [useI18n](composition#usei18n)
*
* @VueI18nComposition
*/
export type UseI18nOptions<
Schema extends {
message?: unknown
datetime?: unknown
number?: unknown
} = {
message: DefaultLocaleMessageSchema
datetime: DefaultDateTimeFormatSchema
number: DefaultNumberFormatSchema
},
Locales extends
| {
messages: unknown
datetimeFormats: unknown
numberFormats: unknown
}
| string = Locale,
Options extends ComposerOptions<Schema, Locales> = ComposerOptions<
Schema,
Locales
>
> = ComposerAdditionalOptions & Options
/**
* Composer additional options for `useI18n`
*
* @remarks
* `ComposerAdditionalOptions` is extend for {@link ComposerOptions}, so you can specify these options.
*
* @VueI18nSee [useI18n](composition#usei18n)
*
* @VueI18nComposition
*/
export interface ComposerAdditionalOptions {
useScope?: I18nScope
}
/**
* Injection key for {@link useI18n}
*
* @remarks
* The global injection key for I18n instances with `useI18n`. this injection key is used in Web Components.
* Specify the i18n instance created by {@link createI18n} together with `provide` function.
*
* @VueI18nGeneral
*/
export const I18nInjectionKey: InjectionKey<I18n> | string =
/* #__PURE__*/ makeSymbol('global-vue-i18n')
export function createI18n<
Legacy extends boolean = true,
Options extends I18nOptions = I18nOptions,
Messages = Options['messages'] extends object ? Options['messages'] : {},
DateTimeFormats = Options['datetimeFormats'] extends object
? Options['datetimeFormats']
: {},
NumberFormats = Options['numberFormats'] extends object
? Options['numberFormats']
: {},
OptionLocale = Options['locale'] extends string ? Options['locale'] : Locale
>(
options: Options,
LegacyVueI18n?: any // eslint-disable-line @typescript-eslint/no-explicit-any
): I18n<Messages, DateTimeFormats, NumberFormats, OptionLocale, Legacy>
/**
* Vue I18n factory
*
* @param options - An options, see the {@link I18nOptions}
*
* @typeParam Schema - The i18n resources (messages, datetimeFormats, numberFormats) schema, default {@link LocaleMessage}
* @typeParam Locales - The locales of i18n resource schema, default `en-US`
* @typeParam Legacy - Whether legacy mode is enabled or disabled, default `true`
*
* @returns {@link I18n} instance
*
* @remarks
* If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option.
*
* If you use composition API mode, you need to specify {@link ComposerOptions}.
*
* @VueI18nSee [Getting Started](../guide/)
* @VueI18nSee [Composition API](../guide/advanced/composition)
*
* @example
* case: for Legacy API
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* // ...
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @example
* case: for composition API
* ```js
* import { createApp } from 'vue'
* import { createI18n, useI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* legacy: false, // you must specify 'legacy: false' option
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* setup() {
* // ...
* const { t } = useI18n({ ... })
* return { ... , t }
* }
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @VueI18nGeneral
*/
export function createI18n<
Schema extends object = DefaultLocaleMessageSchema,
Locales extends string | object = 'en-US',
Legacy extends boolean = true,
Options extends I18nOptions<
SchemaParams<Schema, VueMessageType>,
LocaleParams<Locales>
> = I18nOptions<SchemaParams<Schema, VueMessageType>, LocaleParams<Locales>>,
Messages = Options['messages'] extends object ? Options['messages'] : {},
DateTimeFormats = Options['datetimeFormats'] extends object
? Options['datetimeFormats']
: {},
NumberFormats = Options['numberFormats'] extends object
? Options['numberFormats']
: {},
OptionLocale = Options['locale'] extends string ? Options['locale'] : Locale
>(
options: Options,
LegacyVueI18n?: any // eslint-disable-line @typescript-eslint/no-explicit-any
): I18n<Messages, DateTimeFormats, NumberFormats, OptionLocale, Legacy>
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
export function createI18n(options: any = {}, VueI18nLegacy?: any): any {
type _I18n = I18n & I18nInternal
if (__BRIDGE__ && _legacyI18n) {
__DEV__ &&
warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORT_MULTI_I18N_INSTANCE))
return _legacyI18n
}
if (__BRIDGE__) {
_legacyVueI18n = VueI18nLegacy
}
// prettier-ignore
const __legacyMode = __LITE__
? false
: __FEATURE_LEGACY_API__ && isBoolean(options.legacy)
? options.legacy
: __FEATURE_LEGACY_API__
// prettier-ignore
const __globalInjection = /* #__PURE__*/ !__BRIDGE__
? !!options.globalInjection
: isBoolean(options.globalInjection)
? options.globalInjection
: true
const __instances = new Map<ComponentInternalInstance, VueI18n | Composer>()
const __global = createGlobal(options, __legacyMode, VueI18nLegacy)
const symbol: InjectionKey<I18n> | string = /* #__PURE__*/ makeSymbol(
__DEV__ ? 'vue-i18n' : ''
)
function __getInstance<Instance extends VueI18n | Composer>(
component: ComponentInternalInstance
): Instance | null {
return (__instances.get(component) as unknown as Instance) || null
}
function __setInstance<Instance extends VueI18n | Composer>(
component: ComponentInternalInstance,
instance: Instance
): void {
__instances.set(component, instance)
}
function __deleteInstance(component: ComponentInternalInstance): void {
__instances.delete(component)
}
if (!__BRIDGE__) {
const i18n = {
// mode
get mode(): I18nMode {
return !__LITE__ && __FEATURE_LEGACY_API__ && __legacyMode
? 'legacy'
: 'composition'
},
// install plugin
async install(app: App, ...options: unknown[]): Promise<void> {
if (
!__BRIDGE__ &&
(__DEV__ || __FEATURE_PROD_VUE_DEVTOOLS__) &&
!__NODE_JS__
) {
app.__VUE_I18N__ = i18n as unknown as _I18n
}
// setup global provider
app.__VUE_I18N_SYMBOL__ = symbol
app.provide(app.__VUE_I18N_SYMBOL__, i18n as unknown as I18n)
// global method and properties injection for Composition API
if (!__legacyMode && __globalInjection) {
injectGlobalFields(app, i18n.global as Composer)
}
// install built-in components and directive
if (!__LITE__ && __FEATURE_FULL_INSTALL__) {
applyNext(app, i18n as I18n, ...options)
}
// setup mixin for Legacy API
if (!__LITE__ && __FEATURE_LEGACY_API__ && __legacyMode) {
app.mixin(
defineMixinNext(
__global as unknown as VueI18n,
(__global as unknown as VueI18nInternal).__composer as Composer,
i18n as unknown as I18nInternal
)
)
}
// setup vue-devtools plugin
if ((__DEV__ || __FEATURE_PROD_VUE_DEVTOOLS__) && !__NODE_JS__) {
const ret = await enableDevTools(app, i18n as _I18n)
if (!ret) {
throw createI18nError(
I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN
)
}
const emitter: VueDevToolsEmitter =
createEmitter<VueDevToolsEmitterEvents>()
if (__legacyMode) {
const _vueI18n = __global as unknown as VueI18nInternal
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter)
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = __global as any
_composer[EnableEmitter] && _composer[EnableEmitter](emitter)
}
emitter.on('*', addTimelineEvent)
}
},
// global accessor
get global() {
return __global
},
// @internal
__instances,
// @internal
__getInstance,
// @internal
__setInstance,
// @internal
__deleteInstance
}
return i18n
} else {
// extend legacy VueI18n instance
const i18n = (__global as any)[LegacyInstanceSymbol] // eslint-disable-line @typescript-eslint/no-explicit-any
Object.defineProperty(i18n, 'global', {
get() {
return __global
}
})
Object.defineProperty(i18n, 'mode', {
get() {
return __legacyMode ? 'legacy' : 'composition'
}
})
Object.defineProperty(i18n, '__instances', {
get() {
return __instances
}
})
Object.defineProperty(i18n, 'install', {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: (Vue: any, ...options: unknown[]) => {
const version =
(Vue && Vue.version && Number(Vue.version.split('.')[0])) || -1
if (version !== 2) {
throw createI18nError(I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY)
}
__FEATURE_FULL_INSTALL__ && applyBridge(Vue, ...options)
if (!__legacyMode && __globalInjection) {
injectGlobalFieldsForBridge(Vue, i18n, __global as Composer)
}
Vue.mixin(defineMixinBridge(i18n, _legacyVueI18n))
}
})
const methodMap = {
__getInstance,
__setInstance,
__deleteInstance
}
Object.keys(methodMap).forEach(
key =>
Object.defineProperty(i18n, key, { value: (methodMap as any)[key] }) // eslint-disable-line @typescript-eslint/no-explicit-any
)
_legacyI18n = i18n
return i18n
}
}
export function useI18n<Options extends UseI18nOptions = UseI18nOptions>(
options?: Options
): Composer<
NonNullable<Options['messages']>,
NonNullable<Options['datetimeFormats']>,
NonNullable<Options['numberFormats']>,
NonNullable<Options['locale']>
>
/**
* Use Composition API for Vue I18n
*
* @param options - An options, see {@link UseI18nOptions}
*
* @typeParam Schema - The i18n resources (messages, datetimeFormats, numberFormats) schema, default {@link LocaleMessage}
* @typeParam Locales - The locales of i18n resource schema, default `en-US`
*
* @returns {@link Composer} instance
*
* @remarks
* This function is mainly used by `setup`.
*
* If options are specified, Composer instance is created for each component and you can be localized on the component.
*
* If options are not specified, you can be localized using the global Composer.
*
* @example
* case: Component resource base localization
* ```html
* <template>
* <form>
* <label>{{ t('language') }}</label>
* <select v-model="locale">
* <option value="en">en</option>
* <option value="ja">ja</option>
* </select>
* </form>
* <p>message: {{ t('hello') }}</p>
* </template>
*
* <script>
* import { useI18n } from 'vue-i18n'
*
* export default {
* setup() {
* const { t, locale } = useI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
* // Something to do ...
*
* return { ..., t, locale }
* }
* }
* </script>
* ```
*
* @VueI18nComposition
*/
export function useI18n<
Schema = DefaultLocaleMessageSchema,
Locales = 'en-US',
Options extends UseI18nOptions<
SchemaParams<Schema, VueMessageType>,
LocaleParams<Locales>
> = UseI18nOptions<
SchemaParams<Schema, VueMessageType>,
LocaleParams<Locales>
>
>(
options?: Options
): Composer<
NonNullable<Options['messages']>,
NonNullable<Options['datetimeFormats']>,
NonNullable<Options['numberFormats']>,
NonNullable<Options['locale']>
>
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function useI18n<
Options extends UseI18nOptions = UseI18nOptions,
Messages = NonNullable<Options['messages']>,
DateTimeFormats = NonNullable<Options['datetimeFormats']>,
NumberFormats = NonNullable<Options['numberFormats']>,
OptionLocale = NonNullable<Options['locale']>
>(options: Options = {} as Options) {
const instance = getCurrentInstance()
if (instance == null) {
throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP)
}
if (
!__BRIDGE__ &&
!instance.isCE &&
instance.appContext.app != null &&
!instance.appContext.app.__VUE_I18N_SYMBOL__
) {
throw createI18nError(I18nErrorCodes.NOT_INSLALLED)
}
if (__BRIDGE__) {
if (_legacyVueI18n == null || _legacyI18n == null) {
throw createI18nError(I18nErrorCodes.NOT_INSLALLED)
}
}
const i18n = getI18nInstance(instance)
const global = getGlobalComposer(i18n)
const componentOptions = getComponentOptions(instance)
const scope = getScope(options, componentOptions)
if (scope === 'global') {
adjustI18nResources(global, options, componentOptions)
return global as Composer<
Messages,
DateTimeFormats,
NumberFormats,
OptionLocale
>
}
if (scope === 'parent') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let composer = getComposer(i18n, instance, (options as any).__useComponent)
if (composer == null) {
if (__DEV__) {
warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE))
}
composer = global as unknown as Composer
}
return composer as Composer<
Messages,
DateTimeFormats,
NumberFormats,
OptionLocale
>
}
// scope 'local' case
if (i18n.mode === 'legacy') {
throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE)
}
const i18nInternal = i18n as unknown as I18nInternal
let composer = i18nInternal.__getInstance(instance)
if (composer == null) {
const composerOptions = assign({}, options) as ComposerOptions &
ComposerInternalOptions
if ('__i18n' in componentOptions) {
composerOptions.__i18n = componentOptions.__i18n
}
if (global) {
composerOptions.__root = global
}
composer = createComposer(composerOptions, _legacyVueI18n) as Composer
setupLifeCycle(i18nInternal, instance, composer)
i18nInternal.__setInstance(instance, composer)
}
return composer as Composer<
Messages,
DateTimeFormats,
NumberFormats,
OptionLocale
>
}
/**
* Cast to VueI18n legacy compatible type
*
* @remarks
* This API is provided only with [vue-i18n-bridge](https://vue-i18n.intlify.dev/guide/migration/ways.html#what-is-vue-i18n-bridge).
*
* The purpose of this function is to convert an {@link I18n} instance created with {@link createI18n | createI18n(legacy: true)} into a `vue-i18n@v8.x` compatible instance of `new VueI18n` in a TypeScript environment.
*
* @param i18n - An instance of {@link I18n}
* @returns A i18n instance which is casted to {@link VueI18n} type
*
* @VueI18nTip
* :new: provided by **vue-i18n-bridge only**
*
* @VueI18nGeneral
*/
export const castToVueI18n = /* #__PURE__*/ (
i18n: I18n
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): VueI18n & { install: (Vue: any, options?: any) => void } => {
if (!(__VUE_I18N_BRIDGE__ in i18n)) {
throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N)
}
return i18n as unknown as VueI18n & {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
install: (Vue: any, options?: any) => void
}
}
function createGlobal(
options: I18nOptions,
legacyMode: boolean,
VueI18nLegacy: any // eslint-disable-line @typescript-eslint/no-explicit-any
): VueI18n | Composer {
if (!__BRIDGE__) {
return !__LITE__ && __FEATURE_LEGACY_API__ && legacyMode
? createVueI18n(options, VueI18nLegacy)
: createComposer(options, VueI18nLegacy)
} else {
if (!isLegacyVueI18n(VueI18nLegacy)) {
throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N)
}
return createComposer(options, VueI18nLegacy)
}
}
function getI18nInstance(instance: ComponentInternalInstance): I18n {
if (!__BRIDGE__) {
const i18n = inject(
!instance.isCE
? instance.appContext.app.__VUE_I18N_SYMBOL__!
: I18nInjectionKey
)
/* istanbul ignore if */
if (!i18n) {
throw createI18nError(
!instance.isCE
? I18nErrorCodes.UNEXPECTED_ERROR
: I18nErrorCodes.NOT_INSLALLED_WITH_PROVIDE
)
}
return i18n
} else {
const vm = instance.proxy
/* istanbul ignore if */
if (vm == null) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
}
let i18n = (vm as any)._i18nBridgeRoot // eslint-disable-line @typescript-eslint/no-explicit-any
if (!i18n) {
i18n = _legacyI18n
}
/* istanbul ignore if */
if (!i18n) {
throw createI18nError(I18nErrorCodes.NOT_INSLALLED)
}
return i18n as I18n
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getScope(options: UseI18nOptions, componentOptions: any): I18nScope {
// prettier-ignore
return isEmptyObject(options)
? ('__i18n' in componentOptions)
? 'local'
: 'global'
: !options.useScope
? 'local'
: options.useScope
}
function getGlobalComposer(i18n: I18n): Composer {
// prettier-ignore
return !__BRIDGE__
? i18n.mode === 'composition'
? (i18n.global as unknown as Composer)
: (i18n.global as unknown as VueI18nInternal).__composer
: (i18n.global as unknown as Composer)
}
function getComposer(
i18n: I18n,
target: ComponentInternalInstance,
useComponent = false
): Composer | null {
let composer: Composer | null = null
const root = target.root
let current: ComponentInternalInstance | null = target.parent
while (current != null) {
const i18nInternal = i18n as unknown as I18nInternal
if (i18n.mode === 'composition') {
composer = i18nInternal.__getInstance(current)
} else {
if (!__LITE__ && __FEATURE_LEGACY_API__) {
const vueI18n = i18nInternal.__getInstance(current)
if (vueI18n != null) {
composer = (vueI18n as VueI18n & VueI18nInternal)
.__composer as Composer
if (
useComponent &&
composer &&
!(composer as any)[InejctWithOption] // eslint-disable-line @typescript-eslint/no-explicit-any
) {
composer = null
}
}
}
}
if (composer != null) {
break
}
if (root === current) {
break
}
current = current.parent
}
return composer
}
function setupLifeCycle(
i18n: I18nInternal,
target: ComponentInternalInstance,
composer: Composer
): void {
let emitter: VueDevToolsEmitter | null = null
if (__BRIDGE__) {
// assign legacy VueI18n instance to Vue2 instance
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const vm = target.proxy as any
if (vm == null) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _i18n = (composer as any)[LegacyInstanceSymbol]
if (_i18n === i18n) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
}
vm._i18n = _i18n
vm._i18n_bridge = true
vm._i18nWatcher = vm._i18n.watchI18nData()
if (vm._i18n._sync) {
vm._localeWatcher = vm._i18n.watchLocale()
}
let subscribing = false
onBeforeMount(() => {
vm._i18n.subscribeDataChanging(vm)
subscribing = true
}, target)
onUnmounted(() => {
if (subscribing) {
vm._i18n.unsubscribeDataChanging(vm)
subscribing = false
}
if (vm._i18nWatcher) {
vm._i18nWatcher()
vm._i18n.destroyVM()
delete vm._i18nWatcher
}
if (vm._localeWatcher) {
vm._localeWatcher()
delete vm._localeWatcher
}
delete vm._i18n_bridge
delete vm._i18n
}, target)
} else {
onMounted(() => {
// inject composer instance to DOM for intlify-devtools
if (
(__DEV__ || __FEATURE_PROD_VUE_DEVTOOLS__) &&
!__NODE_JS__ &&
target.vnode.el
) {
target.vnode.el.__VUE_I18N__ = composer
emitter = createEmitter<VueDevToolsEmitterEvents>()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer as any
_composer[EnableEmitter] && _composer[EnableEmitter](emitter)
emitter.on('*', addTimelineEvent)
}
}, target)
onUnmounted(() => {
// remove composer instance from DOM for intlify-devtools
if (
(__DEV__ || __FEATURE_PROD_VUE_DEVTOOLS__) &&
!__NODE_JS__ &&
target.vnode.el &&
target.vnode.el.__VUE_I18N__
) {
emitter && emitter.off('*', addTimelineEvent)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer as any
_composer[DisableEmitter] && _composer[DisableEmitter]()
delete target.vnode.el.__VUE_I18N__
}
i18n.__deleteInstance(target)
}, target)
}
}
/**
* Exported global composer instance
*
* @remarks
* This interface is the [global composer](general#global) that is provided interface that is injected into each component with `app.config.globalProperties`.
*
* @VueI18nGeneral
*/
export interface ExportedGlobalComposer {
/**
* Locale
*
* @remarks
* This property is proxy-like property for `Composer#locale`. About details, see the [Composer#locale](composition#locale)
*/
locale: Locale
/**
* Fallback locale
*
* @remarks
* This property is proxy-like property for `Composer#fallbackLocale`. About details, see the [Composer#fallbackLocale](composition#fallbacklocale)
*/
fallbackLocale: FallbackLocale
/**
* Available locales
*
* @remarks
* This property is proxy-like property for `Composer#availableLocales`. About details, see the [Composer#availableLocales](composition#availablelocales)
*/
readonly availableLocales: Locale[]
}
const globalExportProps = [
'locale',
'fallbackLocale',
'availableLocales'
] as const
const globalExportMethods = !__LITE__ ? ['t', 'rt', 'd', 'n', 'tm'] : ['t']
function injectGlobalFields(app: App, composer: Composer): void {
const i18n = Object.create(null)
globalExportProps.forEach(prop => {
const desc = Object.getOwnPropertyDescriptor(composer, prop)
if (!desc) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
}
const wrap = isRef(desc.value) // check computed props
? {
get() {
return desc.value.value
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
set(val: any) {
desc.value.value = val
}
}
: {
get() {
return desc.get && desc.get()
}
}
Object.defineProperty(i18n, prop, wrap)
})
app.config.globalProperties.$i18n = i18n
globalExportMethods.forEach(method => {
const desc = Object.getOwnPropertyDescriptor(composer, method)
if (!desc || !desc.value) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
}
Object.defineProperty(app.config.globalProperties, `$${method}`, desc)
})
}
function injectGlobalFieldsForBridge(
Vue: any, // eslint-disable-line @typescript-eslint/no-explicit-any
i18n: any, // eslint-disable-line @typescript-eslint/no-explicit-any
composer: Composer
): void {
// The composition mode in vue-i18n-bridge is `$18n` is the VueI18n instance.
// so we need to tell composer to change the locale.
// If we don't do, things like `$t` that are injected will not be reacted.
i18n.watchLocale(composer)
// define fowardcompatible vue-i18n-next inject fields with `globalInjection`
Vue.prototype.$t = function (...args: unknown[]) {
return Reflect.apply(composer.t, composer, [...args])
}
Vue.prototype.$d = function (...args: unknown[]) {
return Reflect.apply(composer.d, composer, [...args])
}
Vue.prototype.$n = function (...args: unknown[]) {
return Reflect.apply(composer.n, composer, [...args])
}
} | the_stack |
import {TypedActions} from '../../actions/typed-actions-gen'
import {TypedState as _TypedState} from '../../constants/reducer'
export type Action = TypedActions
export type AnyAction = TypedActions
export type TypedState = _TypedState
/**
* An *action* is a plain object that represents an intention to change the
* state. Actions are the only way to get data into the store. Any data,
* whether from UI events, network callbacks, or other sources such as
* WebSockets needs to eventually be dispatched as actions.
*
* Actions must have a `type` field that indicates the type of action being
* performed. Types can be defined as constants and imported from another
* module. It's better to use strings for `type` than Symbols because strings
* are serializable.
*
* Other than `type`, the structure of an action object is really up to you.
* If you're interested, check out Flux Standard Action for recommendations on
* how actions should be constructed.
*
* @template T the type of the action's `type` tag.
*/
// export interface Action<T = any> {
// type: T
// }
/**
* An Action type which accepts any other properties.
* This is mainly for the use of the `Reducer` type.
* This is not part of `Action` itself to prevent users who are extending `Action.
*/
// export interface AnyAction extends Action {
// // Allows any extra properties to be defined in an action.
// [extraProps: string]: any
// }
/* reducers */
/**
* A *reducer* (also called a *reducing function*) is a function that accepts
* an accumulation and a value and returns a new accumulation. They are used
* to reduce a collection of values down to a single value
*
* Reducers are not unique to Redux—they are a fundamental concept in
* functional programming. Even most non-functional languages, like
* JavaScript, have a built-in API for reducing. In JavaScript, it's
* `Array.prototype.reduce()`.
*
* In Redux, the accumulated value is the state object, and the values being
* accumulated are actions. Reducers calculate a new state given the previous
* state and an action. They must be *pure functions*—functions that return
* the exact same output for given inputs. They should also be free of
* side-effects. This is what enables exciting features like hot reloading and
* time travel.
*
* Reducers are the most important concept in Redux.
*
* *Do not put API calls into reducers.*
*
* @template S The type of state consumed and produced by this reducer.
* @template A The type of actions the reducer can potentially respond to.
*/
export type Reducer<S = any, A extends Action = AnyAction> = (state: S | undefined, action: A) => S
/**
* Object whose values correspond to different reducer functions.
*
* @template A The type of actions the reducers can potentially respond to.
*/
export type ReducersMapObject<S = any, A extends Action = Action> = {[K in keyof S]: Reducer<S[K], A>}
/**
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* @template S Combined state object type.
*
* @param reducers An object whose values correspond to different reducer
* functions that need to be combined into one. One handy way to obtain it
* is to use ES6 `import * as reducers` syntax. The reducers may never
* return undefined for any action. Instead, they should return their
* initial state if the state passed to them was undefined, and the current
* state for any unrecognized action.
*
* @returns A reducer function that invokes every reducer inside the passed
* object, and builds a state object with the same shape.
*/
export function combineReducers<S>(reducers: ReducersMapObject<S, any>): Reducer<S>
export function combineReducers<S, A extends Action = AnyAction>(
reducers: ReducersMapObject<S, A>
): Reducer<S, A>
/* store */
/**
* A *dispatching function* (or simply *dispatch function*) is a function that
* accepts an action or an async action; it then may or may not dispatch one
* or more actions to the store.
*
* We must distinguish between dispatching functions in general and the base
* `dispatch` function provided by the store instance without any middleware.
*
* The base dispatch function *always* synchronously sends an action to the
* store's reducer, along with the previous state returned by the store, to
* calculate a new state. It expects actions to be plain objects ready to be
* consumed by the reducer.
*
* Middleware wraps the base dispatch function. It allows the dispatch
* function to handle async actions in addition to actions. Middleware may
* transform, delay, ignore, or otherwise interpret actions or async actions
* before passing them to the next middleware.
*
* @template A The type of things (actions or otherwise) which may be
* dispatched.
*/
export interface Dispatch<A extends Action = AnyAction> {
<T extends A>(action: T): void
// KB assume void // T
}
/**
* Function to remove listener added by `Store.subscribe()`.
*/
export interface Unsubscribe {
(): void
}
/**
* A store is an object that holds the application's state tree.
* There should only be a single store in a Redux app, as the composition
* happens on the reducer level.
*
* @template S The type of state held by this store.
* @template A the type of actions which may be dispatched by this store.
*/
export interface Store<S = TypedState, A extends Action = AnyAction> {
/**
* Dispatches an action. It is the only way to trigger a state change.
*
* The `reducer` function, used to create the store, will be called with the
* current state tree and the given `action`. Its return value will be
* considered the **next** state of the tree, and the change listeners will
* be notified.
*
* The base implementation only supports plain object actions. If you want
* to dispatch a Promise, an Observable, a thunk, or something else, you
* need to wrap your store creating function into the corresponding
* middleware. For example, see the documentation for the `redux-thunk`
* package. Even the middleware will eventually dispatch plain object
* actions using this method.
*
* @param action A plain object representing “what changed”. It is a good
* idea to keep actions serializable so you can record and replay user
* sessions, or use the time travelling `redux-devtools`. An action must
* have a `type` property which may not be `undefined`. It is a good idea
* to use string constants for action types.
*
* @returns For convenience, the same action object you dispatched.
*
* Note that, if you use a custom middleware, it may wrap `dispatch()` to
* return something else (for example, a Promise you can await).
*/
dispatch: Dispatch<A>
/**
* Reads the state tree managed by the store.
*
* @returns The current state tree of your application.
*/
getState(): S
/**
* Adds a change listener. It will be called any time an action is
* dispatched, and some part of the state tree may potentially have changed.
* You may then call `getState()` to read the current state tree inside the
* callback.
*
* You may call `dispatch()` from a change listener, with the following
* caveats:
*
* 1. The subscriptions are snapshotted just before every `dispatch()` call.
* If you subscribe or unsubscribe while the listeners are being invoked,
* this will not have any effect on the `dispatch()` that is currently in
* progress. However, the next `dispatch()` call, whether nested or not,
* will use a more recent snapshot of the subscription list.
*
* 2. The listener should not expect to see all states changes, as the state
* might have been updated multiple times during a nested `dispatch()` before
* the listener is called. It is, however, guaranteed that all subscribers
* registered before the `dispatch()` started will be called with the latest
* state by the time it exits.
*
* @param listener A callback to be invoked on every dispatch.
* @returns A function to remove this change listener.
*/
subscribe(listener: () => void): Unsubscribe
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for Redux.
*
* @param nextReducer The reducer for the store to use instead.
*/
replaceReducer(nextReducer: Reducer<S, A>): void
}
export type DeepPartial<T> = {[K in keyof T]?: DeepPartial<T[K]>}
/**
* A store creator is a function that creates a Redux store. Like with
* dispatching function, we must distinguish the base store creator,
* `createStore(reducer, preloadedState)` exported from the Redux package, from
* store creators that are returned from the store enhancers.
*
* @template S The type of state to be held by the store.
* @template A The type of actions which may be dispatched.
* @template Ext Store extension that is mixed in to the Store type.
* @template StateExt State extension that is mixed into the state type.
*/
export interface StoreCreator {
<S, A extends Action, Ext, StateExt>(
reducer: Reducer<S, A>,
enhancer?: StoreEnhancer<Ext, StateExt>
): Store<S & StateExt, A> & Ext
<S, A extends Action, Ext, StateExt>(
reducer: Reducer<S, A>,
preloadedState?: DeepPartial<S>,
enhancer?: StoreEnhancer<Ext>
): Store<S & StateExt, A> & Ext
}
/**
* Creates a Redux store that holds the state tree.
* The only way to change the data in the store is to call `dispatch()` on it.
*
* There should only be a single store in your app. To specify how different
* parts of the state tree respond to actions, you may combine several
* reducers
* into a single reducer function by using `combineReducers`.
*
* @template S State object type.
*
* @param reducer A function that returns the next state tree, given the
* current state tree and the action to handle.
*
* @param [preloadedState] The initial state. You may optionally specify it to
* hydrate the state from the server in universal apps, or to restore a
* previously serialized user session. If you use `combineReducers` to
* produce the root reducer function, this must be an object with the same
* shape as `combineReducers` keys.
*
* @param [enhancer] The store enhancer. You may optionally specify it to
* enhance the store with third-party capabilities such as middleware, time
* travel, persistence, etc. The only store enhancer that ships with Redux
* is `applyMiddleware()`.
*
* @returns A Redux store that lets you read the state, dispatch actions and
* subscribe to changes.
*/
export const createStore: StoreCreator
/**
* A store enhancer is a higher-order function that composes a store creator
* to return a new, enhanced store creator. This is similar to middleware in
* that it allows you to alter the store interface in a composable way.
*
* Store enhancers are much the same concept as higher-order components in
* React, which are also occasionally called “component enhancers”.
*
* Because a store is not an instance, but rather a plain-object collection of
* functions, copies can be easily created and modified without mutating the
* original store. There is an example in `compose` documentation
* demonstrating that.
*
* Most likely you'll never write a store enhancer, but you may use the one
* provided by the developer tools. It is what makes time travel possible
* without the app being aware it is happening. Amusingly, the Redux
* middleware implementation is itself a store enhancer.
*
* @template Ext Store extension that is mixed into the Store type.
* @template StateExt State extension that is mixed into the state type.
*/
export type StoreEnhancer<Ext = {}, StateExt = {}> = (
next: StoreEnhancerStoreCreator
) => StoreEnhancerStoreCreator<Ext, StateExt>
export type StoreEnhancerStoreCreator<Ext = {}, StateExt = {}> = <S = any, A extends Action = AnyAction>(
reducer: Reducer<S, A>,
preloadedState?: DeepPartial<S>
) => Store<S & StateExt, A> & Ext
/* middleware */
export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = TypedState> {
dispatch: D
getState(): S
}
/**
* A middleware is a higher-order function that composes a dispatch function
* to return a new dispatch function. It often turns async actions into
* actions.
*
* Middleware is composable using function composition. It is useful for
* logging actions, performing side effects like routing, or turning an
* asynchronous API call into a series of synchronous actions.
*
* @template DispatchExt Extra Dispatch signature added by this middleware.
* @template S The type of the state supported by this middleware.
* @template D The type of Dispatch of the store where this middleware is
* installed.
*/
export interface Middleware<DispatchExt = {}, S = TypedState, D extends Dispatch = Dispatch> {
(api: MiddlewareAPI<D, S>): (next: Dispatch<AnyAction>) => (action: any) => any
}
/**
* Creates a store enhancer that applies middleware to the dispatch method
* of the Redux store. This is handy for a variety of tasks, such as
* expressing asynchronous actions in a concise manner, or logging every
* action payload.
*
* See `redux-thunk` package as an example of the Redux middleware.
*
* Because middleware is potentially asynchronous, this should be the first
* store enhancer in the composition chain.
*
* Note that each middleware will be given the `dispatch` and `getState`
* functions as named arguments.
*
* @param middlewares The middleware chain to be applied.
* @returns A store enhancer applying the middleware.
*
* @template Ext Dispatch signature added by a middleware.
* @template S The type of the state supported by a middleware.
*/
export function applyMiddleware(): StoreEnhancer
export function applyMiddleware<Ext1, S>(
middleware1: Middleware<Ext1, S, any>
): StoreEnhancer<{dispatch: Ext1}>
export function applyMiddleware<Ext1, Ext2, S>(
middleware1: Middleware<Ext1, S, any>,
middleware2: Middleware<Ext2, S, any>
): StoreEnhancer<{dispatch: Ext1 & Ext2}>
export function applyMiddleware<Ext1, Ext2, Ext3, S>(
middleware1: Middleware<Ext1, S, any>,
middleware2: Middleware<Ext2, S, any>,
middleware3: Middleware<Ext3, S, any>
): StoreEnhancer<{dispatch: Ext1 & Ext2 & Ext3}>
export function applyMiddleware<Ext1, Ext2, Ext3, Ext4, S>(
middleware1: Middleware<Ext1, S, any>,
middleware2: Middleware<Ext2, S, any>,
middleware3: Middleware<Ext3, S, any>,
middleware4: Middleware<Ext4, S, any>
): StoreEnhancer<{dispatch: Ext1 & Ext2 & Ext3 & Ext4}>
export function applyMiddleware<Ext1, Ext2, Ext3, Ext4, Ext5, S>(
middleware1: Middleware<Ext1, S, any>,
middleware2: Middleware<Ext2, S, any>,
middleware3: Middleware<Ext3, S, any>,
middleware4: Middleware<Ext4, S, any>,
middleware5: Middleware<Ext5, S, any>
): StoreEnhancer<{dispatch: Ext1 & Ext2 & Ext3 & Ext4 & Ext5}>
export function applyMiddleware<Ext, S = any>(
...middlewares: Middleware<any, S, any>[]
): StoreEnhancer<{dispatch: Ext}>
/* action creators */
/**
* An *action creator* is, quite simply, a function that creates an action. Do
* not confuse the two terms—again, an action is a payload of information, and
* an action creator is a factory that creates an action.
*
* Calling an action creator only produces an action, but does not dispatch
* it. You need to call the store's `dispatch` function to actually cause the
* mutation. Sometimes we say *bound action creators* to mean functions that
* call an action creator and immediately dispatch its result to a specific
* store instance.
*
* If an action creator needs to read the current state, perform an API call,
* or cause a side effect, like a routing transition, it should return an
* async action instead of an action.
*
* @template A Returned action type.
*/
export interface ActionCreator<A> {
(...args: any[]): A
}
/**
* Object whose values are action creator functions.
*/
export interface ActionCreatorsMapObject<A = any> {
[key: string]: ActionCreator<A>
}
/**
* Turns an object whose values are action creators, into an object with the
* same keys, but with every function wrapped into a `dispatch` call so they
* may be invoked directly. This is just a convenience method, as you can call
* `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
*
* For convenience, you can also pass a single function as the first argument,
* and get a function in return.
*
* @param actionCreator An object whose values are action creator functions.
* One handy way to obtain it is to use ES6 `import * as` syntax. You may
* also pass a single function.
*
* @param dispatch The `dispatch` function available on your Redux store.
*
* @returns The object mimicking the original object, but with every action
* creator wrapped into the `dispatch` call. If you passed a function as
* `actionCreator`, the return value will also be a single function.
*/
export function bindActionCreators<A, C extends ActionCreator<A>>(actionCreator: C, dispatch: Dispatch): C
export function bindActionCreators<A extends ActionCreator<any>, B extends ActionCreator<any>>(
actionCreator: A,
dispatch: Dispatch
): B
export function bindActionCreators<A, M extends ActionCreatorsMapObject<A>>(
actionCreators: M,
dispatch: Dispatch
): M
export function bindActionCreators<
M extends ActionCreatorsMapObject<any>,
N extends ActionCreatorsMapObject<any>
>(actionCreators: M, dispatch: Dispatch): N
/* compose */
type Func0<R> = () => R
type Func1<T1, R> = (a1: T1) => R
type Func2<T1, T2, R> = (a1: T1, a2: T2) => R
type Func3<T1, T2, T3, R> = (a1: T1, a2: T2, a3: T3, ...args: any[]) => R
/**
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for the
* resulting composite function.
*
* @param funcs The functions to compose.
* @returns R function obtained by composing the argument functions from right
* to left. For example, `compose(f, g, h)` is identical to doing
* `(...args) => f(g(h(...args)))`.
*/
export function compose(): <R>(a: R) => R
export function compose<F extends Function>(f: F): F
/* two functions */
export function compose<A, R>(f1: (b: A) => R, f2: Func0<A>): Func0<R>
export function compose<A, T1, R>(f1: (b: A) => R, f2: Func1<T1, A>): Func1<T1, R>
export function compose<A, T1, T2, R>(f1: (b: A) => R, f2: Func2<T1, T2, A>): Func2<T1, T2, R>
export function compose<A, T1, T2, T3, R>(f1: (b: A) => R, f2: Func3<T1, T2, T3, A>): Func3<T1, T2, T3, R>
/* three functions */
export function compose<A, B, R>(f1: (b: B) => R, f2: (a: A) => B, f3: Func0<A>): Func0<R>
export function compose<A, B, T1, R>(f1: (b: B) => R, f2: (a: A) => B, f3: Func1<T1, A>): Func1<T1, R>
export function compose<A, B, T1, T2, R>(
f1: (b: B) => R,
f2: (a: A) => B,
f3: Func2<T1, T2, A>
): Func2<T1, T2, R>
export function compose<A, B, T1, T2, T3, R>(
f1: (b: B) => R,
f2: (a: A) => B,
f3: Func3<T1, T2, T3, A>
): Func3<T1, T2, T3, R>
/* four functions */
export function compose<A, B, C, R>(f1: (b: C) => R, f2: (a: B) => C, f3: (a: A) => B, f4: Func0<A>): Func0<R>
export function compose<A, B, C, T1, R>(
f1: (b: C) => R,
f2: (a: B) => C,
f3: (a: A) => B,
f4: Func1<T1, A>
): Func1<T1, R>
export function compose<A, B, C, T1, T2, R>(
f1: (b: C) => R,
f2: (a: B) => C,
f3: (a: A) => B,
f4: Func2<T1, T2, A>
): Func2<T1, T2, R>
export function compose<A, B, C, T1, T2, T3, R>(
f1: (b: C) => R,
f2: (a: B) => C,
f3: (a: A) => B,
f4: Func3<T1, T2, T3, A>
): Func3<T1, T2, T3, R>
/* rest */
export function compose<R>(f1: (b: any) => R, ...funcs: Function[]): (...args: any[]) => R
export function compose<R>(...funcs: Function[]): (...args: any[]) => R | the_stack |
import { uniqueId } from "../util/uniqueId";
import { loge } from "../util/log";
import "reflect-metadata"
/**
* ``` TypeScript
* // load script in global scope
* Reflect.apply(
* function(doric,context,Entry,require){
* //Script content
* REG()
* },doric.jsObtainContext(id),[
* undefined,
* doric.jsObtainContext(id),
* doric.jsObtainEntry(id),
* doric.__require__,
* ])
* // Direct load class
* Reflect.apply(
* function(doric,context,Entry,require){
* //Script content
* Entry('lastContextId','className')
* },doric.jsObtainContext(id),[
* undefined,
* doric.jsObtainContext(id),
* doric.jsObtainEntry(id),
* doric.__require__,
* ])
* // load module in global scope
* Reflect.apply(doric.jsRegisterModule,this,[
* moduleName,
* Reflect.apply(function(__module){
* (function(module,exports,require){
* //module content
* })(__module,__module.exports,doric.__require__);
* return __module.exports
* },this,[{exports:{}}])
* ])
*
* ```
*/
declare function nativeRequire(moduleName: string): boolean
declare function nativeBridge(contextId: string, namespace: string, method: string, callbackId?: string, args?: any): boolean
declare function nativeSetTimer(timerId: number, interval: number, repeat: boolean): void
declare function nativeClearTimer(timerId: number): void
function hookBeforeNativeCall(context?: Context) {
if (context) {
setContext(context)
context.hookBeforeNativeCall()
}
}
function getContext(): Context | undefined {
return Reflect.getMetadata('__doric_context__', global)
}
function setContext(context?: Context) {
Reflect.defineMetadata('__doric_context__', context, global)
}
export function jsCallResolve(contextId: string, callbackId: string, args?: any) {
const context = gContexts.get(contextId)
if (context === undefined) {
loge(`Cannot find context for context id:${contextId}`)
return
}
const callback = context.callbacks.get(callbackId)
if (callback === undefined) {
loge(`Cannot find call for context id:${contextId},callback id:${callbackId}`)
return
}
const argumentsList: any = []
for (let i = 2; i < arguments.length; i++) {
argumentsList.push(arguments[i])
}
hookBeforeNativeCall(context)
Reflect.apply(callback.resolve, context, argumentsList)
}
export function jsCallReject(contextId: string, callbackId: string, args?: any) {
const context = gContexts.get(contextId)
if (context === undefined) {
loge(`Cannot find context for context id:${contextId}`)
return
}
const callback = context.callbacks.get(callbackId)
if (callback === undefined) {
loge(`Cannot find call for context id:${contextId},callback id:${callbackId}`)
return
}
const argumentsList: any = []
for (let i = 2; i < arguments.length; i++) {
argumentsList.push(arguments[i])
}
hookBeforeNativeCall(context)
Reflect.apply(callback.reject, context.entity, argumentsList)
}
export class Context {
entity: any
id: string
callbacks: Map<string, { resolve: Function, reject: Function }> = new Map
classes: Map<string, ClassType<object>> = new Map
hookBeforeNativeCall() {
if (this.entity && Reflect.has(this.entity, 'hookBeforeNativeCall')) {
Reflect.apply(Reflect.get(this.entity, 'hookBeforeNativeCall'), this.entity, [])
}
}
hookAfterNativeCall() {
if (this.entity && Reflect.has(this.entity, 'hookAfterNativeCall')) {
Reflect.apply(Reflect.get(this.entity, 'hookAfterNativeCall'), this.entity, [])
}
}
constructor(id: string) {
this.id = id
return new Proxy(this, {
get: (target, p: any) => {
if (Reflect.has(target, p)) {
return Reflect.get(target, p)
} else {
const namespace = p
return new Proxy({}, {
get: (target, p: any) => {
if (Reflect.has(target, p)) {
return Reflect.get(target, p)
} else {
const context = this
return function () {
const args = []
args.push(namespace)
args.push(p)
for (let arg of arguments) {
args.push(arg)
}
return Reflect.apply(context.callNative, context, args)
}
}
}
})
}
}
})
}
callNative(namespace: string, method: string, args?: any): Promise<any> {
const callbackId = uniqueId('callback')
return new Promise((resolve, reject) => {
this.callbacks.set(callbackId, {
resolve,
reject,
})
nativeBridge(this.id, namespace, method, callbackId, args)
})
}
register(instance: Object) {
this.entity = instance
}
function2Id(func: Function) {
const functionId = uniqueId('function')
this.callbacks.set(functionId, {
resolve: func,
reject: () => { loge("This should not be called") }
})
return functionId
}
removeFuncById(funcId: string) {
this.callbacks.delete(funcId)
}
}
const gContexts: Map<string, Context> = new Map
const gModules: Map<string, any> = new Map
export function allContexts() {
return gContexts.values()
}
export function jsObtainContext(id: string) {
if (gContexts.has(id)) {
const context = gContexts.get(id)
setContext(context)
return context
} else {
const context: Context = new Context(id)
gContexts.set(id, context)
setContext(context)
return context
}
}
export function jsReleaseContext(id: string) {
const context = gContexts.get(id)
const args = arguments
if (context) {
timerInfos.forEach((v, k) => {
if (v.context === context) {
if (global.nativeClearTimer === undefined) {
return Reflect.apply(_clearTimeout, undefined, args)
}
timerInfos.delete(k)
nativeClearTimer(k)
}
})
}
gContexts.delete(id)
}
export function __require__(name: string): any {
if (gModules.has(name)) {
return gModules.get(name)
} else {
if (nativeRequire(name)) {
return gModules.get(name)
} else {
return undefined
}
}
}
export function jsRegisterModule(name: string, moduleObject: any) {
gModules.set(name, moduleObject)
}
export function jsCallEntityMethod(contextId: string, methodName: string, args?: any) {
const context = gContexts.get(contextId)
if (context === undefined) {
loge(`Cannot find context for context id:${contextId}`)
return
}
if (context.entity === undefined) {
loge(`Cannot find holder for context id:${contextId}`)
return
}
if (Reflect.has(context.entity, methodName)) {
const argumentsList: any = []
for (let i = 2; i < arguments.length; i++) {
argumentsList.push(arguments[i])
}
hookBeforeNativeCall(context)
const ret = Reflect.apply(Reflect.get(context.entity, methodName), context.entity, argumentsList)
return ret
} else {
loge(`Cannot find method for context id:${contextId},method name is:${methodName}`)
}
}
export function pureCallEntityMethod(contextId: string, methodName: string, args?: any) {
const context = gContexts.get(contextId)
if (context === undefined) {
loge(`Cannot find context for context id:${contextId}`)
return
}
if (context.entity === undefined) {
loge(`Cannot find holder for context id:${contextId}`)
return
}
if (Reflect.has(context.entity, methodName)) {
const argumentsList: any = []
for (let i = 2; i < arguments.length; i++) {
argumentsList.push(arguments[i])
}
return Reflect.apply(Reflect.get(context.entity, methodName), context.entity, argumentsList)
} else {
loge(`Cannot find method for context id:${contextId},method name is:${methodName}`)
}
}
type ClassType<T> = new (...args: any) => T
export function jsObtainEntry(contextId: string) {
const context = jsObtainContext(contextId)
const exportFunc = (constructor: ClassType<object>) => {
context?.classes.set(constructor.name, constructor)
const ret = new constructor
Reflect.set(ret, 'context', context)
context?.register(ret)
return constructor
}
return function () {
if (arguments.length === 1) {
const args = arguments[0]
if (args instanceof Array) {
args.forEach(clz => {
context?.classes.set(clz.name, clz)
})
return exportFunc
} else {
return exportFunc(args)
}
} else if (arguments.length === 2) {
const srcContextId = arguments[0] as string
const className = arguments[1] as string
const srcContext = gContexts.get(srcContextId)
if (srcContext) {
srcContext.classes.forEach((v, k) => {
context?.classes.set(k, v)
})
const clz = srcContext.classes.get(className)
if (clz) {
return exportFunc(clz)
} else {
throw new Error(`Cannot find class:${className} in context:${srcContextId}`)
}
} else {
throw new Error(`Cannot find context for ${srcContextId}`)
}
} else {
throw new Error(`Entry arguments error:${arguments}`)
}
}
}
const global = Function('return this')()
let __timerId__ = 1
const timerInfos: Map<number, { callback: () => void, context?: Context }> = new Map
const _setTimeout = global.setTimeout
const _setInterval = global.setInterval
const _clearTimeout = global.clearTimeout
const _clearInterval = global.clearInterval
const doricSetTimeout = function (handler: Function, timeout?: number | undefined, ...args: any[]) {
if (global.nativeSetTimer === undefined) {
return Reflect.apply(_setTimeout, undefined, arguments)
}
const id = __timerId__++
timerInfos.set(id, {
callback: () => {
Reflect.apply(handler, undefined, args)
timerInfos.delete(id)
},
context: getContext(),
})
nativeSetTimer(id, timeout || 0, false)
return id
}
const doricSetInterval = function (handler: Function, timeout?: number | undefined, ...args: any[]) {
if (global.nativeSetTimer === undefined) {
return Reflect.apply(_setInterval, undefined, arguments)
}
const id = __timerId__++
timerInfos.set(id, {
callback: () => {
Reflect.apply(handler, undefined, args)
},
context: getContext(),
})
nativeSetTimer(id, timeout || 0, true)
return id
}
const doricClearTimeout = function (timerId: number) {
if (global.nativeClearTimer === undefined) {
return Reflect.apply(_clearTimeout, undefined, arguments)
}
timerInfos.delete(timerId)
nativeClearTimer(timerId)
}
const doricClearInterval = function (timerId: number) {
if (global.nativeClearTimer === undefined) {
return Reflect.apply(_clearInterval, undefined, arguments)
}
timerInfos.delete(timerId)
nativeClearTimer(timerId)
}
if (!global.setTimeout) {
global.setTimeout = doricSetTimeout
} else {
global.doricSetTimeout = doricSetTimeout
}
if (!global.setInterval) {
global.setInterval = doricSetInterval
} else {
global.doricSetInterval = doricSetInterval
}
if (!global.clearTimeout) {
global.clearTimeout = doricClearTimeout
} else {
global.doricClearTimeout = doricClearTimeout
}
if (!global.clearInterval) {
global.clearInterval = doricClearInterval
} else {
global.doricClearInterval = doricClearInterval
}
export function jsCallbackTimer(timerId: number) {
const timerInfo = timerInfos.get(timerId)
if (timerInfo === undefined) {
return
}
if (timerInfo.callback instanceof Function) {
setContext(timerInfo.context)
hookBeforeNativeCall(timerInfo.context)
Reflect.apply(timerInfo.callback, timerInfo.context, [])
}
}
export function jsHookAfterNativeCall() {
const context = getContext()
context?.hookAfterNativeCall()
} | the_stack |
* This file was automatically generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
* In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
**/
gapi.load('client', () => {
/** now we can use gapi.client */
gapi.client.load('content', 'v2', () => {
/** now we can use gapi.client.content */
/** don't forget to authenticate your client before sending any request to resources: */
/** declare client_id registered in Google Developers Console */
const client_id = '<<PUT YOUR CLIENT ID HERE>>';
const scope = [
/** Manage your product listings and accounts for Google Shopping */
'https://www.googleapis.com/auth/content',
];
const immediate = true;
gapi.auth.authorize({ client_id, scope, immediate }, authResult => {
if (authResult && !authResult.error) {
/** handle succesfull authorization */
run();
} else {
/** handle authorization error */
}
});
run();
});
async function run() {
/** Returns information about the authenticated user. */
await gapi.client.accounts.authinfo({
});
/**
* Claims the website of a Merchant Center sub-account. This method can only be called for accounts to which the managing account has access: either the
* managing account itself for any Merchant Center account, or any sub-account when the managing account is a multi-client account.
*/
await gapi.client.accounts.claimwebsite({
accountId: "accountId",
merchantId: "merchantId",
overwrite: true,
});
/** Retrieves, inserts, updates, and deletes multiple Merchant Center (sub-)accounts in a single request. */
await gapi.client.accounts.custombatch({
dryRun: true,
});
/** Deletes a Merchant Center sub-account. This method can only be called for multi-client accounts. */
await gapi.client.accounts.delete({
accountId: "accountId",
dryRun: true,
force: true,
merchantId: "merchantId",
});
/**
* Retrieves a Merchant Center account. This method can only be called for accounts to which the managing account has access: either the managing account
* itself for any Merchant Center account, or any sub-account when the managing account is a multi-client account.
*/
await gapi.client.accounts.get({
accountId: "accountId",
merchantId: "merchantId",
});
/** Creates a Merchant Center sub-account. This method can only be called for multi-client accounts. */
await gapi.client.accounts.insert({
dryRun: true,
merchantId: "merchantId",
});
/** Lists the sub-accounts in your Merchant Center account. This method can only be called for multi-client accounts. */
await gapi.client.accounts.list({
maxResults: 1,
merchantId: "merchantId",
pageToken: "pageToken",
});
/**
* Updates a Merchant Center account. This method can only be called for accounts to which the managing account has access: either the managing account
* itself for any Merchant Center account, or any sub-account when the managing account is a multi-client account. This method supports patch semantics.
*/
await gapi.client.accounts.patch({
accountId: "accountId",
dryRun: true,
merchantId: "merchantId",
});
/**
* Updates a Merchant Center account. This method can only be called for accounts to which the managing account has access: either the managing account
* itself for any Merchant Center account, or any sub-account when the managing account is a multi-client account.
*/
await gapi.client.accounts.update({
accountId: "accountId",
dryRun: true,
merchantId: "merchantId",
});
await gapi.client.accountstatuses.custombatch({
});
/**
* Retrieves the status of a Merchant Center account. This method can only be called for accounts to which the managing account has access: either the
* managing account itself for any Merchant Center account, or any sub-account when the managing account is a multi-client account.
*/
await gapi.client.accountstatuses.get({
accountId: "accountId",
merchantId: "merchantId",
});
/** Lists the statuses of the sub-accounts in your Merchant Center account. This method can only be called for multi-client accounts. */
await gapi.client.accountstatuses.list({
maxResults: 1,
merchantId: "merchantId",
pageToken: "pageToken",
});
/** Retrieves and updates tax settings of multiple accounts in a single request. */
await gapi.client.accounttax.custombatch({
dryRun: true,
});
/**
* Retrieves the tax settings of the account. This method can only be called for accounts to which the managing account has access: either the managing
* account itself for any Merchant Center account, or any sub-account when the managing account is a multi-client account.
*/
await gapi.client.accounttax.get({
accountId: "accountId",
merchantId: "merchantId",
});
/** Lists the tax settings of the sub-accounts in your Merchant Center account. This method can only be called for multi-client accounts. */
await gapi.client.accounttax.list({
maxResults: 1,
merchantId: "merchantId",
pageToken: "pageToken",
});
/**
* Updates the tax settings of the account. This method can only be called for accounts to which the managing account has access: either the managing
* account itself for any Merchant Center account, or any sub-account when the managing account is a multi-client account. This method supports patch
* semantics.
*/
await gapi.client.accounttax.patch({
accountId: "accountId",
dryRun: true,
merchantId: "merchantId",
});
/**
* Updates the tax settings of the account. This method can only be called for accounts to which the managing account has access: either the managing
* account itself for any Merchant Center account, or any sub-account when the managing account is a multi-client account.
*/
await gapi.client.accounttax.update({
accountId: "accountId",
dryRun: true,
merchantId: "merchantId",
});
await gapi.client.datafeeds.custombatch({
dryRun: true,
});
/** Deletes a datafeed configuration from your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.datafeeds.delete({
datafeedId: "datafeedId",
dryRun: true,
merchantId: "merchantId",
});
/** Retrieves a datafeed configuration from your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.datafeeds.get({
datafeedId: "datafeedId",
merchantId: "merchantId",
});
/** Registers a datafeed configuration with your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.datafeeds.insert({
dryRun: true,
merchantId: "merchantId",
});
/** Lists the datafeeds in your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.datafeeds.list({
maxResults: 1,
merchantId: "merchantId",
pageToken: "pageToken",
});
/**
* Updates a datafeed configuration of your Merchant Center account. This method can only be called for non-multi-client accounts. This method supports
* patch semantics.
*/
await gapi.client.datafeeds.patch({
datafeedId: "datafeedId",
dryRun: true,
merchantId: "merchantId",
});
/** Updates a datafeed configuration of your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.datafeeds.update({
datafeedId: "datafeedId",
dryRun: true,
merchantId: "merchantId",
});
await gapi.client.datafeedstatuses.custombatch({
});
/** Retrieves the status of a datafeed from your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.datafeedstatuses.get({
country: "country",
datafeedId: "datafeedId",
language: "language",
merchantId: "merchantId",
});
/** Lists the statuses of the datafeeds in your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.datafeedstatuses.list({
maxResults: 1,
merchantId: "merchantId",
pageToken: "pageToken",
});
/**
* Updates price and availability for multiple products or stores in a single request. This operation does not update the expiration date of the products.
* This method can only be called for non-multi-client accounts.
*/
await gapi.client.inventory.custombatch({
dryRun: true,
});
/**
* Updates price and availability of a product in your Merchant Center account. This operation does not update the expiration date of the product. This
* method can only be called for non-multi-client accounts.
*/
await gapi.client.inventory.set({
dryRun: true,
merchantId: "merchantId",
productId: "productId",
storeCode: "storeCode",
});
/** Marks an order as acknowledged. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.acknowledge({
merchantId: "merchantId",
orderId: "orderId",
});
/** Sandbox only. Moves a test order from state "inProgress" to state "pendingShipment". This method can only be called for non-multi-client accounts. */
await gapi.client.orders.advancetestorder({
merchantId: "merchantId",
orderId: "orderId",
});
/** Cancels all line items in an order, making a full refund. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.cancel({
merchantId: "merchantId",
orderId: "orderId",
});
/** Cancels a line item, making a full refund. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.cancellineitem({
merchantId: "merchantId",
orderId: "orderId",
});
/** Sandbox only. Creates a test order. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.createtestorder({
merchantId: "merchantId",
});
/** Retrieves or modifies multiple orders in a single request. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.custombatch({
});
/** Retrieves an order from your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.get({
merchantId: "merchantId",
orderId: "orderId",
});
/** Retrieves an order using merchant order id. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.getbymerchantorderid({
merchantId: "merchantId",
merchantOrderId: "merchantOrderId",
});
/**
* Sandbox only. Retrieves an order template that can be used to quickly create a new order in sandbox. This method can only be called for
* non-multi-client accounts.
*/
await gapi.client.orders.gettestordertemplate({
merchantId: "merchantId",
templateName: "templateName",
});
/** Lists the orders in your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.list({
acknowledged: true,
maxResults: 2,
merchantId: "merchantId",
orderBy: "orderBy",
pageToken: "pageToken",
placedDateEnd: "placedDateEnd",
placedDateStart: "placedDateStart",
statuses: "statuses",
});
/** Refund a portion of the order, up to the full amount paid. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.refund({
merchantId: "merchantId",
orderId: "orderId",
});
/** Returns a line item. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.returnlineitem({
merchantId: "merchantId",
orderId: "orderId",
});
/** Marks line item(s) as shipped. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.shiplineitems({
merchantId: "merchantId",
orderId: "orderId",
});
/** Updates the merchant order ID for a given order. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.updatemerchantorderid({
merchantId: "merchantId",
orderId: "orderId",
});
/** Updates a shipment's status, carrier, and/or tracking ID. This method can only be called for non-multi-client accounts. */
await gapi.client.orders.updateshipment({
merchantId: "merchantId",
orderId: "orderId",
});
/** Retrieves, inserts, and deletes multiple products in a single request. This method can only be called for non-multi-client accounts. */
await gapi.client.products.custombatch({
dryRun: true,
});
/** Deletes a product from your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.products.delete({
dryRun: true,
merchantId: "merchantId",
productId: "productId",
});
/** Retrieves a product from your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.products.get({
merchantId: "merchantId",
productId: "productId",
});
/**
* Uploads a product to your Merchant Center account. If an item with the same channel, contentLanguage, offerId, and targetCountry already exists, this
* method updates that entry. This method can only be called for non-multi-client accounts.
*/
await gapi.client.products.insert({
dryRun: true,
merchantId: "merchantId",
});
/** Lists the products in your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.products.list({
includeInvalidInsertedItems: true,
maxResults: 2,
merchantId: "merchantId",
pageToken: "pageToken",
});
/** Gets the statuses of multiple products in a single request. This method can only be called for non-multi-client accounts. */
await gapi.client.productstatuses.custombatch({
includeAttributes: true,
});
/** Gets the status of a product from your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.productstatuses.get({
includeAttributes: true,
merchantId: "merchantId",
productId: "productId",
});
/** Lists the statuses of the products in your Merchant Center account. This method can only be called for non-multi-client accounts. */
await gapi.client.productstatuses.list({
includeAttributes: true,
includeInvalidInsertedItems: true,
maxResults: 3,
merchantId: "merchantId",
pageToken: "pageToken",
});
/** Retrieves and updates the shipping settings of multiple accounts in a single request. */
await gapi.client.shippingsettings.custombatch({
dryRun: true,
});
/**
* Retrieves the shipping settings of the account. This method can only be called for accounts to which the managing account has access: either the
* managing account itself for any Merchant Center account, or any sub-account when the managing account is a multi-client account.
*/
await gapi.client.shippingsettings.get({
accountId: "accountId",
merchantId: "merchantId",
});
/** Retrieves supported carriers and carrier services for an account. */
await gapi.client.shippingsettings.getsupportedcarriers({
merchantId: "merchantId",
});
/** Lists the shipping settings of the sub-accounts in your Merchant Center account. This method can only be called for multi-client accounts. */
await gapi.client.shippingsettings.list({
maxResults: 1,
merchantId: "merchantId",
pageToken: "pageToken",
});
/**
* Updates the shipping settings of the account. This method can only be called for accounts to which the managing account has access: either the managing
* account itself for any Merchant Center account, or any sub-account when the managing account is a multi-client account. This method supports patch
* semantics.
*/
await gapi.client.shippingsettings.patch({
accountId: "accountId",
dryRun: true,
merchantId: "merchantId",
});
/**
* Updates the shipping settings of the account. This method can only be called for accounts to which the managing account has access: either the managing
* account itself for any Merchant Center account, or any sub-account when the managing account is a multi-client account.
*/
await gapi.client.shippingsettings.update({
accountId: "accountId",
dryRun: true,
merchantId: "merchantId",
});
}
}); | the_stack |
import { Component, OnInit, HostListener, ElementRef } from '@angular/core';
import { DataService } from '../data/data.service';
import { CsvService } from '../data/csv.service';
import { SettingsService } from '../settings/settings.service';
import { MatDialog } from '@angular/material/dialog';
import { SettingsComponent } from '../drill/settings/settings.component';
import * as mom from 'moment';
import { MatSnackBar } from '@angular/material/snack-bar';
import {Router} from '@angular/router';
import { UpdateComponent } from '../edit/update/update.component';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
@Component({
selector: 'ff-firestore',
templateUrl: './firestore.component.html',
styleUrls: ['./firestore.component.scss']
})
export class FirestoreComponent implements OnInit {
results = [];
events: string[] = [];
opened: boolean;
fields = [];
filter = {field: undefined, oper: 'eq', val: undefined, val2: undefined, isDate: false, dateVal: undefined};
path;
limit = '10';
working = false;
selected = [];
fieldSettings = {};
sort = {show: false, fields: []};
view = {show: false, value: 'card', types: [{name: 'card', selected: false}, {name: 'table', selected: false}]};
options = {show: false};
textFilter: string;
filters = [];
constructor(
private data: DataService,
private csv: CsvService,
private settings: SettingsService,
private dialog: MatDialog,
public snackBar: MatSnackBar,
private router: Router,
private eRef: ElementRef) { }
ngOnInit() {
this.data.type = 'firestore';
}
drill() {
this.fetch();
}
onChangeLimit(val) {
this.fetch();
}
fetch() {
this.working = true;
this.parseFilter();
const limit = parseInt(this.limit, 10);
const sortField = this.sort.fields.find(f => f.selected);
this.data.fieldSettings = this.settings.getFieldSettings(this.path, 'fs');
const filter = this.filters.length > 0 ? this.filters : this.filter;
this.data.fetch(this.path, filter, limit, sortField).subscribe(results => {
this.fieldSettings = this.settings.getFieldSettings(this.path, 'fs');
const sortedFields = results.map(res => {
res.fields = res.fields.sort(function(a, b) {
if(a.name < b.name) { return -1; }
if(a.name > b.name) { return 1; }
return 0;
});
return res;
});
this.results = sortedFields;
this.fields = this.data.fieldsList.length === 0 ? this.fields : this.data.fieldsList;
if (!this.fields.includes(this.filter.field)) {
this.fields.push(this.filter.field);
}
const selectedSort = this.sort.fields.find(f => f.selected);
this.sort.fields = this.fields.map(f => {
return {name: f, selected: false, direction: undefined};
});
if (selectedSort !== undefined) {
const checkSelected = this.sort.fields.find(f => f.name === selectedSort.name);
if (checkSelected === undefined) {
this.sort.fields.push(selectedSort);
} else {
checkSelected.selected = true;
checkSelected.direction = selectedSort.direction;
}
}
this.working = false;
}, error => {
this.working = false;
const snackBarRef = this.snackBar.open('Error', error.message, { duration: 10000 });
snackBarRef.onAction().subscribe(( ) => {
this.router.navigate(['user']);
});
});
}
parseFilter() {
let parts = [];
let op = 'or';
if (this.textFilter) {
let conj = 'AND';
let hasConj = this.textFilter.includes('AND');
if (!hasConj) {
conj = 'and';
}
parts = this.textFilter.split(conj);
const filters = [];
for (const part of parts) {
const fp = part.trim().split(' ');
const filter = {field: fp[0], oper: fp[1], val: fp[2], val2: undefined, isDate: false, dateVal: undefined}
if (filter.val === "true") {
filter.val = true
}
if (filter.val === "false") {
filter.val = false
}
filters.push(filter);
}
if (this.filter.field !== undefined) {
filters.push(this.filter);
}
this.filters = filters;
}
}
clearTextFilter() {
this.textFilter = undefined;
this.filters = [];
this.fetch();
}
toggleView() {
this.view.show = !this.view.show;
}
toggleSort() {
this.sort.show = !this.sort.show;
}
toggleOptions() {
this.options.show = !this.options.show;
}
@HostListener('document:click', ['$event'])
clickout(event) {
if (event.target.innerText !== 'Sort') {
if (this.sort.show) {
this.sort.show = false;
}
}
if (event.target.innerText !== 'View') {
if (this.view.show) {
this.view.show = false;
}
}
if (event.target.innerText !== 'more_vert') {
if (this.options.show) {
this.options.show = false;
}
}
}
switchView(view) {
this.view.value = view.name;
for (const v of this.view.types) {
v.selected = v.name === view.name;
}
}
doSort(field) {
for (const f of this.sort.fields) {
f.selected = f.name === field.name;
}
field.selected = true;
if (field.direction === undefined) {
field.direction = 'asc';
} else {
field.direction = field.direction === 'asc' ? 'desc' : 'asc';
}
this.fetch();
}
doFilter() {
this.fetch();
}
onFilter(field) {
if (field !== undefined) {
if (field.collection !== undefined) {
this.path = field.collection;
}
this.filter.field = field.name;
if (field.parent !== undefined) {
this.filter.field = field.parent + '.' + field.name;
if (!this.fields.includes(this.filter.field)) {
this.fields.push(this.filter.field);
}
}
this.filter.val = field.value;
this.filter.oper = 'eq';
let isDate = field.isDate;
if (this.fieldSettings[field.name] !== undefined) {
isDate = this.fieldSettings[field.name].isDate;
}
this.filter.isDate = isDate;
if (isDate) {
const moment = mom(field.value);
const start = moment.startOf('day');
this.filter.val = start.valueOf();
const end = moment.endOf('day');
this.filter.val2 = end.valueOf();
this.filter.dateVal = new Date(field.value);
}
}
this.doFilter();
}
clear() {
this.filter = {field: undefined, oper: 'eq', val: '', val2: '', isDate: false, dateVal: undefined};
this.fetch();
}
onChangeFilter(field) {
this.filter = Object.assign(this.filter, {val: '', val2: '', oper: 'eq'}); // reset
this.filter.isDate = this.data.isDateField(field);
const fieldSettings = this.settings.getFieldSettings(this.path, 'fs');
if (fieldSettings[field] !== undefined) {
this.filter.isDate = fieldSettings[field].isDate;
}
}
dateChange(kind, $event) {
// for date eq to work we need SOD to EOD
if (this.filter.oper === 'eq') {
const moment = $event.value;
const start = moment.startOf('day');
this.filter.val = start.valueOf();
const end = moment.endOf('day');
this.filter.val2 = end.valueOf();
} else {
this.filter[kind] = $event.value.valueOf();
}
}
export() {
this.options.show = false;
this.csv.export(this.results);
}
importSelected(files: FileList) {
this.options.show = false;
if (files && files.length > 0) {
const file: File = files.item(0);
const reader: FileReader = new FileReader();
reader.readAsText(file);
reader.onload = (e) => {
const csv: any = reader.result;
this.doImport(csv);
};
}
}
print() {
this.options.show = false;
setTimeout(() => {
window.print();
}, 50);
}
onSelect(selected) {
this.selected = selected;
}
delete() {
this.data.delete(this.selected).then(() => {
this.selected = [];
this.fetch();
});
}
update() {
const dialogRef = this.dialog.open(UpdateComponent, {
width: '600px',
data: {results: this.results, path: this.path, kind: 'fs'}
});
dialogRef.afterClosed().subscribe(result => {
if (result.fields === undefined) {
return;
}
const fields = result.fields;
if (fields.length > 0) {
this.doUpdateResults(fields).then(() => {
this.fetch();
})
}
});
}
doUpdateResults(fields: Array<any>) {
for (const f of fields) {
if (f.datatype === 'integer') {
f.value = parseInt(f.value, 10);
} else if (f.datatype === 'float') {
f.value = parseFloat(f.value);
} else if (f.datatype === 'date') {
f.value = this.data.getTimestamp(f.value.toDate());
} else if (f.datatype === 'boolean') {
f.value = (f.value == 'true' || f.value === true);
}
}
const updates = this.results.map(r => {
r.collection = this.path;
const item = r.item;
for (const f of fields) {
item[f.name] = f.value;
if (f.value == undefined) {
item[f.name] = this.data.getDeleteField();
}
}
return r;
});
return this.data.batchUpdate(updates);
}
openSettings(): void {
const dialogRef = this.dialog.open(SettingsComponent, {
width: '300px',
data: {results: this.results, path: this.path, kind: 'fs'}
});
dialogRef.afterClosed().subscribe(result => {
this.updateResultsDataTypes();
const filterField = this.fieldSettings[this.filter.field];
if (filterField !== undefined) {
this.filter.isDate = filterField.isDate;
}
});
}
// update the results so the date fiels show as dates
private updateResultsDataTypes() {
this.fieldSettings = this.settings.getFieldSettings(this.path, 'fs');
this.data.fieldSettings = this.fieldSettings;
for (const item of this.results) {
for (const f of item.fields) {
if (this.fieldSettings[f.name] !== undefined) {
f.isDate = this.fieldSettings[f.name].isDate;
f.isCurrency = this.fieldSettings[f.name].isCurrency;
}
}
}
// so a change event triggers on child components with results as an input
this.results = this.results.slice();
}
private doImport(csv) {
const items = this.csv.toJson(csv);
if (items.length > 0) {
const item = items[0];
if (item.$key !== undefined) {
const updates = items.map(item => {
// fix boolean values and remove crlf
const keys = Object.keys(item);
for (const key of keys) {
let val = item[key];
if (val !== undefined && typeof val === 'string') {
val = val.replace(/(\r\n|\n|\r)/gm, "");
}
if (val === 'TRUE') {
item[key] = true;
} else {
item[key] = val;
}
}
return {
collection: this.path,
item: {...item, key: item.$key},
}
});
this.data.batchUpdate(updates).then(() => {
this.fetch();
});
} else {
this.data.addAll(items).then(() => {
this.fetch();
});
}
}
}
} | the_stack |
import { Builder } from '@builder.io/react';
import Search from '@material-ui/icons/Search';
import Router from 'next/router';
import useEventListener from 'use-typed-event-listener';
import InputAdornment from '@material-ui/core/InputAdornment';
import Paper from '@material-ui/core/Paper';
import ListItemText from '@material-ui/core/ListItemText';
import ListItem from '@material-ui/core/ListItem';
import CircularProgress from '@material-ui/core/CircularProgress';
import TextField from '@material-ui/core/TextField';
import List from '@material-ui/core/List';
import { useRef, useEffect, useState } from 'react';
import escapeRegExp from 'lodash/escapeRegExp';
import uniqBy from 'lodash/uniqBy';
import { GoogleSearchResponse } from '../interfaces/google-json-search';
import { renderLink as RenderLink } from '../functions/render-link';
import { DiscourseResponse } from '../interfaces/discourse-search';
import useDebounce from 'react-use/lib/useDebounce';
import { defaultSearchBarPlaceholder } from './docs-search.config';
function escapeHtml(unsafeText: string) {
const div = document.createElement('div');
div.innerText = unsafeText;
return div.innerHTML;
}
const proxyUrl = (url: string) =>
`https://cdn.builder.io/api/v1/proxy-api?url=${encodeURIComponent(url)}`;
type DocsSearchProps = { placeholder?: string };
export function DocsSearch(props: DocsSearchProps) {
const [isClient, setIsClient] = useState(false);
useEffect(() => {
setIsClient(true);
}, []);
return isClient ? <DocsSearchBrowser {...props} /> : null;
}
function DocsSearchBrowser(props: DocsSearchProps) {
const [searchText, setSearchText] = useState('');
const [searchResult, setSearchResult] = useState(
null as SearchResult[] | null,
);
const [loading, setLoading] = useState(false);
const [searchFocused, setSearchFocused] = useState(false);
async function getGoogleResults(
text = searchText,
): Promise<GoogleSearchResponse> {
return fetch(
`https://www.googleapis.com/customsearch/v1/siterestrict?key=AIzaSyApBC9gblaCzWrtEBgHnZkd_B37OF49BfM&cx=012652105943418481980:b8ow8geasbo&q=${encodeURIComponent(
text,
)}`,
).then((res) => res.json());
}
async function getForumResults(
text = searchText,
): Promise<DiscourseResponse> {
return fetch(
proxyUrl(
`https://forum.builder.io/search/query.json?term=${encodeURIComponent(
text,
)}`,
),
).then((res) => res.json());
}
async function getBuilderResults(
text = searchText,
): Promise<BuilderContentResponse> {
const fields = [
'name',
'data.pageTitle',
'data.description',
'data.tags',
'data.keywords',
];
const url = `https://cdn.builder.io/api/v2/content/docs-content?apiKey=YJIGb4i01jvw0SRdL5Bt&query.$or=${JSON.stringify(
fields.map((field) => ({
[field]: { $regex: text, $options: 'i' },
})),
)}&fields=name,data.pageTitle,data.description,data.tags,data.keywords,data.url`;
return fetch(url).then((res) => res.json());
}
async function search(): Promise<void> {
if (!searchText) {
setSearchResult(null);
return;
}
setLoading(true);
const [builderResponse, googleResponse, forumResponse] = await Promise.all([
getBuilderResults(searchText),
getGoogleResults(searchText),
getForumResults(searchText).catch((err) => {
console.error('Error getting Discourse posts', err);
return null;
}),
]).catch((err) => {
console.error('Search error:', err);
setLoading(false);
return [];
});
if (!googleResponse || !builderResponse) {
return;
}
const results: SearchResult[] = uniqBy(
builderResponse?.results || [],
(item) => item.data.url,
).map(
(item) =>
({
title: item.data.pageTitle,
url: `https://www.builder.io${item.data.url}`,
// Bold exact text matches
htmlTitle: escapeHtml(item.data.pageTitle || '').replace(
new RegExp(escapeRegExp(searchText), 'gi'),
(match) => `<b>${match}</b>`,
),
htmlDescription: escapeHtml(item.data.description || '').replace(
new RegExp(escapeRegExp(searchText), 'gi'),
(match) => `<b>${match}</b>`,
),
} as SearchResult),
);
const googleResults = googleResponse!.items;
if (googleResults) {
for (const item of googleResults) {
const { pathname, hostname } = new URL(item.link);
let skip = false;
if (hostname === 'www.builder.io' || hostname === 'forum.builder.io') {
// For each of our results, if Google has a result too, augment it
// with the info from Google as Google pulls in additional info like
// the exact matching text snippet on the page, formatted titles
// (with bolding for matches), etc
for (const result of results) {
let parsed: URL | null = null;
try {
parsed = new URL(result.url);
} catch (err) {
console.error('Could not parse url', result.url, err);
}
if (parsed?.pathname === pathname) {
result.htmlDescription = item.htmlSnippet;
result.htmlTitle = item.htmlTitle;
result.displayLink = item.displayLink;
skip = true;
}
}
}
if (!skip) {
results.push({
url: item.link,
title: item.title,
htmlTitle: item.htmlTitle,
htmlDescription: item.htmlSnippet,
displayLink: item.displayLink,
});
}
}
}
// TODO: filter to ensure google didn't also pick up this forum result
const forumResultstoUse =
forumResponse?.topics?.map((item) => {
const blurb =
item.excerpt ||
forumResponse.posts?.find((post) => post.topic_id == item.id)?.blurb;
return {
title: item.title,
url: `https://forum.builder.io/t/${item.slug}/${item.id}`,
htmlTitle: escapeHtml(item.title || '').replace(
new RegExp(escapeRegExp(searchText), 'gi'),
(match) => `<b>${match}</b>`,
),
htmlDescription: escapeHtml(blurb || '').replace(
new RegExp(escapeRegExp(searchText), 'gi'),
(match) => `<b>${match}</b>`,
),
};
}) || [];
results.push(...forumResultstoUse);
setSearchResult(
results.filter((item) => {
try {
const parsedUrl = new URL(item.url);
// Remove marketing pages (homepage and /m/ pages) from docs search results
if (['builder.io', 'www.builder.io'].includes(parsedUrl.hostname)) {
if (
parsedUrl.pathname === '/' ||
parsedUrl.pathname.startsWith('/m/')
) {
return false;
}
}
} catch (err) {
console.error('Error parsing URL', item.url, err);
return false;
}
return true;
}),
);
setLoading(false);
}
const inputRef = useRef<HTMLInputElement | null>(null);
const { width, left, bottom } =
inputRef.current?.getBoundingClientRect() || {};
if (Builder.isBrowser) {
useEventListener(document.body, 'keyup', (event) => {
// Listen for `/` key down to focus search
if (
event.key === '/' &&
document.activeElement === document.body && // An input is not focused
inputRef.current
) {
inputRef.current.focus();
}
});
}
useDebounce(
() => {
search();
},
500,
[searchText],
);
return (
<form
onSubmit={(e) => {
e.preventDefault();
search();
}}
>
<div
css={{
display: 'flex',
width: '100%',
position: 'relative',
alignItems: 'center',
}}
>
<TextField
fullWidth
InputProps={{
disableUnderline: true,
startAdornment: (
<InputAdornment position="start">
<Search
css={{
color: '#999',
marginRight: -2,
marginTop: -2,
fontSize: 20,
}}
/>
</InputAdornment>
),
}}
onFocus={() => setSearchFocused(true)}
onBlur={() => setSearchFocused(false)}
inputRef={inputRef}
type="search"
placeholder={props.placeholder ?? defaultSearchBarPlaceholder}
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
/>
{loading && (
<CircularProgress
css={{
position: 'absolute',
right: 30,
}}
size={20}
disableShrink
/>
)}
</div>
{Boolean(searchResult?.length) && searchFocused && (
<Paper
elevation={24}
css={{
position: 'fixed',
left: (left || 0) + (width || 0) / 2 || '50%',
transform: 'translateX(-50%)',
width: 700,
maxWidth: '90vw',
zIndex: 100,
top: bottom || 200,
maxHeight: bottom ? window.innerHeight - bottom - 10 : undefined,
overflow: 'auto',
}}
>
<List>
{searchResult!.map((item, index) => (
<ListItem
button
key={index}
onMouseDown={(e) => {
e.preventDefault();
if (
item.url.includes('builder.io/c/docs') ||
item.url.startsWith('/c/docs')
) {
Router.push(
item.url.startsWith('/c/docs')
? item.url
: item.url.split('builder.io')[1],
).then(() => {
const docsContentContainer = document.querySelector(
'.docs-content-container',
);
if (docsContentContainer) {
docsContentContainer.scrollTop = 0;
}
});
setTimeout(() => {
inputRef.current?.blur();
}, 200);
} else {
window.open(item.url, '_blank');
}
}}
>
<RenderLink
href={item.url}
{...(!item.url.includes('/c/docs')
? { target: '_blank' }
: null)}
>
<div css={{ fontSize: 10, opacity: 0.4 }}>
{item.url.includes('forum.builder.io')
? 'Builder Forum'
: item.url.includes('www.builder.io') ||
item.displayLink === 'www.builder.io'
? 'Builder Docs'
: item.displayLink || 'Builder Docs'}
</div>
<ListItemText
primary={
item.htmlTitle ? (
<span
dangerouslySetInnerHTML={{ __html: item.htmlTitle }}
/>
) : (
item.title
)
}
secondary={
item.htmlDescription ? (
<span
dangerouslySetInnerHTML={{
__html: item.htmlDescription,
}}
/>
) : (
item.description || `Learn about ${item.title}`
)
}
/>
</RenderLink>
</ListItem>
))}
</List>
</Paper>
)}
</form>
);
}
interface SearchResult {
url: string;
title: string;
description?: string;
htmlTitle?: string;
htmlDescription?: string;
displayLink?: string;
}
export interface BuilderContentResponse {
results: ResultsEntity[];
}
export interface ResultsEntity {
name: string;
data: Data;
}
export interface Data {
pageTitle?: string | null;
keywords?: string | null;
tags?: string | null;
description?: string | null;
url: string;
} | the_stack |
import {
expect,
mkAddress,
getChainData,
ChainData,
txReceiptMock,
createRequestContext,
mkBytes32,
} from "@connext/nxtp-utils";
import { BigNumber, utils } from "ethers";
import { SinonStub, stub } from "sinon";
import * as metrics from "../../../src/lib/helpers/metrics";
import * as entities from "../../../src/lib/entities/metrics";
import { contractReaderMock, ctxMock, txServiceMock } from "../../globalTestHook";
import { chainDataMock, configMock } from "../../utils";
import { parseEther } from "@ethersproject/units";
import * as ConfigFns from "../../../src/config";
import * as SharedFns from "../../../src/lib/helpers/shared";
const requestContext = createRequestContext("TEST", mkBytes32());
describe("convertToUsd", () => {
let priceOracleStub: SinonStub;
beforeEach(() => {
priceOracleStub = stub(ConfigFns, "getDeployedPriceOracleContract");
priceOracleStub.returns({ address: mkAddress("0xaaa"), abi: "xxx" });
});
it("should return zero if no price oracle deployed", async () => {
const amount = 100;
expect(
await metrics.convertToUsd(mkAddress("0xaaaaa"), 1337, BigNumber.from(amount).toString(), requestContext),
).to.be.eq(0);
});
it("should return zero if token isn't configured on price oracle", async () => {
txServiceMock.getTokenPrice.resolves(BigNumber.from(0));
const amount = parseEther("100");
expect(await metrics.convertToUsd(mkAddress("0xaaaaa"), 1, amount.toString(), requestContext)).to.be.eq(0);
});
it("should return price", async () => {
const amount = parseEther("100");
const price = 1;
txServiceMock.getTokenPrice.resolves(parseEther(price.toString()));
expect(await metrics.convertToUsd(mkAddress("0xaaaaa"), 1, amount.toString(), requestContext)).to.be.eq(100);
});
});
describe("getAssetName", () => {
it("should work", () => {
const { assetId, chainId } = configMock.swapPools[0].assets[0];
const name = metrics.getAssetName(assetId, chainId);
expect(name).to.be.eq("TEST");
});
it("should fallback to chaindata if theres no name in the pool", () => {
const { assetId, chainId } = configMock.swapPools[0].assets[0];
configMock.swapPools[0] = {
...configMock.swapPools[0],
name: undefined,
};
const mainnetEquivalent = mkAddress("0xabc");
chainDataMock.set(chainId.toString(), {
assetId: {
[assetId]: {
mainnetEquivalent,
},
},
} as ChainData);
chainDataMock.set("1", {
assetId: {
[mainnetEquivalent]: {
symbol: "TEST_CHAIN_DATA",
},
},
} as ChainData);
const name = metrics.getAssetName(assetId, chainId);
expect(name).to.be.eq("TEST_CHAIN_DATA");
});
});
describe("collectOnchainLiquidity", () => {
let priceOracleStub: SinonStub;
beforeEach(() => {
priceOracleStub = stub(ConfigFns, "getDeployedPriceOracleContract");
priceOracleStub.returns({ address: mkAddress("0xaaa"), abi: "xxx" });
stub(SharedFns, "getMainnetEquivalent").resolves("0xccc");
});
it("should work with varying decimals", async () => {
ctxMock.chainData = await getChainData();
// constants
const amt = "10";
const price = "0.5";
const chainIds = Object.keys(configMock.chainConfig).map((c) => parseInt(c));
const assetIds = Array(chainIds.length)
.fill(0)
.map((_, idx) => {
return configMock.swapPools[0].assets.find((a) => a.chainId === chainIds[idx]).assetId;
});
const decimals = Array(chainIds.length)
.fill(0)
.map((_, idx) => (idx % 2 === 0 ? 6 : 18));
// create stub for asset balances
chainIds.forEach((_, idx) => {
(contractReaderMock.getAssetBalances as SinonStub)
.onCall(idx)
.resolves([{ assetId: assetIds[idx], amount: utils.parseUnits(amt, decimals[idx]) }]);
});
// create stub for token price
// console.log("prices", tokenPrices);
txServiceMock.getTokenPrice.resolves(parseEther(price));
// create stub for decimals
txServiceMock.getDecimalsForAsset.callsFake((chainId: number, _assetId: string) => {
const idx = chainIds.findIndex((c) => c === chainId);
const ret = decimals[idx];
return Promise.resolve(ret ?? 18);
});
// run
const ret = await metrics.collectOnchainLiquidity();
expect(ret).to.be.deep.eq({
1337: [
{
assetId: configMock.swapPools[0].assets.find((a) => a.chainId === 1337).assetId,
amount: +amt * +price,
},
],
1338: [
{
assetId: configMock.swapPools[0].assets.find((a) => a.chainId === 1338).assetId,
amount: +amt * +price,
},
],
});
});
});
describe("collectExpressiveLiquidity", () => {
let priceOracleStub: SinonStub;
beforeEach(() => {
stub(metrics, "getLiquidityCacheExpiry").returns(0);
priceOracleStub = stub(ConfigFns, "getDeployedPriceOracleContract");
priceOracleStub.returns({ address: mkAddress("0xaaa"), abi: "xxx" });
stub(SharedFns, "getMainnetEquivalent").resolves("0xccc");
});
it("should return undefined if all assets fail", async () => {
(contractReaderMock.getExpressiveAssetBalances as SinonStub).rejects(new Error("Fail"));
const ret = await metrics.collectExpressiveLiquidity();
expect(ret).to.be.undefined;
expect((contractReaderMock.getExpressiveAssetBalances as SinonStub).callCount).to.be.eq(
Object.keys(configMock.chainConfig).length,
);
});
it("should work for all other assets if theres one error", async () => {
(contractReaderMock.getExpressiveAssetBalances as SinonStub).onCall(0).rejects(new Error("Fail"));
(contractReaderMock.getExpressiveAssetBalances as SinonStub).onCall(1).resolves([]);
const ret = await metrics.collectExpressiveLiquidity();
expect(ret).to.be.deep.eq({ [Object.keys(configMock.chainConfig)[1]]: [] });
expect((contractReaderMock.getExpressiveAssetBalances as SinonStub).callCount).to.be.eq(
Object.keys(configMock.chainConfig).length,
);
});
it("should work with varying decimals", async () => {
// constants
const amt = "10";
const price = "0.5";
const chainIds = Object.keys(configMock.chainConfig).map((c) => parseInt(c));
const assetIds = Array(chainIds.length)
.fill(0)
.map((_, idx) => {
return configMock.swapPools[0].assets.find((a) => a.chainId === chainIds[idx]).assetId;
});
// create stub for asset balances
chainIds.forEach((_, idx) => {
(contractReaderMock.getExpressiveAssetBalances as SinonStub).onCall(idx).resolves([
{
assetId: assetIds[idx],
amount: utils.parseUnits(amt, 18),
locked: BigNumber.from(0),
supplied: utils.parseUnits(amt, 18),
removed: BigNumber.from(0),
// volume: utils.parseUnits(amt, 18),
// volumeIn: utils.parseUnits(amt, 18),
},
]);
});
// create stub for token price
// console.log("prices", tokenPrices);
txServiceMock.getTokenPrice.resolves(parseEther(price));
// create stub for decimals
txServiceMock.getDecimalsForAsset.resolves(18);
// run
const ret = await metrics.collectExpressiveLiquidity();
expect(ret).to.be.deep.eq({
1337: [
{
assetId: configMock.swapPools[0].assets.find((a) => a.chainId === 1337).assetId,
amount: +amt * +price,
supplied: +amt * +price,
locked: 0,
removed: 0,
// volume: +amt * +price,
// volumeIn: +amt * +price,
},
],
1338: [
{
assetId: configMock.swapPools[0].assets.find((a) => a.chainId === 1338).assetId,
amount: +amt * +price,
supplied: +amt * +price,
locked: 0,
removed: 0,
// volume: +amt * +price,
// volumeIn: +amt * +price,
},
],
});
});
});
describe("collectGasBalance", () => {
it("should work", async () => {
const chainIds = Object.keys(configMock.chainConfig).map((c) => +c);
const balance = 100;
txServiceMock.getBalance.resolves(BigNumber.from(utils.parseEther(balance.toString())));
const expected = {};
chainIds.map((c) => {
expected[c] = balance;
});
expect(await metrics.collectGasBalance()).to.be.deep.eq(expected);
});
it("should work if theres an error on one chain", async () => {
const chainIds = Object.keys(configMock.chainConfig)
.map((c) => +c)
.slice(0, 2);
console.log("chainIds");
const balance = 100;
txServiceMock.getBalance.onFirstCall().resolves(BigNumber.from(utils.parseEther(balance.toString())));
txServiceMock.getBalance.onSecondCall().rejects(new Error("fail"));
const expected = { [chainIds[0]]: balance };
expect(await metrics.collectGasBalance()).to.be.deep.eq(expected);
});
});
describe("collectRpcHeads", () => {
it("should work", async () => {
const chainIds = Object.keys(configMock.chainConfig).map((c) => +c);
const block = 100000;
txServiceMock.getBlockNumber.resolves(block);
const expected = {};
chainIds.map((c) => {
expected[c] = block;
});
expect(await metrics.collectRpcHeads()).to.be.deep.eq(expected);
});
it("should work if theres an error on one chain", async () => {
const chainIds = Object.keys(configMock.chainConfig)
.map((c) => +c)
.slice(0, 2);
const block = 100;
txServiceMock.getBlockNumber.onFirstCall().resolves(block);
txServiceMock.getBlockNumber.onSecondCall().rejects(new Error("fail"));
const expected = { [chainIds[0]]: block };
expect(await metrics.collectRpcHeads()).to.be.deep.eq(expected);
});
});
describe("collectSubgraphHeads", () => {
it("should work", async () => {
const chainIds = Object.keys(configMock.chainConfig).map((c) => +c);
const block = 100000;
(contractReaderMock.getSyncRecords as any).resolves([{ synced: true, syncedBlock: block }]);
const expected = {};
chainIds.map((c) => {
expected[c] = block;
});
expect(await metrics.collectSubgraphHeads()).to.be.deep.eq(expected);
});
it("should work if theres an error on one chain", async () => {
const chainIds = Object.keys(configMock.chainConfig)
.map((c) => +c)
.slice(0, 2);
const block = 100;
(contractReaderMock.getSyncRecords as any).onFirstCall().resolves([{ synced: true, syncedBlock: block }]);
(contractReaderMock.getSyncRecords as any).onSecondCall().rejects(new Error("fail"));
const expected = { [chainIds[0]]: block };
expect(await metrics.collectSubgraphHeads()).to.be.deep.eq(expected);
});
});
describe("incrementFees / incrementGasConsumed / incrementTotalTransferredVolume / incrementRelayerFeesPaid", () => {
const assetName = "TEST";
const chainId = 1337;
const tests = [
{
method: "incrementFees",
args: [mkAddress(), chainId, parseEther("1")],
labels: { assetId: mkAddress(), chainId, assetName },
value: 10,
entity: "feesCollected",
},
{
method: "incrementGasConsumed",
args: [chainId, txReceiptMock, entities.TransactionReasons.Relay],
labels: { reason: entities.TransactionReasons.Relay, chainId },
value: 10,
entity: "gasConsumed",
},
{
method: "incrementRelayerFeesPaid",
args: [chainId, parseEther("0.0001"), mkAddress(), entities.TransactionReasons.CancelReceiver],
labels: { assetId: mkAddress(), reason: entities.TransactionReasons.CancelReceiver, chainId },
value: 10,
entity: "relayerFeesPaid",
},
{
method: "incrementTotalTransferredVolume",
args: [mkAddress(), chainId, parseEther("0.0001")],
labels: { assetId: mkAddress(), chainId },
value: 10,
entity: "totalTransferredVolume",
},
];
for (const test of tests) {
it(`${test.method} should work`, async () => {
const { method, args, labels, value, entity } = test;
stub(metrics, "convertToUsd").resolves(value);
stub(metrics, "getAssetName").returns(assetName);
const incrementStub = stub();
stub(entities, entity as any).value({ inc: incrementStub });
await metrics[method](...args);
expect(incrementStub.calledOnceWithExactly([{ ...labels }, value]));
});
it(`${test.method} should fail if it cannot convert to usdc`, async () => {
const { method, args, entity } = test;
stub(metrics, "convertToUsd").rejects(new Error("fail"));
stub(metrics, "getAssetName").returns(assetName);
const incrementStub = stub();
stub(entities, entity as any).value({ inc: incrementStub });
await expect(metrics[method](...args)).to.be.rejectedWith("fail");
});
}
}); | the_stack |
import url from 'url';
import request from "browser-request";
import { SERVICE_TYPES } from "matrix-js-sdk/src/service-types";
import { Room } from "matrix-js-sdk/src/models/room";
import { logger } from "matrix-js-sdk/src/logger";
import SettingsStore from "./settings/SettingsStore";
import { Service, startTermsFlow, TermsInteractionCallback, TermsNotSignedError } from './Terms';
import { MatrixClientPeg } from "./MatrixClientPeg";
import SdkConfig from "./SdkConfig";
import { WidgetType } from "./widgets/WidgetType";
// The version of the integration manager API we're intending to work with
const imApiVersion = "1.1";
// TODO: Generify the name of this class and all components within - it's not just for Scalar.
export default class ScalarAuthClient {
private scalarToken: string;
private termsInteractionCallback: TermsInteractionCallback;
private isDefaultManager: boolean;
constructor(private apiUrl: string, private uiUrl: string) {
this.scalarToken = null;
// `undefined` to allow `startTermsFlow` to fallback to a default
// callback if this is unset.
this.termsInteractionCallback = undefined;
// We try and store the token on a per-manager basis, but need a fallback
// for the default manager.
const configApiUrl = SdkConfig.get()['integrations_rest_url'];
const configUiUrl = SdkConfig.get()['integrations_ui_url'];
this.isDefaultManager = apiUrl === configApiUrl && configUiUrl === uiUrl;
}
private writeTokenToStore() {
window.localStorage.setItem("mx_scalar_token_at_" + this.apiUrl, this.scalarToken);
if (this.isDefaultManager) {
// We remove the old token from storage to migrate upwards. This is safe
// to do because even if the user switches to /app when this is on /develop
// they'll at worst register for a new token.
window.localStorage.removeItem("mx_scalar_token"); // no-op when not present
}
}
private readTokenFromStore(): string {
let token = window.localStorage.getItem("mx_scalar_token_at_" + this.apiUrl);
if (!token && this.isDefaultManager) {
token = window.localStorage.getItem("mx_scalar_token");
}
return token;
}
private readToken(): string {
if (this.scalarToken) return this.scalarToken;
return this.readTokenFromStore();
}
setTermsInteractionCallback(callback) {
this.termsInteractionCallback = callback;
}
connect(): Promise<void> {
return this.getScalarToken().then((tok) => {
this.scalarToken = tok;
});
}
hasCredentials(): boolean {
return this.scalarToken != null; // undef or null
}
// Returns a promise that resolves to a scalar_token string
getScalarToken(): Promise<string> {
const token = this.readToken();
if (!token) {
return this.registerForToken();
} else {
return this.checkToken(token).catch((e) => {
if (e instanceof TermsNotSignedError) {
// retrying won't help this
throw e;
}
return this.registerForToken();
});
}
}
private getAccountName(token: string): Promise<string> {
const url = this.apiUrl + "/account";
return new Promise(function(resolve, reject) {
request({
method: "GET",
uri: url,
qs: { scalar_token: token, v: imApiVersion },
json: true,
}, (err, response, body) => {
if (err) {
reject(err);
} else if (body && body.errcode === 'M_TERMS_NOT_SIGNED') {
reject(new TermsNotSignedError());
} else if (response.statusCode / 100 !== 2) {
reject(body);
} else if (!body || !body.user_id) {
reject(new Error("Missing user_id in response"));
} else {
resolve(body.user_id);
}
});
});
}
private checkToken(token: string): Promise<string> {
return this.getAccountName(token).then(userId => {
const me = MatrixClientPeg.get().getUserId();
if (userId !== me) {
throw new Error("Scalar token is owned by someone else: " + me);
}
return token;
}).catch((e) => {
if (e instanceof TermsNotSignedError) {
logger.log("Integration manager requires new terms to be agreed to");
// The terms endpoints are new and so live on standard _matrix prefixes,
// but IM rest urls are currently configured with paths, so remove the
// path from the base URL before passing it to the js-sdk
// We continue to use the full URL for the calls done by
// matrix-react-sdk, but the standard terms API called
// by the js-sdk lives on the standard _matrix path. This means we
// don't support running IMs on a non-root path, but it's the only
// realistic way of transitioning to _matrix paths since configs in
// the wild contain bits of the API path.
// Once we've fully transitioned to _matrix URLs, we can give people
// a grace period to update their configs, then use the rest url as
// a regular base url.
const parsedImRestUrl = url.parse(this.apiUrl);
parsedImRestUrl.path = '';
parsedImRestUrl.pathname = '';
return startTermsFlow([new Service(
SERVICE_TYPES.IM,
url.format(parsedImRestUrl),
token,
)], this.termsInteractionCallback).then(() => {
return token;
});
} else {
throw e;
}
});
}
registerForToken(): Promise<string> {
// Get openid bearer token from the HS as the first part of our dance
return MatrixClientPeg.get().getOpenIdToken().then((tokenObject) => {
// Now we can send that to scalar and exchange it for a scalar token
return this.exchangeForScalarToken(tokenObject);
}).then((token) => {
// Validate it (this mostly checks to see if the IM needs us to agree to some terms)
return this.checkToken(token);
}).then((token) => {
this.scalarToken = token;
this.writeTokenToStore();
return token;
});
}
exchangeForScalarToken(openidTokenObject: any): Promise<string> {
const scalarRestUrl = this.apiUrl;
return new Promise(function(resolve, reject) {
request({
method: 'POST',
uri: scalarRestUrl + '/register',
qs: { v: imApiVersion },
body: openidTokenObject,
json: true,
}, (err, response, body) => {
if (err) {
reject(err);
} else if (response.statusCode / 100 !== 2) {
reject(new Error(`Scalar request failed: ${response.statusCode}`));
} else if (!body || !body.scalar_token) {
reject(new Error("Missing scalar_token in response"));
} else {
resolve(body.scalar_token);
}
});
});
}
getScalarPageTitle(url: string): Promise<string> {
let scalarPageLookupUrl = this.apiUrl + '/widgets/title_lookup';
scalarPageLookupUrl = this.getStarterLink(scalarPageLookupUrl);
scalarPageLookupUrl += '&curl=' + encodeURIComponent(url);
return new Promise(function(resolve, reject) {
request({
method: 'GET',
uri: scalarPageLookupUrl,
json: true,
}, (err, response, body) => {
if (err) {
reject(err);
} else if (response.statusCode / 100 !== 2) {
reject(new Error(`Scalar request failed: ${response.statusCode}`));
} else if (!body) {
reject(new Error("Missing page title in response"));
} else {
let title = "";
if (body.page_title_cache_item && body.page_title_cache_item.cached_title) {
title = body.page_title_cache_item.cached_title;
}
resolve(title);
}
});
});
}
/**
* Mark all assets associated with the specified widget as "disabled" in the
* integration manager database.
* This can be useful to temporarily prevent purchased assets from being displayed.
* @param {WidgetType} widgetType The Widget Type to disable assets for
* @param {string} widgetId The widget ID to disable assets for
* @return {Promise} Resolves on completion
*/
disableWidgetAssets(widgetType: WidgetType, widgetId: string): Promise<void> {
let url = this.apiUrl + '/widgets/set_assets_state';
url = this.getStarterLink(url);
return new Promise<void>((resolve, reject) => {
request({
method: 'GET', // XXX: Actions shouldn't be GET requests
uri: url,
json: true,
qs: {
'widget_type': widgetType.preferred,
'widget_id': widgetId,
'state': 'disable',
},
}, (err, response, body) => {
if (err) {
reject(err);
} else if (response.statusCode / 100 !== 2) {
reject(new Error(`Scalar request failed: ${response.statusCode}`));
} else if (!body) {
reject(new Error("Failed to set widget assets state"));
} else {
resolve();
}
});
});
}
getScalarInterfaceUrlForRoom(room: Room, screen: string, id: string): string {
const roomId = room.roomId;
const roomName = room.name;
let url = this.uiUrl;
url += "?scalar_token=" + encodeURIComponent(this.scalarToken);
url += "&room_id=" + encodeURIComponent(roomId);
url += "&room_name=" + encodeURIComponent(roomName);
url += "&theme=" + encodeURIComponent(SettingsStore.getValue("theme"));
if (id) {
url += '&integ_id=' + encodeURIComponent(id);
}
if (screen) {
url += '&screen=' + encodeURIComponent(screen);
}
return url;
}
getStarterLink(starterLinkUrl: string): string {
return starterLinkUrl + "?scalar_token=" + encodeURIComponent(this.scalarToken);
}
} | the_stack |
import basem = require('./ClientApiBases');
import VsoBaseInterfaces = require('./interfaces/common/VsoBaseInterfaces');
import TaskAgentInterfaces = require("./interfaces/TaskAgentInterfaces");
import VSSInterfaces = require("./interfaces/common/VSSInterfaces");
export interface ITaskApi extends basem.ClientApiBase {
getPlanAttachments(scopeIdentifier: string, hubName: string, planId: string, type: string): Promise<TaskAgentInterfaces.TaskAttachment[]>;
createAttachment(customHeaders: any, contentStream: NodeJS.ReadableStream, scopeIdentifier: string, hubName: string, planId: string, timelineId: string, recordId: string, type: string, name: string): Promise<TaskAgentInterfaces.TaskAttachment>;
getAttachment(scopeIdentifier: string, hubName: string, planId: string, timelineId: string, recordId: string, type: string, name: string): Promise<TaskAgentInterfaces.TaskAttachment>;
getAttachmentContent(scopeIdentifier: string, hubName: string, planId: string, timelineId: string, recordId: string, type: string, name: string): Promise<NodeJS.ReadableStream>;
getAttachments(scopeIdentifier: string, hubName: string, planId: string, timelineId: string, recordId: string, type: string): Promise<TaskAgentInterfaces.TaskAttachment[]>;
appendTimelineRecordFeed(lines: TaskAgentInterfaces.TimelineRecordFeedLinesWrapper, scopeIdentifier: string, hubName: string, planId: string, timelineId: string, recordId: string): Promise<void>;
appendLogContent(customHeaders: any, contentStream: NodeJS.ReadableStream, scopeIdentifier: string, hubName: string, planId: string, logId: number): Promise<TaskAgentInterfaces.TaskLog>;
createLog(log: TaskAgentInterfaces.TaskLog, scopeIdentifier: string, hubName: string, planId: string): Promise<TaskAgentInterfaces.TaskLog>;
getLog(scopeIdentifier: string, hubName: string, planId: string, logId: number, startLine?: number, endLine?: number): Promise<string[]>;
getLogs(scopeIdentifier: string, hubName: string, planId: string): Promise<TaskAgentInterfaces.TaskLog[]>;
getPlanGroupsQueueMetrics(scopeIdentifier: string, hubName: string): Promise<TaskAgentInterfaces.TaskOrchestrationPlanGroupsQueueMetrics[]>;
getQueuedPlanGroups(scopeIdentifier: string, hubName: string, statusFilter?: TaskAgentInterfaces.PlanGroupStatus, count?: number): Promise<TaskAgentInterfaces.TaskOrchestrationQueuedPlanGroup[]>;
getQueuedPlanGroup(scopeIdentifier: string, hubName: string, planGroup: string): Promise<TaskAgentInterfaces.TaskOrchestrationQueuedPlanGroup>;
getPlan(scopeIdentifier: string, hubName: string, planId: string): Promise<TaskAgentInterfaces.TaskOrchestrationPlan>;
getRecords(scopeIdentifier: string, hubName: string, planId: string, timelineId: string, changeId?: number): Promise<TaskAgentInterfaces.TimelineRecord[]>;
updateRecords(records: VSSInterfaces.VssJsonCollectionWrapperV<TaskAgentInterfaces.TimelineRecord[]>, scopeIdentifier: string, hubName: string, planId: string, timelineId: string): Promise<TaskAgentInterfaces.TimelineRecord[]>;
createTimeline(timeline: TaskAgentInterfaces.Timeline, scopeIdentifier: string, hubName: string, planId: string): Promise<TaskAgentInterfaces.Timeline>;
deleteTimeline(scopeIdentifier: string, hubName: string, planId: string, timelineId: string): Promise<void>;
getTimeline(scopeIdentifier: string, hubName: string, planId: string, timelineId: string, changeId?: number, includeRecords?: boolean): Promise<TaskAgentInterfaces.Timeline>;
getTimelines(scopeIdentifier: string, hubName: string, planId: string): Promise<TaskAgentInterfaces.Timeline[]>;
}
export declare class TaskApi extends basem.ClientApiBase implements ITaskApi {
constructor(baseUrl: string, handlers: VsoBaseInterfaces.IRequestHandler[], options?: VsoBaseInterfaces.IRequestOptions);
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
* @param {string} type
*/
getPlanAttachments(scopeIdentifier: string, hubName: string, planId: string, type: string): Promise<TaskAgentInterfaces.TaskAttachment[]>;
/**
* @param {NodeJS.ReadableStream} contentStream - Content to upload
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
* @param {string} timelineId
* @param {string} recordId
* @param {string} type
* @param {string} name
*/
createAttachment(customHeaders: any, contentStream: NodeJS.ReadableStream, scopeIdentifier: string, hubName: string, planId: string, timelineId: string, recordId: string, type: string, name: string): Promise<TaskAgentInterfaces.TaskAttachment>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
* @param {string} timelineId
* @param {string} recordId
* @param {string} type
* @param {string} name
*/
getAttachment(scopeIdentifier: string, hubName: string, planId: string, timelineId: string, recordId: string, type: string, name: string): Promise<TaskAgentInterfaces.TaskAttachment>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
* @param {string} timelineId
* @param {string} recordId
* @param {string} type
* @param {string} name
*/
getAttachmentContent(scopeIdentifier: string, hubName: string, planId: string, timelineId: string, recordId: string, type: string, name: string): Promise<NodeJS.ReadableStream>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
* @param {string} timelineId
* @param {string} recordId
* @param {string} type
*/
getAttachments(scopeIdentifier: string, hubName: string, planId: string, timelineId: string, recordId: string, type: string): Promise<TaskAgentInterfaces.TaskAttachment[]>;
/**
* @param {TaskAgentInterfaces.TimelineRecordFeedLinesWrapper} lines
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
* @param {string} timelineId
* @param {string} recordId
*/
appendTimelineRecordFeed(lines: TaskAgentInterfaces.TimelineRecordFeedLinesWrapper, scopeIdentifier: string, hubName: string, planId: string, timelineId: string, recordId: string): Promise<void>;
/**
* @param {NodeJS.ReadableStream} contentStream - Content to upload
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
* @param {number} logId
*/
appendLogContent(customHeaders: any, contentStream: NodeJS.ReadableStream, scopeIdentifier: string, hubName: string, planId: string, logId: number): Promise<TaskAgentInterfaces.TaskLog>;
/**
* @param {TaskAgentInterfaces.TaskLog} log
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
*/
createLog(log: TaskAgentInterfaces.TaskLog, scopeIdentifier: string, hubName: string, planId: string): Promise<TaskAgentInterfaces.TaskLog>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
* @param {number} logId
* @param {number} startLine
* @param {number} endLine
*/
getLog(scopeIdentifier: string, hubName: string, planId: string, logId: number, startLine?: number, endLine?: number): Promise<string[]>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
*/
getLogs(scopeIdentifier: string, hubName: string, planId: string): Promise<TaskAgentInterfaces.TaskLog[]>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
*/
getPlanGroupsQueueMetrics(scopeIdentifier: string, hubName: string): Promise<TaskAgentInterfaces.TaskOrchestrationPlanGroupsQueueMetrics[]>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {TaskAgentInterfaces.PlanGroupStatus} statusFilter
* @param {number} count
*/
getQueuedPlanGroups(scopeIdentifier: string, hubName: string, statusFilter?: TaskAgentInterfaces.PlanGroupStatus, count?: number): Promise<TaskAgentInterfaces.TaskOrchestrationQueuedPlanGroup[]>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planGroup
*/
getQueuedPlanGroup(scopeIdentifier: string, hubName: string, planGroup: string): Promise<TaskAgentInterfaces.TaskOrchestrationQueuedPlanGroup>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
*/
getPlan(scopeIdentifier: string, hubName: string, planId: string): Promise<TaskAgentInterfaces.TaskOrchestrationPlan>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
* @param {string} timelineId
* @param {number} changeId
*/
getRecords(scopeIdentifier: string, hubName: string, planId: string, timelineId: string, changeId?: number): Promise<TaskAgentInterfaces.TimelineRecord[]>;
/**
* @param {VSSInterfaces.VssJsonCollectionWrapperV<TaskAgentInterfaces.TimelineRecord[]>} records
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
* @param {string} timelineId
*/
updateRecords(records: VSSInterfaces.VssJsonCollectionWrapperV<TaskAgentInterfaces.TimelineRecord[]>, scopeIdentifier: string, hubName: string, planId: string, timelineId: string): Promise<TaskAgentInterfaces.TimelineRecord[]>;
/**
* @param {TaskAgentInterfaces.Timeline} timeline
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
*/
createTimeline(timeline: TaskAgentInterfaces.Timeline, scopeIdentifier: string, hubName: string, planId: string): Promise<TaskAgentInterfaces.Timeline>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
* @param {string} timelineId
*/
deleteTimeline(scopeIdentifier: string, hubName: string, planId: string, timelineId: string): Promise<void>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
* @param {string} timelineId
* @param {number} changeId
* @param {boolean} includeRecords
*/
getTimeline(scopeIdentifier: string, hubName: string, planId: string, timelineId: string, changeId?: number, includeRecords?: boolean): Promise<TaskAgentInterfaces.Timeline>;
/**
* @param {string} scopeIdentifier - The project GUID to scope the request
* @param {string} hubName - The name of the server hub: "build" for the Build server or "rm" for the Release Management server
* @param {string} planId
*/
getTimelines(scopeIdentifier: string, hubName: string, planId: string): Promise<TaskAgentInterfaces.Timeline[]>;
} | the_stack |
'use strict';
import { GenericOAuth2Router } from '../common/generic-router';
import { IdpOptions, ExpressHandler, EmailMissingHandler, TwitterIdpConfig, IdentityProvider, AuthRequest, EndpointDefinition, CheckRefreshDecision, AuthResponse, ErrorLink } from '../common/types';
import { OidcProfile, Callback, WickedApi } from 'wicked-sdk';
const { debug, info, warn, error } = require('portal-env').Logger('portal-auth:twitter');
const Router = require('express').Router;
import { utils } from '../common/utils';
import { failMessage, failError, failOAuth, makeError } from '../common/utils-fail';
const request = require('request');
const passport = require('passport');
const Twitter = require('twitter');
const TwitterStrategy = require('passport-twitter');
/**
* Twitter IdP implementation.
*/
export class TwitterIdP implements IdentityProvider {
private genericFlow: GenericOAuth2Router;
private basePath: string;
private authMethodId: string;
private authMethodConfig: TwitterIdpConfig;
private options: IdpOptions;
private authenticateWithTwitter: ExpressHandler;
private authenticateCallback: ExpressHandler;
private emailMissingHandler: EmailMissingHandler;
constructor(basePath: string, authMethodId: string, authMethodConfig: TwitterIdpConfig, options: IdpOptions) {
this.genericFlow = new GenericOAuth2Router(basePath, authMethodId);
this.basePath = basePath;
this.authMethodId = authMethodId;
this.authMethodConfig = authMethodConfig;
// Verify configuration
if (!authMethodConfig.consumerKey)
throw new Error(`Twitter auth method "${authMethodId}": In auth method configuration, property "config", the property "consumerKey" is missing.`);
if (!authMethodConfig.consumerSecret)
throw new Error(`Twitter auth method "${authMethodId}": In auth-server configuration, property "config", the property "consumerSecret" is missing.`);
// Assemble the callback URL
const callbackUrl = `${options.externalUrlBase}/${authMethodId}/callback`;
info(`Twitter Authentication: Expected callback URL: ${callbackUrl}`);
// ========================
// PASSPORT INITIALIZATION
// ========================
// Use the authMethodId as passport "name"; which is subsequently used below
// to identify the strategy to use for a specific end point (see passport.authenticate)
const authenticateSettings = {
session: false,
failureRedirect: '/auth-server/failure'
};
passport.use(new TwitterStrategy({
consumerKey: authMethodConfig.consumerKey,
consumerSecret: authMethodConfig.consumerSecret,
callbackURL: callbackUrl
}, this.verifyProfile));
this.authenticateWithTwitter = passport.authenticate(authMethodId, authenticateSettings);
this.authenticateCallback = passport.authenticate(authMethodId, authenticateSettings);
// Various other handlers
// The email missing handler will be called if we do not get an email address back from
// Twitter, which may happen. It may be that we still already have the email address, in case
// the user already exists. This is checked in the createEmailMissingHandler.
this.emailMissingHandler = this.genericFlow.createEmailMissingHandler(authMethodId, this.continueAuthenticate);
this.genericFlow.initIdP(this);
}
public getType() {
return "twitter";
}
public supportsPrompt(): boolean {
return false;
}
public getRouter() {
return this.genericFlow.getRouter();
};
public authorizeWithUi(req, res, next, authRequest: AuthRequest) {
// Do your thing...
// Redirect to the Twitter login page
return this.authenticateWithTwitter(req, res);
};
public endpoints(): EndpointDefinition[] {
return [
{
method: 'get',
uri: '/callback',
middleware: this.authenticateCallback,
handler: this.callbackHandler
},
{
method: 'post',
uri: '/emailmissing',
handler: this.genericFlow.createEmailMissingPostHandler(this.authMethodId, this.continueAuthenticate)
}
];
};
public authorizeByUserPass(user: string, pass: string, callback: Callback<AuthResponse>) {
// Verify username and password, if possible.
// For Twitter, this is not possible, so we will just return an
// error message.
return failOAuth(400, 'unsupported_grant_type', 'Twitter does not support authorizing headless with username and password', callback);
}
public checkRefreshToken(tokenInfo, apiInfo: WickedApi, callback: Callback<CheckRefreshDecision>) {
// Decide whether it's okay to refresh this token or not, e.g.
// by checking that the user is still valid in your database or such;
// for 3rd party IdPs, this may be tricky. For Twitter, we will just allow it.
return callback(null, {
allowRefresh: true
});
}
public getErrorLinks(): ErrorLink {
return null;
}
// ========================
// HELPER METHODS
// ========================
// Instance function, on purpose; this is used as a passport callback
private verifyProfile = (token, tokenSecret, profile, done: Callback<AuthResponse>) => {
debug('Twitter Authentication succeeded.');
this.createAuthResponse(profile, token, tokenSecret, function (err, authResponse) {
if (err) {
error('createAuthResponse failed.');
error(err);
return done(err);
}
debug('Twitter authResponse:');
debug(authResponse);
done(null, authResponse);
});
};
private createAuthResponse(profile, token: string, tokenSecret: string, callback: Callback<AuthResponse>): void {
debug('normalizeProfile()');
const nameGuess = utils.splitName(profile.displayName, profile.username);
const email = null; // We don't get email addresses from Twitter as a default
const email_verified = false;
const customId = `${this.authMethodId}:${profile.id}`;
debug(`Twitter token: ${token}`);
debug(`Twitter tokenSecret: ${tokenSecret}`);
//debug('Twitter raw profile:');
//debug(profile);
const defaultProfile = {
sub: customId,
username: utils.makeUsername(nameGuess.fullName, profile.username),
preferred_username: utils.makeUsername(nameGuess.fullName, profile.username),
name: nameGuess.fullName,
given_name: nameGuess.firstName,
family_name: nameGuess.lastName,
email: email,
email_verified: email_verified
} as OidcProfile;
// To read the email address, we need the twitter client. Twitter requires
// signing all requests, and thus it's easier to use a library for that rather
// than trying to roll our own signing...
const twitterClient = new Twitter({
consumer_key: this.authMethodConfig.consumerKey,
consumer_secret: this.authMethodConfig.consumerSecret,
access_token_key: token,
access_token_secret: tokenSecret
});
// See https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
const twitterParams = { include_email: false };
debug('Attempting to verify Twitter credentials...');
twitterClient.get('account/verify_credentials', twitterParams, (err, extendedProfile, response) => {
if (err)
return callback(err);
debug('Successfully verified Twitter credentials, here are the results:');
debug(extendedProfile);
const jsonBody = utils.getJson(extendedProfile);
if (jsonBody.email) {
// If we have an email address, Twitter assures it's already verified.
defaultProfile.email = jsonBody.email;
defaultProfile.email_verified = true;
}
const authResponse = {
userId: null,
customId: customId,
defaultGroups: [],
defaultProfile: defaultProfile
};
debug('Twitter authResponse:');
debug(authResponse);
callback(null, authResponse);
});
};
// We will be called back (hopefully) on this end point via the emailMissingPostHandler (in utils.js)
// It's a callback -> use the => notation to keep the correct "this" reference.
private continueAuthenticate = (req, res, next, email) => {
debug(`continueAuthenticate(${this.authMethodId})`);
const session = utils.getSession(req, this.authMethodId);
if (!session ||
!session.tmpAuthResponse) {
return failMessage(500, 'Invalid state: Was expecting a temporary auth response.', next);
}
const authResponse = session.tmpAuthResponse;
delete session.tmpAuthResponse;
authResponse.defaultProfile.email = email;
authResponse.defaultProfile.email_verified = false;
return this.genericFlow.continueAuthorizeFlow(req, res, next, authResponse);
};
/**
* Twitter callback handler; this is the endpoint which is called when Twitter
* returns with a success or failure response.
*
* The instance function notation (=>) is on purpose, as this is a callback function.
*/
private callbackHandler = (req, res, next) => {
// Here we want to assemble the default profile and stuff.
debug('callbackHandler()');
// The authResponse is now in req.user (for this call), and we can pass that on as an authResponse
// to continueAuthorizeFlow. Note the usage of "session: false", so that this data is NOT stored
// automatically in the user session, which passport usually does by default.
const authResponse = req.user;
// Now we have to check whether we received an email adress from Twitter; if not, we need to ask
// the user for one.
if (authResponse.defaultProfile &&
authResponse.defaultProfile.email) {
// Yes, all is good, we can go back to the generic router
return this.genericFlow.continueAuthorizeFlow(req, res, next, authResponse);
}
// No email from Twitter, let's ask for one, but we must store the temporary authResponse for later
// usage, in the session. It may be that emailMissingHandler is able to retrieve the email address
// from wicked, if the user is already registered. Otherwise the user will be asked.
utils.getSession(req, this.authMethodId).tmpAuthResponse = authResponse;
return this.emailMissingHandler(req, res, next, authResponse.customId);
};
} | the_stack |
import { UIDLUtils } from '@teleporthq/teleport-shared'
import {
ProjectUIDL,
UIDLElement,
ComponentUIDL,
UIDLNode,
UIDLStyleSetDefinition,
UIDLStaticValue,
UIDLExternalDependency,
UIDLElementNodeProjectReferencedStyle,
UIDLStyleValue,
UIDLElementNodeInlineReferencedStyle,
UIDLReferencedStyles,
UIDLStyleSetTokenReference,
ComponentValidationError,
} from '@teleporthq/teleport-types'
// Prop definitions and state definitions should have different keys
export const checkForDuplicateDefinitions = (input: ComponentUIDL) => {
const props = Object.keys(input.propDefinitions || {})
const states = Object.keys(input.stateDefinitions || {})
const imports = Object.keys(input.importDefinitions || {})
props
.filter((x) => states.includes(x) || imports.includes(x))
.forEach((duplicate) =>
console.warn(
`\n"${duplicate}" is defined both as a prop and as a state. If you are using VUE Code Generators this can cause bad behavior.`
)
)
}
// In "repeat" node:
// If index is used, "useIndex" must be declared in "meta"
// If custom local variable is used, it's name must be specified inside "meta" as "iteratorName"
export const checkForLocalVariables = (input: ComponentUIDL) => {
const errors: string[] = []
UIDLUtils.traverseRepeats(input.node, (repeatContent) => {
UIDLUtils.traverseNodes(repeatContent.node, (childNode) => {
if (childNode.type === 'dynamic' && childNode.content.referenceType === 'local') {
if (childNode.content.id === 'index') {
if (!repeatContent.meta.useIndex) {
const errorMsg = `\nIndex variable is used but the "useIndex" meta information is false.`
errors.push(errorMsg)
}
// we are dealing with local index here
return
}
if (!validLocalVariableUsage(childNode.content.id, repeatContent.meta.iteratorName)) {
const errorMsg = `\n"${childNode.content.id}" is used in the "repeat" structure but the iterator name has this value: "${repeatContent.meta.iteratorName}"`
errors.push(errorMsg)
}
}
})
})
return errors
}
const validLocalVariableUsage = (dynamicId: string, repeatIteratorName: string) => {
const iteratorName = repeatIteratorName || 'item'
if (!dynamicId.includes('.')) {
return dynamicId === iteratorName
}
const dynamicIdRoot = dynamicId.split('.')[0]
return dynamicIdRoot === iteratorName
}
/* All referenced props, states and importRefs should be previously defined in the
"propDefinitions" and "stateDefinitions" and "importDefinitions" sections
If props or states are defined and not used, a warning witll be displayed */
export const checkDynamicDefinitions = (input: Record<string, unknown>) => {
const propKeys = Object.keys(input.propDefinitions || {})
const stateKeys = Object.keys(input.stateDefinitions || {})
let importKeys = Object.keys(input.importDefinitions || {})
const componentStyleSetKyes = Object.keys(input.styleSetDefinitions || {})
const importDefinitions: { [key: string]: UIDLExternalDependency } = (input?.importDefinitions ??
{}) as unknown as { [key: string]: UIDLExternalDependency }
if (Object.keys(importKeys).length > 0) {
importKeys = importKeys.reduce((acc, importRef) => {
if (importDefinitions[importRef]?.meta?.importJustPath) {
return acc
}
acc.push(importRef)
return acc
}, [])
}
const usedPropKeys: string[] = []
const usedStateKeys: string[] = []
const usedImportKeys: string[] = []
const errors: string[] = []
UIDLUtils.traverseNodes(input.node as UIDLNode, (node) => {
if (node.type === 'element') {
Object.keys(node.content?.events || {}).forEach((eventKey) => {
node.content.events[eventKey].forEach((event) => {
if (event.type === 'stateChange' && !stateKeys.includes(event.modifies)) {
const errorMsg = `"${event.modifies}" is used in events, but not defined. Please add it in stateDefinitions`
errors.push(errorMsg)
return
}
if (event.type === 'propCall' && !propKeys.includes(event.calls)) {
errors.push(
`"${event.calls}" is used in events, but missing from propDefinitons. Please add it in propDefinitions `
)
return
}
})
})
const dynamicVariants: string[] = []
Object.values(node.content?.referencedStyles || {}).forEach((styleRef) => {
if (
styleRef.content.mapType === 'component-referenced' &&
styleRef.content.content.type === 'dynamic'
) {
if (styleRef.content.content.content.referenceType === 'prop') {
const referencedProp = styleRef.content.content.content.id
if (!dynamicPathExistsInDefinitions(referencedProp, propKeys)) {
const errorMsg = `"${referencedProp}" is used but not defined. Please add it in propDefinitions`
errors.push(errorMsg)
return
}
dynamicVariants.push(referencedProp)
usedPropKeys.push(referencedProp)
}
if (styleRef.content.content.content.referenceType === 'comp') {
const compStyleRefId = styleRef.content.content.content.id
if (!componentStyleSetKyes.includes(compStyleRefId)) {
errors.push(
`${compStyleRefId} is used, but not defined in Component Style Sheet in ${input.name}. Please add it in StyleSetDefinitions of the component`
)
}
}
}
})
if (dynamicVariants.length > 1) {
errors.push(`Node ${
node.content?.name || node.content?.key
} is using multiple dynamic variants using propDefinitions.
We can have only one dynamic variant at once`)
}
}
if (node.type === 'dynamic' && node.content.referenceType === 'prop') {
if (!dynamicPathExistsInDefinitions(node.content.id, propKeys)) {
const errorMsg = `"${node.content.id}" is used but not defined. Please add it in propDefinitions`
errors.push(errorMsg)
}
// for member expression we check the root
// if value has no `.` it will be checked as it is
const dynamicIdRoot = node.content.id.split('.')[0]
usedPropKeys.push(dynamicIdRoot)
}
if (node.type === 'dynamic' && node.content.referenceType === 'state') {
if (!dynamicPathExistsInDefinitions(node.content.id, stateKeys)) {
const errorMsg = `\n"${node.content.id}" is used but not defined. Please add it in stateDefinitions`
errors.push(errorMsg)
}
// for member expression we check the root
// if value has no `.` it will be checked as it is
const dynamicIdRoot = node.content.id.split('.')[0]
usedStateKeys.push(dynamicIdRoot)
}
if (node.type === 'import') {
if (!dynamicPathExistsInDefinitions(node.content.id, importKeys)) {
const errorMsg = `\n"${node.content.id}" is used but not defined. Please add it in importDefinitions`
errors.push(errorMsg)
}
// for member expression we check the root
// if value has no `.` it will be checked as it is
const dynamicIdRoot = node.content.id.split('.')[0]
usedImportKeys.push(dynamicIdRoot)
}
})
propKeys
.filter((x) => !usedPropKeys.includes(x))
.forEach((diff) =>
console.warn(`"${diff}" is defined in propDefinitions but it is not used in the UIDL.`)
)
stateKeys
.filter((x) => !usedStateKeys.includes(x))
.forEach((diff) =>
console.warn(`"${diff}" is defined in stateDefinitions but it is not used in the UIDL.`)
)
importKeys
.filter((x) => !usedImportKeys.includes(x))
.forEach((diff) =>
console.warn(`"${diff}" is defined in importDefinitions but it is not used in the UIDL.`)
)
return errors
}
const dynamicPathExistsInDefinitions = (path: string, defKeys: string[]) => {
if (!path.includes('.')) {
// prop/state is a scalar value, not a dot notation
return defKeys.includes(path)
}
// TODO: Expand validation logic to check if the path exists on the prop/state definition
// ex: if prop reference is `user.name`, we should check that prop type is object and has a valid field name
const rootIdentifier = path.split('.')[0]
return defKeys.includes(rootIdentifier)
}
// A projectUIDL must contain "route" key
export const checkRouteDefinition = (input: ProjectUIDL) => {
const errors = []
const keys = Object.keys(input.root.stateDefinitions || {})
if (!keys.includes('route')) {
const errorMsg = 'Route is not defined in stateDefinitions'
errors.push(errorMsg)
}
return errors
}
// All referenced components inside of the projectUIDL should be defined
// in the components section and all the project-referenced styles and tokens
export const checkComponentExistenceAndReferences = (input: ProjectUIDL) => {
const errors: string[] = []
const components = Object.keys(input.components || {})
const styleSetDefinitions = Object.keys(input.root?.styleSetDefinitions || {})
const tokens: string[] = Object.keys(input.root?.designLanguage?.tokens || {})
const nodesToParse = [
input.root.node,
...Object.values(input.components || {}).map((component) => component.node),
]
let usedReferencedStyles: string[] = []
if (input.root?.styleSetDefinitions) {
Object.values(input.root.styleSetDefinitions || {}).forEach((style) => {
const { content, conditions = [] } = style
errors.push(...checkForTokensInstyles(content, tokens))
conditions.forEach((condition) => {
if (condition?.content) {
errors.push(...checkForTokensInstyles(condition.content, tokens))
}
})
})
}
nodesToParse.forEach((node) => {
UIDLUtils.traverseElements(node, (element) => {
/* Checking for project-referenced styles */
if (element?.referencedStyles) {
const { errorsInRferences, usedStyleRefrences } = checkForReferencedStylesUsed(
element.referencedStyles,
styleSetDefinitions,
tokens
)
errors.push(...errorsInRferences)
usedReferencedStyles = [...usedReferencedStyles, ...usedStyleRefrences]
}
/* Checking for token references used in styles */
if (element?.style) {
errors.push(...checkForTokensInstyles(element.style, tokens))
}
if (
element.dependency &&
element.dependency.type === 'local' &&
!components.includes(element.semanticType)
) {
const errorMsg = `\nThe component "${element.semanticType}" is not defined in the UIDL's component section.`
errors.push(errorMsg)
}
})
})
styleSetDefinitions.forEach((key) => {
if (!usedReferencedStyles.includes(key)) {
console.warn(`${key} styleSet is defined but not used in the project.`)
}
})
return errors
}
const checkForReferencedStylesUsed = (
referencedStyles: UIDLReferencedStyles,
styleSetDefinitions: string[],
tokens: string[]
) => {
const errorsInRferences: string[] = []
const usedStyleRefrences: string[] = []
Object.values(referencedStyles || {}).forEach((styleRef) => {
const { mapType } = styleRef.content
if (mapType === 'inlined') {
errorsInRferences.push(
...checkForTokensInstyles(
(styleRef as UIDLElementNodeInlineReferencedStyle).content.styles,
tokens
)
)
}
if (mapType === 'project-referenced') {
const { referenceId } = (styleRef as UIDLElementNodeProjectReferencedStyle).content
usedStyleRefrences.push(referenceId)
if (!styleSetDefinitions.includes(referenceId)) {
errorsInRferences.push(
`\n ${referenceId} is missing from the styleSetDefinitions, please check the reference id.`
)
}
}
})
return {
errorsInRferences,
usedStyleRefrences,
}
}
const checkForTokensInstyles = (styles: Record<string, UIDLStyleValue>, tokens: string[]) => {
const errors: string[] = []
Object.values(styles || {}).forEach((style: UIDLStyleValue) => {
if (
style.type === 'dynamic' &&
style.content.referenceType === 'token' &&
!tokens.includes(style.content.id)
) {
errors.push(`\nToken ${style.content.id} is missing from the project UIDL.`)
}
})
return errors
}
// All components should have the same key as the value of their name key
// Example:
// "components": {
// "OneComponent": {
// "name": "OneComponent",
// ..
// }
// }
export const checkComponentNaming = (input: ProjectUIDL) => {
const errors: string[] = []
const namesUsed = Object.keys(input.components || {})
const diffs = namesUsed.filter((name) => input.components[name].name !== name)
if (diffs.length > 0) {
const errorMsg = `\nThe following components have different name than their key: ${diffs}`
errors.push(errorMsg)
}
return errors
}
export const checkProjectStyleSet = (input: ProjectUIDL) => {
const errors: string[] = []
const styleSet = input.root.styleSetDefinitions
if (styleSet) {
Object.values(styleSet).forEach((styleSetObj: UIDLStyleSetDefinition) => {
const { content, conditions = [] } = styleSetObj
Object.values(conditions).forEach((style) => {
errors.push(...checStylekContentForErrors(style.content))
})
errors.push(...checStylekContentForErrors(content))
})
}
return errors
}
export const checStylekContentForErrors = (
content: Record<string, UIDLStaticValue | UIDLStyleSetTokenReference>
) => {
const errors: string[] = []
Object.values(content).forEach((styleContent) => {
if (styleContent.type === 'dynamic' && styleContent.content.referenceType !== 'token') {
errors.push(`Dynamic nodes in styleSetDefinitions supports only tokens`)
}
if (
styleContent.type === 'static' &&
typeof styleContent.content !== 'string' &&
typeof styleContent.content !== 'number'
) {
errors.push(
`Project Style sheet / styleSetDefinitions only support styles with static
content and dynamic tokens, received ${styleContent}`
)
}
})
return errors
}
// The "root" node should contain only elements of type "conditional"
export const checkRootComponent = (input: ProjectUIDL) => {
const errors = []
const routeNaming: string[] = []
const rootNode = input.root.node.content as UIDLElement
rootNode.children.forEach((child) => {
if (child.type !== 'conditional') {
const errorMsg = `\nRoot Node contains elements of type "${child.type}". It should contain only elements of type "conditional"`
errors.push(errorMsg)
} else {
routeNaming.push(child.content.value.toString())
}
})
const routeValues = input.root.stateDefinitions.route.values
if (!routeValues || routeValues.length <= 0) {
errors.push(
'\nThe `route` state definition from the root node does not contain the possible route values'
)
} else {
input.root.stateDefinitions.route.values
.filter((route) => !routeNaming.includes(route.value.toString()))
.forEach((route) => {
const errorMsg = `\nRoot Node contains a route that don't have a specified state: ${route.value}.`
errors.push(errorMsg)
})
}
return errors
}
// The errors should be displayed in a human-readeable way
export const formatErrors = (errors: Array<{ kind: string; at: string; message: string }>) => {
const listOfErrors: string[] = []
errors.forEach((error) => {
const message = `\n - Path ${error.at}: ${error.message}. \n is a ${error.kind} \n`
listOfErrors.push(message)
})
return `UIDL Format Validation Error. Please check the following: ${listOfErrors}`
}
export const validateNulls = (uidl: Record<string, unknown>) => {
return JSON.parse(JSON.stringify(uidl), (key, value) => {
if (value === undefined || value == null) {
throw new ComponentValidationError(`Validation error, Received ${value} at ${key}`)
}
return value
})
} | the_stack |
import { css, html, LitElement, nothing } from 'lit';
import { property, query, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { copy } from './copy-to-clipboard.js';
interface ServerInfo {
vaadinVersion: string;
flowVersion: string;
javaVersion: string;
osVersion: string;
}
interface Feature {
id: string;
title: string;
moreInfoLink: string;
requiresServerRestart: boolean;
enabled: boolean;
}
interface Tab {
id: 'log' | 'info' | 'features';
title: string;
render: () => unknown;
activate?: () => void;
}
enum ConnectionStatus {
ACTIVE = 'active',
INACTIVE = 'inactive',
UNAVAILABLE = 'unavailable',
ERROR = 'error'
}
export class Connection extends Object {
static HEARTBEAT_INTERVAL = 180000;
status: ConnectionStatus = ConnectionStatus.UNAVAILABLE;
webSocket?: WebSocket;
constructor(url?: string) {
super();
if (url) {
this.webSocket = new WebSocket(url);
this.webSocket.onmessage = (msg) => this.handleMessage(msg);
this.webSocket.onerror = (err) => this.handleError(err);
this.webSocket.onclose = (_) => {
if (this.status !== ConnectionStatus.ERROR) {
this.setStatus(ConnectionStatus.UNAVAILABLE);
}
this.webSocket = undefined;
};
}
setInterval(() => {
if (this.webSocket && self.status !== ConnectionStatus.ERROR && this.status !== ConnectionStatus.UNAVAILABLE) {
this.webSocket.send('');
}
}, Connection.HEARTBEAT_INTERVAL);
}
onHandshake() {
// Intentionally empty
}
onReload() {
// Intentionally empty
}
onConnectionError(_: string) {
// Intentionally empty
}
onStatusChange(_: ConnectionStatus) {
// Intentionally empty
}
onMessage(message: any) {
// eslint-disable-next-line no-console
console.error('Unknown message received from the live reload server:', message);
}
handleMessage(msg: any) {
let json;
try {
json = JSON.parse(msg.data);
} catch (e: any) {
this.handleError(`[${e.name}: ${e.message}`);
return;
}
if (json.command === 'hello') {
this.setStatus(ConnectionStatus.ACTIVE);
this.onHandshake();
} else if (json.command === 'reload') {
if (this.status === ConnectionStatus.ACTIVE) {
this.onReload();
}
} else {
this.onMessage(json);
}
}
handleError(msg: any) {
// eslint-disable-next-line no-console
console.error(msg);
this.setStatus(ConnectionStatus.ERROR);
if (msg instanceof Event && this.webSocket) {
this.onConnectionError(`Error in WebSocket connection to ${this.webSocket.url}`);
} else {
this.onConnectionError(msg);
}
}
setActive(yes: boolean) {
if (!yes && this.status === ConnectionStatus.ACTIVE) {
this.setStatus(ConnectionStatus.INACTIVE);
} else if (yes && this.status === ConnectionStatus.INACTIVE) {
this.setStatus(ConnectionStatus.ACTIVE);
}
}
setStatus(status: ConnectionStatus) {
if (this.status !== status) {
this.status = status;
this.onStatusChange(status);
}
}
private send(command: string, data: any) {
const message = { command, data };
this.webSocket!.send(JSON.stringify(message));
}
setFeature(featureId: string, enabled: boolean) {
this.send('setFeature', { featureId, enabled });
}
sendTelemetry(browserData: any) {
this.send('reportTelemetry', { browserData });
}
}
enum MessageType {
LOG = 'log',
INFORMATION = 'information',
WARNING = 'warning',
ERROR = 'error'
}
interface Message {
id: number;
type: MessageType;
message: string;
details?: string;
link?: string;
persistentId?: string;
dontShowAgain: boolean;
deleted: boolean;
}
export class VaadinDevmodeGizmo extends LitElement {
static BLUE_HSL = css`206, 100%, 70%`;
static GREEN_HSL = css`145, 80%, 42%`;
static GREY_HSL = css`0, 0%, 50%`;
static YELLOW_HSL = css`38, 98%, 64%`;
static RED_HSL = css`355, 100%, 68%`;
static MAX_LOG_ROWS = 1000;
static get styles() {
return css`
:host {
--gizmo-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell,
'Helvetica Neue', sans-serif;
--gizmo-font-family-monospace: SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New',
monospace;
--gizmo-font-size: 0.8125rem;
--gizmo-font-size-small: 0.75rem;
--gizmo-text-color: rgba(255, 255, 255, 0.8);
--gizmo-text-color-secondary: rgba(255, 255, 255, 0.65);
--gizmo-text-color-emphasis: rgba(255, 255, 255, 0.95);
--gizmo-text-color-active: rgba(255, 255, 255, 1);
--gizmo-background-color-inactive: rgba(45, 45, 45, 0.25);
--gizmo-background-color-active: rgba(45, 45, 45, 0.98);
--gizmo-background-color-active-blurred: rgba(45, 45, 45, 0.85);
--gizmo-border-radius: 0.5rem;
--gizmo-box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.05), 0 4px 12px -2px rgba(0, 0, 0, 0.4);
--gizmo-blue-hsl: ${this.BLUE_HSL};
--gizmo-blue-color: hsl(var(--gizmo-blue-hsl));
--gizmo-green-hsl: ${this.GREEN_HSL};
--gizmo-green-color: hsl(var(--gizmo-green-hsl));
--gizmo-grey-hsl: ${this.GREY_HSL};
--gizmo-grey-color: hsl(var(--gizmo-grey-hsl));
--gizmo-yellow-hsl: ${this.YELLOW_HSL};
--gizmo-yellow-color: hsl(var(--gizmo-yellow-hsl));
--gizmo-red-hsl: ${this.RED_HSL};
--gizmo-red-color: hsl(var(--gizmo-red-hsl));
/* Needs to be in ms, used in JavaScript as well */
--gizmo-transition-duration: 180ms;
all: initial;
direction: ltr;
cursor: default;
font: normal 400 var(--gizmo-font-size) / 1.125rem var(--gizmo-font-family);
color: var(--gizmo-text-color);
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
position: fixed;
z-index: 20000;
pointer-events: none;
bottom: 0;
right: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column-reverse;
align-items: flex-end;
}
.gizmo {
pointer-events: auto;
display: flex;
align-items: center;
position: fixed;
z-index: inherit;
right: 0.5rem;
bottom: 0.5rem;
min-width: 1.75rem;
height: 1.75rem;
max-width: 1.75rem;
border-radius: 0.5rem;
padding: 0.375rem;
box-sizing: border-box;
background-color: var(--gizmo-background-color-inactive);
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.05);
color: var(--gizmo-text-color);
transition: var(--gizmo-transition-duration);
white-space: nowrap;
line-height: 1rem;
}
.gizmo:hover,
.gizmo.active {
background-color: var(--gizmo-background-color-active);
box-shadow: var(--gizmo-box-shadow);
}
.gizmo.active {
max-width: calc(100% - 1rem);
}
.gizmo .gizmo-icon {
flex: none;
pointer-events: none;
display: inline-block;
width: 1rem;
height: 1rem;
fill: #fff;
transition: var(--gizmo-transition-duration);
margin: 0;
}
.gizmo.active .gizmo-icon {
opacity: 0;
position: absolute;
transform: scale(0.5);
}
.gizmo .status-blip {
flex: none;
display: block;
width: 6px;
height: 6px;
border-radius: 50%;
z-index: 20001;
background: var(--gizmo-grey-color);
position: absolute;
top: -1px;
right: -1px;
}
.gizmo .status-description {
overflow: hidden;
text-overflow: ellipsis;
padding: 0 0.25rem;
}
.gizmo.error {
background-color: hsla(var(--gizmo-red-hsl), 0.15);
animation: bounce 0.5s;
animation-iteration-count: 2;
}
.switch {
display: inline-flex;
align-items: center;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
position: absolute;
}
.switch .slider {
display: block;
flex: none;
width: 28px;
height: 18px;
border-radius: 9px;
background-color: rgba(255, 255, 255, 0.3);
transition: var(--gizmo-transition-duration);
margin-right: 0.5rem;
}
.switch:focus-within .slider,
.switch .slider:hover {
background-color: rgba(255, 255, 255, 0.35);
transition: none;
}
.switch input:focus-visible ~ .slider {
box-shadow: 0 0 0 2px var(--gizmo-background-color-active), 0 0 0 4px var(--gizmo-blue-color);
}
.switch .slider::before {
content: '';
display: block;
margin: 2px;
width: 14px;
height: 14px;
background-color: #fff;
transition: var(--gizmo-transition-duration);
border-radius: 50%;
}
.switch input:checked + .slider {
background-color: var(--gizmo-green-color);
}
.switch input:checked + .slider::before {
transform: translateX(10px);
}
.switch input:disabled + .slider::before {
background-color: var(--gizmo-grey-color);
}
.window.hidden {
opacity: 0;
transform: scale(0);
position: absolute;
}
.window.visible {
transform: none;
opacity: 1;
pointer-events: auto;
}
.window.visible ~ .gizmo {
opacity: 0;
pointer-events: none;
}
.window.visible ~ .gizmo .gizmo-icon,
.window.visible ~ .gizmo .status-blip {
transition: none;
opacity: 0;
}
.window {
border-radius: var(--gizmo-border-radius);
overflow: hidden;
margin: 0.5rem;
width: 30rem;
max-width: calc(100% - 1rem);
max-height: calc(100vh - 1rem);
flex-shrink: 1;
background-color: var(--gizmo-background-color-active);
color: var(--gizmo-text-color);
transition: var(--gizmo-transition-duration);
transform-origin: bottom right;
display: flex;
flex-direction: column;
box-shadow: var(--gizmo-box-shadow);
outline: none;
}
.window-toolbar {
display: flex;
flex: none;
align-items: center;
padding: 0.375rem;
white-space: nowrap;
order: 1;
background-color: rgba(0, 0, 0, 0.2);
gap: 0.5rem;
}
.tab {
color: var(--gizmo-text-color-secondary);
font: inherit;
font-size: var(--gizmo-font-size-small);
font-weight: 500;
line-height: 1;
padding: 0.25rem 0.375rem;
background: none;
border: none;
margin: 0;
border-radius: 0.25rem;
transition: var(--gizmo-transition-duration);
}
.tab:hover,
.tab.active {
color: var(--gizmo-text-color-active);
}
.tab.active {
background-color: rgba(255, 255, 255, 0.12);
}
.tab.unreadErrors::after {
content: '•';
color: hsl(var(--gizmo-red-hsl));
font-size: 1.5rem;
position: absolute;
transform: translate(0, -50%);
}
.ahreflike {
font-weight: 500;
color: var(--gizmo-text-color-secondary);
text-decoration: underline;
cursor: pointer;
}
.ahreflike:hover {
color: var(--gizmo-text-color-emphasis);
}
.button {
all: initial;
font-family: inherit;
font-size: var(--gizmo-font-size-small);
line-height: 1;
white-space: nowrap;
background-color: rgba(0, 0, 0, 0.2);
color: inherit;
font-weight: 600;
padding: 0.25rem 0.375rem;
border-radius: 0.25rem;
}
.button:focus,
.button:hover {
color: var(--gizmo-text-color-emphasis);
}
.minimize-button {
flex: none;
width: 1rem;
height: 1rem;
color: inherit;
background-color: transparent;
border: 0;
padding: 0;
margin: 0 0 0 auto;
opacity: 0.8;
}
.minimize-button:hover {
opacity: 1;
}
.minimize-button svg {
max-width: 100%;
}
.message.information {
--gizmo-notification-color: var(--gizmo-blue-color);
}
.message.warning {
--gizmo-notification-color: var(--gizmo-yellow-color);
}
.message.error {
--gizmo-notification-color: var(--gizmo-red-color);
}
.message {
display: flex;
padding: 0.1875rem 0.75rem 0.1875rem 2rem;
background-clip: padding-box;
}
.message.log {
padding-left: 0.75rem;
}
.message-content {
margin-right: 0.5rem;
-webkit-user-select: text;
-moz-user-select: text;
user-select: text;
}
.message-heading {
position: relative;
display: flex;
align-items: center;
margin: 0.125rem 0;
}
.message.log {
color: var(--gizmo-text-color-secondary);
}
.message:not(.log) .message-heading {
font-weight: 500;
}
.message.has-details .message-heading {
color: var(--gizmo-text-color-emphasis);
font-weight: 600;
}
.message-heading::before {
position: absolute;
margin-left: -1.5rem;
display: inline-block;
text-align: center;
font-size: 0.875em;
font-weight: 600;
line-height: calc(1.25em - 2px);
width: 14px;
height: 14px;
box-sizing: border-box;
border: 1px solid transparent;
border-radius: 50%;
}
.message.information .message-heading::before {
content: 'i';
border-color: currentColor;
color: var(--gizmo-notification-color);
}
.message.warning .message-heading::before,
.message.error .message-heading::before {
content: '!';
color: var(--gizmo-background-color-active);
background-color: var(--gizmo-notification-color);
}
.features-tray {
padding: 0.75rem;
flex: auto;
overflow: auto;
animation: fade-in var(--gizmo-transition-duration) ease-in;
user-select: text;
}
.features-tray p {
margin-top: 0;
color: var(--gizmo-text-color-secondary);
}
.features-tray .feature {
display: flex;
align-items: center;
gap: 1rem;
}
.message .message-details {
font-weight: 400;
color: var(--gizmo-text-color-secondary);
margin: 0.25rem 0;
}
.message .message-details[hidden] {
display: none;
}
.message .message-details p {
display: inline;
margin: 0;
margin-right: 0.375em;
word-break: break-word;
}
.message .persist {
color: var(--gizmo-text-color-secondary);
white-space: nowrap;
margin: 0.375rem 0;
display: flex;
align-items: center;
position: relative;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
.message .persist::before {
content: '';
width: 1em;
height: 1em;
border-radius: 0.2em;
margin-right: 0.375em;
background-color: rgba(255, 255, 255, 0.3);
}
.message .persist:hover::before {
background-color: rgba(255, 255, 255, 0.4);
}
.message .persist.on::before {
background-color: rgba(255, 255, 255, 0.9);
}
.message .persist.on::after {
content: '';
order: -1;
position: absolute;
width: 0.75em;
height: 0.25em;
border: 2px solid var(--gizmo-background-color-active);
border-width: 0 0 2px 2px;
transform: translate(0.05em, -0.05em) rotate(-45deg) scale(0.8, 0.9);
}
.message .dismiss-message {
font-weight: 600;
align-self: stretch;
display: flex;
align-items: center;
padding: 0 0.25rem;
margin-left: 0.5rem;
color: var(--gizmo-text-color-secondary);
}
.message .dismiss-message:hover {
color: var(--gizmo-text-color);
}
.notification-tray {
display: flex;
flex-direction: column-reverse;
align-items: flex-end;
margin: 0.5rem;
flex: none;
}
.window.hidden + .notification-tray {
margin-bottom: 3rem;
}
.notification-tray .message {
pointer-events: auto;
background-color: var(--gizmo-background-color-active);
color: var(--gizmo-text-color);
max-width: 30rem;
box-sizing: border-box;
border-radius: var(--gizmo-border-radius);
margin-top: 0.5rem;
transition: var(--gizmo-transition-duration);
transform-origin: bottom right;
animation: slideIn var(--gizmo-transition-duration);
box-shadow: var(--gizmo-box-shadow);
padding-top: 0.25rem;
padding-bottom: 0.25rem;
}
.notification-tray .message.animate-out {
animation: slideOut forwards var(--gizmo-transition-duration);
}
.notification-tray .message .message-details {
max-height: 10em;
overflow: hidden;
}
.message-tray {
flex: auto;
overflow: auto;
max-height: 20rem;
user-select: text;
}
.message-tray .message {
animation: fade-in var(--gizmo-transition-duration) ease-in;
padding-left: 2.25rem;
}
.message-tray .message.warning {
background-color: hsla(var(--gizmo-yellow-hsl), 0.09);
}
.message-tray .message.error {
background-color: hsla(var(--gizmo-red-hsl), 0.09);
}
.message-tray .message.error .message-heading {
color: hsl(var(--gizmo-red-hsl));
}
.message-tray .message.warning .message-heading {
color: hsl(var(--gizmo-yellow-hsl));
}
.message-tray .message + .message {
border-top: 1px solid rgba(255, 255, 255, 0.07);
}
.message-tray .dismiss-message,
.message-tray .persist {
display: none;
}
.info-tray {
padding: 0.75rem;
position: relative;
flex: auto;
overflow: auto;
animation: fade-in var(--gizmo-transition-duration) ease-in;
user-select: text;
}
.info-tray dl {
margin: 0;
display: grid;
grid-template-columns: max-content 1fr;
column-gap: 0.75rem;
position: relative;
}
.info-tray dt {
grid-column: 1;
color: var(--gizmo-text-color-emphasis);
}
.info-tray dt:not(:first-child)::before {
content: '';
width: 100%;
position: absolute;
height: 1px;
background-color: rgba(255, 255, 255, 0.1);
margin-top: -0.375rem;
}
.info-tray dd {
grid-column: 2;
margin: 0;
}
.info-tray :is(dt, dd):not(:last-child) {
margin-bottom: 0.75rem;
}
.info-tray dd + dd {
margin-top: -0.5rem;
}
.info-tray .live-reload-status::before {
content: '•';
color: var(--status-color);
width: 0.75rem;
display: inline-block;
font-size: 1rem;
line-height: 0.5rem;
}
.info-tray .copy {
position: fixed;
z-index: 1;
top: 0.5rem;
right: 0.5rem;
}
.info-tray .switch {
vertical-align: -4px;
}
@keyframes slideIn {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0%);
opacity: 1;
}
}
@keyframes slideOut {
from {
transform: translateX(0%);
opacity: 1;
}
to {
transform: translateX(100%);
opacity: 0;
}
}
@keyframes fade-in {
0% {
opacity: 0;
}
}
@keyframes bounce {
0% {
transform: scale(0.8);
}
50% {
transform: scale(1.5);
background-color: hsla(var(--gizmo-red-hsl), 1);
}
100% {
transform: scale(1);
}
}
@supports (backdrop-filter: blur(1px)) {
.gizmo,
.window,
.notification-tray .message {
backdrop-filter: blur(8px);
}
.gizmo:hover,
.gizmo.active,
.window,
.notification-tray .message {
background-color: var(--gizmo-background-color-active-blurred);
}
}
`;
}
static DISMISSED_NOTIFICATIONS_IN_LOCAL_STORAGE = 'vaadin.live-reload.dismissedNotifications';
static ACTIVE_KEY_IN_SESSION_STORAGE = 'vaadin.live-reload.active';
static TRIGGERED_KEY_IN_SESSION_STORAGE = 'vaadin.live-reload.triggered';
static TRIGGERED_COUNT_KEY_IN_SESSION_STORAGE = 'vaadin.live-reload.triggeredCount';
static AUTO_DEMOTE_NOTIFICATION_DELAY = 5000;
static HOTSWAP_AGENT = 'HOTSWAP_AGENT';
static JREBEL = 'JREBEL';
static SPRING_BOOT_DEVTOOLS = 'SPRING_BOOT_DEVTOOLS';
static BACKEND_DISPLAY_NAME: Record<string, string> = {
HOTSWAP_AGENT: 'HotswapAgent',
JREBEL: 'JRebel',
SPRING_BOOT_DEVTOOLS: 'Spring Boot Devtools'
};
static get isActive() {
const active = window.sessionStorage.getItem(VaadinDevmodeGizmo.ACTIVE_KEY_IN_SESSION_STORAGE);
return active === null || active !== 'false';
}
static notificationDismissed(persistentId: string) {
const shown = window.localStorage.getItem(VaadinDevmodeGizmo.DISMISSED_NOTIFICATIONS_IN_LOCAL_STORAGE);
return shown !== null && shown.includes(persistentId);
}
@property({ type: String })
url?: string;
@property({ type: Boolean, attribute: true })
liveReloadDisabled?: boolean;
@property({ type: String })
backend?: string;
@property({ type: Number })
springBootLiveReloadPort?: number;
@property({ type: Boolean, attribute: false })
expanded: boolean = false;
@property({ type: Array, attribute: false })
messages: Message[] = [];
@property({ type: String, attribute: false })
splashMessage?: string;
@property({ type: Array, attribute: false })
notifications: Message[] = [];
@property({ type: String, attribute: false })
frontendStatus: ConnectionStatus = ConnectionStatus.UNAVAILABLE;
@property({ type: String, attribute: false })
javaStatus: ConnectionStatus = ConnectionStatus.UNAVAILABLE;
@state()
private tabs: readonly Tab[] = [
{ id: 'log', title: 'Log', render: this.renderLog, activate: this.activateLog },
{ id: 'info', title: 'Info', render: this.renderInfo },
{ id: 'features', title: 'Experimental Features', render: this.renderFeatures }
];
@state()
private activeTab: string = 'log';
@state()
private serverInfo: ServerInfo = { flowVersion: '', vaadinVersion: '', javaVersion: '', osVersion: '' };
@state()
private features: Feature[] = [];
@state()
private unreadErrors = false;
@query('.window')
private root!: HTMLElement;
private javaConnection?: Connection;
private frontendConnection?: Connection;
private nextMessageId: number = 1;
private disableEventListener?: EventListener;
private transitionDuration: number = 0;
elementTelemetry() {
let data = {};
try {
// localstorage data is collected by vaadin-usage-statistics.js
const localStorageStatsString = localStorage.getItem('vaadin.statistics.basket');
if (!localStorageStatsString) {
// Do not send empty data
return;
}
data = JSON.parse(localStorageStatsString);
} catch (e) {
// In case of parse errors don't send anything
return;
}
if (this.frontendConnection) {
this.frontendConnection.sendTelemetry(data);
}
}
openWebSocketConnection() {
this.frontendStatus = ConnectionStatus.UNAVAILABLE;
this.javaStatus = ConnectionStatus.UNAVAILABLE;
const onConnectionError = (msg: string) => this.log(MessageType.ERROR, msg);
const onReload = () => {
if (this.liveReloadDisabled) {
return;
}
this.showSplashMessage('Reloading…');
const lastReload = window.sessionStorage.getItem(VaadinDevmodeGizmo.TRIGGERED_COUNT_KEY_IN_SESSION_STORAGE);
const nextReload = lastReload ? parseInt(lastReload, 10) + 1 : 1;
window.sessionStorage.setItem(VaadinDevmodeGizmo.TRIGGERED_COUNT_KEY_IN_SESSION_STORAGE, nextReload.toString());
window.sessionStorage.setItem(VaadinDevmodeGizmo.TRIGGERED_KEY_IN_SESSION_STORAGE, 'true');
window.location.reload();
};
const frontendConnection = new Connection(this.getDedicatedWebSocketUrl());
frontendConnection.onHandshake = () => {
this.log(MessageType.LOG, 'Vaadin development mode initialized');
if (!VaadinDevmodeGizmo.isActive) {
frontendConnection.setActive(false);
}
this.elementTelemetry();
};
frontendConnection.onConnectionError = onConnectionError;
frontendConnection.onReload = onReload;
frontendConnection.onStatusChange = (status: ConnectionStatus) => {
this.frontendStatus = status;
};
frontendConnection.onMessage = (message: any) => {
if (message?.command === 'serverInfo') {
this.serverInfo = message.data as ServerInfo;
} else if (message?.command === 'featureFlags') {
this.features = message.data.features as Feature[];
} else {
// eslint-disable-next-line no-console
console.error('Unknown message from front-end connection:', JSON.stringify(message));
}
};
this.frontendConnection = frontendConnection;
let javaConnection: Connection;
if (this.backend === VaadinDevmodeGizmo.SPRING_BOOT_DEVTOOLS && this.springBootLiveReloadPort) {
javaConnection = new Connection(this.getSpringBootWebSocketUrl(window.location));
javaConnection.onHandshake = () => {
if (!VaadinDevmodeGizmo.isActive) {
javaConnection.setActive(false);
}
};
javaConnection.onReload = onReload;
javaConnection.onConnectionError = onConnectionError;
} else if (this.backend === VaadinDevmodeGizmo.JREBEL || this.backend === VaadinDevmodeGizmo.HOTSWAP_AGENT) {
javaConnection = frontendConnection;
} else {
javaConnection = new Connection(undefined);
}
const prevOnStatusChange = javaConnection.onStatusChange;
javaConnection.onStatusChange = (status) => {
prevOnStatusChange(status);
this.javaStatus = status;
};
const prevOnHandshake = javaConnection.onHandshake;
javaConnection.onHandshake = () => {
prevOnHandshake();
if (this.backend) {
this.log(
MessageType.INFORMATION,
`Java live reload available: ${VaadinDevmodeGizmo.BACKEND_DISPLAY_NAME[this.backend]}`
);
}
};
this.javaConnection = javaConnection;
if (!this.backend) {
this.showNotification(
MessageType.WARNING,
'Java live reload unavailable',
'Live reload for Java changes is currently not set up. Find out how to make use of this functionality to boost your workflow.',
'https://vaadin.com/docs/live-reload',
'liveReloadUnavailable'
);
}
}
getDedicatedWebSocketUrl(): string | undefined {
function getAbsoluteUrl(relative: string) {
// Use innerHTML to obtain an absolute URL
const div = document.createElement('div');
div.innerHTML = `<a href="${relative}"/>`;
return (div.firstChild as HTMLLinkElement).href;
}
if (this.url === undefined) {
return undefined;
}
const connectionBaseUrl = getAbsoluteUrl(this.url!);
if (!connectionBaseUrl.startsWith('http://') && !connectionBaseUrl.startsWith('https://')) {
// eslint-disable-next-line no-console
console.error('The protocol of the url should be http or https for live reload to work.');
return undefined;
}
return `${connectionBaseUrl.replace(/^http/, 'ws')}?v-r=push&debug_window`;
}
getSpringBootWebSocketUrl(location: any) {
const { hostname } = location;
const wsProtocol = location.protocol === 'https:' ? 'wss' : 'ws';
if (hostname.endsWith('gitpod.io')) {
// Gitpod uses `port-url` instead of `url:port`
const hostnameWithoutPort = hostname.replace(/.*?-/, '');
return `${wsProtocol}://${this.springBootLiveReloadPort}-${hostnameWithoutPort}`;
} else {
return `${wsProtocol}://${hostname}:${this.springBootLiveReloadPort}`;
}
}
connectedCallback() {
super.connectedCallback();
this.catchErrors();
// when focus or clicking anywhere, move the splash message to the message tray
this.disableEventListener = (_: any) => this.demoteSplashMessage();
document.body.addEventListener('focus', this.disableEventListener);
document.body.addEventListener('click', this.disableEventListener);
this.openWebSocketConnection();
const lastReload = window.sessionStorage.getItem(VaadinDevmodeGizmo.TRIGGERED_KEY_IN_SESSION_STORAGE);
if (lastReload) {
const now = new Date();
const reloaded = `${`0${now.getHours()}`.slice(-2)}:${`0${now.getMinutes()}`.slice(
-2
)}:${`0${now.getSeconds()}`.slice(-2)}`;
this.showSplashMessage(`Page reloaded at ${reloaded}`);
window.sessionStorage.removeItem(VaadinDevmodeGizmo.TRIGGERED_KEY_IN_SESSION_STORAGE);
}
this.transitionDuration = parseInt(
window.getComputedStyle(this).getPropertyValue('--gizmo-transition-duration'),
10
);
if ((window as any).Vaadin) {
(window as any).Vaadin.devModeGizmo = this;
}
}
format(o: any): string {
return o.toString();
}
catchErrors() {
// Process stored messages
const queue = (window as any).Vaadin.ConsoleErrors as any[];
if (queue) {
queue.forEach((args: any[]) => {
this.log(MessageType.ERROR, args.map((o) => this.format(o)).join(' '));
});
}
// Install new handler that immediately processes messages
(window as any).Vaadin.ConsoleErrors = {
push: (args: any[]) => {
this.log(MessageType.ERROR, args.map((o) => this.format(o)).join(' '));
}
};
}
disconnectedCallback() {
if (this.disableEventListener) {
document.body.removeEventListener('focus', this.disableEventListener!);
document.body.removeEventListener('click', this.disableEventListener!);
}
super.disconnectedCallback();
}
toggleExpanded() {
this.notifications.slice().forEach((notification) => this.dismissNotification(notification.id));
this.expanded = !this.expanded;
if (this.expanded) {
this.root.focus();
}
}
showSplashMessage(msg: string | undefined) {
this.splashMessage = msg;
if (this.splashMessage) {
if (this.expanded) {
this.demoteSplashMessage();
} else {
// automatically move notification to message tray after a certain amount of time
setTimeout(() => {
this.demoteSplashMessage();
}, VaadinDevmodeGizmo.AUTO_DEMOTE_NOTIFICATION_DELAY);
}
}
}
demoteSplashMessage() {
if (this.splashMessage) {
this.log(MessageType.LOG, this.splashMessage);
}
this.showSplashMessage(undefined);
}
log(type: MessageType, message: string, details?: string, link?: string) {
const id = this.nextMessageId;
this.nextMessageId += 1;
this.messages.push({
id,
type,
message,
details,
link,
dontShowAgain: false,
deleted: false
});
while (this.messages.length > VaadinDevmodeGizmo.MAX_LOG_ROWS) {
this.messages.shift();
}
this.requestUpdate();
this.updateComplete.then(() => {
// Scroll into view
const lastMessage = this.renderRoot.querySelector('.message-tray .message:last-child');
if (this.expanded && lastMessage) {
setTimeout(() => lastMessage.scrollIntoView({ behavior: 'smooth' }), this.transitionDuration);
this.unreadErrors = false;
} else if (type === MessageType.ERROR) {
this.unreadErrors = true;
}
});
}
showNotification(type: MessageType, message: string, details?: string, link?: string, persistentId?: string) {
if (persistentId === undefined || !VaadinDevmodeGizmo.notificationDismissed(persistentId!)) {
// Do not open persistent message if another is already visible with the same persistentId
const matchingVisibleNotifications = this.notifications
.filter((notification) => notification.persistentId === persistentId)
.filter((notification) => !notification.deleted);
if (matchingVisibleNotifications.length > 0) {
return;
}
const id = this.nextMessageId;
this.nextMessageId += 1;
this.notifications.push({
id,
type,
message,
details,
link,
persistentId,
dontShowAgain: false,
deleted: false
});
// automatically move notification to message tray after a certain amount of time unless it contains a link
if (link === undefined) {
setTimeout(() => {
this.dismissNotification(id);
}, VaadinDevmodeGizmo.AUTO_DEMOTE_NOTIFICATION_DELAY);
}
this.requestUpdate();
} else {
this.log(type, message, details, link);
}
}
dismissNotification(id: number) {
const index = this.findNotificationIndex(id);
if (index !== -1 && !this.notifications[index].deleted) {
const notification = this.notifications[index];
// user is explicitly dismissing a notification---after that we won't bug them with it
if (
notification.dontShowAgain &&
notification.persistentId &&
!VaadinDevmodeGizmo.notificationDismissed(notification.persistentId)
) {
let dismissed = window.localStorage.getItem(VaadinDevmodeGizmo.DISMISSED_NOTIFICATIONS_IN_LOCAL_STORAGE);
dismissed = dismissed === null ? notification.persistentId : `${dismissed},${notification.persistentId}`;
window.localStorage.setItem(VaadinDevmodeGizmo.DISMISSED_NOTIFICATIONS_IN_LOCAL_STORAGE, dismissed);
}
notification.deleted = true;
this.log(notification.type, notification.message, notification.details, notification.link);
// give some time for the animation
setTimeout(() => {
const idx = this.findNotificationIndex(id);
if (idx !== -1) {
this.notifications.splice(idx, 1);
this.requestUpdate();
}
}, this.transitionDuration);
}
}
findNotificationIndex(id: number): number {
let index = -1;
this.notifications.some((notification, idx) => {
if (notification.id === id) {
index = idx;
return true;
} else {
return false;
}
});
return index;
}
toggleDontShowAgain(id: number) {
const index = this.findNotificationIndex(id);
if (index !== -1 && !this.notifications[index].deleted) {
const notification = this.notifications[index];
notification.dontShowAgain = !notification.dontShowAgain;
this.requestUpdate();
}
}
setActive(yes: boolean) {
this.frontendConnection?.setActive(yes);
this.javaConnection?.setActive(yes);
window.sessionStorage.setItem(VaadinDevmodeGizmo.ACTIVE_KEY_IN_SESSION_STORAGE, yes ? 'true' : 'false');
}
getStatusColor(status: ConnectionStatus | undefined) {
if (status === ConnectionStatus.ACTIVE) {
return css`hsl(${VaadinDevmodeGizmo.GREEN_HSL})`;
} else if (status === ConnectionStatus.INACTIVE) {
return css`hsl(${VaadinDevmodeGizmo.GREY_HSL})`;
} else if (status === ConnectionStatus.UNAVAILABLE) {
return css`hsl(${VaadinDevmodeGizmo.YELLOW_HSL})`;
} else if (status === ConnectionStatus.ERROR) {
return css`hsl(${VaadinDevmodeGizmo.RED_HSL})`;
} else {
return css`none`;
}
}
/* eslint-disable lit/no-template-arrow */
renderMessage(messageObject: Message) {
return html`
<div
class="message ${messageObject.type} ${messageObject.deleted ? 'animate-out' : ''} ${messageObject.details ||
messageObject.link
? 'has-details'
: ''}"
>
<div class="message-content">
<div class="message-heading">${messageObject.message}</div>
<div class="message-details" ?hidden="${!messageObject.details && !messageObject.link}">
${messageObject.details ? html`<p>${messageObject.details}</p>` : ''}
${messageObject.link
? html`<a class="ahreflike" href="${messageObject.link}" target="_blank">Learn more</a>`
: ''}
</div>
${messageObject.persistentId
? html`<div
class="persist ${messageObject.dontShowAgain ? 'on' : 'off'}"
@click=${() => this.toggleDontShowAgain(messageObject.id)}
>
Don’t show again
</div>`
: ''}
</div>
<div class="dismiss-message" @click=${() => this.dismissNotification(messageObject.id)}>Dismiss</div>
</div>
`;
}
/* eslint-disable lit/no-template-map */
render() {
return html` <div
class="window ${this.expanded ? 'visible' : 'hidden'}"
tabindex="0"
@keydown=${(e: KeyboardEvent) => e.key === 'Escape' && this.toggleExpanded()}
>
<div class="window-toolbar">
${this.tabs.map(
(tab) =>
html`<button
class=${classMap({
tab: true,
active: this.activeTab === tab.id,
unreadErrors: tab.id === 'log' && this.unreadErrors
})}
id="${tab.id}"
@click=${() => {
this.activeTab = tab.id;
if (tab.activate) tab.activate.call(this);
}}
>
${tab.title}
</button> `
)}
<button class="minimize-button" title="Minimize" @click=${() => this.toggleExpanded()}>
<svg fill="none" height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg">
<g fill="#fff" opacity=".8">
<path
d="m7.25 1.75c0-.41421.33579-.75.75-.75h3.25c2.0711 0 3.75 1.67893 3.75 3.75v6.5c0 2.0711-1.6789 3.75-3.75 3.75h-6.5c-2.07107 0-3.75-1.6789-3.75-3.75v-3.25c0-.41421.33579-.75.75-.75s.75.33579.75.75v3.25c0 1.2426 1.00736 2.25 2.25 2.25h6.5c1.2426 0 2.25-1.0074 2.25-2.25v-6.5c0-1.24264-1.0074-2.25-2.25-2.25h-3.25c-.41421 0-.75-.33579-.75-.75z"
/>
<path
d="m2.96967 2.96967c.29289-.29289.76777-.29289 1.06066 0l5.46967 5.46967v-2.68934c0-.41421.33579-.75.75-.75.4142 0 .75.33579.75.75v4.5c0 .4142-.3358.75-.75.75h-4.5c-.41421 0-.75-.3358-.75-.75 0-.41421.33579-.75.75-.75h2.68934l-5.46967-5.46967c-.29289-.29289-.29289-.76777 0-1.06066z"
/>
</g>
</svg>
</button>
</div>
${this.tabs.map((tab) => (this.activeTab === tab.id ? tab.render.call(this) : nothing))}
</div>
<div class="notification-tray">${this.notifications.map((msg) => this.renderMessage(msg))}</div>
<div
class="gizmo ${this.splashMessage ? 'active' : ''}${this.unreadErrors ? ' error' : ''}"
@click=${() => this.toggleExpanded()}
>
${this.unreadErrors
? html`<svg
fill="none"
height="16"
viewBox="0 0 16 16"
width="16"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
class="gizmo-icon error"
>
<clipPath id="a"><path d="m0 0h16v16h-16z" /></clipPath>
<g clip-path="url(#a)">
<path
d="m6.25685 2.09894c.76461-1.359306 2.72169-1.359308 3.4863 0l5.58035 9.92056c.7499 1.3332-.2135 2.9805-1.7432 2.9805h-11.1606c-1.529658 0-2.4930857-1.6473-1.743156-2.9805z"
fill="#ff5c69"
/>
<path
d="m7.99699 4c-.45693 0-.82368.37726-.81077.834l.09533 3.37352c.01094.38726.32803.69551.71544.69551.38741 0 .70449-.30825.71544-.69551l.09533-3.37352c.0129-.45674-.35384-.834-.81077-.834zm.00301 8c.60843 0 1-.3879 1-.979 0-.5972-.39157-.9851-1-.9851s-1 .3879-1 .9851c0 .5911.39157.979 1 .979z"
fill="#fff"
/>
</g>
</svg>`
: html`<svg
fill="none"
height="17"
viewBox="0 0 16 17"
width="16"
xmlns="http://www.w3.org/2000/svg"
class="gizmo-icon logo"
>
<g fill="#fff">
<path
d="m8.88273 5.97926c0 .04401-.0032.08898-.00801.12913-.02467.42848-.37813.76767-.8117.76767-.43358 0-.78704-.34112-.81171-.76928-.00481-.04015-.00801-.08351-.00801-.12752 0-.42784-.10255-.87656-1.14434-.87656h-3.48364c-1.57118 0-2.315271-.72849-2.315271-2.21758v-1.26683c0-.42431.324618-.768314.748261-.768314.42331 0 .74441.344004.74441.768314v.42784c0 .47924.39576.81265 1.11293.81265h3.41538c1.5542 0 1.67373 1.156 1.725 1.7679h.03429c.05095-.6119.17048-1.7679 1.72468-1.7679h3.4154c.7172 0 1.0145-.32924 1.0145-.80847l-.0067-.43202c0-.42431.3227-.768314.7463-.768314.4234 0 .7255.344004.7255.768314v1.26683c0 1.48909-.6181 2.21758-2.1893 2.21758h-3.4836c-1.04182 0-1.14437.44872-1.14437.87656z"
/>
<path
d="m8.82577 15.1648c-.14311.3144-.4588.5335-.82635.5335-.37268 0-.69252-.2249-.83244-.5466-.00206-.0037-.00412-.0073-.00617-.0108-.00275-.0047-.00549-.0094-.00824-.0145l-3.16998-5.87318c-.08773-.15366-.13383-.32816-.13383-.50395 0-.56168.45592-1.01879 1.01621-1.01879.45048 0 .75656.22069.96595.6993l2.16882 4.05042 2.17166-4.05524c.2069-.47379.513-.69448.9634-.69448.5603 0 1.0166.45711 1.0166 1.01879 0 .17579-.0465.35029-.1348.50523l-3.1697 5.8725c-.00503.0096-.01006.0184-.01509.0272-.00201.0036-.00402.0071-.00604.0106z"
/>
</g>
</svg>`}
<span
class="status-blip"
style="background: linear-gradient(to right, ${this.getStatusColor(
this.frontendStatus
)} 50%, ${this.getStatusColor(this.javaStatus)} 50%)"
></span>
${this.splashMessage ? html`<span class="status-description">${this.splashMessage}</span></div>` : nothing}
</div>`;
}
renderLog() {
return html`<div class="message-tray">${this.messages.map((msg) => this.renderMessage(msg))}</div>`;
}
activateLog() {
this.unreadErrors = false;
this.updateComplete.then(() => {
const lastMessage = this.renderRoot.querySelector('.message-tray .message:last-child');
if (lastMessage) {
lastMessage.scrollIntoView();
}
});
}
renderInfo() {
return html`<div class="info-tray">
<button class="button copy" @click=${this.copyInfoToClipboard}>Copy</button>
<dl>
<dt>Vaadin</dt>
<dd>${this.serverInfo.vaadinVersion}</dd>
<dt>Flow</dt>
<dd>${this.serverInfo.flowVersion}</dd>
<dt>Java</dt>
<dd>${this.serverInfo.javaVersion}</dd>
<dt>OS</dt>
<dd>${this.serverInfo.osVersion}</dd>
<dt>Browser</dt>
<dd>${navigator.userAgent}</dd>
<dt>
Live reload
<label class="switch">
<input
id="toggle"
type="checkbox"
?disabled=${this.liveReloadDisabled ||
((this.frontendStatus === ConnectionStatus.UNAVAILABLE ||
this.frontendStatus === ConnectionStatus.ERROR) &&
(this.javaStatus === ConnectionStatus.UNAVAILABLE || this.javaStatus === ConnectionStatus.ERROR))}
?checked="${this.frontendStatus === ConnectionStatus.ACTIVE ||
this.javaStatus === ConnectionStatus.ACTIVE}"
@change=${(e: InputEvent) => this.setActive((e.target as HTMLInputElement).checked)}
/>
<span class="slider"></span>
</label>
</dt>
<dd class="live-reload-status" style="--status-color: ${this.getStatusColor(this.javaStatus)}">
Java ${this.javaStatus} ${this.backend ? `(${VaadinDevmodeGizmo.BACKEND_DISPLAY_NAME[this.backend]})` : ''}
</dd>
<dd class="live-reload-status" style="--status-color: ${this.getStatusColor(this.frontendStatus)}">
Front end ${this.frontendStatus}
</dd>
</dl>
</div>`;
}
private renderFeatures() {
return html`<div class="features-tray">
<p>
These features are work in progress. The behavior, API, look and feel can still change significantly before (and
if) they become part of a stable release.
</p>
${this.features.map(
(feature) => html`<div class="feature">
<label class="switch">
<input
class="feature-toggle"
id="feature-toggle-${feature.id}"
type="checkbox"
?checked=${feature.enabled}
@change=${(e: InputEvent) => this.toggleFeatureFlag(e, feature)}
/>
<span class="slider"></span>
${feature.title}
</label>
<a class="ahreflike" href="${feature.moreInfoLink}" target="_blank">Learn more</a>
</div>`
)}
</div>`;
}
copyInfoToClipboard() {
const items = this.renderRoot.querySelectorAll('.info-tray dt, .info-tray dd');
const text = Array.from(items)
.map((message) => (message.localName === 'dd' ? ': ' : '\n') + message.textContent!.trim())
.join('')
.replace(/^\n/, '');
copy(text);
this.showNotification(
MessageType.INFORMATION,
'Environment information copied to clipboard',
undefined,
undefined,
'versionInfoCopied'
);
}
toggleFeatureFlag(e: Event, feature: Feature) {
const enabled = (e.target! as HTMLInputElement).checked;
if (this.frontendConnection) {
this.frontendConnection.setFeature(feature.id, enabled);
this.showNotification(
MessageType.INFORMATION,
`“${feature.title}” ${enabled ? 'enabled' : 'disabled'}`,
feature.requiresServerRestart ? 'This feature requires a server restart' : undefined,
undefined,
`feature${feature.id}${enabled ? 'Enabled' : 'Disabled'}`
);
} else {
this.log(MessageType.ERROR, `Unable to toggle feature ${feature.title}: No server connection available`);
}
}
}
if (customElements.get('vaadin-devmode-gizmo') === undefined) {
customElements.define('vaadin-devmode-gizmo', VaadinDevmodeGizmo);
} | the_stack |
import ByteBuffer from "bytebuffer";
import { TransactionType, TransactionTypeGroup } from "../enums";
import { TransactionVersionError } from "../errors";
import { Address } from "../identities";
import { ISerializeOptions } from "../interfaces";
import { ITransaction, ITransactionData } from "../interfaces";
import { configManager } from "../managers/config";
import { isException } from "../utils";
import { isSupportedTransactionVersion } from "../utils";
import { TransactionTypeFactory } from "./types";
// Reference: https://github.com/ArkEcosystem/AIPs/blob/master/AIPS/aip-11.md
export class Serializer {
public static getBytes(transaction: ITransactionData, options: ISerializeOptions = {}): Buffer {
const version: number = transaction.version || 1;
if (options.acceptLegacyVersion || options.disableVersionCheck || isSupportedTransactionVersion(version)) {
if (version === 1) {
return this.getBytesV1(transaction, options);
}
return this.serialize(TransactionTypeFactory.create(transaction), options);
} else {
throw new TransactionVersionError(version);
}
}
/**
* Serializes the given transaction according to AIP11.
*/
public static serialize(transaction: ITransaction, options: ISerializeOptions = {}): Buffer {
const buffer: ByteBuffer = new ByteBuffer(512, true);
this.serializeCommon(transaction.data, buffer);
this.serializeVendorField(transaction, buffer);
const serialized: ByteBuffer | undefined = transaction.serialize(options);
if (!serialized) {
throw new Error();
}
const typeBuffer: ByteBuffer = serialized.flip();
buffer.append(typeBuffer);
this.serializeSignatures(transaction.data, buffer, options);
const flippedBuffer: Buffer = buffer.flip().toBuffer();
transaction.serialized = flippedBuffer;
return flippedBuffer;
}
/**
* Serializes the given transaction prior to AIP11 (legacy).
*/
private static getBytesV1(transaction: ITransactionData, options: ISerializeOptions = {}): Buffer {
let assetSize = 0;
let assetBytes: Buffer | Uint8Array | undefined;
if (transaction.type === TransactionType.SecondSignature && transaction.asset) {
const { signature } = transaction.asset;
const bb = new ByteBuffer(33, true);
if (signature && signature.publicKey) {
const publicKeyBuffer = Buffer.from(signature.publicKey, "hex");
for (const byte of publicKeyBuffer) {
bb.writeByte(byte);
}
}
bb.flip();
assetBytes = new Uint8Array(bb.toArrayBuffer());
assetSize = assetBytes.length;
}
if (
transaction.type === TransactionType.DelegateRegistration &&
transaction.asset &&
transaction.asset.delegate
) {
assetBytes = Buffer.from(transaction.asset.delegate.username, "utf8");
assetSize = assetBytes.length;
}
if (transaction.type === TransactionType.Vote && transaction.asset && transaction.asset.votes) {
assetBytes = Buffer.from(transaction.asset.votes.join(""), "utf8");
assetSize = assetBytes.length;
}
if (
transaction.type === TransactionType.MultiSignature &&
transaction.asset &&
transaction.asset.multiSignatureLegacy
) {
const keysgroupBuffer: Buffer = Buffer.from(
transaction.asset.multiSignatureLegacy.keysgroup.join(""),
"utf8",
);
const bb: ByteBuffer = new ByteBuffer(1 + 1 + keysgroupBuffer.length, true);
bb.writeByte(transaction.asset.multiSignatureLegacy.min);
bb.writeByte(transaction.asset.multiSignatureLegacy.lifetime);
for (const byte of keysgroupBuffer) {
bb.writeByte(byte);
}
bb.flip();
assetBytes = bb.toBuffer();
if (assetBytes) {
assetSize = assetBytes.length;
}
}
const bb: ByteBuffer = new ByteBuffer(1 + 4 + 32 + 8 + 8 + 21 + 64 + 64 + 64 + assetSize, true);
bb.writeByte(transaction.type);
bb.writeInt(transaction.timestamp);
if (transaction.senderPublicKey) {
const senderPublicKeyBuffer: Buffer = Buffer.from(transaction.senderPublicKey, "hex");
for (const byte of senderPublicKeyBuffer) {
bb.writeByte(byte);
}
// Apply fix for broken type 1 and 4 transactions, which were
// erroneously calculated with a recipient id.
const { transactionIdFixTable } = configManager.get("exceptions");
const isBrokenTransaction: boolean =
transactionIdFixTable && Object.values(transactionIdFixTable).includes(transaction.id);
if (isBrokenTransaction || (transaction.recipientId && transaction.type !== 1 && transaction.type !== 4)) {
const recipientId =
transaction.recipientId || Address.fromPublicKey(transaction.senderPublicKey, transaction.network);
const recipient = Address.toBuffer(recipientId).addressBuffer;
for (const byte of recipient) {
bb.writeByte(byte);
}
} else {
for (let i = 0; i < 21; i++) {
bb.writeByte(0);
}
}
}
if (transaction.vendorField) {
const vf: Buffer = Buffer.from(transaction.vendorField);
const fillstart: number = vf.length;
for (let i = 0; i < fillstart; i++) {
bb.writeByte(vf[i]);
}
for (let i = fillstart; i < 64; i++) {
bb.writeByte(0);
}
} else {
for (let i = 0; i < 64; i++) {
bb.writeByte(0);
}
}
// @ts-ignore - The ByteBuffer types say we can't use strings but the code actually handles them.
bb.writeInt64(transaction.amount.toString());
// @ts-ignore - The ByteBuffer types say we can't use strings but the code actually handles them.
bb.writeInt64(transaction.fee.toString());
if (assetSize > 0 && assetBytes) {
for (let i = 0; i < assetSize; i++) {
bb.writeByte(assetBytes[i]);
}
}
if (!options.excludeSignature && transaction.signature) {
const signatureBuffer = Buffer.from(transaction.signature, "hex");
for (const byte of signatureBuffer) {
bb.writeByte(byte);
}
}
if (!options.excludeSecondSignature && transaction.secondSignature) {
const signSignatureBuffer = Buffer.from(transaction.secondSignature, "hex");
for (const byte of signSignatureBuffer) {
bb.writeByte(byte);
}
}
bb.flip();
const arrayBuffer: Uint8Array = new Uint8Array(bb.toArrayBuffer());
const buffer: number[] = [];
for (let i = 0; i < arrayBuffer.length; i++) {
buffer[i] = arrayBuffer[i];
}
return Buffer.from(buffer);
}
private static serializeCommon(transaction: ITransactionData, buffer: ByteBuffer): void {
transaction.version = transaction.version || 0x01;
if (transaction.typeGroup === undefined) {
transaction.typeGroup = TransactionTypeGroup.Core;
}
buffer.writeByte(0xff);
buffer.writeByte(transaction.version);
buffer.writeByte(transaction.network || configManager.get("network.pubKeyHash"));
if (transaction.version === 1) {
buffer.writeByte(transaction.type);
buffer.writeUint32(transaction.timestamp);
} else {
buffer.writeUint32(transaction.typeGroup);
buffer.writeUint16(transaction.type);
if (transaction.nonce) {
// @ts-ignore - The ByteBuffer types say we can't use strings but the code actually handles them.
buffer.writeUint64(transaction.nonce.toString());
}
}
if (transaction.senderPublicKey) {
buffer.append(transaction.senderPublicKey, "hex");
}
// @ts-ignore - The ByteBuffer types say we can't use strings but the code actually handles them.
buffer.writeUint64(transaction.fee.toString());
}
private static serializeVendorField(transaction: ITransaction, buffer: ByteBuffer): void {
if (transaction.hasVendorField()) {
const { data }: ITransaction = transaction;
if (data.vendorField) {
const vf: Buffer = Buffer.from(data.vendorField, "utf8");
buffer.writeByte(vf.length);
buffer.append(vf);
} else {
buffer.writeByte(0x00);
}
} else {
buffer.writeByte(0x00);
}
}
private static serializeSignatures(
transaction: ITransactionData,
buffer: ByteBuffer,
options: ISerializeOptions = {},
): void {
if (transaction.signature && !options.excludeSignature) {
buffer.append(transaction.signature, "hex");
}
const secondSignature: string | undefined = transaction.secondSignature || transaction.signSignature;
if (secondSignature && !options.excludeSecondSignature) {
buffer.append(secondSignature, "hex");
}
if (transaction.signatures) {
if (transaction.version === 1 && isException(transaction)) {
buffer.append("ff", "hex"); // 0xff separator to signal start of multi-signature transactions
buffer.append(transaction.signatures.join(""), "hex");
} else if (!options.excludeMultiSignature) {
buffer.append(transaction.signatures.join(""), "hex");
}
}
}
} | the_stack |
import { expect } from "chai";
import { NodeKey, StandardNodeTypes } from "../../presentation-common/hierarchy/Key";
import { createTestECInstanceKey } from "../_helpers/EC";
import { createTestNodeKey } from "../_helpers/Hierarchy";
import {
createRandomBaseNodeKey, createRandomECClassGroupingNodeKey, createRandomECInstancesNodeKey, createRandomECInstancesNodeKeyJSON,
createRandomECPropertyGroupingNodeKey, createRandomLabelGroupingNodeKey,
} from "../_helpers/random";
describe("NodeKey", () => {
describe("toJSON", () => {
it("serializes BaseNodeKey", () => {
const key = NodeKey.toJSON(createRandomBaseNodeKey());
expect(key).to.matchSnapshot();
});
it("serializes ECInstancesNodeKey", () => {
const key = NodeKey.toJSON(createRandomECInstancesNodeKey());
expect(key).to.matchSnapshot();
});
it("serializes ECClassGroupingNodeKey", () => {
const key = NodeKey.toJSON(createRandomECClassGroupingNodeKey());
expect(key).to.matchSnapshot();
});
it("serializes ECPropertyGroupingNodeKey", () => {
const key = NodeKey.toJSON(createRandomECPropertyGroupingNodeKey());
expect(key).to.matchSnapshot();
});
it("serializes LabelGroupingNodeKey", () => {
const key = NodeKey.toJSON(createRandomLabelGroupingNodeKey());
expect(key).to.matchSnapshot();
});
});
describe("fromJSON", () => {
it("creates BaseNodeKey", () => {
const key = NodeKey.fromJSON(createRandomBaseNodeKey());
expect(key).to.matchSnapshot();
});
it("creates ECInstancesNodeKey", () => {
const key = NodeKey.fromJSON(createRandomECInstancesNodeKeyJSON());
expect(key).to.matchSnapshot();
});
it("creates ECClassGroupingNodeKey", () => {
const key = NodeKey.fromJSON(createRandomECClassGroupingNodeKey());
expect(key).to.matchSnapshot();
});
it("creates ECPropertyGroupingNodeKey", () => {
const key = NodeKey.fromJSON(createRandomECPropertyGroupingNodeKey());
expect(key).to.matchSnapshot();
});
it("creates LabelGroupingNodeKey", () => {
const key = NodeKey.fromJSON(createRandomLabelGroupingNodeKey());
expect(key).to.matchSnapshot();
});
});
describe("isInstancesNodeKey", () => {
it("returns correct results for different types of nodes", () => {
expect(NodeKey.isInstancesNodeKey(createRandomBaseNodeKey())).to.be.false;
expect(NodeKey.isInstancesNodeKey(createRandomECInstancesNodeKey())).to.be.true;
expect(NodeKey.isInstancesNodeKey(createRandomECClassGroupingNodeKey())).to.be.false;
expect(NodeKey.isInstancesNodeKey(createRandomECPropertyGroupingNodeKey())).to.be.false;
expect(NodeKey.isInstancesNodeKey(createRandomLabelGroupingNodeKey())).to.be.false;
});
});
describe("isClassGroupingNodeKey", () => {
it("returns correct results for different types of nodes", () => {
expect(NodeKey.isClassGroupingNodeKey(createRandomBaseNodeKey())).to.be.false;
expect(NodeKey.isClassGroupingNodeKey(createRandomECInstancesNodeKey())).to.be.false;
expect(NodeKey.isClassGroupingNodeKey(createRandomECClassGroupingNodeKey())).to.be.true;
expect(NodeKey.isClassGroupingNodeKey(createRandomECPropertyGroupingNodeKey())).to.be.false;
expect(NodeKey.isClassGroupingNodeKey(createRandomLabelGroupingNodeKey())).to.be.false;
});
});
describe("isPropertyGroupingNodeKey", () => {
it("returns correct results for different types of nodes", () => {
expect(NodeKey.isPropertyGroupingNodeKey(createRandomBaseNodeKey())).to.be.false;
expect(NodeKey.isPropertyGroupingNodeKey(createRandomECInstancesNodeKey())).to.be.false;
expect(NodeKey.isPropertyGroupingNodeKey(createRandomECClassGroupingNodeKey())).to.be.false;
expect(NodeKey.isPropertyGroupingNodeKey(createRandomECPropertyGroupingNodeKey())).to.be.true;
expect(NodeKey.isPropertyGroupingNodeKey(createRandomLabelGroupingNodeKey())).to.be.false;
});
});
describe("isLabelGroupingNodeKey", () => {
it("returns correct results for different types of nodes", () => {
expect(NodeKey.isLabelGroupingNodeKey(createRandomBaseNodeKey())).to.be.false;
expect(NodeKey.isLabelGroupingNodeKey(createRandomECInstancesNodeKey())).to.be.false;
expect(NodeKey.isLabelGroupingNodeKey(createRandomECClassGroupingNodeKey())).to.be.false;
expect(NodeKey.isLabelGroupingNodeKey(createRandomECPropertyGroupingNodeKey())).to.be.false;
expect(NodeKey.isLabelGroupingNodeKey(createRandomLabelGroupingNodeKey())).to.be.true;
});
});
describe("isGroupingNodeKey", () => {
it("returns correct results for different types of nodes", () => {
expect(NodeKey.isGroupingNodeKey(createRandomBaseNodeKey())).to.be.false;
expect(NodeKey.isGroupingNodeKey(createRandomECInstancesNodeKey())).to.be.false;
expect(NodeKey.isGroupingNodeKey(createRandomECClassGroupingNodeKey())).to.be.true;
expect(NodeKey.isGroupingNodeKey(createRandomECPropertyGroupingNodeKey())).to.be.true;
expect(NodeKey.isGroupingNodeKey(createRandomLabelGroupingNodeKey())).to.be.true;
});
});
describe("equals", () => {
it("returns `false` when types are different", () => {
const lhs = createTestNodeKey({ type: "a" });
const rhs = createTestNodeKey({ type: "b" });
expect(NodeKey.equals(lhs, rhs)).to.be.false;
});
it("returns `false` when `pathFromRoot` lengths are different", () => {
const lhs = createTestNodeKey({ pathFromRoot: ["a", "b"] });
const rhs = createTestNodeKey({ pathFromRoot: ["a", "b", "c"] });
expect(NodeKey.equals(lhs, rhs)).to.be.false;
});
describe("when versions are equal", () => {
it("returns `false` when `pathFromRoot` contents are different", () => {
const lhs = createTestNodeKey({ version: 999, pathFromRoot: ["a", "b"] });
const rhs = createTestNodeKey({ version: 999, pathFromRoot: ["a", "c"] });
expect(NodeKey.equals(lhs, rhs)).to.be.false;
});
it("returns `true` when `pathFromRoot` contents are similar", () => {
const lhs = createTestNodeKey({ version: 999, pathFromRoot: ["a", "b"] });
const rhs = createTestNodeKey({ version: 999, pathFromRoot: ["a", "b"] });
expect(NodeKey.equals(lhs, rhs)).to.be.true;
});
});
describe("when versions are different", () => {
it("returns `false` when instance key counts are different for instance node keys", () => {
const lhs = createTestNodeKey({
version: 1,
type: StandardNodeTypes.ECInstancesNode,
instanceKeys: [createTestECInstanceKey({ id: "0x1" }), createTestECInstanceKey({ id: "0x2" })],
});
const rhs = createTestNodeKey({
version: 2,
type: StandardNodeTypes.ECInstancesNode,
instanceKeys: [createTestECInstanceKey({ id: "0x1" }), createTestECInstanceKey({ id: "0x2" }), createTestECInstanceKey({ id: "0x3" })],
});
expect(NodeKey.equals(lhs, rhs)).to.be.false;
});
it("returns `false` when instance keys are different for instance node keys", () => {
const lhs = createTestNodeKey({
version: 1,
type: StandardNodeTypes.ECInstancesNode,
instanceKeys: [createTestECInstanceKey({ id: "0x1" }), createTestECInstanceKey({ id: "0x2" })],
});
const rhs = createTestNodeKey({
version: 2,
type: StandardNodeTypes.ECInstancesNode,
instanceKeys: [createTestECInstanceKey({ id: "0x1" }), createTestECInstanceKey({ id: "0x3" })],
});
expect(NodeKey.equals(lhs, rhs)).to.be.false;
});
it("returns `true` when instance keys are similar for instance node keys", () => {
const lhs = createTestNodeKey({
version: 1,
type: StandardNodeTypes.ECInstancesNode,
instanceKeys: [createTestECInstanceKey({ id: "0x1" }), createTestECInstanceKey({ id: "0x2" })],
});
const rhs = createTestNodeKey({
version: 2,
type: StandardNodeTypes.ECInstancesNode,
instanceKeys: [createTestECInstanceKey({ id: "0x1" }), createTestECInstanceKey({ id: "0x2" })],
});
expect(NodeKey.equals(lhs, rhs)).to.be.true;
});
it("returns `false` when class names are different for class grouping node keys", () => {
const lhs = createTestNodeKey({
version: 1,
type: StandardNodeTypes.ECClassGroupingNode,
className: "a",
});
const rhs = createTestNodeKey({
version: 2,
type: StandardNodeTypes.ECClassGroupingNode,
className: "b",
});
expect(NodeKey.equals(lhs, rhs)).to.be.false;
});
it("returns `true` when class names are similar for class grouping node keys", () => {
const lhs = createTestNodeKey({
version: 1,
type: StandardNodeTypes.ECClassGroupingNode,
className: "a",
});
const rhs = createTestNodeKey({
version: 2,
type: StandardNodeTypes.ECClassGroupingNode,
className: "a",
});
expect(NodeKey.equals(lhs, rhs)).to.be.true;
});
it("returns `false` when class names are different for property grouping node keys", () => {
const lhs = createTestNodeKey({
version: 1,
type: StandardNodeTypes.ECPropertyGroupingNode,
className: "a",
propertyName: "p",
});
const rhs = createTestNodeKey({
version: 2,
type: StandardNodeTypes.ECPropertyGroupingNode,
className: "b",
propertyName: "p",
});
expect(NodeKey.equals(lhs, rhs)).to.be.false;
});
it("returns `false` when property names are different for property grouping node keys", () => {
const lhs = createTestNodeKey({
version: 1,
type: StandardNodeTypes.ECPropertyGroupingNode,
className: "a",
propertyName: "p1",
});
const rhs = createTestNodeKey({
version: 2,
type: StandardNodeTypes.ECPropertyGroupingNode,
className: "a",
propertyName: "p2",
});
expect(NodeKey.equals(lhs, rhs)).to.be.false;
});
it("returns `true` when class and property names are similar for property grouping node keys", () => {
const lhs = createTestNodeKey({
version: 1,
type: StandardNodeTypes.ECPropertyGroupingNode,
className: "a",
propertyName: "p",
});
const rhs = createTestNodeKey({
version: 2,
type: StandardNodeTypes.ECPropertyGroupingNode,
className: "a",
propertyName: "p",
});
expect(NodeKey.equals(lhs, rhs)).to.be.true;
});
it("returns `false` when labels are different for label grouping node keys", () => {
const lhs = createTestNodeKey({
version: 1,
type: StandardNodeTypes.DisplayLabelGroupingNode,
label: "a",
});
const rhs = createTestNodeKey({
version: 2,
type: StandardNodeTypes.DisplayLabelGroupingNode,
label: "b",
});
expect(NodeKey.equals(lhs, rhs)).to.be.false;
});
it("returns `true` when labels are similar for label grouping node keys", () => {
const lhs = createTestNodeKey({
version: 1,
type: StandardNodeTypes.DisplayLabelGroupingNode,
label: "a",
});
const rhs = createTestNodeKey({
version: 2,
type: StandardNodeTypes.DisplayLabelGroupingNode,
label: "a",
});
expect(NodeKey.equals(lhs, rhs)).to.be.true;
});
it("returns `true` when types and `pathFromRoot` lengths are equal for base node keys", () => {
const lhs = createTestNodeKey({
version: 1,
});
const rhs = createTestNodeKey({
version: 2,
});
expect(NodeKey.equals(lhs, rhs)).to.be.true;
});
});
});
}); | the_stack |
import * as CodeMirror from 'codemirror'
import { Addon, FlipFlop, debounce, TokenSeeker, suggestedEditorConfig, normalVisualConfig } from '../core'
import { Position, Token } from 'codemirror'
import { cm_t } from '../core/type'
import { rangesIntersect, orderedRange } from '../core/cm_utils';
const DEBUG = false
const FlagArray = typeof Uint8Array === 'undefined' ? (Array as typeof Uint8Array) : Uint8Array;
export interface HmdTextMarker extends CodeMirror.TextMarker {
/** @internal when caret in this range, break this marker */
_hmd_crange?: [Position, Position]
/** @internal the folder type of current marker */
_hmd_fold_type?: string
}
/********************************************************************************** */
//#region FolderFunc & FoldStream declaration
/**
* 1. Check if `token` is a **BEGINNING TOKEN** of fold-able text (eg. "!" for images)
* 2. Use `stream.findNext` to find the end of the text to be folded (eg. ")" or "]" of link/URL, for images)
* 3. Compose a range `{from, to}`
* - `from` is always `{ line: stream.lineNo, ch: token.start }`
* 4. Check if `stream.requestRange(from, to[, cfrom, cto])` returns `RequestRangeResult.OK`
* - if not ok, you shall return `null` immediately.
* - the optional `cfrom` and `cto` compose a range, let's call it "crange".
* - If user's caret moves into that "crange", your marker will break automatically.
* - If "crange" is not provided, it will be the same as `[from, to]`
* - Note that "crange" can be bigger / smaller than the marker's range,
* as long as they have intersection.
* - In some cases, to prevent auto-breaking, please use `cfrom = from` and `cto = from`
* (and, yes, "crange" can be a zero-width range)
* 5. Use `stream.cm.markText(from, to, options)` to fold text, and return the marker
*
* @param token current checking token. a shortcut to `stream.lineTokens[stream.i_token]`
* @returns a TextMarker if folded.
*/
export type FolderFunc = (stream: FoldStream, token: CodeMirror.Token) => HmdTextMarker;
/** FolderFunc may use FoldStream to lookup for tokens */
export interface FoldStream {
readonly cm: cm_t
readonly line: CodeMirror.LineHandle
readonly lineNo: number
readonly lineTokens: Token[] // always same as cm.getLineTokens(line)
readonly i_token: number // current token's index
/**
* Find next Token that matches the condition AFTER current token (whose index is `i_token`), or a given position
* This function will NOT make the stream precede!
*
* @param condition a RegExp to check token.type, or a function check the Token
* @param maySpanLines by default the searching will not span lines
*/
findNext(condition: TokenSeeker.ConditionType, maySpanLines?: boolean, since?: Position): TokenSeeker.ResultType
/**
* In current line, find next Token that matches the condition SINCE the token with given index
* This function will NOT make the stream precede!
*
* @param condition a RegExp to check token.type, or a function check the Token
* @param i_token_since default: i_token+1 (the next of current token)
*/
findNext(condition: TokenSeeker.ConditionType, i_token_since: number): TokenSeeker.ResultType
/**
* Before creating a TextMarker, check if the range is good to use.
*
* Do NOT create TextMarker unless this returns `RequestRangeResult.OK`
*/
requestRange(from: Position, to: Position): RequestRangeResult
/**
* Before creating a TextMarker, check if the range is good to use.
*
* Do NOT create TextMarker unless this returns `RequestRangeResult.OK`
*
* @param cfrom if cfrom <= caret <= cto, the TextMarker will be removed.
* @param cto if cfrom <= caret <= cto, the TextMarker will be removed.
*/
requestRange(from: Position, to: Position, cfrom: Position, cto: Position): RequestRangeResult
}
export enum RequestRangeResult {
// Use string values because in TypeScript, string enum members do not get a reverse mapping generated at all.
// Otherwise the generated code looks ugly
OK = "ok",
CURSOR_INSIDE = "ci",
HAS_MARKERS = "hm",
}
//#endregion
/********************************************************************************** */
//#region FolderFunc Registry
export var folderRegistry: Record<string, FolderFunc> = {}
/**
* Add a Folder to the System Folder Registry
*
* @param name eg. "math" "html" "image" "link"
* @param folder
* @param suggested enable this folder in suggestedEditorConfig
* @param force if a folder with same name is already exists, overwrite it. (dangerous)
*/
export function registerFolder(name: string, folder: FolderFunc, suggested: boolean, force?: boolean) {
var registry = folderRegistry
if (name in registry && !force) throw new Error(`Folder ${name} already registered`)
defaultOption[name] = false
suggestedOption[name] = !!suggested
registry[name] = folder
}
//#endregion
/********************************************************************************** */
//#region Utils
/** break a TextMarker, move cursor to where marker is */
export function breakMark(cm: cm_t, marker: HmdTextMarker, chOffset?: number) {
cm.operation(function () {
var pos = marker.find().from
pos = { line: pos.line, ch: pos.ch + ~~chOffset }
cm.setCursor(pos)
cm.focus()
marker.clear()
})
}
//#endregion
/********************************************************************************** */
//#region Addon Options
export type Options = Record<string, boolean>
export const defaultOption: Options = {
/* will be populated by registerFolder() */
}
export const suggestedOption: Options = {
/* will be populated by registerFolder() */
}
export type OptionValueType = Options | boolean;
declare global {
namespace HyperMD {
interface EditorConfiguration {
/**
* Enable/disable registered folders, for current editor instance.
*
* `hmdFold` accepts:
*
* 1. `true` -- only enable suggested folders
* 2. `false` -- disable all kinds of folders
* 3. `{ [FolderType]: boolean }` -- enable / disable folders
* - Note: registered but not configured folder kinds will be disabled
*
* @example { image: true, link: true, math: true, html: false }
*/
hmdFold?: OptionValueType
}
}
}
suggestedEditorConfig.hmdFold = suggestedOption
normalVisualConfig.hmdFold = false
CodeMirror.defineOption("hmdFold", defaultOption, function (cm: cm_t, newVal: OptionValueType) {
///// convert newVal's type to `Record<string, boolean>`, if it is not.
if (!newVal || typeof newVal === "boolean") {
newVal = newVal ? suggestedOption : defaultOption
}
if ('customFolders' in newVal) {
console.error('[HyperMD][Fold] `customFolders` is removed. To use custom folders, `registerFolder` first.')
delete newVal['customFolders']
}
///// apply config
var inst = getAddon(cm)
for (const type in folderRegistry) {
inst.setStatus(type, newVal[type])
}
// then, folding task will be queued by setStatus()
})
//#endregion
/********************************************************************************** */
//#region Addon Class
export class Fold extends TokenSeeker implements Addon.Addon, FoldStream {
/**
* stores Folder status for current editor
* @private To enable/disable folders, use `setStatus()`
*/
private _enabled: Record<string, boolean> = {}
/** Folder's output goes here */
public folded: Record<string, HmdTextMarker[]> = {};
/** enable/disable one kind of folder, in current editor */
setStatus(type: string, enabled: boolean) {
if (!(type in folderRegistry)) return
if (!this._enabled[type] !== !enabled) {
this._enabled[type] = !!enabled
if (enabled) this.startFold()
else this.clear(type)
}
}
constructor(public cm: cm_t) {
super(cm)
cm.on("changes", (cm, changes) => {
var changedMarkers: HmdTextMarker[] = []
for (const change of changes) {
let markers = cm.findMarks(change.from, change.to) as HmdTextMarker[]
for (const marker of markers) {
if (marker._hmd_fold_type) changedMarkers.push(marker)
}
}
for (const m of changedMarkers) {
m.clear() // TODO: add "changed" handler for FolderFunc
}
this.startFold();
})
cm.on("cursorActivity", (cm) => {
if (DEBUG) console.time('CA')
let lineStuff: {
[lineNo: string]: {
lineNo: number, ch: number[],
markers: [HmdTextMarker, number, number][] // two numbers are: char_from char_to
}
} = {}
function addPosition(pos: CodeMirror.Position) {
const lineNo = pos.line
if (!(lineNo in lineStuff)) {
let lh = cm.getLineHandle(pos.line)
let ms = lh.markedSpans || []
let markers = [] as [HmdTextMarker, number, number][]
for (let i = 0; i < ms.length; i++) {
let marker = ms[i].marker as HmdTextMarker
if ('_hmd_crange' in marker) {
let from = marker._hmd_crange[0].line < lineNo ? 0 : marker._hmd_crange[0].ch
let to = marker._hmd_crange[1].line > lineNo ? lh.text.length : marker._hmd_crange[1].ch
markers.push([marker, from, to])
}
}
lineStuff[lineNo] = {
lineNo, ch: [pos.ch],
markers,
}
} else {
lineStuff[lineNo].ch.push(pos.ch)
}
}
cm.listSelections().forEach(selection => {
addPosition(selection.anchor)
addPosition(selection.head)
})
for (let tmp_id in lineStuff) {
let lineData = lineStuff[tmp_id]
if (!lineData.markers.length) continue
for (let i = 0; i < lineData.ch.length; i++) {
const ch = lineData.ch[i]
for (let j = 0; j < lineData.markers.length; j++) {
let [marker, from, to] = lineData.markers[j]
if (from <= ch && ch <= to) {
marker.clear()
lineData.markers.splice(j, 1)
j--
}
}
}
}
if (DEBUG) console.timeEnd('CA')
this.startQuickFold()
})
}
///////////////////////////////////////////////////////////////////////////////////////////
/// BEGIN OF APIS THAT EXPOSED TO FolderFunc
/// @see FoldStream
/**
* Check if a range is foldable and update _quickFoldHint
*
* NOTE: this function is always called after `_quickFoldHint` reset by `startFoldImmediately`
*/
requestRange(from: Position, to: Position, cfrom?: Position, cto?: Position): RequestRangeResult {
if (!cto) cto = to
if (!cfrom) cfrom = from
const cm = this.cm
var markers = cm.findMarks(from, to)
if (markers.length !== 0) return RequestRangeResult.HAS_MARKERS
this._quickFoldHint.push(from.line)
// store "crange" for the coming marker
this._lastCRange = [cfrom, cto]
const selections = cm.listSelections()
for (let i = 0; i < selections.length; i++) {
let oselection = orderedRange(selections[i])
// note that "crange" can be bigger or smaller than marked-text range.
if (rangesIntersect(this._lastCRange, oselection) || rangesIntersect([from, to], oselection)) {
return RequestRangeResult.CURSOR_INSIDE
}
}
this._quickFoldHint.push(cfrom.line)
return RequestRangeResult.OK
}
/// END OF APIS THAT EXPOSED TO FolderFunc
///////////////////////////////////////////////////////////////////////////////////////////
/**
* Fold everything! (This is a debounced, and `this`-binded version)
*/
startFold = debounce(this.startFoldImmediately.bind(this), 100)
/**
* Fold everything!
*
* @param toLine last line to fold. Inclusive
*/
startFoldImmediately(fromLine?: number, toLine?: number) {
const cm = this.cm
fromLine = fromLine || cm.firstLine()
toLine = (toLine || cm.lastLine()) + 1
this._quickFoldHint = []
this.setPos(fromLine, 0, true)
if (DEBUG) {
console.log("start fold! ", fromLine, toLine)
}
cm.operation(() => cm.eachLine(fromLine, toLine, line => {
var lineNo = line.lineNo()
if (lineNo < this.lineNo) return // skip current line...
else if (lineNo > this.lineNo) this.setPos(lineNo, 0) // hmmm... maybe last one is empty line
// all the not-foldable chars are marked
var charMarked = new FlagArray(line.text.length)
{
// populate charMarked array.
// @see CodeMirror's findMarksAt
let lineMarkers = line.markedSpans
if (lineMarkers) {
for (let i = 0; i < lineMarkers.length; ++i) {
let span = lineMarkers[i]
let spanFrom = span.from == null ? 0 : span.from
let spanTo = span.to == null ? charMarked.length : span.to
for (let j = spanFrom; j < spanTo; j++) charMarked[j] = 1
}
}
}
const tokens = this.lineTokens
while (this.i_token < tokens.length) {
var token = tokens[this.i_token]
var type: string
var marker: HmdTextMarker = null
var tokenFoldable: boolean = true
{
for (let i = token.start; i < token.end; i++) {
if (charMarked[i]) {
tokenFoldable = false
break
}
}
}
if (tokenFoldable) {
// try all enabled folders in registry
for (type in folderRegistry) {
if (!this._enabled[type]) continue
if (marker = folderRegistry[type](this, token)) break
}
}
if (!marker) {
// this token not folded. check next
this.i_token++
} else {
var { from, to } = marker.find();
(this.folded[type] || (this.folded[type] = [])).push(marker)
marker._hmd_fold_type = type;
marker._hmd_crange = this._lastCRange;
marker.on('clear', (from, to) => {
var markers = this.folded[type]
var idx: number
if (markers && (idx = markers.indexOf(marker)) !== -1) markers.splice(idx, 1)
this._quickFoldHint.push(from.line)
})
if (DEBUG) {
console.log("[FOLD] New marker ", type, from, to, marker)
}
// now let's update the pointer position
if (from.line > lineNo || from.ch > token.start) {
// there are some not-marked chars after current token, before the new marker
// first, advance the pointer
this.i_token++
// then mark the hidden chars as "marked"
let fromCh = from.line === lineNo ? from.ch : charMarked.length
let toCh = to.line === lineNo ? to.ch : charMarked.length
for (let i = fromCh; i < toCh; i++) charMarked[i] = 1
} else {
// classical situation
// new marker starts since current token
if (to.line !== lineNo) {
this.setPos(to.line, to.ch)
return // nothing left in this line
} else {
this.setPos(to.ch) // i_token will be updated by this.setPos()
}
}
}
}
}))
}
/** stores every affected lineNo */
private _quickFoldHint: number[] = []
private _lastCRange: [Position, Position]
/**
* Start a quick fold: only process recent `requestRange`-failed ranges
*/
startQuickFold() {
var hint = this._quickFoldHint
if (hint.length === 0) return
var from = hint[0], to = from
for (const lineNo of hint) {
if (from > lineNo) from = lineNo
if (to < lineNo) to = lineNo
}
this.startFold.stop()
this.startFoldImmediately(from, to)
}
/**
* Clear one type of folded TextMarkers
*
* @param type builtin folder type ("image", "link" etc) or custom fold type
*/
clear(type: string) {
this.startFold.stop()
var folded = this.folded[type]
if (!folded || !folded.length) return
var marker: CodeMirror.TextMarker
while (marker = folded.pop()) marker.clear()
}
/**
* Clear all folding result
*/
clearAll() {
this.startFold.stop()
for (const type in this.folded) {
var folded = this.folded[type]
var marker: CodeMirror.TextMarker
while (marker = folded.pop()) marker.clear()
}
}
}
//#endregion
/** ADDON GETTER (Singleton Pattern): a editor can have only one Fold instance */
export const getAddon = Addon.Getter("Fold", Fold)
declare global { namespace HyperMD { interface HelperCollection { Fold?: Fold } } } | the_stack |
import {
observable
} from '@tko/observable'
import {
computed
} from '@tko/computed'
import components from '../dist'
describe('Components: Loader registry', function () {
var testAsyncDelay = 20,
testComponentName = 'test-component',
testComponentConfig = {},
testComponentDefinition = { template: {} },
loaderThatDoesNotReturnAnything = {
getConfig: function (name, callback) {
expect(name).toBe(testComponentName)
setTimeout(function () { callback(null) }, testAsyncDelay)
},
loadComponent: function (name, config, callback) {
expect(name).toBe(testComponentName)
expect(config).toBe(testComponentConfig)
setTimeout(function () { callback(null) }, testAsyncDelay)
}
},
loaderThatHasNoHandlers = {},
loaderThatReturnsConfig = {
getConfig: function (name, callback) {
expect(name).toBe(testComponentName)
setTimeout(function () { callback(testComponentConfig) }, testAsyncDelay)
}
},
loaderThatReturnsDefinition = {
loadComponent: function (name, config, callback) {
expect(name).toBe(testComponentName)
expect(config).toBe(testComponentConfig)
setTimeout(function () { callback(testComponentDefinition) }, testAsyncDelay)
}
},
loaderThatShouldNeverBeCalled = {
getConfig: function () { throw new Error('Should not be called') },
loadComponent: function () { throw new Error('Should not be called') }
},
loaderThatCompletesSynchronously = {
getConfig: function (name, callback) { callback(testComponentConfig) },
loadComponent: function (name, config, callback) {
expect(config).toBe(testComponentConfig)
callback(testComponentDefinition)
}
},
testLoaderChain = function (spec, chain, options) {
spec.restoreAfter(components, 'loaders')
// Set up a chain of loaders, then query it
components.loaders = chain
var loadedDefinition = 'Not yet loaded'
components.get(testComponentName, function (definition) {
loadedDefinition = definition
})
var onLoaded = function () {
if ('expectedDefinition' in options) {
expect(loadedDefinition).toBe(options.expectedDefinition)
}
if ('done' in options) {
options.done(loadedDefinition)
}
}
// Wait for and verify result
if (loadedDefinition !== 'Not yet loaded') {
// Completed synchronously
onLoaded()
} else {
// Will complete asynchronously
window.waitsFor(function () { return loadedDefinition !== 'Not yet loaded' }, 300)
runs(onLoaded)
}
}
afterEach(function () {
components.unregister(testComponentName)
})
it('Exposes the list of loaders as an array', function () {
expect(components.loaders instanceof Array).toBe(true)
})
it("issues a PEBKAC when a component name does not have a dash", function () {
const logs = []
const orlog = console.log
console.log = (v) => logs.push(v)
components.register('testname', { template: {} })
expect(logs.length).toEqual(1)
expect(logs[0]).toContain('Knockout warning')
console.log = orlog
components.unregister('testname')
})
it("does not issue a PEBCAK when `ignoreCustomElementWarning` is true", function () {
const logs = []
const orlog = console.log
console.log = (v) => logs.push(v)
components.register('testname', { template: {}, ignoreCustomElementWarning: true })
expect(logs.length).toEqual(0)
console.log = orlog
components.unregister('testname')
})
it('Obtains component config and component definition objects by invoking each loader in turn, asynchronously, until one supplies a value', function () {
var loaders = [
loaderThatDoesNotReturnAnything,
loaderThatHasNoHandlers,
loaderThatReturnsDefinition,
loaderThatDoesNotReturnAnything,
loaderThatReturnsConfig,
loaderThatShouldNeverBeCalled
]
testLoaderChain(this, loaders, { expectedDefinition: testComponentDefinition })
})
it('Supplies null if no registered loader returns a config object', function () {
var loaders = [
loaderThatDoesNotReturnAnything,
loaderThatHasNoHandlers,
loaderThatReturnsDefinition,
loaderThatDoesNotReturnAnything
]
testLoaderChain(this, loaders, { expectedDefinition: null })
})
it('Supplies null if no registered loader returns a component for a given config object', function () {
var loaders = [
loaderThatDoesNotReturnAnything,
loaderThatHasNoHandlers,
loaderThatReturnsConfig,
loaderThatDoesNotReturnAnything
]
testLoaderChain(this, loaders, { expectedDefinition: null })
})
it('Aborts if a getConfig call returns a value other than undefined', function () {
// This is just to leave open the option to support synchronous return values in the future.
// We would detect that a getConfig call wants to return synchronously based on getting a
// non-undefined return value, and in that case would not wait for the callback.
var loaders = [
loaderThatReturnsDefinition,
loaderThatDoesNotReturnAnything,
{
getConfig: function (name, callback) {
setTimeout(function () { callback(testComponentDefinition) }, 50)
return testComponentDefinition // This is what's not allowed
},
// Unfortunately there's no way to catch the async exception, and we don't
// want to clutter up the console during tests, so suppress this
suppressLoaderExceptions: true
},
loaderThatReturnsConfig
]
testLoaderChain(this, loaders, { expectedDefinition: null })
})
it('Aborts if a loadComponent call returns a value other than undefined', function () {
// This is just to leave open the option to support synchronous return values in the future.
// We would detect that a loadComponent call wants to return synchronously based on getting a
// non-undefined return value, and in that case would not wait for the callback.
var loaders = [
loaderThatReturnsConfig,
loaderThatDoesNotReturnAnything,
{
loadComponent: function (name, config, callback) {
setTimeout(function () { callback(testComponentDefinition) }, 50)
return testComponentDefinition // This is what's not allowed
},
// Unfortunately there's no way to catch the async exception, and we don't
// want to clutter up the console during tests, so suppress this
suppressLoaderExceptions: true
},
loaderThatReturnsDefinition
]
testLoaderChain(this, loaders, { expectedDefinition: null })
})
it('Ensures that the loading process completes asynchronously, even if the loader completed synchronously', function () {
// This behavior is for consistency. Developers calling components.get shouldn't have to
// be concerned about whether the callback fires before or after their next line of code.
var wasAsync = false
testLoaderChain(this, [loaderThatCompletesSynchronously], {
expectedDefinition: testComponentDefinition,
done: function () {
expect(wasAsync).toBe(true)
}
})
wasAsync = true
})
it('Supplies component definition synchronously if the "synchronous" flag is provided and the loader completes synchronously', function () {
// Set up a synchronous loader that returns a component marked as synchronous
this.restoreAfter(components, 'loaders')
var testSyncComponentConfig = { synchronous: true },
testSyncComponentDefinition = { },
syncComponentName = 'my-sync-component',
getConfigCallCount = 0
components.loaders = [{
getConfig: function (name, callback) {
getConfigCallCount++
callback(testSyncComponentConfig)
},
loadComponent: function (name, config, callback) {
expect(config).toBe(testSyncComponentConfig)
callback(testSyncComponentDefinition)
}
}]
// See that the initial load can complete synchronously
var initialLoadCompletedSynchronously = false
components.get(syncComponentName, function (definition) {
expect(definition).toBe(testSyncComponentDefinition)
initialLoadCompletedSynchronously = true
})
expect(initialLoadCompletedSynchronously).toBe(true)
expect(getConfigCallCount).toBe(1)
// See that subsequent cached loads can complete synchronously
var cachedLoadCompletedSynchronously = false
components.get(syncComponentName, function (definition) {
expect(definition).toBe(testSyncComponentDefinition)
cachedLoadCompletedSynchronously = true
})
expect(cachedLoadCompletedSynchronously).toBe(true)
expect(getConfigCallCount).toBe(1) // Was cached, so no extra loads
// See that, if you use components.get synchronously from inside a computed,
// it ignores dependencies read inside the callback. That is, the callback only
// fires once even if something it accesses changes.
// This represents @lavimc's comment on https://github.com/knockout/knockout/commit/ee6df1398e08e9cc85a7a90497b6d043562d0ed0
// This behavior might be debatable, since conceivably you might want your computed to
// react to observables accessed within the synchronous callback. However, developers
// are at risk of bugs if they do that, because the callback might always fire async
// if the component isn't yet loaded, then their computed would die early. The argument for
// this behavior, then, is that it prevents a really obscure and hard-to-repro race condition
// bug by stopping developers from relying on synchronous dependency detection here at all.
var someObservable = observable('Initial'),
callbackCount = 0
computed(function () {
components.get(syncComponentName, function (/* definition */) {
callbackCount++
someObservable()
})
})
expect(callbackCount).toBe(1)
someObservable('Modified')
expect(callbackCount).toBe(1) // No extra callback
})
it('Supplies component definition synchronously if the "synchronous" flag is provided and definition is already cached', function () {
// Set up an asynchronous loader chain that returns a component marked as synchronous
this.restoreAfter(components, 'loaders')
this.after(function () { delete testComponentConfig.synchronous })
testComponentConfig.synchronous = 'trueish value'
components.loaders = [loaderThatReturnsConfig, loaderThatReturnsDefinition]
// Perform an initial load to prime the cache. Also verify it's set up to be async.
var initialLoadWasAsync = false
getComponentDefinition(testComponentName, function (initialDefinition) {
expect(initialLoadWasAsync).toBe(true)
expect(initialDefinition).toBe(testComponentDefinition)
// Perform a subsequent load and verify it completes synchronously, because
// the component config has the 'synchronous' flag
var cachedLoadWasSynchronous = false
components.get(testComponentName, function (cachedDefinition) {
cachedLoadWasSynchronous = true
expect(cachedDefinition).toBe(testComponentDefinition)
})
expect(cachedLoadWasSynchronous).toBe(true)
})
initialLoadWasAsync = true // We verify that this line runs *before* the definition load completes above
})
it('By default, contains only the default loader', function () {
expect(components.loaders.length).toBe(1)
expect(components.loaders[0]).toBe(components.defaultLoader)
})
it('Caches and reuses loaded component definitions', function () {
// Ensure we leave clean state after the test
this.after(function () {
components.unregister('some-component')
components.unregister('other-component')
})
components.register('some-component', {
viewModel: function () { this.isTheTestComponent = true }
})
components.register('other-component', {
viewModel: function () { this.isTheOtherComponent = true }
})
// Fetch the component definition, and see it's the right thing
var definition1
getComponentDefinition('some-component', function (definition) {
definition1 = definition
expect(definition1.createViewModel().isTheTestComponent).toBe(true)
})
// Fetch it again, and see the definition was reused
getComponentDefinition('some-component', function (definition2) {
expect(definition2).toBe(definition1)
})
// See that requests for other component names don't reuse the same cache entry
getComponentDefinition('other-component', function (otherDefinition) {
expect(otherDefinition).not.toBe(definition1)
expect(otherDefinition.createViewModel().isTheOtherComponent).toBe(true)
})
// See we can choose to force a refresh by clearing a cache entry before fetching a definition.
// This facility probably won't be used by most applications, but it is helpful for tests.
runs(function () { components.clearCachedDefinition('some-component') })
getComponentDefinition('some-component', function (definition3) {
expect(definition3).not.toBe(definition1)
expect(definition3.createViewModel().isTheTestComponent).toBe(true)
})
// See that unregistering a component implicitly clears the cache entry too
runs(function () { components.unregister('some-component') })
getComponentDefinition('some-component', function (definition4) {
expect(definition4).toBe(null)
})
})
it('Only commences a single loading process, even if multiple requests arrive before loading has completed', function () {
// Set up a mock AMD environment that logs calls
var someModuleTemplate = [],
someComponentModule = { template: someModuleTemplate },
requireCallLog = []
this.restoreAfter(window, 'require')
window.require = function (modules, callback) {
requireCallLog.push(modules.slice(0))
setTimeout(function () { callback(someComponentModule) }, 80)
}
components.register(testComponentName, { require: 'path/testcomponent' })
// Begin loading the module; see it synchronously made a request to the module loader
var definition1
components.get(testComponentName, function (loadedDefinition) {
definition1 = loadedDefinition
})
expect(requireCallLog).toEqual([['path/testcomponent']])
// Even a little while later, the module hasn't yet loaded
var definition2
waits(20)
runs(function () {
expect(definition1).toBe(undefined)
// ... but let's make a second request for the same module
components.get(testComponentName, function (loadedDefinition) {
definition2 = loadedDefinition
})
// This time there was no further request to the module loader
expect(requireCallLog.length).toBe(1)
})
// And when the loading eventually completes, both requests are satisfied with the same definition
window.waitsFor(function () { return definition1 }, 300)
runs(function () {
expect(definition1.template).toBe(someModuleTemplate)
expect(definition2).toBe(definition1)
})
// Subsequent requests also don't involve calls to the module loader
getComponentDefinition(testComponentName, function (definition3) {
expect(definition3).toBe(definition1)
expect(requireCallLog.length).toBe(1)
})
})
function getComponentDefinition (componentName, assertionCallback) {
var loadedDefinition,
hasCompleted = false
runs(function () {
components.get(componentName, function (definition) {
loadedDefinition = definition
hasCompleted = true
})
expect(hasCompleted).toBe(false) // Should always complete asynchronously
})
window.waitsFor(function () { return hasCompleted })
runs(function () { assertionCallback(loadedDefinition) })
}
}) | the_stack |
import avro from "avsc";
import _ from "lodash";
import dynamic from "next/dynamic";
import numbro from "numbro";
const Moment = dynamic(import("react-moment"), { ssr: false });
type TimeagoType = "timeago";
export type InputType = "text" | "hex" | "integer" | "float" | "datetime" | "boolean" | "numeric" | "uuid";
export interface Index {
fields: string[];
primary: boolean;
}
export class Schema {
public indexes: Index[];
public primaryIndex?: Index;
public avroSchema: avro.types.RecordType;
public columns: Column[];
constructor(avroSchema: string, indexes: Index[]) {
this.indexes = indexes;
for (const index of indexes) {
if (index.primary) {
this.primaryIndex = index;
break;
}
}
this.avroSchema = avro.Type.forSchema(JSON.parse(avroSchema), {
logicalTypes: {
decimal: Decimal,
uuid: UUID,
"timestamp-millis": DateType,
},
}) as avro.types.RecordType;
this.columns = this.avroSchema.fields.map((field) => {
const key = !!this.primaryIndex?.fields.includes(field.name);
return new Column(field.name, field.name, field.type, (field as any).doc, key);
});
}
public getColumns(includeTimestamp?: boolean) {
if (includeTimestamp) {
const tsCol = new Column("@meta.timestamp", "Time ago", "timeago", undefined, false);
return this.columns.concat([tsCol]);
}
return this.columns;
}
}
export class Column {
public name: string;
public displayName: string;
public type: avro.Type | TimeagoType;
public inputType: InputType;
public typeName: string;
public typeDescription: string;
public doc: string | undefined;
public isKey: boolean;
public isNullable: boolean;
public isNumeric: boolean;
public formatter: (val: any) => string;
constructor(
name: string,
displayName: string,
type: avro.Type | TimeagoType,
doc: string | undefined,
isKey: boolean
) {
this.name = name;
this.displayName = displayName;
this.type = type;
this.doc = doc;
this.isKey = isKey;
this.isNullable = false;
// unwrap union types (i.e. nullables, since unions in Beneath are always [null, actualType])
if (this.type !== "timeago" && avro.Type.isType(this.type, "union:unwrapped")) {
const union = this.type as avro.types.UnwrappedUnionType;
// assert second type is actual type
if (union.types.length !== 2 || !avro.Type.isType(union.types[0], "null")) {
console.error("Got corrupted union type: ", union.types);
}
this.type = union.types[1];
this.isNullable = true;
}
// get inputType
this.inputType = this.makeInputType(this.type);
// compute isNumeric
this.isNumeric = false;
if (this.type !== "timeago") {
const t = this.type.typeName;
if (t === "int" || t === "long" || t === "float" || t === "double") {
this.isNumeric = true;
}
}
// compute type description
const { name: typeName, description: typeDescription } = this.makeTypeDescription(this.type);
this.typeName = typeName;
this.typeDescription = typeDescription;
// make formatter
this.formatter = this.makeFormatter();
}
public formatRecord(record: any) {
return this.formatter(_.get(record, this.name));
}
private makeTypeDescription = (type: avro.Type | TimeagoType): { name: string; description: string } => {
if (type === "timeago") {
return { name: "Timestamp", description: "Date and time with millisecond-precision, displayed as relative time" };
}
if (avro.Type.isType(type, "logical:timestamp-millis")) {
return {
name: "Timestamp",
description: "Date and time with millisecond-precision, displayed in your local timezone",
};
}
if (avro.Type.isType(type, "logical:decimal")) {
return { name: "Numeric", description: "Integer with up to 128 digits" };
}
if (avro.Type.isType(type, "logical:uuid")) {
return { name: "UUID", description: "16-byte unique identifier" };
}
if (avro.Type.isType(type, "boolean")) {
return { name: "Bool", description: "True or false" };
}
if (avro.Type.isType(type, "int")) {
return { name: "Int", description: "32-bit integer" };
}
if (avro.Type.isType(type, "long")) {
return { name: "Long", description: "64-bit integer" };
}
if (avro.Type.isType(type, "float")) {
return { name: "Float", description: "32-bit float" };
}
if (avro.Type.isType(type, "double")) {
return { name: "Double", description: "64-bit float" };
}
if (avro.Type.isType(type, "bytes")) {
return { name: "Bytes", description: "Variable-length byte array, displayed in base64" };
}
if (avro.Type.isType(type, "fixed")) {
const fixed = this.type as avro.types.FixedType;
return { name: `Bytes${fixed.size}`, description: `Fixed-length byte array of size ${fixed.size}` };
}
if (avro.Type.isType(type, "string")) {
return { name: "String", description: "Variable-length UTF-8 string" };
}
if (avro.Type.isType(type, "enum")) {
const enumT = this.type as avro.types.EnumType;
return { name: `${enumT.name}`, description: `Enum with options: ${enumT.symbols.join(", ")}` };
}
if (avro.Type.isType(type, "array")) {
const array = this.type as avro.types.ArrayType;
const { name, description } = this.makeTypeDescription(array.itemsType);
return { name: `${name}[]`, description: `Array of: ${description}` };
}
if (avro.Type.isType(type, "record")) {
const record = this.type as avro.types.RecordType;
const summary = record.fields.map((field) => {
const { name } = this.makeTypeDescription(field.type);
return field.name + ": " + name;
});
return { name: record.name || "record", description: `Record with fields: ${summary}` };
}
console.error("Unrecognized type: ", type);
return { name: "Unknown", description: "Type not known" };
};
private makeInputType = (type: avro.Type | TimeagoType) => {
if (avro.Type.isType(type, "logical:timestamp-millis")) {
return "datetime";
}
if (avro.Type.isType(type, "int", "long")) {
return "integer";
}
if (avro.Type.isType(type, "float", "double")) {
return "float";
}
if (avro.Type.isType(type, "bytes", "fixed")) {
return "hex";
}
if (avro.Type.isType(type, "string", "enum")) {
return "text";
}
if (avro.Type.isType(type, "boolean")) {
return "boolean";
}
if (avro.Type.isType(type, "logical:decimal")) {
return "numeric";
}
if (avro.Type.isType(type, "logical:uuid")) {
return "uuid";
}
if (type === "timeago") {
// shouldn't ever need this
return "datetime";
}
return "text";
};
private makeFormatter() {
const nonNullFormatter = this.makeNonNullFormatter();
return (val: any) => {
if (val === undefined || val === null) {
return "";
}
return nonNullFormatter(val);
};
}
private makeNonNullFormatter() {
if (this.type === "timeago") {
return (val: any) => <Moment fromNow ago date={val} />;
}
if (avro.Type.isType(this.type, "logical:timestamp-millis")) {
return (val: any) => <Moment date={val} format="YYYY-MM-DDTHH:mm:ssZ" />;
}
if (avro.Type.isType(this.type, "int", "long")) {
return (val: any) => {
try {
return Number(val).toLocaleString("en-US");
} catch (e) {
return Number(val).toLocaleString();
}
};
}
if (avro.Type.isType(this.type, "float", "double")) {
return (val: any) => {
// handle NaN, Infinity, and -Infinity
if (typeof val === "string") {
return val.toString();
}
return numbro(val).format("0,0.000");
};
}
if (avro.Type.isType(this.type, "logical:decimal")) {
return (val: any) => {
try {
return BigInt(val).toLocaleString("en-US");
} catch (e) {
return BigInt(val).toLocaleString();
}
};
}
if (avro.Type.isType(this.type, "array", "record")) {
return (val: any) => JSON.stringify(val);
}
if (avro.Type.isType(this.type, "boolean")) {
return (val: any) => {
const boolString = val.toString();
return boolString.charAt(0).toUpperCase() + boolString.slice(1);
};
}
return (val: any) => val;
}
}
class DateType extends avro.types.LogicalType {
public _fromValue(val: any) {
return new Date(val);
}
public _toValue(date: any) {
return date instanceof Date ? +date : undefined;
}
public _resolve(type: avro.Type) {
if (avro.Type.isType(type, "long", "string", "logical:timestamp-millis")) {
return this._fromValue;
}
}
}
class Decimal extends avro.types.LogicalType {
public _fromValue(val: any) {
return val;
}
public _toValue(val: any) {
return val;
}
public _resolve(type: avro.Type) {
if (avro.Type.isType(type, "long", "string", "logical:decimal")) {
return this._fromValue;
}
}
}
class UUID extends avro.types.LogicalType {
public _fromValue(val: any) {
return val;
}
public _toValue(val: any) {
return val;
}
public _resolve(type: avro.Type) {
if (avro.Type.isType(type, "string", "logical:uuid")) {
return this._fromValue;
}
}
}
export const getPlaceholder = (type: InputType) => {
if (type === "text") {
return "Abcd...";
} else if (type === "hex") {
return "0x12ab...";
} else if (type === "integer" || type === "numeric") {
return "1234...";
} else if (type === "float") {
return "1.234...";
} else if (type === "datetime") {
return "2006-01-02T15:04:05";
} else if (type === "boolean") {
return "true";
} else if (type === "uuid") {
return "00000000-0000-0000-0000-000000000000";
}
return "";
};
export const validateValue = (type: InputType, value: string): string | null => {
if (!value || value.length === 0 || type === "text") {
return null;
}
if (type === "hex") {
if (!value.match(/^0x[0-9a-fA-F]+$/) || value.length % 2 !== 0) {
return "Expected a hexadecimal value starting with '0x'";
}
} else if (type === "integer") {
if (!value.match(/^[0-9]+$/)) {
return "Expected an integer";
}
} else if (type === "float") {
if (isNaN(parseFloat(value))) {
return "Expected a floating-point number";
}
} else if (type === "datetime") {
const t = new Date(value);
if (isNaN(t.valueOf())) {
return "Expected a valid timestamp";
}
} else if (type === "boolean") {
if (!["true", "false"].includes(value.toLowerCase())) {
return "Expected a boolean";
}
} else if (type === "numeric") {
if (!value.match(/^[0-9]+$/)) {
return "Expected a whole number";
}
} else if (type === "uuid") {
if (
!(
value.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i) ||
value.match(/[0-9a-f]{32}/i) ||
value.match(/{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}}/i)
)
) {
return "Expected a UUID";
}
}
return null;
};
export const serializeValue = (type: InputType, value: string, isNullable: boolean): any => {
// Remove optional empty strings from the record object
if (isNullable && value === "") {
return null;
} else if (type === "text") {
return value;
} else if (type === "uuid") {
return value;
} else if (type === "integer") {
return parseInt(value);
} else if (type === "float") {
return parseFloat(value);
} else if (type === "datetime") {
const date = new Date(value);
return date.toISOString();
} else if (type === "boolean") {
return value.toLowerCase() === "true";
} else if (type === "hex") {
return hexToBase64(value);
} else if (type === "numeric") {
return value;
} else {
return value;
}
};
export const deserializeValue = (type: avro.Type, value: any) => {
if (avro.Type.isType(type, "string", "logical:uuid", "logical:timestamp-millis")) {
return value;
}
if (avro.Type.isType(type, "int", "long")) {
return (value as number).toString();
}
if (avro.Type.isType(type, "bytes", "fixed")) {
return base64ToHex(value);
}
};
const hexToBase64 = (hex: string) => {
if (hex.substr(0, 2) === "0x") {
hex = hex.substr(2);
}
let parsed = "";
for (let n = 0; n < hex.length; n += 2) {
parsed += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
}
return btoa(parsed);
};
const base64ToHex = (base64: string) => {
const raw = atob(base64);
let result = "";
for (let n = 0; n < raw.length; n++) {
const hex = raw.charCodeAt(n).toString(16);
result += hex.length === 2 ? hex : "0" + hex;
}
return "0x".concat(result);
}; | the_stack |
import 'react-datepicker/dist/react-datepicker.css'
import classNames from 'classnames'
import { sortBy } from 'lodash'
import { useState, useRef, ChangeEvent } from 'react'
import DatePicker from 'react-datepicker'
import { Helmet } from 'react-helmet'
import Recaptcha from 'react-recaptcha'
import Select from 'react-select'
import { Card, Link, InputGroup, Page } from 'src/components'
import { TOPICS } from 'src/components/config'
import { useDarkModeContext } from 'src/contexts/DarkModeContext'
import './DatePickerOverrides.module.scss'
import styles from './ConferenceForm.module.scss'
import { Conference } from './types/Conference'
import {
getConferenceData,
CONFERENCE_DATE_FORMAT,
} from './utils/getConferenceData'
const SORTED_TOPICS_KEYS = sortBy(Object.keys(TOPICS), (x) =>
TOPICS[x].toLocaleLowerCase()
)
const topicOptions = SORTED_TOPICS_KEYS.map((topic) => {
return {
value: topic,
label: TOPICS[topic],
}
})
const LOCATION_ONLINE_REGEX = /online|remote|everywhere|world|web|global|virtual|www|http/i
const VALID_URL_REGEX = /^http(s?):\/\//
const URL_PARAMETER_REGEX = /\?/
const URL_SHORTENER_REGEX = /(\/bitly)|(\/bit\.ly)|(\/t\.co)/i
const TWITTER_REGEX = /@(\w){1,15}$/
const UNWANTED_CONFERENCE_NAME_REGEX = /webinar|marketing|practical guide|meeting|trends|digimarcon|hackathon|101|estate|expo|techspo|outsourcing|physical|biology|neuroscience|healthcare|nutrition|Food Science/i
const UNWANTED_CONFERENCE_URL_REGEX = /webinar|marketing|hackathon|digimarcon/i
const LOCATION_TYPES = [
{
value: 'online',
name: 'Online',
},
{
value: 'in-person',
name: 'In person',
},
{
value: 'hybrid',
name: 'In person & online',
},
]
const defaultConference: Conference = {
name: '',
url: '',
city: '',
country: '',
startDate: null,
endDate: null,
topics: [],
cfpUrl: '',
cfpEndDate: null,
cocUrl: '',
online: true,
offersSignLanguageOrCC: false,
twitter: '@',
}
const ConferenceForm: React.FC = () => {
const endDateDatepickerRef = useRef<DatePicker>(null)
const [locationType, setLocationType] = useState('online')
const [recaptchaLoaded, setRecaptchaLoaded] = useState(false)
const [captchaResponse, setCaptchaResponse] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
const [serverError, setServerError] = useState(false)
const [errors, setErrors] = useState({})
const [conference, setConference] = useState(defaultConference)
const {
values: { darkModeEnabled },
} = useDarkModeContext()
const handleDateChangeBuilder = (key: string) => {
return (date: Date) => {
setConference({
...conference,
[key]: date,
})
}
}
const handleDateChange = {
startDate: handleDateChangeBuilder('startDate'),
endDate: handleDateChangeBuilder('endDate'),
cfpEndDate: handleDateChangeBuilder('cfpEndDate'),
}
const isUrlValid = (url: string) => {
return (
VALID_URL_REGEX.test(url) &&
!URL_PARAMETER_REGEX.test(url) &&
!URL_SHORTENER_REGEX.test(url) &&
!UNWANTED_CONFERENCE_URL_REGEX.test(url)
)
}
const validateForm = (conference: Conference) => {
const {
startDate,
endDate,
topics,
city,
country,
name,
url,
cfpUrl,
cfpEndDate,
twitter,
} = conference
const isNotOnline = locationType !== 'online'
const cfp = cfpUrl || cfpEndDate
const errors = {
topics: topics.length === 0,
name: startDate
? name.indexOf(startDate.getFullYear().toString().substring(2, 4)) !==
-1
: false,
url: !isUrlValid(url),
endDate: startDate && endDate ? startDate > endDate : false,
city: isNotOnline && LOCATION_ONLINE_REGEX.test(city),
country: isNotOnline && LOCATION_ONLINE_REGEX.test(country),
cfpUrl: cfpUrl.length === 0 ? cfp : !isUrlValid(cfpUrl) || url == cfpUrl,
cfpEndDate: startDate && cfpEndDate ? cfpEndDate >= startDate : cfp,
twitter: twitter.length <= 1 ? false : !TWITTER_REGEX.test(twitter),
unwantedConference:
name.length > 0 && UNWANTED_CONFERENCE_NAME_REGEX.test(name),
}
setErrors(errors)
return errors
}
const handleStartDateSelect = (startDate: Date) => {
const { endDate } = conference
endDateDatepickerRef.current?.setFocus()
setConference({
...conference,
startDate,
endDate: endDate || startDate,
})
}
const handleFieldChange = (
event: ChangeEvent<HTMLSelectElement | HTMLInputElement>
) => {
setConference({
...conference,
[event.target.name]: event.target.value,
})
}
// const handleTopicsChange = (topics) => {
// setConference({
// ...conference,
// topics: topics.map((topic) => topic.value),
// })
// }
const handleLocationTypeChange = (event: ChangeEvent<HTMLSelectElement>) => {
setLocationType(event.target.value)
setConference({
...conference,
online: ['online', 'hybrid'].includes(event.target.value),
})
}
const handleCheckboxChange = (event: ChangeEvent<HTMLInputElement>) => {
setConference({
...conference,
[event.target.name]: !conference[event.target.name],
})
}
// Executed once the captcha has been verified
// can be used to post forms, redirect, etc.
const handleVerifyRecaptcha = (captchaResponse: string) => {
setCaptchaResponse(captchaResponse)
}
const handleFormSubmit = (event: React.FormEvent) => {
const errors = validateForm(conference)
event.preventDefault()
const erroneousFieldId = Object.keys(errors).find((x) => errors[x])
if (!recaptchaLoaded || captchaResponse === null) {
return
}
if (erroneousFieldId) {
const erroneousField = document.getElementById(erroneousFieldId)
if (erroneousField && erroneousField.focus) {
erroneousField.focus()
}
return
}
setSubmitting(true)
fetch(`${process.env.REACT_APP_API_END_POINT_DOMAIN}/api/conferences`, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
method: 'post',
body: getConferenceData(conference),
})
.then((response) => {
if (response.status !== 200) {
throw new Error('Network response was not ok')
}
return response.json()
})
.then((responseJson) => {
const pullRequestUrl = responseJson.data.find(
(element: string[]) => element[0] == 'html_url'
)
if (pullRequestUrl) {
window.location.href = pullRequestUrl[1]
}
})
.catch(() => {
setServerError(true)
})
}
const hasError = (field: string) => {
return errors[field]
}
const errorFor = (field: string, errorMessage: string) => {
if (!errors[field]) {
return null
}
return <div className={styles.errorText}>{errorMessage}</div>
}
const {
name,
url,
city,
country,
cfpUrl,
twitter,
cocUrl,
offersSignLanguageOrCC,
startDate,
endDate,
cfpEndDate,
} = conference
return (
<Page
htmlTitle='Add a new conference to Confs.tech'
title='Add a new conference'
searchEngineTitle='Add a conference to Confs.tech and gain visibility'
backButton
>
<Helmet>
<script src='https://www.google.com/recaptcha/api.js' async defer />
</Helmet>
<div>
<p>
Confs.tech is focused on conferences on software development and
related topics, such as product management, UX, and AI.
</p>
<p>
Know a conference on one of these topics? Feel free to submit it using
this form!
</p>
<p>
This will create a{' '}
<Link
external
url='https://github.com/tech-conferences/conference-data/pulls'
>
pull request on GitHub
</Link>{' '}
where you can also add additional comments and track submission
status. Our team will review your request as soon as possible!
</p>
</div>
<div>
<Card>
<form onSubmit={handleFormSubmit} autoComplete='off'>
<InputGroup>
<div className={styles.Select}>
<label htmlFor='type'>Topic</label>
<Select
defaultValue={null}
isMulti
placeholder='Select one or more topics'
onChange={(topics) => {
setConference({
...conference,
topics: topics.map((topic) => topic?.value || ''),
})
}}
options={topicOptions}
/>
{errorFor('topics', 'You need to select at least one topic.')}
</div>
</InputGroup>
<InputGroup>
<div>
<label htmlFor='name'>Conference name</label>
<input
className={classNames(hasError('name') && styles.error)}
type='text'
name='name'
required
autoComplete='off'
placeholder='Conference name (without year)'
value={name}
id='name'
onChange={handleFieldChange}
/>
{errorFor('name', 'Name should not contain year.')}
</div>
</InputGroup>
<InputGroup>
<div>
<label htmlFor='url'>URL</label>
<input
className={classNames(hasError('url') && styles.error)}
type='url'
placeholder='Eg.: https://confs.tech'
required
value={url}
name='url'
id='url'
onChange={handleFieldChange}
/>
<div className={styles.InputHint}>
Must be valid, up and running and specific for the conference
</div>
{errorFor(
'url',
'Must be a valid URL. No query parameters or URL shorteners are allowed.'
)}
</div>
</InputGroup>
<InputGroup inline>
<div>
<label htmlFor='startDate'>Start date</label>
<DatePicker
dateFormat={CONFERENCE_DATE_FORMAT}
name='startDate'
id='startDate'
required
selected={startDate}
onChange={handleStartDateSelect}
placeholderText='Eg.: 2021-03-10'
/>
</div>
<div>
<label htmlFor='endDate'>End date</label>
<DatePicker
ref={endDateDatepickerRef}
dateFormat={CONFERENCE_DATE_FORMAT}
name='endDate'
id='endDate'
required
selected={endDate}
onChange={handleDateChange.endDate}
placeholderText='Eg.: 2021-03-12'
/>
{errorFor('endDate', 'End date is before start date.')}
</div>
</InputGroup>
<InputGroup>
<label htmlFor='locationType'>Location</label>
<select
id='locationType'
name='locationType'
value={locationType}
required
onChange={handleLocationTypeChange}
>
{LOCATION_TYPES.map((locationType) => (
<option key={locationType.value} value={locationType.value}>
{locationType.name}
</option>
))}
</select>
</InputGroup>{' '}
{locationType !== 'online' && (
<InputGroup inline>
<div>
<label htmlFor='city'>City</label>
<input
className={classNames(hasError('city') && styles.error)}
required={locationType !== 'online'}
type='text'
id='city'
name='city'
value={city}
onChange={handleFieldChange}
/>
{errorFor(
'city',
'For Online conferences please select location "online"'
)}
</div>
<div>
<label htmlFor='country'>Country</label>
<input
className={classNames(hasError('country') && styles.error)}
required={locationType !== 'online'}
type='text'
id='country'
name='country'
value={country}
onChange={handleFieldChange}
/>
{errorFor(
'country',
'For Online conferences please select location "online"'
)}
</div>
</InputGroup>
)}
<InputGroup inline>
<div>
<label htmlFor='cfpUrl'>CFP URL</label>
<input
className={classNames(hasError('cfpUrl') && styles.error)}
type='url'
name='cfpUrl'
id='cfpUrl'
value={cfpUrl}
onChange={handleFieldChange}
/>
{errorFor(
'cfpUrl',
'CFP URL must different than URL. No URL query parameters or URL shorteners are allowed.'
)}
</div>
<div>
<label htmlFor='cfpEndDate'>CFP end date</label>
<DatePicker
dateFormat={CONFERENCE_DATE_FORMAT}
name='cfpEndDate'
id='cfpEndDate'
selected={cfpEndDate}
onChange={handleDateChange.cfpEndDate}
/>
{errorFor('cfpEndDate', 'CFP end date is after start date.')}
</div>
</InputGroup>
<InputGroup>
<label htmlFor='twitter'>Conference @TwitterHandle</label>
<input
className={classNames(hasError('twitter') && styles.error)}
type='text'
name='twitter'
id='twitter'
value={twitter}
onChange={handleFieldChange}
/>
{errorFor('twitter', 'Should be formatted like @twitter')}
</InputGroup>
<InputGroup>
<label htmlFor='cocUrl'>Code Of Conduct URL</label>
<input
type='text'
name='cocUrl'
id='cocUrl'
value={cocUrl}
onChange={handleFieldChange}
/>
</InputGroup>
<InputGroup inline>
<input
type='checkbox'
name='offersSignLanguageOrCC'
id='offersSignLanguageOrCC'
checked={offersSignLanguageOrCC}
onChange={handleCheckboxChange}
/>
<label htmlFor='offersSignLanguageOrCC'>
This conference offers interpretation to International sign
language or closed captions.
</label>
</InputGroup>
<Recaptcha
sitekey='6Lf5FEoUAAAAAJtf3_sCGAAzV221KqRS4lAX9AAs'
render='explicit'
verifyCallback={handleVerifyRecaptcha}
onloadCallback={() => setRecaptchaLoaded(true)}
theme={darkModeEnabled ? 'dark' : 'light'}
/>
{serverError && (
<p className={styles.errorText}>
An error happened from the server.
<br />
If it still happens, you can
<Link
external
url='https://github.com/tech-conferences/conference-data/issues/new'
>
create an issue on our GitHub repo.
</Link>
</p>
)}
{errors['unwantedConference'] && (
<p className={styles.errorText}>
A part of the conference name has been blocklisted (Webinar,
Marketing, Hackathon, Meeting, Digimarcon, Techspo etc.)
<br />
Those submissions will not get added to our list
<Link
external
url='https://github.com/tech-conferences/conference-data/pulls?q=is%3Aunmerged'
>
(list of closed and not merged entries)
</Link>
<br />
Confs.tech is focused on conferences related to software
development. We believe that this event is not developer-related
and therefore, it is out of the confs.tech's scope.
<br />
If you think this was an error, and you want to add a software
developer related conference please
<Link
external
url='https://github.com/tech-conferences/conference-data/issues/new'
>
create an issue on our GitHub repo.
</Link>
</p>
)}
<button
className={styles.Button}
disabled={
submitting || !recaptchaLoaded || captchaResponse === null
}
type='submit'
value='Submit'
>
{submitting ? 'Submitting...' : 'Submit'}
</button>
</form>
</Card>
</div>
</Page>
)
}
export default ConferenceForm | the_stack |
interface AqlError extends Error {
new(message: string): Error;
name: string;
}
interface Operation extends Expression {
new(): Expression;
}
interface BinaryOperation extends Operation {
new(operator: string, value1: any, value2: any): Operation;
toAQL(): string;
_operator: string;
}
interface UnaryOperation extends Expression {
new(operator: string, value: any): Expression;
toAQL(): string;
_operator: string;
}
interface SimpleReference extends Expression {
new(value: string): Expression;
toAQL(): string;
re: RegExp;
_value: string;
}
interface RawExpression extends Expression {
new(value: any): Expression;
toAQL(): string;
}
interface BooleanLiteral extends Expression {
new(value: any): Expression;
toAQL(): string;
_value: boolean;
}
interface NumberLiteral extends Expression {
new(value: any): Expression;
toAQL(): string;
re: RegExp;
}
interface IntegerLiteral extends Expression {
new(value: any): Expression;
toAQL(): string;
_value: number;
}
interface StringLiteral extends Expression {
new(value: any): Expression;
toAQL(): string;
}
interface ListLiteral extends Expression {
new(...value: any[]): Expression;
toAQL(): string;
}
interface ObjectLiteral extends Expression {
new(value: any): Expression;
toAQL(): string;
_value: object;
}
interface NAryOperation extends Operation {
new(operator: string, values: any[]): Operation;
toAQL(): string;
_operator: string;
_values: Expression[];
}
interface RangeExpression extends Expression {
new(start: any, end?: any): Expression;
toAQL(): string;
_start: number;
_end: number;
re: RegExp;
}
interface PropertyAccess extends Expression {
new(obj: any, keys: any[]): Expression;
toAQL(): string;
_obj: Expression;
_keys: Expression[];
}
interface TernaryOperation extends Operation {
new(operator1: string, operator2: string, value1: Expression, value2: any, value3: any): Operation;
toAQL(): string;
_operator1: string;
_operator2: string;
}
interface NullLiteral extends Expression {
new(value: any): Expression;
toAQL(): string;
}
interface Keyword extends Expression {
new(value: any): Expression;
toAQL(): string;
_value: string;
re: RegExp;
}
interface Identifier extends Expression {
new(value: any): Expression;
toAQL(): string;
_value: string;
}
interface FunctionCall extends Expression {
new(functionName: string, ...args: any[]): Expression;
toAQL(): string;
_re: RegExp;
_functionName: string;
_args: any[];
}
interface ForExpression extends PartialStatement {
new(prev: PartialStatement, varname: any, expr: any): PartialStatement;
toAQL(): string;
_varname: Identifier;
}
interface FilterExpression extends PartialStatement {
new(prev: PartialStatement, expr: any): PartialStatement;
toAQL(): string;
}
interface Definitions {
new(...dfns: any[]): any;
toAQL(): string;
_dfns: any[];
}
interface LetExpression extends PartialStatement {
new(prev: PartialStatement, ...dfns: any[]): PartialStatement;
toAQL(): string;
_prev: PartialStatement;
_dfns: Definitions;
}
interface CollectExpression extends PartialStatement {
new(prev: PartialStatement, dfns: any[], varname: any, intoExpr: any, keepNames: any[], options: any): PartialStatement;
toAQL(): string;
into(...newVarname: any[]): CollectExpression;
keep(...x: any[]): any;
_keep: Identifier[];
options(newOpts: any): any;
_options: ObjectLiteral;
withCountInto(newVarname: any): CollectWithCountIntoExpression;
}
interface CollectWithCountIntoExpression extends PartialStatement {
new(prev: PartialStatement, dfns: any[], varname: any, options: any): PartialStatement;
toAQL(): string;
options(newOpts: any): any;
}
interface SortExpression extends PartialStatement {
new(prev: PartialStatement, ...args: any[]): PartialStatement;
toAQL(): string;
keywords: string[];
_args: Keyword[];
}
interface LimitExpression extends PartialStatement {
new(prev: PartialStatement, offset: any, count?: any): PartialStatement;
toAQL(): string;
}
interface ReturnExpression extends Expression {
new(prev: LetExpression, value: any, distinct: boolean): Expression;
toAQL(): string;
_prev: LetExpression;
_distinct: boolean;
}
interface RemoveExpression extends PartialStatement {
new(prev: PartialStatement, expr: any, collection: any, options: any): PartialStatement;
returnOld(x: any): ReturnExpression;
toAQL(): string;
options(newOpts: any): RemoveExpression;
}
interface UpsertExpression extends PartialStatement {
new(prev: PartialStatement, upsertExpr: any, insertExpr: any, replace: boolean, updateOrReplaceExpr: any, collection: any, options: any): PartialStatement;
returnNew(x: any): ReturnExpression;
returnOld(x: any): ReturnExpression;
toAQL(): string;
_updateOrReplace: string;
options(newOpts: any): UpsertExpression;
}
interface InsertExpression extends PartialStatement {
new(prev: PartialStatement, expr: any, collection: any, options: any): PartialStatement;
returnNew(x: any): ReturnExpression;
toAQL(): string;
options(newOpts: any): InsertExpression;
}
interface UpdateExpression extends PartialStatement {
new(prev: PartialStatement, expr: any, withExpr: any, collection: any, options: any): PartialStatement;
returnNew(x: any): ReturnExpression;
returnOld(x: any): ReturnExpression;
toAQL(): string;
options(newOpts: any): UpdateExpression;
}
interface ReplaceExpression extends PartialStatement {
new(prev: PartialStatement, expr: any, withExpr: any, collection: any, options: any): PartialStatement;
returnNew(x: any): ReturnExpression;
returnOld(x: any): ReturnExpression;
toAQL(): string;
options(newOpts: any): ReplaceExpression;
}
interface Expression extends PartialStatement {
/**
* Equality
*
* Creates an equality comparison from the given values.
*
* qb.eq(a, b): (a == b)
* OR:
* qbValue.eq(b): (a == b)
*
* If the values are not already values, they will be converted automatically.
*
* Examples
*
* qb.ref('x').eq('y'): (x == y)
*
*
*/
eq(x: any, y?: any): BinaryOperation;
/**
* Inequality
*
* Creates an inequality comparison from the given values.
*
* qb.neq(a, b): (a != b)
* OR:
* qbValue.neq(b): (a != b)
*
* If the values are not already values, they will be converted automatically.
*
* Examples
*
* qb.ref('x').neq('y'): (x != y)
*
*/
neq(x: any, y?: any): BinaryOperation;
/**
* Greater Than
*
* Creates a greater-than comparison from the given values.
*
* qb.gt(a, b): (a > b)
* OR
* qbValue.gt(b): (a > b)
*
* If the values are not already values, they will be converted automatically.
*
* Examples
*
* qb.ref('x').gt('y'): (x > y)
*
*
*/
gt(x: any, y?: any): BinaryOperation;
/**
* Greater Than Or Equal To
*
* Creates a greater-than-or-equal-to comparison from the given values.
*
* qb.gte(a, b): (a >= b)
* OR
* qbValue.gte(b): (a >= b)
*
* If the values are not already values, they will be converted automatically.
*
* Examples
*
* qb.ref('x').gte('y'): (x >= y)
*
*
*/
gte(x: any, y?: any): BinaryOperation;
/**
* Less Than
*
* Creates a less-than comparison from the given values.
*
* qb.lt(a, b): (a < b)
* OR
* qbValue.lt(b): (a < b)
*
* If the values are not already values, they will be converted automatically.
*
* Examples
*
* qb.ref('x').lt('y'): (x < y)
*
*/
lt(x: any, y?: any): BinaryOperation;
/**
* Less Than Or Equal To
*
* Creates a less-than-or-equal-to comparison from the given values.
*
* qb.lte(a, b): (a <= b)
* OR
* qbValue.lte(b): (a <= b)
*
* If the values are not already values, they will be converted automatically.
*
* Examples
*
* qb.ref('x').lte('y'): (x <= y)
*
*/
lte(x: any, y?: any): BinaryOperation;
/**
* Contains
*
* Creates an "in" comparison from the given values.
*
* qb.in(a, b): (a in b)
* OR:
* qbValue.in(b): (a in b)
*
* If the values are not already values, they will be converted automatically.
*
* Examples
* qb.ref('x').in('y'): (x in y)
*/
in(...x: any[]): BinaryOperation;
/**
* Negation
*
* Creates a negation from the given value.
*
* qb.not(a) => !(a)
* OR:
* qbValue.not() => !(a)
*
* If the value is not already an value, it will be converted automatically.
*
* Examples
*
* qb.not('x') => !(x)
*/
not(x?: any): UnaryOperation;
/**
* Negative Value
*
* Creates a negative value expression from the given value.
*
* qb.neg(a) => -(a)
* OR:
* qbValue.neg() => -(a)
*
* If the value is not already an AQL value, it will be converted automatically.
*
* Examples
*
* qb.neg('x') => -(x)
*/
neg(x?: any): UnaryOperation;
/**
* Negated Contains
*
* Creates a "not in" comparison from the given values.
*
* qb.notIn(a, b): (a not in b)
* OR:
* qbValue.notIn(b): (a not in b)
*
* If the values are not already values, they will be converted automatically.
*
* Examples
*
* qb.ref('x').notIn('y'): (x not in y)
*/
notIn(...x: any[]): BinaryOperation;
/**
* Boolean And
*
* Creates an "and" operation from the given values.
*
* qb.and(a, b) =>(a && b)
* OR:
* aqlValue.and(b) =>(a && b)
*
* If the values are not already AQL values, they will be converted automatically.
* This declare function can take any number of arguments.
*
* Examples
*
* qb.ref('x').and('y') =>(x && y)
*/
and(...x: any[]): NAryOperation;
/**
* Boolean Or
*
* Creates an "or" operation from the given values.
*
* qb.or(a, b): (a || b)
* OR:
* Value.or(b): (a || b)
*
* If the values are not already values, they will be converted automatically.
*
* This declare function can take any number of arguments.
*/
or(...x: any[]): NAryOperation;
/**
* Addition
*
* Creates an addition operation from the given values.
*
* qb.add(a, b): (a + b)
* OR:
* Value.add(b): (a + b)
*
* If the values are not already values, they will be converted automatically.
* This declare function can take any number of arguments.
*
* Alias: qb.plus(a, b)
*
* Examples
*
* qb.ref('x').plus('y'): (x + y)
*/
add(...x: any[]): NAryOperation;
plus(...x: any[]): NAryOperation;
/**
* Subtraction
*
* Creates a subtraction operation from the given values.
*
* qb.sub(a, b): (a - b)
* OR:
* Value.sub(b): (a - b)
*
* If the values are not already values, they will be converted automatically.
* This declare function can take any number of arguments.
*
* Alias: qb.minus(a, b)
*
* Examples
*
* qb.ref('x').minus('y'): (x - y)
*/
sub(...x: any[]): NAryOperation;
minus(...x: any[]): NAryOperation;
/**
* Multiplication
*
* Creates a multiplication operation from the given values.
*
* qb.mul(a, b): (a * b)
* OR:
* Value.mul(b): (a * b)
*
* If the values are not already values, they will be converted automatically.
* This declare function can take any number of arguments.
*
* Alias: qb.times(a, b)
*
* Examples
*
* qb.ref('x').times('y'): (x * y)
*/
mul(...x: any[]): NAryOperation;
times(...x: any[]): NAryOperation;
/**
* Division
*
* Creates a division operation from the given values.
*
* qb.div(a, b): (a / b)
* OR:
* Value.div(b): (a / b)
*
* If the values are not already values, they will be converted automatically.
* This declare function can take any number of arguments.
*
* Examples
* qb.ref('x').div('y'): (x / y)
*/
div(...x: any[]): NAryOperation;
/**
* Modulus
*
* Creates a modulus operation from the given values.
*
* qb.mod(a, b): (a % b)
* OR:
* Value.mod(b): (a % b)
*
* If the values are not already values, they will be converted automatically.
* This declare function can take any number of arguments.
*
* Examples
* qb.ref('x').mod('y'): (x % y)
*/
mod(...x: any[]): NAryOperation;
/**
* Range
*
* Creates a range expression from the given values.
*
* qb.range(value1, value2): value1..value2
*
* OR:
*
* Value.range(value2): value1..value2
*
* If the values are not already values, they will be converted automatically.
* Alias: qb.to(value1, value2)
*
* Examples
*
* qb(2).to(5): 2..5
*
*/
range(...value: number[]): RangeExpression;
/**
* Property Access
*
* Creates a property access expression from the given values.
*
* qb.get(obj, key): obj[key]
* OR:
* Obj.get(key): obj[key]
*
* If the values are not already values, they will be converted automatically.
*
* Examples
* qb.ref('x').get('y'): x[y]`
*
*/
get(value: any): PropertyAccess;
/**
* Ternary(if / else)
*
* Creates a ternary expression from the given values.
*
* qb.if(condition, thenDo, elseDo): (condition ? thenDo: elseDo)
* OR:
* qbValue.then(thenDo).else(elseDo): (condition ? thenDo: elseDo)
*
* If the values are not already values, they will be converted automatically.
*
* Alias: qbValue.then(thenDo).otherwise(elseDo)
*
* Examples
* qb.ref('x').then('y').else('z'): (x ? y: z)
*
*/
then(value: any): ThenRet;
}
interface ThenRet {
else(y: any): TernaryOperation;
else_: TernaryOperation;
otherwise(y: any): TernaryOperation;
}
interface ForRet {
in(expr: any): ForExpression;
in_: ForRet["in"];
}
/**
* PartialStatement
*
* In addition to the methods documented above, the query builder provides all methods of PartialStatement objects.
* Statement objects have a method toAQL() which returns their representation as a JavaScript string.
*
* Examples
*
* qb.for('doc').in('my_collection').return('doc._key').toAQL()
* // => FOR doc IN my_collection RETURN doc._key
*/
interface PartialStatement {
/**
* FOR expression IN collection
*
* PartialStatement::for(expression).in(collection): PartialStatement
*
* Examples
*
* _.for('doc').in('my_collection'): FOR doc IN my_collection
*
*/
for(varname: any): ForRet;
/**
* FILTER expression
*
* PartialStatement::filter(expression): PartialStatement
*
* Examples
*
* _.filter(qb.eq('a', 'b')): FILTER a == b
*
*/
filter(varname: any): FilterExpression;
/**
* LET varname = expression
*
* PartialStatement::let(varname, expression): PartialStatement
*
* Examples
*
* _.let('foo', 23): LET foo = 23
*
* LET var1 = expr1, var2 = expr2, …, varn = exprn
*
* PartialStatement::let(definitions): PartialStatement
*
*/
let(varname: {}, expr: any): LetExpression;
/**
* COLLECT
*
* COLLECT WITH COUNT INTO varname
* PartialStatement::collectWithCountInto(varname): CollectExpression
*
* Examples
*
* _.collectWithCountInto('x'): COLLECT WITH COUNT INTO x COLLECT varname = expression
* PartialStatement::collect(varname, expression): CollectExpression
*
* _.collect('x', 'y'): COLLECT x = y COLLECT var1 = expr1, var2 = expr2, …, varn = exprn
* PartialStatement::collect(definitions): CollectExpression
*
* _.collect({x: 'a', y: 'b'}): COLLECT x = a, y = b WITH COUNT INTO varname
* CollectExpression::withCountInto(varname): CollectExpression
*
* _.withCountInto('x'): WITH COUNT INTO x INTO varname
* CollectExpression::into(varname): CollectExpression
*
* _.into('z'): INTO z KEEP ...vars
* CollectExpression::keep(...vars): CollectExpression
*
* _.into('z').keep('a', 'b'): INTO z KEEP a, b INTO varname = expression
* CollectExpression::into(varname, expression): CollectExpression
*
* _.into('x', 'y'): INTO x = y OPTIONS options
* CollectExpression::options(options): CollectExpression
*
* _.options('opts'): OPTIONS opts
*
*/
collect(varname: any, expr: any): CollectExpression;
/**
* COLLECT
*
* COLLECT WITH COUNT INTO varname
* PartialStatement::collectWithCountInto(varname): CollectExpression
*
* Examples
*
* _.collectWithCountInto('x'): COLLECT WITH COUNT INTO x COLLECT varname = expression
* PartialStatement::collect(varname, expression): CollectExpression
*
* _.collect('x', 'y'): COLLECT x = y COLLECT var1 = expr1, var2 = expr2, …, varn = exprn
* PartialStatement::collect(definitions): CollectExpression
*
* _.collect({x: 'a', y: 'b'}): COLLECT x = a, y = b WITH COUNT INTO varname
* CollectExpression::withCountInto(varname): CollectExpression
*
* _.withCountInto('x'): WITH COUNT INTO x INTO varname
* CollectExpression::into(varname): CollectExpression
*
* _.into('z'): INTO z KEEP ...vars
* CollectExpression::keep(...vars): CollectExpression
*
* _.into('z').keep('a', 'b'): INTO z KEEP a, b INTO varname = expression
* CollectExpression::into(varname, expression): CollectExpression
*
* _.into('x', 'y'): INTO x = y OPTIONS options
* CollectExpression::options(options): CollectExpression
*
* _.options('opts'): OPTIONS opts
*
*/
collectWithCountInto(varname: any): CollectWithCountIntoExpression;
/**
* SORT ...args
*
* PartialStatement::sort(...args): PartialStatement
*
* Examples
*
* _.sort('x', 'DESC', 'y', 'ASC'): SORT x DESC, y ASC
*
*/
sort(...args: any[]): SortExpression;
/**
* LIMIT offset, count
*
* PartialStatement::limit([offset,] count): PartialStatement
*
* Examples
*
* _.limit(20): LIMIT 20
*
* _.limit(20, 20): LIMIT 20, 20
*
*/
limit(offset: any, count?: any): LimitExpression;
/**
* RETURN expression
*
* PartialStatement::return(expression): ReturnExpression
*
* Examples
*
* _.return('x'): RETURN x
* _.return({x: 'x'}): RETURN {x: x}
*
*/
return(x: any): ReturnExpression;
/**
* RETURN DISTINCT expression
*
* PartialStatement::returnDistinct(expression): ReturnExpression
*
* Examples
*
* _.returnDistinct('x'): RETURN DISTINCT x
*
*/
returnDistinct(x: any): ReturnExpression;
/**
* REMOVE
*
* REMOVE expression IN collection
* PartialStatement::remove(expression).in(collection): RemoveExpression
*
* Alias: remove(expression).into(collection)
*
* Examples
*
* _.remove('x').in('y'): REMOVE x IN y LET varname = OLD RETURN varname
* RemoveExpression::returnOld(varname): ReturnExpression
*
* _.returnOld('z'): LET z = OLD RETURN z OPTIONS options
* RemoveExpression::options(options): RemoveExpression
*
* _.options('opts'): OPTIONS opts
*
*/
remove(expr: any): RemoveRet;
/**
* UPSERT
*
* UPSERT expression1 INSERT expression2 REPLACE expression3 IN collection
* PartialStatement::upsert(expression1).insert(expression2).replace(expression3).in(collection): UpsertExpression
*
* Alias: ….into(collection)
*
* Examples
*
* _.upsert('x').insert('y').replace('z').in('c'): UPSERT x INSERT y REPLACE z IN c
*
* UPSERT expression1 INSERT expression2 UPDATE expression3 IN collection
* PartialStatement::upsert(expression1).insert(expression2).update(expression3).in(collection): UpsertExpression
*
* Alias: ….into(collection)
*
* _.upsert('x').insert('y').update('z').in('c'): UPSERT x INSERT y UPDATE z IN c OPTIONS options
* UpsertExpression::options(options): UpsertExpression
*
* _.options('opts'): OPTIONS opts
*
*/
upsert(expr: any): UpsertRet;
/**
* INSERT
*
* INSERT expression INTO collection
* PartialStatement::insert(expression).into(collection): InsertExpression
*
* Alias: insert(expression).in(collection)
*
* Examples
*
* _.insert('x').into('y'): INSERT x INTO y OPTIONS options
* InsertExpression::options(options): InsertExpression
*
* _.options('opts'): OPTIONS opts LET varname = NEW RETURN varname
* InsertExpression::returnNew(varname): ReturnExpression
*
* _.returnNew('z'): LET z = NEW RETURN z
*
*/
insert(expr: any): InsertRet;
/**
* UPDATE
*
* UPDATE expression IN collection
* PartialStatement::update(expression).in(collection): UpdateExpression
*
* Alias: update(expression).into(collection)
*
* Examples
*
* _.update('x').in('y'): UPDATE x IN y
*
* UPDATE expression1 WITH expression2 IN collection
* PartialStatement::update(expression1).with(expression2).in(collection): UpdateExpression
*
* Alias: update(expression1).with(expression2).into(collection)
*
* _.update('x').with('y').in('z'): UPDATE x WITH y IN z OPTIONS options
* UpdateExpression::options(options): UpdateExpression
*
* _.options('opts'): OPTIONS opts LET varname = NEW RETURN varname
* UpdateExpression::returnNew(varname): ReturnExpression
*
* _.returnNew('z'): LET z = NEW RETURN z LET varname = OLD RETURN varname
* UpdateExpression::returnOld(varname): ReturnExpression
*
* _.returnOld('z'): LET z = OLD RETURN z
*
*/
update(expr: any): UpdateRetWithRet;
/**
* REPLACE
*
* REPLACE expression IN collection
* PartialStatement::replace(expression).in(collection): ReplaceExpression
*
* Alias: replace(expression).into(collection)
*
* Examples
*
* _.replace('x').in('y'): REPLACE x IN y REPLACE expression1 WITH expression2 IN collection
* PartialStatement::replace(expression1).with(expression2).in(collection): ReplaceExpression
*
* Alias: replace(expression1).with(expression2).into(collection)
*
* _.replace('x').with('y').in('z'): REPLACE x WITH y IN z OPTIONS options
* ReplaceExpression::options(options): ReplaceExpression
*
* _.options('opts'): OPTIONS opts LET varname = NEW RETURN varname
* ReplaceExpression::returnOld(varname): ReturnExpression
*
* _.returnNew('z'): LET z = NEW RETURN z LET varname = OLD RETURN varname
* ReplaceExpression::returnNew(varname): ReturnExpression
*
* _.returnOld('z'): LET z = OLD RETURN z
*
*/
replace(expr: any): ReplaceRetWithRet;
}
interface RemoveRet {
into(collection: any): RemoveExpression;
in: RemoveRet["into"];
in_: RemoveRet["into"];
}
interface UpsertRet {
insert(insertExpr: any): UpsertRetInsertRet;
}
interface UpsertRetInsertRet {
update(updateOrReplaceExpr: any): UpsertRetInsertRetUpdateRet;
replace: UpsertRetInsertRet["update"];
}
interface UpsertRetInsertRetUpdateRet {
into(inCollection: any): UpsertExpression;
in: UpsertRetInsertRetUpdateRet["into"];
in_: UpsertRetInsertRetUpdateRet["into"];
}
interface InsertRet {
into(collection: any): InsertExpression;
in: InsertRet["into"];
in_: InsertRet["into"];
}
interface UpdateRetWithRet {
into(collection: any): UpdateExpression;
in: UpdateRetWithRet["into"];
in_: UpdateRetWithRet["into"];
}
interface ReplaceRetWithRet {
into(collection: any): ReplaceExpression;
in: ReplaceRetWithRet["into"];
in_: ReplaceRetWithRet["into"];
}
interface RemoveRet {
into(collection: any): RemoveExpression;
in: RemoveRet["into"];
in_: RemoveRet["into"];
}
interface UpsertRet {
insert(insertExpr: any): UpsertRetInsertRet;
}
interface UpsertRetInsertRet {
update(updateOrReplaceExpr: any): UpsertRetInsertRetUpdateRet;
replace: UpsertRetInsertRet["update"];
}
interface UpsertRetInsertRetUpdateRet {
into(inCollection: any): UpsertExpression;
in: UpsertRetInsertRetUpdateRet["into"];
in_: UpsertRetInsertRetUpdateRet["into"];
}
interface InsertRet {
into(collection: any): InsertExpression;
in: InsertRet["into"];
in_: InsertRet["into"];
}
interface UpdateRetWithRet {
into(collection: any): UpdateExpression;
with(collection: any): UpdateRetWithRet;
in: UpdateRetWithRet["into"];
in_: UpdateRetWithRet["into"];
}
interface ReplaceRetWithRet {
into(collection: any): ReplaceExpression;
with(collection: any): ReplaceRetWithRet;
in: ReplaceRetWithRet["into"];
in_: ReplaceRetWithRet["into"];
}
declare function toArray(self: Expression, ...args: any[]): any[];
declare function isQuotedString(str: string): boolean;
declare function wrapAQL(expr: Keyword): string;
declare function isValidNumber(number: number): boolean;
declare function castNumber(number: any): NumberLiteral;
declare function castBoolean(bool: any): BooleanLiteral;
declare function castString(str: any): SimpleReference | Identifier | RangeExpression | StringLiteral | Expression | PartialStatement | NullLiteral;
declare function castObject(obj: any): ObjectLiteral | ListLiteral | Identifier;
declare function autoCastToken(token: any): Expression | PartialStatement | NullLiteral;
/**
* AQLfunctions
*
* If raw JavaScript values are passed to statements, they will be wrapped in a matching declare function automatically.
* JavaScript strings wrapped in quotation marks will be wrapped in strings, all other JavaScript strings will be wrapped as simple references(see ref)
* and throw an Error if they are not well-formed.
*/
interface AQLfunctions extends Expression {
/**
* Boolean
*
* Wraps the given value as an Boolean literal.
*
* qb.bool(value)
*
* If the value is truthy, it will be converted to the Boolean true, otherwise it will be converted to the Boolean false.
* If the value is already an Boolean, its own value will be wrapped instead.
*
*/
bool(value: any): BooleanLiteral;
/**
* Number
*
* Wraps the given value as an Number literal.
*
* qb.num(value)
*
* If the value is not a JavaScript Number, it will be converted first.
* If the value does not represent a finite number, an Error will be thrown.
* If the value is already an Number or Integer, its own value will be wrapped instead.
*
*/
num(value: any): NumberLiteral;
/**
* Integer
*
* Wraps the given value as an Integer literal.
*
* qb.int(value)
*
* If the value is not a JavaScript Number, it will be converted first.
* If the value does not represent a finite integer, an Error will be thrown.
* If the value is already an Number or Integer, its own value will be wrapped instead.
*
*/
int(value: any): IntegerLiteral;
/**
* String
*
* Wraps the given value as an String literal.
*
* qb.str(value)
*
* If the value is not a JavaScript String, it will be converted first.
* If the value is a quoted string, it will be treated as a string literal.
* If the value is an object with a toAQL method, the result of calling that method will be wrapped instead.
*
* Examples
*
* 23 => "23"
*
* "some string" => "some string"
*
* '"some string"' => "\"some string\""
*
*/
str(value: any): StringLiteral;
/**
* List
*
* Wraps the given value as an List(Array) literal.
*
* qb.list(value)
*
* If the value is not a JavaScript Array, an Error will be thrown.
* If the value is already an List, its own value will be wrapped instead.
* Any list elements that are not already values will be converted automatically.
*
*/
list(value: any[]): ListLiteral;
/**
* Object
*
* Wraps the given value as an Object literal.
*
* qb.obj(value)
*
* If the value is not a JavaScript Object, an Error will be thrown.
* If the value is already an Object, its own value will be wrapped instead.
* Any property values that are not already values will be converted automatically.
* Any keys that are quoted strings will be treated as string literals.
* Any keys that start with the character ":" will be treated as dynamic properties and must be well-formed simple references.
* Any other keys that need escaping will be quoted if necessary.
* If you need to pass in raw JavaScript objects that shouldn't be converted according to these rules, you can use the qb declare function directly instead.
*
* Examples
*
* qb.obj({'some.name': 'value'}): {"some.name": value}
*
* qb.obj({hello: world}): {hello: world}
*
* qb.obj({'"hello"': world}): {"hello": world}
*
* qb.obj({':dynamic': 'props'}): {[dynamic]: props}
*
* qb.obj({': invalid': 'key'}): throws an error(invalid is not a well-formed reference)
*
*/
obj(obj: object): ObjectLiteral;
/**
* Simple Reference
*
* Wraps a given value in an Simple Reference.
*
* qb.ref(value)
*
* If the value is not a JavaScript string or not a well-formed simple reference, an Error will be thrown.
* If the value is an ArangoCollection, its name property will be used instead.
* If the value is already an Simple Reference, its value is wrapped instead.
*
* Examples
*
* Valid values:
*
* foo
*
* foo.bar
*
* foo[*].bar
*
* foo.bar.QUX
*
* _foo._bar._qux
*
* foo1.bar2
*
* `foo`.bar
*
* foo.`bar`
*
* Invalid values:
*
* 1foo
*
* föö
*
* foo bar
*
* foo[bar]
*
*/
ref(value: string): SimpleReference;
expr(value: any): RawExpression;
/**
* Ternary(if / else)
*
* Creates a ternary expression from the given values.
*
* qb.if(condition, thenDo, elseDo): (condition ? thenDo: elseDo)
* OR:
* qbValue.then(thenDo).else(elseDo): (condition ? thenDo: elseDo)
*
* If the values are not already values, they will be converted automatically.
*
* Alias: qbValue.then(thenDo).otherwise(elseDo)
*
* Examples
* qb.ref('x').then('y').else('z'): (x ? y: z)
*
*/
if(cond: any, then: any, otherwise: any): Expression | number;
/**
* declare Function Call
*
* Creates a functon call for the given name and arguments.
*
* qb.fn(name)(...args)
*
* If the values are not already values, they will be converted automatically.
* For built-in AQLfunctions, methods with the relevant declare function name are already provided by the query builder.
*
* Examples
*
* qb.fn('MY::USER::FUNC')(1, 2, 3): MY::USER::FUNC(1, 2, 3)
*
* qb.fn('hello')(): hello()
*
* qb.RANDOM(): RANDOM()
*
* qb.FLOOR(qb.div(5, 2)): FLOOR((5 / 2))
*
*/
fn(functionName: string): (...arity: any[]) => FunctionCall;
}
type QBfunc = (obj: any) => AQLfunctions;
declare const QB: AQLfunctions & QBfunc;
export = QB; | the_stack |
import { expect } from "chai";
import { mount, shallow } from "enzyme";
import { fireEvent, render, waitFor } from "@testing-library/react";
import sinon from "sinon";
import * as React from "react";
import {
BasePropertyEditorParams, PropertyEditorParamTypes, SliderEditorParams, SpecialKey, StandardEditorNames,
} from "@itwin/appui-abstract";
import { SliderEditor } from "../../components-react/editors/SliderEditor";
import TestUtils, { MineDataController } from "../TestUtils";
import { EditorContainer } from "../../components-react/editors/EditorContainer";
import { PropertyEditorManager } from "../../components-react/editors/PropertyEditorManager";
import { findInstance } from "../ReactInstance";
describe("<SliderEditor />", () => {
before(async () => {
await TestUtils.initializeUiComponents();
});
it("should render", () => {
const wrapper = mount(<SliderEditor />);
wrapper.unmount();
});
it("renders correctly", () => {
shallow(<SliderEditor />).should.matchSnapshot();
});
it("getValue returns proper value after componentDidMount & setState", async () => {
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider);
const wrapper = mount(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const editor = wrapper.instance() as SliderEditor;
expect(editor.state.value).to.equal(50);
wrapper.unmount();
});
it("componentDidUpdate updates the value", async () => {
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider);
const wrapper = mount(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const editor = wrapper.instance() as SliderEditor;
expect(editor.state.value).to.equal(50);
const testValue = 60;
const newRecord = TestUtils.createNumericProperty("Test", testValue, StandardEditorNames.Slider);
wrapper.setProps({ propertyRecord: newRecord });
await TestUtils.flushAsyncOperations();
expect(editor.state.value).to.equal(testValue);
wrapper.unmount();
});
it("should support Slider Editor Params", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const formatTooltip = (_value: number): string => "";
const formatTick = (tick: number): string => tick.toFixed(0);
const getTickCount = (): number => 2; // 2 segments actually 3 ticks
const getTickValues = (): number[] => [1, 100];
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 1,
maximum: 100,
step: 5,
mode: 1,
reversed: true,
showTooltip: true,
tooltipBelow: true,
showMinMax: true,
maxIconSpec: "icon-placeholder",
showTicks: true,
showTickLabels: true,
formatTooltip,
formatTick,
getTickCount,
getTickValues,
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider, editorParams);
const wrapper = mount(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
wrapper.update();
const sliderEditor = wrapper.find(SliderEditor);
expect(sliderEditor.length).to.eq(1);
expect(sliderEditor.state("size")).to.eq(100);
expect(sliderEditor.state("min")).to.eq(1);
expect(sliderEditor.state("max")).to.eq(100);
expect(sliderEditor.state("step")).to.eq(5);
expect(sliderEditor.state("thumbMode")).to.eq("allow-crossing");
expect(sliderEditor.state("trackDisplayMode")).to.eq("odd-segments");
expect(sliderEditor.state("value")).to.eq(50);
expect(sliderEditor.state("isDisabled")).to.eq(undefined);
expect(sliderEditor.state("showTooltip")).to.be.true;
expect(sliderEditor.state("formatTooltip")).to.eq(formatTooltip);
expect(sliderEditor.state("tooltipBelow")).to.be.true;
expect(sliderEditor.state("minLabel")).to.eq(undefined);
expect(wrapper.find(".icon").length).to.eq(1);
wrapper.unmount();
});
it("calls onCommit on OK button click", async () => {
const spyOnCommit = sinon.spy();
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider);
const wrapper = mount(<SliderEditor propertyRecord={record} onCommit={spyOnCommit} />);
const button = wrapper.find(".components-popup-button");
expect(button.length).to.eq(1);
button.first().simulate("click");
await TestUtils.flushAsyncOperations();
wrapper.update();
const okButton = wrapper.find("button.components-popup-ok-button");
expect(okButton.length).to.eq(1);
okButton.first().simulate("click");
await TestUtils.flushAsyncOperations();
wrapper.update();
expect(spyOnCommit.calledOnce).to.be.true;
wrapper.unmount();
});
it("calls onCancel on Cancel button click", async () => {
const spyOnCancel = sinon.spy();
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider);
const wrapper = mount(<SliderEditor propertyRecord={record} onCancel={spyOnCancel} />);
const button = wrapper.find(".components-popup-button");
expect(button.length).to.eq(1);
button.first().simulate("click");
await TestUtils.flushAsyncOperations();
wrapper.update();
const cancelButton = wrapper.find("button.components-popup-cancel-button");
expect(cancelButton.length).to.eq(1);
cancelButton.first().simulate("click");
await TestUtils.flushAsyncOperations();
wrapper.update();
expect(spyOnCancel.calledOnce).to.be.true;
wrapper.unmount();
});
it("calls onCommit on Enter key", async () => {
const spyOnCommit = sinon.spy();
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider);
const wrapper = mount(<SliderEditor propertyRecord={record} onCommit={spyOnCommit} />);
const button = wrapper.find(".components-popup-button");
expect(button.length).to.eq(1);
button.first().simulate("click");
await TestUtils.flushAsyncOperations();
wrapper.update();
window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, view: window, key: "Enter" }));
await TestUtils.flushAsyncOperations();
expect(spyOnCommit.calledOnce).to.be.true;
wrapper.unmount();
});
it("calls onCancel on Escape key", async () => {
const spyOnCancel = sinon.spy();
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider);
const wrapper = mount(<SliderEditor propertyRecord={record} onCancel={spyOnCancel} />);
const button = wrapper.find(".components-popup-button");
expect(button.length).to.eq(1);
button.first().simulate("click");
await TestUtils.flushAsyncOperations();
wrapper.update();
window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, view: window, key: "Escape" }));
await TestUtils.flushAsyncOperations();
expect(spyOnCancel.calledOnce).to.be.true;
wrapper.unmount();
});
it("renders editor for 'number' type and 'slider' editor using SliderEditor", () => {
const propertyRecord = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider);
const renderedComponent = render(<EditorContainer propertyRecord={propertyRecord} title="abc" onCommit={() => { }} onCancel={() => { }} />);
expect(renderedComponent.container.querySelector(".components-slider-editor")).to.not.be.empty;
});
it("calls onCommit for Change", async () => {
const propertyRecord = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider);
const spyOnCommit = sinon.spy();
function handleCommit(): void {
spyOnCommit();
}
const component = render(<EditorContainer propertyRecord={propertyRecord} title="abc" onCommit={handleCommit} onCancel={() => { }} />);
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
const sliderContainer = component.container.ownerDocument.querySelector(".iui-slider-container");
expect(sliderContainer).to.exist;
fireEvent.mouseDown(sliderContainer!);
await TestUtils.flushAsyncOperations();
const ok = component.getByTestId("components-popup-ok-button");
expect(ok).to.exist;
fireEvent.click(ok);
await TestUtils.flushAsyncOperations();
expect(spyOnCommit.calledOnce).to.be.true;
});
it("should render Editor Params reversed track coloring", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 0,
maximum: 100,
step: 5,
reversed: true,
showTooltip: true,
tooltipBelow: true,
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider, editorParams);
const component = render(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
const track = component.container.ownerDocument.querySelector(".iui-slider-track");
expect(track).to.exist;
expect((track as HTMLElement).style.right).to.eq("0%");
expect((track as HTMLElement).style.left).to.eq("50%");
component.unmount();
});
it("should render Editor Params reversed track coloring", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 0,
maximum: 100,
step: 5,
reversed: false,
showTooltip: true,
tooltipBelow: true,
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider, editorParams);
const component = render(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
const track = component.container.ownerDocument.querySelector(".iui-slider-track");
expect(track).to.exist;
expect((track as HTMLElement).style.left).to.eq("0%");
expect((track as HTMLElement).style.right).to.eq("50%");
component.unmount();
});
it("should render Editor Params w/decimal step", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 0,
maximum: 5,
step: 1.5,
mode: 1,
showTooltip: true,
showMinMax: false,
maxIconSpec: "icon-placeholder",
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 3, StandardEditorNames.Slider, editorParams);
const component = render(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
expect(component.container.ownerDocument.querySelector(".iui-tooltip")?.textContent).to.eq("3.0");
component.unmount();
});
it("should render Editor Params w/decimal step", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 0,
maximum: 5,
step: 1.5,
mode: 1,
showTooltip: true,
showMinMax: false,
maxIconSpec: "icon-placeholder",
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 3, StandardEditorNames.Slider, editorParams);
const component = render(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
expect(component.container.ownerDocument.querySelector(".iui-tooltip")?.textContent).to.eq("3.0");
component.unmount();
});
it("should render Editor Params w/ticks no tick labels", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const formatTooltip = (value: number): string => value.toFixed(2);
const formatTick = (value: number): string => value.toFixed(1);
const getTickCount = (): number => 2; // 2 segment / 3 ticks 0-50-100
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 1,
maximum: 100,
step: 5,
mode: 1,
showTooltip: true,
tooltipBelow: true,
showMinMax: true,
maxIconSpec: "icon-placeholder",
showTicks: true,
showTickLabels: false,
getTickCount,
formatTooltip,
formatTick,
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider, editorParams);
const component = render(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
expect(component.container.ownerDocument.querySelector("span.iui-slider-min")?.textContent).to.eq("1");
expect(component.container.ownerDocument.querySelector(".iui-tooltip")?.textContent).to.eq("50.00");
const maxLabel = component.container.ownerDocument.querySelector("span.iui-slider-max");
expect(maxLabel?.querySelector(".icon-placeholder")).to.exist;
const ticks = component.container.ownerDocument.querySelectorAll("span.iui-slider-tick");
expect(ticks.length).to.eq(3);
component.unmount();
});
it("should render Editor Params w/ticks", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const formatTooltip = (value: number): string => value.toFixed(2);
const formatTick = (value: number): string => value.toFixed(1);
const getTickCount = (): number => 1;
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 1,
maximum: 100,
mode: 1,
showTooltip: true,
tooltipBelow: true,
showMinMax: true,
maxIconSpec: "icon-placeholder",
showTicks: true,
showTickLabels: true,
getTickCount,
formatTooltip,
formatTick,
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider, editorParams);
const component = render(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
expect(component.container.ownerDocument.querySelector("span.iui-slider-min")?.textContent).to.eq("1");
expect(component.container.ownerDocument.querySelector(".iui-tooltip")?.textContent).to.eq("50.00");
const maxLabel = component.container.ownerDocument.querySelector("span.iui-slider-max");
expect(maxLabel?.querySelector(".icon-placeholder")).to.exist;
const ticks = component.container.ownerDocument.querySelectorAll("span.iui-slider-tick");
expect(ticks.length).to.eq(2);
expect(ticks[0]?.textContent).to.eq("1.0");
expect(ticks[1]?.textContent).to.eq("100.0");
component.unmount();
});
it("should render Editor Params w/defined ticks values", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const getTickValues = (): number[] => [0, 50, 100];
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 0,
maximum: 100,
step: 5,
mode: 1,
showTooltip: true,
tooltipBelow: true,
showMinMax: true,
showTicks: true,
showTickLabels: true,
getTickValues,
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider, editorParams);
const component = render(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
expect(component.container.ownerDocument.querySelector("span.iui-slider-min")?.textContent).to.eq("0");
expect(component.container.ownerDocument.querySelector(".iui-tooltip")?.textContent).to.eq("50");
expect(component.container.ownerDocument.querySelector("span.iui-slider-max")?.textContent).to.eq("100");
const ticks = component.container.ownerDocument.querySelectorAll("span.iui-slider-tick");
expect(ticks.length).to.eq(3);
expect(ticks[0]?.textContent).to.eq("0");
expect(ticks[1]?.textContent).to.eq("50");
expect(ticks[2]?.textContent).to.eq("100");
component.unmount();
});
it("should render Editor Params w/defined formatted ticks values", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const formatTick = (value: number): string => value.toFixed(1);
const getTickValues = (): number[] => [0, 50, 100];
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 0,
maximum: 100,
step: 5,
mode: 1,
showTooltip: true,
tooltipBelow: true,
showMinMax: true,
showTicks: true,
showTickLabels: true,
getTickValues,
formatTick,
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider, editorParams);
const component = render(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
expect(component.container.ownerDocument.querySelector("span.iui-slider-min")?.textContent).to.eq("0");
expect(component.container.ownerDocument.querySelector(".iui-tooltip")?.textContent).to.eq("50");
expect(component.container.ownerDocument.querySelector("span.iui-slider-max")?.textContent).to.eq("100");
const ticks = component.container.ownerDocument.querySelectorAll("span.iui-slider-tick");
expect(ticks.length).to.eq(3);
expect(ticks[0]?.textContent).to.eq("0.0");
expect(ticks[1]?.textContent).to.eq("50.0");
expect(ticks[2]?.textContent).to.eq("100.0");
component.unmount();
});
it("should render Editor Params w/ticks and default labels", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const getTickCount = (): number => 4; // four segments
// const getTickValues = (): number[] => [1, 100];
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 0,
maximum: 100,
step: 5,
mode: 1,
showTooltip: true,
tooltipBelow: true,
showMinMax: true,
showTicks: true,
showTickLabels: true,
getTickCount,
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider, editorParams);
const component = render(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
expect(component.container.ownerDocument.querySelector("span.iui-slider-min")?.textContent).to.eq("0");
expect(component.container.ownerDocument.querySelector(".iui-tooltip")?.textContent).to.eq("50");
expect(component.container.ownerDocument.querySelector("span.iui-slider-max")?.textContent).to.eq("100");
const ticks = component.container.ownerDocument.querySelectorAll("span.iui-slider-tick");
expect(ticks.length).to.eq(5);
expect(ticks[0]?.textContent).to.eq("0");
expect(ticks[1]?.textContent).to.eq("25");
expect(ticks[2]?.textContent).to.eq("50");
expect(ticks[3]?.textContent).to.eq("75");
expect(ticks[4]?.textContent).to.eq("100");
component.unmount();
});
it("should render Editor Params icon labels", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const formatTooltip = (value: number): string => value.toFixed(1);
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 1,
maximum: 100,
step: 5,
mode: 1,
showTooltip: true,
tooltipBelow: true,
showMinMax: true,
maxIconSpec: "icon-placeholder",
minIconSpec: "icon-placeholder",
showTicks: true,
showTickLabels: true,
formatTooltip,
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider, editorParams);
const component = render(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
expect(component.container.ownerDocument.querySelector(".iui-tooltip")?.textContent).to.eq("50.0");
expect(component.container.ownerDocument.querySelector("span.iui-slider-min")?.querySelector(".icon-placeholder")).to.exist;
expect(component.container.ownerDocument.querySelector("span.iui-slider-max")?.querySelector(".icon-placeholder")).to.exist;
component.unmount();
});
it("should render Editor Params string labels", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 1,
maximum: 100,
showTooltip: true,
tooltipBelow: true,
showMinMax: true,
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider, editorParams);
const component = render(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
expect(component.container.ownerDocument.querySelector(".iui-tooltip")?.textContent).to.eq("50");
expect(component.container.ownerDocument.querySelector("span.iui-slider-min")?.textContent).to.eq("1");
expect(component.container.ownerDocument.querySelector("span.iui-slider-max")?.textContent).to.eq("100");
component.unmount();
});
it("should render Editor Params and trigger handleChange callback", async () => {
const editorParams: BasePropertyEditorParams[] = [];
const sliderParams: SliderEditorParams = {
type: PropertyEditorParamTypes.Slider,
size: 100,
minimum: 1,
maximum: 100,
step: 5,
showTooltip: true,
tooltipBelow: true,
showMinMax: false,
maxIconSpec: "icon-placeholder",
showTicks: true,
showTickLabels: true,
};
editorParams.push(sliderParams);
const record = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider, editorParams);
const component = render(<SliderEditor propertyRecord={record} />);
await TestUtils.flushAsyncOperations();
const button = component.getByTestId("components-popup-button");
expect(button).to.exist;
fireEvent.click(button);
await TestUtils.flushAsyncOperations();
const thumb = component.container.ownerDocument.querySelector(".iui-slider-thumb");
expect(thumb).to.exist;
fireEvent.keyDown(thumb!, { key: SpecialKey.ArrowRight });
await TestUtils.flushAsyncOperations();
expect(component.container.ownerDocument.querySelector(".iui-tooltip")?.textContent).to.eq("55");
component.unmount();
});
it("should not commit if DataController fails to validate", async () => {
PropertyEditorManager.registerDataController("myData", MineDataController);
const propertyRecord = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider);
propertyRecord.property.dataController = "myData";
const spyOnCommit = sinon.spy();
const renderedComponent = render(<EditorContainer propertyRecord={propertyRecord} title="abc" onCommit={spyOnCommit} onCancel={() => { }} />);
expect(renderedComponent).not.to.be.undefined;
const popupButton = await waitFor(() => renderedComponent.getByTestId("components-popup-button"));
expect(popupButton).not.to.be.null;
fireEvent.keyDown(popupButton, { key: SpecialKey.Enter });
await TestUtils.flushAsyncOperations();
expect(spyOnCommit.called).to.be.false;
PropertyEditorManager.deregisterDataController("myData");
});
it("should receive focus", async () => {
const propertyRecord = TestUtils.createNumericProperty("Test", 50, StandardEditorNames.Slider);
const renderedComponent = render(<SliderEditor propertyRecord={propertyRecord} />);
expect(renderedComponent).not.to.be.undefined;
const popupButton = await renderedComponent.findByTestId("components-popup-button");
expect(popupButton).not.to.be.null;
popupButton.focus();
const editor = findInstance(renderedComponent.container.firstChild);
expect (editor).not.to.be.null;
expect (editor.hasFocus).to.be.true;
});
}); | the_stack |
import { RemindersController } from "controller";
import { PluginDataIO } from "data";
import type { ReadOnlyReference } from "model/ref";
import { Reminder, Reminders } from "model/reminder";
import { DATE_TIME_FORMATTER } from "model/time";
import {
App,
Platform,
Plugin,
PluginManifest,
WorkspaceLeaf
} from "obsidian";
import { monkeyPatchConsole } from "obsidian-hack/obsidian-debug-mobile";
import { ReminderSettingTab, SETTINGS } from "settings";
import { AutoComplete } from "ui/autocomplete";
import { DateTimeChooserView } from "ui/datetime-chooser";
import { openDateTimeFormatChooser } from "ui/datetime-format-modal";
import { buildCodeMirrorPlugin } from "ui/editor-extension";
import { ReminderModal } from "ui/reminder";
import { ReminderListItemViewProxy } from "ui/reminder-list";
import { OkCancel, showOkCancelDialog } from "ui/util";
import { VIEW_TYPE_REMINDER_LIST } from "./constants";
export default class ReminderPlugin extends Plugin {
pluginDataIO: PluginDataIO;
private viewProxy: ReminderListItemViewProxy;
private reminders: Reminders;
private remindersController: RemindersController;
private editDetector: EditDetector;
private reminderModal: ReminderModal;
private autoComplete: AutoComplete;
constructor(app: App, manifest: PluginManifest) {
super(app, manifest);
this.reminders = new Reminders(() => {
// on changed
if (this.viewProxy) {
this.viewProxy.invalidate();
}
this.pluginDataIO.changed = true;
});
this.pluginDataIO = new PluginDataIO(this, this.reminders);
this.reminders.reminderTime = SETTINGS.reminderTime;
DATE_TIME_FORMATTER.setTimeFormat(SETTINGS.dateFormat, SETTINGS.dateTimeFormat, SETTINGS.strictDateFormat);
this.editDetector = new EditDetector(SETTINGS.editDetectionSec);
this.viewProxy = new ReminderListItemViewProxy(app.workspace, this.reminders, SETTINGS.reminderTime,
// On select a reminder in the list
(reminder) => {
if (reminder.muteNotification) {
this.showReminder(reminder);
return;
}
this.openReminderFile(reminder);
});
this.remindersController = new RemindersController(
app.vault,
this.viewProxy,
this.reminders
);
this.reminderModal = new ReminderModal(this.app, SETTINGS.useSystemNotification, SETTINGS.laters);
this.autoComplete = new AutoComplete(SETTINGS.autoCompleteTrigger);
}
override async onload() {
await this.pluginDataIO.load();
if (this.pluginDataIO.debug.value) {
monkeyPatchConsole(this);
}
this.setupUI();
this.setupCommands();
this.watchVault();
this.startPeriodicTask();
}
private setupUI() {
// Reminder List
this.registerView(VIEW_TYPE_REMINDER_LIST, (leaf: WorkspaceLeaf) => {
return this.viewProxy.createView(leaf);
});
this.addSettingTab(
new ReminderSettingTab(this.app, this)
);
this.registerDomEvent(document, "keydown", (evt: KeyboardEvent) => {
this.editDetector.fileChanged();
});
if (Platform.isDesktopApp) {
this.registerEditorExtension(buildCodeMirrorPlugin(this.app, this.reminders));
this.registerCodeMirror((cm: CodeMirror.Editor) => {
const dateTimeChooser = new DateTimeChooserView(cm, this.reminders);
cm.on(
"change",
(cmEditor: CodeMirror.Editor, changeObj: CodeMirror.EditorChange) => {
if (!this.autoComplete.isTrigger(cmEditor, changeObj)) {
dateTimeChooser.cancel();
return;
}
dateTimeChooser.show()
.then(value => {
this.autoComplete.insert(cmEditor, value);
})
.catch(() => { /* do nothing on cancel */ });
return;
}
);
});
}
// Open reminder list view
if (this.app.workspace.layoutReady) {
this.viewProxy.openView();
} else {
(this.app.workspace as any).on("layout-ready", () => {
this.viewProxy.openView();
});
}
}
private setupCommands() {
this.addCommand({
id: "scan-reminders",
name: "Scan reminders",
checkCallback: (checking: boolean) => {
if (checking) {
return true;
}
this.remindersController.reloadAllFiles();
return true;
},
});
this.addCommand({
id: "show-reminders",
name: "Show reminders",
checkCallback: (checking: boolean) => {
if (!checking) {
this.showReminderList();
}
return true;
},
});
this.addCommand({
id: "convert-reminder-time-format",
name: "Convert reminder time format",
checkCallback: (checking: boolean) => {
if (!checking) {
showOkCancelDialog("Convert reminder time format", "This command rewrite reminder dates in all markdown files. You should make a backup of your vault before you execute this. May I continue to convert?").then((res) => {
if (res !== OkCancel.OK) {
return;
}
openDateTimeFormatChooser(this.app, (dateFormat, dateTimeFormat) => {
this.remindersController.convertDateTimeFormat(dateFormat, dateTimeFormat)
.catch(() => { /* ignore */ });
});
});
}
return true;
},
});
this.addCommand({
id: "show-date-chooser",
name: "Show calendar popup",
icon: "calendar-with-checkmark",
hotkeys: [
{
modifiers: ["Meta", "Shift"],
key: "2" // Shift + 2 = `@`
}
],
editorCheckCallback: (checking, editor): boolean | void => {
if (checking) {
return true;
}
this.autoComplete.show(this.app, editor, this.reminders);
},
});
this.addCommand({
id: "toggle-checklist-status",
name: "Toggle checklist status",
hotkeys: [
{
modifiers: ["Meta", "Shift"],
key: "Enter"
}
],
editorCheckCallback: (checking, editor, view): boolean | void => {
if (checking) {
return true;
}
this.remindersController.toggleCheck(view.file, editor.getCursor().line);
},
});
}
private watchVault() {
[
this.app.vault.on("modify", async (file) => {
this.remindersController.reloadFile(file, true);
}),
this.app.vault.on("delete", (file) => {
this.remindersController.removeFile(file.path);
}),
this.app.vault.on("rename", (file, oldPath) => {
this.remindersController.removeFile(oldPath);
this.remindersController.reloadFile(file);
}),
].forEach(eventRef => {
this.registerEvent(eventRef);
})
}
private startPeriodicTask() {
let intervalTaskRunning = false;
this.registerInterval(
window.setInterval(() => {
if (intervalTaskRunning) {
console.log(
"Skip reminder interval task because task is already running."
);
return;
}
intervalTaskRunning = true;
this.periodicTask().finally(() => {
intervalTaskRunning = false;
});
}, SETTINGS.reminderCheckIntervalSec.value * 1000)
);
}
private async periodicTask(): Promise<void> {
this.viewProxy.reload(false);
if (!this.pluginDataIO.scanned.value) {
this.remindersController.reloadAllFiles().then(() => {
this.pluginDataIO.scanned.value = true;
this.pluginDataIO.save();
});
}
this.pluginDataIO.save(false);
if (this.editDetector.isEditing()) {
return;
}
const expired = this.reminders.getExpiredReminders(
SETTINGS.reminderTime.value
);
expired.forEach((reminder) => {
if (reminder.muteNotification) {
return;
}
this.showReminder(reminder);
});
}
private showReminder(reminder: Reminder) {
reminder.muteNotification = true;
this.reminderModal.show(
reminder,
(time) => {
console.info("Remind me later: time=%o", time);
reminder.time = time;
reminder.muteNotification = false;
this.remindersController.updateReminder(reminder, false);
this.pluginDataIO.save(true);
},
() => {
console.info("done");
reminder.muteNotification = false;
this.remindersController.updateReminder(reminder, true);
this.reminders.removeReminder(reminder);
this.pluginDataIO.save(true);
},
() => {
console.info("Mute");
reminder.muteNotification = true;
this.viewProxy.reload(true);
},
() => {
console.info("Open");
this.openReminderFile(reminder);
}
);
}
private async openReminderFile(reminder: Reminder) {
const leaf = this.app.workspace.getUnpinnedLeaf();
await this.remindersController.openReminder(reminder, leaf);
}
override onunload(): void {
this.app.workspace
.getLeavesOfType(VIEW_TYPE_REMINDER_LIST)
.forEach((leaf) => leaf.detach());
}
showReminderList(): void {
if (this.app.workspace.getLeavesOfType(VIEW_TYPE_REMINDER_LIST).length) {
return;
}
this.app.workspace.getRightLeaf(false).setViewState({
type: VIEW_TYPE_REMINDER_LIST,
});
}
}
class EditDetector {
private lastModified?: Date;
constructor(private editDetectionSec: ReadOnlyReference<number>) { }
fileChanged() {
this.lastModified = new Date();
}
isEditing(): boolean {
if (this.editDetectionSec.value <= 0) {
return false;
}
if (this.lastModified == null) {
return false;
}
const elapsedSec =
(new Date().getTime() - this.lastModified.getTime()) / 1000;
return elapsedSec < this.editDetectionSec.value;
}
} | the_stack |
//todo: ix this - import Xml = require("System.Xml");
import {XmlNamespace} from "../Enumerations/XmlNamespace";
import {EwsUtilities} from "./EwsUtilities";
import {EwsLogging} from "./EwsLogging";
import {StringHelper, DOMParser, xml2JsObject} from "../ExtensionMethods";
/** @internal */
export class EwsXmlReader {
private static ReadWriteBufferSize: number = 4096;
get HasAttributes(): boolean { return this.currentNode ? this.currentNode.hasAttributes() : false; }
get IsEmptyElement(): boolean { return this.currentNode.nodeType == Node.ELEMENT_NODE /*System.Xml.XmlNodeType.Element*/ && !this.currentNode.hasChildNodes(); }
get LocalName(): string { return this.currentNode ? this.currentNode.localName : undefined; }
get NamespacePrefix(): string { return this.currentNode ? (<any>this.currentNode).prefix : undefined; }
get NamespaceUri(): string { return this.currentNode ? this.currentNode.namespaceURI : undefined; }
get NodeType(): number /*Xml.XmlNodeType*/ { return this.currentNode ? this.currentNode.nodeType : undefined; }
//get PrevNodeType(): System.Xml.XmlNodeType { return this.prevNodeType; }
get IsRoot(): boolean { return this.currentNode == this.treeWalker.root; }
get ParentNode(): Node { return this.currentNode ? this.currentNode.parentNode : undefined; }
get CurrentNode(): Node { return this.currentNode; }
private prevNodeType: number /*Xml.XmlNodeType*/;
private xmlReader: any;
get Eof(): boolean { return this.eof; }
private eof: boolean = false;
protected xmlDoc: XMLDocument;
protected currentNode: Node;
protected treeWalker: TreeWalker;
//#region xml2JS logic
get JsObject(): any { return this.jsObject; }
private jsObject: any;
//#endregion
//#region Constructor
constructor(rawXML: string) {
var parser = new DOMParser();
this.xmlDoc = parser.parseFromString(rawXML, "text/xml");
//this.treeWalker = this.xmlDoc.createTreeWalker(this.xmlDoc, NodeFilter.SHOW_ELEMENT, null, false);
//this.currentNode = this.treeWalker.root;
var xml2js = new xml2JsObject();
this.jsObject = xml2js.parseXMLNode(this.xmlDoc.documentElement, true);
EwsLogging.DebugLog(this.JsObject, true);
}
//#endregion
EnsureCurrentNodeIsEndElement(xmlNamespace: XmlNamespace, localName: string): any { throw new Error("EwsXmlReader.ts - EnsureCurrentNodeIsEndElement : Not implemented."); }
//EnsureCurrentNodeIsStartElement(xmlNamespace: XmlNamespace, localName: string): any { throw new Error("EwsXmlReader.ts - EnsureCurrentNodeIsStartElement : Not implemented."); }
//EnsureCurrentNodeIsStartElement(): any { throw new Error("EwsXmlReader.ts - EnsureCurrentNodeIsStartElement : Not implemented."); }
FormatElementName(namespacePrefix: string, localElementName: string): string { throw new Error("EwsXmlReader.ts - FormatElementName : Not implemented."); }
GetXmlReaderForNode(): any { throw new Error("EwsXmlReader.ts - GetXmlReaderForNode : Not implemented."); }
InitializeXmlReader(stream: any /*System.IO.Stream*/): any { throw new Error("EwsXmlReader.ts - InitializeXmlReader : Not implemented."); }
//InternalReadElement(namespacePrefix: string, localName: string, nodeType: System.Xml.XmlNodeType): any;// { throw new Error("EwsXmlReader.ts - InternalReadElement : Not implemented."); }
InternalReadElement(xmlNamespace: XmlNamespace, localName: string, nodeType: number /*Xml.XmlNodeType*/): any {
if (this.LocalName === localName && this.NamespaceUri == EwsUtilities.GetNamespaceUri(xmlNamespace)) return;
this.Read(nodeType);
if (localName && nodeType)
if ((this.LocalName != localName) || (this.NamespaceUri != EwsUtilities.GetNamespaceUri(xmlNamespace))) {
throw new Error(StringHelper.Format(
"unexpected element, {0}:{1}, {2}, {3}, {4}",
EwsUtilities.GetNamespacePrefix(xmlNamespace),
localName,
nodeType,
this.xmlReader.Name,
this.NodeType));
}
}
HasRecursiveParent(localName: string, node: Node = this.currentNode): boolean {
if (node === null || node.parentNode === null) return false;
if (node.parentNode.localName == localName) return true;
else
return this.HasRecursiveParent(localName, node.parentNode);
}
HasRecursiveParentNode(parentNode: Node, parentName: string, node: Node = this.currentNode): boolean {
if (node === null || node.parentNode === null) return false;
if (node.parentNode.localName == parentName && node.parentNode != parentNode) return false;
if (node.parentNode == parentNode) return true;
else
return this.HasRecursiveParentNode(parentNode, parentName, node.parentNode);
}
//IsEndElement(xmlNamespace: XmlNamespace, localName: string): boolean { throw new Error("EwsXmlReader.ts - IsEndElement : Not implemented."); }
//IsEndElement(namespacePrefix: string, localName: string): boolean { throw new Error("EwsXmlReader.ts - IsEndElement : Not implemented."); }
//IsStartElement(namespacePrefix: string, localName: string): boolean { throw new Error("EwsXmlReader.ts - IsStartElement : Not implemented."); }
//IsStartElement(): boolean { throw new Error("EwsXmlReader.ts - IsStartElement : Not implemented."); }
//IsStartElement(xmlNamespace: XmlNamespace, localName: string): boolean { throw new Error("EwsXmlReader.ts - IsStartElement : Not implemented."); }
IsElement(xmlNamespace: XmlNamespace, localName: string): boolean {
return (this.LocalName == localName) &&
((this.NamespacePrefix == EwsUtilities.GetNamespacePrefix(xmlNamespace)) ||
(this.NamespaceUri == EwsUtilities.GetNamespaceUri(xmlNamespace)));
}
//Read(): any { throw new Error("EwsXmlReader.ts - Read : Not implemented."); }
Read(nodeType?: number /*Xml.XmlNodeType*/): boolean {
this.currentNode = this.treeWalker.nextNode();
if (this.currentNode == null) this.eof = true;
if (nodeType) {
if (this.NodeType !== nodeType) throw new Error("unexpected element type");
}
return this.currentNode != null;
}
//ReadAttributeValue(attributeName: string): string;// { throw new Error("EwsXmlReader.ts - ReadAttributeValue : Not implemented."); }
//ReadAttributeValue(attributeName: string): any { throw new Error("EwsXmlReader.ts - ReadAttributeValue : Not implemented."); }
ReadAttributeValue(xmlNamespace: XmlNamespace, attributeName: string): string {
if (this.currentNode == null || this.currentNode.nodeType != this.currentNode.ELEMENT_NODE || !this.currentNode.hasAttributes()) return null;
var elem = <Element>this.currentNode;
var val = elem.getAttributeNS(EwsUtilities.GetNamespaceUri(xmlNamespace), attributeName);
return val;
}
//ReadBase64ElementValue(outputStream: System.IO.Stream): any { throw new Error("EwsXmlReader.ts - ReadBase64ElementValue : Not implemented."); }
ReadBase64ElementValue(): any[] /*System.Byte[]*/ { throw new Error("EwsXmlReader.ts - ReadBase64ElementValue : Not implemented."); }
ReadElementValue(): string {
return this.currentNode.textContent;
}
//ReadElementValue(): any { throw new Error("EwsXmlReader.ts - ReadElementValue : Not implemented."); }
//ReadElementValue(xmlNamespace: XmlNamespace, localName: string): any { throw new Error("EwsXmlReader.ts - ReadElementValue : Not implemented."); }
//ReadElementValue(namespacePrefix: string, localName: string): string { throw new Error("EwsXmlReader.ts - ReadElementValue : Not implemented."); }
//ReadElementValue(xmlNamespace: XmlNamespace, localName: string): string { throw new Error("EwsXmlReader.ts - ReadElementValue : Not implemented."); }
//ReadEndElement(namespacePrefix: string, elementName: string): any { throw new Error("EwsXmlReader.ts - ReadEndElement : Not implemented."); }
ReadEndElement(xmlNamespace: XmlNamespace, localName: string): void {
this.InternalReadElement(xmlNamespace, localName, Node.ELEMENT_NODE /*System.Xml.XmlNodeType.Element*/);
}
ReadEndElementIfNecessary(xmlNamespace: XmlNamespace, localName: string): void {
if (!(this.IsElement(xmlNamespace, localName) && this.IsEmptyElement)) {
//if (!this.IsEndElement(xmlNamespace, localName)) {
this.ReadEndElement(xmlNamespace, localName);
//}
}
}
ReadInnerXml(): string { throw new Error("EwsXmlReader.ts - ReadInnerXml : Not implemented."); }
ReadNullableAttributeValue(attributeName: string): any { throw new Error("EwsXmlReader.ts - ReadNullableAttributeValue : Not implemented."); }
ReadOuterXml(): string { throw new Error("EwsXmlReader.ts - ReadOuterXml : Not implemented."); }
//ReadStartElement(namespacePrefix: string, localName: string): any { throw new Error("EwsXmlReader.ts - ReadStartElement : Not implemented."); }
ReadStartElement(xmlNamespace: XmlNamespace, localName: string): void {
this.InternalReadElement(xmlNamespace, localName, Node.ELEMENT_NODE /*System.Xml.XmlNodeType.Element*/);
}
ReadToDescendant(xmlNamespace: XmlNamespace, localName: string): any { throw new Error("EwsXmlReader.ts - ReadToDescendant : Not implemented."); }
ReadValue(): string { throw new Error("EwsXmlReader.ts - ReadValue : Not implemented."); }
//ReadValue(): any { throw new Error("EwsXmlReader.ts - ReadValue : Not implemented."); }
SeekLast(): void {
if (!this.eof) this.currentNode = this.treeWalker.previousNode();
}
SkipCurrentElement(): void {
//debug:
var parentNode = this.CurrentNode;
do {
this.Read();
}
while (this.HasRecursiveParentNode(parentNode, parentNode.localName));
this.SeekLast();
}
SkipElement(xmlNamespace: XmlNamespace, localName: string): any { throw new Error("EwsXmlReader.ts - SkipElement : Not implemented."); }
//SkipElement(namespacePrefix: string, localName: string): any { throw new Error("EwsXmlReader.ts - SkipElement : Not implemented."); }
TryReadValue(value: any): boolean { throw new Error("EwsXmlReader.ts - TryReadValue : Not implemented."); }
} | the_stack |
import Big, { BigSource } from "big.js"
import * as crypto from "../crypto"
import LedgerApp, { PublicKey, SignedSignature } from "../ledger/ledger-app"
import Transaction from "../tx"
import { AminoPrefix, Coin, ListMiniMsg } from "../types/"
import HttpRequest from "../utils/request"
import { checkNumber } from "../utils/validateHelper"
import Gov from "./gov"
import Swap from "./swap"
import TokenManagement, { validateMiniTokenSymbol } from "./token"
import { Bridge } from "./bridge"
import { Stake } from "./stake"
const BASENUMBER = Math.pow(10, 8)
export const api = {
broadcast: "/api/v1/broadcast",
nodeInfo: "/api/v1/node-info",
getAccount: "/api/v1/account",
getMarkets: "/api/v1/markets",
getSwaps: "/api/v1/atomic-swaps",
getOpenOrders: "/api/v1/orders/open",
getDepth: "/api/v1/depth",
getTransactions: "/api/v1/transactions",
getTxs: "/bc/api/v1/txs",
getTx: "/api/v1/tx",
}
export const NETWORK_PREFIX_MAPPING = {
testnet: "tbnb",
mainnet: "bnb",
} as const
export type Transfer = { to: string; coins: Coin[] }
/**
* The default signing delegate which uses the local private key.
* @param {Transaction} tx the transaction
* @param {Object} signMsg the canonical sign bytes for the msg
* @return {Transaction}
*/
export const DefaultSigningDelegate = async function (
this: BncClient,
tx: Transaction,
signMsg?: any
): Promise<Transaction> {
const privateKey = this.getPrivateKey()
if (!privateKey) {
return Promise.reject(
"Private key has to be set before signing a transaction"
)
}
return tx.sign(privateKey, signMsg)
}
/**
* The default broadcast delegate which immediately broadcasts a transaction.
* @param {Transaction} signedTx the signed transaction
*/
export const DefaultBroadcastDelegate = async function (
this: BncClient,
signedTx: Transaction
) {
return this.sendTransaction(signedTx, true)
}
/**
* The Ledger signing delegate.
* @param {LedgerApp} ledgerApp
* @param {preSignCb} function
* @param {postSignCb} function
* @param {errCb} function
* @return {function}
*/
export const LedgerSigningDelegate = (
ledgerApp: LedgerApp,
preSignCb: (preSignCb: Buffer) => void,
postSignCb: (pubKeyResp: PublicKey, sigResp: SignedSignature) => void,
errCb: (error: any) => void,
hdPath: number[]
): typeof DefaultSigningDelegate =>
async function (tx, signMsg) {
const signBytes = tx.getSignBytes(signMsg)
preSignCb && preSignCb(signBytes)
let pubKeyResp: PublicKey, sigResp: SignedSignature
try {
pubKeyResp = await ledgerApp.getPublicKey(hdPath)
sigResp = await ledgerApp.sign(signBytes, hdPath)
postSignCb && postSignCb(pubKeyResp, sigResp)
} catch (err) {
console.warn("LedgerSigningDelegate error", err)
errCb && errCb(err)
}
if (sigResp! && sigResp!.signature) {
const pubKey = crypto.getPublicKey(pubKeyResp!.pk!.toString("hex"))
return tx.addSignature(pubKey, sigResp!.signature)
}
return tx
}
/**
* validate the input number.
* @param {Array} outputs
*/
const checkOutputs = (outputs: Transfer[]) => {
outputs.forEach((transfer) => {
const coins = transfer.coins || []
coins.forEach((coin) => {
checkNumber(coin.amount)
if (!coin.denom) {
throw new Error("invalid denmon")
}
})
})
}
/**
* sum corresponding input coin
* @param {Array} inputs
* @param {Array} coins
*/
const calInputCoins = (inputs: Array<{ coins: Coin[] }>, coins: Coin[]) => {
coins.forEach((coin) => {
const existCoin = inputs[0].coins.find((c) => c.denom === coin.denom)
if (existCoin) {
const existAmount = new Big(existCoin.amount)
existCoin.amount = Number(existAmount.plus(coin.amount).toString())
} else {
inputs[0].coins.push({ ...coin })
}
})
}
/**
* The Binance Chain client.
*/
export class BncClient {
public _httpClient: HttpRequest
public _signingDelegate: typeof DefaultSigningDelegate
public _broadcastDelegate: typeof DefaultBroadcastDelegate
public _useAsyncBroadcast: boolean
public _source: number
public tokens: TokenManagement
public swap: Swap
public gov: Gov
public bridge: Bridge
public stake: Stake
public chainId?: string | null
public addressPrefix: typeof NETWORK_PREFIX_MAPPING[keyof typeof NETWORK_PREFIX_MAPPING] =
"tbnb"
public network: keyof typeof NETWORK_PREFIX_MAPPING = "testnet"
public address?: string
public _setPkPromise?: ReturnType<HttpRequest["request"]>
public account_number?: string | number
private _privateKey: string | null = null
/**
* @param {String} server Binance Chain public url
* @param {Boolean} useAsyncBroadcast use async broadcast mode, faster but less guarantees (default off)
* @param {Number} source where does this transaction come from (default 0)
*/
constructor(server: string, useAsyncBroadcast = false, source = 0) {
if (!server) {
throw new Error("Binance chain server should not be null")
}
this._httpClient = new HttpRequest(server)
this._signingDelegate = DefaultSigningDelegate
this._broadcastDelegate = DefaultBroadcastDelegate
this._useAsyncBroadcast = useAsyncBroadcast
this._source = source
this.tokens = new TokenManagement(this)
this.swap = new Swap(this)
this.gov = new Gov(this)
this.bridge = new Bridge(this)
this.stake = new Stake(this)
}
/**
* Initialize the client with the chain's ID. Asynchronous.
* @return {Promise}
*/
async initChain() {
if (!this.chainId) {
const data = await this._httpClient.request("get", api.nodeInfo)
this.chainId = data.result.node_info && data.result.node_info.network
}
return this
}
/**
* Sets the client network (testnet or mainnet).
* @param {String} network Indicate testnet or mainnet
*/
chooseNetwork(network: keyof typeof NETWORK_PREFIX_MAPPING) {
this.addressPrefix = NETWORK_PREFIX_MAPPING[network] || "tbnb"
this.network = NETWORK_PREFIX_MAPPING[network] ? network : "testnet"
}
/**
* Sets the client's private key for calls made by this client. Asynchronous.
* @param {string} privateKey the private key hexstring
* @param {boolean} localOnly set this to true if you will supply an account_number yourself via `setAccountNumber`. Warning: You must do that if you set this to true!
* @return {Promise}
*/
async setPrivateKey(privateKey: string, localOnly = false) {
if (privateKey !== this._privateKey) {
const address = crypto.getAddressFromPrivateKey(
privateKey,
this.addressPrefix
)
if (!address)
throw new Error(`address is falsy: ${address}. invalid private key?`)
this._privateKey = privateKey
this.address = address
if (!localOnly) {
// _setPkPromise is used in _sendTransaction for non-await calls
try {
const promise = (this._setPkPromise = this._httpClient.request(
"get",
`${api.getAccount}/${address}`
))
const data = await promise
this.account_number = data.result.account_number
} catch (e) {
throw new Error(
`unable to query the address on the blockchain. try sending it some funds first: ${address}`
)
}
}
}
return this
}
/**
* Removes client's private key.
* @return {BncClient} this instance (for chaining)
*/
removePrivateKey() {
this._privateKey = null
return this
}
/**
* Gets client's private key.
* @return {string|null} the private key hexstring or `null` if no private key has been set
*/
getPrivateKey() {
return this._privateKey
}
/**
* Sets the client's account number.
* @param {number} accountNumber
*/
setAccountNumber(accountNumber: number) {
this.account_number = accountNumber
}
/**
* Use async broadcast mode. Broadcasts faster with less guarantees (default off)
* @param {Boolean} useAsyncBroadcast
* @return {BncClient} this instance (for chaining)
*/
useAsyncBroadcast(useAsyncBroadcast = true): BncClient {
this._useAsyncBroadcast = useAsyncBroadcast
return this
}
/**
* Sets the signing delegate (for wallet integrations).
* @param {function} delegate
* @return {BncClient} this instance (for chaining)
*/
setSigningDelegate(delegate: BncClient["_signingDelegate"]): BncClient {
if (typeof delegate !== "function")
throw new Error("signing delegate must be a function")
this._signingDelegate = delegate
return this
}
/**
* Sets the broadcast delegate (for wallet integrations).
* @param {function} delegate
* @return {BncClient} this instance (for chaining)
*/
setBroadcastDelegate(delegate: BncClient["_broadcastDelegate"]): BncClient {
if (typeof delegate !== "function")
throw new Error("broadcast delegate must be a function")
this._broadcastDelegate = delegate
return this
}
/**
* Applies the default signing delegate.
* @return {BncClient} this instance (for chaining)
*/
useDefaultSigningDelegate(): BncClient {
this._signingDelegate = DefaultSigningDelegate
return this
}
/**
* Applies the default broadcast delegate.
* @return {BncClient} this instance (for chaining)
*/
useDefaultBroadcastDelegate(): BncClient {
this._broadcastDelegate = DefaultBroadcastDelegate
return this
}
/**
* Applies the Ledger signing delegate.
* @param {function} ledgerApp
* @param {function} preSignCb
* @param {function} postSignCb
* @param {function} errCb
* @return {BncClient} this instance (for chaining)
*/
useLedgerSigningDelegate(...args: Parameters<typeof LedgerSigningDelegate>) {
this._signingDelegate = LedgerSigningDelegate(...args)
return this
}
/**
* Transfer tokens from one address to another.
* @param {String} fromAddress
* @param {String} toAddress
* @param {Number} amount
* @param {String} asset
* @param {String} memo optional memo
* @param {Number} sequence optional sequence
* @return {Promise} resolves with response (success or fail)
*/
async transfer(
fromAddress: string,
toAddress: string,
amount: BigSource,
asset: string,
memo = "",
sequence: number | null = null
) {
const accCode = crypto.decodeAddress(fromAddress)
const toAccCode = crypto.decodeAddress(toAddress)
amount = new Big(amount)
amount = Number(amount.mul(BASENUMBER).toString())
checkNumber(amount, "amount")
const coin = {
denom: asset,
amount: amount,
}
const msg = {
inputs: [
{
address: accCode,
coins: [coin],
},
],
outputs: [
{
address: toAccCode,
coins: [coin],
},
],
aminoPrefix: AminoPrefix.MsgSend,
}
const signMsg = {
inputs: [
{
address: fromAddress,
coins: [
{
amount: amount,
denom: asset,
},
],
},
],
outputs: [
{
address: toAddress,
coins: [
{
amount: amount,
denom: asset,
},
],
},
],
}
const signedTx = await this._prepareTransaction(
msg,
signMsg,
fromAddress,
sequence,
memo
)
return this._broadcastDelegate(signedTx)
}
/**
* Create and sign a multi send tx
* @param {String} fromAddress
* @param {Array} outputs
* @example
* const outputs = [
* {
* "to": "tbnb1p4kpnj5qz5spsaf0d2555h6ctngse0me5q57qe",
* "coins": [{
* "denom": "BNB",
* "amount": 10
* },{
* "denom": "BTC",
* "amount": 10
* }]
* },
* {
* "to": "tbnb1scjj8chhhp7lngdeflltzex22yaf9ep59ls4gk",
* "coins": [{
* "denom": "BTC",
* "amount": 10
* },{
* "denom": "BNB",
* "amount": 10
* }]
* }]
* @param {String} memo optional memo
* @param {Number} sequence optional sequence
* @return {Promise} resolves with response (success or fail)
*/
async multiSend(
fromAddress: string,
outputs: Transfer[],
memo = "",
sequence: number | null = null
) {
if (!fromAddress) {
throw new Error("fromAddress should not be falsy")
}
if (!Array.isArray(outputs)) {
throw new Error("outputs should be array")
}
checkOutputs(outputs)
//sort denom by alphbet and init amount
outputs.forEach((item) => {
item.coins = item.coins.sort((a, b) => a.denom.localeCompare(b.denom))
item.coins.forEach((coin) => {
const amount = new Big(coin.amount)
coin.amount = Number(amount.mul(BASENUMBER).toString())
})
})
type AddressBufferCoins = { address: Buffer; coins: Coin[] }
type AddressStringCoins = { address: string; coins: Coin[] }
const fromAddrCode = crypto.decodeAddress(fromAddress)
const inputs: AddressBufferCoins[] = [{ address: fromAddrCode, coins: [] }]
const transfers: AddressBufferCoins[] = []
outputs.forEach((item) => {
const toAddcCode = crypto.decodeAddress(item.to)
calInputCoins(inputs, item.coins)
transfers.push({ address: toAddcCode, coins: item.coins })
})
const msg = {
inputs,
outputs: transfers,
aminoPrefix: AminoPrefix.MsgSend,
}
const signInputs = [{ address: fromAddress, coins: [] }]
const signOutputs: AddressStringCoins[] = []
outputs.forEach((item, index) => {
signOutputs.push({ address: item.to, coins: [] })
item.coins.forEach((c) => {
signOutputs[index].coins.push(c)
})
calInputCoins(signInputs, item.coins)
})
const signMsg = {
inputs: signInputs,
outputs: signOutputs,
}
const signedTx = await this._prepareTransaction(
msg,
signMsg,
fromAddress,
sequence,
memo
)
return this._broadcastDelegate(signedTx)
}
/**
* Cancel an order.
* @param {String} fromAddress
* @param {String} symbol the market pair
* @param {String} refid the order ID of the order to cancel
* @param {Number} sequence optional sequence
* @return {Promise} resolves with response (success or fail)
*/
async cancelOrder(
fromAddress: string,
symbol: string,
refid: string,
sequence: number | null = null
) {
const accCode = crypto.decodeAddress(fromAddress)
const msg = {
sender: accCode,
symbol: symbol,
refid: refid,
aminoPrefix: AminoPrefix.CancelOrderMsg,
}
const signMsg = {
refid: refid,
sender: fromAddress,
symbol: symbol,
}
const signedTx = await this._prepareTransaction(
msg,
signMsg,
fromAddress,
sequence,
""
)
return this._broadcastDelegate(signedTx)
}
/**
* Place an order.
* @param {String} address
* @param {String} symbol the market pair
* @param {Number} side (1-Buy, 2-Sell)
* @param {Number} price
* @param {Number} quantity
* @param {Number} sequence optional sequence
* @param {Number} timeinforce (1-GTC(Good Till Expire), 3-IOC(Immediate or Cancel))
* @return {Promise} resolves with response (success or fail)
*/
async placeOrder(
address: string = this.address!,
symbol: string,
side: number,
price: number,
quantity: number,
sequence: number | null = null,
timeinforce = 1
) {
if (!address) {
throw new Error("address should not be falsy")
}
if (!symbol) {
throw new Error("symbol should not be falsy")
}
if (side !== 1 && side !== 2) {
throw new Error("side can only be 1 or 2")
}
if (timeinforce !== 1 && timeinforce !== 3) {
throw new Error("timeinforce can only be 1 or 3")
}
const accCode = crypto.decodeAddress(address)
if (sequence !== 0 && !sequence) {
const data = await this._httpClient.request(
"get",
`${api.getAccount}/${address}`
)
sequence = data.result && data.result.sequence
}
const bigPrice = new Big(price)
const bigQuantity = new Big(quantity)
const placeOrderMsg = {
sender: accCode,
id: `${accCode.toString("hex")}-${sequence! + 1}`.toUpperCase(),
symbol: symbol,
ordertype: 2,
side,
price: parseFloat(bigPrice.mul(BASENUMBER).toString()),
quantity: parseFloat(bigQuantity.mul(BASENUMBER).toString()),
timeinforce: timeinforce,
aminoPrefix: AminoPrefix.NewOrderMsg,
}
const signMsg = {
id: placeOrderMsg.id,
ordertype: placeOrderMsg.ordertype,
price: placeOrderMsg.price,
quantity: placeOrderMsg.quantity,
sender: address,
side: placeOrderMsg.side,
symbol: placeOrderMsg.symbol,
timeinforce: timeinforce,
}
checkNumber(placeOrderMsg.price, "price")
checkNumber(placeOrderMsg.quantity, "quantity")
const signedTx = await this._prepareTransaction(
placeOrderMsg,
signMsg,
address,
sequence,
""
)
return this._broadcastDelegate(signedTx)
}
/**
* @param {String} address
* @param {Number} proposalId
* @param {String} baseAsset
* @param {String} quoteAsset
* @param {Number} initPrice
* @param {Number} sequence optional sequence
* @return {Promise} resolves with response (success or fail)
*/
async list(
address: string,
proposalId: number,
baseAsset: string,
quoteAsset: string,
initPrice: number,
sequence: number | null = null
) {
const accCode = crypto.decodeAddress(address)
if (!address) {
throw new Error("address should not be falsy")
}
if (proposalId <= 0) {
throw new Error("proposal id should larger than 0")
}
if (initPrice <= 0) {
throw new Error("price should larger than 0")
}
if (!baseAsset) {
throw new Error("baseAsset should not be falsy")
}
if (!quoteAsset) {
throw new Error("quoteAsset should not be falsy")
}
const init_price = Number(new Big(initPrice).mul(BASENUMBER).toString())
const listMsg = {
from: accCode,
proposal_id: proposalId,
base_asset_symbol: baseAsset,
quote_asset_symbol: quoteAsset,
init_price: init_price,
aminoPrefix: AminoPrefix.ListMsg,
}
const signMsg = {
base_asset_symbol: baseAsset,
from: address,
init_price: init_price,
proposal_id: proposalId,
quote_asset_symbol: quoteAsset,
}
const signedTx = await this._prepareTransaction(
listMsg,
signMsg,
address,
sequence,
""
)
return this._broadcastDelegate(signedTx)
}
/**
* list miniToken
*/
async listMiniToken({
from,
baseAsset,
quoteAsset,
initPrice,
sequence = null,
}: {
from: string
baseAsset: string
quoteAsset: string
initPrice: number
sequence?: number | null
}) {
validateMiniTokenSymbol(baseAsset)
if (initPrice <= 0) {
throw new Error("price should larger than 0")
}
if (!from) {
throw new Error("address should not be falsy")
}
if (!quoteAsset) {
throw new Error("quoteAsset should not be falsy")
}
const init_price = Number(new Big(initPrice).mul(BASENUMBER).toString())
const listMiniMsg = new ListMiniMsg({
from,
base_asset_symbol: baseAsset,
quote_asset_symbol: quoteAsset,
init_price,
})
const signedTx = await this._prepareTransaction(
listMiniMsg.getMsg(),
listMiniMsg.getSignMsg(),
from,
sequence
)
return this._broadcastDelegate(signedTx)
}
/**
* Set account flags
* @param {String} address
* @param {Number} flags new value of account flags
* @param {Number} sequence optional sequence
* @return {Promise} resolves with response (success or fail)
*/
async setAccountFlags(
address: string,
flags: number,
sequence: number | null = null
) {
const accCode = crypto.decodeAddress(address)
const msg = {
from: accCode,
flags: flags,
aminoPrefix: AminoPrefix.SetAccountFlagsMsg,
}
const signMsg = {
flags: flags,
from: address,
}
const signedTx = await this._prepareTransaction(
msg,
signMsg,
address,
sequence,
""
)
return this._broadcastDelegate(signedTx)
}
/**
* Prepare a serialized raw transaction for sending to the blockchain.
* @param {Object} msg the msg object
* @param {Object} stdSignMsg the sign doc object used to generate a signature
* @param {String} address
* @param {Number} sequence optional sequence
* @param {String} memo optional memo
* @return {Transaction} signed transaction
*/
async _prepareTransaction(
msg: any,
stdSignMsg: any,
address: string,
sequence: string | number | null = null,
memo = ""
) {
if ((!this.account_number || (sequence !== 0 && !sequence)) && address) {
const data = await this._httpClient.request(
"get",
`${api.getAccount}/${address}`
)
sequence = data.result.sequence
this.account_number = data.result.account_number
// if user has not used `await` in its call to setPrivateKey (old API), we should wait for the promise here
} else if (this._setPkPromise) {
await this._setPkPromise
}
const tx = new Transaction({
accountNumber:
typeof this.account_number !== "number"
? parseInt(this.account_number!)
: this.account_number,
chainId: this.chainId!,
memo: memo,
msg,
sequence: typeof sequence !== "number" ? parseInt(sequence!) : sequence,
source: this._source,
})
return this._signingDelegate.call(this, tx, stdSignMsg)
}
/**
* Broadcast a transaction to the blockchain.
* @param {signedTx} tx signed Transaction object
* @param {Boolean} sync use synchronous mode, optional
* @return {Promise} resolves with response (success or fail)
*/
async sendTransaction(signedTx: Transaction, sync: boolean) {
const signedBz = signedTx.serialize()
return this.sendRawTransaction(signedBz, sync)
}
/**
* Broadcast a raw transaction to the blockchain.
* @param {String} signedBz signed and serialized raw transaction
* @param {Boolean} sync use synchronous mode, optional
* @return {Promise} resolves with response (success or fail)
*/
async sendRawTransaction(signedBz: string, sync = !this._useAsyncBroadcast) {
const opts = {
data: signedBz,
headers: {
"content-type": "text/plain",
},
}
return this._httpClient.request(
"post",
`${api.broadcast}?sync=${sync}`,
null,
opts
)
}
/**
* Broadcast a raw transaction to the blockchain.
* @param {Object} msg the msg object
* @param {Object} stdSignMsg the sign doc object used to generate a signature
* @param {String} address
* @param {Number} sequence optional sequence
* @param {String} memo optional memo
* @param {Boolean} sync use synchronous mode, optional
* @return {Promise} resolves with response (success or fail)
*/
async _sendTransaction(
msg: any,
stdSignMsg: any,
address: string,
sequence: string | number | null = null,
memo = "",
sync = !this._useAsyncBroadcast
) {
const signedTx = await this._prepareTransaction(
msg,
stdSignMsg,
address,
sequence,
memo
)
return this.sendTransaction(signedTx, sync)
}
/**
* get account
* @param {String} address
* @return {Promise} resolves with http response
*/
async getAccount(address = this.address) {
if (!address) {
throw new Error("address should not be falsy")
}
try {
const data = await this._httpClient.request(
"get",
`${api.getAccount}/${address}`
)
return data
} catch (err) {
return null
}
}
/**
* get balances
* @param {String} address optional address
* @return {Promise} resolves with http response
*/
async getBalance(address = this.address) {
try {
const data = await this.getAccount(address)
return data!.result.balances
} catch (err) {
return []
}
}
/**
* get markets
* @param {Number} limit max 1000 is default
* @param {Number} offset from beggining, default 0
* @return {Promise} resolves with http response
*/
async getMarkets(limit = 1000, offset = 0) {
try {
const data = await this._httpClient.request(
"get",
`${api.getMarkets}?limit=${limit}&offset=${offset}`
)
return data
} catch (err) {
console.warn("getMarkets error", err)
return []
}
}
/**
* get transactions for an account
* @param {String} address optional address
* @param {Number} offset from beggining, default 0
* @return {Promise} resolves with http response
* @deprecated please use getTxs instead.
*/
async getTransactions(address = this.address, offset = 0) {
try {
const data = await this._httpClient.request(
"get",
`${api.getTransactions}?address=${address}&offset=${offset}`
)
return data
} catch (err) {
console.warn("getTransactions error", err)
return []
}
}
/**
* get transactions for an account
* @param {String} address optional address
* @param {Number} startTime start time in milliseconds
* @param {Number} endTime end time in in milliseconds, endTime - startTime should be smaller than 7 days
* @return {Promise} resolves with http response ([more details](https://docs.binance.org/api-reference/dex-api/block-service.html#apiv1txs))
* ```js
* // Example:
* const client = new BncClient('https://testnet-api.binance.org')
* client.getTxs(...);
* ```
*/
async getTxs(address = this.address, startTime: number, endTime: number) {
try {
const data = await this._httpClient.request(
"get",
`${api.getTxs}?address=${address}&startTime=${startTime}&endTime=${endTime}`
)
return data
} catch (err) {
console.warn("getTxs error", err)
return []
}
}
/**
* get transaction
* @param {String} hash the transaction hash
* @return {Promise} resolves with http response
*/
async getTx(hash: string) {
try {
const data = await this._httpClient.request("get", `${api.getTx}/${hash}`)
return data
} catch (err) {
console.warn("getTx error", err)
return []
}
}
/**
* get depth for a given market
* @param {String} symbol the market pair
* @return {Promise} resolves with http response
*/
async getDepth(symbol = "BNB_BUSD-BD1") {
try {
const data = await this._httpClient.request(
"get",
`${api.getDepth}?symbol=${symbol}`
)
return data
} catch (err) {
console.warn("getDepth error", err)
return []
}
}
/**
* get open orders for an address
* @param {String} address binance address
* @param {String} symbol binance BEP2 symbol
* @return {Promise} resolves with http response
*/
async getOpenOrders(address: string = this.address!) {
try {
const data = await this._httpClient.request(
"get",
`${api.getOpenOrders}?address=${address}`
)
return data
} catch (err) {
console.warn("getOpenOrders error", err)
return []
}
}
/**
* get atomic swap
* @param {String} swapID: ID of an existing swap
* @return {Promise} AtomicSwap
*/
async getSwapByID(swapID: string) {
try {
const data = await this._httpClient.request(
"get",
`${api.getSwaps}/${swapID}`
)
return data
} catch (err) {
console.warn("query swap by swapID error", err)
return []
}
}
/**
* query atomic swap list by creator address
* @param {String} creator: swap creator address
* @param {Number} offset from beginning, default 0
* @param {Number} limit, max 1000 is default
* @return {Promise} Array of AtomicSwap
*/
async getSwapByCreator(creator: string, limit = 100, offset = 0) {
try {
const data = await this._httpClient.request(
"get",
`${api.getSwaps}?fromAddress=${creator}&limit=${limit}&offset=${offset}`
)
return data
} catch (err) {
console.warn("query swap list by swap creator error", err)
return []
}
}
/**
* query atomic swap list by recipient address
* @param {String} recipient: the recipient address of the swap
* @param {Number} offset from beginning, default 0
* @param {Number} limit, max 1000 is default
* @return {Promise} Array of AtomicSwap
*/
async getSwapByRecipient(recipient: string, limit = 100, offset = 0) {
try {
const data = await this._httpClient.request(
"get",
`${api.getSwaps}?toAddress=${recipient}&limit=${limit}&offset=${offset}`
)
return data
} catch (err) {
console.warn("query swap list by swap recipient error", err)
return []
}
}
/**
* Creates a private key and returns it and its address.
* @return {object} the private key and address in an object.
* {
* address,
* privateKey
* }
*/
createAccount() {
const privateKey = crypto.generatePrivateKey()
return {
privateKey,
address: crypto.getAddressFromPrivateKey(privateKey, this.addressPrefix),
}
}
/**
* Creates an account keystore object, and returns the private key and address.
* @param {String} password
* {
* privateKey,
* address,
* keystore
* }
*/
createAccountWithKeystore(password: string) {
if (!password) {
throw new Error("password should not be falsy")
}
const privateKey = crypto.generatePrivateKey()
const address = crypto.getAddressFromPrivateKey(
privateKey,
this.addressPrefix
)
const keystore = crypto.generateKeyStore(privateKey, password)
return {
privateKey,
address,
keystore,
}
}
/**
* Creates an account from mnemonic seed phrase.
* @return {object}
* {
* privateKey,
* address,
* mnemonic
* }
*/
createAccountWithMneomnic() {
const mnemonic = crypto.generateMnemonic()
const privateKey = crypto.getPrivateKeyFromMnemonic(mnemonic)
const address = crypto.getAddressFromPrivateKey(
privateKey,
this.addressPrefix
)
return {
privateKey,
address,
mnemonic,
}
}
/**
* Recovers an account from a keystore object.
* @param {object} keystore object.
* @param {string} password password.
* {
* privateKey,
* address
* }
*/
recoverAccountFromKeystore(
keystore: Parameters<typeof crypto.getPrivateKeyFromKeyStore>[0],
password: Parameters<typeof crypto.getPrivateKeyFromKeyStore>[1]
) {
const privateKey = crypto.getPrivateKeyFromKeyStore(keystore, password)
const address = crypto.getAddressFromPrivateKey(
privateKey,
this.addressPrefix
)
return {
privateKey,
address,
}
}
/**
* Recovers an account from a mnemonic seed phrase.
* @param {string} mneomnic
* {
* privateKey,
* address
* }
*/
recoverAccountFromMnemonic(mnemonic: string) {
const privateKey = crypto.getPrivateKeyFromMnemonic(mnemonic)
const address = crypto.getAddressFromPrivateKey(
privateKey,
this.addressPrefix
)
return {
privateKey,
address,
}
}
// support an old method name containing a typo
recoverAccountFromMneomnic(mnemonic: string) {
return this.recoverAccountFromMnemonic(mnemonic)
}
/**
* Recovers an account using private key.
* @param {String} privateKey
* {
* privateKey,
* address
* }
*/
recoverAccountFromPrivateKey(privateKey: string) {
const address = crypto.getAddressFromPrivateKey(
privateKey,
this.addressPrefix
)
return {
privateKey,
address,
}
}
/**
* Validates an address.
* @param {String} address
* @param {String} prefix
* @return {Boolean}
*/
checkAddress(
address: string,
prefix: BncClient["addressPrefix"] = this.addressPrefix
) {
return crypto.checkAddress(address, prefix)
}
/**
* Returns the address for the current account if setPrivateKey has been called on this client.
* @return {String}
*/
getClientKeyAddress() {
if (!this._privateKey)
throw new Error("no private key is set on this client")
const address = crypto.getAddressFromPrivateKey(
this._privateKey,
this.addressPrefix
)
this.address = address
return address
}
} | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ShowTestsQueryVariables = {
showID: string;
};
export type ShowTestsQueryResponse = {
readonly show: {
readonly " $fragmentRefs": FragmentRefs<"Show_show">;
} | null;
};
export type ShowTestsQuery = {
readonly response: ShowTestsQueryResponse;
readonly variables: ShowTestsQueryVariables;
};
/*
query ShowTestsQuery(
$showID: String!
) {
show(id: $showID) {
...Show_show
id
}
}
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 ShowArtworksEmptyState_show on Show {
isFairBooth
status
}
fragment ShowArtworks_show_1NSlNd on Show {
slug
internalID
showArtworks: filterArtworksConnection(first: 30, aggregations: [ARTIST, ARTIST_NATIONALITY, COLOR, DIMENSION_RANGE, FOLLOWED_ARTISTS, MAJOR_PERIOD, MATERIALS_TERMS, MEDIUM, PRICE_RANGE], input: {sort: "partner_show_position"}) {
aggregations {
slice
counts {
count
name
value
}
}
edges {
node {
id
__typename
}
cursor
}
counts {
total
}
...InfiniteScrollArtworksGrid_connection
pageInfo {
endCursor
hasNextPage
}
id
}
}
fragment ShowContextCard_show on Show {
internalID
slug
isFairBooth
fair {
internalID
slug
name
exhibitionPeriod(format: SHORT)
profile {
icon {
imageUrl: url(version: "untouched-png")
}
id
}
image {
imageUrl: url(version: "large_rectangle")
}
id
}
partner {
__typename
... on Partner {
internalID
slug
name
profile {
slug
id
}
cities
artworksConnection(sort: MERCHANDISABILITY_DESC, first: 3) {
edges {
node {
image {
url(version: "larger")
}
id
}
}
}
}
... on Node {
__isNode: __typename
id
}
... on ExternalPartner {
id
}
}
}
fragment ShowHeader_show on Show {
name
startAt
endAt
formattedStartAt: startAt(format: "MMMM D")
formattedEndAt: endAt(format: "MMMM D, YYYY")
partner {
__typename
... on Partner {
name
}
... on ExternalPartner {
name
id
}
... on Node {
__isNode: __typename
id
}
}
}
fragment ShowInfo_show on Show {
href
about: description
}
fragment ShowInstallShots_show on Show {
name
images(default: false) {
internalID
caption
src: url(version: ["larger", "large"])
dimensions: resized(height: 300) {
width
height
}
}
}
fragment ShowViewingRoom_show on Show {
internalID
slug
partner {
__typename
... on Partner {
name
}
... on ExternalPartner {
name
id
}
... on Node {
__isNode: __typename
id
}
}
viewingRoomsConnection {
edges {
node {
internalID
slug
title
status
distanceToOpen(short: true)
distanceToClose(short: true)
href
image {
imageURLs {
normalized
}
}
}
}
}
}
fragment Show_show on Show {
internalID
slug
...ShowHeader_show
...ShowInstallShots_show
...ShowInfo_show
...ShowViewingRoom_show
...ShowContextCard_show
...ShowArtworks_show_1NSlNd
...ShowArtworksEmptyState_show
viewingRoomIDs
images(default: false) {
__typename
}
counts {
eligibleArtworks
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "showID"
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "showID"
}
],
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "slug",
"storageKey": null
},
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
v5 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endAt",
"storageKey": null
},
v6 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v7 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v8 = [
(v4/*: any*/),
(v7/*: any*/)
],
v9 = {
"kind": "InlineFragment",
"selections": [
(v7/*: any*/)
],
"type": "Node",
"abstractKey": "__isNode"
},
v10 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
v11 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "title",
"storageKey": null
},
v12 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "status",
"storageKey": null
},
v13 = [
{
"kind": "Literal",
"name": "short",
"value": true
}
],
v14 = [
{
"kind": "Literal",
"name": "aggregations",
"value": [
"ARTIST",
"ARTIST_NATIONALITY",
"COLOR",
"DIMENSION_RANGE",
"FOLLOWED_ARTISTS",
"MAJOR_PERIOD",
"MATERIALS_TERMS",
"MEDIUM",
"PRICE_RANGE"
]
},
{
"kind": "Literal",
"name": "first",
"value": 30
},
{
"kind": "Literal",
"name": "input",
"value": {
"sort": "partner_show_position"
}
}
],
v15 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "String"
},
v16 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "FormattedNumber"
},
v17 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "ID"
},
v18 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Image"
},
v19 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Profile"
},
v20 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "String"
},
v21 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Int"
},
v22 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Boolean"
},
v23 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Artwork"
};
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "ShowTestsQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Show",
"kind": "LinkedField",
"name": "show",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "Show_show"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "ShowTestsQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Show",
"kind": "LinkedField",
"name": "show",
"plural": false,
"selections": [
(v2/*: any*/),
(v3/*: any*/),
(v4/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "startAt",
"storageKey": null
},
(v5/*: any*/),
{
"alias": "formattedStartAt",
"args": [
{
"kind": "Literal",
"name": "format",
"value": "MMMM D"
}
],
"kind": "ScalarField",
"name": "startAt",
"storageKey": "startAt(format:\"MMMM D\")"
},
{
"alias": "formattedEndAt",
"args": [
{
"kind": "Literal",
"name": "format",
"value": "MMMM D, YYYY"
}
],
"kind": "ScalarField",
"name": "endAt",
"storageKey": "endAt(format:\"MMMM D, YYYY\")"
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
(v6/*: any*/),
{
"kind": "InlineFragment",
"selections": [
(v4/*: any*/),
(v2/*: any*/),
(v3/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Profile",
"kind": "LinkedField",
"name": "profile",
"plural": false,
"selections": [
(v3/*: any*/),
(v7/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cities",
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "first",
"value": 3
},
{
"kind": "Literal",
"name": "sort",
"value": "MERCHANDISABILITY_DESC"
}
],
"concreteType": "ArtworkConnection",
"kind": "LinkedField",
"name": "artworksConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ArtworkEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"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\")"
}
],
"storageKey": null
},
(v7/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "artworksConnection(first:3,sort:\"MERCHANDISABILITY_DESC\")"
}
],
"type": "Partner",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": (v8/*: any*/),
"type": "ExternalPartner",
"abstractKey": null
},
(v9/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "default",
"value": false
}
],
"concreteType": "Image",
"kind": "LinkedField",
"name": "images",
"plural": true,
"selections": [
(v2/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "caption",
"storageKey": null
},
{
"alias": "src",
"args": [
{
"kind": "Literal",
"name": "version",
"value": [
"larger",
"large"
]
}
],
"kind": "ScalarField",
"name": "url",
"storageKey": "url(version:[\"larger\",\"large\"])"
},
{
"alias": "dimensions",
"args": [
{
"kind": "Literal",
"name": "height",
"value": 300
}
],
"concreteType": "ResizedImageUrl",
"kind": "LinkedField",
"name": "resized",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "width",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "height",
"storageKey": null
}
],
"storageKey": "resized(height:300)"
},
(v6/*: any*/)
],
"storageKey": "images(default:false)"
},
(v10/*: any*/),
{
"alias": "about",
"args": null,
"kind": "ScalarField",
"name": "description",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ViewingRoomsConnection",
"kind": "LinkedField",
"name": "viewingRoomsConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ViewingRoomsEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ViewingRoom",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v2/*: any*/),
(v3/*: any*/),
(v11/*: any*/),
(v12/*: any*/),
{
"alias": null,
"args": (v13/*: any*/),
"kind": "ScalarField",
"name": "distanceToOpen",
"storageKey": "distanceToOpen(short:true)"
},
{
"alias": null,
"args": (v13/*: any*/),
"kind": "ScalarField",
"name": "distanceToClose",
"storageKey": "distanceToClose(short:true)"
},
(v10/*: any*/),
{
"alias": null,
"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
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isFairBooth",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Fair",
"kind": "LinkedField",
"name": "fair",
"plural": false,
"selections": [
(v2/*: any*/),
(v3/*: any*/),
(v4/*: any*/),
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "format",
"value": "SHORT"
}
],
"kind": "ScalarField",
"name": "exhibitionPeriod",
"storageKey": "exhibitionPeriod(format:\"SHORT\")"
},
{
"alias": null,
"args": null,
"concreteType": "Profile",
"kind": "LinkedField",
"name": "profile",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "icon",
"plural": false,
"selections": [
{
"alias": "imageUrl",
"args": [
{
"kind": "Literal",
"name": "version",
"value": "untouched-png"
}
],
"kind": "ScalarField",
"name": "url",
"storageKey": "url(version:\"untouched-png\")"
}
],
"storageKey": null
},
(v7/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": [
{
"alias": "imageUrl",
"args": [
{
"kind": "Literal",
"name": "version",
"value": "large_rectangle"
}
],
"kind": "ScalarField",
"name": "url",
"storageKey": "url(version:\"large_rectangle\")"
}
],
"storageKey": null
},
(v7/*: any*/)
],
"storageKey": null
},
{
"alias": "showArtworks",
"args": (v14/*: any*/),
"concreteType": "FilterArtworksConnection",
"kind": "LinkedField",
"name": "filterArtworksConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ArtworksAggregationResults",
"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
},
(v4/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "value",
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "FilterArtworksEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v7/*: any*/),
(v6/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cursor",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "FilterArtworksCounts",
"kind": "LinkedField",
"name": "counts",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "total",
"storageKey": null
}
],
"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
},
(v7/*: any*/),
{
"kind": "InlineFragment",
"selections": [
{
"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
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
(v6/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v3/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "aspectRatio",
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "version",
"value": "large"
}
],
"kind": "ScalarField",
"name": "url",
"storageKey": "url(version:\"large\")"
}
],
"storageKey": null
},
(v11/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "date",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "saleMessage",
"storageKey": null
},
(v2/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "artistNames",
"storageKey": null
},
(v10/*: any*/),
{
"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
},
(v5/*: any*/),
(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": (v8/*: any*/),
"storageKey": null
}
],
"storageKey": null
},
(v9/*: any*/)
],
"storageKey": null
}
],
"type": "ArtworkConnectionInterface",
"abstractKey": "__isArtworkConnectionInterface"
}
],
"storageKey": "filterArtworksConnection(aggregations:[\"ARTIST\",\"ARTIST_NATIONALITY\",\"COLOR\",\"DIMENSION_RANGE\",\"FOLLOWED_ARTISTS\",\"MAJOR_PERIOD\",\"MATERIALS_TERMS\",\"MEDIUM\",\"PRICE_RANGE\"],first:30,input:{\"sort\":\"partner_show_position\"})"
},
{
"alias": "showArtworks",
"args": (v14/*: any*/),
"filters": [
"aggregations",
"input"
],
"handle": "connection",
"key": "Show_showArtworks",
"kind": "LinkedHandle",
"name": "filterArtworksConnection"
},
(v12/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "viewingRoomIDs",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ShowCounts",
"kind": "LinkedField",
"name": "counts",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "eligibleArtworks",
"storageKey": null
}
],
"storageKey": null
},
(v7/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": "27856e34cc439060191ae665aafb665b",
"metadata": {
"relayTestingSelectionTypeInfo": {
"show": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Show"
},
"show.about": (v15/*: any*/),
"show.counts": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ShowCounts"
},
"show.counts.eligibleArtworks": (v16/*: any*/),
"show.endAt": (v15/*: any*/),
"show.fair": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Fair"
},
"show.fair.exhibitionPeriod": (v15/*: any*/),
"show.fair.id": (v17/*: any*/),
"show.fair.image": (v18/*: any*/),
"show.fair.image.imageUrl": (v15/*: any*/),
"show.fair.internalID": (v17/*: any*/),
"show.fair.name": (v15/*: any*/),
"show.fair.profile": (v19/*: any*/),
"show.fair.profile.icon": (v18/*: any*/),
"show.fair.profile.icon.imageUrl": (v15/*: any*/),
"show.fair.profile.id": (v17/*: any*/),
"show.fair.slug": (v17/*: any*/),
"show.formattedEndAt": (v15/*: any*/),
"show.formattedStartAt": (v15/*: any*/),
"show.href": (v15/*: any*/),
"show.id": (v17/*: any*/),
"show.images": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "Image"
},
"show.images.__typename": (v20/*: any*/),
"show.images.caption": (v15/*: any*/),
"show.images.dimensions": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ResizedImageUrl"
},
"show.images.dimensions.height": (v21/*: any*/),
"show.images.dimensions.width": (v21/*: any*/),
"show.images.internalID": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ID"
},
"show.images.src": (v15/*: any*/),
"show.internalID": (v17/*: any*/),
"show.isFairBooth": (v22/*: any*/),
"show.name": (v15/*: any*/),
"show.partner": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "PartnerTypes"
},
"show.partner.__isNode": (v20/*: any*/),
"show.partner.__typename": (v20/*: any*/),
"show.partner.artworksConnection": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ArtworkConnection"
},
"show.partner.artworksConnection.edges": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "ArtworkEdge"
},
"show.partner.artworksConnection.edges.node": (v23/*: any*/),
"show.partner.artworksConnection.edges.node.id": (v17/*: any*/),
"show.partner.artworksConnection.edges.node.image": (v18/*: any*/),
"show.partner.artworksConnection.edges.node.image.url": (v15/*: any*/),
"show.partner.cities": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "String"
},
"show.partner.id": (v17/*: any*/),
"show.partner.internalID": (v17/*: any*/),
"show.partner.name": (v15/*: any*/),
"show.partner.profile": (v19/*: any*/),
"show.partner.profile.id": (v17/*: any*/),
"show.partner.profile.slug": (v17/*: any*/),
"show.partner.slug": (v17/*: any*/),
"show.showArtworks": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "FilterArtworksConnection"
},
"show.showArtworks.__isArtworkConnectionInterface": (v20/*: any*/),
"show.showArtworks.aggregations": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "ArtworksAggregationResults"
},
"show.showArtworks.aggregations.counts": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "AggregationCount"
},
"show.showArtworks.aggregations.counts.count": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "Int"
},
"show.showArtworks.aggregations.counts.name": (v20/*: any*/),
"show.showArtworks.aggregations.counts.value": (v20/*: any*/),
"show.showArtworks.aggregations.slice": {
"enumValues": [
"ARTIST",
"ARTIST_NATIONALITY",
"ATTRIBUTION_CLASS",
"COLOR",
"DIMENSION_RANGE",
"FOLLOWED_ARTISTS",
"GALLERY",
"INSTITUTION",
"LOCATION_CITY",
"MAJOR_PERIOD",
"MATERIALS_TERMS",
"MEDIUM",
"MERCHANDISABLE_ARTISTS",
"PARTNER",
"PARTNER_CITY",
"PERIOD",
"PRICE_RANGE",
"TOTAL"
],
"nullable": true,
"plural": false,
"type": "ArtworkAggregation"
},
"show.showArtworks.counts": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "FilterArtworksCounts"
},
"show.showArtworks.counts.total": (v16/*: any*/),
"show.showArtworks.edges": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "ArtworkEdgeInterface"
},
"show.showArtworks.edges.__isNode": (v20/*: any*/),
"show.showArtworks.edges.__typename": (v20/*: any*/),
"show.showArtworks.edges.cursor": (v20/*: any*/),
"show.showArtworks.edges.id": (v17/*: any*/),
"show.showArtworks.edges.node": (v23/*: any*/),
"show.showArtworks.edges.node.__typename": (v20/*: any*/),
"show.showArtworks.edges.node.artistNames": (v15/*: any*/),
"show.showArtworks.edges.node.date": (v15/*: any*/),
"show.showArtworks.edges.node.href": (v15/*: any*/),
"show.showArtworks.edges.node.id": (v17/*: any*/),
"show.showArtworks.edges.node.image": (v18/*: any*/),
"show.showArtworks.edges.node.image.aspectRatio": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "Float"
},
"show.showArtworks.edges.node.image.url": (v15/*: any*/),
"show.showArtworks.edges.node.internalID": (v17/*: any*/),
"show.showArtworks.edges.node.partner": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Partner"
},
"show.showArtworks.edges.node.partner.id": (v17/*: any*/),
"show.showArtworks.edges.node.partner.name": (v15/*: any*/),
"show.showArtworks.edges.node.sale": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Sale"
},
"show.showArtworks.edges.node.sale.displayTimelyAt": (v15/*: any*/),
"show.showArtworks.edges.node.sale.endAt": (v15/*: any*/),
"show.showArtworks.edges.node.sale.id": (v17/*: any*/),
"show.showArtworks.edges.node.sale.isAuction": (v22/*: any*/),
"show.showArtworks.edges.node.sale.isClosed": (v22/*: any*/),
"show.showArtworks.edges.node.saleArtwork": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SaleArtwork"
},
"show.showArtworks.edges.node.saleArtwork.counts": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SaleArtworkCounts"
},
"show.showArtworks.edges.node.saleArtwork.counts.bidderPositions": (v16/*: any*/),
"show.showArtworks.edges.node.saleArtwork.currentBid": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SaleArtworkCurrentBid"
},
"show.showArtworks.edges.node.saleArtwork.currentBid.display": (v15/*: any*/),
"show.showArtworks.edges.node.saleArtwork.id": (v17/*: any*/),
"show.showArtworks.edges.node.saleArtwork.lotLabel": (v15/*: any*/),
"show.showArtworks.edges.node.saleMessage": (v15/*: any*/),
"show.showArtworks.edges.node.slug": (v17/*: any*/),
"show.showArtworks.edges.node.title": (v15/*: any*/),
"show.showArtworks.id": (v17/*: any*/),
"show.showArtworks.pageInfo": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "PageInfo"
},
"show.showArtworks.pageInfo.endCursor": (v15/*: any*/),
"show.showArtworks.pageInfo.hasNextPage": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "Boolean"
},
"show.showArtworks.pageInfo.startCursor": (v15/*: any*/),
"show.slug": (v17/*: any*/),
"show.startAt": (v15/*: any*/),
"show.status": (v15/*: any*/),
"show.viewingRoomIDs": {
"enumValues": null,
"nullable": false,
"plural": true,
"type": "String"
},
"show.viewingRoomsConnection": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ViewingRoomsConnection"
},
"show.viewingRoomsConnection.edges": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "ViewingRoomsEdge"
},
"show.viewingRoomsConnection.edges.node": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ViewingRoom"
},
"show.viewingRoomsConnection.edges.node.distanceToClose": (v15/*: any*/),
"show.viewingRoomsConnection.edges.node.distanceToOpen": (v15/*: any*/),
"show.viewingRoomsConnection.edges.node.href": (v15/*: any*/),
"show.viewingRoomsConnection.edges.node.image": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ARImage"
},
"show.viewingRoomsConnection.edges.node.image.imageURLs": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ImageURLs"
},
"show.viewingRoomsConnection.edges.node.image.imageURLs.normalized": (v15/*: any*/),
"show.viewingRoomsConnection.edges.node.internalID": (v17/*: any*/),
"show.viewingRoomsConnection.edges.node.slug": (v20/*: any*/),
"show.viewingRoomsConnection.edges.node.status": (v20/*: any*/),
"show.viewingRoomsConnection.edges.node.title": (v20/*: any*/)
}
},
"name": "ShowTestsQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = 'e66a82701b1f2dc6d44fad3939c7ee9e';
export default node; | the_stack |
import './VDataTable.sass'
// Types
import { VNode, VNodeChildrenArrayContents, VNodeChildren } from 'vue'
import { PropValidator } from 'vue/types/options'
import {
DataTableHeader,
DataTableFilterFunction,
DataScopeProps,
DataOptions,
DataPagination,
DataTableCompareFunction,
DataItemsPerPageOption,
ItemGroup,
RowClassFunction,
DataTableItemProps,
} from 'vuetify/types'
// Components
import { VData } from '../VData'
import { VDataFooter, VDataIterator } from '../VDataIterator'
import VBtn from '../VBtn'
import VDataTableHeader from './VDataTableHeader'
// import VVirtualTable from './VVirtualTable'
import VIcon from '../VIcon'
import Row from './Row'
import RowGroup from './RowGroup'
import VSimpleCheckbox from '../VCheckbox/VSimpleCheckbox'
import VSimpleTable from './VSimpleTable'
import MobileRow from './MobileRow'
// Mixins
import Loadable from '../../mixins/loadable'
// Directives
import ripple from '../../directives/ripple'
// Helpers
import mixins from '../../util/mixins'
import { deepEqual, getObjectValueByPath, getPrefixedScopedSlots, getSlot, defaultFilter, camelizeObjectKeys, getPropertyFromItem } from '../../util/helpers'
import { breaking } from '../../util/console'
import { mergeClasses } from '../../util/mergeData'
function filterFn (item: any, search: string | null, filter: DataTableFilterFunction) {
return (header: DataTableHeader) => {
const value = getObjectValueByPath(item, header.value)
return header.filter ? header.filter(value, search, item) : filter(value, search, item)
}
}
function searchTableItems (
items: any[],
search: string | null,
headersWithCustomFilters: DataTableHeader[],
headersWithoutCustomFilters: DataTableHeader[],
customFilter: DataTableFilterFunction
) {
search = typeof search === 'string' ? search.trim() : null
return items.filter(item => {
// Headers with custom filters are evaluated whether or not a search term has been provided.
// We need to match every filter to be included in the results.
const matchesColumnFilters = headersWithCustomFilters.every(filterFn(item, search, defaultFilter))
// Headers without custom filters are only filtered by the `search` property if it is defined.
// We only need a single column to match the search term to be included in the results.
const matchesSearchTerm = !search || headersWithoutCustomFilters.some(filterFn(item, search, customFilter))
return matchesColumnFilters && matchesSearchTerm
})
}
/* @vue/component */
export default mixins(
VDataIterator,
Loadable,
).extend({
name: 'v-data-table',
// https://github.com/vuejs/vue/issues/6872
directives: {
ripple,
},
props: {
headers: {
type: Array,
default: () => [],
} as PropValidator<DataTableHeader[]>,
showSelect: Boolean,
checkboxColor: String,
showExpand: Boolean,
showGroupBy: Boolean,
// TODO: Fix
// virtualRows: Boolean,
height: [Number, String],
hideDefaultHeader: Boolean,
caption: String,
dense: Boolean,
headerProps: Object,
calculateWidths: Boolean,
fixedHeader: Boolean,
headersLength: Number,
expandIcon: {
type: String,
default: '$expand',
},
customFilter: {
type: Function,
default: defaultFilter,
} as PropValidator<typeof defaultFilter>,
itemClass: {
type: [String, Function],
default: () => '',
} as PropValidator<RowClassFunction | string>,
loaderHeight: {
type: [Number, String],
default: 4,
},
},
data () {
return {
internalGroupBy: [] as string[],
openCache: {} as { [key: string]: boolean },
widths: [] as number[],
}
},
computed: {
computedHeaders (): DataTableHeader[] {
if (!this.headers) return []
const headers = this.headers.filter(h => h.value === undefined || !this.internalGroupBy.find(v => v === h.value))
const defaultHeader = { text: '', sortable: false, width: '1px' }
if (this.showSelect) {
const index = headers.findIndex(h => h.value === 'data-table-select')
if (index < 0) headers.unshift({ ...defaultHeader, value: 'data-table-select' })
else headers.splice(index, 1, { ...defaultHeader, ...headers[index] })
}
if (this.showExpand) {
const index = headers.findIndex(h => h.value === 'data-table-expand')
if (index < 0) headers.unshift({ ...defaultHeader, value: 'data-table-expand' })
else headers.splice(index, 1, { ...defaultHeader, ...headers[index] })
}
return headers
},
colspanAttrs (): object | undefined {
return this.isMobile ? undefined : {
colspan: this.headersLength || this.computedHeaders.length,
}
},
columnSorters (): Record<string, DataTableCompareFunction> {
return this.computedHeaders.reduce<Record<string, DataTableCompareFunction>>((acc, header) => {
if (header.sort) acc[header.value] = header.sort
return acc
}, {})
},
headersWithCustomFilters (): DataTableHeader[] {
return this.headers.filter(header => header.filter && (!header.hasOwnProperty('filterable') || header.filterable === true))
},
headersWithoutCustomFilters (): DataTableHeader[] {
return this.headers.filter(header => !header.filter && (!header.hasOwnProperty('filterable') || header.filterable === true))
},
sanitizedHeaderProps (): Record<string, any> {
return camelizeObjectKeys(this.headerProps)
},
computedItemsPerPage (): number {
const itemsPerPage = this.options && this.options.itemsPerPage ? this.options.itemsPerPage : this.itemsPerPage
const itemsPerPageOptions: DataItemsPerPageOption[] | undefined = this.sanitizedFooterProps.itemsPerPageOptions
if (
itemsPerPageOptions &&
!itemsPerPageOptions.find(item => typeof item === 'number' ? item === itemsPerPage : item.value === itemsPerPage)
) {
const firstOption = itemsPerPageOptions[0]
return typeof firstOption === 'object' ? firstOption.value : firstOption
}
return itemsPerPage
},
},
created () {
const breakingProps = [
['sort-icon', 'header-props.sort-icon'],
['hide-headers', 'hide-default-header'],
['select-all', 'show-select'],
]
/* istanbul ignore next */
breakingProps.forEach(([original, replacement]) => {
if (this.$attrs.hasOwnProperty(original)) breaking(original, replacement, this)
})
},
mounted () {
// if ((!this.sortBy || !this.sortBy.length) && (!this.options.sortBy || !this.options.sortBy.length)) {
// const firstSortable = this.headers.find(h => !('sortable' in h) || !!h.sortable)
// if (firstSortable) this.updateOptions({ sortBy: [firstSortable.value], sortDesc: [false] })
// }
if (this.calculateWidths) {
window.addEventListener('resize', this.calcWidths)
this.calcWidths()
}
},
beforeDestroy () {
if (this.calculateWidths) {
window.removeEventListener('resize', this.calcWidths)
}
},
methods: {
calcWidths () {
this.widths = Array.from(this.$el.querySelectorAll('th')).map(e => e.clientWidth)
},
customFilterWithColumns (items: any[], search: string) {
return searchTableItems(items, search, this.headersWithCustomFilters, this.headersWithoutCustomFilters, this.customFilter)
},
customSortWithHeaders (items: any[], sortBy: string[], sortDesc: boolean[], locale: string) {
return this.customSort(items, sortBy, sortDesc, locale, this.columnSorters)
},
createItemProps (item: any, index: number): DataTableItemProps {
const props = VDataIterator.options.methods.createItemProps.call(this, item, index)
return Object.assign(props, { headers: this.computedHeaders })
},
genCaption (props: DataScopeProps) {
if (this.caption) return [this.$createElement('caption', [this.caption])]
return getSlot(this, 'caption', props, true)
},
genColgroup (props: DataScopeProps) {
return this.$createElement('colgroup', this.computedHeaders.map(header => {
return this.$createElement('col', {
class: {
divider: header.divider,
},
})
}))
},
genLoading () {
const th = this.$createElement('th', {
staticClass: 'column',
attrs: this.colspanAttrs,
}, [this.genProgress()])
const tr = this.$createElement('tr', {
staticClass: 'v-data-table__progress',
}, [th])
return this.$createElement('thead', [tr])
},
genHeaders (props: DataScopeProps) {
const data = {
props: {
...this.sanitizedHeaderProps,
headers: this.computedHeaders,
options: props.options,
mobile: this.isMobile,
showGroupBy: this.showGroupBy,
checkboxColor: this.checkboxColor,
someItems: this.someItems,
everyItem: this.everyItem,
singleSelect: this.singleSelect,
disableSort: this.disableSort,
},
on: {
sort: props.sort,
group: props.group,
'toggle-select-all': this.toggleSelectAll,
},
}
// TODO: rename to 'head'? (thead, tbody, tfoot)
const children: VNodeChildrenArrayContents = [getSlot(this, 'header', {
...data,
isMobile: this.isMobile,
})]
if (!this.hideDefaultHeader) {
const scopedSlots = getPrefixedScopedSlots('header.', this.$scopedSlots)
children.push(this.$createElement(VDataTableHeader, {
...data,
scopedSlots,
}))
}
if (this.loading) children.push(this.genLoading())
return children
},
genEmptyWrapper (content: VNodeChildrenArrayContents) {
return this.$createElement('tr', {
staticClass: 'v-data-table__empty-wrapper',
}, [
this.$createElement('td', {
attrs: this.colspanAttrs,
}, content),
])
},
genItems (items: any[], props: DataScopeProps) {
const empty = this.genEmpty(props.originalItemsLength, props.pagination.itemsLength)
if (empty) return [empty]
return props.groupedItems
? this.genGroupedRows(props.groupedItems, props)
: this.genRows(items, props)
},
genGroupedRows (groupedItems: ItemGroup<any>[], props: DataScopeProps) {
return groupedItems.map(group => {
if (!this.openCache.hasOwnProperty(group.name)) this.$set(this.openCache, group.name, true)
if (this.$scopedSlots.group) {
return this.$scopedSlots.group({
group: group.name,
options: props.options,
isMobile: this.isMobile,
items: group.items,
headers: this.computedHeaders,
})
} else {
return this.genDefaultGroupedRow(group.name, group.items, props)
}
})
},
genDefaultGroupedRow (group: string, items: any[], props: DataScopeProps) {
const isOpen = !!this.openCache[group]
const children: VNodeChildren = [
this.$createElement('template', { slot: 'row.content' }, this.genRows(items, props)),
]
const toggleFn = () => this.$set(this.openCache, group, !this.openCache[group])
const removeFn = () => props.updateOptions({ groupBy: [], groupDesc: [] })
if (this.$scopedSlots['group.header']) {
children.unshift(this.$createElement('template', { slot: 'column.header' }, [
this.$scopedSlots['group.header']!({
group,
groupBy: props.options.groupBy,
isMobile: this.isMobile,
items,
headers: this.computedHeaders,
isOpen,
toggle: toggleFn,
remove: removeFn,
}),
]))
} else {
const toggle = this.$createElement(VBtn, {
staticClass: 'ma-0',
props: {
icon: true,
small: true,
},
on: {
click: toggleFn,
},
}, [this.$createElement(VIcon, [isOpen ? '$minus' : '$plus'])])
const remove = this.$createElement(VBtn, {
staticClass: 'ma-0',
props: {
icon: true,
small: true,
},
on: {
click: removeFn,
},
}, [this.$createElement(VIcon, ['$close'])])
const column = this.$createElement('td', {
staticClass: 'text-start',
attrs: this.colspanAttrs,
}, [toggle, `${props.options.groupBy[0]}: ${group}`, remove])
children.unshift(this.$createElement('template', { slot: 'column.header' }, [column]))
}
if (this.$scopedSlots['group.summary']) {
children.push(this.$createElement('template', { slot: 'column.summary' }, [
this.$scopedSlots['group.summary']!({
group,
groupBy: props.options.groupBy,
isMobile: this.isMobile,
items,
headers: this.computedHeaders,
isOpen,
toggle: toggleFn,
}),
]))
}
return this.$createElement(RowGroup, {
key: group,
props: {
value: isOpen,
},
}, children)
},
genRows (items: any[], props: DataScopeProps) {
return this.$scopedSlots.item ? this.genScopedRows(items, props) : this.genDefaultRows(items, props)
},
genScopedRows (items: any[], props: DataScopeProps) {
const rows = []
for (let i = 0; i < items.length; i++) {
const item = items[i]
rows.push(this.$scopedSlots.item!({
...this.createItemProps(item, i),
isMobile: this.isMobile,
}))
if (this.isExpanded(item)) {
rows.push(this.$scopedSlots['expanded-item']!({
headers: this.computedHeaders,
isMobile: this.isMobile,
index: i,
item,
}))
}
}
return rows
},
genDefaultRows (items: any[], props: DataScopeProps) {
return this.$scopedSlots['expanded-item']
? items.map((item, index) => this.genDefaultExpandedRow(item, index))
: items.map((item, index) => this.genDefaultSimpleRow(item, index))
},
genDefaultExpandedRow (item: any, index: number): VNode {
const isExpanded = this.isExpanded(item)
const classes = {
'v-data-table__expanded v-data-table__expanded__row': isExpanded,
}
const headerRow = this.genDefaultSimpleRow(item, index, classes)
const expandedRow = this.$createElement('tr', {
staticClass: 'v-data-table__expanded v-data-table__expanded__content',
}, [this.$scopedSlots['expanded-item']!({
headers: this.computedHeaders,
isMobile: this.isMobile,
item,
})])
return this.$createElement(RowGroup, {
props: {
value: isExpanded,
},
}, [
this.$createElement('template', { slot: 'row.header' }, [headerRow]),
this.$createElement('template', { slot: 'row.content' }, [expandedRow]),
])
},
genDefaultSimpleRow (item: any, index: number, classes: Record<string, boolean> = {}): VNode {
const scopedSlots = getPrefixedScopedSlots('item.', this.$scopedSlots)
const data = this.createItemProps(item, index)
if (this.showSelect) {
const slot = scopedSlots['data-table-select']
scopedSlots['data-table-select'] = slot ? () => slot({
...data,
isMobile: this.isMobile,
}) : () => this.$createElement(VSimpleCheckbox, {
staticClass: 'v-data-table__checkbox',
props: {
value: data.isSelected,
disabled: !this.isSelectable(item),
color: this.checkboxColor ?? '',
},
on: {
input: (val: boolean) => data.select(val),
},
})
}
if (this.showExpand) {
const slot = scopedSlots['data-table-expand']
scopedSlots['data-table-expand'] = slot ? () => slot(data) : () => this.$createElement(VIcon, {
staticClass: 'v-data-table__expand-icon',
class: {
'v-data-table__expand-icon--active': data.isExpanded,
},
on: {
click: (e: MouseEvent) => {
e.stopPropagation()
data.expand(!data.isExpanded)
},
},
}, [this.expandIcon])
}
return this.$createElement(this.isMobile ? MobileRow : Row, {
key: getObjectValueByPath(item, this.itemKey),
class: mergeClasses(
{ ...classes, 'v-data-table__selected': data.isSelected },
getPropertyFromItem(item, this.itemClass)
),
props: {
headers: this.computedHeaders,
hideDefaultHeader: this.hideDefaultHeader,
index,
item,
rtl: this.$vuetify.rtl,
},
scopedSlots,
on: {
// TODO: for click, the first argument should be the event, and the second argument should be data,
// but this is a breaking change so it's for v3
click: () => this.$emit('click:row', item, data),
contextmenu: (event: MouseEvent) => this.$emit('contextmenu:row', event, data),
dblclick: (event: MouseEvent) => this.$emit('dblclick:row', event, data),
},
})
},
genBody (props: DataScopeProps): VNode | string | VNodeChildren {
const data = {
...props,
expand: this.expand,
headers: this.computedHeaders,
isExpanded: this.isExpanded,
isMobile: this.isMobile,
isSelected: this.isSelected,
select: this.select,
}
if (this.$scopedSlots.body) {
return this.$scopedSlots.body!(data)
}
return this.$createElement('tbody', [
getSlot(this, 'body.prepend', data, true),
this.genItems(props.items, props),
getSlot(this, 'body.append', data, true),
])
},
genFoot (props: DataScopeProps): VNode[] | undefined {
return this.$scopedSlots.foot?.(props)
},
genFooters (props: DataScopeProps) {
const data = {
props: {
options: props.options,
pagination: props.pagination,
itemsPerPageText: '$vuetify.dataTable.itemsPerPageText',
...this.sanitizedFooterProps,
},
on: {
'update:options': (value: any) => props.updateOptions(value),
},
widths: this.widths,
headers: this.computedHeaders,
}
const children: VNodeChildren = [
getSlot(this, 'footer', data, true),
]
if (!this.hideDefaultFooter) {
children.push(this.$createElement(VDataFooter, {
...data,
scopedSlots: getPrefixedScopedSlots('footer.', this.$scopedSlots),
}))
}
return children
},
genDefaultScopedSlot (props: DataScopeProps): VNode {
const simpleProps = {
height: this.height,
fixedHeader: this.fixedHeader,
dense: this.dense,
}
// if (this.virtualRows) {
// return this.$createElement(VVirtualTable, {
// props: Object.assign(simpleProps, {
// items: props.items,
// height: this.height,
// rowHeight: this.dense ? 24 : 48,
// headerHeight: this.dense ? 32 : 48,
// // TODO: expose rest of props from virtual table?
// }),
// scopedSlots: {
// items: ({ items }) => this.genItems(items, props) as any,
// },
// }, [
// this.proxySlot('body.before', [this.genCaption(props), this.genHeaders(props)]),
// this.proxySlot('bottom', this.genFooters(props)),
// ])
// }
return this.$createElement(VSimpleTable, {
props: simpleProps,
class: {
'v-data-table--mobile': this.isMobile,
},
}, [
this.proxySlot('top', getSlot(this, 'top', {
...props,
isMobile: this.isMobile,
}, true)),
this.genCaption(props),
this.genColgroup(props),
this.genHeaders(props),
this.genBody(props),
this.genFoot(props),
this.proxySlot('bottom', this.genFooters(props)),
])
},
proxySlot (slot: string, content: VNodeChildren) {
return this.$createElement('template', { slot }, content)
},
},
render (): VNode {
return this.$createElement(VData, {
props: {
...this.$props,
customFilter: this.customFilterWithColumns,
customSort: this.customSortWithHeaders,
itemsPerPage: this.computedItemsPerPage,
},
on: {
'update:options': (v: DataOptions, old: DataOptions) => {
this.internalGroupBy = v.groupBy || []
!deepEqual(v, old) && this.$emit('update:options', v)
},
'update:page': (v: number) => this.$emit('update:page', v),
'update:items-per-page': (v: number) => this.$emit('update:items-per-page', v),
'update:sort-by': (v: string | string[]) => this.$emit('update:sort-by', v),
'update:sort-desc': (v: boolean | boolean[]) => this.$emit('update:sort-desc', v),
'update:group-by': (v: string | string[]) => this.$emit('update:group-by', v),
'update:group-desc': (v: boolean | boolean[]) => this.$emit('update:group-desc', v),
pagination: (v: DataPagination, old: DataPagination) => !deepEqual(v, old) && this.$emit('pagination', v),
'current-items': (v: any[]) => {
this.internalCurrentItems = v
this.$emit('current-items', v)
},
'page-count': (v: number) => this.$emit('page-count', v),
},
scopedSlots: {
default: this.genDefaultScopedSlot,
},
})
},
}) | the_stack |
import { addListeners } from '../../../../client/addListener'
import {
ANIMATION_T_MS,
linearTransition,
} from '../../../../client/animation/animation'
import { ANIMATION_T_S } from '../../../../client/animation/ANIMATION_T_S'
import { Component } from '../../../../client/component'
import mergeStyle from '../../../../client/component/mergeStyle'
import { makeCustomListener } from '../../../../client/event/custom'
import { makeClickListener } from '../../../../client/event/pointer/click'
import { makePointerCancelListener } from '../../../../client/event/pointer/pointercancel'
import { makePointerDownListener } from '../../../../client/event/pointer/pointerdown'
import { makePointerMoveListener } from '../../../../client/event/pointer/pointermove'
import { makePointerUpListener } from '../../../../client/event/pointer/pointerup'
import { makeResizeListener } from '../../../../client/event/resize'
import { MAX_Z_INDEX } from '../../../../client/MAX_Z_INDEX'
import parentElement from '../../../../client/platform/web/parentElement'
import {
COLOR_NONE,
setAlpha,
themeBackgroundColor,
} from '../../../../client/theme'
import { userSelect } from '../../../../client/util/style/userSelect'
import { DIM_OPACITY, whenInteracted } from '../../../../client/whenInteracted'
import { Pod } from '../../../../pod'
import { System } from '../../../../system'
import { Dict } from '../../../../types/Dict'
import { IHTMLDivElement } from '../../../../types/global/dom'
import { Unlisten } from '../../../../types/Unlisten'
import callAll from '../../../../util/call/callAll'
import { uuid } from '../../../../util/id'
import clamp from '../../../core/relation/Clamp/f'
import Div from '../../../platform/component/Div/Component'
import Icon from '../../../platform/component/Icon/Component'
import { dragOverTimeListener } from '../IconTabs/dragOverTimeListener'
export interface Props {
className?: string
style?: Dict<string>
icon?: string
width?: number
height?: number
x?: number
y?: number
_x?: number
_y?: number
collapsed?: boolean
}
export const DEFAULT_STYLE = {}
export const COLLAPSED_WIDTH = 33
export const COLLAPSED_HEIGHT = 33
export const BUTTON_HEIGHT = 24
export default class GUIControl extends Component<IHTMLDivElement, Props> {
private _root: Div
private _collapsed_x: number
private _collapsed_y: number
private _non_collapsed_x: number
private _non_collapsed_y: number
private _x: number
private _y: number
private _collapsed: boolean
constructor($props: Props, $system: System, $pod: Pod) {
super($props, $system, $pod)
const { icon, width = 100, height = 100, style = {} } = this.$props
let { x = 0, y = 0, collapsed = true } = this.$props
this._x = x
this._y = y
this._collapsed = collapsed
// if (this._collapsed) {
// this._collapsed_x = this._x
// this._collapsed_y = this._y
// } else {
// }
this._collapsed_x = this._x
this._collapsed_y = this._y
this._non_collapsed_x = this._x
this._non_collapsed_y = this._y
const WR = COLLAPSED_WIDTH / width
const HR = COLLAPSED_HEIGHT / height
const root = new Div(
{
className: 'iounappcontrol',
style: {
position: 'absolute',
left: `${x}px`,
top: `${y}px`,
width: this._collapsed ? `${COLLAPSED_WIDTH}px` : `${width}px`,
height: this._collapsed ? `${COLLAPSED_HEIGHT}px` : `${height}px`,
borderRadius: '3px',
// borderRadius: this._collapsed ? '50%' : '3px',
boxSizing: 'content-box',
borderWidth: '1px',
borderStyle: 'solid',
borderColor: this._collapsed ? 'currentColor' : COLOR_NONE,
transition: `opacity ${ANIMATION_T_S}s linear`,
zIndex: `${this._z_index}`,
opacity: this._collapsed ? `${DIM_OPACITY}` : '0',
touchAction: 'none',
// contain: 'size layout style paint',
...style,
},
},
this.$system,
this.$pod
)
const collapse = () => {
if (_iounapp_control_in_count === 0) {
this._collapsed = true
unlisten_pointer()
unlisten_pointer = listen_pointer(root)
this._x = this._collapsed_x || this._x + (width - COLLAPSED_WIDTH) / 2
this._y = this._collapsed_y || this._y + height - COLLAPSED_HEIGHT
this._clamp_x_y()
const backgroundColor = this._background_color()
mergeStyle(root, {
left: `${this._x}px`,
top: `${this._y}px`,
width: `${COLLAPSED_WIDTH}px`,
height: `${COLLAPSED_HEIGHT}px`,
borderColor: 'currentColor',
// borderRadius: '50%',
backgroundColor,
transition: `left ${ANIMATION_T_S}s linear, top ${ANIMATION_T_S}s linear, width ${ANIMATION_T_S}s linear, height ${ANIMATION_T_S}s linear, border-color ${ANIMATION_T_S}s linear, border-radius ${ANIMATION_T_S}s linear, background-color ${ANIMATION_T_S}s linear`,
})
// root.animate(
// [
// {
// top: `${y}px`,
// left: `${x}px`,
// width: `33px`,
// height: `33px`,
// borderColor: 'currentColor',
// },
// ],
// {
// duration: ANIMATION_T_MS,
// fill: 'forwards',
// }
// )
setTimeout(() => {
mergeStyle(root, {
transition: `opacity ${ANIMATION_T_S}s linear`,
})
}, ANIMATION_T_MS)
mergeStyle(container, {
opacity: '0',
transform: `scale(${WR}, ${HR})`,
pointerEvents: 'none',
...userSelect('none'),
})
mergeStyle(_icon, {
opacity: '1',
pointerEvents: 'auto',
})
mergeStyle(button, {
bottom: '-13px',
pointerEvents: 'none',
})
reset_dim()
} else {
this.dispatchContextEvent('_iounapp_control_back', false)
}
}
const uncollapse = () => {
const { width, height } = this.$props
this._collapsed = false
unlisten_pointer()
unlisten_pointer = listen_pointer(button)
this._x = this._non_collapsed_x || (this._x - width + COLLAPSED_WIDTH) / 2
this._y = this._non_collapsed_y || this._y - height + COLLAPSED_HEIGHT
this._clamp_x_y()
mergeStyle(root, {
left: `${this._x}px`,
top: `${this._y}px`,
width: `${width}px`,
height: `${height}px`,
borderColor: COLOR_NONE,
// borderRadius: '3px',
backgroundColor: COLOR_NONE,
transition: `opacity ${ANIMATION_T_S}s linear, left ${ANIMATION_T_S}s linear, top ${ANIMATION_T_S}s linear, width ${ANIMATION_T_S}s linear, height ${ANIMATION_T_S}s linear, border-color ${ANIMATION_T_S}s linear, border-radius ${ANIMATION_T_S}s linear, background-color ${ANIMATION_T_S}s linear`,
})
// root.animate(
// [
// {
// top: `${y}px`,
// left: `${x}px`,
// width: `312px`,
// height: `210px`,
// },
// ],
// {
// duration: ANIMATION_T_MS,
// fill: 'forwards',
// }
// )
mergeStyle(container, {
opacity: '1',
transform: 'scale(1, 1)',
pointerEvents: 'auto',
...userSelect('auto'),
})
mergeStyle(button, {
bottom: '-24px',
pointerEvents: 'auto',
})
setTimeout(() => {
mergeStyle(root, {
transition: `opacity ${ANIMATION_T_S}s linear`,
})
}, ANIMATION_T_MS)
mergeStyle(_icon, {
opacity: '0',
pointerEvents: 'none',
})
undim()
}
const toggle_collapse = (): void => {
if (this._collapsed) {
uncollapse()
} else {
collapse()
}
}
let unlisten_pointer: Unlisten
const listen_pointer = (component: Component): Unlisten => {
return callAll([
component.addEventListeners([
makeClickListener({
onClick: () => {
toggle_collapse()
},
}),
makePointerDownListener(({ pointerId, clientX, clientY }) => {
component.setPointerCapture(pointerId)
let hx = clientX - this._x
let hy = clientY - this._y
const release = () => {
component.releasePointerCapture(pointerId)
unlisten()
}
const unlisten = component.addEventListeners([
makePointerMoveListener(({ clientX, clientY }) => {
this._x = clientX - hx
this._y = clientY - hy
if (this._collapsed) {
this._collapsed_x = this._x
this._collapsed_y = this._y
} else {
this._non_collapsed_x = this._x
this._non_collapsed_y = this._y
}
this._clamp_x_y()
mergeStyle(root, {
left: `${this._x}px`,
top: `${this._y}px`,
})
}),
makePointerUpListener(() => {
// alert('up')
release()
}),
makePointerCancelListener(() => {
// alert('cancel')
release()
}),
])
}),
]),
dragOverTimeListener(component, 500, () => {
toggle_collapse()
}),
])
}
const dim = () => {
mergeStyle(root, {
opacity: `${DIM_OPACITY}`,
})
}
const undim = () => {
mergeStyle(root, {
opacity: '1',
})
}
const reset_dim = () => {
if (this._collapsed) {
const on_active = (): void => {
const message_id = uuid()
this._message_id[message_id] = true
this.dispatchContextEvent('_iounapp_control_foreground', {
message_id,
})
this._set_z_index(MAX_Z_INDEX)
if (!this._collapsed) {
return
}
undim()
}
const on_inactive = (): void => {
if (!this._collapsed) {
return
}
dim()
}
const unlisten_interacted = whenInteracted(
root,
3000,
false,
on_active,
on_inactive
)
}
}
this._root = root
reset_dim()
const container = new Div(
{
style: {
position: 'absolute',
top: '0',
left: '0',
transform: `${
this._collapsed ? `scale(${WR}, ${HR})` : 'scale(1, 1)'
}`,
transformOrigin: 'top left',
borderWidth: '0px',
borderStyle: 'solid',
borderColor: COLOR_NONE,
width: `${width}px`,
height: `${height}px`,
opacity: this._collapsed ? '0' : '1',
transition: `transform ${ANIMATION_T_S}s linear, opacity ${ANIMATION_T_S}s linear`,
},
},
this.$system,
this.$pod
)
let _iounapp_control_in_count = 0
container.addEventListeners([
makeCustomListener('_iounapp_control_in', () => {
_iounapp_control_in_count++
}),
makeCustomListener('_iounapp_control_out', () => {
_iounapp_control_in_count--
}),
])
const _icon = new Icon(
{
className: 'iounapp-control-icon',
icon,
style: {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
padding: '3px',
boxSizing: 'border-box',
width: '100%',
height: '100%',
opacity: this._collapsed ? '1' : '0',
transition: `opacity ${ANIMATION_T_S}s linear`,
cursor: 'pointer',
pointerEvents: this._collapsed ? 'auto' : 'none',
},
},
this.$system,
this.$pod
)
_icon.addEventListener(
makeClickListener({
onClick: uncollapse,
})
)
_icon.$element.setAttribute('dropTarget', 'true')
const button = new Div(
{
style: {
position: 'absolute',
bottom: this._collapsed
? `-${BUTTON_HEIGHT / 2 + 1}px`
: `-${BUTTON_HEIGHT}px`,
left: '50%',
height: `${BUTTON_HEIGHT}px`,
backgroundColor: COLOR_NONE,
width: '48px',
cursor: 'pointer',
willChange: 'bottom',
transition: linearTransition('bottom'),
transform: 'translateX(-50%)',
pointerEvents: this._collapsed ? 'none' : 'auto',
touchAction: 'none',
},
},
this.$system,
this.$pod
)
button.preventDefault('mousedown')
button.preventDefault('touchdown')
button.$element.setAttribute('dropTarget', 'true')
if (this._collapsed) {
unlisten_pointer = listen_pointer(root)
} else {
unlisten_pointer = listen_pointer(button)
}
const button_bar = new Div(
{
className: 'iounapp-keyboard-knob',
style: {
position: 'absolute',
bottom: '12px',
left: '50%',
backgroundColor: 'currentColor',
height: '1px',
width: '18px',
cursor: 'pointer',
transform: 'translateX(-50%)',
...userSelect('none'),
},
},
this.$system,
this.$pod
)
const $element = parentElement($system)
this.$element = $element
this.$slot = container.$slot
this.$subComponent = {
root,
button,
button_bar,
icon: _icon,
}
this.registerRoot(root)
root.registerParentRoot(container)
root.registerParentRoot(button)
button.registerParentRoot(button_bar)
root.registerParentRoot(_icon)
}
onPropChanged(prop: string, current: any): void {
if (prop === 'style') {
const { width, height } = this.$props
this._root.setProp('style', {
position: 'absolute',
left: `${this._x}px`,
top: `${this._y}px`,
width: this._collapsed ? `${COLLAPSED_WIDTH}px` : `${width}px`,
height: this._collapsed ? `${COLLAPSED_HEIGHT}px` : `${height}px`,
borderRadius: '3px',
// borderRadius: this._collapsed ? '50%' : '3px',
borderWidth: '1px',
borderStyle: 'solid',
borderColor: this._collapsed ? 'currentColor' : COLOR_NONE,
transition: `opacity ${ANIMATION_T_S}s linear`,
zIndex: `${this._z_index}`,
opacity: this._collapsed ? `${DIM_OPACITY}` : '0',
touchAction: 'none',
// contain: 'size layout style paint',
...current,
})
}
}
private _background_color = (): string => {
const { $theme } = this.$context
const backgroundColor = setAlpha(themeBackgroundColor($theme), 0.75)
return backgroundColor
}
private _refresh_color = (): void => {
if (this._collapsed) {
const backgroundColor = this._background_color()
mergeStyle(this._root, {
backgroundColor,
})
} else {
mergeStyle(this._root, {
backgroundColor: COLOR_NONE,
})
}
}
private _set_z_index = (zIndex: number) => {
this._z_index = zIndex
mergeStyle(this._root, {
zIndex: `${zIndex}`,
})
}
private _context_unlisten: Unlisten
private _z_index: number = MAX_Z_INDEX
private _message_id: Dict<boolean> = {}
private _clamp_x_y = () => {
const { width, height } = this.$props
const { $width, $height } = this.$context
const w = this._collapsed ? COLLAPSED_WIDTH : width
const h = this._collapsed ? COLLAPSED_HEIGHT : height
this._x = clamp({
a: this._x,
min: 0,
max: $width - w - 2,
}).a
this._y = clamp({
a: this._y,
min: 0,
max: $height - h - BUTTON_HEIGHT - 2,
}).a
}
onMount(): void {
this._context_unlisten = addListeners(this.$context, [
makeCustomListener('themechanged', () => {
this._refresh_color()
}),
makeResizeListener(() => {
this._clamp_x_y()
mergeStyle(this._root, {
left: `${this._x}px`,
top: `${this._y}px`,
})
}),
makeCustomListener('_iounapp_control_foreground', ({ message_id }) => {
if (!this._message_id[message_id]) {
this._set_z_index(this._z_index - 1)
} else {
delete this._message_id[message_id]
}
}),
])
this._refresh_color()
}
onUnmount(): void {
this._context_unlisten()
}
} | the_stack |
import {expect} from '@loopback/testlab';
import {
AsyncProxy,
Context,
createProxyWithInterceptors,
inject,
intercept,
Interceptor,
ResolutionSession,
ValueOrPromise,
} from '../..';
import {BindingScope} from '../../binding';
import {Provider} from '../../provider';
describe('Interception proxy', () => {
let ctx: Context;
beforeEach(givenContextAndEvents);
it('invokes async interceptors on an async method', async () => {
// Apply `log` to all methods on the class
@intercept(log)
class MyController {
// Apply multiple interceptors. The order of `log` will be preserved as it
// explicitly listed at method level
@intercept(convertName, log)
async greet(name: string) {
return `Hello, ${name}`;
}
}
const proxy = createProxyWithInterceptors(new MyController(), ctx);
const msg = await proxy.greet('John');
expect(msg).to.equal('Hello, JOHN');
expect(events).to.eql([
'convertName: before-greet',
'log: before-greet',
'log: after-greet',
'convertName: after-greet',
]);
});
it('creates a proxy that converts sync method to be async', async () => {
// Apply `log` to all methods on the class
@intercept(log)
class MyController {
// Apply multiple interceptors. The order of `log` will be preserved as it
// explicitly listed at method level
@intercept(convertName, log)
greet(name: string) {
return `Hello, ${name}`;
}
}
const proxy = createProxyWithInterceptors(new MyController(), ctx);
const msg = await proxy.greet('John');
expect(msg).to.equal('Hello, JOHN');
expect(events).to.eql([
'convertName: before-greet',
'log: before-greet',
'log: after-greet',
'convertName: after-greet',
]);
// Make sure `greet` always return Promise now
expect(proxy.greet('Jane')).to.be.instanceOf(Promise);
});
it('creates async methods for the proxy', async () => {
class MyController {
name: string;
greet(name: string): string {
return `Hello, ${name}`;
}
async hello(name: string) {
return `Hello, ${name}`;
}
}
interface ExpectedAsyncProxyForMyController {
name: string;
greet(name: string): ValueOrPromise<string>; // the return type becomes `Promise<string>`
hello(name: string): Promise<string>; // the same as MyController
}
const proxy = createProxyWithInterceptors(new MyController(), ctx);
const greeting = await proxy.greet('John');
expect(greeting).to.eql('Hello, John');
// Enforce compile time check to ensure the AsyncProxy typing works for TS
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const check: ExpectedAsyncProxyForMyController = proxy;
});
it('invokes interceptors on a static method', async () => {
// Apply `log` to all methods on the class
@intercept(log)
class MyController {
// The class level `log` will be applied
static greetStatic(name: string) {
return `Hello, ${name}`;
}
}
ctx.bind('name').to('John');
const proxy = createProxyWithInterceptors(MyController, ctx);
const msg = await proxy.greetStatic('John');
expect(msg).to.equal('Hello, John');
expect(events).to.eql([
'log: before-greetStatic',
'log: after-greetStatic',
]);
});
it('accesses properties on the proxy', () => {
class MyController {
constructor(public prefix: string) {}
greet() {
return `${this.prefix}: Hello`;
}
}
const proxy = createProxyWithInterceptors(new MyController('abc'), ctx);
expect(proxy.prefix).to.eql('abc');
proxy.prefix = 'xyz';
expect(proxy.prefix).to.eql('xyz');
});
it('accesses static properties on the proxy', () => {
class MyController {
static count = 0;
}
const proxyForClass = createProxyWithInterceptors(MyController, ctx);
expect(proxyForClass.count).to.eql(0);
proxyForClass.count = 3;
expect(proxyForClass.count).to.eql(3);
});
it('supports asProxyWithInterceptors resolution option', async () => {
// Apply `log` to all methods on the class
@intercept(log)
class MyController {
// Apply multiple interceptors. The order of `log` will be preserved as it
// explicitly listed at method level
@intercept(convertName, log)
async greet(name: string) {
return `Hello, ${name}`;
}
}
ctx.bind('my-controller').toClass(MyController);
const proxy = await ctx.get<MyController>('my-controller', {
asProxyWithInterceptors: true,
});
const msg = await proxy!.greet('John');
expect(msg).to.equal('Hello, JOHN');
expect(events).to.eql([
'convertName: before-greet',
'log: [my-controller] before-greet',
'log: [my-controller] after-greet',
'convertName: after-greet',
]);
});
it('supports asProxyWithInterceptors resolution option for singletons', async () => {
// Apply `log` to all methods on the class
@intercept(log)
class MyController {
// Apply multiple interceptors. The order of `log` will be preserved as it
// explicitly listed at method level
@intercept(convertName, log)
async greet(name: string) {
return `Hello, ${name}`;
}
}
ctx
.bind('my-controller')
.toClass(MyController)
.inScope(BindingScope.SINGLETON);
// Proxy version
let proxy = await ctx.get<MyController>('my-controller', {
asProxyWithInterceptors: true,
});
let msg = await proxy!.greet('John');
expect(msg).to.equal('Hello, JOHN');
// Non proxy version
const inst = await ctx.get<MyController>('my-controller');
msg = await inst.greet('John');
expect(msg).to.equal('Hello, John');
// Try the proxy again
proxy = await ctx.get<MyController>('my-controller', {
asProxyWithInterceptors: true,
});
msg = await proxy!.greet('John');
expect(msg).to.equal('Hello, JOHN');
});
it('supports asProxyWithInterceptors resolution option for dynamic value', async () => {
// Apply `log` to all methods on the class
@intercept(log)
class MyController {
// Apply multiple interceptors. The order of `log` will be preserved as it
// explicitly listed at method level
@intercept(convertName, log)
async greet(name: string) {
return `Hello, ${name}`;
}
}
ctx.bind('my-controller').toDynamicValue(() => new MyController());
const proxy = await ctx.get<MyController>('my-controller', {
asProxyWithInterceptors: true,
});
const msg = await proxy!.greet('John');
expect(msg).to.equal('Hello, JOHN');
expect(events).to.eql([
'convertName: before-greet',
'log: [my-controller] before-greet',
'log: [my-controller] after-greet',
'convertName: after-greet',
]);
});
it('supports asProxyWithInterceptors resolution option for provider', async () => {
// Apply `log` to all methods on the class
@intercept(log)
class MyController {
// Apply multiple interceptors. The order of `log` will be preserved as it
// explicitly listed at method level
@intercept(convertName, log)
async greet(name: string) {
return `Hello, ${name}`;
}
}
class MyControllerProvider implements Provider<MyController> {
value() {
return new MyController();
}
}
ctx.bind('my-controller').toProvider(MyControllerProvider);
const proxy = await ctx.get<MyController>('my-controller', {
asProxyWithInterceptors: true,
});
const msg = await proxy!.greet('John');
expect(msg).to.equal('Hello, JOHN');
expect(events).to.eql([
'convertName: before-greet',
'log: [my-controller] before-greet',
'log: [my-controller] after-greet',
'convertName: after-greet',
]);
});
it('allows asProxyWithInterceptors for non-object value', async () => {
ctx.bind('my-value').toDynamicValue(() => 'my-value');
const value = await ctx.get<string>('my-value', {
asProxyWithInterceptors: true,
});
expect(value).to.eql('my-value');
});
it('supports asProxyWithInterceptors resolution option for @inject', async () => {
// Apply `log` to all methods on the class
@intercept(log)
class MyController {
// Apply multiple interceptors. The order of `log` will be preserved as it
// explicitly listed at method level
@intercept(convertName, log)
async greet(name: string) {
return `Hello, ${name}`;
}
}
class DummyController {
constructor(
@inject('my-controller', {asProxyWithInterceptors: true})
public readonly myController: AsyncProxy<MyController>,
) {}
}
ctx.bind('my-controller').toClass(MyController);
ctx.bind('dummy-controller').toClass(DummyController);
const dummyController = await ctx.get<DummyController>('dummy-controller');
const msg = await dummyController.myController.greet('John');
expect(msg).to.equal('Hello, JOHN');
expect(events).to.eql([
'convertName: before-greet',
'log: [dummy-controller --> my-controller] before-greet',
'log: [dummy-controller --> my-controller] after-greet',
'convertName: after-greet',
]);
});
let events: string[];
const log: Interceptor = async (invocationCtx, next) => {
let source: string;
if (invocationCtx.source instanceof ResolutionSession) {
source = `[${invocationCtx.source.getBindingPath()}] `;
} else {
source = invocationCtx.source ? `[${invocationCtx.source}] ` : '';
}
events.push(`log: ${source}before-${invocationCtx.methodName}`);
const result = await next();
events.push(`log: ${source}after-${invocationCtx.methodName}`);
return result;
};
// An interceptor to convert the 1st arg to upper case
const convertName: Interceptor = async (invocationCtx, next) => {
events.push('convertName: before-' + invocationCtx.methodName);
invocationCtx.args[0] = (invocationCtx.args[0] as string).toUpperCase();
const result = await next();
events.push('convertName: after-' + invocationCtx.methodName);
return result;
};
function givenContextAndEvents() {
ctx = new Context();
events = [];
}
}); | the_stack |
const copy = require('clipboard-copy');
// eslint-disable-next-line @typescript-eslint/no-var-requires,import/order
const JsDiff = require('diff/dist/diff.min.js');
import '@gravitee/ui-components/wc/gv-policy-studio';
import '@gravitee/ui-components/wc/gv-switch';
import '@gravitee/ui-components/wc/gv-popover';
import * as _ from 'lodash';
import * as angular from 'angular';
import { StateService } from '@uirouter/core';
import { propertyProviders } from '../../design/design/design.controller';
enum Modes {
Diff = 'Diff',
DiffWithMaster = 'DiffWithMaster',
Payload = 'Payload',
Design = 'Design',
}
class ApiHistoryController {
public modes = Modes;
public modeOptions: any;
private studio: any;
private mode: string;
private api: any;
private events: any;
private eventsSelected: any;
private eventsTimeline: any;
private eventsToCompare: any;
private eventSelected: any;
private eventToCompareRequired: boolean;
private eventTypes: string;
private apisSelected: any;
private eventSelectedPayloadDefinition: any;
private eventSelectedPayload: any;
private right: any;
private left: any;
private added: number;
private removed: number;
constructor(
private $mdDialog: ng.material.IDialogService,
private $scope: any,
private $rootScope: ng.IRootScopeService,
private $state: StateService,
private ApiService,
private NotificationService,
private resolvedEvents,
private PolicyService,
private ResourceService,
private FlowService,
) {
'ngInject';
this.api = JSON.parse(angular.toJson(_.cloneDeep(this.$scope.$parent.apiCtrl.api)));
this.events = resolvedEvents.data;
this.eventsSelected = [];
this.eventsTimeline = [];
this.eventsToCompare = [];
this.eventSelected = {};
this.mode = this.hasDesign() ? Modes.Design : Modes.Payload;
this.eventToCompareRequired = false;
this.eventTypes = 'PUBLISH_API';
this.modeOptions = [
{ title: Modes.Design, id: Modes.Design },
{ title: Modes.Payload, id: Modes.Payload },
];
}
$onInit() {
this.studio = document.querySelector('gv-policy-studio');
if (this.hasDesign()) {
Promise.all([
this.PolicyService.list(true, true),
this.ResourceService.list(true, true),
this.ApiService.getFlowSchemaForm(),
this.FlowService.getConfigurationSchema(),
]).then(([policies, resources, flowSchema, configurationSchema]) => {
this.studio.policies = policies.data;
this.studio.resourceTypes = resources.data;
this.studio.flowSchema = flowSchema.data;
this.studio.configurationSchema = configurationSchema.data;
this.studio.propertyProviders = propertyProviders;
});
}
this.init();
this.initTimeline(this.events);
}
init() {
this.$scope.$parent.apiCtrl.checkAPISynchronization(this.api);
this.$scope.$on('apiChangeSuccess', (event, args) => {
if (this.$state.current.name.endsWith('history')) {
// reload API
this.api = JSON.parse(angular.toJson(_.cloneDeep(args.api)));
// reload API events
this.ApiService.getApiEvents(this.api.id, this.eventTypes).then((response) => {
this.events = response.data;
this.reloadEventsTimeline(this.events);
});
}
});
this.$scope.$on('checkAPISynchronizationSucceed', () => {
this.reloadEventsTimeline(this.events);
});
}
setEventToStudio(eventTimeline, api) {
this.studio.definition = {
version: api.version,
flows: api.flows != null ? api.flows : [],
resources: api.resources,
plans: api.plans != null ? api.plans : [],
properties: api.properties,
'flow-mode': api.flow_mode,
};
this.studio.services = api.services || {};
}
initTimeline(events) {
this.eventsTimeline = events.map((event) => ({
event: event,
badgeClass: 'info',
badgeIconClass: 'action:check_circle',
title: event.type,
when: event.created_at,
user: event.user,
deploymentLabel: event.properties.deployment_label,
deploymentNumber: event.properties.deployment_number,
}));
}
selectEvent(_eventTimeline) {
if (this.eventToCompareRequired) {
this.diff(_eventTimeline);
this.selectEventToCompare(_eventTimeline);
} else {
this.mode = this.hasDesign() ? Modes.Design : Modes.Payload;
this.apisSelected = [];
this.eventsSelected = [];
this.clearDataToCompare();
const idx = this.eventsSelected.indexOf(_eventTimeline);
if (idx > -1) {
this.eventsSelected.splice(idx, 1);
} else {
this.eventsSelected.push(_eventTimeline);
}
if (this.eventsSelected.length > 0) {
const eventSelected = this.eventsSelected[0];
this.eventSelectedPayload = JSON.parse(eventSelected.event.payload);
this.eventSelectedPayloadDefinition = this.reorganizeEvent(this.eventSelectedPayload);
this.setEventToStudio(_eventTimeline, this.eventSelectedPayloadDefinition);
}
}
}
selectEventToCompare(_eventTimeline) {
this.eventsToCompare.push(_eventTimeline);
}
clearDataToCompare() {
this.eventsToCompare = [];
}
clearDataSelected() {
this.eventsSelected = [];
}
isEventSelectedForComparaison(_event) {
return this.eventsToCompare.indexOf(_event) > -1;
}
diffWithMaster() {
if (this.mode === Modes.DiffWithMaster) {
this.mode = null;
this.mode = Modes.Payload;
this.clearDataToCompare();
} else {
this.mode = null;
this.mode = Modes.DiffWithMaster;
this.eventToCompareRequired = false;
this.clearDataToCompare();
const latestEvent = this.events[0];
if (this.eventsSelected.length > 0) {
if (this.eventsSelected[0].isCurrentAPI) {
this.right = this.reorganizeEvent(JSON.parse(this.eventsSelected[0].event.payload));
this.left = this.reorganizeEvent(JSON.parse(latestEvent.payload));
} else {
this.left = this.reorganizeEvent(JSON.parse(this.eventsSelected[0].event.payload));
this.right = this.reorganizeEvent(JSON.parse(latestEvent.payload));
}
this.updateDiffStats();
}
}
}
computeLines(part) {
if (part && part.value) {
return part.value.split('\n').length - 1;
}
return 0;
}
updateDiffStats() {
this.added = 0;
this.removed = 0;
const diff = JsDiff.diffJson(this.left, this.right);
diff.forEach((part) => {
if (part.added) {
this.added += this.computeLines(part);
} else if (part.removed) {
this.removed += this.computeLines(part);
}
});
}
hasDiff() {
return this.mode === this.modes.Diff || this.mode === this.modes.DiffWithMaster;
}
enableDiff() {
this.clearDataToCompare();
this.eventToCompareRequired = true;
}
disableDiff() {
this.eventToCompareRequired = false;
}
hasDesign() {
return this.api != null && this.api.gravitee != null && this.api.gravitee === '2.0.0';
}
copyToClipboard(event) {
copy(JSON.stringify(this.eventSelectedPayloadDefinition, null, 2));
const clipboardIcon = event.target.icon;
event.target.icon = 'communication:clipboard-check';
setTimeout(() => {
event.target.icon = clipboardIcon;
}, 1000);
}
toggleMode({ detail }) {
if (detail === false) {
this.clearDataToCompare();
this.eventToCompareRequired = false;
this.mode = Modes.Design;
} else {
this.mode = Modes.Payload;
}
}
diff(eventTimeline) {
this.mode = Modes.Diff;
if (this.eventsSelected.length > 0) {
if (eventTimeline.isCurrentAPI) {
this.left = this.reorganizeEvent(JSON.parse(this.eventsSelected[0].event.payload));
this.right = this.reorganizeEvent(JSON.parse(eventTimeline.event.payload));
} else {
const event1UpdatedAt = eventTimeline.event.updated_at;
const event2UpdatedAt = this.eventsSelected[0].event.updated_at;
const eventSelected = this.reorganizeEvent(JSON.parse(this.eventsSelected[0].event.payload));
if (event1UpdatedAt > event2UpdatedAt) {
this.left = eventSelected;
this.right = this.reorganizeEvent(JSON.parse(eventTimeline.event.payload));
} else {
this.left = this.reorganizeEvent(JSON.parse(eventTimeline.event.payload));
this.right = eventSelected;
}
}
this.updateDiffStats();
}
this.disableDiff();
}
isEventSelected(_eventTimeline) {
return this.eventsSelected.indexOf(_eventTimeline) > -1;
}
rollback(_apiPayload) {
const _apiDefinition = JSON.parse(_apiPayload.definition);
delete _apiDefinition.id;
delete _apiDefinition.deployed_at;
_apiDefinition.description = _apiPayload.description;
_apiDefinition.visibility = _apiPayload.visibility;
this.ApiService.rollback(this.api.id, _apiDefinition).then(() => {
this.NotificationService.show('Api rollback !');
this.ApiService.get(this.api.id).then((response) => {
this.$rootScope.$broadcast('apiChangeSuccess', { api: response.data });
});
});
}
showRollbackAPIConfirm(ev, api) {
ev.stopPropagation();
this.$mdDialog
.show({
controller: 'DialogConfirmController',
controllerAs: 'ctrl',
template: require('../../../../components/dialog/confirm.dialog.html'),
clickOutsideToClose: true,
locals: {
title: 'Would you like to rollback your API?',
confirmButton: 'Rollback',
},
})
.then((response) => {
if (response) {
this.rollback(api);
}
});
}
stringifyCurrentApi() {
const payload = _.cloneDeep(this.api);
// Because server add "/" to virtual_hosts at deploy
payload.proxy.virtual_hosts = payload.proxy.virtual_hosts.map((host) => {
if (!host.path.endsWith('/')) {
host.path = `${host.path}/`;
}
return host;
});
delete payload.deployed_at;
delete payload.created_at;
delete payload.updated_at;
delete payload.visibility;
delete payload.state;
delete payload.permission;
delete payload.owner;
delete payload.picture_url;
delete payload.categories;
delete payload.groups;
delete payload.etag;
delete payload.context_path;
delete payload.disable_membership_notifications;
delete payload.labels;
delete payload.entrypoints;
delete payload.lifecycle_state;
delete payload.path_mappings;
delete payload.tags;
delete payload.workflow_state;
delete payload.response_templates;
return JSON.stringify({ definition: JSON.stringify(payload) });
}
reloadEventsTimeline(events) {
this.clearDataSelected();
this.initTimeline(events);
if (!this.$scope.$parent.apiCtrl.apiIsSynchronized && !this.$scope.$parent.apiCtrl.apiJustDeployed) {
this.eventsTimeline.unshift({
event: {
payload: this.stringifyCurrentApi(),
},
badgeClass: 'warning',
badgeIconClass: 'notification:sync',
title: 'TO_DEPLOY',
isCurrentAPI: true,
});
}
this.selectEvent(this.eventsTimeline[0]);
}
reorganizeEvent(_event) {
const eventPayloadDefinition = JSON.parse(_event.definition);
const reorganizedEvent = {
...eventPayloadDefinition,
name: eventPayloadDefinition.name,
version: eventPayloadDefinition.version,
description: _event.description != null ? _event.description : eventPayloadDefinition.description,
tags: eventPayloadDefinition.tags,
proxy: eventPayloadDefinition.proxy,
paths: eventPayloadDefinition.paths,
flows: eventPayloadDefinition.flows,
properties: eventPayloadDefinition.properties,
services: eventPayloadDefinition.services,
resources: eventPayloadDefinition.resources,
path_mappings: eventPayloadDefinition.path_mappings,
response_templates: eventPayloadDefinition.response_templates,
};
if (reorganizedEvent.flow_mode != null) {
reorganizedEvent.flow_mode = reorganizedEvent.flow_mode.toLowerCase();
}
return reorganizedEvent;
}
fetchPolicyDocumentation({ detail }) {
const policy = detail.policy;
this.PolicyService.getDocumentation(policy.id)
.then((response) => {
this.studio.documentation = { content: response.data, image: policy.icon, id: policy.id };
})
.catch(() => (this.studio.documentation = null));
}
fetchResourceDocumentation(event) {
const {
detail: { resourceType, target },
} = event;
this.ResourceService.getDocumentation(resourceType.id)
.then((response) => {
target.documentation = { content: response.data, image: resourceType.icon };
})
.catch(() => (target.documentation = null));
}
}
export default ApiHistoryController; | the_stack |
import d3 from "d3";
import isEqual from "lodash.isequal";
import * as React from "react";
import ReactDOM from "react-dom";
import AnimationCircle from "./AnimationCircle";
import ChartStripes from "./ChartStripes";
import Maths from "../../utils/Maths";
import TimeSeriesArea from "./TimeSeriesArea";
import TimeSeriesMouseOver from "./TimeSeriesMouseOver";
import ValueTypes from "../../constants/ValueTypes";
import Util from "../../utils/Util";
export default class TimeSeriesChart extends React.Component {
static defaultProps = {
axisConfiguration: {
x: {
showZeroTick: true,
},
},
margin: {
top: 10,
left: 45,
bottom: 25,
right: 5,
},
maxY: 10,
refreshRate: 0,
ticksY: 3,
y: "y",
yFormat: ValueTypes.PERCENTAGE,
};
clipPathID = `clip-${Util.uniqueID()}`;
maskID = `mask-${Util.uniqueID()}`;
getHeight = ({ height, margin }) => height - margin.top - margin.bottom;
getWidth = ({ margin, width }) => width - margin.left - margin.right;
getXScale(data = [], width, refreshRate) {
const length = data[0]?.values?.length ?? width;
const timeAgo = -(length - 1) * (refreshRate / 1000);
return d3.scale.linear().range([0, width]).domain([timeAgo, 0]);
}
formatXAxis = (d) => {
const hideMatch = this.props.axisConfiguration.x.hideMatch;
if (hideMatch && hideMatch.test(d.toString())) {
return "";
}
if (parseInt(Math.abs(d), 10) > 0) {
return `${d}s`;
}
return d;
};
componentDidMount() {
const props = this.props;
const height = this.getHeight(props);
const width = this.getWidth(props);
this.renderAxis(props, width, height);
this.createClipPath(width, height);
}
shouldComponentUpdate(nextProps) {
const props = this.props;
// The d3 axis helper requires a <g> element passed into do its work. This
// happens after mount and ends up keeping the axis code outside of react
// unfortunately.
// If non `data` props change then we need to update the whole graph
if (!isEqual(Util.omit(props, "data"), Util.omit(nextProps, "data"))) {
const height = this.getHeight(nextProps);
const width = this.getWidth(nextProps);
this.renderAxis(nextProps, width, height);
return true;
}
// This won't be scalable if we decide to stack graphs
const prevVal = props.data[0].values;
const nextVal = nextProps.data[0].values;
const prevY = prevVal.map((value) => value[props.y]);
const nextY = nextVal.map((value) => value[props.y]);
return !isEqual(prevY, nextY);
}
componentDidUpdate() {
const props = this.props;
const height = this.getHeight(props);
const width = this.getWidth(props);
this.updateClipPath(width, height);
}
createClipPath(width, height) {
// create clip path for areas and x-axis
d3.select(this.movingElsRef)
.append("defs")
.append("clipPath")
.attr("id", this.clipPathID)
.append("rect");
this.updateClipPath(width, height);
}
updateClipPath(width, height) {
d3.select("#" + this.clipPathID + " rect").attr({
width,
height,
});
}
getArea(y, xTimeScale, yScale, firstSuccessful) {
// We need firstSuccessful because if the current value is null,
// we want to make it equal to the most recent successful value in order to
// have a straight line on the graph.
const value = firstSuccessful[y] || 0;
let successfulValue = yScale(value);
return d3.svg
.area()
.x((d) => xTimeScale(d.date))
.y0(() => yScale(0))
.y1((d) => {
if (d[y] != null) {
successfulValue = yScale(d[y]);
}
return successfulValue;
})
.interpolate("monotone");
}
getValueLine(xTimeScale, yScale, firstSuccessful) {
// We need firstSuccessful because if the current value is null,
// we want to make it equal to the most recent successful value in order to
// have a straight line on the graph.
const y = this.props.y;
const value = firstSuccessful[y] || 0.1;
let successfulValue = yScale(value);
return d3.svg
.line()
.defined((d) => d[y] != null)
.x((d) => xTimeScale(d.date))
.y((d) => {
if (d[y] != null) {
successfulValue = yScale(d[y] || 0.1);
}
return successfulValue;
})
.interpolate("monotone");
}
getUnavailableLine(xTimeScale, yScale, firstSuccessful) {
// We need firstSuccessful because if the current value is null,
// we want to make it equal to the most recent successful value in order to
// have a straight line on the graph.
const y = this.props.y;
const value = firstSuccessful[y] || 0.1;
let successfulValue = yScale(value);
return d3.svg
.line()
.x((d) => xTimeScale(d.date))
.y((d) => {
if (d[y] != null) {
successfulValue = yScale(d[y] || 0.1);
}
return successfulValue;
})
.interpolate("monotone");
}
getXTickValues(xScale) {
const domain = xScale.domain();
const mean = Maths.mean(domain);
return [domain[0], mean, domain[domain.length - 1]];
}
getXTimeScale(data, width) {
let date = Date.now();
let dateDelta = Date.now();
const firstDataSet = data[0];
if (firstDataSet != null) {
const hiddenValuesCount = 1;
const values = firstDataSet.values;
// [first date, last date - 1]
// Restrict x domain to have one extra point outside of graph area,
// since we are animating the graph in from right
date = values[0].date;
dateDelta = values[values.length - 1 - hiddenValuesCount].date;
}
return d3.time.scale().range([0, width]).domain([date, dateDelta]);
}
getYScale(height, maxY) {
return (
d3.scale
.linear()
// give a little space in the top for the number
.range([height, 0])
.domain([0, maxY])
);
}
getYCaption(yFormat) {
if (yFormat === ValueTypes.PERCENTAGE) {
return "%";
}
return "";
}
formatYAxis(props) {
const { maxY, ticksY, yFormat } = props;
if (yFormat === ValueTypes.PERCENTAGE) {
const formatPercent = d3.scale
.linear()
.tickFormat(ticksY, ".0" + this.getYCaption(yFormat));
return (d) => (d >= maxY ? "100%" : formatPercent(d / maxY));
}
return (d) => (d >= maxY ? maxY : d);
}
renderAxis(props, width, height) {
const xScale = this.getXScale(props.data, width, props.refreshRate);
const yScale = this.getYScale(height, props.maxY);
const xAxis = d3.svg
.axis()
.scale(xScale)
.tickValues(this.getXTickValues(xScale))
.tickFormat(this.formatXAxis)
.orient("bottom");
d3.select(this.xAxisRef)
.interrupt()
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
const yAxis = d3.svg
.axis()
.scale(yScale)
.ticks(props.ticksY)
.tickFormat(this.formatYAxis(props))
.orient("left");
d3.select(this.yAxisRef).call(yAxis);
d3.select(this.gridRef).call(
d3.svg
.axis()
.scale(yScale)
.orient("left")
.ticks(props.ticksY)
.tickSize(-width, 0, 0)
.tickFormat("")
);
}
getTransitionTime(data) {
// look at the difference between the last and the third last point
// to calculate transition time
const l = data.length - 1;
return (data[l].date - data[l - 1].date) / 1;
}
/*
* Returns the x position of the data point that we are about to animate in
*/
getNextXPosition(values, xTimeScale, transitionTime) {
const firstDataSet = values[0];
let date = Date.now();
if (firstDataSet != null) {
date = firstDataSet.date;
}
// add transition time since we are moving towards new pos
return xTimeScale(date + transitionTime);
}
/*
* Returns the y position of the data point that we are about to animate in
*/
getNextYPosition(obj, y, yScale, height) {
const latestDataPoint = Util.last(obj.values);
// most recent y - height of chart
return yScale(latestDataPoint[y]) - height;
}
getAreaList(props, yScale, xTimeScale) {
const firstSuccess =
props.data[0].values.find(
(stateResource) => stateResource[props.y] != null
) || {};
// We need firstSuccess because if the current value is null,
// we want to make it equal to the most recent successful value in order to
// have a straight line on the graph.
const area = this.getArea(props.y, xTimeScale, yScale, firstSuccess);
const valueLine = this.getValueLine(xTimeScale, yScale, firstSuccess);
const unavailableLine = this.getUnavailableLine(
xTimeScale,
yScale,
firstSuccess
);
return props.data.map((stateResource, i) => {
const transitionTime = this.getTransitionTime(stateResource.values);
const nextY = this.getNextXPosition(
stateResource.values,
xTimeScale,
transitionTime
);
return (
<TimeSeriesArea
className={"path-color-" + stateResource.colorIndex}
key={i}
line={valueLine(stateResource.values)}
unavailableLine={unavailableLine(stateResource.values)}
path={area(stateResource.values)}
position={[-nextY, 0]}
transitionTime={transitionTime}
/>
);
});
}
getCircleList(props, yScale, width, height) {
return props.data.map((obj, i) => {
const transitionTime = this.getTransitionTime(obj.values);
const lastObj = Util.last(obj.values);
if (lastObj[props.y] == null) {
return null;
}
const nextX = this.getNextYPosition(obj, props.y, yScale, height);
return (
<AnimationCircle
className={"arc path-color-" + obj.colorIndex}
cx={width}
cy={height}
key={i}
position={[0, nextX]}
transitionTime={transitionTime}
/>
);
});
}
getBoundingBox(props) {
const margin = props.margin;
return () => {
const el = ReactDOM.findDOMNode(this);
const elPosition = el.getBoundingClientRect();
return {
top: elPosition.top + margin.top,
right: elPosition.left + props.width - margin.right,
bottom: elPosition.top + props.height - margin.bottom,
left: elPosition.left + margin.left,
};
};
}
addMouseHandler = (handleMouseMove, handleMouseOut) => {
const el = ReactDOM.findDOMNode(this);
el.addEventListener("mousemove", handleMouseMove);
el.addEventListener("mouseout", handleMouseOut);
};
removeMouseHandler = (handleMouseMove, handleMouseOut) => {
const el = ReactDOM.findDOMNode(this);
el.removeEventListener("mousemove", handleMouseMove);
el.removeEventListener("mouseout", handleMouseOut);
};
render() {
const {
data,
height,
margin,
maxY,
refreshRate,
width,
yFormat,
y,
} = this.props;
const stripeHeight = this.getHeight(this.props);
const stripeWidth = this.getWidth(this.props);
const xScale = this.getXScale(data, stripeWidth, refreshRate);
const xTimeScale = this.getXTimeScale(data, stripeWidth);
const yScale = this.getYScale(stripeHeight, maxY);
const clipPath = "url(#" + this.clipPathID + ")";
const maskID = this.maskID;
return (
<div className="timeseries-chart">
<svg height={height} width={width}>
<g transform={"translate(" + margin.left + "," + margin.top + ")"}>
<ChartStripes count={4} height={stripeHeight} width={stripeWidth} />
<g
className="bars grid-graph"
ref={(ref) => (this.gridRef = ref)}
/>
<g className="y axis" ref={(ref) => (this.yAxisRef = ref)} />
<g className="x axis" ref={(ref) => (this.xAxisRef = ref)} />
<TimeSeriesMouseOver
addMouseHandler={this.addMouseHandler}
data={this.props.data}
getBoundingBox={this.getBoundingBox(this.props)}
height={stripeHeight}
removeMouseHandler={this.removeMouseHandler}
width={stripeWidth}
xScale={xScale}
y={y}
yCaption={this.getYCaption(yFormat)}
yScale={yScale}
/>
</g>
</svg>
<svg
height={height}
width={width}
ref={(ref) => (this.movingElsRef = ref)}
className="moving-elements"
>
<g transform={"translate(" + margin.left + "," + margin.top + ")"}>
<g mask={`url(#${maskID})`} clipPath={clipPath}>
{this.getAreaList(this.props, yScale, xTimeScale)}
</g>
{this.getCircleList(this.props, yScale, stripeWidth, stripeHeight)}
</g>
</svg>
</div>
);
}
} | the_stack |
import {
I,
err,
genSource,
queryTypes,
resultTypes,
version as versionLib,
bitHas,
bitSet,
makeSubGroup,
} from '@statecraft/core'
import {
TransactionOptionCode,
Database,
// StreamingMode,
keySelector
} from 'foundationdb'
import msgpack from 'msgpack-lite'
import assert from 'assert'
// import debugLib from 'debug'
const fieldOps = resultTypes[I.ResultType.Single]
// All system-managed keys are at 0x00___.
// For conflicts we want that if two clients both submit operations with non-
// overlapping conflict keys, we want the two operations to not conflict with
// one another. This gives us better throughput. To make that happen, we're
// using versionstamps. The mutation operations themselves will only conflict
// on the keys themselves, not the version. But we also write to a version
// field because we need to be able to watch on a single key to find out about
// updates.
// Statecraft manages anything starting in \0x00 in the keyspace. We could
// instead prefix all content. Ideally, SC would create two directories with
// the directory layer, one for content and the other for configuration. But
// that has to wait for node-foundationdb to implement directories.
// Issue: https://github.com/josephg/node-foundationdb/issues/12
// Note as well that FDB versionstamps are 10 byte big endian values. We're
// using & passing them throughout the system as binary values because JS
// doesn't support integers bigger than 53 bits, let alone 80 bits.
const CONFIG_KEY = Buffer.from('\x00config', 'ascii')
// Using a single key like this will cause thrashing on a single node in the
// FDB cluster, but its somewhat unavoidable given the design. A different
// approach would be to make multiple sources backed by the same FDB store;
// but you can kind of already do that by just making multiple fdb client
// instances and glueing them together with router.
const VERSION_KEY = Buffer.from('\x00v', 'ascii')
const OP_PREFIX = Buffer.from('\x00op', 'ascii')
// Remove this when porting this code to the directory layer.
const START_KEY = Buffer.from('\x01', 'ascii')
const END_KEY = Buffer.from('\xff', 'ascii')
// const NULL_VERSION = new Uint8Array(10) //Buffer.alloc(10)
const NULL_VERSION = Buffer.alloc(10)
// const END_VERSION = (new Uint8Array(10)).fill(0xff)//Buffer.alloc(10, 0xff)
const END_VERSION = Buffer.alloc(10, 0xff)
// const debug = debugLib('statecraft')
// let running = 0
// setInterval(() => console.log('running', running), 1000).unref()
type Config = {
sc_ver: number,
source: string
}
type OpEntry = [
[I.Key, I.Op<any>][],
I.Metadata
]
// I'm using a decoder because otherwise there's no good way to read
// stamp/value pairs out of ranges.
const unpackVersion = (data: Buffer): [Buffer, any] => [
data.slice(0, 10),
data.length > 10 ? msgpack.decode(data.slice(10)) : undefined
]
const max = (a: Buffer, b: Buffer) => Buffer.compare(a, b) > 0 ? a : b
const min = (a: Buffer, b: Buffer) => Buffer.compare(a, b) > 0 ? b : a
const clamp = (x: Buffer, low: Buffer, high: Buffer) => min(max(x, low), high)
const staticKStoFDBSel = ({k, isAfter}: I.StaticKeySelector) => (
// isAfter ? keySelector.firstGreaterThan(k) : keySelector.firstGreaterOrEqual(k)
keySelector(clamp(Buffer.from(k, 'utf8'), START_KEY, END_KEY), isAfter, 1)
)
const kStoFDBSel = ({k, isAfter, offset}: I.KeySelector) => (
keySelector(clamp(Buffer.from(k, 'utf8'), START_KEY, END_KEY), isAfter, (offset || 0) + 1)
)
const capabilities = {
queryTypes: bitSet(I.QueryType.AllKV, I.QueryType.KV, I.QueryType.StaticRange, I.QueryType.Range),
mutationTypes: bitSet(I.ResultType.KV),
}
/**
* This function constructs a statecraft store which wraps a foundationdb
* database.
*
* The foundationdb database must be initialized by the user before calling this
* and passed in as an argument here. See the README file or the playground file
* for usage examples.
*
* Note that this library will use the passed foundationdb database reference
* directly. You probably want to prefix your foundationdb instance before
* passing it in here. If you don't do that, we'll effectively take ownership of
* the entire foundationdb keyspace.
*
* Eg: `fdbStore(fdb.openSync().at('my_statecraft_data'))`
*
* @param db The foundationdb database object.
*/
export default async function fdbStore<Val>(rawDb: Database): Promise<I.Store<Val>> {
// Does it make sense to prefix like this? Once the directory layer is in,
// we'll use that instead.
const db = rawDb.withKeyEncoding().withValueEncoding({
pack: msgpack.encode,
// Only needed pre node-foundationdb 0.9.0
unpack: (buf) => buf.length === 0 ? undefined : msgpack.decode(buf),
})
const opDb = rawDb.at(OP_PREFIX).withValueEncoding({
pack: msgpack.encode,
unpack: (buf) => msgpack.decode(buf) as OpEntry
})
// First we need to get the sc_ver and source
const source = await db.doTn(async tn => {
const config = await tn.get(CONFIG_KEY) as Config | null
if (config == null) {
// debug('Database was created - no config!')
const source = genSource()
tn.set(CONFIG_KEY, {sc_ver: 1, source})
// This shouldn't be necessary - but it simplifies the watch logic below.
tn.setVersionstampPrefixedValue(VERSION_KEY)
return source
} else {
const {sc_ver, source:dbSource} = config
assert(sc_ver === 1, 'LDMB database was set up using invalid or old statecraft version.')
return dbSource as string
}
})
// Could fetch this in the config txn above.
let v0 = await rawDb.get(VERSION_KEY)
// TODO: Consider implementing a base version so we can prune old operations
let closed = false
let cancelWatch: null | (() => void) = null
// let mid = 0
const fetch: I.FetchFn<Val> = async (query, opts = {}) => {
if (!bitHas(capabilities.queryTypes, query.type)) throw new err.UnsupportedTypeError(`${query.type} not supported by lmdb store`)
const qops = queryTypes[query.type]
let bakedQuery: I.Query | undefined
let maxVersion: Uint8Array | null = null
let results: I.ResultData<Val>
const vs = await rawDb.doTn(async rawTn => {
// This could be way cleaner.
const tn = rawTn.scopedTo(rawDb.withValueEncoding({
pack() {throw Error('Cannot write')},
unpack: unpackVersion
}))
switch (query.type) {
case I.QueryType.KV: {
results = new Map<I.Key, Val>()
await Promise.all(Array.from(query.q).map(async k => {
const result = await tn.get(k)
if (result) {
const [stamp, value] = result
if (value != null) results.set(k, opts.noDocs ? 1 : value)
maxVersion = maxVersion ? versionLib.vMax(maxVersion, stamp) : stamp
}
}))
break
}
case I.QueryType.AllKV: {
// TODO: Make this work with larger databases (>5mb). Currently
// this is trying to fetch the whole db contents using a single
// txn, which will cause problems if the database is nontrivial.
// There's a few strategies we could implement here:
//
// - Lean on fdb's MVCC implementation and create a series of
// transactions at the same version
// - Use a series of transactions at incrementing versions, then
// fetch all the operations in the range and run catchup on any
// old data that was returned
// - Implement maxDocs and force the client to implement the
// iterative retry logic
// Whatever we do should also work on static ranges.
const resultsList = await tn.getRangeAll(START_KEY, END_KEY)
results = new Map<I.Key, Val>()
for (const [kbuf, [stamp, value]] of resultsList) {
results.set(kbuf.toString('utf8'), opts.noDocs ? 1 : value)
maxVersion = maxVersion ? versionLib.vMax(maxVersion, stamp) : stamp
}
break
}
case I.QueryType.StaticRange: {
// const q = query.q as I.RangeQuery
results = await Promise.all(query.q.map(async ({low, high, reverse}) => {
// This is so clean. Its almost like I designed statecraft with
// foundationdb in mind... ;)
return (await tn.getRangeAll(staticKStoFDBSel(low), staticKStoFDBSel(high), {reverse: reverse}))
.map(([kbuf, [stamp, value]]) => {
maxVersion = maxVersion ? versionLib.vMax(maxVersion, stamp) : stamp
return [kbuf.toString('utf8'), opts.noDocs ? 1 : value] as [I.Key, Val]
}) //.filter(([k, v]) => v != undefined)
}))
break
}
case I.QueryType.Range: {
// There's a bunch of ways I could write this, but a bit of copy + pasta is the simplest.
// bakedQuery = {type: 'static range', q:[]}
const baked: I.StaticRangeQuery = []
results = await Promise.all(query.q.map(async ({low, high, reverse, limit}, i) => {
// console.log('range results', (await tn.getRangeAll(kStoFDBSel(low), kStoFDBSel(high), {reverse: reverse, limit: limit})).length)
const vals = (await tn.getRangeAll(kStoFDBSel(low), kStoFDBSel(high), {reverse: reverse, limit: limit}))
.map(([kbuf, [stamp, value]]) => {
maxVersion = maxVersion ? versionLib.vMax(maxVersion, stamp) : stamp
// console.log('arr entry', [kbuf.toString('utf8'), value])
return [kbuf.toString('utf8'), opts.noDocs ? 1 : value] as [I.Key, Val]
}) //.filter(([k, v]) => v != undefined)
// Note: These aren't tested thoroughly yet. Probably a bit broken.
baked[i] = vals.length ? {
low: {k: reverse ? vals[vals.length-1][0] : vals[0][0], isAfter: !!reverse},
high: {k: reverse ? vals[0][0] : vals[vals.length-1][0], isAfter: !reverse},
reverse
} : {
low: {k: low.k, isAfter: low.isAfter},
high: {k: low.k, isAfter: low.isAfter},
reverse
}
// console.log('range ->', vals)
return vals
}))
// console.log('range query ->', results)
bakedQuery = {type: I.QueryType.StaticRange, q: baked}
break
}
default: throw new err.UnsupportedTypeError(`${query.type} not supported by fdb store`)
}
return rawTn.getVersionstampPrefixedValue(VERSION_KEY)
})
return {
bakedQuery,
results,
versions: [{
from: maxVersion || NULL_VERSION,
to: vs ? vs.stamp : NULL_VERSION
}]
}
}
const getOps: I.GetOpsFn<Val> = async (query, versions, opts = {}) => {
const qtype = query.type
const qops = queryTypes[qtype]
const limitOps = opts.limitOps || -1
const vOut: I.FullVersionRange = []
const reqV = versions[0]
if (reqV == null) return {ops: [], versions: []}
let {from, to} = reqV
if (from.length === 0) from = NULL_VERSION
if (to.length === 0) to = END_VERSION
if (typeof from === 'number' || typeof to === 'number') throw Error('Invalid version request')
if (versionLib.vCmp(from, to) > 0) return {ops: [], versions: []}
// TODO: This will have some natural limit based on how big a
// transaction can be. Split this up across multiple transactions using
// getRangeBatch (we don't need write conflicts or any of that jazz).
const ops = await opDb.getRangeAll(
keySelector.firstGreaterThan(Buffer.from(from)),
keySelector.firstGreaterThan(Buffer.from(to))
)
const result = [] as I.TxnWithMeta<Val>[]
for (let i = 0; i < ops.length; i++) {
const [version, [txnArr, meta]] = ops[i]
// console.log('ops', version, txnArr, meta)
const txn = qops.adaptTxn(new Map<I.Key, I.Op<Val>>(txnArr), query.q)
// console.log('txn', txn)
if (txn != null) result.push({txn, meta, versions: [version]})
}
return {
ops: result,
versions: [{
from,
to: ops.length ? ops[ops.length-1][0] : from
}]
}
}
const subGroup = makeSubGroup({initialVersion: [v0!], fetch, getOps})
const store: I.Store<Val> = {
storeInfo: {
uid: `fdb(${source})`, // TODO: Consider passing the database prefix (or something like it) in here.
sources: [source],
capabilities
},
async mutate(type, _txn, versions, opts = {}) {
if (type !== I.ResultType.KV) throw new err.UnsupportedTypeError()
const txn = _txn as I.KVTxn<Val>
// const m = mid++
// debug('mutate', m, versions && versions[source], txn)
// Could be easily, just haven't done it.
if (opts.conflictKeys && opts.conflictKeys.length) throw Error('conflictKeys not implemented')
// const expectedVersion = (versions && versions[source] != null) ? versions[source] : version
const v = versions && versions[0]
if (typeof v === 'number') throw Error('Got invalid numeric version')
if (v) assert.strictEqual(v.byteLength, 10, 'Version invalid - wrong length')
const vs = await (await db.doTn(async tn => {
await Promise.all(Array.from(txn.entries()).map(async ([k, op]) => {
const oldValue = await tn.getVersionstampPrefixedValue(k)
// console.log(m, 'oldvalue stamp', oldValue && oldValue.stamp, 'v', v, 'conflict', (oldValue && v) ? vCmp(oldValue.stamp, v) > 0 : 'no compare')
if (v != null && oldValue != null && versionLib.vCmp(oldValue.stamp, v) > 0) {
// console.log('throwing write conflict', m)
throw new err.WriteConflictError('Write conflict in key ' + k)
}
const newVal = fieldOps.apply(oldValue ? oldValue.value : null, op)
// I'm leaving an empty entry in the lmdb database even if newData is
// null so fetch will correctly report last modified versions.
// This can be stripped with a periodically updating baseVersion if
// thats useful.
// if (newVal === undefined) tn.clear(k)
// console.log(m, 'setting', k, newVal)
tn.setVersionstampPrefixedValue(k, newVal)
}))
// Add the operation to the oplog
tn.setVersionstampSuffixedKey(OP_PREFIX, [Array.from(txn), opts.meta || {}])
// Bump the global version. We don't want to conflict here. We really
// sort of want to set it to MAX(current value, new commit) but the
// new version will always be higher than the old anyway so it doesn't
// matter.
tn.setOption(TransactionOptionCode.NextWriteNoWriteConflictRange)
tn.setVersionstampPrefixedValue(VERSION_KEY)
return tn.getVersionstamp()
})).promise
// debug('mutate complete', m)
// console.log('mutate -> resulting version', vs)
return [vs]
},
fetch,
getOps,
subscribe: subGroup.create.bind(subGroup),
close() {
closed = true
cancelWatch && cancelWatch()
// TODO: And close the database properly.
},
}
const opwatcher = async () => {
try {
// running++
// await new Promise(resolve => setTimeout(resolve, 1000))
if (v0 == null) throw new Error('Inconsistent state - version key missing')
// console.log('initial version', v0)
while (!closed) {
const watch = await rawDb.getAndWatch(VERSION_KEY)
const {value: version, promise} = watch
if (version != null && !v0.equals(version)) {
// TODO: Probably should chunk this?
const ops = await opDb.getRangeAll(
keySelector.firstGreaterThan(v0),
keySelector.firstGreaterThan(version!)
)
// console.log('version', v0, version, ops)
const txns: I.TxnWithMeta<Val>[] = []
for (let i = 0; i < ops.length; i++) {
const [version, v] = ops[i]
const [op, meta] = v
// console.log('v', v0, version)
assert(versionLib.vCmp(v0, version) < 0)
txns.push({
txn: new Map(op),
meta,
versions: [version],
})
}
// console.log('subgroup', v0, '->', version, ops)
subGroup.onOp(0, v0, txns)
v0 = version
}
// If the store was closed between the top of the loop and this point
// (async, remember!) then we explicitly close now. We need to cancel
// the watch immediately because otherwise the node event loop would
// be held open.
if (closed) { watch.cancel(); break }
else cancelWatch = watch.cancel.bind(watch)
// This promise should resolve to false when the watch was cancelled.
// TODO: Check what happens when the database connection is
// interrupted.
await promise
}
} catch (e) {
console.error('Unhandled error in FDB operation watch process', e.message, e.stack)
// Throw to the global exception handler, which will normally crash the process.
process.emit('uncaughtException', e)
}
// running--
}
opwatcher()
return store
}
// Fix commonjs imports
fdbStore.default = fdbStore
module.exports = fdbStore | the_stack |
import * as chai from "chai";
import "url-search-params-polyfill";
import { MindSphereSdk } from "../src";
import { DeviceConfigurationModels } from "../src/api/sdk/open-edge/open-edge-models";
import { decrypt, loadAuth } from "../src/api/utils";
import { setupDeviceTestStructure, tearDownDeviceTestStructure } from "./test-device-setup-utils";
import { getPasskeyForUnitTest, sleep } from "./test-utils";
chai.should();
const timeOffset = new Date().getTime();
describe("[SDK] DeviceManagementClient.DeviceConfiguration", () => {
const auth = loadAuth();
const sdk = new MindSphereSdk({
...auth,
basicAuth: decrypt(auth, getPasskeyForUnitTest()),
});
const deviceConfigurationClient = sdk.GetDeviceConfigurationClient();
const tenant = sdk.GetTenant();
const configFileTemplate = {
path: `/${tenant}/TEST/${timeOffset}/TEST_DEVICE_CONFIGURATION.json`,
description: `Configuration for test the API. generated by ${tenant} on ${new Date()}`,
};
const testConfigurationTask = {
files: [
{
name: configFileTemplate.path,
uri: `https://testuri.com/${tenant}/TEST/${timeOffset}/TEST_DEVICE_CONFIGURATION.json`,
checksum: "sha1:cf23...",
},
],
customData: {
name: "TEST_DEVICE_CONFIGURATION",
sampleKey1: "sampleValue1",
sampleKey2: "sampleValue2",
created: timeOffset,
},
target: {
address: "XTOOLS",
},
};
const testConfigurationState = {
state: DeviceConfigurationModels.Updatetask.StateEnum.CONFIGURING,
progress: 0,
message: "Configuring.",
details: {},
};
let deviceTypeId = "aee2e37f-f562-4ed6-b90a-c43208dc054a";
let assetTypeId = `${tenant}.UnitTestDeviceAssetType`;
let assetId = "";
let gFolderid = "";
let deviceId = "";
let configTaskId = "";
let globalFileId = "";
let globalFilePath = "";
before(async () => {
// tear Down test infrastructure
await deleteFiles();
await tearDownDeviceTestStructure(sdk);
// Setup the testing architecture
const { device, deviceAsset, deviceType, deviceAssetType, folderid } = await setupDeviceTestStructure(sdk);
assetTypeId = `${(deviceAssetType as any).id}`;
deviceTypeId = `${(deviceType as any).id}`;
assetId = `${(deviceAsset as any).assetId}`;
deviceId = `${(device as any).id}`;
gFolderid = `${folderid}`;
// Post a new file config
const newFile = await deviceConfigurationClient.PostNewFile(configFileTemplate);
globalFileId = `${(newFile as any).id}`;
globalFilePath = `${(newFile as any).path}`;
});
after(async () => {
// Cancel all configuration tasks
// await CancelAllGeneratedConfigurationTaks();
// delete all generated files
await deleteFiles();
// tear Down test infrastructure
await tearDownDeviceTestStructure(sdk);
});
it("SDK should not be undefined", async () => {
sdk.should.not.be.undefined;
});
it("standard properties shoud be defined", async () => {
deviceConfigurationClient.should.not.be.undefined;
deviceConfigurationClient.GetGateway().should.be.equal(auth.gateway);
(await deviceConfigurationClient.GetToken()).length.should.be.greaterThan(200);
(await deviceConfigurationClient.GetToken()).length.should.be.greaterThan(200);
});
it("should POST to create a new empty file", async () => {
deviceConfigurationClient.should.not.be.undefined;
// Prepare the template
const _configFileTemplate = {
path: `/${tenant}/TEST/${timeOffset}/TEST_DEVICE_CONFIGURATION_A.json`,
description: `Configuration for test the API. generated by ${tenant} on ${new Date()}`,
};
const newFile = await deviceConfigurationClient.PostNewFile(_configFileTemplate);
newFile.should.not.be.undefined;
newFile.should.not.be.null;
(newFile as any).id.should.not.be.undefined;
(newFile as any).id.should.not.be.null;
(newFile as any).path.should.not.be.undefined;
(newFile as any).path.should.not.be.null;
// delete file
await deviceConfigurationClient.DeleteFile((newFile as any).id);
});
it("should POST to create a new empty file and add content revision of 1b.", async () => {
deviceConfigurationClient.should.not.be.undefined;
// Prepare the template
const _configFileTemplate = {
path: `/${tenant}/TEST/${timeOffset}/TEST_DEVICE_CONFIGURATION_B.json`,
description: `Configuration for test the API. generated by ${tenant} on ${new Date()}`,
};
const newFile = await deviceConfigurationClient.PostNewFile(_configFileTemplate);
newFile.should.not.be.undefined;
newFile.should.not.be.null;
(newFile as any).id.should.not.be.undefined;
(newFile as any).id.should.not.be.null;
(newFile as any).path.should.not.be.undefined;
(newFile as any).path.should.not.be.null;
const _fileId = (newFile as any).id;
// post content of 1kb
const buffer = Buffer.alloc(1);
const revision = await deviceConfigurationClient.PostFileRevision(_fileId, buffer);
(revision as any).fileId.should.not.be.undefined;
(revision as any).fileId.should.not.be.null;
(revision as any).contentType.should.not.be.undefined;
(revision as any).contentType.should.not.be.null;
// delete file
await deviceConfigurationClient.DeleteFile((newFile as any).id);
});
it("should POST to create a new empty file and add content revision of 8Mb.", async () => {
deviceConfigurationClient.should.not.be.undefined;
// Prepare the template
const _configFileTemplate = {
path: `/${tenant}/TEST/${timeOffset}/TEST_DEVICE_CONFIGURATION_C.json`,
description: `Configuration for test the API. generated by ${tenant} on ${new Date()}`,
};
const newFile = await deviceConfigurationClient.PostNewFile(_configFileTemplate);
newFile.should.not.be.undefined;
newFile.should.not.be.null;
(newFile as any).id.should.not.be.undefined;
(newFile as any).id.should.not.be.null;
(newFile as any).path.should.not.be.undefined;
(newFile as any).path.should.not.be.null;
const _fileId = (newFile as any).id;
// post content of 1kb
const buffer = Buffer.alloc(8 * 1024 * 1024);
const revision = await deviceConfigurationClient.PostFileRevision(_fileId, buffer);
(revision as any).fileId.should.not.be.undefined;
(revision as any).fileId.should.not.be.null;
(revision as any).contentType.should.not.be.undefined;
(revision as any).contentType.should.not.be.null;
// delete file
await deviceConfigurationClient.DeleteFile((newFile as any).id);
});
it("should POST to create a new empty file and add content revision of 16Mb.", async () => {
deviceConfigurationClient.should.not.be.undefined;
// Prepare the template
const _configFileTemplate = {
path: `/${tenant}/TEST/${timeOffset}/TEST_DEVICE_CONFIGURATION_D.json`,
description: `Configuration for test the API. generated by ${tenant} on ${new Date()}`,
};
const newFile = await deviceConfigurationClient.PostNewFile(_configFileTemplate);
newFile.should.not.be.undefined;
newFile.should.not.be.null;
(newFile as any).id.should.not.be.undefined;
(newFile as any).id.should.not.be.null;
(newFile as any).path.should.not.be.undefined;
(newFile as any).path.should.not.be.null;
const _fileId = (newFile as any).id;
// post content of 1kb
const buffer = Buffer.alloc(16 * 1024 * 1024);
const revision = await deviceConfigurationClient.PostFileRevision(_fileId, buffer);
(revision as any).fileId.should.not.be.undefined;
(revision as any).fileId.should.not.be.null;
(revision as any).contentType.should.not.be.undefined;
(revision as any).contentType.should.not.be.null;
// delete file
await deviceConfigurationClient.DeleteFile((newFile as any).id);
});
it("should POST to add content revision of 1Mb.", async () => {
deviceConfigurationClient.should.not.be.undefined;
// post content of 1kb
const buffer = Buffer.alloc(1 * 1024 * 1024);
const revision = await deviceConfigurationClient.PostFileRevision(globalFileId, buffer);
(revision as any).fileId.should.not.be.undefined;
(revision as any).fileId.should.not.be.null;
(revision as any).contentType.should.not.be.undefined;
(revision as any).contentType.should.not.be.null;
});
// it("should PATCH to Update head to new revision of 2Mb.", async () => {
// deviceConfigurationClient.should.not.be.undefined;
//
// // post content of 1kb
// const buffer = Buffer.alloc(2 * 1024 * 1024);
// const revision = await deviceConfigurationClient.PatchFileHead(globalFileId, buffer);
// (revision as any).fileId.should.not.be.undefined;
// (revision as any).fileId.should.not.be.null;
// (revision as any).contentType.should.not.be.undefined;
// (revision as any).contentType.should.not.be.null;
// });
it("should GET to list all files revisions.", async () => {
deviceConfigurationClient.should.not.be.undefined;
const revisions = await deviceConfigurationClient.GetFileRevisions(globalFileId);
(revisions as any).should.not.be.undefined;
(revisions as any).should.not.be.null;
(revisions as any).page.number.should.equal(0);
(revisions as any).page.size.should.be.gte(10);
(revisions as any).content.length.should.be.gte(0);
});
it("should GET to list all files from path.", async () => {
deviceConfigurationClient.should.not.be.undefined;
const files = await deviceConfigurationClient.GetFiles(`/${tenant}/TEST/${timeOffset}/`);
(files as any).should.not.be.undefined;
(files as any).should.not.be.null;
(files as any).page.number.should.equal(0);
(files as any).page.size.should.be.gte(10);
(files as any).content.length.should.be.gte(0);
});
it("should GET file meta data.", async () => {
deviceConfigurationClient.should.not.be.undefined;
const fileMetaData = await deviceConfigurationClient.GetFileMetadata(globalFileId);
(fileMetaData as any).should.not.be.undefined;
(fileMetaData as any).should.not.be.null;
(fileMetaData as any).id.should.not.be.undefined;
(fileMetaData as any).id.should.not.be.null;
(fileMetaData as any).path.should.not.be.undefined;
(fileMetaData as any).path.should.not.be.null;
});
it("should GET file revision meta data.", async () => {
deviceConfigurationClient.should.not.be.undefined;
// Prepare the template
const _configFileTemplate = {
path: `/${tenant}/TEST/${timeOffset}/TEST_DEVICE_CONFIGURATION_E.json`,
description: `Configuration for test the API. generated by ${tenant} on ${new Date()}`,
};
const newFile = await deviceConfigurationClient.PostNewFile(_configFileTemplate);
newFile.should.not.be.undefined;
newFile.should.not.be.null;
(newFile as any).id.should.not.be.undefined;
(newFile as any).id.should.not.be.null;
(newFile as any).path.should.not.be.undefined;
(newFile as any).path.should.not.be.null;
const _fileId = (newFile as any).id;
// post content of 1kb
const buffer = Buffer.alloc(1);
const revision = await deviceConfigurationClient.PostFileRevision(_fileId, buffer);
(revision as any).fileId.should.not.be.undefined;
(revision as any).fileId.should.not.be.null;
(revision as any).contentType.should.not.be.undefined;
(revision as any).contentType.should.not.be.null;
// Get file revision
const rRevision = await deviceConfigurationClient.GetFileRevisionMetadata(_fileId, (revision as any).hash);
(rRevision as any).fileId.should.not.be.undefined;
(rRevision as any).fileId.should.not.be.null;
(rRevision as any).fileId.should.be.equal((revision as any).fileId);
(rRevision as any).contentType.should.not.be.undefined;
(rRevision as any).contentType.should.not.be.null;
(rRevision as any).contentType.should.be.equal((revision as any).contentType);
(rRevision as any).hash.should.not.be.undefined;
(rRevision as any).hash.should.not.be.null;
(rRevision as any).hash.should.be.equal((revision as any).hash);
// delete file
await deviceConfigurationClient.DeleteFile((newFile as any).id);
});
it("should GET file revision content.", async () => {
deviceConfigurationClient.should.not.be.undefined;
// Prepare the template
const _configFileTemplate = {
path: `/${tenant}/TEST/${timeOffset}/TEST_DEVICE_CONFIGURATION_F.json`,
description: `Configuration for test the API. generated by ${tenant} on ${new Date()}`,
};
const newFile = await deviceConfigurationClient.PostNewFile(_configFileTemplate);
newFile.should.not.be.undefined;
newFile.should.not.be.null;
(newFile as any).id.should.not.be.undefined;
(newFile as any).id.should.not.be.null;
(newFile as any).path.should.not.be.undefined;
(newFile as any).path.should.not.be.null;
const _fileId = (newFile as any).id;
// post content of 1kb
const buffer = Buffer.alloc(1);
const revision = await deviceConfigurationClient.PostFileRevision(_fileId, buffer);
(revision as any).fileId.should.not.be.undefined;
(revision as any).fileId.should.not.be.null;
(revision as any).contentType.should.not.be.undefined;
(revision as any).contentType.should.not.be.null;
// Get file revision
const rContent = await deviceConfigurationClient.GetFileRevisionContent(_fileId, (revision as any).hash);
rContent.should.not.be.undefined;
rContent.should.not.be.null;
// delete file
await deviceConfigurationClient.DeleteFile((newFile as any).id);
});
it("should DELETE a file of 1b.", async () => {
deviceConfigurationClient.should.not.be.undefined;
// Prepare the template
const _configFileTemplate = {
path: `/${tenant}/TEST/${timeOffset}/TEST_DEVICE_CONFIGURATION_G.json`,
description: `Configuration for test the API. generated by ${tenant} on ${new Date()}`,
};
const newFile = await deviceConfigurationClient.PostNewFile(_configFileTemplate);
newFile.should.not.be.undefined;
newFile.should.not.be.null;
(newFile as any).id.should.not.be.undefined;
(newFile as any).id.should.not.be.null;
(newFile as any).path.should.not.be.undefined;
(newFile as any).path.should.not.be.null;
const _fileId = (newFile as any).id;
// post content of 1b
const buffer = Buffer.alloc(1);
const revision = await deviceConfigurationClient.PostFileRevision(_fileId, buffer);
(revision as any).fileId.should.not.be.undefined;
(revision as any).fileId.should.not.be.null;
(revision as any).contentType.should.not.be.undefined;
(revision as any).contentType.should.not.be.null;
// delete file
await deviceConfigurationClient.DeleteFile((newFile as any).id);
});
it("should POST a new configuration task", async () => {
deviceConfigurationClient.should.not.be.undefined;
// Change the testConfigurationTask
testConfigurationTask.customData.name = `TEST_DEVICE_CONFIGURATION_${tenant}_${timeOffset}_A`;
// Create a new app instance configuration
const newConfigtask = await deviceConfigurationClient.PostNewDeploymentTaskConfiguration(
deviceId,
testConfigurationTask
);
newConfigtask.should.not.be.undefined;
newConfigtask.should.not.be.null;
(newConfigtask as any).id.should.not.be.undefined;
(newConfigtask as any).id.should.not.be.null;
(newConfigtask as any).customData.name.should.not.be.undefined;
(newConfigtask as any).customData.name.should.not.be.null;
(newConfigtask as any).currentState.should.not.be.undefined;
(newConfigtask as any).currentState.should.not.be.null;
configTaskId = `${(newConfigtask as any).id}`;
//
// const _configTaskId = `${(newConfigtask as any).id}`;
//
// // Cancel the task
// testConfigurationState.state = DeviceConfigurationModels.Updatetask.StateEnum.CANCELED;
// testConfigurationState.progress = 100;
// const configtask = await deviceConfigurationClient.PatchDeploymentTaskConfiguration(
// deviceId,
// _configTaskId,
// testConfigurationState
// );
});
it("should GET list all tasks of a device @sanity", async () => {
deviceConfigurationClient.should.not.be.undefined;
const apps = await deviceConfigurationClient.GetConfigurationTasks(deviceId);
apps.should.not.be.undefined;
apps.should.not.be.null;
(apps as any).page.number.should.equal(0);
(apps as any).page.size.should.be.gte(10);
(apps as any).content.length.should.be.gte(0);
});
it("should GET status of a configuration task by id", async () => {
deviceConfigurationClient.should.not.be.undefined;
const status = await deviceConfigurationClient.GetDeviceConfigurationTask(deviceId, configTaskId);
status.should.not.be.undefined;
status.should.not.be.null;
(status as any).currentState.should.not.be.undefined;
(status as any).currentState.should.not.be.null;
});
it("should PATCH status of configuration task: cancel task.", async () => {
// Patch the task
// Prepare the state
testConfigurationState.state = DeviceConfigurationModels.Updatetask.StateEnum.CANCELED;
testConfigurationState.progress = 100;
const configtask = await deviceConfigurationClient.PatchDeploymentTaskConfiguration(
deviceId,
configTaskId,
testConfigurationState
);
(configtask as any).id.should.not.be.undefined;
(configtask as any).id.should.not.be.null;
(configtask as any).currentState.should.not.be.undefined;
(configtask as any).currentState.should.not.be.null;
});
it("should GET status of a configuration task, which should be canceled", async () => {
deviceConfigurationClient.should.not.be.undefined;
const status = await deviceConfigurationClient.GetDeviceConfigurationTask(deviceId, configTaskId);
status.should.not.be.undefined;
status.should.not.be.null;
(status as any).currentState.should.not.be.undefined;
(status as any).currentState.should.not.be.null;
(status as any).currentState.state.should.be.equal(
DeviceConfigurationModels.ConfigurationStateInfo.StateEnum.CANCELED.toString()
);
});
async function deleteFiles() {
await sleep(2000);
let files = null;
let page = 0;
do {
files = (await deviceConfigurationClient.GetFiles(
`/${tenant}/TEST`,
100
)) as DeviceConfigurationModels.PaginatedFileMetaData;
files.content = files.content || [];
files.page = files.page || { totalPages: 0 };
for (const _fileMetaData of files.content || []) {
const fileMetaData = _fileMetaData as DeviceConfigurationModels.FileMetaData;
await deviceConfigurationClient.DeleteFile(`${fileMetaData.id}`);
}
} while (page++ < (files.page.totalPages || 0));
}
}); | the_stack |
import {
Directive,
ElementRef,
Renderer2,
Input,
Output,
EventEmitter,
NgZone,
OnChanges,
AfterViewInit,
OnDestroy,
Inject,
PLATFORM_ID,
SimpleChanges
} from '@angular/core';
import { ResizeObserver as ResizeObserverPonyfill } from '@juggle/resize-observer';
import { take } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { isPlatformBrowser } from '@angular/common';
let ResizeObserver = ResizeObserverPonyfill;
/**
* Directive to truncate the contained text, if it exceeds the element's boundaries
* and append characters (configurable, default '...') if so.
*/
@Directive({
selector: '[ellipsis]',
exportAs: 'ellipsis'
})
export class EllipsisDirective implements OnChanges, OnDestroy, AfterViewInit {
/**
* The original text (not truncated yet)
*/
private originalText: string;
/**
* The referenced element
*/
private elem: any;
/**
* Inner div element (will be auto-created)
*/
private innerElem: any;
/**
* Anchor tag wrapping the `ellipsisCharacters`
*/
private moreAnchor: HTMLAnchorElement;
private previousDimensions: {
width: number,
height: number
};
/**
* Subject triggered when resize listeners should be removed
*/
private removeResizeListeners$ = new Subject<void>();
/**
* Remove function for the currently registered click listener
* on the link `this.ellipsisCharacters` are wrapped in.
*/
private destroyMoreClickListener: () => void;
/**
* The ellipsis html attribute
* If anything is passed, this will be used as a string to append to
* the truncated contents.
* Else '...' will be appended.
*/
@Input('ellipsis') ellipsisCharacters: string;
/**
* The ellipsis-content html attribute
* If passed this is used as content, else contents
* are fetched from textContent
*/
@Input('ellipsis-content') ellipsisContent: string | number = null;
/**
* The ellipsis-word-boundaries html attribute
* If anything is passed, each character will be interpreted
* as a word boundary at which the text may be truncated.
* Else the text may be truncated at any character.
*/
@Input('ellipsis-word-boundaries') ellipsisWordBoundaries: string;
/**
* Function to use for string splitting. Defaults to the native `String#substr`.
* (This may for example be used to avoid splitting surrogate pairs- used by some emojis -
* by providing a lib such as runes.)
*/
@Input('ellipsis-substr-fn') ellipsisSubstrFn: (str: string, from: number, length?: number) => string;
/**
* The ellipsis-resize-detection html attribute
* Algorithm to use to detect element/window resize - any of the following:
* 'resize-observer': (default) Use native ResizeObserver - see
* https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
* and https://github.com/juggle/resize-observer
* 'window': Only check if the whole window has been resized/changed orientation by using angular's built-in HostListener
*/
@Input('ellipsis-resize-detection') resizeDetectionStrategy:
'' | 'manual' | 'resize-observer' | 'window';
/**
* The ellipsis-click-more html attribute
* If anything is passed, the ellipsisCharacters will be
* wrapped in <a></a> tags and an event handler for the
* passed function will be added to the link
*/
@Output('ellipsis-click-more') moreClickEmitter: EventEmitter<MouseEvent> = new EventEmitter();
/**
* The ellipsis-change html attribute
* This emits after which index the text has been truncated.
* If it hasn't been truncated, null is emitted.
*/
@Output('ellipsis-change') changeEmitter: EventEmitter<number> = new EventEmitter();
/**
* Utility method to quickly find the largest number for
* which `callback(number)` still returns true.
* @param max Highest possible number
* @param callback Should return true as long as the passed number is valid
* @return Largest possible number
*/
private static numericBinarySearch(max: number, callback: (n: number) => boolean): number {
let low = 0;
let high = max;
let best = -1;
let mid: number;
while (low <= high) {
// tslint:disable-next-line:no-bitwise
mid = ~~((low + high) / 2);
const result = callback(mid);
if (!result) {
high = mid - 1;
} else {
best = mid;
low = mid + 1;
}
}
return best;
}
/**
* Convert ellipsis input to string
* @param input string or number to be displayed as an ellipsis
* @return input converted to string
*/
private static convertEllipsisInputToString(input: string | number): string {
if (typeof input === 'undefined' || input === null) {
return '';
}
return String(input);
}
/**
* The directive's constructor
*/
public constructor(
private elementRef: ElementRef<HTMLElement>,
private renderer: Renderer2,
private ngZone: NgZone,
@Inject(PLATFORM_ID) private platformId: Object
) { }
/**
* Angular's init view life cycle hook.
* Initializes the element for displaying the ellipsis.
*/
ngAfterViewInit() {
if (!isPlatformBrowser(this.platformId)) {
// in angular universal we don't have access to the ugly
// DOM manipulation properties we sadly need to access here,
// so wait until we're in the browser:
return;
}
// Prefer native ResizeObserver over ponyfill, if available:
if ((<any> window).ResizeObserver != null) {
ResizeObserver = (<any> window).ResizeObserver;
}
// let the ellipsis characters default to '...':
if (this.ellipsisCharacters === '') {
this.ellipsisCharacters = '...';
}
// create more anchor element:
this.moreAnchor = <HTMLAnchorElement> this.renderer.createElement('a');
this.moreAnchor.className = 'ngx-ellipsis-more';
this.moreAnchor.href = '#';
this.moreAnchor.textContent = this.ellipsisCharacters;
// perform regex replace on word boundaries:
if (!this.ellipsisWordBoundaries) {
this.ellipsisWordBoundaries = '';
}
this.ellipsisWordBoundaries = '[' + this.ellipsisWordBoundaries.replace(/\\n/, '\n').replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + ']';
if (!this.ellipsisSubstrFn) {
this.ellipsisSubstrFn = (str: string, from: number, length?: number) => {
return str.substr(from, length);
}
}
// store the original contents of the element:
this.elem = this.elementRef.nativeElement;
if (typeof this.ellipsisContent !== 'undefined' && this.ellipsisContent !== null) {
this.originalText = EllipsisDirective.convertEllipsisInputToString(this.ellipsisContent);
} else if (!this.originalText) {
this.originalText = this.elem.textContent.trim();
}
// add a wrapper div (required for resize events to work properly):
this.renderer.setProperty(this.elem, 'innerHTML', '');
this.innerElem = this.renderer.createElement('div');
this.renderer.addClass(this.innerElem, 'ngx-ellipsis-inner');
const text = this.renderer.createText(this.originalText);
this.renderer.appendChild(this.innerElem, text);
this.renderer.appendChild(this.elem, this.innerElem);
this.previousDimensions = {
width: this.elem.clientWidth,
height: this.elem.clientHeight
};
// start listening for resize events:
this.addResizeListener(true);
}
/**
* Angular's change life cycle hook.
* Change original text (if the ellipsis-content has been passed)
* and re-render
*/
ngOnChanges(changes: SimpleChanges) {
const moreAnchorRequiresChange = this.moreAnchor && changes['ellipsisCharacters'];
if (moreAnchorRequiresChange) {
this.moreAnchor.textContent = this.ellipsisCharacters;
}
if (this.elem
&& typeof this.ellipsisContent !== 'undefined'
&& (
this.originalText !== EllipsisDirective.convertEllipsisInputToString(this.ellipsisContent)
|| moreAnchorRequiresChange
)
) {
this.originalText = EllipsisDirective.convertEllipsisInputToString(this.ellipsisContent);
this.applyEllipsis();
}
}
/**
* Angular's destroy life cycle hook.
* Remove event listeners
*/
ngOnDestroy() {
// In angular universal we don't have any listeners hooked up (all requiring ugly DOM manipulation methods),
// so we only need to remove them, if we're inside the browser:
if (isPlatformBrowser(this.platformId)) {
this.removeAllListeners();
}
}
/**
* remove all resize listeners
*/
private removeAllListeners() {
if (this.destroyMoreClickListener) {
this.destroyMoreClickListener();
}
this.removeResizeListeners$.next();
this.removeResizeListeners$.complete();
}
/**
* Set up an event listener to call applyEllipsis() whenever a resize has been registered.
* The type of the listener (window/element) depends on the resizeDetectionStrategy.
* @param triggerNow=false if true, the ellipsis is applied immediately
*/
private addResizeListener(triggerNow = false) {
if (typeof (this.resizeDetectionStrategy) === 'undefined') {
this.resizeDetectionStrategy = '';
}
switch (this.resizeDetectionStrategy) {
case 'manual':
// Users will trigger applyEllipsis via the public API
break;
case 'window':
this.addWindowResizeListener();
break;
default:
if (typeof (console) !== 'undefined') {
console.warn(
`No such ellipsis-resize-detection strategy: '${this.resizeDetectionStrategy}'. Using 'resize-observer' instead`
);
}
// eslint-disable-next-line no-fallthrough
case 'resize-observer':
case '':
this.addElementResizeListener();
break;
}
if (triggerNow && this.resizeDetectionStrategy !== 'manual') {
this.applyEllipsis();
}
}
/**
* Set up an event listener to call applyEllipsis() whenever the window gets resized.
*/
private addWindowResizeListener() {
const removeWindowResizeListener = this.renderer.listen('window', 'resize', () => {
this.ngZone.run(() => {
this.applyEllipsis();
});
});
this.removeResizeListeners$.pipe(take(1)).subscribe(() => removeWindowResizeListener());
}
/**
* Set up an event listener to call applyEllipsis() whenever the element
* has been resized.
*/
private addElementResizeListener() {
const resizeObserver = new ResizeObserver(() => {
window.requestAnimationFrame(() => {
if (this.previousDimensions.width !== this.elem.clientWidth || this.previousDimensions.height !== this.elem.clientHeight) {
this.ngZone.run(() => {
this.applyEllipsis();
});
this.previousDimensions.width = this.elem.clientWidth;
this.previousDimensions.height = this.elem.clientHeight;
}
});
});
resizeObserver.observe(this.elem);
this.removeResizeListeners$.pipe(take(1)).subscribe(() => resizeObserver.disconnect());
}
/**
* Get the original text's truncated version. If the text really needed to
* be truncated, this.ellipsisCharacters will be appended.
* @param max the maximum length the text may have
* @return string the truncated string
*/
private getTruncatedText(max: number): string {
if (!this.originalText || this.originalText.length <= max) {
return this.originalText;
}
const truncatedText = this.ellipsisSubstrFn(this.originalText, 0, max);
if (this.ellipsisWordBoundaries === '[]' || this.originalText.charAt(max).match(this.ellipsisWordBoundaries)) {
return truncatedText;
}
let i = max - 1;
while (i > 0 && !truncatedText.charAt(i).match(this.ellipsisWordBoundaries)) {
i--;
}
return this.ellipsisSubstrFn(truncatedText, 0, i);
}
/**
* Set the truncated text to be displayed in the inner div
* @param max the maximum length the text may have
* @param addMoreListener=false listen for click on the ellipsisCharacters anchor tag if the text has been truncated
* @returns length of remaining text (excluding the ellipsisCharacters, if they were added)
*/
private truncateText(max: number, addMoreListener = false): number {
let text = this.getTruncatedText(max);
const truncatedLength = text.length;
const textTruncated = (truncatedLength !== this.originalText.length);
if (textTruncated && !this.showMoreLink) {
text += this.ellipsisCharacters;
}
this.renderer.setProperty(this.innerElem, 'textContent', text);
if (textTruncated && this.showMoreLink) {
this.renderer.appendChild(this.innerElem, this.moreAnchor);
}
// Remove any existing more click listener:
if (this.destroyMoreClickListener) {
this.destroyMoreClickListener();
this.destroyMoreClickListener = null;
}
// If the text has been truncated, add a more click listener:
if (addMoreListener && textTruncated) {
this.destroyMoreClickListener = this.renderer.listen(this.moreAnchor, 'click', (e: MouseEvent) => {
if (!e.target || !(<HTMLElement> e.target).classList.contains('ngx-ellipsis-more')) {
return;
}
e.preventDefault();
this.moreClickEmitter.emit(e);
});
}
return truncatedLength;
}
/**
* Display ellipsis in the inner div if the text would exceed the boundaries
*/
public applyEllipsis() {
// Remove the resize listener as changing the contained text would trigger events:
this.removeResizeListeners$.next();
// Find the best length by trial and error:
const maxLength = EllipsisDirective.numericBinarySearch(this.originalText.length, curLength => {
this.truncateText(curLength);
return !this.isOverflowing;
});
// Apply the best length:
const finalLength = this.truncateText(maxLength, this.showMoreLink);
// Re-attach the resize listener:
this.addResizeListener();
// Emit change event:
if (this.changeEmitter.observers.length > 0) {
this.changeEmitter.emit(
(this.originalText.length === finalLength) ? null : finalLength
);
}
}
/**
* Whether the text is exceeding the element's boundaries or not
*/
private get isOverflowing(): boolean {
// Enforce hidden overflow (required to compare client width/height with scroll width/height)
const currentOverflow = this.elem.style.overflow;
if (!currentOverflow || currentOverflow === 'visible') {
this.elem.style.overflow = 'hidden';
}
const isOverflowing = this.elem.clientWidth < this.elem.scrollWidth - 1 || this.elem.clientHeight < this.elem.scrollHeight - 1;
// Reset overflow to the original configuration:
this.elem.style.overflow = currentOverflow;
return isOverflowing;
}
/**
* Whether the `ellipsisCharacters` are to be wrapped inside an anchor tag (if they are shown at all)
*/
private get showMoreLink(): boolean {
return (this.moreClickEmitter.observers.length > 0);
}
} | the_stack |
import type vscode from 'vscode';
import { SymbolInformation } from 'vscode-languageserver-types';
import {
Uri as URI,
IRange,
IDisposable,
UriComponents,
SymbolTag,
CancellationToken,
Event,
IMarkdownString,
} from '@opensumi/ide-core-common';
import { ISingleEditOperation } from '@opensumi/ide-editor';
// eslint-disable-next-line import/no-restricted-paths
import type { CallHierarchyItem } from '@opensumi/ide-monaco/lib/browser/contrib/callHierarchy';
// eslint-disable-next-line import/no-restricted-paths
import type { TypeHierarchyItem } from '@opensumi/ide-monaco/lib/browser/contrib/typeHierarchy';
import type { CompletionItemLabel } from '@opensumi/monaco-editor-core/esm/vs/editor/common/modes';
import { LanguageFeatureRegistry } from '@opensumi/monaco-editor-core/esm/vs/editor/common/modes/languageFeatureRegistry';
import type { languages, editor } from '@opensumi/monaco-editor-core/esm/vs/editor/editor.api';
// 内置的api类型声明
import { IndentAction, SymbolKind } from './ext-types';
export { IMarkdownString, SymbolTag, CallHierarchyItem, TypeHierarchyItem };
export interface IRawColorInfo {
color: [number, number, number, number];
range: Range;
}
/**
* String representations for a color
*/
export interface IColorPresentation {
/**
* The label of this color presentation. It will be shown on the color
* picker header. By default this is also the text that is inserted when selecting
* this color presentation.
*/
label: string;
/**
* An [edit](#TextEdit) which is applied to a document when selecting
* this presentation for the color.
*/
textEdit?: TextEdit;
/**
* An optional array of additional [text edits](#TextEdit) that are applied when
* selecting this color presentation.
*/
additionalTextEdits?: TextEdit[];
}
export interface CustomCodeAction {
title: string;
kind?: string;
_isSynthetic?: boolean;
command?: VSCommand;
edit?: IWorkspaceEditDto;
isPreferred?: boolean;
}
/**
* A position in the editor. This interface is suitable for serialization.
*/
export interface Position {
/**
* line number (starts at 1)
*/
readonly lineNumber: number;
/**
* column (the first character in a line is between column 1 and column 2)
*/
readonly column: number;
}
export interface Range {
/**
* Line number on which the range starts (starts at 1).
*/
readonly startLineNumber: number;
/**
* Column on which the range starts in line `startLineNumber` (starts at 1).
*/
readonly startColumn: number;
/**
* Line number on which the range ends.
*/
readonly endLineNumber: number;
/**
* Column on which the range ends in line `endLineNumber`.
*/
readonly endColumn: number;
}
export interface Selection {
/**
* The line number on which the selection has started.
*/
readonly selectionStartLineNumber: number;
/**
* The column on `selectionStartLineNumber` where the selection has started.
*/
readonly selectionStartColumn: number;
/**
* The line number on which the selection has ended.
*/
readonly positionLineNumber: number;
/**
* The column on `positionLineNumber` where the selection has ended.
*/
readonly positionColumn: number;
}
export interface Hover {
contents: IMarkdownString[];
range?: Range;
}
export interface SerializedDocumentFilter {
$serialized: true;
language?: string;
scheme?: string;
pattern?: vscode.GlobPattern;
}
export interface CommentRule {
lineComment?: string;
blockComment?: CharacterPair;
}
export interface SerializedRegExp {
pattern: string;
flags?: string;
}
export interface SerializedIndentationRule {
decreaseIndentPattern?: SerializedRegExp;
increaseIndentPattern?: SerializedRegExp;
indentNextLinePattern?: SerializedRegExp;
unIndentedLinePattern?: SerializedRegExp;
}
export interface EnterAction {
indentAction: IndentAction;
outdentCurrentLine?: boolean;
appendText?: string;
removeText?: number;
}
export interface SerializedOnEnterRule {
beforeText: SerializedRegExp;
afterText?: SerializedRegExp;
action: EnterAction;
previousLineText: SerializedRegExp;
}
export type CharacterPair = [string, string];
export interface SerializedLanguageConfiguration {
comments?: CommentRule;
brackets?: CharacterPair[];
wordPattern?: SerializedRegExp;
indentationRules?: SerializedIndentationRule;
onEnterRules?: SerializedOnEnterRule[];
}
/**
* Represents a location inside a resource, such as a line
* inside a text file.
*/
export interface Location {
/**
* The resource identifier of this location.
*/
uri: URI;
/**
* The document range of this locations.
*/
range: Range;
}
export interface LocationLink {
/**
* A range to select where this link originates from.
*/
originSelectionRange?: Range;
/**
* The target uri this link points to.
*/
uri: URI;
/**
* The full range this link points to.
*/
range: Range;
/**
* A range to select this link points to. Must be contained
* in `LocationLink.range`.
*/
targetSelectionRange?: Range;
}
export enum CompletionTriggerKind {
Invoke = 0,
TriggerCharacter = 1,
TriggerForIncompleteCompletions = 2,
}
export interface CompletionContext {
triggerKind: CompletionTriggerKind;
triggerCharacter?: string;
}
export type CompletionType =
| 'method'
| 'function'
| 'constructor'
| 'field'
| 'variable'
| 'class'
| 'struct'
| 'interface'
| 'module'
| 'property'
| 'event'
| 'operator'
| 'unit'
| 'value'
| 'constant'
| 'enum'
| 'enum-member'
| 'keyword'
| 'snippet'
| 'text'
| 'color'
| 'file'
| 'reference'
| 'customcolor'
| 'folder'
| 'type-parameter';
/**
* A completion item represents a text snippet that is
* proposed to complete text that is being typed.
*/
export interface CompletionItem {
/**
* The label of this completion item. By default
* this is also the text that is inserted when selecting
* this completion.
*/
label: string | CompletionItemLabel;
/**
* The kind of this completion item. Based on the kind
* an icon is chosen by the editor.
*/
kind: CompletionItemKind;
/**
* A modifier to the `kind` which affect how the item
* is rendered, e.g. Deprecated is rendered with a strikeout
*/
tags?: ReadonlyArray<CompletionItemTag>;
/**
* A human-readable string with additional information
* about this item, like type or symbol information.
*/
detail?: string;
/**
* A human-readable string that represents a doc-comment.
*/
documentation?: string | IMarkdownString;
/**
* A string that should be used when comparing this item
* with other items. When `falsy` the [label](#CompletionItem.label)
* is used.
*/
sortText?: string;
/**
* A string that should be used when filtering a set of
* completion items. When `falsy` the [label](#CompletionItem.label)
* is used.
*/
filterText?: string;
/**
* Select this item when showing. *Note* that only one completion item can be selected and
* that the editor decides which item that is. The rule is that the *first* item of those
* that match best is selected.
*/
preselect?: boolean;
/**
* A string or snippet that should be inserted in a document when selecting
* this completion.
* is used.
*/
insertText: string;
/**
* Addition rules (as bitmask) that should be applied when inserting
* this completion.
*/
insertTextRules?: CompletionItemInsertTextRule;
/**
* A range of text that should be replaced by this completion item.
*
* Defaults to a range from the start of the [current word](#TextDocument.getWordRangeAtPosition) to the
* current position.
*
* *Note:* The range must be a [single line](#Range.isSingleLine) and it must
* [contain](#Range.contains) the position at which completion has been [requested](#CompletionItemProvider.provideCompletionItems).
*/
range?: IRange | { insert: IRange; replace: IRange };
/**
* An optional set of characters that when pressed while this completion is active will accept it first and
* then type that character. *Note* that all commit characters should have `length=1` and that superfluous
* characters will be ignored.
*/
commitCharacters?: string[];
/**
* An optional array of additional text edits that are applied when
* selecting this completion. Edits must not overlap with the main edit
* nor with themselves.
*/
additionalTextEdits?: ISingleEditOperation[];
/**
* A command that should be run upon acceptance of this item.
*/
command?: VSCommand;
/**
* @internal
*/
[key: string]: any;
}
export interface CompletionList {
suggestions: CompletionItem[];
incomplete?: boolean;
dispose?(): void;
}
export interface SingleEditOperation {
range: Range;
text: string;
/**
* This indicates that this operation has "insert" semantics.
* i.e. forceMoveMarkers = true => if `range` is collapsed, all markers at the position will be moved.
*/
forceMoveMarkers?: boolean;
/**
* This indicates that this operation only has diff patch
*/
onlyPatch?: boolean;
}
export type SnippetType = 'internal' | 'textmate';
export interface VSCommand {
id: string;
title: string;
tooltip?: string;
arguments?: any[];
}
export class IdObject {
id?: number;
}
export enum CompletionItemInsertTextRule {
/**
* Adjust whitespace/indentation of multiline insert texts to
* match the current line indentation.
*/
KeepWhitespace = 1,
/**
* `insertText` is a snippet.
*/
InsertAsSnippet = 4,
}
export type Definition = Location | Location[];
export interface DefinitionLink {
uri: UriComponents;
range: Range;
origin?: Range;
selectionRange?: Range;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface FoldingContext {}
export interface FoldingRange {
/**
* The one-based start line of the range to fold. The folded area starts after the line's last character.
*/
start: number;
/**
* The one-based end line of the range to fold. The folded area ends with the line's last character.
*/
end: number;
/**
* Describes the [Kind](#FoldingRangeKind) of the folding range such as [Comment](#FoldingRangeKind.Comment) or
* [Region](#FoldingRangeKind.Region). The kind is used to categorize folding ranges and used by commands
* like 'Fold all comments'. See
* [FoldingRangeKind](#FoldingRangeKind) for an enumeration of standardized kinds.
*/
kind?: FoldingRangeKind;
}
export class FoldingRangeKind {
/**
* Kind for folding range representing a comment. The value of the kind is 'comment'.
*/
static readonly Comment = new FoldingRangeKind('comment');
/**
* Kind for folding range representing a import. The value of the kind is 'imports'.
*/
static readonly Imports = new FoldingRangeKind('imports');
/**
* Kind for folding range representing regions (for example marked by `#region`, `#endregion`).
* The value of the kind is 'region'.
*/
static readonly Region = new FoldingRangeKind('region');
/**
* Creates a new [FoldingRangeKind](#FoldingRangeKind).
*
* @param value of the kind.
*/
public constructor(public value: string) {}
}
export interface SelectionRange {
range: Range;
}
export interface Color {
readonly red: number;
readonly green: number;
readonly blue: number;
readonly alpha: number;
}
export interface ColorPresentation {
label: string;
textEdit?: TextEdit;
additionalTextEdits?: TextEdit[];
}
export interface ColorInformation {
range: Range;
color: Color;
}
export interface TextEdit {
range: Range;
text: string;
eol?: editor.EndOfLineSequence;
}
export interface RawColorInfo {
color: [number, number, number, number];
range: Range;
}
// 放在正确位置 end
export enum DocumentHighlightKind {
Text = 0,
Read = 1,
Write = 2,
}
export interface DocumentHighlight {
range: Range;
kind?: DocumentHighlightKind;
}
export interface FormattingOptions {
tabSize: number;
insertSpaces: boolean;
}
export interface CodeLens {
range: IRange;
cacheId?: ChainedCacheId;
command?: VSCommand;
}
export interface ICodeLensListDto {
cacheId?: number;
lenses: CodeLens[];
}
export interface CodeLensList {
lenses: CodeLens[];
dispose(): void;
}
export interface WorkspaceEditDto extends languages.WorkspaceEdit {
rejectReason?: string;
}
export type IWorkspaceEditDto = WorkspaceEditDto;
export interface FileOperationOptions {
overwrite?: boolean;
ignoreIfExists?: boolean;
ignoreIfNotExists?: boolean;
recursive?: boolean;
}
export type ResourceFileEditDto = languages.WorkspaceFileEdit;
export type ResourceTextEditDto = languages.WorkspaceTextEdit;
export interface DocumentLink {
range: Range;
url?: string;
}
/**
* Value-object that contains additional information when
* requesting references.
*/
export interface ReferenceContext {
/**
* Include the declaration of the current symbol.
*/
includeDeclaration: boolean;
}
export interface ILink {
range: IRange;
url?: URI | string;
tooltip?: string;
}
export interface ILinksList {
links: ILink[];
dispose?(): void;
}
export interface ILinkDto extends ILink {
cacheId?: ChainedCacheId;
}
export interface ILinksListDto {
id?: CacheId;
links: ILink[];
}
export interface DocumentSymbol {
name: string;
detail: string;
kind: SymbolKind;
tags: ReadonlyArray<SymbolTag>;
containerName?: string;
range: Range;
selectionRange: Range;
children?: DocumentSymbol[];
}
export interface WorkspaceSymbolProvider {
provideWorkspaceSymbols(params: WorkspaceSymbolParams, token: CancellationToken): Thenable<SymbolInformation[]>;
resolveWorkspaceSymbol(symbol: SymbolInformation, token: CancellationToken): Thenable<SymbolInformation>;
}
export interface IWorkspaceSymbol {
name: string;
containerName?: string;
kind: SymbolKind;
tags?: SymbolTag[];
location: Location;
}
export interface WorkspaceSymbolParams {
query: string;
}
export interface ParameterInformation {
label: string | [number, number];
documentation?: string | IMarkdownString;
}
export interface SignatureInformation {
label: string;
documentation?: string | IMarkdownString;
parameters: ParameterInformation[];
activeParameter?: number;
}
export interface SignatureHelp {
signatures: SignatureInformation[];
activeSignature: number;
activeParameter: number;
}
export interface ISignatureHelpDto extends SignatureHelp {
id: number;
}
export interface SignatureHelpResult extends IDisposable {
value: SignatureHelp;
}
export interface RenameLocation {
range: Range;
text: string;
}
export interface Rejection {
rejectReason?: string;
}
export interface ISerializedSignatureHelpProviderMetadata {
readonly triggerCharacters: readonly string[];
readonly retriggerCharacters: readonly string[];
}
export interface SignatureHelpContextDto {
readonly triggerKind: SignatureHelpTriggerKind;
readonly triggerCharacter?: string;
readonly isRetrigger: boolean;
readonly activeSignatureHelp?: SignatureHelpDto;
}
export enum SignatureHelpTriggerKind {
Invoke = 1,
TriggerCharacter = 2,
ContentChange = 3,
}
export interface SignatureHelpDto {
id: CacheId;
signatures: SignatureInformation[];
activeSignature: number;
activeParameter: number;
}
export type CacheId = number;
export type ChainedCacheId = [CacheId, CacheId];
export enum CompletionItemKind {
Method,
Function,
Constructor,
Field,
Variable,
Class,
Struct,
Interface,
Module,
Property,
Event,
Operator,
Unit,
Value,
Constant,
Enum,
EnumMember,
Keyword,
Text,
Color,
File,
Reference,
Customcolor,
Folder,
TypeParameter,
User,
Issue,
Snippet, // <- highest value (used for compare!)
}
export enum CompletionItemTag {
Deprecated = 1,
}
/**
* Mapped-type that replaces all occurrences of URI with UriComponents and
* drops all functions.
*/
export type Dto<T> = T extends { toJSON(): infer U } ? U : T extends object ? { [k in keyof T]: Dto<T[k]> } : T;
export type ICallHierarchyItemDto = Dto<CallHierarchyItem>;
export type ITypeHierarchyItemDto = Dto<TypeHierarchyItem>;
export interface IIncomingCallDto {
from: ICallHierarchyItemDto;
fromRanges: IRange[];
}
export interface IOutgoingCallDto {
fromRanges: IRange[];
to: ICallHierarchyItemDto;
}
/**
* TODO: From vs/editor/common/core/range
*/
export function isIRange(obj: any): obj is Range {
return (
obj &&
typeof obj.startLineNumber === 'number' &&
typeof obj.startColumn === 'number' &&
typeof obj.endLineNumber === 'number' &&
typeof obj.endColumn === 'number'
);
}
export function isLocationLink(thing: any): thing is LocationLink {
return (
thing &&
URI.isUri((thing as LocationLink).uri) &&
isIRange((thing as LocationLink).range) &&
(isIRange((thing as LocationLink).originSelectionRange) || isIRange((thing as LocationLink).targetSelectionRange))
);
}
export interface SemanticTokensLegend {
readonly tokenTypes: string[];
readonly tokenModifiers: string[];
}
export interface SemanticTokens {
readonly resultId?: string;
readonly data: Uint32Array;
}
export interface SemanticTokensEdit {
readonly start: number;
readonly deleteCount: number;
readonly data?: Uint32Array;
}
export interface SemanticTokensEdits {
readonly resultId?: string;
readonly edits: SemanticTokensEdit[];
}
export interface WithDuration<T> {
_dur: number;
result: T;
}
/**
* A provider of folding ranges for editor models.
*/
export interface FoldingRangeProvider {
/**
* An optional event to signal that the folding ranges from this provider have changed.
*/
onDidChange?: Event<this>;
/**
* Provides the folding ranges for a specific model.
*/
provideFoldingRanges(
model: editor.ITextModel,
context: FoldingContext,
token: CancellationToken,
): vscode.ProviderResult<FoldingRange[]>;
}
export const FoldingRangeProviderRegistry = new LanguageFeatureRegistry<FoldingRangeProvider>(); | the_stack |
import { RouterOSAPI, RosException } from "node-routeros";
import { flatten, reduce } from "lodash";
import * as utils from "./utils";
import * as Types from "./Types";
export abstract class RouterOSAPICrud {
protected rosApi: RouterOSAPI;
protected pathVal: string;
protected proplistVal: string;
protected queryVal: string[] = [];
protected snakeCase: boolean;
private needsObjectTranslation: boolean = false;
private placeAfter: any;
/**
* Creates a CRUD set of operations and handle
* the raw query to input on the raw API
*
* @param rosApi the raw api
* @param path the menu path we are in
* @param snakeCase if should return routerboard properties in snake_case, defaults to camelCase
*/
constructor(rosApi: RouterOSAPI, path: string, snakeCase: boolean) {
this.rosApi = rosApi;
this.snakeCase = snakeCase;
this.pathVal = path
.replace(/ /g, "/")
.replace(/(print|enable|disable|add|set|remove|getall|move)$/, "")
.replace(/\/$/, "");
}
/**
* Get the current menu
*/
public getCurrentMenu(): string {
return this.pathVal;
}
/**
* Adds an item on the menu
*
* @param data the params that will be used to add the item
*/
public add(data: object): Types.SocPromise {
return this.exec("add", data).then((results: any) => {
if (results.length === 0) return Promise.resolve(null);
return this.recoverDataFromChangedItems(results.shift().ret);
});
}
/**
* Alias of add
*
* @param data the params that will be used to add the item
*/
public create(data: object): Types.SocPromise {
return this.add(data);
}
/**
* Disable one or more entries
*
* @param ids the id(s) or number(s) to disable
*/
public disable(ids?: Types.Id): Types.SocPromise {
if (ids) {
ids = this.stringfySearchQuery(ids);
this.queryVal.push("=numbers=" + ids);
}
let disabledIds = utils.lookForIdParameterAndReturnItsValue(this.queryVal);
return this.queryForIdsIfNeeded(disabledIds).then((ids: string) => {
disabledIds = ids;
return this.exec("disable");
}).then((response: any[]) => {
return this.recoverDataFromChangedItems(disabledIds);
});
}
/**
* Delete one or more entries
*
* @param ids the id(s) or number(s) to delete
*/
public delete(ids?: Types.Id): Types.SocPromise {
return this.remove(ids);
}
/**
* Enable one or more entries
*
* @param ids the id(s) or number(s) to enable
*/
public enable(ids?: Types.Id): Types.SocPromise {
if (ids) {
ids = this.stringfySearchQuery(ids);
this.queryVal.push("=numbers=" + ids);
}
let enabledIds = utils.lookForIdParameterAndReturnItsValue(this.queryVal);
return this.queryForIdsIfNeeded(enabledIds).then((ids: string) => {
enabledIds = ids;
return this.exec("enable");
}).then((response: any[]) => {
return this.recoverDataFromChangedItems(enabledIds);
});
}
/**
* Run a custom command over the api, for example "export"
*
* @param command the command to run
* @param data optional data that goes with the command
*/
public exec(command: string, data?: object): Types.SocPromise {
if (data) this.makeQuery(data);
const query = this.fullQuery("/" + command);
return this.translateQueryIntoId(query).then((consultedQuery) => {
return this.write(consultedQuery);
}).then((results) => {
// Only runs when using the place-after feature
// otherwise it will return the response immediately
return this.prepareToPlaceAfter(results);
});
}
/**
* Move a queried rule above another.
*
* @param to where to move the queried rule
*/
public moveAbove(to?: string): Types.SocPromise {
let movedIds = utils.lookForIdParameterAndReturnItsValue(this.queryVal);
return this.queryForIdsIfNeeded(movedIds).then((ids: string) => {
movedIds = ids;
if (to) this.queryVal.push("=destination=" + to);
return this.exec("move");
}).then(() => {
return this.recoverDataFromChangedItems(movedIds);
});
}
/**
* Update an entry or set of entries of the menu
*
* @param data the new data to update the item
* @param ids optional id(s) of the rules
*/
public update(data: object, ids?: Types.Id): Types.SocPromise {
if (ids) {
ids = this.stringfySearchQuery(ids);
this.queryVal.push("=numbers=" + ids);
}
let updatedIds = utils.lookForIdParameterAndReturnItsValue(this.queryVal);
return this.queryForIdsIfNeeded(updatedIds).then((ids: string) => {
updatedIds = ids;
this.makeQuery(data);
return this.exec("set");
}).then((response: any[]) => {
return this.recoverDataFromChangedItems(updatedIds);
});
}
/**
* Unset a property or set of properties of one or more entries
*
* @param properties one or more properties to unset
* @param ids the id(s) of the entries to unset the property(ies)
*/
public unset(properties: string | string[], ids?: Types.Id): Types.SocPromise {
if (ids) {
ids = this.stringfySearchQuery(ids);
this.queryVal.push("=numbers=" + ids);
}
let updatedIds = utils.lookForIdParameterAndReturnItsValue(this.queryVal);
return this.queryForIdsIfNeeded(updatedIds).then((ids: string) => {
updatedIds = ids;
if (typeof properties === "string") properties = [properties];
const $q: Types.SocPromise[] = [];
// Saving current queryVal for reuse, since running exec will reset it
const curQueryVal = this.queryVal.slice();
// Cleaning current queryVal to prevent duplication
this.queryVal = [];
properties.forEach((property) => {
// Putting back queryVal after a cleanup
this.queryVal = curQueryVal.slice();
this.queryVal.push("=value-name=" + utils.camelCaseOrSnakeCaseToDashedCase(property));
$q.push(this.exec("unset"));
});
return Promise.all($q);
}).then(() => {
return this.recoverDataFromChangedItems(updatedIds);
});
}
/**
* Removes an entry or set of entries of the menu
*
* @param ids optional id(s) to be removed from the menu
*/
public remove(ids?: any): Types.SocPromise {
if (ids) {
ids = this.stringfySearchQuery(ids);
this.queryVal.push("=numbers=" + ids);
}
const idsForRemoval = utils.lookForIdParameterAndReturnItsValue(this.queryVal);
let responseData;
return this.queryForIdsIfNeeded(idsForRemoval).then((ids: string) => {
return this.recoverDataFromChangedItems(ids);
}).then((response: any) => {
responseData = response;
return this.exec("remove");
}).then(() => {
return Promise.resolve(responseData);
});
}
/**
* Alias of update
*
* @param data the new data to update the item
* @param ids optional id(s) of the rules
*/
public set(data: object, ids?: Types.Id): Types.SocPromise {
return this.update(data, ids);
}
/**
* Alias of update
*
* @param data the new data to update the item
* @param ids optional id(s) of the rules
*/
public edit(data: object, ids?: Types.Id): Types.SocPromise {
return this.update(data, ids);
}
/**
* Moves a rule ABOVE the destination
*
* @param from the rule you want to move
* @param to the destination where you want to move
*/
protected moveEntry(from: Types.Id, to?: string | number): Types.SocPromise {
if (!Array.isArray(from)) from = [from];
from = this.stringfySearchQuery(from);
this.queryVal.push("=numbers=" + from);
if (to) {
to = this.stringfySearchQuery(to);
this.queryVal.push("=destination=" + to);
}
const movedIds = utils.lookForIdParameterAndReturnItsValue(this.queryVal);
return this.exec("move").then(() => {
return this.recoverDataFromChangedItems(movedIds);
});
}
/**
* Creates the full array of sentences that will be
* compatible with the raw API to be sent to the
* routerboard using all the functions triggered
* up until now
*
* @param append action to add in front of the menu
*/
protected fullQuery(append?: string): string[] {
let val = [];
if (append) {
val.push(this.pathVal + append);
} else {
val.push(this.pathVal);
}
if (this.proplistVal) val.push(this.proplistVal);
val = val.concat(this.queryVal).slice();
if (!/(print|getall)$/.test(val[0])) {
for (let index = 0; index < val.length; index++) {
val[index] = val[index].replace(/^\?/, "=");
}
}
return val;
}
/**
* Make the query array to write on the API,
* adding a question mark if it needs to print
* filtered content
*
* @param searchParameters The key-value pair to add to the search
*/
protected makeQuery(searchParameters: object, addQuestionMark: boolean = false, addToLocalQuery: boolean = true): string[] {
let tmpKey: string;
let tmpVal: string | number | boolean | null;
const tmpQuery = addToLocalQuery ? this.queryVal : [];
for (const key in searchParameters) {
if (searchParameters.hasOwnProperty(key)) {
tmpVal = searchParameters[key];
if (/[A-Z]/.test(tmpKey)) {
tmpKey = tmpKey.replace(/([A-Z])/g, "$1").toLowerCase();
}
tmpKey = key.replace(/_/, "-");
// if selecting for id, convert it to .id to match mikrotik standards
switch (tmpKey) {
case "id":
tmpKey = ".id";
break;
case "next":
tmpKey = ".nextid";
break;
case "dead":
tmpKey = ".dead";
break;
default:
break;
}
if (typeof tmpVal === "boolean") {
tmpVal = tmpVal ? "yes" : "no";
} else if (tmpVal === null) {
tmpVal = "";
} else if (typeof tmpVal === "object") {
tmpVal = this.stringfySearchQuery(tmpVal);
} else if (tmpKey === "placeAfter") {
this.placeAfter = tmpVal;
tmpKey = "placeBefore";
}
tmpKey = (addQuestionMark ? "?" : "=") + tmpKey;
tmpKey = utils.camelCaseOrSnakeCaseToDashedCase(tmpKey);
tmpQuery.push(tmpKey + "=" + tmpVal);
}
}
return tmpQuery;
}
/**
* Write the query using the raw API
*
* @param query the raw array of sentences to write on the socket
*/
protected write(query: string[]): Types.SocPromise {
this.queryVal = [];
this.proplistVal = "";
return this.rosApi.write(query).then((results) => {
return Promise.resolve(this.treatMikrotikProperties(results));
});
}
/**
* Translates .id, place-before and number without using internal
* mikrotik id (something like *4A).
*
* This should check if one of those parameters are an object
* and use that object to search the real id of the item.
*
* @param queries query array
*/
protected translateQueryIntoId(queries: string[]): Promise<any> {
if (queries.length === 0 || !this.needsObjectTranslation) return Promise.resolve(queries);
const promises = [];
const consultedIndexes = [];
for (const [index, element] of queries.entries()) {
const str = element.replace(/^\?/, "").replace(/^\=/, "");
if (str.includes(".id=") || str.includes("place-before=") || str.includes("place-after=") || str.includes("numbers=")) {
if (/\{.*\}/.test(str)) {
const key = str.split("=").shift();
const value = JSON.parse(str.split("=").pop());
const treatedQuery = [
this.pathVal + "/print",
"=.proplist=.id"
].concat(this.makeQuery(value, true, false));
const promise = this.rosApi.write(treatedQuery);
consultedIndexes.push({
index: index,
key: key
});
promises.push(promise);
}
}
}
return Promise.all(promises).then((results) => {
for (let result of results) {
if (Array.isArray(result)) result = result.shift();
const consulted = consultedIndexes.shift();
if (!result) return Promise.reject(new RosException("REFNOTFND", { key: consulted.key}));
if (consulted.key === "place-after") {
this.placeAfter = result[".id"];
consulted.key = "place-before";
}
queries[consulted.index] = "=" + consulted.key + "=" + result[".id"];
}
this.needsObjectTranslation = false;
return Promise.resolve(queries);
});
}
/**
* If the place-after feature was used, the rule below
* will be moved above here.
*
* @param results
*/
protected prepareToPlaceAfter(results): Promise<any> {
if (!this.placeAfter || results.length !== 1) return Promise.resolve(results);
if (!results[0].ret) return Promise.resolve(results);
const from = this.placeAfter;
const to = results[0].ret;
this.placeAfter = null;
return this.moveEntry(from, to).then(() => {
return Promise.resolve(results);
});
}
/**
* Transform mikrotik properties to either camelCase or snake_case
* and casts values of true or false to boolean and
* integer strings to number
*
* @param results the result set of an operation
*/
protected treatMikrotikProperties(results: object[]): object[] {
const treatedArr: object[] = [];
results.forEach((result) => {
const tmpItem = {
$$path: this.pathVal
};
for (const key in result) {
if (result.hasOwnProperty(key)) {
const tmpVal = result[key];
let tmpKey = this.snakeCase
? utils.dashedCaseToSnakeCase(key)
: utils.dashedCaseToCamelCase(key);
tmpKey = tmpKey.replace(/^\./, "");
tmpItem[tmpKey] = tmpVal;
if (tmpVal === "true" || tmpVal === "false") {
tmpItem[tmpKey] = tmpVal === "true";
} else if (/^\d+(\.\d+)?$/.test(tmpVal)) {
tmpItem[tmpKey] = parseFloat(tmpVal);
}
}
}
treatedArr.push(tmpItem);
});
return treatedArr;
}
/**
* Stringify a json formated object to be used later
* for a translation
*
* @param items object items to stringfy
*/
private stringfySearchQuery(items: any): any {
let isArray = true;
const newItems = [];
if (!Array.isArray(items)) {
isArray = false;
items = [items];
}
for (const item of items) {
if (typeof item === "object") {
this.needsObjectTranslation = true;
newItems.push(JSON.stringify(item));
} else newItems.push(item);
}
return isArray ? newItems : newItems.shift();
}
/**
* Clean data print of provided ids, used only when
* creating, editting or unsetting properties
*
* @param data
* @param ids
*/
private recoverDataFromChangedItems(ids?: string): Promise<any | any[]> {
if (!ids) {
return this.rosApi.write([this.pathVal + "/print"])
.then((data) => Promise.resolve(this.treatMikrotikProperties(data).shift()));
}
const promises = [];
const splittedIds = ids.split(",");
for (const id of splittedIds) {
const promise = this.rosApi.write([
this.pathVal + "/print",
"?.id=" + id
]);
promises.push(promise);
}
return Promise.all(promises).then((data) => {
if (!data) return Promise.resolve(data);
data = flatten(data);
data = this.treatMikrotikProperties(data);
if (!ids.includes(",")) return Promise.resolve(data.shift());
return Promise.resolve(data);
});
}
/**
* If trying do any action without providing any id, just
* a query. Find all their ids and return them
*
* @param ids
*/
private queryForIdsIfNeeded(ids?: string): Promise<string> {
if (ids) return Promise.resolve(ids);
this.queryVal.push("=.proplist=.id");
const query = this.fullQuery("/print");
let queriedIds;
return this.write(query).then((data: any[]) => {
data = reduce(data, (result, value, key) => {
result.push(value.id);
return result;
}, []);
queriedIds = data + "";
if (queriedIds) this.queryVal.push("=numbers=" + queriedIds);
return Promise.resolve(queriedIds);
});
}
} | the_stack |
import { GlobalProps } from 'ojs/ojvcomponent';
import { ComponentChildren } from 'preact';
import { DvtTimeComponentScale } from '../ojdvttimecomponentscale';
import { ojTimeAxis } from '../ojtimeaxis';
import Converter = require('../ojconverter');
import { KeySet } from '../ojkeyset';
import { DataProvider } from '../ojdataprovider';
import { dvtTimeComponent, dvtTimeComponentEventMap, dvtTimeComponentSettableProperties } from '../ojtime-base';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojGantt<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> extends dvtTimeComponent<ojGanttSettableProperties<K1, K2, D1, D2>> {
animationOnDataChange: 'auto' | 'none';
animationOnDisplay: 'auto' | 'none';
as: string;
axisPosition: 'bottom' | 'top';
dependencyData?: (DataProvider<K1, D1>);
dnd: {
move?: {
tasks?: 'disabled' | 'enabled';
};
};
dragMode: 'pan' | 'select';
end: string;
expanded: KeySet<K2>;
gridlines: {
horizontal?: 'hidden' | 'visible' | 'auto';
vertical?: 'hidden' | 'visible' | 'auto';
};
majorAxis: {
converter?: (ojTimeAxis.Converters | Converter<string>);
height?: number;
scale?: (string | DvtTimeComponentScale);
zoomOrder?: Array<string | DvtTimeComponentScale>;
};
minorAxis: {
converter?: (ojTimeAxis.Converters | Converter<string>);
height?: number;
scale?: (string | DvtTimeComponentScale);
zoomOrder?: Array<string | DvtTimeComponentScale>;
};
referenceObjects: ojGantt.ReferenceObject[];
rowAxis: {
label?: {
renderer: ((context: ojGantt.RowAxisLabelRendererContext<K2, D2>) => ({
insert: Element;
}));
};
maxWidth?: string;
rendered?: 'on' | 'off';
width?: string;
};
rowDefaults: {
height?: number;
};
scrollPosition: {
offsetY?: number;
rowIndex?: number;
y?: number;
};
selection: K2[];
selectionMode: 'none' | 'single' | 'multiple';
start: string;
taskData?: (DataProvider<K2, D2>);
taskDefaults: {
baseline?: {
borderRadius?: string;
height?: number;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
borderRadius?: string;
height?: number;
labelPosition?: (string | string[]);
overlap?: {
behavior?: 'stack' | 'stagger' | 'overlay' | 'auto';
offset?: number;
};
progress?: {
borderRadius?: string;
height?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
resizable?: 'disabled' | 'enabled';
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'normal' | 'milestone' | 'summary' | 'auto';
};
tooltip: {
renderer: ((context: ojGantt.TooltipContext<K2, D2>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
}));
};
valueFormats: {
baselineDate?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
baselineEnd?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
baselineStart?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
date?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
end?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
label?: {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
progress?: {
converter?: (Converter<number>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
row?: {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
start?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
};
viewportEnd: string;
viewportStart: string;
translations: {
accessibleDependencyInfo?: string;
accessiblePredecessorInfo?: string;
accessibleSuccessorInfo?: string;
accessibleTaskTypeMilestone?: string;
accessibleTaskTypeSummary?: string;
componentName?: string;
finishFinishDependencyAriaDesc?: string;
finishStartDependencyAriaDesc?: string;
labelAndValue?: string;
labelBaselineDate?: string;
labelBaselineEnd?: string;
labelBaselineStart?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelDate?: string;
labelEnd?: string;
labelInvalidData?: string;
labelLabel?: string;
labelLevel?: string;
labelMoveBy?: string;
labelNoData?: string;
labelProgress?: string;
labelResizeBy?: string;
labelRow?: string;
labelStart?: string;
startFinishDependencyAriaDesc?: string;
startStartDependencyAriaDesc?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
taskMoveCancelled?: string;
taskMoveFinalized?: string;
taskMoveInitiated?: string;
taskMoveInitiatedInstruction?: string;
taskMoveSelectionInfo?: string;
taskResizeCancelled?: string;
taskResizeEndHandle?: string;
taskResizeEndInitiated?: string;
taskResizeFinalized?: string;
taskResizeInitiatedInstruction?: string;
taskResizeSelectionInfo?: string;
taskResizeStartHandle?: string;
taskResizeStartInitiated?: string;
tooltipZoomIn?: string;
tooltipZoomOut?: string;
};
addEventListener<T extends keyof ojGanttEventMap<K1, K2, D1, D2>>(type: T, listener: (this: HTMLElement, ev: ojGanttEventMap<K1, K2, D1, D2>[T]) => any, options?: (boolean |
AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojGanttSettableProperties<K1, K2, D1, D2>>(property: T): ojGantt<K1, K2, D1, D2>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojGanttSettableProperties<K1, K2, D1, D2>>(property: T, value: ojGanttSettableProperties<K1, K2, D1, D2>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojGanttSettableProperties<K1, K2, D1, D2>>): void;
setProperties(properties: ojGanttSettablePropertiesLenient<K1, K2, D1, D2>): void;
getContextByNode(node: Element): {
subId: 'oj-gantt-row-label';
index: number;
} | {
subId: 'oj-gantt-taskbar';
rowIndex: number;
index: number;
} | null;
}
export namespace ojGantt {
interface ojMove<K2, D2> extends CustomEvent<{
baselineEnd: string;
baselineStart: string;
end: string;
rowContext: {
rowData: Row<K2>;
componentElement: Element;
};
start: string;
taskContexts: Array<{
data: RowTask<K2>;
rowData: Row<K2>;
itemData: D2 | null;
color: string;
}>;
value: string;
[propName: string]: any;
}> {
}
interface ojResize<K2, D2> extends CustomEvent<{
end: string;
start: string;
taskContexts: Array<{
data: RowTask<K2>;
rowData: Row<K2>;
itemData: D2 | null;
color: string;
}>;
type: string;
value: string;
[propName: string]: any;
}> {
}
interface ojViewportChange extends CustomEvent<{
majorAxisScale: string;
minorAxisScale: string;
viewportEnd: string;
viewportStart: string;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type axisPositionChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["axisPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type dependencyDataChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["dependencyData"]>;
// tslint:disable-next-line interface-over-type-literal
type dndChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["dnd"]>;
// tslint:disable-next-line interface-over-type-literal
type dragModeChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["dragMode"]>;
// tslint:disable-next-line interface-over-type-literal
type endChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["end"]>;
// tslint:disable-next-line interface-over-type-literal
type expandedChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["expanded"]>;
// tslint:disable-next-line interface-over-type-literal
type gridlinesChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["gridlines"]>;
// tslint:disable-next-line interface-over-type-literal
type majorAxisChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["majorAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type minorAxisChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["minorAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type referenceObjectsChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["referenceObjects"]>;
// tslint:disable-next-line interface-over-type-literal
type rowAxisChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["rowAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type rowDefaultsChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["rowDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type scrollPositionChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["scrollPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type startChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["start"]>;
// tslint:disable-next-line interface-over-type-literal
type taskDataChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["taskData"]>;
// tslint:disable-next-line interface-over-type-literal
type taskDefaultsChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["taskDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type valueFormatsChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["valueFormats"]>;
// tslint:disable-next-line interface-over-type-literal
type viewportEndChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["viewportEnd"]>;
// tslint:disable-next-line interface-over-type-literal
type viewportStartChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["viewportStart"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K1, K2, D1 extends Dependency<K1, K2> | any, D2 extends DataTask | any> = dvtTimeComponent.trackResizeChanged<ojGanttSettableProperties<K1, K2, D1, D2>>;
// tslint:disable-next-line interface-over-type-literal
type DataTask<K2 = any, D2 = any> = {
baseline?: {
borderRadius?: string;
end?: string;
height?: number;
start?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
borderRadius?: string;
end?: string;
height?: number;
label?: string;
labelPosition?: 'start' | 'innerCenter' | 'innerStart' | 'innerEnd' | 'end' | 'none';
labelStyle?: Partial<CSSStyleDeclaration>;
overlap?: {
behavior?: 'stack' | 'stagger' | 'overlay' | 'auto';
};
progress?: {
borderRadius?: string;
height?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value?: number;
};
rowId?: any;
shortDesc?: (string | ((context: TaskShortDescContext<K2, D2>) => string));
start?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'normal' | 'milestone' | 'summary' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type Dependency<K1, K2> = {
id: K1;
predecessorTaskId: K2;
shortDesc?: string;
successorTaskId: K2;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'finishStart' | 'finishFinish' | 'startStart' | 'startFinish';
};
// tslint:disable-next-line interface-over-type-literal
type DependencyContentTemplateContext<K1, K2, D1> = {
content: {
predecessorX: number;
predecessorY: number;
successorX: number;
successorY: number;
};
data: Dependency<K1, K2>;
itemData: D1;
state: {
focused: boolean;
hovered: boolean;
};
};
// tslint:disable-next-line interface-over-type-literal
type DependencyTemplateContext = {
componentElement: Element;
data: object;
index: number;
key: any;
};
// tslint:disable-next-line interface-over-type-literal
type ReferenceObject = {
end?: string;
shortDesc?: string;
start?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'area' | 'line';
value?: string;
};
// tslint:disable-next-line interface-over-type-literal
type Row<K2> = {
id?: any;
label?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
tasks?: Array<RowTask<K2>>;
};
// tslint:disable-next-line interface-over-type-literal
type RowAxisLabelRendererContext<K2, D2> = {
componentElement: Element;
itemData: D2[];
maxHeight: number;
maxWidth: number;
parentElement: Element;
rowData: Row<K2>;
};
// tslint:disable-next-line interface-over-type-literal
type RowTask<K2, D2 = any> = {
baseline?: {
borderRadius?: string;
end?: string;
height?: number;
start?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
borderRadius?: string;
end?: string;
height?: number;
id: K2;
label?: string;
labelPosition?: 'start' | 'innerCenter' | 'innerStart' | 'innerEnd' | 'end' | 'none';
labelStyle?: Partial<CSSStyleDeclaration>;
overlap?: {
behavior?: 'stack' | 'stagger' | 'overlay' | 'auto';
};
progress?: {
borderRadius?: string;
height?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value?: number;
};
shortDesc?: (string | ((context: TaskShortDescContext<K2, D2>) => string));
start?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'normal' | 'milestone' | 'summary' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type RowTemplateContext = {
componentElement: Element;
id: any;
index: number;
tasks: Array<{
data: object;
index: number;
key: any;
parentData: object[];
parentKey: any;
}>;
};
// tslint:disable-next-line interface-over-type-literal
type TaskContentTemplateContext<K2, D2> = {
content: {
height: number;
width: number;
};
data: RowTask<K2>;
itemData: D2;
rowData: Row<K2>;
state: {
expanded: boolean;
focused: boolean;
hovered: boolean;
selected: boolean;
};
};
// tslint:disable-next-line interface-over-type-literal
type TaskShortDescContext<K2, D2> = {
data: RowTask<K2, D2>;
itemData: D2;
rowData: Row<K2>;
};
// tslint:disable-next-line interface-over-type-literal
type TaskTemplateContext = {
componentElement: Element;
data: object;
index: number;
key: any;
parentData: object[];
parentKey: any;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K2, D2> = {
color: string;
componentElement: Element;
data: RowTask<K2>;
itemData: D2;
parentElement: Element;
rowData: Row<K2>;
};
}
export interface ojGanttEventMap<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> extends dvtTimeComponentEventMap<ojGanttSettableProperties<K1, K2, D1, D2>> {
'ojMove': ojGantt.ojMove<K2, D2>;
'ojResize': ojGantt.ojResize<K2, D2>;
'ojViewportChange': ojGantt.ojViewportChange;
'animationOnDataChangeChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["animationOnDataChange"]>;
'animationOnDisplayChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["animationOnDisplay"]>;
'asChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["as"]>;
'axisPositionChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["axisPosition"]>;
'dependencyDataChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["dependencyData"]>;
'dndChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["dnd"]>;
'dragModeChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["dragMode"]>;
'endChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["end"]>;
'expandedChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["expanded"]>;
'gridlinesChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["gridlines"]>;
'majorAxisChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["majorAxis"]>;
'minorAxisChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["minorAxis"]>;
'referenceObjectsChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["referenceObjects"]>;
'rowAxisChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["rowAxis"]>;
'rowDefaultsChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["rowDefaults"]>;
'scrollPositionChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["scrollPosition"]>;
'selectionChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["selectionMode"]>;
'startChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["start"]>;
'taskDataChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["taskData"]>;
'taskDefaultsChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["taskDefaults"]>;
'tooltipChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["tooltip"]>;
'valueFormatsChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["valueFormats"]>;
'viewportEndChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["viewportEnd"]>;
'viewportStartChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["viewportStart"]>;
'trackResizeChanged': JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["trackResize"]>;
}
export interface ojGanttSettableProperties<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> extends dvtTimeComponentSettableProperties {
animationOnDataChange: 'auto' | 'none';
animationOnDisplay: 'auto' | 'none';
as: string;
axisPosition: 'bottom' | 'top';
dependencyData?: (DataProvider<K1, D1>);
dnd: {
move?: {
tasks?: 'disabled' | 'enabled';
};
};
dragMode: 'pan' | 'select';
end: string;
expanded: KeySet<K2>;
gridlines: {
horizontal?: 'hidden' | 'visible' | 'auto';
vertical?: 'hidden' | 'visible' | 'auto';
};
majorAxis: {
converter?: (ojTimeAxis.Converters | Converter<string>);
height?: number;
scale?: (string | DvtTimeComponentScale);
zoomOrder?: Array<string | DvtTimeComponentScale>;
};
minorAxis: {
converter?: (ojTimeAxis.Converters | Converter<string>);
height?: number;
scale?: (string | DvtTimeComponentScale);
zoomOrder?: Array<string | DvtTimeComponentScale>;
};
referenceObjects: ojGantt.ReferenceObject[];
rowAxis: {
label?: {
renderer: ((context: ojGantt.RowAxisLabelRendererContext<K2, D2>) => ({
insert: Element;
}));
};
maxWidth?: string;
rendered?: 'on' | 'off';
width?: string;
};
rowDefaults: {
height?: number;
};
scrollPosition: {
offsetY?: number;
rowIndex?: number;
y?: number;
};
selection: K2[];
selectionMode: 'none' | 'single' | 'multiple';
start: string;
taskData?: (DataProvider<K2, D2>);
taskDefaults: {
baseline?: {
borderRadius?: string;
height?: number;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
borderRadius?: string;
height?: number;
labelPosition?: (string | string[]);
overlap?: {
behavior?: 'stack' | 'stagger' | 'overlay' | 'auto';
offset?: number;
};
progress?: {
borderRadius?: string;
height?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
resizable?: 'disabled' | 'enabled';
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'normal' | 'milestone' | 'summary' | 'auto';
};
tooltip: {
renderer: ((context: ojGantt.TooltipContext<K2, D2>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
}));
};
valueFormats: {
baselineDate?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
baselineEnd?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
baselineStart?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
date?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
end?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
label?: {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
progress?: {
converter?: (Converter<number>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
row?: {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
start?: {
converter?: (Converter<string>);
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
};
viewportEnd: string;
viewportStart: string;
translations: {
accessibleDependencyInfo?: string;
accessiblePredecessorInfo?: string;
accessibleSuccessorInfo?: string;
accessibleTaskTypeMilestone?: string;
accessibleTaskTypeSummary?: string;
componentName?: string;
finishFinishDependencyAriaDesc?: string;
finishStartDependencyAriaDesc?: string;
labelAndValue?: string;
labelBaselineDate?: string;
labelBaselineEnd?: string;
labelBaselineStart?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelDate?: string;
labelEnd?: string;
labelInvalidData?: string;
labelLabel?: string;
labelLevel?: string;
labelMoveBy?: string;
labelNoData?: string;
labelProgress?: string;
labelResizeBy?: string;
labelRow?: string;
labelStart?: string;
startFinishDependencyAriaDesc?: string;
startStartDependencyAriaDesc?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
taskMoveCancelled?: string;
taskMoveFinalized?: string;
taskMoveInitiated?: string;
taskMoveInitiatedInstruction?: string;
taskMoveSelectionInfo?: string;
taskResizeCancelled?: string;
taskResizeEndHandle?: string;
taskResizeEndInitiated?: string;
taskResizeFinalized?: string;
taskResizeInitiatedInstruction?: string;
taskResizeSelectionInfo?: string;
taskResizeStartHandle?: string;
taskResizeStartInitiated?: string;
tooltipZoomIn?: string;
tooltipZoomOut?: string;
};
}
export interface ojGanttSettablePropertiesLenient<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> extends Partial<ojGanttSettableProperties<K1, K2, D1, D2>> {
[key: string]: any;
}
export interface ojGanttDependency extends JetElement<ojGanttDependencySettableProperties> {
predecessorTaskId: any;
shortDesc?: string | null;
successorTaskId: any;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'finishStart' | 'finishFinish' | 'startStart' | 'startFinish';
addEventListener<T extends keyof ojGanttDependencyEventMap>(type: T, listener: (this: HTMLElement, ev: ojGanttDependencyEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojGanttDependencySettableProperties>(property: T): ojGanttDependency[T];
getProperty(property: string): any;
setProperty<T extends keyof ojGanttDependencySettableProperties>(property: T, value: ojGanttDependencySettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojGanttDependencySettableProperties>): void;
setProperties(properties: ojGanttDependencySettablePropertiesLenient): void;
}
export namespace ojGanttDependency {
// tslint:disable-next-line interface-over-type-literal
type predecessorTaskIdChanged = JetElementCustomEvent<ojGanttDependency["predecessorTaskId"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged = JetElementCustomEvent<ojGanttDependency["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type successorTaskIdChanged = JetElementCustomEvent<ojGanttDependency["successorTaskId"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged = JetElementCustomEvent<ojGanttDependency["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged = JetElementCustomEvent<ojGanttDependency["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type typeChanged = JetElementCustomEvent<ojGanttDependency["type"]>;
}
export interface ojGanttDependencyEventMap extends HTMLElementEventMap {
'predecessorTaskIdChanged': JetElementCustomEvent<ojGanttDependency["predecessorTaskId"]>;
'shortDescChanged': JetElementCustomEvent<ojGanttDependency["shortDesc"]>;
'successorTaskIdChanged': JetElementCustomEvent<ojGanttDependency["successorTaskId"]>;
'svgClassNameChanged': JetElementCustomEvent<ojGanttDependency["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojGanttDependency["svgStyle"]>;
'typeChanged': JetElementCustomEvent<ojGanttDependency["type"]>;
}
export interface ojGanttDependencySettableProperties extends JetSettableProperties {
predecessorTaskId: any;
shortDesc?: string | null;
successorTaskId: any;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'finishStart' | 'finishFinish' | 'startStart' | 'startFinish';
}
export interface ojGanttDependencySettablePropertiesLenient extends Partial<ojGanttDependencySettableProperties> {
[key: string]: any;
}
export interface ojGanttRow extends JetElement<ojGanttRowSettableProperties> {
label?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
addEventListener<T extends keyof ojGanttRowEventMap>(type: T, listener: (this: HTMLElement, ev: ojGanttRowEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojGanttRowSettableProperties>(property: T): ojGanttRow[T];
getProperty(property: string): any;
setProperty<T extends keyof ojGanttRowSettableProperties>(property: T, value: ojGanttRowSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojGanttRowSettableProperties>): void;
setProperties(properties: ojGanttRowSettablePropertiesLenient): void;
}
export namespace ojGanttRow {
// tslint:disable-next-line interface-over-type-literal
type labelChanged = JetElementCustomEvent<ojGanttRow["label"]>;
// tslint:disable-next-line interface-over-type-literal
type labelStyleChanged = JetElementCustomEvent<ojGanttRow["labelStyle"]>;
}
export interface ojGanttRowEventMap extends HTMLElementEventMap {
'labelChanged': JetElementCustomEvent<ojGanttRow["label"]>;
'labelStyleChanged': JetElementCustomEvent<ojGanttRow["labelStyle"]>;
}
export interface ojGanttRowSettableProperties extends JetSettableProperties {
label?: string;
labelStyle?: Partial<CSSStyleDeclaration>;
}
export interface ojGanttRowSettablePropertiesLenient extends Partial<ojGanttRowSettableProperties> {
[key: string]: any;
}
export interface ojGanttTask<K2 = any, D2 = any> extends dvtTimeComponent<ojGanttTaskSettableProperties<K2, D2>> {
baseline?: {
borderRadius?: string;
end?: string;
height?: number;
start?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
borderRadius?: string;
end?: string;
height?: number;
label?: string;
labelPosition?: 'start' | 'innerCenter' | 'innerStart' | 'innerEnd' | 'end' | 'none';
labelStyle?: Partial<CSSStyleDeclaration>;
overlap?: {
behavior?: 'stack' | 'stagger' | 'overlay' | 'auto';
};
progress?: {
borderRadius?: string;
height?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value?: number;
};
rowId?: any;
shortDesc?: (string | ((context: ojGantt.TaskShortDescContext<K2, D2>) => string));
start?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'normal' | 'milestone' | 'summary' | 'auto';
addEventListener<T extends keyof ojGanttTaskEventMap<K2, D2>>(type: T, listener: (this: HTMLElement, ev: ojGanttTaskEventMap<K2, D2>[T]) => any, options?: (boolean |
AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojGanttTaskSettableProperties<K2, D2>>(property: T): ojGanttTask<K2, D2>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojGanttTaskSettableProperties<K2, D2>>(property: T, value: ojGanttTaskSettableProperties<K2, D2>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojGanttTaskSettableProperties<K2, D2>>): void;
setProperties(properties: ojGanttTaskSettablePropertiesLenient<K2, D2>): void;
}
export namespace ojGanttTask {
// tslint:disable-next-line interface-over-type-literal
type baselineChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["baseline"]>;
// tslint:disable-next-line interface-over-type-literal
type borderRadiusChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["borderRadius"]>;
// tslint:disable-next-line interface-over-type-literal
type endChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["end"]>;
// tslint:disable-next-line interface-over-type-literal
type heightChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["height"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type labelPositionChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["labelPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type labelStyleChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["labelStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type overlapChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["overlap"]>;
// tslint:disable-next-line interface-over-type-literal
type progressChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["progress"]>;
// tslint:disable-next-line interface-over-type-literal
type rowIdChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["rowId"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type startChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["start"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type typeChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["type"]>;
}
export interface ojGanttTaskEventMap<K2 = any, D2 = any> extends dvtTimeComponentEventMap<ojGanttTaskSettableProperties<K2, D2>> {
'baselineChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["baseline"]>;
'borderRadiusChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["borderRadius"]>;
'endChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["end"]>;
'heightChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["height"]>;
'labelChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["label"]>;
'labelPositionChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["labelPosition"]>;
'labelStyleChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["labelStyle"]>;
'overlapChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["overlap"]>;
'progressChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["progress"]>;
'rowIdChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["rowId"]>;
'shortDescChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["shortDesc"]>;
'startChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["start"]>;
'svgClassNameChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["svgStyle"]>;
'typeChanged': JetElementCustomEvent<ojGanttTask<K2, D2>["type"]>;
}
export interface ojGanttTaskSettableProperties<K2 = any, D2 = any> extends dvtTimeComponentSettableProperties {
baseline?: {
borderRadius?: string;
end?: string;
height?: number;
start?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
borderRadius?: string;
end?: string;
height?: number;
label?: string;
labelPosition?: 'start' | 'innerCenter' | 'innerStart' | 'innerEnd' | 'end' | 'none';
labelStyle?: Partial<CSSStyleDeclaration>;
overlap?: {
behavior?: 'stack' | 'stagger' | 'overlay' | 'auto';
};
progress?: {
borderRadius?: string;
height?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value?: number;
};
rowId?: any;
shortDesc?: (string | ((context: ojGantt.TaskShortDescContext<K2, D2>) => string));
start?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'normal' | 'milestone' | 'summary' | 'auto';
}
export interface ojGanttTaskSettablePropertiesLenient<K2 = any, D2 = any> extends Partial<ojGanttTaskSettableProperties<K2, D2>> {
[key: string]: any;
}
export type GanttElement<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = ojGantt<K1, K2, D1, D2>;
export type GanttDependencyElement = ojGanttDependency;
export type GanttRowElement = ojGanttRow;
export type GanttTaskElement<K2 = any, D2 = any> = ojGanttTask<K2>;
export namespace GanttElement {
interface ojMove<K2, D2> extends CustomEvent<{
baselineEnd: string;
baselineStart: string;
end: string;
rowContext: {
rowData: ojGantt.Row<K2>;
componentElement: Element;
};
start: string;
taskContexts: Array<{
data: ojGantt.RowTask<K2>;
rowData: ojGantt.Row<K2>;
itemData: D2 | null;
color: string;
}>;
value: string;
[propName: string]: any;
}> {
}
interface ojResize<K2, D2> extends CustomEvent<{
end: string;
start: string;
taskContexts: Array<{
data: ojGantt.RowTask<K2>;
rowData: ojGantt.Row<K2>;
itemData: D2 | null;
color: string;
}>;
type: string;
value: string;
[propName: string]: any;
}> {
}
interface ojViewportChange extends CustomEvent<{
majorAxisScale: string;
minorAxisScale: string;
viewportEnd: string;
viewportStart: string;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type axisPositionChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["axisPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type dependencyDataChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["dependencyData"]>;
// tslint:disable-next-line interface-over-type-literal
type dndChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["dnd"]>;
// tslint:disable-next-line interface-over-type-literal
type dragModeChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["dragMode"]>;
// tslint:disable-next-line interface-over-type-literal
type endChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["end"]>;
// tslint:disable-next-line interface-over-type-literal
type expandedChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["expanded"]>;
// tslint:disable-next-line interface-over-type-literal
type gridlinesChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["gridlines"]>;
// tslint:disable-next-line interface-over-type-literal
type majorAxisChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["majorAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type minorAxisChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["minorAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type referenceObjectsChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["referenceObjects"]>;
// tslint:disable-next-line interface-over-type-literal
type rowAxisChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["rowAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type rowDefaultsChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["rowDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type scrollPositionChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["scrollPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type startChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["start"]>;
// tslint:disable-next-line interface-over-type-literal
type taskDataChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["taskData"]>;
// tslint:disable-next-line interface-over-type-literal
type taskDefaultsChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["taskDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type valueFormatsChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["valueFormats"]>;
// tslint:disable-next-line interface-over-type-literal
type viewportEndChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["viewportEnd"]>;
// tslint:disable-next-line interface-over-type-literal
type viewportStartChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = JetElementCustomEvent<ojGantt<K1, K2, D1, D2>["viewportStart"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K1, K2, D1 extends ojGantt.Dependency<K1, K2> | any, D2 extends ojGantt.DataTask | any> = dvtTimeComponent.trackResizeChanged<ojGanttSettableProperties<K1, K2, D1, D2>>;
// tslint:disable-next-line interface-over-type-literal
type DataTask<K2 = any, D2 = any> = {
baseline?: {
borderRadius?: string;
end?: string;
height?: number;
start?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
borderRadius?: string;
end?: string;
height?: number;
label?: string;
labelPosition?: 'start' | 'innerCenter' | 'innerStart' | 'innerEnd' | 'end' | 'none';
labelStyle?: Partial<CSSStyleDeclaration>;
overlap?: {
behavior?: 'stack' | 'stagger' | 'overlay' | 'auto';
};
progress?: {
borderRadius?: string;
height?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value?: number;
};
rowId?: any;
shortDesc?: (string | ((context: ojGantt.TaskShortDescContext<K2, D2>) => string));
start?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'normal' | 'milestone' | 'summary' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type DependencyContentTemplateContext<K1, K2, D1> = {
content: {
predecessorX: number;
predecessorY: number;
successorX: number;
successorY: number;
};
data: ojGantt.Dependency<K1, K2>;
itemData: D1;
state: {
focused: boolean;
hovered: boolean;
};
};
// tslint:disable-next-line interface-over-type-literal
type ReferenceObject = {
end?: string;
shortDesc?: string;
start?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'area' | 'line';
value?: string;
};
// tslint:disable-next-line interface-over-type-literal
type RowAxisLabelRendererContext<K2, D2> = {
componentElement: Element;
itemData: D2[];
maxHeight: number;
maxWidth: number;
parentElement: Element;
rowData: ojGantt.Row<K2>;
};
// tslint:disable-next-line interface-over-type-literal
type RowTemplateContext = {
componentElement: Element;
id: any;
index: number;
tasks: Array<{
data: object;
index: number;
key: any;
parentData: object[];
parentKey: any;
}>;
};
// tslint:disable-next-line interface-over-type-literal
type TaskShortDescContext<K2, D2> = {
data: ojGantt.RowTask<K2, D2>;
itemData: D2;
rowData: ojGantt.Row<K2>;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K2, D2> = {
color: string;
componentElement: Element;
data: ojGantt.RowTask<K2>;
itemData: D2;
parentElement: Element;
rowData: ojGantt.Row<K2>;
};
}
export namespace GanttDependencyElement {
// tslint:disable-next-line interface-over-type-literal
type predecessorTaskIdChanged = JetElementCustomEvent<ojGanttDependency["predecessorTaskId"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged = JetElementCustomEvent<ojGanttDependency["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type successorTaskIdChanged = JetElementCustomEvent<ojGanttDependency["successorTaskId"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged = JetElementCustomEvent<ojGanttDependency["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged = JetElementCustomEvent<ojGanttDependency["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type typeChanged = JetElementCustomEvent<ojGanttDependency["type"]>;
}
export namespace GanttRowElement {
// tslint:disable-next-line interface-over-type-literal
type labelChanged = JetElementCustomEvent<ojGanttRow["label"]>;
// tslint:disable-next-line interface-over-type-literal
type labelStyleChanged = JetElementCustomEvent<ojGanttRow["labelStyle"]>;
}
export namespace GanttTaskElement {
// tslint:disable-next-line interface-over-type-literal
type baselineChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["baseline"]>;
// tslint:disable-next-line interface-over-type-literal
type borderRadiusChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["borderRadius"]>;
// tslint:disable-next-line interface-over-type-literal
type endChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["end"]>;
// tslint:disable-next-line interface-over-type-literal
type heightChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["height"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type labelPositionChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["labelPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type labelStyleChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["labelStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type overlapChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["overlap"]>;
// tslint:disable-next-line interface-over-type-literal
type progressChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["progress"]>;
// tslint:disable-next-line interface-over-type-literal
type rowIdChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["rowId"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type startChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["start"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type typeChanged<K2 = any, D2 = any> = JetElementCustomEvent<ojGanttTask<K2, D2>["type"]>;
}
export interface GanttIntrinsicProps extends Partial<Readonly<ojGanttSettableProperties<any, any, any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onojMove?: (value: ojGanttEventMap<any, any, any, any>['ojMove']) => void;
onojResize?: (value: ojGanttEventMap<any, any, any, any>['ojResize']) => void;
onojViewportChange?: (value: ojGanttEventMap<any, any, any, any>['ojViewportChange']) => void;
onanimationOnDataChangeChanged?: (value: ojGanttEventMap<any, any, any, any>['animationOnDataChangeChanged']) => void;
onanimationOnDisplayChanged?: (value: ojGanttEventMap<any, any, any, any>['animationOnDisplayChanged']) => void;
onasChanged?: (value: ojGanttEventMap<any, any, any, any>['asChanged']) => void;
onaxisPositionChanged?: (value: ojGanttEventMap<any, any, any, any>['axisPositionChanged']) => void;
ondependencyDataChanged?: (value: ojGanttEventMap<any, any, any, any>['dependencyDataChanged']) => void;
ondndChanged?: (value: ojGanttEventMap<any, any, any, any>['dndChanged']) => void;
ondragModeChanged?: (value: ojGanttEventMap<any, any, any, any>['dragModeChanged']) => void;
onendChanged?: (value: ojGanttEventMap<any, any, any, any>['endChanged']) => void;
onexpandedChanged?: (value: ojGanttEventMap<any, any, any, any>['expandedChanged']) => void;
ongridlinesChanged?: (value: ojGanttEventMap<any, any, any, any>['gridlinesChanged']) => void;
onmajorAxisChanged?: (value: ojGanttEventMap<any, any, any, any>['majorAxisChanged']) => void;
onminorAxisChanged?: (value: ojGanttEventMap<any, any, any, any>['minorAxisChanged']) => void;
onreferenceObjectsChanged?: (value: ojGanttEventMap<any, any, any, any>['referenceObjectsChanged']) => void;
onrowAxisChanged?: (value: ojGanttEventMap<any, any, any, any>['rowAxisChanged']) => void;
onrowDefaultsChanged?: (value: ojGanttEventMap<any, any, any, any>['rowDefaultsChanged']) => void;
onscrollPositionChanged?: (value: ojGanttEventMap<any, any, any, any>['scrollPositionChanged']) => void;
onselectionChanged?: (value: ojGanttEventMap<any, any, any, any>['selectionChanged']) => void;
onselectionModeChanged?: (value: ojGanttEventMap<any, any, any, any>['selectionModeChanged']) => void;
onstartChanged?: (value: ojGanttEventMap<any, any, any, any>['startChanged']) => void;
ontaskDataChanged?: (value: ojGanttEventMap<any, any, any, any>['taskDataChanged']) => void;
ontaskDefaultsChanged?: (value: ojGanttEventMap<any, any, any, any>['taskDefaultsChanged']) => void;
ontooltipChanged?: (value: ojGanttEventMap<any, any, any, any>['tooltipChanged']) => void;
onvalueFormatsChanged?: (value: ojGanttEventMap<any, any, any, any>['valueFormatsChanged']) => void;
onviewportEndChanged?: (value: ojGanttEventMap<any, any, any, any>['viewportEndChanged']) => void;
onviewportStartChanged?: (value: ojGanttEventMap<any, any, any, any>['viewportStartChanged']) => void;
ontrackResizeChanged?: (value: ojGanttEventMap<any, any, any, any>['trackResizeChanged']) => void;
children?: ComponentChildren;
}
export interface GanttDependencyIntrinsicProps extends Partial<Readonly<ojGanttDependencySettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onpredecessorTaskIdChanged?: (value: ojGanttDependencyEventMap['predecessorTaskIdChanged']) => void;
onshortDescChanged?: (value: ojGanttDependencyEventMap['shortDescChanged']) => void;
onsuccessorTaskIdChanged?: (value: ojGanttDependencyEventMap['successorTaskIdChanged']) => void;
onsvgClassNameChanged?: (value: ojGanttDependencyEventMap['svgClassNameChanged']) => void;
onsvgStyleChanged?: (value: ojGanttDependencyEventMap['svgStyleChanged']) => void;
ontypeChanged?: (value: ojGanttDependencyEventMap['typeChanged']) => void;
children?: ComponentChildren;
}
export interface GanttRowIntrinsicProps extends Partial<Readonly<ojGanttRowSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onlabelChanged?: (value: ojGanttRowEventMap['labelChanged']) => void;
onlabelStyleChanged?: (value: ojGanttRowEventMap['labelStyleChanged']) => void;
children?: ComponentChildren;
}
export interface GanttTaskIntrinsicProps extends Partial<Readonly<ojGanttTaskSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onbaselineChanged?: (value: ojGanttTaskEventMap<any>['baselineChanged']) => void;
onborderRadiusChanged?: (value: ojGanttTaskEventMap<any>['borderRadiusChanged']) => void;
onendChanged?: (value: ojGanttTaskEventMap<any>['endChanged']) => void;
onheightChanged?: (value: ojGanttTaskEventMap<any>['heightChanged']) => void;
onlabelChanged?: (value: ojGanttTaskEventMap<any>['labelChanged']) => void;
onlabelPositionChanged?: (value: ojGanttTaskEventMap<any>['labelPositionChanged']) => void;
onlabelStyleChanged?: (value: ojGanttTaskEventMap<any>['labelStyleChanged']) => void;
onoverlapChanged?: (value: ojGanttTaskEventMap<any>['overlapChanged']) => void;
onprogressChanged?: (value: ojGanttTaskEventMap<any>['progressChanged']) => void;
onrowIdChanged?: (value: ojGanttTaskEventMap<any>['rowIdChanged']) => void;
onshortDescChanged?: (value: ojGanttTaskEventMap<any>['shortDescChanged']) => void;
onstartChanged?: (value: ojGanttTaskEventMap<any>['startChanged']) => void;
onsvgClassNameChanged?: (value: ojGanttTaskEventMap<any>['svgClassNameChanged']) => void;
onsvgStyleChanged?: (value: ojGanttTaskEventMap<any>['svgStyleChanged']) => void;
ontypeChanged?: (value: ojGanttTaskEventMap<any>['typeChanged']) => void;
children?: ComponentChildren;
}
declare global {
namespace preact.JSX {
interface IntrinsicElements {
"oj-gantt": GanttIntrinsicProps;
"oj-gantt-dependency": GanttDependencyIntrinsicProps;
"oj-gantt-row": GanttRowIntrinsicProps;
"oj-gantt-task": GanttTaskIntrinsicProps;
}
}
} | the_stack |
import { ToneWithContext, ToneWithContextOptions } from "../context/ToneWithContext";
import { Seconds, Ticks, Time } from "../type/Units";
import { optionsFromArguments } from "../util/Defaults";
import { readOnly } from "../util/Interface";
import { PlaybackState, StateTimeline, StateTimelineEvent } from "../util/StateTimeline";
import { Timeline } from "../util/Timeline";
import { isDefined } from "../util/TypeCheck";
import { TickSignal } from "./TickSignal";
import { EQ } from "../util/Math";
interface TickSourceOptions extends ToneWithContextOptions {
frequency: number;
units: "bpm" | "hertz";
}
interface TickSourceOffsetEvent {
ticks: number;
time: number;
seconds: number;
}
/**
* Uses [TickSignal](TickSignal) to track elapsed ticks with complex automation curves.
*/
export class TickSource<TypeName extends "bpm" | "hertz"> extends ToneWithContext<TickSourceOptions> {
readonly name: string = "TickSource";
/**
* The frequency the callback function should be invoked.
*/
readonly frequency: TickSignal<TypeName>;
/**
* The state timeline
*/
private _state: StateTimeline = new StateTimeline();
/**
* The offset values of the ticks
*/
private _tickOffset: Timeline<TickSourceOffsetEvent> = new Timeline();
/**
* @param frequency The initial frequency that the signal ticks at
*/
constructor(frequency?: number);
constructor(options?: Partial<TickSourceOptions>);
constructor() {
super(optionsFromArguments(TickSource.getDefaults(), arguments, ["frequency"]));
const options = optionsFromArguments(TickSource.getDefaults(), arguments, ["frequency"]);
this.frequency = new TickSignal({
context: this.context,
units: options.units as TypeName,
value: options.frequency,
});
readOnly(this, "frequency");
// set the initial state
this._state.setStateAtTime("stopped", 0);
// add the first event
this.setTicksAtTime(0, 0);
}
static getDefaults(): TickSourceOptions {
return Object.assign({
frequency: 1,
units: "hertz" as const,
}, ToneWithContext.getDefaults());
}
/**
* Returns the playback state of the source, either "started", "stopped" or "paused".
*/
get state(): PlaybackState {
return this.getStateAtTime(this.now());
}
/**
* Start the clock at the given time. Optionally pass in an offset
* of where to start the tick counter from.
* @param time The time the clock should start
* @param offset The number of ticks to start the source at
*/
start(time: Time, offset?: Ticks): this {
const computedTime = this.toSeconds(time);
if (this._state.getValueAtTime(computedTime) !== "started") {
this._state.setStateAtTime("started", computedTime);
if (isDefined(offset)) {
this.setTicksAtTime(offset, computedTime);
}
}
return this;
}
/**
* Stop the clock. Stopping the clock resets the tick counter to 0.
* @param time The time when the clock should stop.
*/
stop(time: Time): this {
const computedTime = this.toSeconds(time);
// cancel the previous stop
if (this._state.getValueAtTime(computedTime) === "stopped") {
const event = this._state.get(computedTime);
if (event && event.time > 0) {
this._tickOffset.cancel(event.time);
this._state.cancel(event.time);
}
}
this._state.cancel(computedTime);
this._state.setStateAtTime("stopped", computedTime);
this.setTicksAtTime(0, computedTime);
return this;
}
/**
* Pause the clock. Pausing does not reset the tick counter.
* @param time The time when the clock should stop.
*/
pause(time: Time): this {
const computedTime = this.toSeconds(time);
if (this._state.getValueAtTime(computedTime) === "started") {
this._state.setStateAtTime("paused", computedTime);
}
return this;
}
/**
* Cancel start/stop/pause and setTickAtTime events scheduled after the given time.
* @param time When to clear the events after
*/
cancel(time: Time): this {
time = this.toSeconds(time);
this._state.cancel(time);
this._tickOffset.cancel(time);
return this;
}
/**
* Get the elapsed ticks at the given time
* @param time When to get the tick value
* @return The number of ticks
*/
getTicksAtTime(time?: Time): Ticks {
const computedTime = this.toSeconds(time);
const stopEvent = this._state.getLastState("stopped", computedTime) as StateTimelineEvent;
// this event allows forEachBetween to iterate until the current time
const tmpEvent: StateTimelineEvent = { state: "paused", time: computedTime };
this._state.add(tmpEvent);
// keep track of the previous offset event
let lastState = stopEvent;
let elapsedTicks = 0;
// iterate through all the events since the last stop
this._state.forEachBetween(stopEvent.time, computedTime + this.sampleTime, e => {
let periodStartTime = lastState.time;
// if there is an offset event in this period use that
const offsetEvent = this._tickOffset.get(e.time);
if (offsetEvent && offsetEvent.time >= lastState.time) {
elapsedTicks = offsetEvent.ticks;
periodStartTime = offsetEvent.time;
}
if (lastState.state === "started" && e.state !== "started") {
elapsedTicks += this.frequency.getTicksAtTime(e.time) - this.frequency.getTicksAtTime(periodStartTime);
}
lastState = e;
});
// remove the temporary event
this._state.remove(tmpEvent);
// return the ticks
return elapsedTicks;
}
/**
* The number of times the callback was invoked. Starts counting at 0
* and increments after the callback was invoked. Returns -1 when stopped.
*/
get ticks(): Ticks {
return this.getTicksAtTime(this.now());
}
set ticks(t: Ticks) {
this.setTicksAtTime(t, this.now());
}
/**
* The time since ticks=0 that the TickSource has been running. Accounts
* for tempo curves
*/
get seconds(): Seconds {
return this.getSecondsAtTime(this.now());
}
set seconds(s: Seconds) {
const now = this.now();
const ticks = this.frequency.timeToTicks(s, now);
this.setTicksAtTime(ticks, now);
}
/**
* Return the elapsed seconds at the given time.
* @param time When to get the elapsed seconds
* @return The number of elapsed seconds
*/
getSecondsAtTime(time: Time): Seconds {
time = this.toSeconds(time);
const stopEvent = this._state.getLastState("stopped", time) as StateTimelineEvent;
// this event allows forEachBetween to iterate until the current time
const tmpEvent: StateTimelineEvent = { state: "paused", time };
this._state.add(tmpEvent);
// keep track of the previous offset event
let lastState = stopEvent;
let elapsedSeconds = 0;
// iterate through all the events since the last stop
this._state.forEachBetween(stopEvent.time, time + this.sampleTime, e => {
let periodStartTime = lastState.time;
// if there is an offset event in this period use that
const offsetEvent = this._tickOffset.get(e.time);
if (offsetEvent && offsetEvent.time >= lastState.time) {
elapsedSeconds = offsetEvent.seconds;
periodStartTime = offsetEvent.time;
}
if (lastState.state === "started" && e.state !== "started") {
elapsedSeconds += e.time - periodStartTime;
}
lastState = e;
});
// remove the temporary event
this._state.remove(tmpEvent);
// return the ticks
return elapsedSeconds;
}
/**
* Set the clock's ticks at the given time.
* @param ticks The tick value to set
* @param time When to set the tick value
*/
setTicksAtTime(ticks: Ticks, time: Time): this {
time = this.toSeconds(time);
this._tickOffset.cancel(time);
this._tickOffset.add({
seconds: this.frequency.getDurationOfTicks(ticks, time),
ticks,
time,
});
return this;
}
/**
* Returns the scheduled state at the given time.
* @param time The time to query.
*/
getStateAtTime(time: Time): PlaybackState {
time = this.toSeconds(time);
return this._state.getValueAtTime(time);
}
/**
* Get the time of the given tick. The second argument
* is when to test before. Since ticks can be set (with setTicksAtTime)
* there may be multiple times for a given tick value.
* @param tick The tick number.
* @param before When to measure the tick value from.
* @return The time of the tick
*/
getTimeOfTick(tick: Ticks, before = this.now()): Seconds {
const offset = this._tickOffset.get(before) as TickSourceOffsetEvent;
const event = this._state.get(before) as StateTimelineEvent;
const startTime = Math.max(offset.time, event.time);
const absoluteTicks = this.frequency.getTicksAtTime(startTime) + tick - offset.ticks;
return this.frequency.getTimeOfTick(absoluteTicks);
}
/**
* Invoke the callback event at all scheduled ticks between the
* start time and the end time
* @param startTime The beginning of the search range
* @param endTime The end of the search range
* @param callback The callback to invoke with each tick
*/
forEachTickBetween(startTime: number, endTime: number, callback: (when: Seconds, ticks: Ticks) => void): this {
// only iterate through the sections where it is "started"
let lastStateEvent = this._state.get(startTime);
this._state.forEachBetween(startTime, endTime, event => {
if (lastStateEvent && lastStateEvent.state === "started" && event.state !== "started") {
this.forEachTickBetween(Math.max(lastStateEvent.time, startTime), event.time - this.sampleTime, callback);
}
lastStateEvent = event;
});
let error: Error | null = null;
if (lastStateEvent && lastStateEvent.state === "started") {
const maxStartTime = Math.max(lastStateEvent.time, startTime);
// figure out the difference between the frequency ticks and the
const startTicks = this.frequency.getTicksAtTime(maxStartTime);
const ticksAtStart = this.frequency.getTicksAtTime(lastStateEvent.time);
const diff = startTicks - ticksAtStart;
let offset = Math.ceil(diff) - diff;
// guard against floating point issues
offset = EQ(offset, 1) ? 0 : offset;
let nextTickTime = this.frequency.getTimeOfTick(startTicks + offset);
while (nextTickTime < endTime) {
try {
callback(nextTickTime, Math.round(this.getTicksAtTime(nextTickTime)));
} catch (e) {
error = e;
break;
}
nextTickTime += this.frequency.getDurationOfTicks(1, nextTickTime);
}
}
if (error) {
throw error;
}
return this;
}
/**
* Clean up
*/
dispose(): this {
super.dispose();
this._state.dispose();
this._tickOffset.dispose();
this.frequency.dispose();
return this;
}
} | the_stack |
import { writeFileSync } from 'fs';
import { join, relative, resolve } from 'path';
import { Feed } from 'feed';
import type {
BuildArgs,
CreateNodeArgs,
CreatePagesArgs,
CreateResolversArgs,
Node,
} from 'gatsby';
// Note: we need to use relative paths here because app-module-path causes WebPack 5 to throw
// PackFileCacheStrategy/FileSystemInfo warnings. Even though the overall build works.
import type { PostType } from 'src/types/Post';
import type { AllDataQueryType, AllPostsQueryType } from 'src/types/queries';
import { appendToLastTextBlock } from './src/util/appendToLastTextBlock';
import { fixLocalLinks } from './src/util/fixLocalLinks';
import { getPreFoldContent } from './src/util/getPreFoldContent';
import { getTagCounts } from './src/util/getTagCounts';
import { prune } from './src/util/prune';
import { removeTags } from './src/util/removeTags';
const POST_COUNT_FOR_FEEDS = 20;
const RECENT_COUNT_FOR_SYNDICATION = 10;
const TAG_POSTS_WITH_HTML_PREVIEW = 5;
type RawAllPostsQueryType = {
errors?: Array<Error>;
data?: AllPostsQueryType;
};
type RawAllDataType = {
errors?: Array<Error>;
data?: AllDataQueryType;
};
// We would like to use the official GatsbyNode type here, but the onCreateNode typings
// are forcing the node parameter type to {}, causing problems for us when we give it
// a real type.
// https://github.com/gatsbyjs/gatsby/blob/54e3d7ae24924215ae9e0976b89e185159d9e38f/packages/gatsby/index.d.ts#L284-L288
type NodeType = Node & {
frontmatter?: {
path: string;
};
};
function getHTMLPreview(html: string, slug: string): string {
const preFold = getPreFoldContent(html);
if (!preFold) {
throw new Error('getHTMLPreview: Missing pre-fold content!');
}
const textLink = ` <a href="${slug}">Read more »</a>`;
return appendToLastTextBlock(preFold, textLink);
}
const MAX_TEXT_PREVIEW = 200;
function getTextPreview(html: string) {
const preFold = getPreFoldContent(html);
if (!preFold) {
throw new Error('getTextPreview: Missing pre-fold content!');
}
const noTags = removeTags(preFold);
if (!noTags) {
throw new Error(`getTextPreview: No tags returned for html: ${preFold}`);
}
return prune(noTags, MAX_TEXT_PREVIEW);
}
const gatsbyNode = {
createPages: async ({ graphql, actions }: CreatePagesArgs): Promise<void> => {
const { createPage } = actions;
const blogPostPage = resolve('./src/dynamic-pages/post.tsx');
const tagPage = resolve('./src/dynamic-pages/tag.tsx');
const result: RawAllPostsQueryType = await graphql(
`
{
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
edges {
node {
htmlPreview
textPreview
fields {
slug
}
frontmatter {
date
tags
title
path
}
}
}
}
}
`
);
if (result.errors?.length) {
throw result.errors[0] ?? new Error('Something went wrong!');
}
if (!result.data) {
console.error('Query results malformed', result);
throw new Error('Query returned no data!');
}
// Create a page for each blog post
const posts = result.data.allMarkdownRemark.edges.map(item => item.node);
posts.forEach((post, index) => {
const next = index === 0 ? null : posts[index - 1];
const previous = index === posts.length - 1 ? null : posts[index + 1];
const path = post.fields?.slug;
if (!path) {
throw new Error(`Page had missing slug: ${JSON.stringify(post)}`);
}
createPage({
path,
component: blogPostPage,
context: {
slug: path,
previous: previous && {
...previous,
htmlPreview: undefined,
},
next: next && {
...next,
htmlPreview: undefined,
},
},
});
});
// Create a page for each tag
const tagCounts = getTagCounts(posts);
tagCounts.forEach(({ tag }) => {
if (!tag) {
return;
}
const postsWithTag = posts.filter(post => post.frontmatter?.tags?.includes(tag));
const withText: Array<PostType> = [];
const justLink: Array<PostType> = [];
// By removing some of this data, we can reduce the size of the page-data.json for
// this page.
postsWithTag.forEach((post, index) => {
if (index <= TAG_POSTS_WITH_HTML_PREVIEW) {
withText.push({
...post,
htmlPreview: undefined,
});
} else {
justLink.push({
...post,
htmlPreview: undefined,
textPreview: undefined,
});
}
});
createPage({
path: `/tags/${tag}`,
component: tagPage,
context: {
tag,
withText,
justLink,
},
});
});
},
// This is the easy way to add fields to a given GrapnQL node.
// Note: values generated here are persisted in Gatsby's build cache, so it should be
// reserved for values that don't change very often. If you make a change here while
// running 'yarn develop', you'll need to both shut down and `yarn clean` before it
// will show up.
onCreateNode: ({ node, actions }: CreateNodeArgs<NodeType>): void => {
const { createNodeField } = actions;
if (node.internal.type === 'MarkdownRemark') {
const slug: string | undefined = node.frontmatter?.path;
if (!slug) {
throw new Error(`Post was missing path: ${JSON.stringify(node)}`);
}
createNodeField({
name: 'slug',
node,
value: slug,
});
const absolutePath = node['fileAbsolutePath'];
if (typeof absolutePath !== 'string') {
throw new Error(`Post was missing fileAbsolutePath: ${JSON.stringify(node)}`);
}
const relativePath = relative(__dirname, absolutePath);
createNodeField({
name: 'relativePath',
node,
value: relativePath,
});
}
},
// This server-side calculation of htmlPreview/textPreview ensure that Gatsby's
// generated page-data.json files don't balloon out of control. We get complex here,
// adding custom fields to the GraphQL, because gatsby-transformer-remark lazily
// generates HTML from markdown. We only get html when we call that plugin's resolver
// manually!
// Thanks, @zaparo! https://github.com/gatsbyjs/gatsby/issues/17045#issuecomment-529161439
/* eslint-disable max-params, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access */
createResolvers: ({ createResolvers }: CreateResolversArgs): any => {
const resolvers = {
MarkdownRemark: {
htmlPreview: {
type: 'String',
resolve: async (source: PostType, args: any, context: any, info: any) => {
const htmlField = info.schema.getType('MarkdownRemark').getFields().html;
const html = await htmlField.resolve(source, args, context, info);
const slug = source.frontmatter?.path;
if (!slug) {
throw new Error(`source was missing path: ${JSON.stringify(source)}`);
}
return getHTMLPreview(html, slug);
},
},
textPreview: {
type: 'String',
resolve: async (source: PostType, args: any, context: any, info: any) => {
const htmlField = info.schema.getType('MarkdownRemark').getFields().html;
const html = await htmlField.resolve(source, args, context, info);
return getTextPreview(html);
},
},
},
};
createResolvers(resolvers);
},
/* eslint-enable max-params, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access */
// Build key assets that live next to built files in public/
onPostBuild: async ({ graphql }: BuildArgs): Promise<void> => {
const result: RawAllDataType = await graphql(
`
{
site {
siteMetadata {
blogTitle
favicon
domain
author {
name
email
twitter
url
image
blurb
}
}
}
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
edges {
node {
html
textPreview
htmlPreview
fields {
slug
}
frontmatter {
date
tags
title
path
}
}
}
}
}
`
);
if (result.errors?.length) {
throw result.errors[0] ?? new Error('Something went wrong!');
}
if (!result.data) {
console.error('Query results malformed', result);
throw new Error('Query returned no data!');
}
// Write RSS and Atom
const posts = result.data.allMarkdownRemark.edges.map(item => item.node);
const { siteMetadata } = result.data.site;
const now = new Date();
const author = {
name: siteMetadata.author.name,
email: siteMetadata.author.email,
link: siteMetadata.author.url,
};
const feed = new Feed({
title: siteMetadata.blogTitle,
id: `${siteMetadata.domain}/`,
description: siteMetadata.tagLine,
link: siteMetadata.domain,
copyright: `All rights reserved ${now.getFullYear()}, Scott Nonnenberg`,
feed: `${siteMetadata.domain}/atom.xml`,
author,
});
const mostRecent = posts.slice(0, POST_COUNT_FOR_FEEDS);
mostRecent.forEach(post => {
if (!post.frontmatter) {
console.error('Malformed post', post);
throw new Error('Post was missing frontmatter!');
}
if (!post.html) {
console.error('Malformed post', post);
throw new Error('Post was missing html!');
}
const data = post.frontmatter;
if (!data.title || !data.date || !data.path) {
console.error('Malformed post', post);
throw new Error('Post metadata was missing title, date, or path');
}
const htmlPreview = post.htmlPreview;
if (!htmlPreview) {
console.error('Malformed post', post);
throw new Error('Post metadata was missing htmlPreview');
}
const description = fixLocalLinks(htmlPreview, siteMetadata.domain);
const link = `${siteMetadata.domain}${data.path}`;
feed.addItem({
title: data.title,
link,
description,
content: fixLocalLinks(post.html, siteMetadata.domain),
date: new Date(data.date),
author: [author],
});
});
const rssPath = join(__dirname, 'public/rss.xml');
const atomPath = join(__dirname, 'public/atom.xml');
writeFileSync(rssPath, feed.rss2());
writeFileSync(atomPath, feed.atom1());
// Write JSON
const json = posts.map(post => {
if (!post.frontmatter) {
console.error('Malformed post', post);
throw new Error('Post was missing frontmatter!');
}
const data = post.frontmatter;
if (!data.path) {
console.error('Malformed post', post);
throw new Error('Post metadata was missing path');
}
const htmlPreview = post.htmlPreview;
if (!htmlPreview) {
console.error('Malformed post', post);
throw new Error('Post metadata was missing htmlPreview');
}
const preview = fixLocalLinks(htmlPreview, siteMetadata.domain);
const url = `${siteMetadata.domain}${data.path}`;
return {
title: post.frontmatter.title,
date: post.frontmatter.date,
preview,
url,
tags: post.frontmatter.tags,
};
});
const allPath = join(__dirname, 'public/all.json');
const recentPath = join(__dirname, 'public/recent.json');
writeFileSync(allPath, JSON.stringify(json, null, ' '));
writeFileSync(
recentPath,
JSON.stringify(json.slice(0, RECENT_COUNT_FOR_SYNDICATION), null, ' ')
);
},
};
export default gatsbyNode; | the_stack |
'use strict'
// **Github:** https://github.com/fidm/quic
//
// **License:** MIT
import { inspect } from 'util'
import { QuicError } from './error'
import { BufferVisitor } from './common'
import { parseFrame, Frame } from './frame'
import {
getVersions,
isSupportedVersion,
ConnectionID,
PacketNumber,
SocketAddress,
Tag,
QuicTags,
SessionType,
} from './protocol'
// --- QUIC Public Packet Header
//
// 0 1 2 3 4 8
// +--------+--------+--------+--------+--------+--- ---+
// | Public | Connection ID (64) ... | ->
// |Flags(8)| (optional) |
// +--------+--------+--------+--------+--------+--- ---+
//
// 9 10 11 12
// +--------+--------+--------+--------+
// | QUIC Version (32) | ->
// | (optional) |
// +--------+--------+--------+--------+
//
// 13 14 15 16 17 18 19 20
// +--------+--------+--------+--------+--------+--------+--------+--------+
// | Diversification Nonce | ->
// | (optional) |
// +--------+--------+--------+--------+--------+--------+--------+--------+
//
// 21 22 23 24 25 26 27 28
// +--------+--------+--------+--------+--------+--------+--------+--------+
// | Diversification Nonce Continued | ->
// | (optional) |
// +--------+--------+--------+--------+--------+--------+--------+--------+
//
// 29 30 31 32 33 34 35 36
// +--------+--------+--------+--------+--------+--------+--------+--------+
// | Diversification Nonce Continued | ->
// | (optional) |
// +--------+--------+--------+--------+--------+--------+--------+--------+
//
// 37 38 39 40 41 42 43 44
// +--------+--------+--------+--------+--------+--------+--------+--------+
// | Diversification Nonce Continued | ->
// | (optional) |
// +--------+--------+--------+--------+--------+--------+--------+--------+
//
// 45 46 47 48 49 50
// +--------+--------+--------+--------+--------+--------+
// | Packet Number (8, 16, 32, or 48) |
// | (variable length) |
// +--------+--------+--------+--------+--------+--------+
// ---
//
// Public Flags:
// 0x01 = PUBLIC_FLAG_VERSION. Interpretation of this flag depends on whether the packet
// is sent by the server or the client. When sent by the client, setting it indicates that
// the header contains a QUIC Version (see below)...
// 0x02 = PUBLIC_FLAG_RESET. Set to indicate that the packet is a Public Reset packet.
// 0x04 = Indicates the presence of a 32 byte diversification nonce in the header.
// 0x08 = Indicates the full 8 byte Connection ID is present in the packet.
// Two bits at 0x30 indicate the number of low-order-bytes of the packet number that
// are present in each packet. The bits are only used for Frame Packets. For Public Reset
// and Version Negotiation Packets (sent by the server) which don't have a packet number,
// these bits are not used and must be set to 0. Within this 2 bit mask:
// 0x30 indicates that 6 bytes of the packet number is present
// 0x20 indicates that 4 bytes of the packet number is present
// 0x10 indicates that 2 bytes of the packet number is present
// 0x00 indicates that 1 byte of the packet number is present
// 0x40 is reserved for multipath use.
// 0x80 is currently unused, and must be set to 0.
export function parsePacket (bufv: BufferVisitor, packetSentBy: SessionType): Packet {
bufv.walk(0) // align start and end
const flag = bufv.buf.readUInt8(bufv.start)
// 0x80, currently unused
if (flag >= 127) {
throw new QuicError('QUIC_INTERNAL_ERROR')
}
// 0x08, connectionID
if ((flag & 0b1000) === 0) {
throw new QuicError('QUIC_INTERNAL_ERROR')
}
if ((flag & 0b10) > 0) { // Reset Packet
return ResetPacket.fromBuffer(bufv)
}
const hasVersion = (flag & 0b1) > 0
if (hasVersion && packetSentBy === SessionType.SERVER) { // Negotiation Packet
return NegotiationPacket.fromBuffer(bufv)
}
return RegularPacket.fromBuffer(bufv, flag, packetSentBy)
}
/** Packet representing a base Packet. */
export abstract class Packet {
static fromBuffer (_bufv: BufferVisitor, _flag?: number, _packetSentBy?: SessionType): Packet {
throw new Error(`class method "fromBuffer" is not implemented`)
}
flag: number
connectionID: ConnectionID
sentTime: number
constructor (connectionID: ConnectionID, flag: number) {
this.flag = flag
this.connectionID = connectionID
this.sentTime = 0 // timestamp, ms
}
isReset (): boolean {
return this instanceof ResetPacket
}
isNegotiation (): boolean {
return this instanceof NegotiationPacket
}
isRegular (): boolean {
return this instanceof RegularPacket
}
valueOf () {
return {
connectionID: this.connectionID.valueOf(),
flag: this.flag,
}
}
toString (): string {
return JSON.stringify(this.valueOf())
}
[inspect.custom] (_depth: any, _options: any): string {
return `<${this.constructor.name} ${this.toString()}>`
}
abstract byteLen (): number
abstract writeTo (bufv: BufferVisitor): BufferVisitor
}
/** ResetPacket representing a reset Packet. */
export class ResetPacket extends Packet {
// --- Public Reset Packet
// 0 1 2 3 4 8
// +--------+--------+--------+--------+--------+-- --+
// | Public | Connection ID (64) ... | ->
// |Flags(8)| |
// +--------+--------+--------+--------+--------+-- --+
//
// 9 10 11 12 13 14
// +--------+--------+--------+--------+--------+--------+---
// | Quic Tag (32) | Tag value map ... ->
// | (PRST) | (variable length)
// +--------+--------+--------+--------+--------+--------+---
static fromBuffer (bufv: BufferVisitor): ResetPacket {
bufv.walk(1) // flag
const connectionID = ConnectionID.fromBuffer(bufv)
const quicTag = QuicTags.fromBuffer(bufv)
if (quicTag.name !== Tag.PRST || !quicTag.has(Tag.RNON)) {
throw new QuicError('QUIC_INVALID_PUBLIC_RST_PACKET')
}
return new ResetPacket(connectionID, quicTag)
}
nonceProof: Buffer
packetNumber: PacketNumber | null
socketAddress: SocketAddress | null
tags: QuicTags
constructor (connectionID: ConnectionID, tags: QuicTags) {
super(connectionID, 0b00001010)
this.tags = tags
this.packetNumber = null
this.socketAddress = null
const nonceProof = tags.get(Tag.RNON)
if (nonceProof == null) {
throw new QuicError('QUIC_INVALID_PUBLIC_RST_PACKET')
}
this.nonceProof = nonceProof
const rseq = tags.get(Tag.RSEQ)
if (rseq != null) {
this.packetNumber = PacketNumber.fromBuffer(new BufferVisitor(rseq), rseq.length)
}
const cadr = tags.get(Tag.CADR)
if (cadr != null) {
this.socketAddress = SocketAddress.fromBuffer(new BufferVisitor(cadr))
}
}
valueOf () {
return {
connectionID: this.connectionID.valueOf(),
flag: this.flag,
packetNumber: this.packetNumber == null ? null : this.packetNumber.valueOf(),
socketAddress: this.socketAddress == null ? null : this.socketAddress.valueOf(),
nonceProof: this.nonceProof,
}
}
byteLen (): number {
return 9 + this.tags.byteLen()
}
writeTo (bufv: BufferVisitor): BufferVisitor {
bufv.walk(1)
bufv.buf.writeUInt8(this.flag, bufv.start)
this.connectionID.writeTo(bufv)
this.tags.writeTo(bufv)
return bufv
}
}
/** NegotiationPacket representing a negotiation Packet. */
export class NegotiationPacket extends Packet {
// --- Version Negotiation Packet
// 0 1 2 3 4 5 6 7 8
// +--------+--------+--------+--------+--------+--------+--------+--------+--------+
// | Public | Connection ID (64) | ->
// |Flags(8)| |
// +--------+--------+--------+--------+--------+--------+--------+--------+--------+
//
// 9 10 11 12 13 14 15 16 17
// +--------+--------+--------+--------+--------+--------+--------+--------+---...--+
// | 1st QUIC version supported | 2nd QUIC version supported | ...
// | by server (32) | by server (32) |
// +--------+--------+--------+--------+--------+--------+--------+--------+---...--+
static fromConnectionID (connectionID: ConnectionID): NegotiationPacket {
return new NegotiationPacket(connectionID, getVersions())
}
static fromBuffer (bufv: BufferVisitor): NegotiationPacket {
bufv.walk(1) // flag
const connectionID = ConnectionID.fromBuffer(bufv)
const versions = []
while (bufv.length > bufv.end) {
bufv.walk(4)
const version = bufv.buf.toString('utf8', bufv.start, bufv.end)
if (!isSupportedVersion(version)) {
throw new QuicError('QUIC_INVALID_VERSION')
}
versions.push(version)
}
return new NegotiationPacket(connectionID, versions)
}
versions: string[]
constructor (connectionID: ConnectionID, versions: string[]) {
super(connectionID, 0b00001001)
this.versions = versions
}
valueOf () {
return {
connectionID: this.connectionID.valueOf(),
flag: this.flag,
versions: this.versions,
}
}
byteLen (): number {
return 9 + 4 * this.versions.length
}
writeTo (bufv: BufferVisitor): BufferVisitor {
bufv.walk(1)
bufv.buf.writeUInt8(this.flag, bufv.start)
this.connectionID.writeTo(bufv)
for (const version of this.versions) {
bufv.walk(4)
bufv.buf.write(version, bufv.start, 4)
}
return bufv
}
}
/** RegularPacket representing a regular Packet. */
export class RegularPacket extends Packet {
// --- Frame Packet
// +--------+---...---+--------+---...---+
// | Type | Payload | Type | Payload |
// +--------+---...---+--------+---...---+
static fromBuffer (bufv: BufferVisitor, flag: number, packetSentBy: SessionType): RegularPacket {
bufv.walk(1) // flag
const connectionID = ConnectionID.fromBuffer(bufv)
let version = ''
const hasVersion = (flag & 0b1) > 0
if (hasVersion) {
bufv.walk(4)
version = bufv.buf.toString('utf8', bufv.start, bufv.end)
if (!isSupportedVersion(version)) {
throw new QuicError('QUIC_INVALID_VERSION')
}
}
// Contrary to what the gQUIC wire spec says, the 0x4 bit only indicates the presence of
// the diversification nonce for packets sent by the server.
// It doesn't have any meaning when sent by the client.
let nonce = null
if (packetSentBy === SessionType.SERVER && (flag & 0b100) > 0) {
bufv.walk(32)
nonce = bufv.buf.slice(bufv.start, bufv.end)
if (nonce.length !== 32) {
throw new QuicError('QUIC_INTERNAL_ERROR')
}
}
const packetNumber = PacketNumber.fromBuffer(bufv, PacketNumber.flagToByteLen((flag & 0b110000) >> 4))
const packet = new RegularPacket(connectionID, packetNumber, nonce)
if (version !== '') {
packet.setVersion(version)
}
return packet
}
packetNumber: PacketNumber
version: string
nonce: Buffer | null
frames: Frame[]
isRetransmittable: boolean
constructor (connectionID: ConnectionID, packetNumber: PacketNumber, nonce: Buffer | null = null) {
let flag = 0b00001000
flag |= (packetNumber.flagBits() << 4)
if (nonce != null) {
flag |= 0x04
}
super(connectionID, flag)
this.packetNumber = packetNumber
this.version = '' // 4 byte, string
this.nonce = nonce // 32 byte, buffer
this.frames = []
this.isRetransmittable = true
}
valueOf () {
return {
connectionID: this.connectionID.valueOf(),
flag: this.flag,
version: this.version,
packetNumber: this.packetNumber.valueOf(),
nonce: this.nonce,
frames: this.frames.map((val) => val.valueOf()),
}
}
setVersion (version: string) {
this.flag |= 0b00000001
this.version = version
}
setPacketNumber (packetNumber: PacketNumber) {
this.packetNumber = packetNumber
this.flag &= 0b11001111
this.flag |= (packetNumber.flagBits() << 4)
}
needAck (): boolean {
for (const frame of this.frames) {
if (frame.isRetransmittable()) {
return true
}
}
return false
}
parseFrames (bufv: BufferVisitor) {
while (bufv.end < bufv.length) {
this.addFrames(parseFrame(bufv, this.packetNumber))
}
}
addFrames (...frames: Frame[]): this {
this.frames.push(...frames)
return this
}
headerLen (): number {
let len = 9
if (this.version !== '') {
len += 4
}
if (this.nonce != null) {
len += 32
}
len += this.packetNumber.byteLen()
return len
}
byteLen (): number {
let len = this.headerLen()
for (const frame of this.frames) {
len += frame.byteLen()
}
return len
}
writeTo (bufv: BufferVisitor): BufferVisitor {
bufv.walk(1)
bufv.buf.writeUInt8(this.flag, bufv.start)
this.connectionID.writeTo(bufv)
if (this.version !== '') {
bufv.walk(4)
bufv.buf.write(this.version, bufv.start, 4)
}
if (this.nonce != null) {
bufv.walk(32)
this.nonce.copy(bufv.buf, bufv.start, 0, 32)
}
this.packetNumber.writeTo(bufv)
for (const frame of this.frames) {
frame.writeTo(bufv)
}
return bufv
}
} | the_stack |
import * as d3 from 'd3'
import Util from '../base/utils'
import { randomColor, getColorStrFromCanvas } from '../base/color-util'
class OrgChart {
d3: any
width: number
height: number
padding: number
nodeWidth: number
nodeHeight: number
unitPadding: number
unitWidth: number
unitHeight: number
duration: number
scale: number
data: any
treeGenerator: any
treeData: any
virtualContainerNode: any
container: any
canvasNode: any
hiddenCanvasNode: any
context: any
hiddenContext: any
colorNodeMap: {}
onDrag_: boolean
dragStartPoint_: { x: number; y: number }
constructor() {
this.d3 = d3
this.init()
}
init() {
this.initVariables()
this.initCanvas()
this.initVirtualNode()
this.setCanvasListener()
}
initVariables() {
this.width = window.innerWidth
this.height = window.innerHeight
this.padding = 20
// tree node size
this.nodeWidth = 180
this.nodeHeight = 280
// org unit size
this.unitPadding = 20
this.unitWidth = 140
this.unitHeight = 100
// animation duration
this.duration = 600
this.scale = 1.0
}
draw(data) {
this.data = this.d3.hierarchy(data)
this.treeGenerator = this.d3
.tree()
.nodeSize([this.nodeWidth, this.nodeHeight])
this.update(null)
const self = this
this.d3.timer(function () {
self.drawCanvas()
})
}
update(targetTreeNode) {
this.treeData = this.treeGenerator(this.data)
const nodes = this.treeData.descendants()
const links = this.treeData.links()
let animatedStartX = 0
let animatedStartY = 0
let animatedEndX = 0
let animatedEndY = 0
if (targetTreeNode) {
animatedStartX = targetTreeNode.x0
animatedStartY = targetTreeNode.y0
animatedEndX = targetTreeNode.x
animatedEndY = targetTreeNode.y
}
this.updateOrgUnits(
nodes,
animatedStartX,
animatedStartY,
animatedEndX,
animatedEndY
)
this.updateLinks(
links,
animatedStartX,
animatedStartY,
animatedEndX,
animatedEndY
)
this.addColorKey()
this.bindNodeToTreeData()
}
updateOrgUnits(
nodes,
animatedStartX,
animatedStartY,
animatedEndX,
animatedEndY
) {
let orgUnitSelection = this.virtualContainerNode
.selectAll('.orgUnit')
.data(nodes, (d) => d['colorKey'])
orgUnitSelection
.attr('class', 'orgUnit')
.attr('x', function (data) {
return data.x0
})
.attr('y', function (data) {
return data.y0
})
.transition()
.duration(this.duration)
.attr('x', function (data) {
return data.x
})
.attr('y', function (data) {
return data.y
})
.attr('fillStyle', '#ff0000')
orgUnitSelection
.enter()
.append('orgUnit')
.attr('class', 'orgUnit')
.attr('x', animatedStartX)
.attr('y', animatedStartY)
.transition()
.duration(this.duration)
.attr('x', function (data) {
return data.x
})
.attr('y', function (data) {
return data.y
})
.attr('fillStyle', '#ff0000')
orgUnitSelection
.exit()
.transition()
.duration(this.duration)
.attr('x', animatedEndX)
.attr('y', animatedEndY)
.remove()
// record origin index for animation
nodes.forEach((treeNode) => {
treeNode['x0'] = treeNode.x
treeNode['y0'] = treeNode.y
})
orgUnitSelection = null
}
updateLinks(
links,
animatedStartX,
animatedStartY,
animatedEndX,
animatedEndY
) {
let linkSelection = this.virtualContainerNode
.selectAll('.link')
.data(links, function (d) {
return d.source['colorKey'] + ':' + d.target['colorKey']
})
linkSelection
.attr('class', 'link')
.attr('sourceX', function (linkData) {
return linkData.source['x00']
})
.attr('sourceY', function (linkData) {
return linkData.source['y00']
})
.attr('targetX', function (linkData) {
return linkData.target['x00']
})
.attr('targetY', function (linkData) {
return linkData.target['y00']
})
.transition()
.duration(this.duration)
.attr('sourceX', function (linkData) {
return linkData.source.x
})
.attr('sourceY', function (linkData) {
return linkData.source.y
})
.attr('targetX', function (linkData) {
return linkData.target.x
})
.attr('targetY', function (linkData) {
return linkData.target.y
})
linkSelection
.enter()
.append('link')
.attr('class', 'link')
.attr('sourceX', animatedStartX)
.attr('sourceY', animatedStartY)
.attr('targetX', animatedStartX)
.attr('targetY', animatedStartY)
.transition()
.duration(this.duration)
.attr('sourceX', function (link) {
return link.source.x
})
.attr('sourceY', function (link) {
return link.source.y
})
.attr('targetX', function (link) {
return link.target.x
})
.attr('targetY', function (link) {
return link.target.y
})
linkSelection
.exit()
.transition()
.duration(this.duration)
.attr('sourceX', animatedEndX)
.attr('sourceY', animatedEndY)
.attr('targetX', animatedEndX)
.attr('targetY', animatedEndY)
.remove()
// record origin data for animation
links.forEach((treeNode) => {
treeNode.source['x00'] = treeNode.source.x
treeNode.source['y00'] = treeNode.source.y
treeNode.target['x00'] = treeNode.target.x
treeNode.target['y00'] = treeNode.target.y
})
linkSelection = null
}
initCanvas() {
this.container = this.d3.select('#org-chart-container')
this.canvasNode = this.container
.append('canvas')
.attr('class', 'orgChart')
.attr('width', this.width)
.attr('height', this.height)
this.hiddenCanvasNode = this.container
.append('canvas')
.attr('class', 'orgChart')
.attr('width', this.width)
.attr('height', this.height)
.style('display', '')
this.context = this.canvasNode.node().getContext('2d')
this.context.translate(this.width / 2, this.padding)
this.hiddenContext = this.hiddenCanvasNode.node().getContext('2d')
this.hiddenContext.translate(this.width / 2, this.padding)
}
initVirtualNode() {
let virtualContainer = document.createElement('root')
this.virtualContainerNode = this.d3.select(virtualContainer)
this.colorNodeMap = {}
}
addColorKey() {
// give each node a unique color
const self = this
this.virtualContainerNode.selectAll('.orgUnit').each(function () {
const node = self.d3.select(this)
let newColor = randomColor()
while (self.colorNodeMap[newColor]) {
newColor = randomColor()
}
node.attr('colorKey', newColor)
node.data()[0]['colorKey'] = newColor
self.colorNodeMap[newColor] = node
})
}
bindNodeToTreeData() {
// give each node a unique color
const self = this
this.virtualContainerNode.selectAll('.orgUnit').each(function () {
const node = self.d3.select(this)
const data = node.data()[0]
data.node = node
})
}
drawCanvas() {
this.drawShowCanvas()
this.drawHiddenCanvas()
}
drawShowCanvas() {
this.context.clearRect(-50000, -10000, 100000, 100000)
const self = this
// draw links
this.virtualContainerNode.selectAll('.link').each(function () {
const node = self.d3.select(this)
const linkPath = self.d3
.linkVertical()
.x(function (d) {
return d.x
})
.y(function (d) {
return d.y
})
.source(function () {
return { x: node.attr('sourceX'), y: node.attr('sourceY') }
})
.target(function () {
return { x: node.attr('targetX'), y: node.attr('targetY') }
})
const path = new Path2D(linkPath())
self.context.stroke(path)
})
this.virtualContainerNode.selectAll('.orgUnit').each(function () {
const node = self.d3.select(this)
const treeNode = node.data()[0]
const data = treeNode.data
self.context.fillStyle = '#3ca0ff'
const indexX = Number(node.attr('x')) - self.unitWidth / 2
const indexY = Number(node.attr('y')) - self.unitHeight / 2
// draw unit outline rect (if you want to modify this line ===> please modify the same line in `drawHiddenCanvas`)
Util.roundRect(
self.context,
indexX,
indexY,
self.unitWidth,
self.unitHeight,
4,
true,
false
)
Util.text(
self.context,
data.name,
indexX + self.unitPadding,
indexY + self.unitPadding,
'20px',
'#ffffff'
)
// Util.text(self.context, data.title, indexX + self.unitPadding, indexY + self.unitPadding + 30, '20px', '#000000')
const maxWidth = self.unitWidth - 2 * self.unitPadding
Util.wrapText(
self.context,
data.title,
indexX + self.unitPadding,
indexY + self.unitPadding + 24,
maxWidth,
20,
'#000000'
)
})
}
/**
* fill the node outline with colorKey color
*/
drawHiddenCanvas() {
this.hiddenContext.clearRect(-50000, -10000, 100000, 100000)
const self = this
this.virtualContainerNode.selectAll('.orgUnit').each(function () {
const node = self.d3.select(this)
self.hiddenContext.fillStyle = node.attr('colorKey')
Util.roundRect(
self.hiddenContext,
Number(node.attr('x')) - self.unitWidth / 2,
Number(node.attr('y')) - self.unitHeight / 2,
self.unitWidth,
self.unitHeight,
4,
true,
false
)
})
}
setCanvasListener() {
this.setClickListener()
this.setDragListener()
this.setMouseWheelZoomListener()
}
setClickListener() {
const self = this
this.canvasNode.node().addEventListener('click', (e) => {
const colorStr = getColorStrFromCanvas(
self.hiddenContext,
e.layerX,
e.layerY
)
const node = self.colorNodeMap[colorStr]
if (node) {
self.toggleTreeNode(node.data()[0])
self.update(node.data()[0])
}
})
}
setMouseWheelZoomListener() {
const self = this
this.canvasNode.node().addEventListener('mousewheel', (event) => {
event.preventDefault()
if (event.deltaY < 0) {
self.bigger()
} else {
self.smaller()
}
})
}
setDragListener() {
this.onDrag_ = false
this.dragStartPoint_ = { x: 0, y: 0 }
const self = this
this.canvasNode.node().onmousedown = function (e) {
self.dragStartPoint_.x = e.x
self.dragStartPoint_.y = e.y
self.onDrag_ = true
}
this.canvasNode.node().onmousemove = function (e) {
if (!self.onDrag_) {
return
}
self.context.translate(
(e.x - self.dragStartPoint_.x) / self.scale,
(e.y - self.dragStartPoint_.y) / self.scale
)
self.hiddenContext.translate(
(e.x - self.dragStartPoint_.x) / self.scale,
(e.y - self.dragStartPoint_.y) / self.scale
)
self.dragStartPoint_.x = e.x
self.dragStartPoint_.y = e.y
}
this.canvasNode.node().onmouseout = function (e) {
if (self.onDrag_) {
self.onDrag_ = false
}
}
this.canvasNode.node().onmouseup = function (e) {
if (self.onDrag_) {
self.onDrag_ = false
}
}
}
toggleTreeNode(treeNode) {
if (treeNode.children) {
treeNode._children = treeNode.children
treeNode.children = null
} else {
treeNode.children = treeNode._children
treeNode._children = null
}
}
bigger() {
if (this.scale > 7) return
this.clearCanvas_()
this.scale = (this.scale * 5) / 4
this.context.scale(5 / 4, 5 / 4)
this.hiddenContext.scale(5 / 4, 5 / 4)
}
smaller() {
if (this.scale < 0.2) return
this.clearCanvas_()
this.scale = (this.scale * 4) / 5
this.context.scale(4 / 5, 4 / 5)
this.hiddenContext.scale(4 / 5, 4 / 5)
}
clearCanvas_() {
this.context.clearRect(-1000000, -10000, 2000000, 2000000)
this.hiddenContext.clearRect(-1000000, -10000, 2000000, 2000000)
}
}
export default OrgChart | the_stack |
import {
AfterViewInit,
Attribute,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
forwardRef,
Input,
NgZone,
OnChanges,
OnDestroy,
Output,
SimpleChanges,
ViewChild,
ViewEncapsulation
} from '@angular/core';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from '@angular/forms';
import {coerceBooleanProperty, coerceNumberProperty} from '@angular/cdk/coercion';
import {Platform, supportsPassiveEventListeners} from '@angular/cdk/platform';
import {fromEvent, Subject} from 'rxjs';
import {takeUntil, auditTime} from 'rxjs/operators';
import {MDCComponent} from '@angular-mdc/web/base';
import {EventType, SpecificEventListener} from '@material/base/types';
import {MDCSliderFoundation, MDCSliderAdapter} from '@material/slider';
export const MDC_SLIDER_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MdcSlider),
multi: true
};
export class MdcSliderChange {
constructor(
public source: MdcSlider,
public value: number) {}
}
@Component({
selector: 'mdc-slider',
exportAs: 'mdcSlider',
host: {
'role': 'slider',
'aria-orientation': 'horizontal',
'[attr.tabindex]': 'tabIndex || 0',
'class': 'mdc-slider',
'[class.mdc-slider--discrete]': 'discrete',
'[class.mdc-slider--display-markers]': 'markers && discrete',
'(blur)': '_onTouched()',
},
templateUrl: 'slider.html',
providers: [MDC_SLIDER_CONTROL_VALUE_ACCESSOR],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None
})
export class MdcSlider extends MDCComponent<MDCSliderFoundation>
implements AfterViewInit, OnChanges, OnDestroy, ControlValueAccessor {
/** Emits whenever the component is destroyed. */
private _destroyed = new Subject<void>();
private _initialized = false;
_root!: Element;
@Input() tabIndex: number = 0;
@Input()
get discrete(): boolean {
return this._discrete;
}
set discrete(value: boolean) {
this._discrete = coerceBooleanProperty(value);
}
private _discrete = false;
@Input()
get markers(): boolean {
return this._markers;
}
set markers(value: boolean) {
this._markers = coerceBooleanProperty(value);
}
private _markers = false;
@Input()
get min(): number {
return this._min;
}
set min(value: number) {
const min = coerceNumberProperty(value);
if (min !== this._min) {
this._min = min;
}
}
private _min: number = 0;
@Input()
get max(): number {
return this._max;
}
set max(value: number) {
const max = coerceNumberProperty(value);
if (max !== this._max) {
this._max = max;
}
}
private _max: number = 100;
@Input()
get step(): number {
return this._step;
}
set step(value: number) {
const step = coerceNumberProperty(value, this._step);
if (step !== this._step) {
this._step = step;
}
}
private _step: number = 1;
@Input()
get value(): number | null {
if (this._value === null) {
this.value = this.min;
}
return this._value;
}
set value(newValue: number | null) {
this._value = coerceNumberProperty(newValue, null);
}
private _value: number | null = null;
@Input()
get disabled(): boolean {
return this._disabled;
}
set disabled(value: boolean) {
this.setDisabledState(value);
}
private _disabled = false;
@Output() readonly change: EventEmitter<MdcSliderChange> = new EventEmitter<MdcSliderChange>();
@Output() readonly input: EventEmitter<MdcSliderChange> = new EventEmitter<MdcSliderChange>();
/**
* Emits when the raw value of the slider changes. This is here primarily
* to facilitate the two-way binding for the `value` input.
*/
@Output() readonly valueChange: EventEmitter<number> = new EventEmitter<number>();
@ViewChild('thumbcontainer', {static: false}) thumbContainer!: ElementRef<HTMLElement>;
@ViewChild('sliderThumb', {static: false}) _sliderThumb!: ElementRef<HTMLElement>;
@ViewChild('track', {static: false}) track!: ElementRef<HTMLElement>;
@ViewChild('pin', {static: false}) pinValueMarker?: ElementRef;
@ViewChild('markercontainer', {static: false}) trackMarkerContainer?: ElementRef<HTMLElement>;
/** Function when touched */
_onTouched: () => any = () => {};
/** Function when changed */
_controlValueAccessorChangeFn: (value: number) => void = () => {};
getDefaultFoundation() {
const adapter: MDCSliderAdapter = {
hasClass: (className: string) => this._root.classList.contains(className),
addClass: (className: string) => this._root.classList.add(className),
removeClass: (className: string) => this._root.classList.remove(className),
getAttribute: (name: string) => this._root.getAttribute(name),
setAttribute: (name: string, value: string) => this._root.setAttribute(name, value),
removeAttribute: (name: string) => this._root.removeAttribute(name),
computeBoundingRect: () => this._root.getBoundingClientRect(),
getTabIndex: () => (<HTMLElement>this._root).tabIndex,
registerInteractionHandler: <K extends EventType>(evtType: K, handler: SpecificEventListener<K>) =>
(<HTMLElement>this._root).addEventListener(evtType, handler),
deregisterInteractionHandler: <K extends EventType>(evtType: K, handler: SpecificEventListener<K>) =>
(<HTMLElement>this._root).removeEventListener(evtType, handler),
registerThumbContainerInteractionHandler:
<K extends EventType>(evtType: K, handler: SpecificEventListener<K>) => {
this._ngZone.runOutsideAngular(() => {
this.thumbContainer.nativeElement.addEventListener(evtType, handler, supportsPassiveEventListeners());
});
},
deregisterThumbContainerInteractionHandler: <K extends EventType>(evtType: K,
handler: SpecificEventListener<K>) =>
this.thumbContainer.nativeElement.removeEventListener(evtType, handler, supportsPassiveEventListeners()),
registerBodyInteractionHandler: <K extends EventType>(evtType: K, handler: SpecificEventListener<K>) =>
document.body.addEventListener(evtType, handler),
deregisterBodyInteractionHandler: <K extends EventType>(evtType: K, handler: SpecificEventListener<K>) =>
document.body.removeEventListener(evtType, handler),
registerResizeHandler: () => {},
deregisterResizeHandler: () => {},
notifyInput: () => {
const newValue = this._foundation.getValue();
if (newValue !== this.value) {
this.value = newValue;
this.input.emit(this._createChangeEvent(newValue));
}
},
notifyChange: () => {
this.value = this._foundation.getValue();
this._emitChangeEvent(this.value!);
},
setThumbContainerStyleProperty: (propertyName: string, value: string) =>
this.thumbContainer.nativeElement.style.setProperty(propertyName, value),
setTrackStyleProperty: (propertyName: string, value: string) =>
this.track.nativeElement.style.setProperty(propertyName, value),
setMarkerValue: (value: number) => {
this._changeDetectorRef.markForCheck();
this.pinValueMarker!.nativeElement.innerText = value !== null ? value.toString() : null;
},
setTrackMarkers: (step: number, max: number, min: number) =>
this.trackMarkerContainer!.nativeElement.style.setProperty('background',
this._getTrackMarkersBackground(step, min, max)),
isRTL: () => this._platform.isBrowser ?
window.getComputedStyle(this._root).getPropertyValue('direction') === 'rtl' : false,
};
return new MDCSliderFoundation(adapter);
}
constructor(
private _platform: Platform,
private _ngZone: NgZone,
private _changeDetectorRef: ChangeDetectorRef,
public elementRef: ElementRef,
@Attribute('tabindex') tabIndex: string) {
super(elementRef);
this.tabIndex = parseInt(tabIndex, 10) || 0;
this._root = this.elementRef.nativeElement;
}
ngOnChanges(changes: SimpleChanges) {
if (!this._initialized) {
return;
}
if (changes['step']) {
this._syncStepWithFoundation();
}
if (changes['max']) {
this._syncMaxWithFoundation();
}
if (changes['min']) {
this._syncMinWithFoundation();
}
if (changes['value']) {
this._syncValueWithFoundation();
}
if (changes['markers'] || changes['discrete']) {
this._refreshTrackMarkers();
}
}
async _asyncInitializeFoundation(): Promise<void> {
this._foundation.init();
}
ngAfterViewInit(): void {
if (this._platform.isBrowser) {
this._initialized = true;
this._asyncInitializeFoundation()
.then(() => {
this._syncStepWithFoundation();
this._syncMaxWithFoundation();
this._syncMinWithFoundation();
this._syncValueWithFoundation();
this._foundation.setupTrackMarker();
this._loadListeners();
this._changeDetectorRef.markForCheck();
});
}
}
ngOnDestroy(): void {
this._destroyed.next();
this._destroyed.complete();
this.destroy();
}
writeValue(value: any): void {
this.value = value;
this._syncValueWithFoundation();
}
registerOnChange(fn: any): void {
this._controlValueAccessorChangeFn = fn;
}
registerOnTouched(fn: any): void {
this._onTouched = fn;
}
setDisabledState(disabled: boolean): void {
this._disabled = coerceBooleanProperty(disabled);
this._foundation.setDisabled(disabled);
this._changeDetectorRef.markForCheck();
}
layout(): void {
this._foundation.layout();
}
private _loadListeners(): void {
this._ngZone.runOutsideAngular(() =>
fromEvent(window, 'resize')
.pipe(auditTime(16), takeUntil(this._destroyed))
.subscribe(() => this.layout()));
}
private _syncValueWithFoundation(): void {
this._foundation.setValue(this.value!);
}
private _syncStepWithFoundation(): void {
this._foundation.setStep(this.step);
}
private _syncMinWithFoundation(): void {
this._foundation.setMin(this.min);
}
private _syncMaxWithFoundation(): void {
this._foundation.setMax(this.max);
}
private _createChangeEvent(newValue: number): MdcSliderChange {
return new MdcSliderChange(this, newValue);
}
private _emitChangeEvent(newValue: number) {
this._controlValueAccessorChangeFn(newValue);
this.valueChange.emit(newValue);
this.change.emit(this._createChangeEvent(newValue));
}
/** Keep calculation in css for better rounding/subpixel behavior. */
private _getTrackMarkersBackground(step: number, min: number, max: number): string {
const stepStr = step.toLocaleString();
const maxStr = max.toLocaleString();
const minStr = min.toLocaleString();
const markerAmount = `((${maxStr} - ${minStr}) / ${stepStr})`;
const markerWidth = `2px`;
const markerBkgdImage = `linear-gradient(to right, currentColor ${markerWidth}, transparent 0)`;
const markerBkgdLayout = `0 center / calc((100% - ${markerWidth}) / ${markerAmount}) 100% repeat-x`;
return `${markerBkgdImage} ${markerBkgdLayout}`;
}
/** Method that ensures that track markers are refreshed. */
private _refreshTrackMarkers() {
(this._foundation as any).hasTrackMarker_ = this.markers;
this._foundation.setupTrackMarker();
}
} | the_stack |
import * as path from "path";
import * as expressHandlebars from "../lib/index";
import type {
TemplateDelegateObject,
EngineOptions,
} from "../types";
function fixturePath (filePath = "") {
return path.resolve(__dirname, "./fixtures", filePath);
}
// allow access to private functions for testing
// https://github.com/microsoft/TypeScript/issues/19335
/* eslint-disable dot-notation, @typescript-eslint/no-empty-function */
describe("express-handlebars", () => {
test("ExpressHandlebars instance", () => {
const exphbs = new expressHandlebars.ExpressHandlebars();
expect(exphbs).toBeDefined();
});
test("should nomalize extname", () => {
const exphbs1 = expressHandlebars.create({ extname: "ext" });
const exphbs2 = expressHandlebars.create({ extname: ".ext" });
expect(exphbs1.extname).toBe(".ext");
expect(exphbs2.extname).toBe(".ext");
});
describe("getPartials", () => {
test("should throw if partialsDir is not correct type", async () => {
// @ts-expect-error partialsDir is invalid
const exphbs = expressHandlebars.create({ partialsDir: 1 });
let error: Error;
try {
await exphbs.getPartials();
} catch (e) {
error = e;
}
expect(error).toEqual(expect.any(Error));
expect(error.message).toBe("A partials dir must be a string or config object");
});
test("should return empty object if no partialsDir is defined", async () => {
const exphbs = expressHandlebars.create();
const partials = await exphbs.getPartials();
expect(partials).toEqual({});
});
test("should return empty object partialsDir does not exist", async () => {
const exphbs = expressHandlebars.create({ partialsDir: "does-not-exist" });
const partials = await exphbs.getPartials();
expect(partials).toEqual({});
});
test("should return partials on string", async () => {
const exphbs = expressHandlebars.create({ partialsDir: fixturePath("partials") });
const partials = await exphbs.getPartials();
expect(partials).toEqual({
partial: expect.any(Function),
"partial-latin1": expect.any(Function),
});
});
test("should return partials on array", async () => {
const exphbs = expressHandlebars.create({ partialsDir: [fixturePath("partials")] });
const partials = await exphbs.getPartials();
expect(partials).toEqual({
partial: expect.any(Function),
"partial-latin1": expect.any(Function),
});
});
test("should return partials on object", async () => {
const fn = jest.fn();
const exphbs = expressHandlebars.create({
partialsDir: {
templates: { "partial template": fn },
namespace: "partial namespace",
dir: fixturePath("partials"),
},
});
const partials = await exphbs.getPartials();
expect(partials).toEqual({
"partial namespace/partial template": fn,
});
});
test("should return renamed partials with rename function", async () => {
const fn = jest.fn();
const exphbs = expressHandlebars.create({
partialsDir: {
templates: { "partial/template": fn },
namespace: "partial namespace",
dir: fixturePath("partials"),
rename: (filePath, namespace) => {
return `${namespace}/${filePath.split("/")[0]}`;
},
},
});
const partials = await exphbs.getPartials();
expect(partials).toEqual({
"partial namespace/partial": fn,
});
});
test("should return partials on path relative to cwd", async () => {
const exphbs = expressHandlebars.create({ partialsDir: "spec/fixtures/partials" });
const partials = await exphbs.getPartials();
expect(partials).toEqual({
partial: expect.any(Function),
"partial-latin1": expect.any(Function),
});
});
test("should return template function", async () => {
const exphbs = expressHandlebars.create({ partialsDir: "spec/fixtures/partials" });
const partials = await exphbs.getPartials() as TemplateDelegateObject;
const html = partials.partial({ text: "test text" });
expect(html).toBe("partial test text");
});
test("should return a template with encoding", async () => {
const exphbs = expressHandlebars.create({ partialsDir: "spec/fixtures/partials" });
const partials = await exphbs.getPartials({ encoding: "latin1" }) as TemplateDelegateObject;
const html = partials["partial-latin1"]({});
expect(html).toContain("ñáéíóú");
});
test("should return a template with default encoding", async () => {
const exphbs = expressHandlebars.create({
encoding: "latin1",
partialsDir: "spec/fixtures/partials",
});
const partials = await exphbs.getPartials() as TemplateDelegateObject;
const html = partials["partial-latin1"]({});
expect(html).toContain("ñáéíóú");
});
});
describe("getTemplate", () => {
test("should return cached template", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("templates/template.handlebars");
const compiledCachedFunction = (() => "compiled") as Handlebars.TemplateDelegate;
exphbs.compiled[filePath] = Promise.resolve(compiledCachedFunction);
const precompiledCachedFunction = (() => "precompiled") as TemplateSpecification;
exphbs.precompiled[filePath] = Promise.resolve(precompiledCachedFunction);
const template = await exphbs.getTemplate(filePath, { cache: true });
expect(template).toBe(compiledCachedFunction);
});
test("should return precompiled cached template", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("templates/template.handlebars");
const compiledCachedFunction = (() => "compiled") as Handlebars.TemplateDelegate;
exphbs.compiled[filePath] = Promise.resolve(compiledCachedFunction);
const precompiledCachedFunction = (() => "precompiled") as TemplateSpecification;
exphbs.precompiled[filePath] = Promise.resolve(precompiledCachedFunction);
const template = await exphbs.getTemplate(filePath, { precompiled: true, cache: true });
expect(template).toBe(precompiledCachedFunction);
});
test("should store in precompiled cache", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("templates/template.handlebars");
expect(exphbs.compiled[filePath]).toBeUndefined();
expect(exphbs.precompiled[filePath]).toBeUndefined();
await exphbs.getTemplate(filePath, { precompiled: true });
expect(exphbs.compiled[filePath]).toBeUndefined();
expect(exphbs.precompiled[filePath]).toBeDefined();
});
test("should store in compiled cache", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("templates/template.handlebars");
expect(exphbs.compiled[filePath]).toBeUndefined();
expect(exphbs.precompiled[filePath]).toBeUndefined();
await exphbs.getTemplate(filePath);
expect(exphbs.compiled[filePath]).toBeDefined();
expect(exphbs.precompiled[filePath]).toBeUndefined();
});
test("should return a template", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("templates/template.handlebars");
const template = await exphbs.getTemplate(filePath) as HandlebarsTemplateDelegate;
const html = template({ text: "test text" });
expect(html).toBe("<p>test text</p>");
});
test("should return a template with encoding", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("templates/template-latin1.handlebars");
const template = await exphbs.getTemplate(filePath, { encoding: "latin1" }) as HandlebarsTemplateDelegate;
const html = template({});
expect(html).toContain("ñáéíóú");
});
test("should return a template with default encoding", async () => {
const exphbs = expressHandlebars.create({ encoding: "latin1" });
const filePath = fixturePath("templates/template-latin1.handlebars");
const template = await exphbs.getTemplate(filePath) as HandlebarsTemplateDelegate;
const html = template({});
expect(html).toContain("ñáéíóú");
});
test("should not store in cache on error", async () => {
const exphbs = expressHandlebars.create();
const filePath = "does-not-exist";
expect(exphbs.compiled[filePath]).toBeUndefined();
let error: Error;
try {
await exphbs.getTemplate(filePath);
} catch (e) {
error = e;
}
expect(error.message).toEqual(expect.stringContaining("no such file or directory"));
expect(exphbs.compiled[filePath]).toBeUndefined();
});
});
describe("getTemplates", () => {
test("should return cached templates", async () => {
const exphbs = expressHandlebars.create();
const dirPath = fixturePath("templates");
const fsCache = Promise.resolve([]);
exphbs._fsCache[dirPath] = fsCache;
const templates = await exphbs.getTemplates(dirPath, { cache: true });
expect(templates).toEqual({});
});
test("should return templates", async () => {
const exphbs = expressHandlebars.create();
const dirPath = fixturePath("templates");
const templates = await exphbs.getTemplates(dirPath);
const html = templates["template.handlebars"]({ text: "test text" });
expect(html).toBe("<p>test text</p>");
});
test("should get templates in sub directories", async () => {
const exphbs = expressHandlebars.create();
const dirPath = fixturePath("templates");
const templates = await exphbs.getTemplates(dirPath);
expect(Object.keys(templates)).toEqual([
"subdir/template.handlebars",
"template-latin1.handlebars",
"template.handlebars",
]);
});
});
describe("render", () => {
test("should return cached templates", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("render-cached.handlebars");
exphbs.compiled[filePath] = Promise.resolve(() => "cached");
const html = await exphbs.render(filePath, null, { cache: true });
expect(html).toBe("cached");
});
test("should use helpers", async () => {
const exphbs = expressHandlebars.create({
helpers: {
help: () => "help",
},
});
const filePath = fixturePath("render-helper.handlebars");
const html = await exphbs.render(filePath, { text: "test text" });
expect(html).toBe("<p>help</p>");
});
test("should override helpers", async () => {
const exphbs = expressHandlebars.create({
helpers: {
help: () => "help",
},
});
const filePath = fixturePath("render-helper.handlebars");
const html = await exphbs.render(filePath, { text: "test text" }, {
helpers: {
help: (text: string) => text,
},
});
expect(html).toBe("<p>test text</p>");
});
test("should return html", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("render-text.handlebars");
const html = await exphbs.render(filePath, { text: "test text" });
expect(html).toBe("<p>test text</p>");
});
test("should return html with encoding", async () => {
const exphbs = expressHandlebars.create({
partialsDir: fixturePath("partials"),
});
const filePath = fixturePath("render-latin1.handlebars");
const html = await exphbs.render(filePath, null, { encoding: "latin1" });
expect(html).toContain("partial ñáéíóú");
expect(html).toContain("render ñáéíóú");
});
test("should return html with default encoding", async () => {
const exphbs = expressHandlebars.create({
encoding: "latin1",
partialsDir: fixturePath("partials"),
});
const filePath = fixturePath("render-latin1.handlebars");
const html = await exphbs.render(filePath);
expect(html).toContain("partial ñáéíóú");
expect(html).toContain("render ñáéíóú");
});
test("should render with partial", async () => {
const exphbs = expressHandlebars.create({
partialsDir: fixturePath("partials"),
});
const filePath = fixturePath("render-partial.handlebars");
const html = await exphbs.render(filePath, { text: "test text" });
expect(html.replace(/\r/g, "")).toBe("<h1>partial test text</h1>\n<p>test text</p>");
});
test("should render with runtimeOptions", async () => {
const exphbs = expressHandlebars.create({
runtimeOptions: { allowProtoPropertiesByDefault: true },
});
const filePath = fixturePath("test");
const spy = jest.fn(() => { return "test"; }) as Handlebars.TemplateDelegate;
exphbs.compiled[filePath] = Promise.resolve(spy);
await exphbs.render(filePath, null, { cache: true });
expect(spy).toHaveBeenCalledWith(expect.any(Object), expect.objectContaining({ allowProtoPropertiesByDefault: true }));
});
test("should override runtimeOptions", async () => {
const exphbs = expressHandlebars.create({
runtimeOptions: { allowProtoPropertiesByDefault: true },
});
const filePath = fixturePath("test");
const spy = jest.fn(() => { return "test"; }) as Handlebars.TemplateDelegate;
exphbs.compiled[filePath] = Promise.resolve(spy);
await exphbs.render(filePath, null, {
cache: true,
runtimeOptions: { allowProtoPropertiesByDefault: false },
});
expect(spy).toHaveBeenCalledWith(expect.any(Object), expect.objectContaining({ allowProtoPropertiesByDefault: false }));
});
});
describe("engine", () => {
test("should call renderView", async () => {
jest.spyOn(expressHandlebars.ExpressHandlebars.prototype, "renderView").mockImplementation(() => Promise.resolve(null));
const exphbs = expressHandlebars.create();
const cb = () => { /* empty */ };
exphbs.engine("view", {}, cb);
expect(expressHandlebars.ExpressHandlebars.prototype.renderView).toHaveBeenCalledWith("view", {}, cb);
});
test("should call engine", async () => {
jest.spyOn(expressHandlebars.ExpressHandlebars.prototype, "renderView").mockImplementation(() => Promise.resolve(null));
const cb = () => { /* empty */ };
expressHandlebars.engine()("view", {}, cb);
expect(expressHandlebars.ExpressHandlebars.prototype.renderView).toHaveBeenCalledWith("view", {}, cb);
});
test("should render html", async () => {
const renderView = expressHandlebars.engine({ defaultLayout: null });
const viewPath = fixturePath("render-text.handlebars");
const html = await renderView(viewPath, { text: "test text" } as EngineOptions);
expect(html).toBe("<p>test text</p>");
});
});
describe("renderView", () => {
test("should use settings.views", async () => {
const exphbs = expressHandlebars.create();
const viewPath = fixturePath("render-partial.handlebars");
const viewsPath = fixturePath();
const html = await exphbs.renderView(viewPath, {
text: "test text",
settings: { views: viewsPath },
});
expect(html.replace(/\r/g, "")).toBe("<body>\n<h1>partial test text</h1>\n<p>test text</p>\n</body>");
});
test("should use settings.views array", async () => {
const exphbs = expressHandlebars.create();
const viewPath = fixturePath("render-partial.handlebars");
const viewsPath = fixturePath();
const html = await exphbs.renderView(viewPath, {
text: "test text",
settings: { views: [viewsPath] },
});
expect(html.replace(/\r/g, "")).toBe("<body>\n<h1>partial test text</h1>\n<p>test text</p>\n</body>");
});
test("should not use settings.views array when no parent found", async () => {
const exphbs = expressHandlebars.create({ defaultLayout: null });
const viewPath = fixturePath("render-text.handlebars");
const viewsPath = "does-not-exist";
const html = await exphbs.renderView(viewPath, {
text: "test text",
settings: { views: [viewsPath] },
});
expect(html).toBe("<p>test text</p>");
});
test("should use settings.views when it changes", async () => {
const exphbs = expressHandlebars.create();
const viewPath = fixturePath("render-partial.handlebars");
const viewsPath = fixturePath();
const html = await exphbs.renderView(viewPath, {
text: "test text",
settings: { views: viewsPath },
});
expect(html.replace(/\r/g, "")).toBe("<body>\n<h1>partial test text</h1>\n<p>test text</p>\n</body>");
const otherViewsPath = fixturePath("other-views");
const otherhtml = await exphbs.renderView(viewPath, {
text: "test text",
settings: { views: otherViewsPath },
});
expect(otherhtml.replace(/\r/g, "")).toBe("<body>\nother layout\n<h1>other partial test text</h1>\n<p>test text</p>\n</body>");
});
test("should not overwrite config with settings.views", async () => {
const exphbs = expressHandlebars.create({
layoutsDir: fixturePath("layouts"),
partialsDir: fixturePath("partials"),
});
const viewPath = fixturePath("render-partial.handlebars");
const viewsPath = fixturePath("other-views");
const html = await exphbs.renderView(viewPath, {
text: "test text",
settings: { views: viewsPath },
});
expect(html.replace(/\r/g, "")).toBe("<body>\n<h1>partial test text</h1>\n<p>test text</p>\n</body>");
});
test("should merge helpers", async () => {
const exphbs = expressHandlebars.create({
defaultLayout: null,
helpers: {
help: () => "help",
},
});
const viewPath = fixturePath("render-helper.handlebars");
const html = await exphbs.renderView(viewPath, {
text: "test text",
helpers: {
help: (text: string) => text,
},
});
expect(html).toBe("<p>test text</p>");
});
test("should use layout option", async () => {
const exphbs = expressHandlebars.create({ defaultLayout: null });
const layoutPath = fixturePath("layouts/main.handlebars");
const viewPath = fixturePath("render-text.handlebars");
const html = await exphbs.renderView(viewPath, {
text: "test text",
layout: layoutPath,
});
expect(html.replace(/\r/g, "")).toBe("<body>\n<p>test text</p>\n</body>");
});
test("should render html", async () => {
const exphbs = expressHandlebars.create({ defaultLayout: null });
const viewPath = fixturePath("render-text.handlebars");
const html = await exphbs.renderView(viewPath, { text: "test text" });
expect(html).toBe("<p>test text</p>");
});
test("should render html with encoding", async () => {
const exphbs = expressHandlebars.create({
defaultLayout: "main-latin1",
partialsDir: fixturePath("partials"),
layoutsDir: fixturePath("layouts"),
});
const viewPath = fixturePath("render-latin1.handlebars");
const html = await exphbs.renderView(viewPath, { encoding: "latin1" });
expect(html).toContain("layout ñáéíóú");
expect(html).toContain("partial ñáéíóú");
expect(html).toContain("render ñáéíóú");
});
test("should render html with default encoding", async () => {
const exphbs = expressHandlebars.create({
encoding: "latin1",
defaultLayout: "main-latin1",
partialsDir: fixturePath("partials"),
layoutsDir: fixturePath("layouts"),
});
const viewPath = fixturePath("render-latin1.handlebars");
const html = await exphbs.renderView(viewPath);
expect(html).toContain("layout ñáéíóú");
expect(html).toContain("partial ñáéíóú");
expect(html).toContain("render ñáéíóú");
});
test("should call callback with html", (done) => {
const exphbs = expressHandlebars.create({ defaultLayout: null });
const viewPath = fixturePath("render-text.handlebars");
exphbs.renderView(viewPath, { text: "test text" }, (err: Error|null, html: string) => {
expect(err).toBe(null);
expect(html).toBe("<p>test text</p>");
done();
});
});
test("should call callback as second parameter", (done) => {
const exphbs = expressHandlebars.create({ defaultLayout: null });
const viewPath = fixturePath("render-text.handlebars");
exphbs.renderView(viewPath, (err: Error|null, html: string) => {
expect(err).toBe(null);
expect(html).toBe("<p></p>");
done();
});
});
test("should call callback with error", (done) => {
const exphbs = expressHandlebars.create({ defaultLayout: null });
const viewPath = "does-not-exist";
exphbs.renderView(viewPath, {}, (err: Error|null, html: string) => {
expect(err.message).toEqual(expect.stringContaining("no such file or directory"));
expect(html).toBeUndefined();
done();
});
});
test("should reject with error", async () => {
const exphbs = expressHandlebars.create({ defaultLayout: null });
const viewPath = "does-not-exist";
let error: Error;
try {
await exphbs.renderView(viewPath);
} catch (e) {
error = e;
}
expect(error.message).toEqual(expect.stringContaining("no such file or directory"));
});
test("should use runtimeOptions", async () => {
const exphbs = expressHandlebars.create({ defaultLayout: null });
const filePath = fixturePath("test");
const spy = jest.fn(() => { return "test"; }) as Handlebars.TemplateDelegate;
exphbs.compiled[filePath] = Promise.resolve(spy);
await exphbs.renderView(filePath, {
cache: true,
runtimeOptions: { allowProtoPropertiesByDefault: true },
});
expect(spy).toHaveBeenCalledWith(expect.any(Object), expect.objectContaining({ allowProtoPropertiesByDefault: true }));
});
});
describe("hooks", () => {
describe("_compileTemplate", () => {
test("should call template with context and options", () => {
const exphbs = expressHandlebars.create();
// @ts-expect-error empty function
jest.spyOn(exphbs.handlebars, "compile").mockImplementation(() => {});
const template = "template";
const options = {};
exphbs["_compileTemplate"](template, options);
expect(exphbs.handlebars.compile).toHaveBeenCalledWith(template, options);
});
test("should trim template", () => {
const exphbs = expressHandlebars.create();
// @ts-expect-error empty function
jest.spyOn(exphbs.handlebars, "compile").mockImplementation(() => {});
const template = " template\n";
const options = {};
exphbs["_compileTemplate"](template, options);
expect(exphbs.handlebars.compile).toHaveBeenCalledWith("template", options);
});
});
describe("_precompileTemplate", () => {
test("should call template with context and options", () => {
const exphbs = expressHandlebars.create();
// @ts-expect-error empty function
jest.spyOn(exphbs.handlebars, "precompile").mockImplementation(() => {});
const template = "template";
const options = {};
exphbs["_precompileTemplate"](template, options);
expect(exphbs.handlebars.precompile).toHaveBeenCalledWith(template, options);
});
test("should trim template", () => {
const exphbs = expressHandlebars.create();
// @ts-expect-error empty function
jest.spyOn(exphbs.handlebars, "precompile").mockImplementation(() => {});
const template = " template\n";
const options = {};
exphbs["_precompileTemplate"](template, options);
expect(exphbs.handlebars.precompile).toHaveBeenCalledWith("template", options);
});
});
describe("_renderTemplate", () => {
test("should call template with context and options", () => {
const exphbs = expressHandlebars.create();
const template = jest.fn(() => "");
const context = {};
const options = {};
exphbs["_renderTemplate"](template, context, options);
expect(template).toHaveBeenCalledWith(context, options);
});
test("should trim html", () => {
const exphbs = expressHandlebars.create();
const template = () => " \n";
const html = exphbs["_renderTemplate"](template);
expect(html).toBe("");
});
});
describe("_getDir", () => {
test("should get from cache", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("test");
exphbs._fsCache[filePath] = "test";
const file = await exphbs["_getDir"](filePath, { cache: true });
expect(file).toBe("test");
});
test("should store in cache", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("templates");
expect(exphbs._fsCache[filePath]).toBeUndefined();
await exphbs["_getDir"](filePath);
expect(exphbs._fsCache[filePath]).toBeDefined();
});
test("should not store in cache on error", async () => {
const exphbs = expressHandlebars.create();
const filePath = "test";
expect(exphbs._fsCache[filePath]).toBeUndefined();
let error: Error;
try {
await exphbs["_getDir"](filePath, {
// @ts-expect-error Add this just for testing
_throwTestError: true,
});
} catch (e) {
error = e;
}
expect(error).toBeTruthy();
expect(exphbs._fsCache[filePath]).toBeUndefined();
});
});
describe("_getFile", () => {
test("should get from cache", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("test");
exphbs._fsCache[filePath] = "test";
const file = await exphbs["_getFile"](filePath, { cache: true });
expect(file).toBe("test");
});
test("should store in cache", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("render-text.handlebars");
expect(exphbs._fsCache[filePath]).toBeUndefined();
await exphbs["_getFile"](filePath);
expect(exphbs._fsCache[filePath]).toBeDefined();
});
test("should not store in cache on error", async () => {
const exphbs = expressHandlebars.create();
const filePath = "does-not-exist";
expect(exphbs._fsCache[filePath]).toBeUndefined();
let error: Error;
try {
await exphbs["_getFile"](filePath);
} catch (e) {
error = e;
}
expect(error.message).toEqual(expect.stringContaining("no such file or directory"));
expect(exphbs._fsCache[filePath]).toBeUndefined();
});
test("should read as utf8", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("render-text.handlebars");
const text = await exphbs["_getFile"](filePath);
expect(text.trim()).toBe("<p>{{text}}</p>");
});
test("should read as utf8 by default", async () => {
const exphbs = expressHandlebars.create({ encoding: null });
const filePath = fixturePath("render-text.handlebars");
const text = await exphbs["_getFile"](filePath);
expect(text.trim()).toBe("<p>{{text}}</p>");
});
test("should read as latin1", async () => {
const exphbs = expressHandlebars.create();
const filePath = fixturePath("render-latin1.handlebars");
const text = await exphbs["_getFile"](filePath, { encoding: "latin1" });
expect(text).toContain("ñáéíóú");
});
test("should read as default encoding", async () => {
const exphbs = expressHandlebars.create({ encoding: "latin1" });
const filePath = fixturePath("render-latin1.handlebars");
const text = await exphbs["_getFile"](filePath);
expect(text).toContain("ñáéíóú");
});
});
describe("_getTemplateName", () => {
test("should remove extension", () => {
const exphbs = expressHandlebars.create();
const name = exphbs["_getTemplateName"]("filePath.handlebars");
expect(name).toBe("filePath");
});
test("should leave if no extension", () => {
const exphbs = expressHandlebars.create();
const name = exphbs["_getTemplateName"]("filePath");
expect(name).toBe("filePath");
});
test("should add namespace", () => {
const exphbs = expressHandlebars.create();
const name = exphbs["_getTemplateName"]("filePath.handlebars", "namespace");
expect(name).toBe("namespace/filePath");
});
});
describe("_resolveViewsPath", () => {
test("should return closest parent", () => {
const file = "/root/views/file.hbs";
const exphbs = expressHandlebars.create();
const viewsPath = exphbs["_resolveViewsPath"]([
"/root",
"/root/views",
"/root/views/file",
], file);
expect(viewsPath).toBe("/root/views");
});
test("should return string views", () => {
const exphbs = expressHandlebars.create();
const viewsPath = exphbs["_resolveViewsPath"]("./views", "filePath.hbs");
expect(viewsPath).toBe("./views");
});
test("should return null views", () => {
const exphbs = expressHandlebars.create();
const viewsPath = exphbs["_resolveViewsPath"](null, "filePath.hbs");
expect(viewsPath).toBe(null);
});
test("should return null if not found", () => {
const file = "/file.hbs";
const exphbs = expressHandlebars.create();
const viewsPath = exphbs["_resolveViewsPath"]([
"/views",
], file);
expect(viewsPath).toBe(null);
});
});
describe("_resolveLayoutPath", () => {
test("should add extension", () => {
const exphbs = expressHandlebars.create();
const layoutPath = exphbs["_resolveLayoutPath"]("filePath");
expect(layoutPath).toEqual(expect.stringMatching(/filePath\.handlebars$/));
});
test("should use layoutsDir", () => {
const layoutsDir = fixturePath("layouts");
const filePath = "filePath.handlebars";
const exphbs = expressHandlebars.create({ layoutsDir });
const layoutPath = exphbs["_resolveLayoutPath"](filePath);
expect(layoutPath).toBe(path.resolve(layoutsDir, filePath));
});
test("should return null", () => {
const exphbs = expressHandlebars.create();
const layoutPath = exphbs["_resolveLayoutPath"](null);
expect(layoutPath).toBe(null);
});
});
});
}); | the_stack |
import WatchJS from 'melanke-watchjs';
import { Common } from '../common';
import { Constants } from '../constants';
import { Capivara } from '../index';
import { ScopeProxy } from '../scope/scope.proxy';
import { ComponentConfig } from './component.config';
import { Controller } from './controller';
import { Magic } from './magic/magic';
import { Observe } from './observer';
export class ComponentInstance {
public config: ComponentConfig;
public element: any;
public contextObj: any;
public componentScope;
public destroyed: boolean;
public constantsValue = {};
public functionsValue = {};
public bindingsValue = {};
public listenerContextBindings = {};
constructor(_element, _config: ComponentConfig) {
_config.controllerAs = _config.controllerAs || '$ctrl';
this.element = _element;
this.element.$instance = this;
this.config = _config;
this.config.controller = this.config.controller || function isolatedScope() { };
this.renderTemplate();
this.destroyed = true;
this.registerController();
}
public renderTemplate() {
if (this.config.template) {
if (DOMParser) {
const templateToElm: any = new DOMParser().parseFromString(this.config.template, 'text/html');
const transcludeTemplate = new DOMParser().parseFromString(this.element.innerHTML, 'text/html');
if (transcludeTemplate && templateToElm && transcludeTemplate.querySelectorAll) {
Array.from((transcludeTemplate.querySelectorAll('cp-transclude') || [])).forEach((transclude: any) => {
const attrName = transclude.getAttribute('name');
const query = transclude.nodeName.toLowerCase() + (attrName ? '[name="' + attrName + '"]' : '');
Array.from((templateToElm.querySelectorAll(query) || [])).forEach((transcludeReference: any) => {
Array.from(transclude.children).forEach((children) => {
Common.appendAfter(transcludeReference, children);
});
transcludeReference.parentNode.removeChild(transcludeReference);
});
});
this.element.innerHTML = templateToElm.body.innerHTML;
} else {
this.element.innerHTML = this.config.template;
}
} else {
this.element.innerHTML = this.config.template;
}
}
}
public registerController() {
new Controller(this.element, (scope) => {
this.componentScope = scope;
});
}
public initController() {
if (this.destroyed) {
this.destroyed = false;
if (this.config.controller) {
const args = [
this.componentScope.element[Constants.SCOPE_ATTRIBUTE_NAME],
this.componentScope.mapDom.element,
this.componentScope.mapDom,
];
this.componentScope[this.config.controllerAs] = new this.config.controller(...args);
}
this.contextObj = Magic.getContext(this.element);
this.applyConstantsComponentMagic();
this.applyFunctionsComponentMagic();
this.applyBindingsComponentMagic();
if (this.componentScope[this.config.controllerAs] && this.componentScope[this.config.controllerAs].$onInit) {
this.componentScope[this.config.controllerAs].$onInit();
}
Object.defineProperty(this.componentScope, '__$controllerAs__', {
value: this.config.controllerAs,
configurable: true,
});
const context = Common.getScope(this.element);
context.$emit('$onInit');
context.mapDom.reload();
}
}
/**
* @description Aplica os bindings|constants|functions
*/
public build() {
this.applyConstantsComponentBuilder();
this.applyFunctionsComponentBuilder();
if (this.contextObj) {
this.applyBindingsComponentBuilder();
}
const context = Common.getScope(this.element);
if (context.scope.$ctrl.$onBuild) {
context.scope.$ctrl.$onBuild();
}
}
/**
* @description Renderiza o template no elemento.
*/
public create() {
this.initController();
}
/**
* @description Função executada quando o elemento é destruído do documento.
*/
public destroy() {
this.destroyed = true;
this.element[Constants.SCOPE_ATTRIBUTE_NAME].destroy();
Observe.unobserve(this.componentScope[this.config.controllerAs]);
if (this.componentScope[this.config.controllerAs] && this.componentScope[this.config.controllerAs].$destroy) {
this.componentScope[this.config.controllerAs].$destroy();
}
if (this.componentScope[this.config.controllerAs] && this.componentScope[this.config.controllerAs].$onDestroy) {
this.componentScope[this.config.controllerAs].$onDestroy();
}
try {
window['capivara'].scopes = window['capivara'].scopes.filter((scope) => {
return scope.id !== this.componentScope.element[Constants.SCOPE_ATTRIBUTE_NAME].id &&
scope.id !== this.contextObj.element[Constants.SCOPE_ATTRIBUTE_NAME].id;
});
} catch (e) { }
}
/**
* @description
* @param obj Contexto dos bindings, o contexto é o objeto que possui os valores dos bindings
*/
public context(obj) {
this.contextObj = obj;
return this;
}
/**
* @description Cria os bindings que o componente espera.
* @param _bindings Objeto com o nome dos bindings
*/
public bindings(_bindings = {}) {
if (!this.contextObj) {
console.error('Bindings ainda não aplicados. Primeiro, é necessário informar o contexto.');
return this;
}
this.bindingsValue = Object.assign(this.bindingsValue, _bindings);
return this;
}
public applyBindingsComponentBuilder() {
(this.config.bindings || []).forEach((key) => {
this.setAttributeValue(this.bindingsValue, key);
this.createObserverContext(this.bindingsValue, key);
});
this.createObserverScope(this.bindingsValue);
}
public applyBindingsComponentMagic() {
if (!Common.getScope(this.element).scope[this.config.controllerAs]['$bindings']) {
Common.set(Common.getScope(this.element).scope, this.config.controllerAs + '.$bindings', {});
Common.set(Common.getScope(this.element).scope, '$bindings', {});
}
(this.config.bindings || []).forEach((bindingKey) => {
const bindAttribute = bindingKey.replace(/([A-Z])/g, "-$1").toLowerCase();
const valueAttribute = this.element.getAttribute(bindAttribute);
if (valueAttribute) {
this.bindingsValue[bindingKey] = valueAttribute;
this.setAttributeValue(this.bindingsValue, bindingKey);
this.createObserverContext(this.bindingsValue, bindingKey);
}
});
this.createObserverScope(this.bindingsValue);
}
/**
* @description Observa o componente quando houver alteração é modificado o contexto
*/
public createObserverScope(_bindings = {}) {
const $ctrl = Common.getScope(this.element).scope[this.config.controllerAs];
Object.defineProperty($ctrl, '_$$checkBindings', {
value: (changes) => {
changes.forEach((change) => {
if (change.type === 'update' && _bindings.hasOwnProperty(change.name)) {
Common.set(this.contextObj, _bindings[change.name], change.object[change.name]);
this.forceUpdateContext();
}
});
},
writable: true,
configurable: true,
});
}
private forceUpdateContext() {
if (this.contextObj) {
if (this.contextObj['$forceUpdate']) {
this.contextObj['$forceUpdate']();
}
if (this.contextObj['$apply']) {
this.contextObj['$apply']();
}
if (this.contextObj['forceUpdate']) {
this.contextObj['forceUpdate']();
}
if (window['ng']) {
const debugContext = window['ng'].probe(this.element);
if (debugContext) {
debugContext.injector.get(window['ng'].coreTokens.ApplicationRef).tick();
}
}
}
}
/**
* @description Observa o contexto, quando houver alteração é modificado no escopo do componente
*/
public static getFirstAttribute(_bindings = {}, key) {
return _bindings[key].indexOf('.') !== -1 ? _bindings[key].substring(0, _bindings[key].indexOf('.')) : _bindings[key];
}
public observeAndSetValues(obj, _bindings, key) {
Observe.observe(obj, () => {
this.setAttributeValue(_bindings, key);
});
}
public createObserverContext(_bindings, key) {
if (!_bindings[key]) {
return;
}
if (this.contextObj instanceof ScopeProxy) {
if (this.contextObj[this.config.controllerAs]) {
this.observeAndSetValues(this.contextObj[this.config.controllerAs], _bindings, key);
} else {
this.observeAndSetValues(this.contextObj, _bindings, key);
}
} else {
const attrToObserve = ComponentInstance.getFirstAttribute(_bindings, key);
WatchJS.watch(this.contextObj, attrToObserve,
() => {
this.setAttributeValue(_bindings, key);
}, 1);
}
}
public setAttributeRecursive(element, bindKey) {
const scope = Common.getScope(element).scope;
const bindKeyFormatted = bindKey.replace(/([A-Z])/g, "-$1").toLowerCase();
Object.keys((Capivara.components)).forEach((key) => {
const componentName = key.toLowerCase();
const components = Array.from(this.element.querySelectorAll(componentName));
components.forEach((component: any) => {
if (component.firstChild) {
const componentCtx = Common.getScope(component.firstChild).scope;
Common.set(componentCtx[this.config.controllerAs], '$bindings.' + bindKey, Common.get(scope, component.getAttribute(bindKeyFormatted)));
}
});
});
}
public setAttributeValue(_bindings = {}, key) {
const parentRepeat = Common.parentHasRepeat(this.element), scope = Common.getScope(this.element).scope;
if (this.contextObj instanceof ScopeProxy && _bindings[key].startsWith(this.config.controllerAs) && parentRepeat) {
const ctx = Common.getScope(parentRepeat);
if (ctx.$parent) {
Common.set(scope, this.config.controllerAs + '.$bindings.' + key, Common.get(ctx.$parent.scope, _bindings[key]));
Common.set(scope, '$bindings.' + key, Common.get(ctx.$parent.scope, _bindings[key]));
}
} else {
Common.set(scope[this.config.controllerAs], '$bindings.' + key, Common.get(this.contextObj, _bindings[key]));
Common.set(scope, '$bindings.' + key, Common.get(this.contextObj, _bindings[key]));
}
this.setAttributeRecursive(this.element, key);
if (scope[this.config.controllerAs] && scope[this.config.controllerAs].$onChanges) {
scope[this.config.controllerAs].$onChanges();
}
}
/**
* @description Crie valores sem referências
* @param _constants Objeto com o nome das constants
*/
public constants(_constants = {}) {
this.constantsValue = _constants;
return this;
}
public applyConstantsComponentMagic() {
if (!Common.getScope(this.element).scope[this.config.controllerAs]['$constants']) {
Common.set(Common.getScope(this.element).scope, this.config.controllerAs + '.$constants', {});
Common.set(Common.getScope(this.element).scope, '$constants', {});
}
(this.config.constants || []).forEach((constantKey) => {
const bindAttribute = constantKey.replace(/([A-Z])/g, "-$1").toLowerCase();
const valueAttribute = this.element.getAttribute(bindAttribute);
if (valueAttribute) {
const constantValue = Common.evalInContext(valueAttribute, this.contextObj);
Common.set(Common.getScope(this.element).scope, this.config.controllerAs + '.$constants.' + constantKey, constantValue);
Common.set(Common.getScope(this.element).scope, '$constants.' + constantKey, constantValue);
}
});
}
public applyConstantsComponentBuilder() {
(this.config.constants || []).forEach((key) => {
Common.set(Common.getScope(this.element).scope, this.config.controllerAs + '.$constants.' + key, this.constantsValue[key]);
// Mantém compatibilidade
Common.set(Common.getScope(this.element).scope, '$constants.' + key, this.constantsValue[key]);
});
}
public functions(_functions = {}) {
this.functionsValue = _functions;
return this;
}
public applyFunctionsComponentMagic() {
if (!Common.getScope(this.element).scope[this.config.controllerAs]['$functions']) {
Common.set(Common.getScope(this.element).scope, this.config.controllerAs + '.$functions', {});
Common.set(Common.getScope(this.element).scope, '$functions', {});
}
(this.config.functions || []).forEach((functionKey) => {
const bindAttribute = functionKey.replace(/([A-Z])/g, "-$1").toLowerCase();
const valueAttribute = this.element.getAttribute(bindAttribute);
if (valueAttribute) {
const indexRelative = valueAttribute.indexOf('(');
const callback = indexRelative !== -1 ? Common.get(this.contextObj, valueAttribute.substring(0, indexRelative)) : Common.get(this.contextObj, valueAttribute);
if (callback) {
Object.defineProperty(callback, '__ctx__', {
value: this.contextObj,
configurable: true,
});
Common.set(Common.getScope(this.element).scope, this.config.controllerAs + '.$functions.' + functionKey, callback);
Common.set(Common.getScope(this.element).scope, '$functions.' + functionKey, callback);
}
}
});
}
public applyFunctionsComponentBuilder() {
(this.config.functions || []).forEach((key) => {
Common.set(Common.getScope(this.element).scope, this.config.controllerAs + '.$functions.' + key, this.functionsValue[key]);
Common.set(Common.getScope(this.element).scope, '$functions.' + key, this.functionsValue[key]);
});
}
} | the_stack |
import { BasicClient } from "../BasicClient";
import { Candle } from "../Candle";
import { CandlePeriod } from "../CandlePeriod";
import { batch } from "../flowcontrol/Batch";
import { CancelableFn } from "../flowcontrol/Fn";
import { throttle } from "../flowcontrol/Throttle";
import { Level2Point } from "../Level2Point";
import { Level2Snapshot } from "../Level2Snapshots";
import { Ticker } from "../Ticker";
import { Trade } from "../Trade";
import { Market } from "../Market";
import { Level2Update } from "../Level2Update";
import * as https from "../Https";
export type BinanceClientOptions = {
name?: string;
wssPath?: string;
restL2SnapshotPath?: string;
watcherMs?: number;
useAggTrades?: boolean;
requestSnapshot?: boolean;
socketBatchSize?: number;
socketThrottleMs?: number;
restThrottleMs?: number;
l2updateSpeed?: string;
l2snapshotSpeed?: string;
testNet?: boolean;
batchTickers?: boolean;
};
export class BinanceBase extends BasicClient {
public useAggTrades: boolean;
public l2updateSpeed: string;
public l2snapshotSpeed: string;
public requestSnapshot: boolean;
public candlePeriod: CandlePeriod;
public batchTickers: boolean;
protected _messageId: number;
protected _restL2SnapshotPath: string;
protected _tickersActive: boolean;
protected _batchSub: CancelableFn;
protected _batchUnsub: CancelableFn;
protected _sendMessage: CancelableFn;
protected _requestLevel2Snapshot: CancelableFn;
constructor({
name,
wssPath,
restL2SnapshotPath,
watcherMs = 30000,
useAggTrades = true,
requestSnapshot = true,
socketBatchSize = 200,
socketThrottleMs = 1000,
restThrottleMs = 1000,
l2updateSpeed = "",
l2snapshotSpeed = "",
batchTickers = true,
}: BinanceClientOptions = {}) {
super(wssPath, name, undefined, watcherMs);
this._restL2SnapshotPath = restL2SnapshotPath;
this.useAggTrades = useAggTrades;
this.l2updateSpeed = l2updateSpeed;
this.l2snapshotSpeed = l2snapshotSpeed;
this.requestSnapshot = requestSnapshot;
this.hasTickers = true;
this.hasTrades = true;
this.hasCandles = true;
this.hasLevel2Snapshots = true;
this.hasLevel2Updates = true;
this.batchTickers = batchTickers;
this._messageId = 0;
this._tickersActive = false;
this.candlePeriod = CandlePeriod._1m;
this._batchSub = batch(this.__batchSub.bind(this), socketBatchSize);
this._batchUnsub = batch(this.__batchUnsub.bind(this), socketBatchSize);
this._sendMessage = throttle(this.__sendMessage.bind(this), socketThrottleMs);
this._requestLevel2Snapshot = throttle(
this.__requestLevel2Snapshot.bind(this),
restThrottleMs,
);
}
//////////////////////////////////////////////
protected _onClosing() {
this._tickersActive = false;
this._batchSub.cancel();
this._batchUnsub.cancel();
this._sendMessage.cancel();
this._requestLevel2Snapshot.cancel();
super._onClosing();
}
protected _sendSubTicker(remote_id: string) {
if (this.batchTickers) {
if (this._tickersActive) return;
this._tickersActive = true;
this._wss.send(
JSON.stringify({
method: "SUBSCRIBE",
params: ["!ticker@arr"],
id: ++this._messageId,
}),
);
} else {
this._wss.send(
JSON.stringify({
method: "SUBSCRIBE",
params: [`${remote_id.toLowerCase()}@ticker`],
id: ++this._messageId,
}),
);
}
}
protected _sendUnsubTicker(remote_id: string) {
if (this.batchTickers) {
if (this._tickerSubs.size > 1) return;
this._tickersActive = false;
this._wss.send(
JSON.stringify({
method: "UNSUBSCRIBE",
params: ["!ticker@arr"],
id: ++this._messageId,
}),
);
} else {
this._wss.send(
JSON.stringify({
method: "UNSUBSCRIBE",
params: [`${remote_id.toLowerCase()}@ticker`],
id: ++this._messageId,
}),
);
}
}
protected __batchSub(args: any[]) {
const params = args.map(p => p[0]);
const id = ++this._messageId;
const msg = JSON.stringify({
method: "SUBSCRIBE",
params,
id,
});
this._sendMessage(msg);
}
protected __batchUnsub(args) {
const params = args.map(p => p[0]);
const id = ++this._messageId;
const msg = JSON.stringify({
method: "UNSUBSCRIBE",
params,
id,
});
this._sendMessage(msg);
}
protected __sendMessage(msg) {
this._wss.send(msg);
}
protected _sendSubTrades(remote_id: string) {
const stream = remote_id.toLowerCase() + (this.useAggTrades ? "@aggTrade" : "@trade");
this._batchSub(stream);
}
protected _sendUnsubTrades(remote_id: string) {
const stream = remote_id.toLowerCase() + (this.useAggTrades ? "@aggTrade" : "@trade");
this._batchUnsub(stream);
}
protected _sendSubCandles(remote_id: string) {
const stream = remote_id.toLowerCase() + "@kline_" + candlePeriod(this.candlePeriod);
this._batchSub(stream);
}
protected _sendUnsubCandles(remote_id: string) {
const stream = remote_id.toLowerCase() + "@kline_" + candlePeriod(this.candlePeriod);
this._batchUnsub(stream);
}
protected _sendSubLevel2Snapshots(remote_id: string) {
const stream =
remote_id.toLowerCase() +
"@depth20" +
(this.l2snapshotSpeed ? `@${this.l2snapshotSpeed}` : "");
this._batchSub(stream);
}
protected _sendUnsubLevel2Snapshots(remote_id: string) {
const stream =
remote_id.toLowerCase() +
"@depth20" +
(this.l2snapshotSpeed ? `@${this.l2snapshotSpeed}` : "");
this._batchUnsub(stream);
}
protected _sendSubLevel2Updates(remote_id: string) {
if (this.requestSnapshot)
this._requestLevel2Snapshot(this._level2UpdateSubs.get(remote_id));
const stream =
remote_id.toLowerCase() +
"@depth" +
(this.l2updateSpeed ? `@${this.l2updateSpeed}` : "");
this._batchSub(stream);
}
protected _sendUnsubLevel2Updates(remote_id: string) {
const stream =
remote_id.toLowerCase() +
"@depth" +
(this.l2updateSpeed ? `@${this.l2updateSpeed}` : "");
this._batchUnsub(stream);
}
protected _sendSubLevel3Snapshots() {
throw new Error("Method not implemented.");
}
protected _sendUnsubLevel3Snapshots() {
throw new Error("Method not implemented.");
}
protected _sendSubLevel3Updates() {
throw new Error("Method not implemented.");
}
protected _sendUnsubLevel3Updates() {
throw new Error("Method not implemented.");
}
/////////////////////////////////////////////
protected _onMessage(raw: string) {
const msg = JSON.parse(raw);
// subscribe/unsubscribe responses
if (msg.result === null && msg.id) {
// console.log(msg);
return;
}
// errors
if (msg.error) {
const error = new Error(msg.error.msg) as any;
error.msg = msg;
this.emit("error", error);
}
// All code past this point relies on msg.stream in some manner. This code
// acts as a guard on msg.stream and aborts prematurely if the property is
// not available.
if (!msg.stream) {
return;
}
// ticker
if (msg.stream === "!ticker@arr") {
for (const raw of msg.data) {
const remote_id = raw.s;
const market = this._tickerSubs.get(remote_id);
if (!market) continue;
const ticker = this._constructTicker(raw, market);
this.emit("ticker", ticker, market);
}
return;
}
// trades
if (msg.stream.toLowerCase().endsWith("trade")) {
const remote_id = msg.data.s;
const market = this._tradeSubs.get(remote_id);
if (!market) return;
const trade = this.useAggTrades
? this._constructAggTrade(msg, market)
: this._constructRawTrade(msg, market);
this.emit("trade", trade, market);
return;
}
// candle
if (msg.data.e === "kline") {
const remote_id = msg.data.s;
const market = this._candleSubs.get(remote_id);
if (!market) return;
const candle = this._constructCandle(msg);
this.emit("candle", candle, market);
return;
}
// l2snapshot
if (msg.stream.match(/@depth20/)) {
const remote_id = msg.stream.split("@")[0].toUpperCase();
const market = this._level2SnapshotSubs.get(remote_id);
if (!market) return;
const snapshot = this._constructLevel2Snapshot(msg, market);
this.emit("l2snapshot", snapshot, market);
return;
}
// l2update
if (msg.stream.match(/@depth/)) {
const remote_id = msg.stream.split("@")[0].toUpperCase();
const market = this._level2UpdateSubs.get(remote_id);
if (!market) return;
const update = this._constructLevel2Update(msg, market);
this.emit("l2update", update, market);
return;
}
}
protected _constructTicker(msg, market: Market) {
const {
E: timestamp,
c: last,
v: volume,
q: quoteVolume,
h: high,
l: low,
p: change,
P: changePercent,
a: ask,
A: askVolume,
b: bid,
B: bidVolume,
} = msg;
const open = parseFloat(last) + parseFloat(change);
return new Ticker({
exchange: this.name,
base: market.base,
quote: market.quote,
timestamp: timestamp,
last,
open: open.toFixed(8),
high,
low,
volume,
quoteVolume,
change,
changePercent,
bid,
bidVolume,
ask,
askVolume,
});
}
protected _constructAggTrade({ data }, market: Market) {
const { a: trade_id, p: price, q: size, T: time, m: buyer } = data;
const unix = time;
const amount = size;
const side = buyer ? "buy" : "sell";
return new Trade({
exchange: this.name,
base: market.base,
quote: market.quote,
tradeId: trade_id.toFixed(),
unix,
side,
price,
amount,
});
}
protected _constructRawTrade({ data }, market: Market) {
const {
t: trade_id,
p: price,
q: size,
b: buyOrderId,
a: sellOrderId,
T: time,
m: buyer,
} = data;
const unix = time;
const amount = size;
const side = buyer ? "buy" : "sell";
return new Trade({
exchange: this.name,
base: market.base,
quote: market.quote,
tradeId: trade_id,
unix,
side,
price,
amount,
buyOrderId,
sellOrderId,
});
}
/**
* Kline data looks like:
{ stream: 'btcusdt@kline_1m',
data:
{ e: 'kline',
E: 1571068845689,
s: 'BTCUSDT',
k:
{ t: 1571068800000,
T: 1571068859999,
s: 'BTCUSDT',
i: '1m',
f: 189927800,
L: 189928107,
o: '8254.05000000',
c: '8253.61000000',
h: '8256.58000000',
l: '8250.93000000',
v: '19.10571600',
n: 308,
x: false,
q: '157694.32610840',
V: '8.19456200',
Q: '67640.56793106',
B: '0' } } }
*/
protected _constructCandle({ data }) {
const k = data.k;
return new Candle(k.t, k.o, k.h, k.l, k.c, k.v);
}
protected _constructLevel2Snapshot(msg, market: Market) {
const sequenceId = msg.data.lastUpdateId;
const asks = msg.data.asks.map(p => new Level2Point(p[0], p[1]));
const bids = msg.data.bids.map(p => new Level2Point(p[0], p[1]));
return new Level2Snapshot({
exchange: this.name,
base: market.base,
quote: market.quote,
sequenceId,
asks,
bids,
});
}
/**
{
"e": "depthUpdate", // Event type
"E": 123456789, // Event time
"s": "BNBBTC", // Symbol
"U": 157, // First update ID in event
"u": 160, // Final update ID in event
"b": [ // Bids to be updated
[
"0.0024", // Price level to be updated
"10" // Quantity
]
],
"a": [ // Asks to be updated
[
"0.0026", // Price level to be updated
"100" // Quantity
]
]
}
*/
protected _constructLevel2Update(msg, market) {
const eventMs = msg.data.E;
const sequenceId = msg.data.U;
const lastSequenceId = msg.data.u;
const asks = msg.data.a.map(p => new Level2Point(p[0], p[1]));
const bids = msg.data.b.map(p => new Level2Point(p[0], p[1]));
return new Level2Update({
exchange: this.name,
base: market.base,
quote: market.quote,
sequenceId,
lastSequenceId,
eventMs,
asks,
bids,
});
}
protected async __requestLevel2Snapshot(market) {
let failed = false;
try {
const remote_id = market.id;
const uri = `${this._restL2SnapshotPath}?limit=1000&symbol=${remote_id}`;
const raw = (await https.get(uri)) as any;
const sequenceId = raw.lastUpdateId;
const timestampMs = raw.E;
const asks = raw.asks.map(p => new Level2Point(p[0], p[1]));
const bids = raw.bids.map(p => new Level2Point(p[0], p[1]));
const snapshot = new Level2Snapshot({
exchange: this.name,
base: market.base,
quote: market.quote,
sequenceId,
timestampMs,
asks,
bids,
});
this.emit("l2snapshot", snapshot, market);
} catch (ex) {
this.emit("error", ex);
failed = true;
} finally {
if (failed) this._requestLevel2Snapshot(market);
}
}
}
export function candlePeriod(p) {
switch (p) {
case CandlePeriod._1m:
return "1m";
case CandlePeriod._3m:
return "3m";
case CandlePeriod._5m:
return "5m";
case CandlePeriod._15m:
return "15m";
case CandlePeriod._30m:
return "30m";
case CandlePeriod._1h:
return "1h";
case CandlePeriod._2h:
return "2h";
case CandlePeriod._4h:
return "4h";
case CandlePeriod._6h:
return "6h";
case CandlePeriod._8h:
return "8h";
case CandlePeriod._12h:
return "12h";
case CandlePeriod._1d:
return "1d";
case CandlePeriod._3d:
return "3d";
case CandlePeriod._1w:
return "1w";
case CandlePeriod._1M:
return "1M";
}
} | the_stack |
import { ChildProcess } from 'child_process';
import * as events from 'events';
import { inject, injectable } from 'inversify';
import * as path from 'path';
import * as apid from '../../../../api';
import FileUtil from '../../../util/FileUtil';
import ProcessUtil from '../../../util/ProcessUtil';
import Util from '../../../util/Util';
import IVideoUtil, { VideoInfo } from '../../api/video/IVideoUtil';
import IChannelDB from '../../db/IChannelDB';
import IRecordedDB from '../../db/IRecordedDB';
import IVideoFileDB from '../../db/IVideoFileDB';
import IEncodeEvent from '../../event/IEncodeEvent';
import IConfiguration from '../../IConfiguration';
import ILogger from '../../ILogger';
import ILoggerModel from '../../ILoggerModel';
import IEncodeFileManageModel from './IEncodeFileManageModel';
import IEncodeProcessManageModel from './IEncodeProcessManageModel';
import { EncodeOption, EncodeProgressInfo, IEncoderModel } from './IEncoderModel';
@injectable()
class EncoderModel implements IEncoderModel {
private log: ILogger;
private configure: IConfiguration;
private processManager: IEncodeProcessManageModel;
private fileManager: IEncodeFileManageModel;
private videoFileDB: IVideoFileDB;
private recordedDB: IRecordedDB;
private channelDB: IChannelDB;
private videoUtil: IVideoUtil;
private encodeEvent: IEncodeEvent;
private listener: events.EventEmitter = new events.EventEmitter();
private encodeOption: EncodeOption | null = null; // エンコード情報
private childProcess: ChildProcess | null = null; // エンコードプロセス
private timerId: NodeJS.Timer | null = null; // タイムアウト検知用タイマーid
private isCanceld: boolean = false; // キャンセルが呼び出されたか?
private progressInfo: EncodeProgressInfo | null = null;
constructor(
@inject('ILoggerModel') logger: ILoggerModel,
@inject('IConfiguration') configure: IConfiguration,
@inject('IEncodeProcessManageModel') processManager: IEncodeProcessManageModel,
@inject('IEncodeFileManageModel') fileManager: IEncodeFileManageModel,
@inject('IVideoFileDB') videoFileDB: IVideoFileDB,
@inject('IRecordedDB') recordedDB: IRecordedDB,
@inject('IChannelDB') channelDB: IChannelDB,
@inject('IVideoUtil') videoUtil: IVideoUtil,
@inject('IEncodeEvent') encodeEvent: IEncodeEvent,
) {
this.log = logger.getLogger();
this.configure = configure;
this.processManager = processManager;
this.fileManager = fileManager;
this.videoFileDB = videoFileDB;
this.recordedDB = recordedDB;
this.channelDB = channelDB;
this.videoUtil = videoUtil;
this.encodeEvent = encodeEvent;
}
/**
* エンコードに必要な設定をセットする
* @param encodeOption: EncodeOption
*/
public setOption(encodeOption: EncodeOption): void {
if (this.encodeOption !== null) {
this.log.encode.error('encodeOption is not null');
throw new Error('EncodeSetOptionError');
}
this.encodeOption = encodeOption;
}
/**
* エンコード終了イベント登録
* @param callback
*/
public setOnFinish(callback: (isError: boolean, outputFilePath: string | null) => void): void {
this.listener.once(EncoderModel.ENCODE_FINISH_EVENT, (isError: boolean, outputFilePath: string | null) => {
callback(isError, outputFilePath);
});
}
/**
* エンコード開始
*/
public async start(): Promise<void> {
if (this.encodeOption === null) {
this.log.encode.error('encodeOption is null');
throw new Error('EncodeOptionIsNull');
}
// エンコード元ファイルの情報を取得
const video = await this.videoFileDB.findId(this.encodeOption.sourceVideoFileId);
if (video === null) {
throw new Error('VideoFileIdIsNotFound');
}
// 番組情報を取得する
const recorded = await this.recordedDB.findId(this.encodeOption.recordedId);
if (recorded === null) {
throw new Error('RecordedIsNotFound');
}
// 放送局情報を取得する
const channel = await this.channelDB.findId(recorded.channelId);
if (channel === null) {
throw new Error('CannelIsNotFound');
}
// ソースビデオファイルのファイルパスを生成する
const inputFilePath = await this.videoUtil.getFullFilePathFromId(this.encodeOption.sourceVideoFileId);
if (inputFilePath === null) {
throw new Error('VideoPathIsNotFound');
}
// ソースビデオファイルの存在を確認
try {
await FileUtil.stat(inputFilePath);
} catch (err) {
this.log.encode.error(`video file is not found: ${inputFilePath}`);
throw err;
}
// エンコードコマンド設定を探す
const encodeCmd = this.configure.getConfig().encode.find(enc => {
return enc.name === this.encodeOption?.mode;
});
if (typeof encodeCmd === 'undefined') {
throw new Error('EncodeCommandIsNotFound');
}
// 出力先ディレクトリパスを取得する
const outputDirPath = typeof encodeCmd.suffix === 'undefined' ? null : this.getDirPath(this.encodeOption);
// 出力先ディレクトリの存在確認 & 作成
if (outputDirPath !== null) {
try {
await FileUtil.stat(outputDirPath);
} catch (e) {
// ディレクトリが存在しなければ作成する
this.log.encode.info(`mkdirp: ${outputDirPath}`);
await FileUtil.mkdir(outputDirPath);
}
}
// 出力先をファイルパスを生成する
const outputFilePath =
outputDirPath === null || typeof encodeCmd.suffix === 'undefined'
? null
: await this.fileManager.getFilePath(outputDirPath, inputFilePath, encodeCmd.suffix);
const config = this.configure.getConfig();
// DIR
let dir: string = '';
if (typeof encodeCmd.suffix === 'undefined' && typeof this.encodeOption.directory !== 'undefined') {
dir = this.encodeOption.directory;
} else if (outputFilePath !== null) {
dir = outputFilePath;
}
// エンコード開始
this.log.encode.info(
`encode start. mode: ${this.encodeOption.mode} name: ${recorded.name} file: ${inputFilePath} -> ${outputFilePath}`,
);
this.log.encode.info(`encodeId: ${this.encodeOption.encodeId}`);
this.log.encode.info(`encodeCmd.suffix: ${encodeCmd.suffix}`);
this.log.encode.info(`queueItem.directory: ${this.encodeOption.directory}`);
this.log.encode.info(`outputFilePath: ${outputFilePath}`);
// プロセスの生成
this.childProcess = await this.processManager.create({
input: inputFilePath,
output: outputFilePath,
cmd: encodeCmd.cmd,
priority: EncoderModel.ENCODE_PRIPORITY,
spawnOption: {
env: {
...process.env,
RECORDEDID: recorded.id.toString(10),
INPUT: inputFilePath,
OUTPUT: outputFilePath === null ? '' : outputFilePath,
DIR: dir,
SUBDIR: this.encodeOption.directory || '',
FFMPEG: config.ffmpeg,
FFPROBE: config.ffprobe,
NAME: recorded.name,
HALF_WIDTH_NAME: recorded.halfWidthName,
DESCRIPTION: recorded.description || '',
HALF_WIDTH_DESCRIPTION: recorded.halfWidthDescription || '',
EXTENDED: recorded.extended || '',
HALF_WIDTH_EXTENDED: recorded.halfWidthExtended || '',
VIDEOTYPE: recorded.videoType || '',
VIDEORESOLUTION: recorded.videoResolution || '',
VIDEOSTREAMCONTENT:
typeof recorded.videoStreamContent === 'number' ? recorded.videoStreamContent.toString(10) : '',
VIDEOCOMPONENTTYPE:
typeof recorded.videoComponentType === 'number' ? recorded.videoComponentType.toString(10) : '',
AUDIOSAMPLINGRATE:
typeof recorded.audioSamplingRate === 'number' ? recorded.audioSamplingRate.toString(10) : '',
AUDIOCOMPONENTTYPE:
typeof recorded.audioComponentType === 'number' ? recorded.audioComponentType.toString(10) : '',
CHANNELID: typeof recorded.channelId === 'number' ? recorded.channelId.toString(10) : '',
CHANNELNAME: typeof channel.name === 'string' ? channel.name : '',
HALF_WIDTH_CHANNELNAME: typeof channel.halfWidthName === 'string' ? channel.halfWidthName : '',
GENRE1: typeof recorded.genre1 === 'number' ? recorded.genre1.toString(10) : '',
SUBGENRE1: typeof recorded.subGenre1 === 'number' ? recorded.subGenre1.toString(10) : '',
GENRE2: typeof recorded.genre2 === 'number' ? recorded.genre2.toString(10) : '',
SUBGENRE2: typeof recorded.subGenre2 === 'number' ? recorded.subGenre2.toString(10) : '',
GENRE3: typeof recorded.genre3 === 'number' ? recorded.genre3.toString(10) : '',
SUBGENRE3: typeof recorded.subGenre3 === 'number' ? recorded.subGenre3.toString(10) : '',
START_AT: recorded.startAt.toString(10),
END_AT: recorded.endAt.toString(10),
DROPLOG_ID: recorded.dropLogFile?.id.toString(10) || '',
DROPLOG_PATH: recorded.dropLogFile?.filePath || '',
ERROR_CNT: recorded.dropLogFile?.errorCnt.toString(10) || '',
DROP_CNT: recorded.dropLogFile?.dropCnt.toString(10) || '',
SCRAMBLING_CNT: recorded.dropLogFile?.scramblingCnt.toString(10) || '',
},
},
});
// タイムアウト設定
this.timerId = setTimeout(async () => {
if (this.encodeOption === null) {
return;
}
this.log.encode.error(`encode process is time out: ${this.encodeOption.encodeId} ${outputFilePath}`);
await this.cancel();
}, recorded.duration * (typeof encodeCmd.rate === 'undefined' ? EncoderModel.DEFAULT_TIMEOUT_RATE : encodeCmd.rate));
/**
* プロセスの設定
*/
// debug 用
if (this.childProcess.stderr !== null) {
this.childProcess.stderr.on('data', data => {
this.log.encode.debug(String(data));
});
}
// 進捗情報更新用
if (this.childProcess.stdout !== null) {
let videoInfo: VideoInfo | null = null;
try {
videoInfo = await this.videoUtil.getInfo(inputFilePath);
} catch (err) {
this.log.encode.error(`get encode vidoe file info: ${inputFilePath}`);
this.log.encode.error(err);
}
if (videoInfo !== null) {
// エンコードプロセスの標準出力から進捗情報を取り出す
this.childProcess.stdout.on('data', data => {
try {
this.updateEncodingProgressInfo(data);
} catch (err) {
// error
}
});
}
}
// プロセス終了処理
this.childProcess.on('exit', async (code, signal) => {
this.childEndProcessing(code, signal, outputFilePath);
});
// プロセスの即時終了対応
if (ProcessUtil.isExited(this.childProcess) === true) {
this.childEndProcessing(this.childProcess.exitCode, this.childProcess.signalCode, outputFilePath);
this.childProcess.removeAllListeners();
}
}
/**
* queueItem で指定された dir パスを取得する
* @param queueItem: EncodeOption
* @return string
*/
private getDirPath(queueItem: EncodeOption): string {
const parentDir = this.videoUtil.getParentDirPath(queueItem.parentDir);
if (parentDir === null) {
this.log.encode.error(`parent dir config is not found: ${queueItem.parentDir}`);
throw new Error('parentDirIsNotFound');
}
return typeof queueItem.directory === 'undefined' ? parentDir : path.join(parentDir, queueItem.directory);
}
/**
* エンコード進捗情報更新
* @param data: エンコードプロセスの標準出力
* @param encodeId: apid.EncodeId
*/
private updateEncodingProgressInfo(data: any): void {
if (this.encodeOption === null) {
return;
}
const logs = String(data).split('\n');
for (let j = 0; j < logs.length; j++) {
if (logs[j] != '') {
const log = JSON.parse(String(logs[j]));
this.log.encode.debug(log);
if (log.type === 'progress' && typeof log.percent === 'number' && typeof log.log === 'string') {
this.progressInfo = {
percent: log.percent,
log: log.log,
};
// エンコード進捗変更通知
this.encodeEvent.emitUpdateEncodeProgress();
}
}
}
}
/**
* エンコードプロセス終了処理
* @param code number | null
* @param signal NodeJS.Signals | null
* @param outputFilePath 出力先をファイルパス
* @param queueItem EncodeQueueItem
*/
private async childEndProcessing(
code: number | null,
signal: NodeJS.Signals | null,
outputFilePath: string | null,
): Promise<void> {
// exit code
this.log.encode.info(`exit code: ${code}, signal: ${signal}`);
// タイムアウトタイマークリア
if (this.timerId !== null) {
clearTimeout(this.timerId);
}
// ファイルパスの登録を削除
if (outputFilePath !== null) {
this.fileManager.release(outputFilePath);
}
if (this.encodeOption === null) {
this.log.encode.error('encodeOptionIsNull');
return;
}
let isError = true;
if (this.isCanceld === true) {
// キャンセルされた
this.log.encode.info(`canceld encode: ${this.encodeOption.encodeId}`);
} else if (code !== 0) {
// エンコードが正常終了しなかった
this.log.encode.error(`encode failed: ${this.encodeOption.encodeId} ${outputFilePath}`);
} else {
// エンコード正常終了
this.log.encode.info(`Successfully encod: ${this.encodeOption.encodeId} ${outputFilePath}`);
isError = false;
}
if (isError === true) {
// 出力ファイルを削除
if (outputFilePath !== null) {
this.log.encode.info(`delete encode output file: ${outputFilePath}`);
await Util.sleep(1000);
await FileUtil.unlink(outputFilePath).catch(err => {
this.log.encode.error(`delete encode output file failed: ${outputFilePath}`);
this.log.encode.error(err);
});
}
}
// エンコードプロセスの終了を通知
this.listener.emit(EncoderModel.ENCODE_FINISH_EVENT, isError, outputFilePath);
this.listener.removeAllListeners();
}
/**
* キャンセル処理
*/
public async cancel(): Promise<void> {
if (this.encodeOption === null) {
return;
}
this.log.encode.info(`cancel encode: ${this.encodeOption.encodeId}`);
// プロセスが実行されていれば削除する
if (this.childProcess !== null) {
this.log.encode.info(
`kill encode process encodeId: ${this.encodeOption.encodeId}, pid: ${this.childProcess.pid}`,
);
this.isCanceld = true;
await ProcessUtil.kill(this.childProcess).catch(err => {
this.log.encode.error(`kill encode process failed: ${this.encodeOption?.encodeId}`);
this.log.encode.error(err);
});
}
}
/**
* セットされたエンコードオプションを返す
* @returns EncodeOption | null
*/
public getEncodeOption(): EncodeOption | null {
return this.encodeOption;
}
/**
* エンコードの進捗情報を返す
* @returns EncodeProgressInfo | null
*/
public getProgressInfo(): EncodeProgressInfo | null {
return this.progressInfo;
}
/**
* encodeId を返す
* @returns apid.EncodeId | null
*/
public getEncodeId(): apid.EncodeId | null {
return this.encodeOption === null ? null : this.encodeOption.encodeId;
}
}
namespace EncoderModel {
export const ENCODE_FINISH_EVENT = 'encodeFinishEvent';
export const ENCODE_PRIPORITY = 10;
export const DEFAULT_TIMEOUT_RATE = 4.0;
}
export default EncoderModel; | the_stack |
import {defaultTypeResolver, Deserializer} from './deserializer';
import {logError, logWarning, nameof, parseToJSObject} from './helpers';
import {createArrayType} from './json-array-member';
import {
CustomDeserializerParams,
CustomSerializerParams,
JsonObjectMetadata,
TypeHintEmitter,
TypeResolver,
} from './metadata';
import {extractOptionBase, OptionsBase} from './options-base';
import {defaultTypeEmitter, Serializer} from './serializer';
import {ensureTypeDescriptor, MapT, SetT} from './type-descriptor';
import {Constructor, IndexedObject, Serializable} from './types';
export type JsonTypes = Object | boolean | string | number | null | undefined;
export {defaultTypeResolver, defaultTypeEmitter};
export interface MappedTypeConverters<T> {
/**
* Use this deserializer to convert a JSON value to the type.
*/
deserializer?: ((json: any, params: CustomDeserializerParams) => T | null | undefined) | null;
/**
* Use this serializer to convert a type back to JSON.
*/
serializer?: ((value: T | null | undefined, params: CustomSerializerParams) => any) | null;
}
export interface ITypedJSONSettings extends OptionsBase {
/**
* Sets the handler callback to invoke on errors during serializing and deserializing.
* Re-throwing errors in this function will halt serialization/deserialization.
* The default behavior is to log errors to the console.
*/
errorHandler?: ((e: Error) => void) | null;
/**
* Maps a type to their respective (de)serializer. Prevents you from having to repeat
* (de)serializers. Register additional types with `TypedJSON.mapType`.
*/
mappedTypes?: Map<Serializable<any>, MappedTypeConverters<any>> | null;
/**
* Sets a callback that determines the constructor of the correct sub-type of polymorphic
* objects while deserializing.
* The default behavior is to read the type-name from the '__type' property of 'sourceObject',
* and look it up in 'knownTypes'.
* The constructor of the sub-type should be returned.
*/
typeResolver?: TypeResolver | null;
nameResolver?: ((ctor: Function) => string) | null;
/**
* Sets a callback that writes type-hints to serialized objects.
* The default behavior is to write the type-name to the '__type' property, if a derived type
* is present in place of a base type.
*/
typeHintEmitter?: TypeHintEmitter | null;
/**
* Sets the amount of indentation to use in produced JSON strings.
* Default value is 0, or no indentation.
*/
indent?: number | null;
replacer?: ((key: string, value: any) => any) | null;
knownTypes?: Array<Constructor<any>> | null;
}
export class TypedJSON<T> {
private static _globalConfig: ITypedJSONSettings = {};
private serializer: Serializer = new Serializer();
private deserializer: Deserializer<T> = new Deserializer<T>();
private globalKnownTypes: Array<Constructor<any>> = [];
private indent: number = 0;
private rootConstructor: Serializable<T>;
private errorHandler: (e: Error) => void;
private nameResolver: (ctor: Function) => string;
private replacer?: (key: string, value: any) => any;
/**
* Creates a new TypedJSON instance to serialize (stringify) and deserialize (parse) object
* instances of the specified root class type.
* @param rootConstructor The constructor of the root class type.
* @param settings Additional configuration settings.
*/
constructor(rootConstructor: Serializable<T>, settings?: ITypedJSONSettings) {
const rootMetadata = JsonObjectMetadata.getFromConstructor(rootConstructor);
if (rootMetadata === undefined
|| (!rootMetadata.isExplicitlyMarked && !rootMetadata.isHandledWithoutAnnotation)) {
throw new TypeError(
'The TypedJSON root data type must have the @jsonObject decorator used.',
);
}
this.nameResolver = (ctor) => nameof(ctor);
this.rootConstructor = rootConstructor;
this.errorHandler = (error) => logError(error);
this.config(settings);
}
static parse<T>(
object: any,
rootType: Serializable<T>,
settings?: ITypedJSONSettings,
): T | undefined {
return new TypedJSON(rootType, settings).parse(object);
}
static parseAsArray<T>(
object: any,
elementType: Serializable<T>,
settings?: ITypedJSONSettings,
dimensions?: 1,
): Array<T>;
static parseAsArray<T>(
object: any,
elementType: Serializable<T>,
settings: ITypedJSONSettings | undefined,
dimensions: 2,
): Array<Array<T>>;
static parseAsArray<T>(
object: any,
elementType: Serializable<T>,
settings: ITypedJSONSettings | undefined,
dimensions: 3,
): Array<Array<Array<T>>>;
static parseAsArray<T>(
object: any,
elementType: Serializable<T>,
settings: ITypedJSONSettings | undefined,
dimensions: 4,
): Array<Array<Array<Array<T>>>>;
static parseAsArray<T>(
object: any,
elementType: Serializable<T>,
settings: ITypedJSONSettings | undefined,
dimensions: 5,
): Array<Array<Array<Array<Array<T>>>>>;
static parseAsArray<T>(
object: any,
elementType: Serializable<T>,
settings?: ITypedJSONSettings,
dimensions?: number,
): Array<any> {
return new TypedJSON(elementType, settings).parseAsArray(object, dimensions as any);
}
static parseAsSet<T>(
object: any,
elementType: Serializable<T>,
settings?: ITypedJSONSettings,
): Set<T> {
return new TypedJSON(elementType, settings).parseAsSet(object);
}
static parseAsMap<K, V>(
object: any,
keyType: Serializable<K>,
valueType: Serializable<V>,
settings?: ITypedJSONSettings,
): Map<K, V> {
return new TypedJSON(valueType, settings).parseAsMap(object, keyType);
}
static toPlainJson<T>(
object: T,
rootType: Serializable<T>,
settings?: ITypedJSONSettings,
): JsonTypes {
return new TypedJSON(rootType, settings).toPlainJson(object);
}
static toPlainArray<T>(
object: Array<T>,
elementType: Serializable<T>,
dimensions?: 1,
settings?: ITypedJSONSettings,
): Array<Object>;
static toPlainArray<T>(
object: Array<Array<T>>,
elementType: Serializable<T>,
dimensions: 2,
settings?: ITypedJSONSettings,
): Array<Array<Object>>;
static toPlainArray<T>(
object: Array<Array<Array<T>>>,
elementType: Serializable<T>,
dimensions: 3,
settings?: ITypedJSONSettings,
): Array<Array<Array<Object>>>;
static toPlainArray<T>(
object: Array<Array<Array<Array<T>>>>,
elementType: Serializable<T>,
dimensions: 4, settings?: ITypedJSONSettings,
): Array<Array<Array<Array<Object>>>>;
static toPlainArray<T>(
object: Array<Array<Array<Array<Array<T>>>>>,
elementType: Serializable<T>,
dimensions: 5,
settings?: ITypedJSONSettings,
): Array<Array<Array<Array<Array<Object>>>>>;
static toPlainArray<T>(
object: Array<any>,
elementType: Serializable<T>,
dimensions: number,
settings?: ITypedJSONSettings,
): Array<any>;
static toPlainArray<T>(
object: Array<any>,
elementType: Serializable<T>,
dimensions?: any,
settings?: ITypedJSONSettings,
): Array<any> {
return new TypedJSON(elementType, settings).toPlainArray(object, dimensions);
}
static toPlainSet<T>(
object: Set<T>,
elementType: Serializable<T>,
settings?: ITypedJSONSettings,
): Array<Object> | undefined {
return new TypedJSON(elementType, settings).toPlainSet(object);
}
static toPlainMap<K, V>(
object: Map<K, V>,
keyCtor: Serializable<K>,
valueCtor: Serializable<V>,
settings?: ITypedJSONSettings,
): IndexedObject | Array<{key: any; value: any}> | undefined {
return new TypedJSON(valueCtor, settings).toPlainMap(object, keyCtor);
}
static stringify<T>(
object: T,
rootType: Serializable<T>,
settings?: ITypedJSONSettings,
): string {
return new TypedJSON(rootType, settings).stringify(object);
}
static stringifyAsArray<T>(
object: Array<T>,
elementType: Serializable<T>,
dimensions?: 1,
settings?: ITypedJSONSettings,
): string;
static stringifyAsArray<T>(
object: Array<Array<T>>,
elementType: Serializable<T>,
dimensions: 2,
settings?: ITypedJSONSettings,
): string;
static stringifyAsArray<T>(
object: Array<Array<Array<T>>>,
elementType: Serializable<T>,
dimensions: 3,
settings?: ITypedJSONSettings,
): string;
static stringifyAsArray<T>(
object: Array<Array<Array<Array<T>>>>,
elementType: Serializable<T>,
dimensions: 4,
settings?: ITypedJSONSettings,
): string;
static stringifyAsArray<T>(
object: Array<Array<Array<Array<Array<T>>>>>,
elementType: Serializable<T>,
dimensions: 5,
settings?: ITypedJSONSettings,
): string;
static stringifyAsArray<T>(
object: Array<any>,
elementType: Serializable<T>,
dimensions: number, settings?: ITypedJSONSettings,
): string;
static stringifyAsArray<T>(
object: Array<any>,
elementType: Serializable<T>,
dimensions?: any,
settings?: ITypedJSONSettings,
): string {
return new TypedJSON(elementType, settings).stringifyAsArray(object, dimensions);
}
static stringifyAsSet<T>(
object: Set<T>,
elementType: Serializable<T>,
settings?: ITypedJSONSettings,
): string {
return new TypedJSON(elementType, settings).stringifyAsSet(object);
}
static stringifyAsMap<K, V>(
object: Map<K, V>,
keyCtor: Serializable<K>,
valueCtor: Serializable<V>,
settings?: ITypedJSONSettings,
): string {
return new TypedJSON(valueCtor, settings).stringifyAsMap(object, keyCtor);
}
static setGlobalConfig(config: ITypedJSONSettings) {
Object.assign(this._globalConfig, config);
}
/**
* Map a type to its (de)serializer.
*/
static mapType<T, R = T>(type: Serializable<T>, converters: MappedTypeConverters<R>): void {
if (this._globalConfig.mappedTypes == null) {
this._globalConfig.mappedTypes = new Map<any, any>();
}
this._globalConfig.mappedTypes.set(type, converters);
}
/**
* Configures TypedJSON through a settings object.
* @param settings The configuration settings object.
*/
config(settings?: ITypedJSONSettings) {
settings = {
...TypedJSON._globalConfig,
...settings,
};
if (settings.knownTypes != null
&& TypedJSON._globalConfig.knownTypes != null) {
// Merge known-types (also de-duplicate them, so Array -> Set -> Array).
settings.knownTypes = Array.from(new Set(
settings.knownTypes.concat(TypedJSON._globalConfig.knownTypes),
));
}
const options = extractOptionBase(settings);
this.serializer.options = options;
this.deserializer.options = options;
if (settings.errorHandler != null) {
this.errorHandler = settings.errorHandler;
this.deserializer.setErrorHandler(settings.errorHandler);
this.serializer.setErrorHandler(settings.errorHandler);
}
if (settings.replacer != null) {
this.replacer = settings.replacer;
}
if (settings.typeResolver != null) {
this.deserializer.setTypeResolver(settings.typeResolver);
}
if (settings.typeHintEmitter != null) {
this.serializer.setTypeHintEmitter(settings.typeHintEmitter);
}
if (settings.indent != null) {
this.indent = settings.indent;
}
if (settings.mappedTypes != null) {
settings.mappedTypes.forEach((upDown, type) => {
this.setSerializationStrategies(type, upDown);
});
}
if (settings.nameResolver != null) {
this.nameResolver = settings.nameResolver;
this.deserializer.setNameResolver(settings.nameResolver);
}
if (settings.knownTypes != null) {
// Type-check knownTypes elements to recognize errors in advance.
settings.knownTypes.forEach((knownType: any, i) => {
if (typeof knownType === 'undefined' || knownType === null) {
logWarning(
`TypedJSON.config: 'knownTypes' contains an undefined/null value`
+ ` (element ${i}).`,
);
}
});
this.globalKnownTypes = settings.knownTypes;
}
}
mapType<T, R = T>(type: Serializable<T>, converters: MappedTypeConverters<R>): void {
this.setSerializationStrategies(type, converters);
}
/**
* Converts a JSON string to the root class type.
* @param object The JSON to parse and convert.
* @throws Error if any errors are thrown in the specified errorHandler callback (re-thrown).
* @returns Deserialized T or undefined if there were errors.
*/
parse(object: any): T | undefined {
const json = parseToJSObject(object, this.rootConstructor);
let result: T | undefined;
try {
result = this.deserializer.convertSingleValue(
json,
ensureTypeDescriptor(this.rootConstructor),
this.getKnownTypes(),
) as T;
} catch (e) {
this.errorHandler(e);
}
return result;
}
parseAsArray(object: any, dimensions?: 1): Array<T>;
parseAsArray(object: any, dimensions: 2): Array<Array<T>>;
parseAsArray(object: any, dimensions: 3): Array<Array<Array<T>>>;
parseAsArray(object: any, dimensions: 4): Array<Array<Array<Array<T>>>>;
parseAsArray(object: any, dimensions: 5): Array<Array<Array<Array<Array<T>>>>>;
parseAsArray(object: any, dimensions: number): Array<any>;
parseAsArray(object: any, dimensions: number = 1): Array<any> {
const json = parseToJSObject(object, Array);
return this.deserializer.convertSingleValue(
json,
createArrayType(ensureTypeDescriptor(this.rootConstructor), dimensions),
this._mapKnownTypes(this.globalKnownTypes),
);
}
parseAsSet(object: any): Set<T> {
const json = parseToJSObject(object, Set);
return this.deserializer.convertSingleValue(
json,
SetT(this.rootConstructor),
this._mapKnownTypes(this.globalKnownTypes),
);
}
parseAsMap<K>(object: any, keyConstructor: Serializable<K>): Map<K, T> {
const json = parseToJSObject(object, Map);
return this.deserializer.convertSingleValue(
json,
MapT(keyConstructor, this.rootConstructor),
this._mapKnownTypes(this.globalKnownTypes),
);
}
/**
* Converts an instance of the specified class type to a plain JSON object.
* @param object The instance to convert to a JSON string.
* @returns Serialized object or undefined if an error has occured.
*/
toPlainJson(object: T): JsonTypes {
try {
return this.serializer.convertSingleValue(
object,
ensureTypeDescriptor(this.rootConstructor),
);
} catch (e) {
this.errorHandler(e);
}
}
toPlainArray(object: Array<T>, dimensions?: 1): Array<Object>;
toPlainArray(object: Array<Array<T>>, dimensions: 2): Array<Array<Object>>;
toPlainArray(object: Array<Array<Array<T>>>, dimensions: 3): Array<Array<Array<Object>>>;
toPlainArray(
object: Array<Array<Array<Array<T>>>>,
dimensions: 4,
): Array<Array<Array<Array<Object>>>>;
toPlainArray(
object: Array<Array<Array<Array<Array<T>>>>>,
dimensions: 5,
): Array<Array<Array<Array<Array<Object>>>>>;
toPlainArray(object: Array<any>, dimensions: 1 | 2 | 3 | 4 | 5 = 1): Array<Object> | undefined {
try {
return this.serializer.convertSingleValue(
object,
createArrayType(ensureTypeDescriptor(this.rootConstructor), dimensions),
);
} catch (e) {
this.errorHandler(e);
}
}
toPlainSet(object: Set<T>): Array<Object> | undefined {
try {
return this.serializer.convertSingleValue(object, SetT(this.rootConstructor));
} catch (e) {
this.errorHandler(e);
}
}
toPlainMap<K>(
object: Map<K, T>,
keyConstructor: Serializable<K>,
): IndexedObject | Array<{key: any; value: any}> | undefined {
try {
return this.serializer.convertSingleValue(
object,
MapT(keyConstructor, this.rootConstructor),
);
} catch (e) {
this.errorHandler(e);
}
}
/**
* Converts an instance of the specified class type to a JSON string.
* @param object The instance to convert to a JSON string.
* @throws Error if any errors are thrown in the specified errorHandler callback (re-thrown).
* @returns String with the serialized object or an empty string if an error has occured, but
* the errorHandler did not throw.
*/
stringify(object: T): string {
const result = this.toPlainJson(object);
if (result === undefined) {
return '';
}
return JSON.stringify(result, this.replacer, this.indent);
}
stringifyAsArray(object: Array<T>, dimensions?: 1): string;
stringifyAsArray(object: Array<Array<T>>, dimensions: 2): string;
stringifyAsArray(object: Array<Array<Array<T>>>, dimensions: 3): string;
stringifyAsArray(object: Array<Array<Array<Array<T>>>>, dimensions: 4): string;
stringifyAsArray(object: Array<Array<Array<Array<Array<T>>>>>, dimensions: 5): string;
stringifyAsArray(object: Array<any>, dimensions: any): string {
return JSON.stringify(this.toPlainArray(object, dimensions), this.replacer, this.indent);
}
stringifyAsSet(object: Set<T>): string {
return JSON.stringify(this.toPlainSet(object), this.replacer, this.indent);
}
stringifyAsMap<K>(object: Map<K, T>, keyConstructor: Serializable<K>): string {
return JSON.stringify(this.toPlainMap(object, keyConstructor), this.replacer, this.indent);
}
private getKnownTypes(): Map<string, Function> {
const rootMetadata = JsonObjectMetadata.getFromConstructor(this.rootConstructor);
const knownTypes = new Map<string, Function>();
this.globalKnownTypes.filter(ktc => ktc).forEach(knownTypeCtor => {
knownTypes.set(this.nameResolver(knownTypeCtor), knownTypeCtor);
});
if (rootMetadata !== undefined) {
rootMetadata.processDeferredKnownTypes();
rootMetadata.knownTypes.forEach(knownTypeCtor => {
knownTypes.set(this.nameResolver(knownTypeCtor), knownTypeCtor);
});
}
return knownTypes;
}
private _mapKnownTypes(constructors: Array<Constructor<any>>) {
const map = new Map<string, Constructor<any>>();
constructors.filter(ctor => ctor).forEach(ctor => map.set(this.nameResolver(ctor), ctor));
return map;
}
private setSerializationStrategies<T, R = T>(
type: Serializable<T>,
converters: MappedTypeConverters<R>,
): void {
if (converters.deserializer != null) {
this.deserializer.setDeserializationStrategy(
type,
value => converters.deserializer!(
value,
{
fallback: (so, td) => this.deserializer.convertSingleValue(
so,
ensureTypeDescriptor(td),
this.getKnownTypes(),
),
},
),
);
}
if (converters.serializer != null) {
this.serializer.setSerializationStrategy(
type,
value => converters.serializer!(
value,
{
fallback: (so, td) => this.serializer.convertSingleValue(
so,
ensureTypeDescriptor(td),
),
},
),
);
}
}
} | the_stack |
import _ from 'lodash'
import { EntryPoint, EntryPointInterceptor } from '../src/API'
import { interceptEntryPoints, interceptEntryPointsMap } from '../src/interceptEntryPoints'
import { createAppHost } from '../testKit'
type LogSpy = jest.Mock<void, string[]>
function takeLog(spy: LogSpy): string[] {
return _.flatten(spy.mock.calls)
}
function takeAndClearLog(spy: LogSpy): string[] {
const result = takeLog(spy)
spy.mockClear()
return result
}
describe('interceptEntryPoints', () => {
it('should intercept name', () => {
const spy: LogSpy = jest.fn()
const entryPoints = createTestEntryPoints(2, spy)
const interceptor = createTestInterceptor(spy, 'INTR1', { interceptName: true })
const intercepted = interceptEntryPoints(entryPoints, interceptor)
expect(intercepted[0].name).toBe('INTR1!EP-0')
expect(intercepted[1].name).toBe('INTR1!EP-1')
})
it('should intercept tags', () => {
const spy: LogSpy = jest.fn()
const entryPoints = createTestEntryPoints(2, spy)
const interceptor = createTestInterceptor(spy, 'INTR1', { interceptTags: true })
const intercepted = interceptEntryPoints(entryPoints, interceptor)
expect(intercepted[0].tags).toMatchObject({ test_ep_index: '0', intercepted_by: 'INTR1' })
expect(intercepted[1].tags).toMatchObject({ test_ep_index: '1', intercepted_by: 'INTR1' })
})
it('should intercept attach', () => {
const spy: LogSpy = jest.fn()
const entryPoints = createTestEntryPoints(1, spy)
const interceptor = createTestInterceptor(spy, 'INTR1', { interceptAttach: true })
const intercepted = interceptEntryPoints(entryPoints, interceptor)
intercepted[0].attach && intercepted[0].attach({} as any)
expect(takeLog(spy)).toEqual(['INTR1:attach', 'EP-0:attach'])
})
it('should intercept extend', () => {
const spy: LogSpy = jest.fn()
const entryPoints = createTestEntryPoints(1, spy)
const interceptor = createTestInterceptor(spy, 'INTR1', { interceptExtend: true })
const intercepted = interceptEntryPoints(entryPoints, interceptor)
intercepted[0].extend && intercepted[0].extend({} as any)
expect(takeLog(spy)).toEqual(['INTR1:extend', 'EP-0:extend'])
})
it('should intercept detach', () => {
const spy: LogSpy = jest.fn()
const entryPoints = createTestEntryPoints(1, spy)
const interceptor = createTestInterceptor(spy, 'INTR1', { interceptDetach: true })
const intercepted = interceptEntryPoints(entryPoints, interceptor)
intercepted[0].detach && intercepted[0].detach({} as any)
expect(takeLog(spy)).toEqual(['INTR1:detach', 'EP-0:detach'])
})
it('should intercept declareAPIs', () => {
const spy: LogSpy = jest.fn()
const entryPoints = createTestEntryPoints(1, spy)
const interceptor = createTestInterceptor(spy, 'I1', { interceptDeclareAPIs: true })
const intercepted = interceptEntryPoints(entryPoints, interceptor)
intercepted[0].declareAPIs && intercepted[0].declareAPIs()
expect(takeLog(spy)).toEqual(['I1:declareAPIs', 'EP-0:declareAPIs'])
})
it('should intercept getDependencyAPIs', () => {
const spy: LogSpy = jest.fn()
const entryPoints = createTestEntryPoints(1, spy)
const interceptor = createTestInterceptor(spy, 'I1', { interceptGetDependencyAPIs: true })
const intercepted = interceptEntryPoints(entryPoints, interceptor)
intercepted[0].getDependencyAPIs && intercepted[0].getDependencyAPIs()
expect(takeLog(spy)).toEqual(['I1:getDependencyAPIs', 'EP-0:getDependencyAPIs'])
})
it('should invoke original if not intercepted', () => {
const spy: LogSpy = jest.fn()
const entryPoints = createTestEntryPoints(1, spy)
const interceptor = createTestInterceptor(spy, 'INTR1', {}) // flags are all false
const intercepted = interceptEntryPoints(entryPoints, interceptor)
const interceptedName = intercepted[0].name
intercepted[0].attach && intercepted[0].attach({} as any)
intercepted[0].extend && intercepted[0].extend({} as any)
intercepted[0].detach && intercepted[0].detach({} as any)
intercepted[0].getDependencyAPIs && intercepted[0].getDependencyAPIs()
intercepted[0].declareAPIs && intercepted[0].declareAPIs()
expect(interceptedName).toBe('EP-0')
expect(takeLog(spy)).toEqual(['EP-0:attach', 'EP-0:extend', 'EP-0:detach', 'EP-0:getDependencyAPIs', 'EP-0:declareAPIs'])
})
it('should allow multiple interceptors', () => {
const spy: LogSpy = jest.fn()
const entryPoints = createTestEntryPoints(3, spy)
const interceptor1 = createTestInterceptor(spy, 'I1', { interceptAttach: true })
const interceptor2 = createTestInterceptor(spy, 'I2', { interceptAttach: true })
const intercepted1 = interceptEntryPoints(entryPoints[0], interceptor1)
const intercepted2 = interceptEntryPoints(intercepted1, interceptor2)
intercepted2[0].attach && intercepted2[0].attach({} as any)
expect(takeLog(spy)).toEqual(['I2:attach', 'I1:attach', 'EP-0:attach'])
})
it('should apply single interceptor to map of entry points', () => {
const spy: LogSpy = jest.fn()
const entryPoints = createTestEntryPoints(3, spy)
const packagesMap = {
one: entryPoints[0],
two: [entryPoints[1], entryPoints[2]]
}
const interceptor = createTestInterceptor(spy, 'I1', { interceptAttach: true })
const interceptedMap = interceptEntryPointsMap(packagesMap, interceptor)
const intercepted = [
(interceptedMap.one as EntryPoint[])[0],
(interceptedMap.two as EntryPoint[])[0],
(interceptedMap.two as EntryPoint[])[1]
]
intercepted[0].attach && intercepted[0].attach({} as any)
const logOne0 = takeAndClearLog(spy)
intercepted[1].attach && intercepted[1].attach({} as any)
const logTwo0 = takeAndClearLog(spy)
intercepted[2].attach && intercepted[2].attach({} as any)
const logTwo1 = takeAndClearLog(spy)
expect(typeof interceptedMap).toBe('object')
expect(logOne0).toEqual(['I1:attach', 'EP-0:attach'])
expect(logTwo0).toEqual(['I1:attach', 'EP-1:attach'])
expect(logTwo1).toEqual(['I1:attach', 'EP-2:attach'])
})
it('should apply multiple interceptors to map of entry points', () => {
const spy: LogSpy = jest.fn()
const entryPoints = createTestEntryPoints(3, spy)
const packagesMap = {
one: entryPoints[0],
two: [entryPoints[1], entryPoints[2]]
}
const interceptor1 = createTestInterceptor(spy, 'I1', { interceptAttach: true })
const interceptor2 = createTestInterceptor(spy, 'I2', { interceptAttach: true })
const interceptedMap1 = interceptEntryPointsMap(packagesMap, interceptor1)
const interceptedMap2 = interceptEntryPointsMap(interceptedMap1, interceptor2)
const intercepted = [
(interceptedMap2.one as EntryPoint[])[0],
(interceptedMap2.two as EntryPoint[])[0],
(interceptedMap2.two as EntryPoint[])[1]
]
intercepted[0].attach && intercepted[0].attach({} as any)
const logOne0 = takeAndClearLog(spy)
intercepted[1].attach && intercepted[1].attach({} as any)
const logTwo0 = takeAndClearLog(spy)
intercepted[2].attach && intercepted[2].attach({} as any)
const logTwo1 = takeAndClearLog(spy)
expect(typeof interceptedMap1).toBe('object')
expect(logOne0).toEqual(['I2:attach', 'I1:attach', 'EP-0:attach'])
expect(logTwo0).toEqual(['I2:attach', 'I1:attach', 'EP-1:attach'])
expect(logTwo1).toEqual(['I2:attach', 'I1:attach', 'EP-2:attach'])
})
it('should be able to add intercepted entry point to AppHost', () => {
const spy: LogSpy = jest.fn()
const entryPoints = createTestEntryPoints(1, spy)
const interceptor = createTestInterceptor(spy, 'I1', { interceptAttach: true, interceptExtend: true })
const intercepted = interceptEntryPoints(entryPoints, interceptor)
createAppHost(intercepted, {
monitoring: {}
})
// getDependencyAPIs appears to be called multiple times
expect(_.uniq(takeLog(spy))).toEqual([
'EP-0:declareAPIs', // called because of circular validation
'EP-0:getDependencyAPIs',
'I1:attach',
'EP-0:attach',
'I1:extend',
'EP-0:extend'
])
})
})
type TestInterceptorFlags = { [P in keyof EntryPointInterceptor]?: boolean }
function createTestEntryPoints(count: number, spy: LogSpy): EntryPoint[] {
return _.times(count).map<EntryPoint>(index => ({
name: `EP-${index}`,
tags: { test_ep_index: `${index}` },
getDependencyAPIs() {
spy(`EP-${index}:getDependencyAPIs`)
return []
},
declareAPIs() {
spy(`EP-${index}:declareAPIs`)
return []
},
attach() {
spy(`EP-${index}:attach`)
return []
},
extend() {
spy(`EP-${index}:extend`)
return []
},
detach() {
spy(`EP-${index}:detach`)
return []
}
}))
}
function createTestInterceptor(spy: LogSpy, interceptorName: string, flags: TestInterceptorFlags): EntryPointInterceptor {
return {
interceptName: flags.interceptName
? name => {
return `${interceptorName}!${name}`
}
: undefined,
interceptTags: flags.interceptTags
? tags => {
return { intercepted_by: interceptorName, ...tags }
}
: undefined,
interceptDeclareAPIs: flags.interceptDeclareAPIs
? innerDeclareAPIs => {
return () => {
spy(`${interceptorName}:declareAPIs`)
return (innerDeclareAPIs && innerDeclareAPIs()) || []
}
}
: undefined,
interceptGetDependencyAPIs: flags.interceptGetDependencyAPIs
? innerGetDependencyAPIs => {
return () => {
spy(`${interceptorName}:getDependencyAPIs`)
return (innerGetDependencyAPIs && innerGetDependencyAPIs()) || []
}
}
: undefined,
interceptAttach: flags.interceptAttach
? innerAttach => {
return shell => {
spy(`${interceptorName}:attach`)
innerAttach && innerAttach(shell)
}
}
: undefined,
interceptExtend: flags.interceptExtend
? innerExtend => {
return shell => {
spy(`${interceptorName}:extend`)
innerExtend && innerExtend(shell)
}
}
: undefined,
interceptDetach: flags.interceptDetach
? innerDetach => {
return shell => {
spy(`${interceptorName}:detach`)
innerDetach && innerDetach(shell)
}
}
: undefined
}
} | the_stack |
import { Application, TextView, Color, View, Frame, GridLayout, LaunchEventData, ApplicationEventData, profile, profilingUptime, Page, LayoutBase } from '@nativescript/core';
// import './dom-adapter';
// import 'nativescript-intl';
import { Type, Injector, CompilerOptions, PlatformRef, NgModuleFactory, NgModuleRef, EventEmitter, Sanitizer, InjectionToken, StaticProvider } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { NativeScriptDebug } from './trace';
import { defaultPageFactoryProvider, setRootPage, PageFactory, PAGE_FACTORY, getRootPage } from './platform-providers';
import { AppHostView, AppHostAsyncView } from './app-host-view';
export const onBeforeLivesync = new EventEmitter<NgModuleRef<any>>();
export const onAfterLivesync = new EventEmitter<{
moduleRef?: NgModuleRef<any>;
error?: Error;
}>();
let lastBootstrappedModule: WeakRef<NgModuleRef<any>>;
type BootstrapperAction = () => Promise<NgModuleRef<any>>;
// Work around a TS bug requiring an import of OpaqueToken without using it
// if ((<any>global).___TS_UNUSED) {
// (() => {
// return InjectionToken;
// })();
// }
// tslint:disable:max-line-length
/**
* Options to be passed when HMR is enabled
*/
export interface HmrOptions {
/**
* A factory function that returns either Module type or NgModuleFactory type.
* This needs to be a factory function as the types will change when modules are replaced.
*/
moduleTypeFactory?: () => Type<any> | NgModuleFactory<any>;
/**
* A livesync callback that will be called instead of the original livesync.
* It gives the HMR a hook to apply the module replacement.
* @param bootstrapPlatform - A bootstrap callback to be called after HMR is done. It will bootstrap a new angular app within the exisiting platform, using the moduleTypeFactory to get the Module or NgModuleFactory to be used.
*/
livesyncCallback: (bootstrapPlatform: () => void) => void;
}
// tslint:enable:max-line-length
export interface AppLaunchView extends LayoutBase {
// called when the animation is to begin
startAnimation?: () => void;
// called when bootstrap is complete and cleanup can begin
// should resolve when animation is completely finished
cleanup?: () => Promise<any>;
}
export interface AppOptions {
bootInExistingPage?: boolean;
cssFile?: string;
startPageActionBarHidden?: boolean;
hmrOptions?: HmrOptions;
/**
* Background color of the root view
*/
backgroundColor?: string;
/**
* Use animated launch view (async by default)
*/
launchView?: AppLaunchView;
/**
* When using Async APP_INITIALIZER, set this to `true`.
* (Not needed when using launchView)
*/
async?: boolean;
}
export type PlatformFactory = (extraProviders?: StaticProvider[]) => PlatformRef;
export class NativeScriptSanitizer extends Sanitizer {
sanitize(_context: any, value: string): string {
return value;
}
}
export class NativeScriptDocument {
// Required by the AnimationDriver
public body: any = {
isOverride: true,
};
createElement(tag: string) {
throw new Error('NativeScriptDocument is not DOM Document. There is no createElement() method.');
}
}
export const COMMON_PROVIDERS = [defaultPageFactoryProvider, { provide: Sanitizer, useClass: NativeScriptSanitizer, deps: [] }, { provide: DOCUMENT, useClass: NativeScriptDocument, deps: [] }];
export class NativeScriptPlatformRef extends PlatformRef {
private _bootstrapper: BootstrapperAction;
constructor(private platform: PlatformRef, private appOptions: AppOptions = {}) {
super();
}
@profile
bootstrapModuleFactory<M>(moduleFactory: NgModuleFactory<M>): Promise<NgModuleRef<M>> {
this._bootstrapper = () => {
let bootstrapFactory = moduleFactory;
if (this.appOptions.hmrOptions) {
bootstrapFactory = <NgModuleFactory<M>>this.appOptions.hmrOptions.moduleTypeFactory();
}
return this.platform.bootstrapModuleFactory(bootstrapFactory);
};
this.bootstrapApp();
return null; // Make the compiler happy
}
@profile
bootstrapModule<M>(moduleType: Type<M>, compilerOptions: CompilerOptions | CompilerOptions[] = []): Promise<NgModuleRef<M>> {
this._bootstrapper = () => {
let bootstrapType = moduleType;
if (this.appOptions.hmrOptions) {
bootstrapType = <Type<M>>this.appOptions.hmrOptions.moduleTypeFactory();
}
return this.platform.bootstrapModule(bootstrapType, compilerOptions);
};
this.bootstrapApp();
return null; // Make the compiler happy
}
@profile
private bootstrapApp() {
(<any>global).__onLiveSyncCore = () => {
if (this.appOptions.hmrOptions) {
const rootView = Application.getRootView();
if (rootView) {
rootView._closeAllModalViewsInternal();
}
this.appOptions.hmrOptions.livesyncCallback(() => this._livesync());
} else {
this._livesync();
}
};
if (this.appOptions && typeof this.appOptions.cssFile === 'string') {
Application.setCssFileName(this.appOptions.cssFile);
}
this.bootstrapNativeScriptApp();
}
onDestroy(callback: () => void): void {
this.platform.onDestroy(callback);
}
get injector(): Injector {
return this.platform.injector;
}
destroy(): void {
this.platform.destroy();
}
get destroyed(): boolean {
return this.platform.destroyed;
}
@profile
private bootstrapNativeScriptApp() {
let rootContent: View;
if (NativeScriptDebug.isLogEnabled()) {
NativeScriptDebug.bootstrapLog('NativeScriptPlatform bootstrap started.');
}
const launchCallback = profile('@nativescript/angular/platform-common.launchCallback', (args: LaunchEventData) => {
if (NativeScriptDebug.isLogEnabled()) {
NativeScriptDebug.bootstrapLog('Application launch event fired');
}
// Create a temp page for root of the renderer
let tempAppHostView: AppHostView;
let tempAppHostAsyncView: AppHostAsyncView;
if (this.appOptions && (this.appOptions.async || this.appOptions.launchView)) {
tempAppHostAsyncView = new AppHostAsyncView(new Color(this.appOptions && this.appOptions.backgroundColor ? this.appOptions.backgroundColor : '#fff'));
if (this.appOptions.launchView) {
this.appOptions.launchView.style.zIndex = 1000;
tempAppHostAsyncView.addChild(this.appOptions.launchView);
}
rootContent = tempAppHostAsyncView.ngAppRoot;
setRootPage(<any>tempAppHostAsyncView);
} else {
tempAppHostView = new AppHostView(new Color(this.appOptions && this.appOptions.backgroundColor ? this.appOptions.backgroundColor : '#fff'));
setRootPage(<any>tempAppHostView);
}
let bootstrapPromiseCompleted = false;
const bootstrap = () => {
this._bootstrapper().then(
(moduleRef) => {
bootstrapPromiseCompleted = true;
if (NativeScriptDebug.isLogEnabled()) {
NativeScriptDebug.bootstrapLog(`Angular bootstrap bootstrap done. uptime: ${profilingUptime()}`);
}
if (this.appOptions.launchView && this.appOptions.launchView.cleanup) {
this.appOptions.launchView.cleanup().then(() => {
// cleanup any custom launch views
tempAppHostAsyncView.removeChild(this.appOptions.launchView);
this.appOptions.launchView = null;
});
} else if (tempAppHostView) {
rootContent = tempAppHostView.content;
}
lastBootstrappedModule = new WeakRef(moduleRef);
},
(err) => {
bootstrapPromiseCompleted = true;
const errorMessage = err.message + '\n\n' + err.stack;
if (NativeScriptDebug.isLogEnabled()) {
NativeScriptDebug.bootstrapLogError('ERROR BOOTSTRAPPING ANGULAR');
}
if (NativeScriptDebug.isLogEnabled()) {
NativeScriptDebug.bootstrapLogError(errorMessage);
}
rootContent = this.createErrorUI(errorMessage);
}
);
if (NativeScriptDebug.isLogEnabled()) {
NativeScriptDebug.bootstrapLog('bootstrapAction called, draining micro tasks queue. Root: ' + rootContent);
}
(<any>global).Zone.drainMicroTaskQueue();
if (NativeScriptDebug.isLogEnabled()) {
NativeScriptDebug.bootstrapLog('bootstrapAction called, draining micro tasks queue finished! Root: ' + rootContent);
}
};
if (this.appOptions && this.appOptions.launchView && this.appOptions.launchView.startAnimation) {
// start animations on next tick (after initial boot)
setTimeout(() => {
// ensure launch animation is executed after launchView added to view stack
this.appOptions.launchView.startAnimation();
});
}
bootstrap();
// if (!bootstrapPromiseCompleted) {
// const errorMessage = "Bootstrap promise didn't resolve";
// if (NativeScriptDebug.isLogEnabled()) {
// NativeScriptDebug.bootstrapLogError(errorMessage);
// }
// rootContent = this.createErrorUI(errorMessage);
// }
args.root = rootContent;
});
const exitCallback = profile('@nativescript/angular/platform-common.exitCallback', (args: ApplicationEventData) => {
const androidActivity = args.android;
if (androidActivity && !androidActivity.isFinishing()) {
// Exit event was triggered as a part of a restart of the app.
return;
}
const lastModuleRef = lastBootstrappedModule ? lastBootstrappedModule.get() : null;
if (lastModuleRef) {
// Make sure the module is only destroyed once
lastBootstrappedModule = null;
lastModuleRef.destroy();
}
rootContent = null;
});
Application.on(Application.launchEvent, launchCallback);
Application.on(Application.exitEvent, exitCallback);
Application.run();
}
@profile
public _livesync() {
if (NativeScriptDebug.isLogEnabled()) {
NativeScriptDebug.bootstrapLog('Angular livesync started.');
}
const lastModuleRef = lastBootstrappedModule ? lastBootstrappedModule.get() : null;
onBeforeLivesync.next(lastModuleRef);
if (lastModuleRef) {
lastModuleRef.destroy();
}
this._bootstrapper().then(
(moduleRef) => {
if (NativeScriptDebug.isLogEnabled()) {
NativeScriptDebug.bootstrapLog('Angular livesync done.');
}
onAfterLivesync.next({ moduleRef });
lastBootstrappedModule = new WeakRef(moduleRef);
Application.resetRootView({
create: () => (getRootPage() instanceof AppHostView ? ((<any>getRootPage()) as AppHostView).ngAppRoot : getRootPage()),
});
},
(error) => {
if (NativeScriptDebug.isLogEnabled()) {
NativeScriptDebug.bootstrapLogError('ERROR LIVESYNC BOOTSTRAPPING ANGULAR');
}
const errorMessage = error.message + '\n\n' + error.stack;
if (NativeScriptDebug.isLogEnabled()) {
NativeScriptDebug.bootstrapLogError(errorMessage);
}
Application.resetRootView({
create: () => this.createErrorUI(errorMessage),
});
onAfterLivesync.next({ error });
}
);
}
private createErrorUI(message: string): View {
const errorTextBox = new TextView();
errorTextBox.text = message;
errorTextBox.color = new Color('red');
return errorTextBox;
}
private createFrameAndPage(isLivesync: boolean) {
const frame = new Frame();
const pageFactory: PageFactory = this.platform.injector.get(PAGE_FACTORY);
const page = pageFactory({ isBootstrap: true, isLivesync });
frame.navigate({
create: () => {
return page;
},
});
return { page, frame };
}
} | the_stack |
import {Number2, Number3} from '../../../../../types/GlobalTypes';
import {EventContext} from '../../../../scene/utils/events/_BaseEventsController';
import {RaycastEventNode, TargetType, TARGET_TYPES} from '../../Raycast';
import {Object3D} from 'three/src/core/Object3D';
import {Vector2} from 'three/src/math/Vector2';
import {Raycaster, Intersection} from 'three/src/core/Raycaster';
import {NodeContext} from '../../../../poly/NodeContext';
import {BaseObjNodeType} from '../../../obj/_Base';
import {Mesh} from 'three/src/objects/Mesh';
import {Points} from 'three/src/objects/Points';
import {BufferGeometry} from 'three/src/core/BufferGeometry';
import {GeoObjNode} from '../../../obj/Geo';
import {TypeAssert} from '../../../../poly/Assert';
import {Plane} from 'three/src/math/Plane';
import {Vector3} from 'three/src/math/Vector3';
import {ParamType} from '../../../../poly/ParamType';
import {AttribType, ATTRIBUTE_TYPES} from '../../../../../core/geometry/Constant';
import {objectTypeFromConstructor, ObjectType} from '../../../../../core/geometry/Constant';
import {CoreGeometry} from '../../../../../core/geometry/Geometry';
import {BufferAttribute} from 'three/src/core/BufferAttribute';
import {Triangle} from 'three/src/math/Triangle';
import {BaseCameraObjNodeType} from '../../../obj/_BaseCamera';
import {Vector3Param} from '../../../../params/Vector3';
import {Poly} from '../../../../Poly';
import {RaycastCPUVelocityController} from './VelocityController';
import {CoreType} from '../../../../../core/Type';
import {CPUIntersectWith, CPU_INTERSECT_WITH_OPTIONS} from './CpuConstants';
import {isBooleanTrue} from '../../../../../core/BooleanValue';
interface CursorOffset {
offsetX: number;
offsetY: number;
}
interface CursorPage {
pageX: number;
pageY: number;
}
function setEventOffset(cursorPage: CursorPage, canvas: HTMLCanvasElement, offset: CursorOffset) {
var rect = canvas.getBoundingClientRect();
offset.offsetX = cursorPage.pageX - rect.left;
offset.offsetY = cursorPage.pageY - rect.top;
}
export class RaycastCPUController {
private _offset: CursorOffset = {offsetX: 0, offsetY: 0};
private _mouse: Vector2 = new Vector2();
private _mouse_array: Number2 = [0, 0];
private _raycaster = new Raycaster();
private _resolved_targets: Object3D[] | undefined;
public readonly velocity_controller: RaycastCPUVelocityController;
constructor(private _node: RaycastEventNode) {
this.velocity_controller = new RaycastCPUVelocityController(this._node);
}
updateMouse(context: EventContext<MouseEvent | DragEvent | PointerEvent | TouchEvent>) {
const canvas = context.viewer?.canvas();
const cameraNode = context.cameraNode;
if (!(canvas && cameraNode)) {
return;
}
const updateFromCursor = (cursor: CursorOffset) => {
this._mouse.x = (cursor.offsetX / canvas.offsetWidth) * 2 - 1;
this._mouse.y = -(cursor.offsetY / canvas.offsetHeight) * 2 + 1;
this._mouse.toArray(this._mouse_array);
this._node.p.mouse.set(this._mouse_array);
};
const event = context.event;
if (event instanceof MouseEvent || event instanceof DragEvent || event instanceof PointerEvent) {
setEventOffset(event, canvas, this._offset);
}
if (
window.TouchEvent /* check first that TouchEvent is defined, since it does on firefox desktop */ &&
event instanceof TouchEvent
) {
const touch = event.touches[0];
setEventOffset(touch, canvas, this._offset);
}
updateFromCursor(this._offset);
this._raycaster.setFromCamera(this._mouse, cameraNode.object);
}
processEvent(context: EventContext<MouseEvent>) {
this._prepareRaycaster(context);
const type = CPU_INTERSECT_WITH_OPTIONS[this._node.pv.intersectWith];
switch (type) {
case CPUIntersectWith.GEOMETRY: {
return this._intersect_with_geometry(context);
}
case CPUIntersectWith.PLANE: {
return this._intersect_with_plane(context);
}
}
TypeAssert.unreachable(type);
}
private _plane = new Plane();
private _plane_intersect_target = new Vector3();
private _intersect_with_plane(context: EventContext<MouseEvent>) {
this._plane.normal.copy(this._node.pv.planeDirection);
this._plane.constant = this._node.pv.planeOffset;
this._raycaster.ray.intersectPlane(this._plane, this._plane_intersect_target);
this._set_position_param(this._plane_intersect_target);
this._node.trigger_hit(context);
}
private _intersections: Intersection[] = [];
private _intersect_with_geometry(context: EventContext<MouseEvent>) {
if (!this._resolved_targets) {
this.update_target();
}
if (this._resolved_targets) {
// clear array before
this._intersections.length = 0;
const intersections = this._raycaster.intersectObjects(
this._resolved_targets,
isBooleanTrue(this._node.pv.traverseChildren),
this._intersections
);
const intersection = intersections[0];
if (intersection) {
this._set_position_param(intersection.point);
if (isBooleanTrue(this._node.pv.geoAttribute)) {
this._resolve_geometry_attribute(intersection);
}
context.value = {intersect: intersection};
this._node.trigger_hit(context);
} else {
this._node.trigger_miss(context);
}
}
}
private _resolve_geometry_attribute(intersection: Intersection) {
const attrib_type = ATTRIBUTE_TYPES[this._node.pv.geoAttributeType];
const val = RaycastCPUController.resolve_geometry_attribute(
intersection,
this._node.pv.geoAttributeName,
attrib_type
);
if (val != null) {
switch (attrib_type) {
case AttribType.NUMERIC: {
this._node.p.geoAttributeValue1.set(val);
return;
}
case AttribType.STRING: {
if (CoreType.isString(val)) {
this._node.p.geoAttributeValues.set(val);
}
return;
}
}
TypeAssert.unreachable(attrib_type);
}
}
static resolve_geometry_attribute(intersection: Intersection, attribute_name: string, attrib_type: AttribType) {
const object_type = objectTypeFromConstructor(intersection.object.constructor);
switch (object_type) {
case ObjectType.MESH:
return this.resolve_geometry_attribute_for_mesh(intersection, attribute_name, attrib_type);
case ObjectType.POINTS:
return this.resolve_geometry_attribute_for_point(intersection, attribute_name, attrib_type);
}
// TODO: have the raycast cpu controller work with all object types
// TypeAssert.unreachable(object_type)
}
private static _vA = new Vector3();
private static _vB = new Vector3();
private static _vC = new Vector3();
private static _uvA = new Vector2();
private static _uvB = new Vector2();
private static _uvC = new Vector2();
private static _hitUV = new Vector2();
static resolve_geometry_attribute_for_mesh(
intersection: Intersection,
attribute_name: string,
attrib_type: AttribType
) {
const geometry = (intersection.object as Mesh).geometry as BufferGeometry;
if (geometry) {
const attribute = geometry.getAttribute(attribute_name) as BufferAttribute;
if (attribute) {
switch (attrib_type) {
case AttribType.NUMERIC: {
const position = geometry.getAttribute('position') as BufferAttribute;
if (intersection.face) {
this._vA.fromBufferAttribute(position, intersection.face.a);
this._vB.fromBufferAttribute(position, intersection.face.b);
this._vC.fromBufferAttribute(position, intersection.face.c);
this._uvA.fromBufferAttribute(attribute, intersection.face.a);
this._uvB.fromBufferAttribute(attribute, intersection.face.b);
this._uvC.fromBufferAttribute(attribute, intersection.face.c);
intersection.uv = Triangle.getUV(
intersection.point,
this._vA,
this._vB,
this._vC,
this._uvA,
this._uvB,
this._uvC,
this._hitUV
);
return this._hitUV.x;
}
return;
}
case AttribType.STRING: {
const core_geometry = new CoreGeometry(geometry);
const core_point = core_geometry.points()[0];
if (core_point) {
return core_point.stringAttribValue(attribute_name);
}
return;
}
}
TypeAssert.unreachable(attrib_type);
}
}
}
static resolve_geometry_attribute_for_point(
intersection: Intersection,
attribute_name: string,
attrib_type: AttribType
) {
const geometry = (intersection.object as Points).geometry as BufferGeometry;
if (geometry && intersection.index != null) {
switch (attrib_type) {
case AttribType.NUMERIC: {
const attribute = geometry.getAttribute(attribute_name);
if (attribute) {
return attribute.array[intersection.index];
}
return;
}
case AttribType.STRING: {
const core_geometry = new CoreGeometry(geometry);
const core_point = core_geometry.points()[intersection.index];
if (core_point) {
return core_point.stringAttribValue(attribute_name);
}
return;
}
}
TypeAssert.unreachable(attrib_type);
}
}
private _found_position_target_param: Vector3Param | undefined;
private _hit_position_array: Number3 = [0, 0, 0];
private _set_position_param(hit_position: Vector3) {
hit_position.toArray(this._hit_position_array);
if (isBooleanTrue(this._node.pv.tpositionTarget)) {
if (Poly.playerMode()) {
this._found_position_target_param =
this._found_position_target_param || this._node.pv.positionTarget.paramWithType(ParamType.VECTOR3);
} else {
// Do not cache the param in the editor, but fetch it directly from the operator_path.
// The reason is that params are very prone to disappear and be re-generated,
// Such as spare params created by Gl Builders
const target_param = this._node.pv.positionTarget;
this._found_position_target_param = target_param.paramWithType(ParamType.VECTOR3);
}
if (this._found_position_target_param) {
this._found_position_target_param.set(this._hit_position_array);
}
} else {
this._node.p.position.set(this._hit_position_array);
}
this.velocity_controller.process(hit_position);
}
private _prepareRaycaster(context: EventContext<MouseEvent>) {
const points_param = this._raycaster.params.Points;
if (points_param) {
points_param.threshold = this._node.pv.pointsThreshold;
}
let camera_node: Readonly<BaseCameraObjNodeType> | undefined = context.cameraNode;
if (isBooleanTrue(this._node.pv.overrideCamera)) {
if (isBooleanTrue(this._node.pv.overrideRay)) {
this._raycaster.ray.origin.copy(this._node.pv.rayOrigin);
this._raycaster.ray.direction.copy(this._node.pv.rayDirection);
} else {
const found_camera_node = this._node.p.camera.found_node_with_context(NodeContext.OBJ);
if (found_camera_node) {
camera_node = (<unknown>found_camera_node) as Readonly<BaseCameraObjNodeType>;
}
}
}
if (camera_node && !isBooleanTrue(this._node.pv.overrideRay)) {
camera_node.prepareRaycaster(this._mouse, this._raycaster);
}
}
update_target() {
const targetType = TARGET_TYPES[this._node.pv.targetType];
switch (targetType) {
case TargetType.NODE: {
return this._update_target_from_node();
}
case TargetType.SCENE_GRAPH: {
return this._update_target_from_scene_graph();
}
}
TypeAssert.unreachable(targetType);
}
private _update_target_from_node() {
const node = this._node.p.targetNode.value.nodeWithContext(NodeContext.OBJ) as BaseObjNodeType;
if (node) {
const found_obj = isBooleanTrue(this._node.pv.traverseChildren)
? node.object
: (node as GeoObjNode).childrenDisplayController.sopGroup();
if (found_obj) {
this._resolved_targets = [found_obj];
} else {
this._resolved_targets = undefined;
}
} else {
this._node.states.error.set('node is not an object');
}
}
private _update_target_from_scene_graph() {
const objects: Object3D[] = this._node.scene().objectsByMask(this._node.pv.objectMask);
if (objects.length > 0) {
this._resolved_targets = objects;
} else {
this._resolved_targets = undefined;
}
}
async update_position_target() {
if (this._node.p.positionTarget.isDirty()) {
await this._node.p.positionTarget.compute();
}
}
static PARAM_CALLBACK_update_target(node: RaycastEventNode) {
node.cpuController.update_target();
}
// static PARAM_CALLBACK_update_position_target(node: RaycastEventNode) {
// node.cpu_controller.update_position_target();
// }
static PARAM_CALLBACK_print_resolve(node: RaycastEventNode) {
node.cpuController.print_resolve();
}
private print_resolve() {
this.update_target();
console.log(this._resolved_targets);
}
} | the_stack |
import React from 'react';
import {create, ReactTestInstance} from 'react-test-renderer';
import {generateRandomSeries} from './helpers';
import {graphicsComponent, testSelector} from './specs';
import {Chart} from './Chart';
import {Bars} from './Bars';
import {Transform} from './Transform';
const seriesObjects3x5 = generateRandomSeries(3, 5, {type: 'object'});
describe('Bars', () => {
graphicsComponent(Bars, {
pointGroupClassName: 'bar',
pointStyling: true,
visibleProperties: {
seriesVisible: ['g', 'series'],
barVisible: ['path']
},
attributesProperties: {
seriesAttributes: ['g', 'series'],
barAttributes: ['path']
},
styleProperties: {
seriesStyle: ['g', 'series'],
barStyle: ['path'],
groupStyle: ['g', 'bar']
}
});
const selector = (instance: ReactTestInstance) => {
return instance.type === 'g' && instance.props?.className?.includes('bars-bar');
};
it('should set bars width', () => {
const renderer = create(<Chart width={100} height={100} series={seriesObjects3x5}>
<Bars className='bars' barWidth={72} />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h72 ');
expect(d).toContain('M-36,0 ');
});
it('should have combined mode', () => {
const renderer = create(<Chart width={100} height={100} series={seriesObjects3x5}>
<Bars className='bars' combined={true} />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h20 '); // 100 (chart width) / 5 (number of points)
});
describe('should support inner padding', () => {
it('can be a number', () => {
const renderer = create(<Chart width={150} height={100} series={seriesObjects3x5}>
<Bars className='bars' innerPadding={2} />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h8 '); // 150 (chart width) / 15 (number of points) - 2 (inner padding)
});
it('can be percents as a string', () => {
const renderer = create(<Chart width={150} height={100} series={seriesObjects3x5}>
<Bars className='bars' innerPadding='1%' />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h8.5 '); // 150 (chart width) / 15 (number of points) - 1.5 (inner padding, 1%)
});
it('can be percents as a number', () => {
const consoleWrap = jest.spyOn(console, 'warn').mockReturnValue();
const renderer = create(<Chart width={150} height={100} series={seriesObjects3x5}>
<Bars className='bars' innerPadding='2%' />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h7 '); // 150 (chart width) / 15 (number of points) - 3 (inner padding, 1%)
consoleWrap.mockRestore();
});
});
it('should set inner padding and bar width', () => {
const renderer = create(<Chart width={150} height={100} series={seriesObjects3x5}>
<Bars className='bars' innerPadding={10} combined={true} />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h20 '); // 150 (chart width) / 5 (number of points) - 10 (inner padding)
});
describe('should support group padding', () => {
it('can be a number', () => {
const renderer = create(<Chart width={150} height={100} series={seriesObjects3x5}>
<Bars className='bars' groupPadding={6} />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h8 '); // (150 (chart width) - 6 (group padding) * 5 (groups)) / 15 (number of points)
});
it('can be percents as a string', () => {
const renderer = create(<Chart width={150} height={100} series={seriesObjects3x5}>
<Bars className='bars' groupPadding='2%' />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h9 '); // (150 (chart width) - 3 (group padding) * 5 (groups)) / 15 (number of points)
});
it('can be percents as a number', () => {
const consoleWrap = jest.spyOn(console, 'warn').mockReturnValue();
const renderer = create(<Chart width={100} height={100} series={seriesObjects3x5}>
<Bars className='bars' groupPadding='2%' />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h6 '); // (100 (chart width) - 2 (group padding) * 5 (groups)) / 15 (number of points)
consoleWrap.mockRestore();
});
});
it('should support group padding and inner padding together', () => {
const renderer = create(<Chart width={250} height={100} series={seriesObjects3x5}>
<Bars className='bars' groupPadding={5} innerPadding={2} />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h13 '); // (250 (chart width) - 5 (group padding) * 5 (groups)) / 15 (number of points) - 2 (inner padding)
});
it('should ignore group padding in case of combined enabled', () => {
const renderer = create(<Chart width={250} height={100} series={seriesObjects3x5}>
<Bars className='bars' groupPadding={5} combined={true} />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h50 '); // (250 (chart width) / 5 (number of points)
});
it('should support group padding and combined props together', () => {
const renderer = create(<Chart width={250} height={100} series={seriesObjects3x5}>
<Bars className='bars' innerPadding={5} combined={true} />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h45 '); // (250 (chart width) / 5 (number of points) - 5 (inner padding)
});
it('should be sensitive for paddings on x scale', () => {
const renderer = create(<Chart
width={150} height={100} series={seriesObjects3x5}
scaleX={{paddingStart: -0.5, paddingEnd: -0.5}}>
<Bars className='bars' combined={true} />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h50 ');
});
describe('should correct paddings on x scale', () => {
it('in case of natural direction of the scale', () => {
const renderer = create(<Chart
width={250} height={100} series={seriesObjects3x5}
scaleX={{paddingStart: 0, paddingEnd: 0}}>
<Bars className='bars' innerPadding={5} combined={true} />
</Chart>);
// it corrects paddingStart=0 and paddingEnd=0 to paddingStart=0.5 and paddingEnd=0.5
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h45 ');
});
it('in case of reversed direction of the scale', () => {
const renderer = create(<Chart
width={250} height={100} series={seriesObjects3x5}
scaleX={{paddingStart: 0, paddingEnd: 0, direction: -1}}>
<Bars className='bars' innerPadding={5} combined={true} />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h45 ');
});
});
it('should support rotate transformation', () => {
const renderer = create(<Chart
width={250} height={250} series={seriesObjects3x5}>
<Transform method='rotate'>
<Bars className='bars' innerPadding={5} combined={true} />
</Transform>
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' v45 ');
});
it('should support stacked bars', () => {
const height = 250;
const renderer = create(<Chart
width={150} height={height} series={seriesObjects3x5}>
<Transform method='stack'>
<Bars className='bars' combined={true} />
</Transform>
</Chart>);
let remain = height;
seriesObjects3x5.forEach((series, seriesIndex) => {
const g = renderer.root
.findAll(testSelector('g.bars-series'))[seriesIndex]
.findAll(testSelector('g.bars-bar'))[0];
const {d} = g.findByType('path').props;
const barHeight = Number(d.split(',0 v')[1].split(' h30 ')[0]);
const barY = Number(g.props.transform.split('(15 ')[1].split(')')[0]);
remain -= barHeight;
expect(Math.abs(remain - barY)).toBeLessThan(2);
});
});
describe('should handle some wrong input data', () => {
it('undefined x scale direction', () => {
const renderer = create(<Chart
width={250} height={100} series={seriesObjects3x5}
scaleX={{direction: null}}>
<Bars className='bars' innerPadding={5} combined={true} />
</Chart>);
const child = renderer.root.findAll(selector)[3].children[0] as ReactTestInstance;
const d = child.props.d;
expect(d).toContain(' h45 ');
});
it('undefined series', () => {
const renderer = create(<Chart width={100} height={100}>
<Bars className='bars' />
</Chart>);
expect(renderer.root.findAll(instance => {
return instance.type === 'g' && instance.props?.className === 'bars';
}).length).toEqual(1);
});
});
}); | the_stack |
import { css } from '@emotion/react';
import { ArticleDisplay } from '@guardian/libs';
import { breakpoints } from '@guardian/source-foundations';
/*
* Working on this file? Checkout out 027-pictures.md for background information & context!
*/
type Props = {
imageSources: ImageSource[];
role: RoleType;
format: ArticleFormat;
alt: string;
height: string;
width: string;
isMainMedia?: boolean;
isLazy?: boolean;
};
type ResolutionType = 'hdpi' | 'mdpi';
type Pixel = number;
type Breakpoint = number;
export type DesiredWidth = {
breakpoint: Breakpoint;
width: Pixel;
};
/**
* Given a desired width & array of SrcSetItems, return the closest match.
* The match will always be greater than the desired width when available
*
* @param desiredWidth
* @param inlineSrcSets
* @returns {SrcSetItem}
*/
export const getBestSourceForDesiredWidth = (
desiredWidth: Pixel,
inlineSrcSets: SrcSetItem[],
): SrcSetItem => {
const sorted = inlineSrcSets.slice().sort((a, b) => b.width - a.width);
return sorted.reduce((best, current) => {
if (current.width < best.width && current.width >= desiredWidth) {
return current;
}
return best;
});
};
const getSourcesForRoleAndResolution = (
imageSources: ImageSource[],
role: RoleType,
resolution: ResolutionType,
) => {
const setsForRole = imageSources.filter(
({ weighting }) =>
// Use toLowerCase to handle cases where we have halfWidth comparing to halfwidth
weighting.toLowerCase() === role.toLowerCase(),
)[0].srcSet;
return resolution === 'hdpi'
? setsForRole.filter((set) => set.src.includes('dpr=2'))
: setsForRole.filter((set) => !set.src.includes('dpr=2'));
};
const getFallback = (sources: SrcSetItem[]): string | undefined => {
if (sources.length === 0) return undefined;
// The assumption here is readers on devices that do not support srcset are likely to be on poor
// network connections so we're going to fallback to a small image
return getBestSourceForDesiredWidth(300, sources).src;
};
/**
* Removes redundant widths from an array of DesiredWidths
*
* This function specifically looks for *consecutive duplicates*,
* in which case we should always keep the last consecutive element.
*
* @param {DesiredWidth[]} desiredWidths
* @returns {DesiredWidth}
*/
export const removeRedundantWidths = (
allDesiredWidths: DesiredWidth[],
): DesiredWidth[] => {
const desiredWidths: DesiredWidth[] = [];
for (const desiredWidth of allDesiredWidths) {
if (
desiredWidths[desiredWidths.length - 1]?.width ===
desiredWidth.width
) {
// We overwrite the end element as we want to keep the *last* consecutive duplicate
desiredWidths[desiredWidths.length - 1] = desiredWidth;
} else desiredWidths.push(desiredWidth);
}
return desiredWidths;
};
/**
* Returns the desired width for an image at the specified breakpoint, based on the image role, format, and if it's main media.
* This function acts as a source of truth for widths of images based on the provided parameters
*
* Returns 'breakpoint', or 'breakpoint / x' when the image is expected to fill a % of the viewport,
* instead of a fixed width.
*
* @param breakpoint
* @param role
* @param isMainMedia
* @param format
* @returns {Pixel}
*/
const getDesiredWidthForBreakpoint = (
breakpoint: number,
role: RoleType,
isMainMedia: boolean,
format: ArticleFormat,
): Pixel => {
if (
(format.display === ArticleDisplay.Showcase ||
format.display === ArticleDisplay.NumberedList) &&
isMainMedia
) {
// Showcase main media images (which includes numbered list articles) appear
// larger than in body showcase images so we use a different set of image sizes
if (breakpoint >= breakpoints.wide) return 1020;
if (breakpoint >= breakpoints.leftCol) return 940;
if (breakpoint >= breakpoints.tablet) return 700;
if (breakpoint >= breakpoints.phablet) return 700;
return breakpoint;
}
switch (role) {
case 'inline':
if (
breakpoint >= breakpoints.tablet &&
breakpoint < breakpoints.desktop
)
return 680;
if (breakpoint >= breakpoints.phablet) return 620;
return breakpoint;
case 'halfWidth':
if (breakpoint >= breakpoints.phablet) return 300;
return Math.round(breakpoint / 2);
case 'thumbnail':
return 140;
case 'immersive':
if (breakpoint >= breakpoints.wide) return 1300;
return breakpoint;
case 'supporting':
if (breakpoint >= breakpoints.wide) return 380;
if (breakpoint >= breakpoints.tablet) return 300;
return breakpoint;
case 'showcase':
if (breakpoint >= breakpoints.wide) return 860;
if (breakpoint >= breakpoints.leftCol) return 780;
if (breakpoint >= breakpoints.phablet) return 620;
return breakpoint;
}
};
// Takes a size & sources, and returns a source set with 1 matching image with the desired size
const getSourceForDesiredWidth = (
desiredWidth: Pixel,
sources: SrcSetItem[],
resolution: ResolutionType,
) => {
// The image sources we're provided use double-widths for HDPI images
// We should therefor multiply the width based on if it's HDPI or not
// e.g { url: '... ?width=500&dpr=2 ...', width: '1000' }
const source = getBestSourceForDesiredWidth(
resolution === 'hdpi' ? desiredWidth * 2 : desiredWidth,
sources,
);
return `${source.src} ${source.width}w`;
};
// Create sourcesets for portrait immersive
// TODO: In a future PR this system will be updated to solve scaling issues with DPR
const portraitImmersiveMainMediaSource = (
sources: SrcSetItem[],
resolution: ResolutionType,
) => (
<source
media={
resolution === 'hdpi'
? '(orientation: portrait) and (-webkit-min-device-pixel-ratio: 1.25), (orientation: portrait) and (min-resolution: 120dpi)'
: '(orientation: portrait)'
}
// Immersive MainMedia elements fill the height of the viewport, meaning
// on mobile devices even though the viewport width is small, we'll need
// a larger image to maintain quality. To solve this problem we're using
// the viewport height (vh) to calculate width. The value of 167vh
// relates to an assumed image ratio of 5:3 which is equal to
// 167 (viewport height) : 100 (viewport width).
sizes="167vh"
srcSet={sources
.map((srcSet) => `${srcSet.src} ${srcSet.width}w`)
.join(',')}
/>
);
// Create sourcesets for landscape immersive
const landscapeImmersiveMainMediaSource = (
sources: SrcSetItem[],
resolution: ResolutionType,
) => {
const sortedSources = sources.slice().sort((a, b) => b.width - a.width);
const getMedia = (sourceWidth: number, isLast: boolean): string => {
const width = resolution === 'hdpi' ? sourceWidth / 2 : sourceWidth;
const breakpoint = isLast ? 0 : width;
return resolution === 'hdpi'
? `(min-width: ${breakpoint}px) and (-webkit-min-device-pixel-ratio: 1.25), (min-width: ${breakpoint}px) and (min-resolution: 120dpi)`
: `(min-width: ${breakpoint}px)`;
};
return (
<>
{/* For immersive main media, images will always take up 100% of the screen width,
therefore it is more beneficial to loop through all the image sources, instead of the breakpoints.
This means that we are not limited to sources within the boundaries of the breakpoints, and can provide
more appropriately sized images where applicable. */}
{sortedSources.map((sourceSet, index) => (
<source
srcSet={`${sourceSet.src} ${sourceSet.width}w`}
media={getMedia(
sourceSet.width,
index === sortedSources.length - 1,
)}
/>
))}
</>
);
};
export const Picture = ({
imageSources,
role,
format,
alt,
height,
width,
isMainMedia = false,
isLazy = true,
}: Props) => {
const hdpiSourceSets = getSourcesForRoleAndResolution(
imageSources,
role,
'hdpi',
);
const mdpiSourceSets = getSourcesForRoleAndResolution(
imageSources,
role,
'mdpi',
);
const fallbackSrc = getFallback(
hdpiSourceSets.length ? hdpiSourceSets : mdpiSourceSets,
);
const allDesiredWidths: DesiredWidth[] = [
// Create an array of breakpoints going from highest to lowest, with 0 as the final option
breakpoints.wide,
breakpoints.leftCol,
breakpoints.desktop,
breakpoints.tablet,
breakpoints.phablet,
breakpoints.mobileLandscape,
breakpoints.mobileMedium,
breakpoints.mobile,
0,
].map((breakpoint) => ({
breakpoint,
width: getDesiredWidthForBreakpoint(
breakpoint,
role,
isMainMedia,
format,
),
}));
const desiredWidths: DesiredWidth[] =
removeRedundantWidths(allDesiredWidths);
const isImmersiveMainMedia =
format.display === ArticleDisplay.Immersive && isMainMedia;
return (
<picture itemProp="contentUrl">
{/* Rendering for Immersive Main Media! */}
{isImmersiveMainMedia && (
<>
{portraitImmersiveMainMediaSource(hdpiSourceSets, 'hdpi')}
{portraitImmersiveMainMediaSource(mdpiSourceSets, 'mdpi')}
{landscapeImmersiveMainMediaSource(hdpiSourceSets, 'hdpi')}
{landscapeImmersiveMainMediaSource(mdpiSourceSets, 'mdpi')}
</>
)}
{/* rendering for all other image types */}
{!isImmersiveMainMedia &&
desiredWidths.map(({ breakpoint, width: desiredWidth }) => (
<>
{/* HDPI Source (DPR2) - images in this srcset have `dpr=2&quality=45` in the url */}
{hdpiSourceSets.length > 0 && (
<source
srcSet={getSourceForDesiredWidth(
desiredWidth,
hdpiSourceSets,
'hdpi',
)}
media={`(min-width: ${breakpoint}px) and (-webkit-min-device-pixel-ratio: 1.25), (min-width: ${breakpoint}px) and (min-resolution: 120dpi)`}
/>
)}
{/* MDPI Source - images in this srcset have `quality=85` in the url */}
<source
srcSet={getSourceForDesiredWidth(
desiredWidth,
mdpiSourceSets,
'mdpi',
)}
media={`(min-width: ${breakpoint}px)`}
/>
</>
))}
<img
alt={alt}
src={fallbackSrc}
height={height}
width={width}
loading={
isLazy && !Picture.disableLazyLoading ? 'lazy' : undefined
}
// https://stackoverflow.com/questions/10844205/html-5-strange-img-always-adds-3px-margin-at-bottom
// why did we add the css `vertical-align: middle;` to the img tag
css={css`
vertical-align: middle;
`}
/>
</picture>
);
};
// We use disableLazyLoading to decide if we want to turn off lazy loading of images site wide. We use this
// to prevent false negatives on Chromatic snapshots (see /.storybook/config)
Picture.disableLazyLoading = false; | the_stack |
import * as t from './sdk_types'
export abstract class Sdk {
abstract getAccountInfoSync(): t.AccountInfo;
abstract getBatteryInfoSync(): t.GetBatteryInfoSyncResult;
abstract getExtConfigSync(): t.ExtInfo;
abstract getLaunchOptionsSync(): t.LaunchOptionsApp;
abstract getMenuButtonBoundingClientRect(): t.Rect;
abstract getStorageInfoSync(): t.GetStorageInfoSyncOption;
abstract getSystemInfoSync(): t.GetSystemInfoSyncResult;
abstract createAnimation(option: t.CreateAnimationOption): t.Animation;
abstract createAudioContext(
/** `<audio/>` 组件的 id */
id: string,
/** 在自定义组件下,当前组件实例的this,以操作组件内 `<audio/>` 组件 */
component?: any,
): t.AudioContext;
abstract getBackgroundAudioManager(): t.BackgroundAudioManager;
abstract createCameraContext(): t.CameraContext;
abstract createCanvasContext(
/** 要获取上下文的 `<canvas>` 组件 canvas-id 属性 */
canvasId: string,
/** 在自定义组件下,当前组件实例的this,表示在这个自定义组件下查找拥有 canvas-id 的 `<canvas/>` ,如果省略则不在任何自定义组件内查找 */
component?: any,
): t.CanvasContext;
abstract downloadFile(option: t.DownloadFileOption): t.DownloadTask;
abstract getFileSystemManager(): t.FileSystemManager;
abstract createInnerAudioContext(): t.InnerAudioContext;
abstract createIntersectionObserver(
/** 自定义组件实例 */
component: any,
/** 选项 */
options: t.CreateIntersectionObserverOption,
): t.IntersectionObserver;
abstract createIntersectionObserver(
/** 选项 */
options: t.CreateIntersectionObserverOption,
): IntersectionObserver;
abstract createLivePlayerContext(
/** `<live-player/>` 组件的 id */
id: string,
/** 在自定义组件下,当前组件实例的this,以操作组件内 `<live-player/>` 组件 */
component?: any,
): t.LivePlayerContext;
abstract createLivePusherContext(): t.LivePusherContext;
abstract getLogManager(option: t.GetLogManagerOption): t.LogManager;
abstract createMapContext(
/** `<map/>` 组件的 id */
mapId: string,
/** 在自定义组件下,当前组件实例的this,以操作组件内 `<map/>` 组件 */
component?: any,
): t.MapContext;
abstract getRecorderManager(): t.RecorderManager;
abstract request(option: t.RequestOption): t.RequestTask;
abstract createSelectorQuery(): t.SelectorQuery;
abstract connectSocket(option: t.ConnectSocketOption): t.SocketTask;
abstract getUpdateManager(): t.UpdateManager;
abstract uploadFile(option: t.UploadFileOption): t.UploadTask;
abstract createVideoContext(
/** `<video/>` 组件的 id */
id: string,
/** 在自定义组件下,当前组件实例的this,以操作组件内 `<video/>` 组件 */
component: any,
): t.VideoContext;
abstract createWorker(
/** worker 入口文件的**绝对路径** */
scriptPath: string,
): Worker;
abstract getStorageSync(
/** 本地缓存中指定的 key */
key: string,
): any;
abstract canIUse(
/** 使用 `${API}.${method}.${param}.${options}` 或者 `${component}.${attribute}.${option}` 方式来调用 */
schema: string,
): boolean;
abstract addCard(option: t.AddCardOption): void;
abstract addPhoneContact(option: t.AddPhoneContactOption): void;
abstract authorize(option: t.AuthorizeOption): void;
abstract canvasGetImageData(
option: t.CanvasGetImageDataOption,
/** 在自定义组件下,当前组件实例的this,以操作组件内 `<canvas/>` 组件 */
component?: any,
): void;
abstract canvasPutImageData(
option: t.CanvasPutImageDataOption,
/** 在自定义组件下,当前组件实例的this,以操作组件内 `<canvas/>` 组件 */
component?: any,
): void;
abstract canvasToTempFilePath(
option: t.CanvasToTempFilePathOption,
/** 在自定义组件下,当前组件实例的this,以操作组件内 `<canvas/>` 组件 */
component?: any,
): void;
abstract checkIsSoterEnrolledInDevice(
option: t.CheckIsSoterEnrolledInDeviceOption,
): void;
abstract checkIsSupportSoterAuthentication(
option?: t.CheckIsSupportSoterAuthenticationOption,
): void;
abstract clearStorage(option?: t.ClearStorageOption): void;
abstract checkSession(option?: t.CheckSessionOption): void;
abstract chooseAddress(option?: t.ChooseAddressOption): void;
abstract chooseImage(option: t.ChooseImageOption): void;
abstract chooseInvoice(option?: t.ChooseInvoiceOption): void;
abstract chooseInvoiceTitle(option?: t.ChooseInvoiceTitleOption): void;
abstract chooseLocation(option?: t.ChooseLocationOption): void;
abstract chooseMessageFile(option: t.ChooseMessageFileOption): void;
abstract chooseVideo(option: t.ChooseVideoOption): void;
abstract clearStorageSync(): void;
abstract closeBLEConnection(option: t.CloseBLEConnectionOption): void;
abstract closeBluetoothAdapter(option?: t.CloseBluetoothAdapterOption): void;
abstract closeSocket(option: t.CloseSocketOption): void;
abstract compressImage(option: t.CompressImageOption): void;
abstract connectWifi(option: t.ConnectWifiOption): void;
abstract createBLEConnection(option: t.CreateBLEConnectionOption): void;
abstract getAvailableAudioSources(option?: t.GetAvailableAudioSourcesOption): void;
abstract getBLEDeviceCharacteristics(
option: t.GetBLEDeviceCharacteristicsOption,
): void;
abstract getBLEDeviceServices(option: t.GetBLEDeviceServicesOption): void;
abstract getBackgroundAudioPlayerState(
option?: t.GetBackgroundAudioPlayerStateOption,
): void;
abstract getBatteryInfo(option?: t.GetBatteryInfoOption): void;
abstract getBeacons(option?: t.GetBeaconsOption): void;
abstract getBluetoothAdapterState(option?: t.GetBluetoothAdapterStateOption): void;
abstract getBluetoothDevices(option?: t.GetBluetoothDevicesOption): void;
abstract getClipboardData(option?: t.GetClipboardDataOption): void;
abstract getConnectedBluetoothDevices(
option: t.GetConnectedBluetoothDevicesOption,
): void;
abstract getConnectedWifi(option?: t.GetConnectedWifiOption): void;
abstract getExtConfig(option?: t.GetExtConfigOption): void;
abstract getFileInfo(option: t.WxGetFileInfoOption): void;
abstract getHCEState(option?: t.GetHCEStateOption): void;
abstract getImageInfo(option: t.GetImageInfoOption): void;
abstract getLocation(option: t.GetLocationOption): void;
abstract getNetworkType(option?: t.GetNetworkTypeOption): void;
abstract getSavedFileInfo(option: t.GetSavedFileInfoOption): void;
abstract getSavedFileList(option?: t.WxGetSavedFileListOption): void;
abstract getScreenBrightness(option?: t.GetScreenBrightnessOption): void;
abstract getSetting(option?: t.GetSettingOption): void;
abstract getShareInfo(option: t.GetShareInfoOption): void;
abstract getStorage(option: t.GetStorageOption): void;
abstract getStorageInfo(option?: t.GetStorageInfoOption): void;
abstract getSystemInfo(option?: t.GetSystemInfoOption): void;
abstract getUserInfo(option: t.GetUserInfoOption): void;
abstract getWeRunData(option?: t.GetWeRunDataOption): void;
abstract getWifiList(option?: t.GetWifiListOption): void;
abstract hideLoading(option?: t.HideLoadingOption): void;
abstract hideNavigationBarLoading(option?: t.HideNavigationBarLoadingOption): void;
abstract hideShareMenu(option?: t.HideShareMenuOption): void;
abstract hideTabBar(option: t.HideTabBarOption): void;
abstract hideTabBarRedDot(option: t.HideTabBarRedDotOption): void;
abstract hideToast(option?: t.HideToastOption): void;
abstract loadFontFace(option: t.LoadFontFaceOption): void;
abstract login(option: t.LoginOption): void;
abstract makePhoneCall(option: t.MakePhoneCallOption): void;
abstract navigateBack(option: t.NavigateBackOption): void;
abstract navigateBackMiniProgram(option: t.NavigateBackMiniProgramOption): void;
abstract navigateTo(option: t.NavigateToOption): void;
abstract navigateToMiniProgram(option: t.NavigateToMiniProgramOption): void;
abstract nextTick(callback: Function): void;
abstract notifyBLECharacteristicValueChange(
option: t.NotifyBLECharacteristicValueChangeOption,
): void;
abstract offAppHide(
/** 小程序切后台事件的回调函数 */
callback: t.OffAppHideCallback,
): void;
abstract offAppShow(
/** 小程序切前台事件的回调函数 */
callback: t.OffAppShowCallback,
): void;
abstract offAudioInterruptionBegin(
/** 音频因为受到系统占用而被中断开始事件的回调函数 */
callback: t.OffAudioInterruptionBeginCallback,
): void;
abstract offAudioInterruptionEnd(
/** 音频中断结束事件的回调函数 */
callback: t.OffAudioInterruptionEndCallback,
): void;
abstract offError(
/** 小程序错误事件的回调函数 */
callback: Function,
): void;
abstract offLocalServiceDiscoveryStop(
/** mDNS 服务停止搜索的事件的回调函数 */
callback: t.OffLocalServiceDiscoveryStopCallback,
): void;
abstract offLocalServiceFound(
/** mDNS 服务发现的事件的回调函数 */
callback: t.OffLocalServiceFoundCallback,
): void;
abstract offLocalServiceLost(
/** mDNS 服务离开的事件的回调函数 */
callback: t.OffLocalServiceLostCallback,
): void;
abstract offLocalServiceResolveFail(
/** mDNS 服务解析失败的事件的回调函数 */
callback: t.OffLocalServiceResolveFailCallback,
): void;
abstract offPageNotFound(
/** 小程序要打开的页面不存在事件的回调函数 */
callback: t.OffPageNotFoundCallback,
): void;
abstract offWindowResize(
/** 窗口尺寸变化事件的回调函数 */
callback: t.OffWindowResizeCallback,
): void;
abstract onAccelerometerChange(
/** 加速度数据事件的回调函数 */
callback: t.OnAccelerometerChangeCallback,
): void;
abstract onAppHide(
/** 小程序切后台事件的回调函数 */
callback: t.OnAppHideCallback,
): void;
abstract onAppShow(
/** 小程序切前台事件的回调函数 */
callback: t.OnAppShowCallback,
): void;
abstract onAudioInterruptionBegin(
/** 音频因为受到系统占用而被中断开始事件的回调函数 */
callback: t.OnAudioInterruptionBeginCallback,
): void;
abstract onAudioInterruptionEnd(
/** 音频中断结束事件的回调函数 */
callback: t.OnAudioInterruptionEndCallback,
): void;
abstract onBLECharacteristicValueChange(
/** 低功耗蓝牙设备的特征值变化事件的回调函数 */
callback: t.OnBLECharacteristicValueChangeCallback,
): void;
abstract onBLEConnectionStateChange(
/** 低功耗蓝牙连接状态的改变事件的回调函数 */
callback: t.OnBLEConnectionStateChangeCallback,
): void;
abstract onBackgroundAudioPause(
/** 音乐暂停事件的回调函数 */
callback: t.OnBackgroundAudioPauseCallback,
): void;
abstract onBackgroundAudioPlay(
/** 音乐播放事件的回调函数 */
callback: t.OnBackgroundAudioPlayCallback,
): void;
abstract onBackgroundAudioStop(
/** 音乐停止事件的回调函数 */
callback: t.OnBackgroundAudioStopCallback,
): void;
abstract onBeaconServiceChange(
/** iBeacon 服务状态变化事件的回调函数 */
callback: t.OnBeaconServiceChangeCallback,
): void;
abstract onBeaconUpdate(
/** iBeacon 设备更新事件的回调函数 */
callback: t.OnBeaconUpdateCallback,
): void;
abstract onBluetoothAdapterStateChange(
/** 蓝牙适配器状态变化事件的回调函数 */
callback: t.OnBluetoothAdapterStateChangeCallback,
): void;
abstract onBluetoothDeviceFound(
/** 寻找到新设备的事件的回调函数 */
callback: t.OnBluetoothDeviceFoundCallback,
): void;
abstract onCompassChange(
/** 罗盘数据变化事件的回调函数 */
callback: t.OnCompassChangeCallback,
): void;
abstract onDeviceMotionChange(
/** 设备方向变化事件的回调函数 */
callback: t.OnDeviceMotionChangeCallback,
): void;
abstract onError(
/** 小程序错误事件的回调函数 */
callback: t.OnAppErrorCallback,
): void;
abstract onGetWifiList(
/** 获取到 Wi-Fi 列表数据事件的回调函数 */
callback: t.OnGetWifiListCallback,
): void;
abstract onGyroscopeChange(
/** 陀螺仪数据变化事件的回调函数 */
callback: t.OnGyroscopeChangeCallback,
): void;
abstract onHCEMessage(
/** 接收 NFC 设备消息事件的回调函数 */
callback: t.OnHCEMessageCallback,
): void;
abstract onLocalServiceDiscoveryStop(
/** mDNS 服务停止搜索的事件的回调函数 */
callback: t.OnLocalServiceDiscoveryStopCallback,
): void;
abstract onLocalServiceFound(
/** mDNS 服务发现的事件的回调函数 */
callback: t.OnLocalServiceFoundCallback,
): void;
abstract onLocalServiceLost(
/** mDNS 服务离开的事件的回调函数 */
callback: t.OnLocalServiceLostCallback,
): void;
abstract onLocalServiceResolveFail(
/** mDNS 服务解析失败的事件的回调函数 */
callback: t.OnLocalServiceResolveFailCallback,
): void;
abstract onMemoryWarning(
/** 内存不足告警事件的回调函数 */
callback: t.OnMemoryWarningCallback,
): void;
abstract onNetworkStatusChange(
/** 网络状态变化事件的回调函数 */
callback: t.OnNetworkStatusChangeCallback,
): void;
abstract onPageNotFound(
/** 小程序要打开的页面不存在事件的回调函数 */
callback: t.OnPageNotFoundCallback,
): void;
abstract onSocketClose(
/** WebSocket 连接关闭事件的回调函数 */
callback: t.OnSocketCloseCallback,
): void;
abstract onSocketError(
/** WebSocket 错误事件的回调函数 */
callback: t.OnSocketErrorCallback,
): void;
abstract onSocketMessage(
/** WebSocket 接受到服务器的消息事件的回调函数 */
callback: t.OnSocketMessageCallback,
): void;
abstract onSocketOpen(
/** WebSocket 连接打开事件的回调函数 */
callback: t.OnSocketOpenCallback,
): void;
abstract onUserCaptureScreen(
/** 用户主动截屏事件的回调函数 */
callback: t.OnUserCaptureScreenCallback,
): void;
abstract onWifiConnected(
/** 连接上 Wi-Fi 的事件的回调函数 */
callback: t.OnWifiConnectedCallback,
): void;
abstract onWindowResize(
/** 窗口尺寸变化事件的回调函数 */
callback: t.OnWindowResizeCallback,
): void;
abstract openBluetoothAdapter(option?: t.OpenBluetoothAdapterOption): void;
abstract openCard(option: t.OpenCardOption): void;
abstract openDocument(option: t.OpenDocumentOption): void;
abstract openLocation(option: t.OpenLocationOption): void;
abstract openSetting(option?: t.OpenSettingOption): void;
abstract pageScrollTo(option: t.PageScrollToOption): void;
abstract pauseBackgroundAudio(option?: t.PauseBackgroundAudioOption): void;
abstract pauseVoice(option?: t.PauseVoiceOption): void;
abstract playBackgroundAudio(option: t.PlayBackgroundAudioOption): void;
abstract playVoice(option: t.PlayVoiceOption): void;
abstract previewImage(option: t.PreviewImageOption): void;
abstract reLaunch(option: t.ReLaunchOption): void;
abstract readBLECharacteristicValue(option: t.ReadBLECharacteristicValueOption): void;
abstract redirectTo(option: t.RedirectToOption): void;
abstract removeSavedFile(option: t.WxRemoveSavedFileOption): void;
abstract removeStorage(option: t.RemoveStorageOption): void;
abstract removeStorageSync(
/** 本地缓存中指定的 key */
key: string,
): void;
abstract removeTabBarBadge(option: t.RemoveTabBarBadgeOption): void;
abstract reportAnalytics(
/** 事件名 */
eventName: string,
/** 上报的自定义数据。 */
data: t.Data,
): void;
abstract reportMonitor(
/** 监控ID,在「小程序管理后台」新建数据指标后获得 */
name: string,
/** 上报数值,经处理后会在「小程序管理后台」上展示每分钟的上报总量 */
value: number,
): void;
abstract requestPayment(option: t.RequestPaymentOption): void;
abstract saveFile(option: t.WxSaveFileOption): void;
abstract saveImageToPhotosAlbum(option: t.SaveImageToPhotosAlbumOption): void;
abstract saveVideoToPhotosAlbum(option: t.SaveVideoToPhotosAlbumOption): void;
abstract scanCode(option: t.ScanCodeOption): void;
abstract seekBackgroundAudio(option: t.SeekBackgroundAudioOption): void;
abstract sendHCEMessage(option: t.SendHCEMessageOption): void;
abstract sendSocketMessage(option: t.SendSocketMessageOption): void;
abstract setBackgroundColor(option: t.SetBackgroundColorOption): void;
abstract setBackgroundTextStyle(option: t.SetBackgroundTextStyleOption): void;
abstract setClipboardData(option: t.SetClipboardDataOption): void;
abstract setEnableDebug(option: t.SetEnableDebugOption): void;
abstract setInnerAudioOption(option: t.SetInnerAudioOption): void;
abstract setKeepScreenOn(option: t.SetKeepScreenOnOption): void;
abstract setNavigationBarColor(option: t.SetNavigationBarColorOption): void;
abstract setNavigationBarTitle(option: t.SetNavigationBarTitleOption): void;
abstract setScreenBrightness(option: t.SetScreenBrightnessOption): void;
abstract setStorage(option: t.SetStorageOption): void;
abstract setStorageSync(
/** 本地缓存中指定的 key */
key: string,
/** 需要存储的内容。只支持原生类型、Date、及能够通过`JSON.stringify`序列化的对象。 */
data: any,
): void;
abstract setTabBarBadge(option: t.SetTabBarBadgeOption): void;
abstract setTabBarItem(option: t.SetTabBarItemOption): void;
abstract setTabBarStyle(option: t.SetTabBarStyleOption): void;
abstract setTopBarText(option: t.SetTopBarTextOption): void;
abstract setWifiList(option: t.SetWifiListOption): void;
abstract showActionSheet(option: t.ShowActionSheetOption): void;
abstract showLoading(option: t.ShowLoadingOption): void;
abstract showModal(option: t.ShowModalOption): void;
abstract showNavigationBarLoading(option?: t.ShowNavigationBarLoadingOption): void;
abstract showShareMenu(option: t.ShowShareMenuOption): void;
abstract showTabBar(option: t.ShowTabBarOption): void;
abstract showTabBarRedDot(option: t.ShowTabBarRedDotOption): void;
abstract showToast(option: t.ShowToastOption): void;
abstract startAccelerometer(option: t.StartAccelerometerOption): void;
abstract startBeaconDiscovery(option: t.StartBeaconDiscoveryOption): void;
abstract startBluetoothDevicesDiscovery(
option: t.StartBluetoothDevicesDiscoveryOption,
): void;
abstract startCompass(option?: t.StartCompassOption): void;
abstract startDeviceMotionListening(option: t.StartDeviceMotionListeningOption): void;
abstract startGyroscope(option: t.StartGyroscopeOption): void;
abstract startHCE(option: t.StartHCEOption): void;
abstract startLocalServiceDiscovery(option: t.StartLocalServiceDiscoveryOption): void;
abstract startPullDownRefresh(option?: t.StartPullDownRefreshOption): void;
abstract startRecord(option: t.WxStartRecordOption): void;
abstract startSoterAuthentication(option: t.StartSoterAuthenticationOption): void;
abstract startWifi(option?: t.StartWifiOption): void;
abstract stopAccelerometer(option?: t.StopAccelerometerOption): void;
abstract stopBackgroundAudio(option?: t.StopBackgroundAudioOption): void;
abstract stopBeaconDiscovery(option?: t.StopBeaconDiscoveryOption): void;
abstract stopBluetoothDevicesDiscovery(
option?: t.StopBluetoothDevicesDiscoveryOption,
): void;
abstract stopCompass(option?: t.StopCompassOption): void;
abstract stopDeviceMotionListening(option?: t.StopDeviceMotionListeningOption): void;
abstract stopGyroscope(option?: t.StopGyroscopeOption): void;
abstract stopHCE(option?: t.StopHCEOption): void;
abstract stopLocalServiceDiscovery(option?: t.StopLocalServiceDiscoveryOption): void;
abstract stopPullDownRefresh(option?: t.StopPullDownRefreshOption): void;
abstract stopRecord(): void;
abstract stopVoice(option?: t.StopVoiceOption): void;
abstract stopWifi(option?: t.StopWifiOption): void;
abstract switchTab(option: t.SwitchTabOption): void;
abstract updateShareMenu(option: t.UpdateShareMenuOption): void;
abstract vibrateLong(option?: t.VibrateLongOption): void;
abstract vibrateShort(option?: t.VibrateShortOption): void;
abstract writeBLECharacteristicValue(
option: t.WriteBLECharacteristicValueOption,
): void;
abstract clearInterval(
intervalID: number,
): void
abstract clearTimeout(
timeoutID: number,
): void;
abstract setInterval(
/** 回调函数 */
callback: Function,
/** 执行回调函数之间的时间间隔,单位 ms。 */
delay?: number,
/** param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数。 */
rest?: any,
): number;
abstract setTimeout(
/** 回调函数 */
callback: Function,
/** 延迟的时间,函数的调用会在该延迟之后发生,单位 ms。 */
delay?: number,
/** param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数。 */
rest?: any,
): number;
} | the_stack |
* @packageDocumentation
* @module std
*/
//================================================================
import { MultiMap } from "../base/container/MultiMap";
import { IHashMap } from "../base/container/IHashMap";
import { IHashContainer } from "../internal/container/associative/IHashContainer";
import { MapElementList } from "../internal/container/associative/MapElementList";
import { MapHashBuckets } from "../internal/hash/MapHashBuckets";
import { NativeArrayIterator } from "../internal/iterator/disposable/NativeArrayIterator";
import { IForwardIterator } from "../iterator/IForwardIterator";
import { IPair } from "../utility/IPair";
import { Entry } from "../utility/Entry";
import { BinaryPredicator } from "../internal/functional/BinaryPredicator";
import { Hasher } from "../internal/functional/Hasher";
import { Temporary } from "../internal/functional/Temporary";
/**
* Multiple-key Map based on Hash buckets.
*
* @author Jeongho Nam - https://github.com/samchon
*/
export class HashMultiMap<Key, T>
extends MultiMap<Key, T,
HashMultiMap<Key, T>,
HashMultiMap.Iterator<Key, T>,
HashMultiMap.ReverseIterator<Key, T>>
implements IHashMap<Key, T, false, HashMultiMap<Key, T>>
{
private buckets_!: MapHashBuckets<Key, T, false, HashMultiMap<Key, T>>;
/* =========================================================
CONSTRUCTORS & SEMI-CONSTRUCTORS
- CONSTRUCTORS
- ASSIGN & CLEAR
============================================================
CONSTURCTORS
--------------------------------------------------------- */
/**
* Default Constructor.
*
* @param hash An unary function returns hash code. Default is {hash}.
* @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}.
*/
public constructor(hash?: Hasher<Key>, equal?: BinaryPredicator<Key>);
/**
* Initializer Constructor.
*
* @param items Items to assign.
* @param hash An unary function returns hash code. Default is {hash}.
* @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}.
*/
public constructor(items: IPair<Key, T>[], hash?: Hasher<Key>, equal?: BinaryPredicator<Key>);
/**
* Copy Constructor.
*
* @param obj Object to copy.
*/
public constructor(obj: HashMultiMap<Key, T>);
/**
* Range Constructor.
*
* @param first Input iterator of the first position.
* @param last Input iterator of the last position.
* @param hash An unary function returns hash code. Default is {hash}.
* @param equal A binary function predicates two arguments are equal. Default is {@link equal_to}.
*/
public constructor
(
first: Readonly<IForwardIterator<IPair<Key, T>>>,
last: Readonly<IForwardIterator<IPair<Key, T>>>,
hash?: Hasher<Key>, equal?: BinaryPredicator<Key>
);
public constructor(...args: any[])
{
super(thisArg => new MapElementList(thisArg));
IHashContainer.construct<Key, Entry<Key, T>,
HashMultiMap<Key, T>,
HashMultiMap.Iterator<Key, T>,
HashMultiMap.ReverseIterator<Key, T>,
IPair<Key, T>>
(
this, HashMultiMap,
(hash, pred) =>
{
this.buckets_ = new MapHashBuckets(this as HashMultiMap<Key, T>, hash, pred);
},
...args
);
}
/* ---------------------------------------------------------
ASSIGN & CLEAR
--------------------------------------------------------- */
/**
* @inheritDoc
*/
public clear(): void
{
this.buckets_.clear();
super.clear();
}
/**
* @inheritDoc
*/
public swap(obj: HashMultiMap<Key, T>): void
{
// SWAP CONTENTS
[this.data_, obj.data_] = [obj.data_, this.data_];
MapElementList._Swap_associative(this.data_ as Temporary, obj.data_ as Temporary);
// SWAP BUCKETS
MapHashBuckets._Swap_source(this.buckets_, obj.buckets_);
[this.buckets_, obj.buckets_] = [obj.buckets_, this.buckets_];
}
/* =========================================================
ACCESSORS
- MEMBER
- HASH
============================================================
MEMBER
--------------------------------------------------------- */
/**
* @inheritDoc
*/
public find(key: Key): HashMultiMap.Iterator<Key, T>
{
return this.buckets_.find(key);
}
/**
* @inheritDoc
*/
public count(key: Key): number
{
// FIND MATCHED BUCKET
const index = this.bucket(key);
const bucket = this.buckets_.at(index);
// ITERATE THE BUCKET
let cnt: number = 0;
for (let it of bucket)
if (this.buckets_.key_eq()(it.first, key))
++cnt;
return cnt;
}
/**
* @inheritDoc
*/
public begin(): HashMultiMap.Iterator<Key, T>;
/**
* @inheritDoc
*/
public begin(index: number): HashMultiMap.Iterator<Key, T>;
public begin(index: number | null = null): HashMultiMap.Iterator<Key, T>
{
if (index === null)
return super.begin();
else
return this.buckets_.at(index)[0];
}
/**
* @inheritDoc
*/
public end(): HashMultiMap.Iterator<Key, T>;
/**
* @inheritDoc
*/
public end(index: number): HashMultiMap.Iterator<Key, T>
public end(index: number | null = null): HashMultiMap.Iterator<Key, T>
{
if (index === null)
return super.end();
else
{
const bucket = this.buckets_.at(index);
return bucket[bucket.length - 1].next();
}
}
/**
* @inheritDoc
*/
public rbegin(): HashMultiMap.ReverseIterator<Key, T>;
/**
* @inheritDoc
*/
public rbegin(index: number): HashMultiMap.ReverseIterator<Key, T>;
public rbegin(index: number | null = null): HashMultiMap.ReverseIterator<Key, T>
{
return this.end(index!).reverse();
}
/**
* @inheritDoc
*/
public rend(): HashMultiMap.ReverseIterator<Key, T>;
/**
* @inheritDoc
*/
public rend(index: number): HashMultiMap.ReverseIterator<Key, T>;
public rend(index: number | null = null): HashMultiMap.ReverseIterator<Key, T>
{
return this.begin(index!).reverse();
}
/* ---------------------------------------------------------
HASH
--------------------------------------------------------- */
/**
* @inheritDoc
*/
public bucket_count(): number
{
return this.buckets_.length();
}
/**
* @inheritDoc
*/
public bucket_size(index: number): number
{
return this.buckets_.at(index).length;
}
/**
* @inheritDoc
*/
public load_factor(): number
{
return this.buckets_.load_factor();
}
/**
* @inheritDoc
*/
public hash_function(): Hasher<Key>
{
return this.buckets_.hash_function();
}
/**
* @inheritDoc
*/
public key_eq(): BinaryPredicator<Key>
{
return this.buckets_.key_eq();
}
/**
* @inheritDoc
*/
public bucket(key: Key): number
{
return this.hash_function()(key) % this.buckets_.length();
}
/**
* @inheritDoc
*/
public max_load_factor(): number;
/**
* @inheritDoc
*/
public max_load_factor(z: number): void;
public max_load_factor(z: number | null = null): any
{
return this.buckets_.max_load_factor(z!);
}
/**
* @inheritDoc
*/
public reserve(n: number): void
{
this.buckets_.reserve(n);
}
/**
* @inheritDoc
*/
public rehash(n: number): void
{
if (n <= this.bucket_count())
return;
this.buckets_.rehash(n);
}
protected _Key_eq(x: Key, y: Key): boolean
{
return this.key_eq()(x, y);
}
/* =========================================================
ELEMENTS I/O
- INSERT
- POST-PROCESS
============================================================
INSERT
--------------------------------------------------------- */
/**
* @inheritDoc
*/
public emplace(key: Key, val: T): HashMultiMap.Iterator<Key, T>
{
// INSERT
const it = this.data_.insert(this.data_.end(), new Entry(key, val));
this._Handle_insert(it, it.next()); // POST-PROCESS
return it;
}
/**
* @inheritDoc
*/
public emplace_hint(hint: HashMultiMap.Iterator<Key, T>, key: Key, val: T): HashMultiMap.Iterator<Key, T>
{
// INSERT
const it = this.data_.insert(hint, new Entry(key, val));
// POST-PROCESS
this._Handle_insert(it, it.next());
return it;
}
protected _Insert_by_range<InputIterator extends Readonly<IForwardIterator<IPair<Key, T>, InputIterator>>>
(first: InputIterator, last: InputIterator): void
{
//--------
// INSERTIONS
//--------
// PRELIMINARIES
const entries: Array<Entry<Key, T>> = [];
for (let it = first; !it.equals(last); it = it.next())
entries.push(new Entry(it.value.first, it.value.second));
// INSERT ELEMENTS
const my_first = this.data_.insert
(
this.data_.end(),
new NativeArrayIterator(entries, 0),
new NativeArrayIterator(entries, entries.length)
);
//--------
// HASHING INSERTED ITEMS
//--------
// IF NEEDED, HASH_BUCKET TO HAVE SUITABLE SIZE
if (this.size() > this.buckets_.capacity())
this.reserve(Math.max(this.size(), this.buckets_.capacity() * 2));
// POST-PROCESS
this._Handle_insert(my_first, this.end());
}
/* ---------------------------------------------------------
POST-PROCESS
--------------------------------------------------------- */
protected _Handle_insert(first: HashMultiMap.Iterator<Key, T>, last: HashMultiMap.Iterator<Key, T>): void
{
for (; !first.equals(last); first = first.next())
this.buckets_.insert(first);
}
protected _Handle_erase(first: HashMultiMap.Iterator<Key, T>, last: HashMultiMap.Iterator<Key, T>): void
{
for (; !first.equals(last); first = first.next())
this.buckets_.erase(first);
}
}
/**
*
*/
export namespace HashMultiMap
{
//----
// PASCAL NOTATION
//----
// HEAD
/**
* Iterator of {@link HashMultiMap}
*/
export type Iterator<Key, T> = MapElementList.Iterator<Key, T, false, HashMultiMap<Key, T>>;
/**
* Reverse iterator of {@link HashMultiMap}
*/
export type ReverseIterator<Key, T> = MapElementList.ReverseIterator<Key, T, false, HashMultiMap<Key, T>>;
// BODY
export const Iterator = MapElementList.Iterator;
export const ReverseIterator = MapElementList.ReverseIterator;
} | the_stack |
import {OpCode} from './enums';
import * as opcodes from './opcodes';
import {Method} from './methods';
import {FieldReference, ClassReference} from './ConstantPool';
export interface JitInfo {
pops: number, // If negative, then it is treated a request rather than a demand
pushes: number,
hasBranch: boolean,
emit: (pops: string[], pushes: string[], suffix: string, onSuccess: string, code: Buffer, pc: number, onErrorPushes: string[], method: Method) => string
}
function makeOnError(onErrorPushes: string[], pc: number) {
return onErrorPushes.length > 0 ? `f.pc=${pc};f.opStack.pushAll(${onErrorPushes.join(',')});` : `f.pc=${pc};`;
}
const escapeStringRegEx = /\\/g;
export const opJitInfo: JitInfo[] = function() {
// Intentionally indented higher: emitted code is shorter.
const table:JitInfo[] = [];
table[OpCode.ACONST_NULL] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=null;${onSuccess}`;
}};
table[OpCode.ICONST_M1] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=-1;${onSuccess}`;
}};
const load0_32: JitInfo = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=f.locals[0];${onSuccess}`;
}};
const load1_32: JitInfo = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=f.locals[1];${onSuccess}`;
}};
const load2_32: JitInfo = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=f.locals[2];${onSuccess}`;
}};
const load3_32: JitInfo = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=f.locals[3];${onSuccess}`;
}};
table[OpCode.ALOAD_0] = load0_32;
table[OpCode.ILOAD_0] = load0_32;
table[OpCode.FLOAD_0] = load0_32;
table[OpCode.ALOAD_1] = load1_32;
table[OpCode.ILOAD_1] = load1_32;
table[OpCode.FLOAD_1] = load1_32;
table[OpCode.ALOAD_2] = load2_32;
table[OpCode.ILOAD_2] = load2_32;
table[OpCode.FLOAD_2] = load2_32;
table[OpCode.ALOAD_3] = load3_32;
table[OpCode.ILOAD_3] = load3_32;
table[OpCode.FLOAD_3] = load3_32;
const load0_64: JitInfo = {hasBranch: false, pops: 0, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=f.locals[0],${pushes[1]}=null;${onSuccess}`;
}};
const load1_64: JitInfo = {hasBranch: false, pops: 0, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=f.locals[1],${pushes[1]}=null;${onSuccess}`;
}};
const load2_64: JitInfo = {hasBranch: false, pops: 0, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=f.locals[2],${pushes[1]}=null;${onSuccess}`;
}};
const load3_64: JitInfo = {hasBranch: false, pops: 0, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=f.locals[3],${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.LLOAD_0] = load0_64;
table[OpCode.DLOAD_0] = load0_64;
table[OpCode.LLOAD_1] = load1_64;
table[OpCode.DLOAD_1] = load1_64;
table[OpCode.LLOAD_2] = load2_64;
table[OpCode.DLOAD_2] = load2_64;
table[OpCode.LLOAD_3] = load3_64;
table[OpCode.DLOAD_3] = load3_64;
const store0_32: JitInfo = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
return `f.locals[0]=${pops[0]};${onSuccess}`;
}}
const store1_32: JitInfo = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
return `f.locals[1]=${pops[0]};${onSuccess}`;
}}
const store2_32: JitInfo = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
return `f.locals[2]=${pops[0]};${onSuccess}`;
}}
const store3_32: JitInfo = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
return `f.locals[3]=${pops[0]};${onSuccess}`;
}}
table[OpCode.ASTORE_0] = store0_32;
table[OpCode.ISTORE_0] = store0_32;
table[OpCode.FSTORE_0] = store0_32;
table[OpCode.ASTORE_1] = store1_32;
table[OpCode.ISTORE_1] = store1_32;
table[OpCode.FSTORE_1] = store1_32;
table[OpCode.ASTORE_2] = store2_32;
table[OpCode.ISTORE_2] = store2_32;
table[OpCode.FSTORE_2] = store2_32;
table[OpCode.ASTORE_3] = store3_32;
table[OpCode.ISTORE_3] = store3_32;
table[OpCode.FSTORE_3] = store3_32;
const store_64: JitInfo = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const offset = code[pc + 1];
return `f.locals[${offset+1}]=${pops[0]};f.locals[${offset}]=${pops[1]};${onSuccess}`;
}}
const store0_64: JitInfo = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
return `f.locals[1]=${pops[0]};f.locals[0]=${pops[1]};${onSuccess}`;
}}
const store1_64: JitInfo = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
return `f.locals[2]=${pops[0]};f.locals[1]=${pops[1]};${onSuccess}`;
}}
const store2_64: JitInfo = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
return `f.locals[3]=${pops[0]};f.locals[2]=${pops[1]};${onSuccess}`;
}}
const store3_64: JitInfo = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
return `f.locals[4]=${pops[0]};f.locals[3]=${pops[1]};${onSuccess}`;
}}
table[OpCode.LSTORE] = store_64;
table[OpCode.DSTORE] = store_64;
table[OpCode.LSTORE_0] = store0_64;
table[OpCode.DSTORE_0] = store0_64;
table[OpCode.LSTORE_1] = store1_64;
table[OpCode.DSTORE_1] = store1_64;
table[OpCode.LSTORE_2] = store2_64;
table[OpCode.DSTORE_2] = store2_64;
table[OpCode.LSTORE_3] = store3_64;
table[OpCode.DSTORE_3] = store3_64;
const const0_32: JitInfo = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=0;${onSuccess}`;
}}
const const1_32: JitInfo = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=1;${onSuccess}`;
}}
const const2_32: JitInfo = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=2;${onSuccess}`;
}}
table[OpCode.ICONST_0] = const0_32;
table[OpCode.ICONST_1] = const1_32;
table[OpCode.ICONST_2] = const2_32;
table[OpCode.FCONST_0] = const0_32;
table[OpCode.FCONST_1] = const1_32;
table[OpCode.FCONST_2] = const2_32;
table[OpCode.ICONST_3] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=3;${onSuccess}`;
}}
table[OpCode.ICONST_4] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=4;${onSuccess}`;
}}
table[OpCode.ICONST_5] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=5;${onSuccess}`;
}}
table[OpCode.LCONST_0] = {hasBranch: false, pops: 0, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=u.gLong.ZERO,${pushes[1]}=null;${onSuccess}`;
}}
table[OpCode.LCONST_1] = {hasBranch: false, pops: 0, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=u.gLong.ONE,${pushes[1]}=null;${onSuccess}`;
}}
table[OpCode.DCONST_0] = {hasBranch: false, pops: 0, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=0,${pushes[1]}=null;${onSuccess}`;
}}
table[OpCode.DCONST_1] = {hasBranch: false, pops: 0, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=1,${pushes[1]}=null;${onSuccess}`;
}}
const aload32: JitInfo = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes, pc);
return `
if(!u.isNull(t,f,${pops[1]})){
var len${suffix}=${pops[1]}.array.length;
if(${pops[0]}<0||${pops[0]}>=len${suffix}){
${onError}
u.throwException(t,f,'Ljava/lang/ArrayIndexOutOfBoundsException;',""+${pops[0]}+" not in length "+len${suffix}+" array of type "+${pops[1]}.getClass().getInternalName());
}else{var ${pushes[0]}=${pops[1]}.array[${pops[0]}];${onSuccess}}
}else{${onError}}`;
}}
table[OpCode.IALOAD] = aload32;
table[OpCode.FALOAD] = aload32;
table[OpCode.AALOAD] = aload32;
table[OpCode.BALOAD] = aload32;
table[OpCode.CALOAD] = aload32;
table[OpCode.SALOAD] = aload32;
const aload64: JitInfo = {hasBranch: false, pops: 2, pushes: 2, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes, pc);
return `
if(!u.isNull(t,f,${pops[1]})){
var len${suffix}=${pops[1]}.array.length;
if(${pops[0]}<0||${pops[0]}>=len${suffix}){
${onError}
u.throwException(t,f,'Ljava/lang/ArrayIndexOutOfBoundsException;',""+${pops[0]}+" not in length "+len${suffix}+" array of type "+${pops[1]}.getClass().getInternalName());
}else{var ${pushes[0]}=${pops[1]}.array[${pops[0]}],${pushes[1]}=null;${onSuccess}}
}else{${onError}}`;
}}
table[OpCode.DALOAD] = aload64;
table[OpCode.LALOAD] = aload64;
const astore32: JitInfo = {hasBranch: false, pops: 3, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes, pc);
return `
if(!u.isNull(t,f,${pops[2]})){
var len${suffix}=${pops[2]}.array.length;
if(${pops[1]}<0||${pops[1]}>=len${suffix}){
${onError}
u.throwException(t,f,'Ljava/lang/ArrayIndexOutOfBoundsException;',""+${pops[1]}+" not in length "+len${suffix}+" array of type "+${pops[2]}.getClass().getInternalName());
}else{${pops[2]}.array[${pops[1]}]=${pops[0]};${onSuccess}}
}else{${onError}}`;
}}
table[OpCode.IASTORE] = astore32;
table[OpCode.FASTORE] = astore32;
table[OpCode.AASTORE] = astore32;
table[OpCode.BASTORE] = astore32;
table[OpCode.CASTORE] = astore32;
table[OpCode.SASTORE] = astore32;
const astore64: JitInfo = {hasBranch: false, pops: 4, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes, pc);
return `
if(!u.isNull(t,f,${pops[3]})){
var len${suffix}=${pops[3]}.array.length;
if(${pops[2]}<0||${pops[2]}>=len${suffix}){
${onError}
u.throwException(t,f,'Ljava/lang/ArrayIndexOutOfBoundsException;',""+${pops[2]}+" not in length "+len${suffix}+" array of type "+${pops[3]}.getClass().getInternalName());
}else{${pops[3]}.array[${pops[2]}]=${pops[1]};${onSuccess}}
}else{${onError}}`;
}}
table[OpCode.DASTORE] = astore64;
table[OpCode.LASTORE] = astore64;
// TODO: get the constant at JIT time ?
table[OpCode.LDC] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const index = code[pc + 1];
const onError = makeOnError(onErrorPushes, pc);
return `
var cnst${suffix}=f.method.cls.constantPool.get(${index});
if(cnst${suffix}.isResolved()){var ${pushes[0]}=cnst${suffix}.getConstant(t);${onSuccess}
}else{${onError}u.resolveCPItem(t,f,cnst${suffix});}`;
}};
// TODO: get the constant at JIT time ?
table[OpCode.LDC_W] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const index = code.readUInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc);
return `
var cnst${suffix}=f.method.cls.constantPool.get(${index});
if(cnst${suffix}.isResolved()){var ${pushes[0]}=cnst${suffix}.getConstant(t);${onSuccess}
}else{${onError}u.resolveCPItem(t,f,cnst${suffix});}`;
}};
// TODO: get the constant at JIT time ?
table[OpCode.LDC2_W] = {hasBranch: false, pops: 0, pushes: 2, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const index = code.readUInt16BE(pc + 1);
return `var ${pushes[0]}=f.method.cls.constantPool.get(${index}).value,${pushes[1]}=null;${onSuccess}`;
}};
// TODO: get the field info at JIT time ?
table[OpCode.GETSTATIC_FAST32] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const index = code.readUInt16BE(pc + 1);
return `var fi${suffix}=f.method.cls.constantPool.get(${index}),${pushes[0]}=fi${suffix}.fieldOwnerConstructor[fi${suffix}.fullFieldName];${onSuccess}`;
}};
// TODO: get the field info at JIT time ?
table[OpCode.GETSTATIC_FAST64] = {hasBranch: false, pops: 0, pushes: 2, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const index = code.readUInt16BE(pc + 1);
return `
var fi${suffix}=f.method.cls.constantPool.get(${index}),${pushes[0]}=fi${suffix}.fieldOwnerConstructor[fi${suffix}.fullFieldName],
${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.GETFIELD_FAST32] = {hasBranch: false, pops: 1, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes, method) => {
const onError = makeOnError(onErrorPushes, pc);
const index = code.readUInt16BE(pc + 1);
const fieldInfo = <FieldReference> method.cls.constantPool.get(index);
const name = fieldInfo.fullFieldName.replace(escapeStringRegEx, "\\\\")
return `if(!u.isNull(t,f,${pops[0]})){var ${pushes[0]}=${pops[0]}['${name}'];${onSuccess}}else{${onError}}`;
}};
table[OpCode.GETFIELD_FAST64] = {hasBranch: false, pops: 1, pushes: 2, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes, method) => {
const onError = makeOnError(onErrorPushes, pc);
const index = code.readUInt16BE(pc + 1);
const fieldInfo = <FieldReference> method.cls.constantPool.get(index);
const name = fieldInfo.fullFieldName.replace(escapeStringRegEx, "\\\\")
return `if(!u.isNull(t,f,${pops[0]})){var ${pushes[0]}=${pops[0]}['${name}'],${pushes[1]}=null;${onSuccess}}else{${onError}}`;
}};
table[OpCode.PUTFIELD_FAST32] = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes, method) => {
const onError = makeOnError(onErrorPushes, pc);
const index = code.readUInt16BE(pc + 1);
const fieldInfo = <FieldReference> method.cls.constantPool.get(index);
const name = fieldInfo.fullFieldName.replace(escapeStringRegEx, "\\\\")
return `if(!u.isNull(t,f,${pops[1]})){${pops[1]}['${name}']=${pops[0]};${onSuccess}}else{${onError}}`;
}};
table[OpCode.PUTFIELD_FAST64] = {hasBranch: false, pops: 3, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes, method) => {
const onError = makeOnError(onErrorPushes, pc);
const index = code.readUInt16BE(pc + 1);
const fieldInfo = <FieldReference> method.cls.constantPool.get(index);
const name = fieldInfo.fullFieldName.replace(escapeStringRegEx, "\\\\")
return `if(!u.isNull(t,f,${pops[2]})){${pops[2]}['${name}']=${pops[1]};${onSuccess}}else{${onError}}`;
}};
// TODO: get the constant at JIT time ?
table[OpCode.INSTANCEOF_FAST] = {hasBranch: false, pops: 1, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const index = code.readUInt16BE(pc + 1);
return `var cls${suffix}=f.method.cls.constantPool.get(${index}).cls,${pushes[0]}=${pops[0]}!==null?(${pops[0]}.getClass().isCastable(cls${suffix})?1:0):0;${onSuccess}`;
}};
table[OpCode.CHECKCAST_FAST] = {hasBranch: false, pops: 1, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes, method) => {
const index = code.readUInt16BE(pc + 1);
const classRef = <ClassReference> method.cls.constantPool.get(index),
targetClass = classRef.cls.getExternalName();
return `var cls${suffix}=f.method.cls.constantPool.get(${index}).cls;
if((${pops[0]}!=null)&&!${pops[0]}.getClass().isCastable(cls${suffix})){
u.throwException(t,f,'Ljava/lang/ClassCastException;',${pops[0]}.getClass().getExternalName()+' cannot be cast to ${targetClass}');
}else{var ${pushes[0]}=${pops[0]};${onSuccess}}`
}};
table[OpCode.ARRAYLENGTH] = {hasBranch: false, pops: 1, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes, pc);
return `if(!u.isNull(t,f,${pops[0]})){var ${pushes[0]}=${pops[0]}.array.length;${onSuccess}}else{${onError}}`;
}};
const load32: JitInfo = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const index = code[pc + 1];
return `var ${pushes[0]}=f.locals[${index}];${onSuccess}`;
}}
table[OpCode.ILOAD] = load32;
table[OpCode.ALOAD] = load32;
table[OpCode.FLOAD] = load32;
const load64: JitInfo = {hasBranch: false, pops: 0, pushes: 2, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const index = code[pc + 1];
return `var ${pushes[0]}=f.locals[${index}],${pushes[1]}=null;${onSuccess}`;
}}
table[OpCode.LLOAD] = load64;
table[OpCode.DLOAD] = load64;
const store32: JitInfo = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const index = code[pc + 1];
return `f.locals[${index}]=${pops[0]};${onSuccess}`;
}}
table[OpCode.ISTORE] = store32;
table[OpCode.ASTORE] = store32;
table[OpCode.FSTORE] = store32;
table[OpCode.BIPUSH] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const value = code.readInt8(pc + 1);
return `var ${pushes[0]}=${value};${onSuccess}`;
}};
table[OpCode.SIPUSH] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const value = code.readInt16BE(pc + 1);
return `var ${pushes[0]}=${value};${onSuccess}`;
}};
table[OpCode.IINC] = {hasBranch: false, pops: 0, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const idx = code[pc + 1];
const val = code.readInt8(pc + 2);
return `f.locals[${idx}]=(f.locals[${idx}]+${val})|0;${onSuccess}`;
}};
// This is marked as hasBranch: true to stop further opcode inclusion during JITC. The name of "hasBranch" ought to be changed.
table[OpCode.ATHROW] = {hasBranch: true, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes, pc);
return `${onError}t.throwException(${pops[0]});f.returnToThreadLoop=true;`;
}};
table[OpCode.GOTO] = {hasBranch: true, pops: 0, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const offset = code.readInt16BE(pc + 1);
return `f.pc=${pc + offset};${onSuccess}`;
}};
table[OpCode.TABLESWITCH] = {hasBranch: true, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
// Ignore padding bytes. The +1 is to skip the opcode byte.
const alignedPC = pc + ((4 - (pc + 1) % 4) % 4) + 1;
const defaultOffset = code.readInt32BE(alignedPC),
low = code.readInt32BE(alignedPC + 4),
high = code.readInt32BE(alignedPC + 8);
if ((high - low) < 8) {
let emitted = `switch(${pops[0]}){`;
for (let i = low; i <= high; i++) {
const offset = code.readInt32BE(alignedPC + 12+((i-low)*4));
emitted += `case ${i}:f.pc=${pc + offset};break;`;
}
emitted += `default:f.pc=${pc + defaultOffset}}${onSuccess}`
return emitted;
} else {
return `if(${pops[0]}>=${low}&&${pops[0]}<=${high}){f.pc=${pc}+f.method.getCodeAttribute().getCode().readInt32BE(${alignedPC + 12}+((${pops[0]} - ${low})*4))}else{f.pc=${pc + defaultOffset}}${onSuccess}`;
}
}};
const cmpeq: JitInfo = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[0]}===${pops[1]}){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IF_ICMPEQ] = cmpeq;
table[OpCode.IF_ACMPEQ] = cmpeq;
const cmpne: JitInfo = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[0]}!==${pops[1]}){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IF_ICMPNE] = cmpne;
table[OpCode.IF_ACMPNE] = cmpne;
table[OpCode.IF_ICMPGE] = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[1]}>=${pops[0]}){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IF_ICMPGT] = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[1]}>${pops[0]}){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IF_ICMPLE] = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[1]}<=${pops[0]}){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IF_ICMPLT] = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[1]}<${pops[0]}){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IFNULL] = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[0]}==null){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IFNONNULL] = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[0]}!=null){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IFEQ] = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[0]}===0){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IFNE] = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[0]}!==0){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IFGT] = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[0]}>0){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IFLT] = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[0]}<0){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IFGE] = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[0]}>=0){${onError}}else{${onSuccess}}`;
}};
table[OpCode.IFLE] = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const offset = code.readInt16BE(pc + 1);
const onError = makeOnError(onErrorPushes, pc + offset);
return `if(${pops[0]}<=0){${onError}}else{${onSuccess}}`;
}};
table[OpCode.LCMP] = {hasBranch: false, pops: 4, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[3]}.compare(${pops[1]});${onSuccess}`;
}};
table[OpCode.FCMPL] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[0]}===${pops[1]}?0:(${pops[1]}>${pops[0]}?1:-1);${onSuccess}`;
}};
table[OpCode.DCMPL] = {hasBranch: false, pops: 4, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[3]}===${pops[1]}?0:(${pops[3]}>${pops[1]}?1:-1);${onSuccess}`;
}};
table[OpCode.FCMPG] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[0]}===${pops[1]}?0:(${pops[1]}<${pops[0]}?-1:1);${onSuccess}`;
}};
table[OpCode.DCMPG] = {hasBranch: false, pops: 4, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[3]}===${pops[1]}?0:(${pops[3]}<${pops[1]}?-1:1);${onSuccess}`;
}};
table[OpCode.RETURN] = {hasBranch: true, pops: 0, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes, method) => {
// TODO: on error pushes
if (method.accessFlags.isSynchronized()) {
return `f.pc=${pc};f.returnToThreadLoop=true;if(!f.method.methodLock(t,f).exit(t)){return}t.asyncReturn();`;
} else {
return `f.pc=${pc};f.returnToThreadLoop=true;t.asyncReturn();`;
}
}};
const return32: JitInfo = {hasBranch: true, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes, method) => {
// TODO: on error pushes
if (method.accessFlags.isSynchronized()) {
return `f.pc=${pc};f.returnToThreadLoop=true;if(!f.method.methodLock(t,f).exit(t)){return}t.asyncReturn(${pops[0]});`;
} else {
return `f.pc=${pc};f.returnToThreadLoop=true;t.asyncReturn(${pops[0]});`;
}
}};
table[OpCode.IRETURN] = return32;
table[OpCode.FRETURN] = return32;
table[OpCode.ARETURN] = return32;
const return64: JitInfo = {hasBranch: true, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes, method) => {
// TODO: on error pushes
if (method.accessFlags.isSynchronized()) {
return `f.pc=${pc};f.returnToThreadLoop=true;if(!f.method.methodLock(t,f).exit(t)){return}t.asyncReturn(${pops[1]},null);`;
} else {
return `f.pc=${pc};f.returnToThreadLoop=true;t.asyncReturn(${pops[1]},null);`;
}
}};
table[OpCode.LRETURN] = return64;
table[OpCode.DRETURN] = return64;
table[OpCode.MONITOREXIT] = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes, pc);
return `if(${pops[0]}.getMonitor().exit(t)){${onSuccess}}else{${onError}f.returnToThreadLoop=true;}`;
}};
table[OpCode.IXOR] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[0]}^${pops[1]};${onSuccess}`;
}};
table[OpCode.LXOR] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[1]}.xor(${pops[3]}),${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.IOR] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[0]}|${pops[1]};${onSuccess}`;
}};
table[OpCode.LOR] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[3]}.or(${pops[1]}),${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.IAND] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[0]}&${pops[1]};${onSuccess}`;
}};
table[OpCode.LAND] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[3]}.and(${pops[1]}),${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.IADD] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=(${pops[0]}+${pops[1]})|0;${onSuccess}`;
}};
table[OpCode.LADD] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[1]}.add(${pops[3]}),${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.DADD] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[1]}+${pops[3]},${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.IMUL] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=Math.imul(${pops[0]}, ${pops[1]});${onSuccess}`;
}};
table[OpCode.FMUL] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=u.wrapFloat(${pops[0]}*${pops[1]});${onSuccess}`;
}};
table[OpCode.LMUL] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[3]}.multiply(${pops[1]}),${pushes[1]}= null;${onSuccess}`;
}};
table[OpCode.DMUL] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[3]}*${pops[1]},${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.IDIV] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes, pc);
return `
if(${pops[0]}===0){${onError}u.throwException(t,f,'Ljava/lang/ArithmeticException;','/ by zero');
}else{var ${pushes[0]}=(${pops[1]}===u.Constants.INT_MIN&&${pops[0]}===-1)?${pops[1]}:((${pops[1]}/${pops[0]})|0);${onSuccess}}`;
}};
table[OpCode.LDIV] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes, pc);
return `
if(${pops[1]}.isZero()){${onError}u.throwException(t,f,'Ljava/lang/ArithmeticException;','/ by zero');
}else{var ${pushes[0]}=${pops[3]}.div(${pops[1]}),${pushes[1]}=null;${onSuccess}}`;
}};
table[OpCode.DDIV] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[3]}/${pops[1]},${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.ISUB] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=(${pops[1]}-${pops[0]})|0;${onSuccess}`;
}};
table[OpCode.LSUB] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[1]}.negate().add(${pops[3]}),${pushes[1]}= null;${onSuccess}`;
}};
table[OpCode.DSUB] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[3]}-${pops[1]},${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.IREM] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes, pc);
return `if(${pops[0]}===0){${onError}u.throwException(t,f,'Ljava/lang/ArithmeticException;','/ by zero');
}else{var ${pushes[0]}=${pops[1]}%${pops[0]};${onSuccess}}`;
}};
table[OpCode.LREM] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes, pc);
return `if(${pops[1]}.isZero()){${onError}u.throwException(t,f,'Ljava/lang/ArithmeticException;','/ by zero');
}else{var ${pushes[0]}=${pops[3]}.modulo(${pops[1]}),${pushes[1]}=null;${onSuccess}}`;
}};
table[OpCode.DREM] = {hasBranch: false, pops: 4, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[3]}%${pops[1]},${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.INEG] = {hasBranch: false, pops: 1, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=(-${pops[0]})|0;${onSuccess}`;
}};
table[OpCode.LNEG] = {hasBranch: false, pops: 2, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[1]}.negate(),${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.ISHL] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[1]}<<${pops[0]};${onSuccess}`;
}};
table[OpCode.LSHL] = {hasBranch: false, pops: 3, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[2]}.shiftLeft(u.gLong.fromInt(${pops[0]})),${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.ISHR] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[1]}>>${pops[0]};${onSuccess}`;
}};
table[OpCode.LSHR] = {hasBranch: false, pops: 3, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[2]}.shiftRight(u.gLong.fromInt(${pops[0]})),${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.IUSHR] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=(${pops[1]}>>>${pops[0]})|0;${onSuccess}`;
}};
table[OpCode.LUSHR] = {hasBranch: false, pops: 3, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[2]}.shiftRightUnsigned(u.gLong.fromInt(${pops[0]})),${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.I2B] = {hasBranch: false, pops: 1, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=(${pops[0]}<<24)>>24;${onSuccess}`;
}};
table[OpCode.I2S] = {hasBranch: false, pops: 1, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=(${pops[0]}<<16)>>16;${onSuccess}`;
}};
table[OpCode.I2C] = {hasBranch: false, pops: 1, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[0]}&0xFFFF;${onSuccess}`;
}};
table[OpCode.I2L] = {hasBranch: false, pops: 1, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=u.gLong.fromInt(${pops[0]}),${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.I2F] = {hasBranch: false, pops: 0, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
return `${onSuccess}`;
}};
table[OpCode.I2D] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=null;${onSuccess}`;
}};
table[OpCode.F2I] = {hasBranch: false, pops: 1, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=u.float2int(${pops[0]});${onSuccess}`;
}};
table[OpCode.F2D] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=null;${onSuccess}`;
}};
table[OpCode.L2I] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[1]}.toInt();${onSuccess}`;
}};
table[OpCode.L2D] = {hasBranch: false, pops: 2, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[1]}.toNumber(),${pushes[1]}=null;${onSuccess}`;
}};
table[OpCode.D2I] = {hasBranch: false, pops: 2, pushes: 1, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=u.float2int(${pops[1]});${onSuccess}`;
}};
// TODO: update the DUPs when peeking is supported
table[OpCode.DUP] = {hasBranch: false, pops: 1, pushes: 2, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[0]},${pushes[1]}=${pops[0]};${onSuccess}`;
}};
table[OpCode.DUP2] = {hasBranch: false, pops: 2, pushes: 4, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[1]},${pushes[1]}=${pops[0]},${pushes[2]}=${pops[1]},${pushes[3]}=${pops[0]};${onSuccess}`;
}};
table[OpCode.DUP_X1] = {hasBranch: false, pops: 2, pushes: 3, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[0]},${pushes[1]}=${pops[1]},${pushes[2]}=${pops[0]};${onSuccess}`;
}};
table[OpCode.DUP_X2] = {hasBranch: false, pops: 3, pushes: 4, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[0]},${pushes[1]}=${pops[2]},${pushes[2]}=${pops[1]},${pushes[3]}=${pops[0]};${onSuccess}`;
}};
table[OpCode.DUP2_X1] = {hasBranch: false, pops: 3, pushes: 5, emit: (pops, pushes, suffix, onSuccess) => {
return `var ${pushes[0]}=${pops[1]},${pushes[1]}=${pops[0]},${pushes[2]}=${pops[2]},${pushes[3]}=${pops[1]},${pushes[4]}=${pops[0]};${onSuccess}`;
}};
table[OpCode.NEW_FAST] = {hasBranch: false, pops: 0, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc) => {
const index = code.readUInt16BE(pc + 1);
return `var cr${suffix}=f.method.cls.constantPool.get(${index}),${pushes[0]}=(new cr${suffix}.clsConstructor(t));${onSuccess}`;
}};
table[OpCode.NEWARRAY] = {hasBranch: false, pops: 1, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const index = code[pc + 1];
const arrayType = "[" + opcodes.ArrayTypes[index];
const onError = makeOnError(onErrorPushes, pc);
return `
var cls${suffix}=f.getLoader().getInitializedClass(t,'${arrayType}');
if(${pops[0]}>=0){var ${pushes[0]}=new (cls${suffix}.getConstructor(t))(t,${pops[0]});${onSuccess}
}else{${onError}u.throwException(t,f,'Ljava/lang/NegativeArraySizeException;','Tried to init ${arrayType} array with length '+${pops[0]});}`;
}};
table[OpCode.ANEWARRAY_FAST] = {hasBranch: false, pops: 1, pushes: 1, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const index = code.readUInt16BE(pc + 1);
const arrayType = "[" + opcodes.ArrayTypes[index];
const onError = makeOnError(onErrorPushes, pc);
return `
var cr${suffix}=f.method.cls.constantPool.get(${index});
if(${pops[0]}>=0){var ${pushes[0]}=new cr${suffix}.arrayClassConstructor(t,${pops[0]});${onSuccess}
}else{${onError}u.throwException(t,f,'Ljava/lang/NegativeArraySizeException;','Tried to init '+cr${suffix}.arrayClass.getInternalName()+' array with length '+${pops[0]});}`;
}};
table[OpCode.NOP] = {hasBranch: false, pops: 0, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
return `${onSuccess}`;
}};
table[OpCode.POP] = {hasBranch: false, pops: 1, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
return `${onSuccess}`;
}};
table[OpCode.POP2] = {hasBranch: false, pops: 2, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
return `${onSuccess}`;
}};
return table;
}(); | the_stack |
import {
OperationParameter,
OperationURLParameter,
OperationQueryParameter
} from "@azure/core-client";
import {
FactoryRepoUpdate as FactoryRepoUpdateMapper,
Factory as FactoryMapper,
FactoryUpdateParameters as FactoryUpdateParametersMapper,
GitHubAccessTokenRequest as GitHubAccessTokenRequestMapper,
UserAccessPolicy as UserAccessPolicyMapper,
ExposureControlRequest as ExposureControlRequestMapper,
ExposureControlBatchRequest as ExposureControlBatchRequestMapper,
IntegrationRuntimeResource as IntegrationRuntimeResourceMapper,
UpdateIntegrationRuntimeRequest as UpdateIntegrationRuntimeRequestMapper,
IntegrationRuntimeRegenerateKeyParameters as IntegrationRuntimeRegenerateKeyParametersMapper,
LinkedIntegrationRuntimeRequest as LinkedIntegrationRuntimeRequestMapper,
CreateLinkedIntegrationRuntimeRequest as CreateLinkedIntegrationRuntimeRequestMapper,
GetSsisObjectMetadataRequest as GetSsisObjectMetadataRequestMapper,
UpdateIntegrationRuntimeNodeRequest as UpdateIntegrationRuntimeNodeRequestMapper,
LinkedServiceResource as LinkedServiceResourceMapper,
DatasetResource as DatasetResourceMapper,
PipelineResource as PipelineResourceMapper,
RunFilterParameters as RunFilterParametersMapper,
TriggerFilterParameters as TriggerFilterParametersMapper,
TriggerResource as TriggerResourceMapper,
DataFlowResource as DataFlowResourceMapper,
CreateDataFlowDebugSessionRequest as CreateDataFlowDebugSessionRequestMapper,
DataFlowDebugPackage as DataFlowDebugPackageMapper,
DeleteDataFlowDebugSessionRequest as DeleteDataFlowDebugSessionRequestMapper,
DataFlowDebugCommandRequest as DataFlowDebugCommandRequestMapper,
ManagedVirtualNetworkResource as ManagedVirtualNetworkResourceMapper,
ManagedPrivateEndpointResource as ManagedPrivateEndpointResourceMapper,
PrivateLinkConnectionApprovalRequestResource as PrivateLinkConnectionApprovalRequestResourceMapper
} from "../models/mappers";
export const accept: OperationParameter = {
parameterPath: "accept",
mapper: {
defaultValue: "application/json",
isConstant: true,
serializedName: "Accept",
type: {
name: "String"
}
}
};
export const $host: OperationURLParameter = {
parameterPath: "$host",
mapper: {
serializedName: "$host",
required: true,
type: {
name: "String"
}
},
skipEncoding: true
};
export const apiVersion: OperationQueryParameter = {
parameterPath: "apiVersion",
mapper: {
defaultValue: "2018-06-01",
isConstant: true,
serializedName: "api-version",
type: {
name: "String"
}
}
};
export const nextLink: OperationURLParameter = {
parameterPath: "nextLink",
mapper: {
serializedName: "nextLink",
required: true,
type: {
name: "String"
}
},
skipEncoding: true
};
export const subscriptionId: OperationURLParameter = {
parameterPath: "subscriptionId",
mapper: {
serializedName: "subscriptionId",
required: true,
type: {
name: "String"
}
}
};
export const contentType: OperationParameter = {
parameterPath: ["options", "contentType"],
mapper: {
defaultValue: "application/json",
isConstant: true,
serializedName: "Content-Type",
type: {
name: "String"
}
}
};
export const factoryRepoUpdate: OperationParameter = {
parameterPath: "factoryRepoUpdate",
mapper: FactoryRepoUpdateMapper
};
export const locationId: OperationURLParameter = {
parameterPath: "locationId",
mapper: {
serializedName: "locationId",
required: true,
type: {
name: "String"
}
}
};
export const resourceGroupName: OperationURLParameter = {
parameterPath: "resourceGroupName",
mapper: {
constraints: {
Pattern: new RegExp("^[-\\w\\._\\(\\)]+$"),
MaxLength: 90,
MinLength: 1
},
serializedName: "resourceGroupName",
required: true,
type: {
name: "String"
}
}
};
export const factory: OperationParameter = {
parameterPath: "factory",
mapper: FactoryMapper
};
export const factoryName: OperationURLParameter = {
parameterPath: "factoryName",
mapper: {
constraints: {
Pattern: new RegExp("^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"),
MaxLength: 63,
MinLength: 3
},
serializedName: "factoryName",
required: true,
type: {
name: "String"
}
}
};
export const ifMatch: OperationParameter = {
parameterPath: ["options", "ifMatch"],
mapper: {
serializedName: "If-Match",
type: {
name: "String"
}
}
};
export const factoryUpdateParameters: OperationParameter = {
parameterPath: "factoryUpdateParameters",
mapper: FactoryUpdateParametersMapper
};
export const ifNoneMatch: OperationParameter = {
parameterPath: ["options", "ifNoneMatch"],
mapper: {
serializedName: "If-None-Match",
type: {
name: "String"
}
}
};
export const gitHubAccessTokenRequest: OperationParameter = {
parameterPath: "gitHubAccessTokenRequest",
mapper: GitHubAccessTokenRequestMapper
};
export const policy: OperationParameter = {
parameterPath: "policy",
mapper: UserAccessPolicyMapper
};
export const exposureControlRequest: OperationParameter = {
parameterPath: "exposureControlRequest",
mapper: ExposureControlRequestMapper
};
export const exposureControlBatchRequest: OperationParameter = {
parameterPath: "exposureControlBatchRequest",
mapper: ExposureControlBatchRequestMapper
};
export const integrationRuntime: OperationParameter = {
parameterPath: "integrationRuntime",
mapper: IntegrationRuntimeResourceMapper
};
export const integrationRuntimeName: OperationURLParameter = {
parameterPath: "integrationRuntimeName",
mapper: {
constraints: {
Pattern: new RegExp("^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"),
MaxLength: 63,
MinLength: 3
},
serializedName: "integrationRuntimeName",
required: true,
type: {
name: "String"
}
}
};
export const updateIntegrationRuntimeRequest: OperationParameter = {
parameterPath: "updateIntegrationRuntimeRequest",
mapper: UpdateIntegrationRuntimeRequestMapper
};
export const regenerateKeyParameters: OperationParameter = {
parameterPath: "regenerateKeyParameters",
mapper: IntegrationRuntimeRegenerateKeyParametersMapper
};
export const linkedIntegrationRuntimeRequest: OperationParameter = {
parameterPath: "linkedIntegrationRuntimeRequest",
mapper: LinkedIntegrationRuntimeRequestMapper
};
export const createLinkedIntegrationRuntimeRequest: OperationParameter = {
parameterPath: "createLinkedIntegrationRuntimeRequest",
mapper: CreateLinkedIntegrationRuntimeRequestMapper
};
export const getMetadataRequest: OperationParameter = {
parameterPath: ["options", "getMetadataRequest"],
mapper: GetSsisObjectMetadataRequestMapper
};
export const nodeName: OperationURLParameter = {
parameterPath: "nodeName",
mapper: {
constraints: {
Pattern: new RegExp("^[a-z0-9A-Z][a-z0-9A-Z_-]{0,149}$"),
MaxLength: 150,
MinLength: 1
},
serializedName: "nodeName",
required: true,
type: {
name: "String"
}
}
};
export const updateIntegrationRuntimeNodeRequest: OperationParameter = {
parameterPath: "updateIntegrationRuntimeNodeRequest",
mapper: UpdateIntegrationRuntimeNodeRequestMapper
};
export const linkedService: OperationParameter = {
parameterPath: "linkedService",
mapper: LinkedServiceResourceMapper
};
export const linkedServiceName: OperationURLParameter = {
parameterPath: "linkedServiceName",
mapper: {
constraints: {
Pattern: new RegExp("^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$"),
MaxLength: 260,
MinLength: 1
},
serializedName: "linkedServiceName",
required: true,
type: {
name: "String"
}
}
};
export const dataset: OperationParameter = {
parameterPath: "dataset",
mapper: DatasetResourceMapper
};
export const datasetName: OperationURLParameter = {
parameterPath: "datasetName",
mapper: {
constraints: {
Pattern: new RegExp("^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$"),
MaxLength: 260,
MinLength: 1
},
serializedName: "datasetName",
required: true,
type: {
name: "String"
}
}
};
export const pipeline: OperationParameter = {
parameterPath: "pipeline",
mapper: PipelineResourceMapper
};
export const pipelineName: OperationURLParameter = {
parameterPath: "pipelineName",
mapper: {
constraints: {
Pattern: new RegExp("^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$"),
MaxLength: 260,
MinLength: 1
},
serializedName: "pipelineName",
required: true,
type: {
name: "String"
}
}
};
export const parameters: OperationParameter = {
parameterPath: ["options", "parameters"],
mapper: {
serializedName: "parameters",
type: {
name: "Dictionary",
value: { type: { name: "Dictionary", value: { type: { name: "any" } } } }
}
}
};
export const referencePipelineRunId: OperationQueryParameter = {
parameterPath: ["options", "referencePipelineRunId"],
mapper: {
serializedName: "referencePipelineRunId",
type: {
name: "String"
}
}
};
export const isRecovery: OperationQueryParameter = {
parameterPath: ["options", "isRecovery"],
mapper: {
serializedName: "isRecovery",
type: {
name: "Boolean"
}
}
};
export const startActivityName: OperationQueryParameter = {
parameterPath: ["options", "startActivityName"],
mapper: {
serializedName: "startActivityName",
type: {
name: "String"
}
}
};
export const startFromFailure: OperationQueryParameter = {
parameterPath: ["options", "startFromFailure"],
mapper: {
serializedName: "startFromFailure",
type: {
name: "Boolean"
}
}
};
export const filterParameters: OperationParameter = {
parameterPath: "filterParameters",
mapper: RunFilterParametersMapper
};
export const runId: OperationURLParameter = {
parameterPath: "runId",
mapper: {
serializedName: "runId",
required: true,
type: {
name: "String"
}
}
};
export const isRecursive: OperationQueryParameter = {
parameterPath: ["options", "isRecursive"],
mapper: {
serializedName: "isRecursive",
type: {
name: "Boolean"
}
}
};
export const filterParameters1: OperationParameter = {
parameterPath: "filterParameters",
mapper: TriggerFilterParametersMapper
};
export const trigger: OperationParameter = {
parameterPath: "trigger",
mapper: TriggerResourceMapper
};
export const triggerName: OperationURLParameter = {
parameterPath: "triggerName",
mapper: {
constraints: {
Pattern: new RegExp("^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$"),
MaxLength: 260,
MinLength: 1
},
serializedName: "triggerName",
required: true,
type: {
name: "String"
}
}
};
export const dataFlow: OperationParameter = {
parameterPath: "dataFlow",
mapper: DataFlowResourceMapper
};
export const dataFlowName: OperationURLParameter = {
parameterPath: "dataFlowName",
mapper: {
constraints: {
Pattern: new RegExp("^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$"),
MaxLength: 260,
MinLength: 1
},
serializedName: "dataFlowName",
required: true,
type: {
name: "String"
}
}
};
export const request: OperationParameter = {
parameterPath: "request",
mapper: CreateDataFlowDebugSessionRequestMapper
};
export const request1: OperationParameter = {
parameterPath: "request",
mapper: DataFlowDebugPackageMapper
};
export const request2: OperationParameter = {
parameterPath: "request",
mapper: DeleteDataFlowDebugSessionRequestMapper
};
export const request3: OperationParameter = {
parameterPath: "request",
mapper: DataFlowDebugCommandRequestMapper
};
export const managedVirtualNetwork: OperationParameter = {
parameterPath: "managedVirtualNetwork",
mapper: ManagedVirtualNetworkResourceMapper
};
export const managedVirtualNetworkName: OperationURLParameter = {
parameterPath: "managedVirtualNetworkName",
mapper: {
constraints: {
Pattern: new RegExp(
"^([_A-Za-z0-9]|([_A-Za-z0-9][-_A-Za-z0-9]{0,125}[_A-Za-z0-9]))$"
),
MaxLength: 127,
MinLength: 1
},
serializedName: "managedVirtualNetworkName",
required: true,
type: {
name: "String"
}
}
};
export const managedPrivateEndpoint: OperationParameter = {
parameterPath: "managedPrivateEndpoint",
mapper: ManagedPrivateEndpointResourceMapper
};
export const managedPrivateEndpointName: OperationURLParameter = {
parameterPath: "managedPrivateEndpointName",
mapper: {
constraints: {
Pattern: new RegExp(
"^([_A-Za-z0-9]|([_A-Za-z0-9][-_A-Za-z0-9]{0,125}[_A-Za-z0-9]))$"
),
MaxLength: 127,
MinLength: 1
},
serializedName: "managedPrivateEndpointName",
required: true,
type: {
name: "String"
}
}
};
export const privateEndpointWrapper: OperationParameter = {
parameterPath: "privateEndpointWrapper",
mapper: PrivateLinkConnectionApprovalRequestResourceMapper
};
export const privateEndpointConnectionName: OperationURLParameter = {
parameterPath: "privateEndpointConnectionName",
mapper: {
serializedName: "privateEndpointConnectionName",
required: true,
type: {
name: "String"
}
}
}; | the_stack |
* @fileoverview Type definitions for Blockly Messages.
* @author samelh@google.com (Sam El-Husseini)
*/
declare namespace Blockly.Msg {
let ADD_COMMENT : string ;
let CANNOT_DELETE_VARIABLE_PROCEDURE : string ;
let CHANGE_VALUE_TITLE : string ;
let CLEAN_UP : string ;
let COLLAPSED_WARNINGS_WARNING : string ;
let COLLAPSE_ALL : string ;
let COLLAPSE_BLOCK : string ;
let COLOUR_BLEND_COLOUR1 : string ;
let COLOUR_BLEND_COLOUR2 : string ;
let COLOUR_BLEND_HELPURL : string ;
let COLOUR_BLEND_RATIO : string ;
let COLOUR_BLEND_TITLE : string ;
let COLOUR_BLEND_TOOLTIP : string ;
let COLOUR_HUE : string ;
let COLOUR_PICKER_HELPURL : string ;
let COLOUR_PICKER_TOOLTIP : string ;
let COLOUR_RANDOM_HELPURL : string ;
let COLOUR_RANDOM_TITLE : string ;
let COLOUR_RANDOM_TOOLTIP : string ;
let COLOUR_RGB_BLUE : string ;
let COLOUR_RGB_GREEN : string ;
let COLOUR_RGB_HELPURL : string ;
let COLOUR_RGB_RED : string ;
let COLOUR_RGB_TITLE : string ;
let COLOUR_RGB_TOOLTIP : string ;
let CONTROLS_FLOW_STATEMENTS_HELPURL : string ;
let CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK : string ;
let CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE : string ;
let CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK : string ;
let CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE : string ;
let CONTROLS_FLOW_STATEMENTS_WARNING : string ;
let CONTROLS_FOREACH_HELPURL : string ;
let CONTROLS_FOREACH_INPUT_DO : string ;
let CONTROLS_FOREACH_TITLE : string ;
let CONTROLS_FOREACH_TOOLTIP : string ;
let CONTROLS_FOR_HELPURL : string ;
let CONTROLS_FOR_INPUT_DO : string ;
let CONTROLS_FOR_TITLE : string ;
let CONTROLS_FOR_TOOLTIP : string ;
let CONTROLS_IF_ELSEIF_TITLE_ELSEIF : string ;
let CONTROLS_IF_ELSEIF_TOOLTIP : string ;
let CONTROLS_IF_ELSE_TITLE_ELSE : string ;
let CONTROLS_IF_ELSE_TOOLTIP : string ;
let CONTROLS_IF_HELPURL : string ;
let CONTROLS_IF_IF_TITLE_IF : string ;
let CONTROLS_IF_IF_TOOLTIP : string ;
let CONTROLS_IF_MSG_ELSE : string ;
let CONTROLS_IF_MSG_ELSEIF : string ;
let CONTROLS_IF_MSG_IF : string ;
let CONTROLS_IF_MSG_THEN : string ;
let CONTROLS_IF_TOOLTIP_1 : string ;
let CONTROLS_IF_TOOLTIP_2 : string ;
let CONTROLS_IF_TOOLTIP_3 : string ;
let CONTROLS_IF_TOOLTIP_4 : string ;
let CONTROLS_REPEAT_HELPURL : string ;
let CONTROLS_REPEAT_INPUT_DO : string ;
let CONTROLS_REPEAT_TITLE : string ;
let CONTROLS_REPEAT_TOOLTIP : string ;
let CONTROLS_WHILEUNTIL_HELPURL : string ;
let CONTROLS_WHILEUNTIL_INPUT_DO : string ;
let CONTROLS_WHILEUNTIL_OPERATOR_UNTIL : string ;
let CONTROLS_WHILEUNTIL_OPERATOR_WHILE : string ;
let CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL : string ;
let CONTROLS_WHILEUNTIL_TOOLTIP_WHILE : string ;
let DELETE_ALL_BLOCKS : string ;
let DELETE_BLOCK : string ;
let DELETE_VARIABLE : string ;
let DELETE_VARIABLE_CONFIRMATION : string ;
let DELETE_X_BLOCKS : string ;
let DISABLE_BLOCK : string ;
let DUPLICATE_BLOCK : string ;
let DUPLICATE_COMMENT : string ;
let ENABLE_BLOCK : string ;
let EXPAND_ALL : string ;
let EXPAND_BLOCK : string ;
let EXTERNAL_INPUTS : string ;
let HELP : string ;
let INLINE_INPUTS : string ;
let IOS_CANCEL : string ;
let IOS_ERROR : string ;
let IOS_OK : string ;
let IOS_PROCEDURES_ADD_INPUT : string ;
let IOS_PROCEDURES_ALLOW_STATEMENTS : string ;
let IOS_PROCEDURES_DUPLICATE_INPUTS_ERROR : string ;
let IOS_PROCEDURES_INPUTS : string ;
let IOS_VARIABLES_ADD_BUTTON : string ;
let IOS_VARIABLES_ADD_VARIABLE : string ;
let IOS_VARIABLES_DELETE_BUTTON : string ;
let IOS_VARIABLES_EMPTY_NAME_ERROR : string ;
let IOS_VARIABLES_RENAME_BUTTON : string ;
let IOS_VARIABLES_VARIABLE_NAME : string ;
let LISTS_CREATE_EMPTY_HELPURL : string ;
let LISTS_CREATE_EMPTY_TITLE : string ;
let LISTS_CREATE_EMPTY_TOOLTIP : string ;
let LISTS_CREATE_WITH_CONTAINER_TITLE_ADD : string ;
let LISTS_CREATE_WITH_CONTAINER_TOOLTIP : string ;
let LISTS_CREATE_WITH_HELPURL : string ;
let LISTS_CREATE_WITH_INPUT_WITH : string ;
let LISTS_CREATE_WITH_ITEM_TITLE : string ;
let LISTS_CREATE_WITH_ITEM_TOOLTIP : string ;
let LISTS_CREATE_WITH_TOOLTIP : string ;
let LISTS_GET_INDEX_FIRST : string ;
let LISTS_GET_INDEX_FROM_END : string ;
let LISTS_GET_INDEX_FROM_START : string ;
let LISTS_GET_INDEX_GET : string ;
let LISTS_GET_INDEX_GET_REMOVE : string ;
let LISTS_GET_INDEX_HELPURL : string ;
let LISTS_GET_INDEX_INPUT_IN_LIST : string ;
let LISTS_GET_INDEX_LAST : string ;
let LISTS_GET_INDEX_RANDOM : string ;
let LISTS_GET_INDEX_REMOVE : string ;
let LISTS_GET_INDEX_TAIL : string ;
let LISTS_GET_INDEX_TOOLTIP_GET_FIRST : string ;
let LISTS_GET_INDEX_TOOLTIP_GET_FROM : string ;
let LISTS_GET_INDEX_TOOLTIP_GET_LAST : string ;
let LISTS_GET_INDEX_TOOLTIP_GET_RANDOM : string ;
let LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST : string ;
let LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM : string ;
let LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST : string ;
let LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM : string ;
let LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST : string ;
let LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM : string ;
let LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST : string ;
let LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM : string ;
let LISTS_GET_SUBLIST_END_FROM_END : string ;
let LISTS_GET_SUBLIST_END_FROM_START : string ;
let LISTS_GET_SUBLIST_END_LAST : string ;
let LISTS_GET_SUBLIST_HELPURL : string ;
let LISTS_GET_SUBLIST_INPUT_IN_LIST : string ;
let LISTS_GET_SUBLIST_START_FIRST : string ;
let LISTS_GET_SUBLIST_START_FROM_END : string ;
let LISTS_GET_SUBLIST_START_FROM_START : string ;
let LISTS_GET_SUBLIST_TAIL : string ;
let LISTS_GET_SUBLIST_TOOLTIP : string ;
let LISTS_HUE : string ;
let LISTS_INDEX_FROM_END_TOOLTIP : string ;
let LISTS_INDEX_FROM_START_TOOLTIP : string ;
let LISTS_INDEX_OF_FIRST : string ;
let LISTS_INDEX_OF_HELPURL : string ;
let LISTS_INDEX_OF_INPUT_IN_LIST : string ;
let LISTS_INDEX_OF_LAST : string ;
let LISTS_INDEX_OF_TOOLTIP : string ;
let LISTS_INLIST : string ;
let LISTS_ISEMPTY_HELPURL : string ;
let LISTS_ISEMPTY_TITLE : string ;
let LISTS_ISEMPTY_TOOLTIP : string ;
let LISTS_LENGTH_HELPURL : string ;
let LISTS_LENGTH_TITLE : string ;
let LISTS_LENGTH_TOOLTIP : string ;
let LISTS_REPEAT_HELPURL : string ;
let LISTS_REPEAT_TITLE : string ;
let LISTS_REPEAT_TOOLTIP : string ;
let LISTS_REVERSE_HELPURL : string ;
let LISTS_REVERSE_MESSAGE0 : string ;
let LISTS_REVERSE_TOOLTIP : string ;
let LISTS_SET_INDEX_HELPURL : string ;
let LISTS_SET_INDEX_INPUT_IN_LIST : string ;
let LISTS_SET_INDEX_INPUT_TO : string ;
let LISTS_SET_INDEX_INSERT : string ;
let LISTS_SET_INDEX_SET : string ;
let LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST : string ;
let LISTS_SET_INDEX_TOOLTIP_INSERT_FROM : string ;
let LISTS_SET_INDEX_TOOLTIP_INSERT_LAST : string ;
let LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM : string ;
let LISTS_SET_INDEX_TOOLTIP_SET_FIRST : string ;
let LISTS_SET_INDEX_TOOLTIP_SET_FROM : string ;
let LISTS_SET_INDEX_TOOLTIP_SET_LAST : string ;
let LISTS_SET_INDEX_TOOLTIP_SET_RANDOM : string ;
let LISTS_SORT_HELPURL : string ;
let LISTS_SORT_ORDER_ASCENDING : string ;
let LISTS_SORT_ORDER_DESCENDING : string ;
let LISTS_SORT_TITLE : string ;
let LISTS_SORT_TOOLTIP : string ;
let LISTS_SORT_TYPE_IGNORECASE : string ;
let LISTS_SORT_TYPE_NUMERIC : string ;
let LISTS_SORT_TYPE_TEXT : string ;
let LISTS_SPLIT_HELPURL : string ;
let LISTS_SPLIT_LIST_FROM_TEXT : string ;
let LISTS_SPLIT_TEXT_FROM_LIST : string ;
let LISTS_SPLIT_TOOLTIP_JOIN : string ;
let LISTS_SPLIT_TOOLTIP_SPLIT : string ;
let LISTS_SPLIT_WITH_DELIMITER : string ;
let LOGIC_BOOLEAN_FALSE : string ;
let LOGIC_BOOLEAN_HELPURL : string ;
let LOGIC_BOOLEAN_TOOLTIP : string ;
let LOGIC_BOOLEAN_TRUE : string ;
let LOGIC_COMPARE_HELPURL : string ;
let LOGIC_COMPARE_TOOLTIP_EQ : string ;
let LOGIC_COMPARE_TOOLTIP_GT : string ;
let LOGIC_COMPARE_TOOLTIP_GTE : string ;
let LOGIC_COMPARE_TOOLTIP_LT : string ;
let LOGIC_COMPARE_TOOLTIP_LTE : string ;
let LOGIC_COMPARE_TOOLTIP_NEQ : string ;
let LOGIC_HUE : string ;
let LOGIC_NEGATE_HELPURL : string ;
let LOGIC_NEGATE_TITLE : string ;
let LOGIC_NEGATE_TOOLTIP : string ;
let LOGIC_NULL : string ;
let LOGIC_NULL_HELPURL : string ;
let LOGIC_NULL_TOOLTIP : string ;
let LOGIC_OPERATION_AND : string ;
let LOGIC_OPERATION_HELPURL : string ;
let LOGIC_OPERATION_OR : string ;
let LOGIC_OPERATION_TOOLTIP_AND : string ;
let LOGIC_OPERATION_TOOLTIP_OR : string ;
let LOGIC_TERNARY_CONDITION : string ;
let LOGIC_TERNARY_HELPURL : string ;
let LOGIC_TERNARY_IF_FALSE : string ;
let LOGIC_TERNARY_IF_TRUE : string ;
let LOGIC_TERNARY_TOOLTIP : string ;
let LOOPS_HUE : string ;
let MATH_ADDITION_SYMBOL : string ;
let MATH_ARITHMETIC_HELPURL : string ;
let MATH_ARITHMETIC_TOOLTIP_ADD : string ;
let MATH_ARITHMETIC_TOOLTIP_DIVIDE : string ;
let MATH_ARITHMETIC_TOOLTIP_MINUS : string ;
let MATH_ARITHMETIC_TOOLTIP_MULTIPLY : string ;
let MATH_ARITHMETIC_TOOLTIP_POWER : string ;
let MATH_ATAN2_HELPURL : string ;
let MATH_ATAN2_TITLE : string ;
let MATH_ATAN2_TOOLTIP : string ;
let MATH_CHANGE_HELPURL : string ;
let MATH_CHANGE_TITLE : string ;
let MATH_CHANGE_TITLE_ITEM : string ;
let MATH_CHANGE_TOOLTIP : string ;
let MATH_CONSTANT_HELPURL : string ;
let MATH_CONSTANT_TOOLTIP : string ;
let MATH_CONSTRAIN_HELPURL : string ;
let MATH_CONSTRAIN_TITLE : string ;
let MATH_CONSTRAIN_TOOLTIP : string ;
let MATH_DIVISION_SYMBOL : string ;
let MATH_HUE : string ;
let MATH_IS_DIVISIBLE_BY : string ;
let MATH_IS_EVEN : string ;
let MATH_IS_NEGATIVE : string ;
let MATH_IS_ODD : string ;
let MATH_IS_POSITIVE : string ;
let MATH_IS_PRIME : string ;
let MATH_IS_TOOLTIP : string ;
let MATH_IS_WHOLE : string ;
let MATH_MODULO_HELPURL : string ;
let MATH_MODULO_TITLE : string ;
let MATH_MODULO_TOOLTIP : string ;
let MATH_MULTIPLICATION_SYMBOL : string ;
let MATH_NUMBER_HELPURL : string ;
let MATH_NUMBER_TOOLTIP : string ;
let MATH_ONLIST_HELPURL : string ;
let MATH_ONLIST_OPERATOR_AVERAGE : string ;
let MATH_ONLIST_OPERATOR_MAX : string ;
let MATH_ONLIST_OPERATOR_MEDIAN : string ;
let MATH_ONLIST_OPERATOR_MIN : string ;
let MATH_ONLIST_OPERATOR_MODE : string ;
let MATH_ONLIST_OPERATOR_RANDOM : string ;
let MATH_ONLIST_OPERATOR_STD_DEV : string ;
let MATH_ONLIST_OPERATOR_SUM : string ;
let MATH_ONLIST_TOOLTIP_AVERAGE : string ;
let MATH_ONLIST_TOOLTIP_MAX : string ;
let MATH_ONLIST_TOOLTIP_MEDIAN : string ;
let MATH_ONLIST_TOOLTIP_MIN : string ;
let MATH_ONLIST_TOOLTIP_MODE : string ;
let MATH_ONLIST_TOOLTIP_RANDOM : string ;
let MATH_ONLIST_TOOLTIP_STD_DEV : string ;
let MATH_ONLIST_TOOLTIP_SUM : string ;
let MATH_POWER_SYMBOL : string ;
let MATH_RANDOM_FLOAT_HELPURL : string ;
let MATH_RANDOM_FLOAT_TITLE_RANDOM : string ;
let MATH_RANDOM_FLOAT_TOOLTIP : string ;
let MATH_RANDOM_INT_HELPURL : string ;
let MATH_RANDOM_INT_TITLE : string ;
let MATH_RANDOM_INT_TOOLTIP : string ;
let MATH_ROUND_HELPURL : string ;
let MATH_ROUND_OPERATOR_ROUND : string ;
let MATH_ROUND_OPERATOR_ROUNDDOWN : string ;
let MATH_ROUND_OPERATOR_ROUNDUP : string ;
let MATH_ROUND_TOOLTIP : string ;
let MATH_SINGLE_HELPURL : string ;
let MATH_SINGLE_OP_ABSOLUTE : string ;
let MATH_SINGLE_OP_ROOT : string ;
let MATH_SINGLE_TOOLTIP_ABS : string ;
let MATH_SINGLE_TOOLTIP_EXP : string ;
let MATH_SINGLE_TOOLTIP_LN : string ;
let MATH_SINGLE_TOOLTIP_LOG10 : string ;
let MATH_SINGLE_TOOLTIP_NEG : string ;
let MATH_SINGLE_TOOLTIP_POW10 : string ;
let MATH_SINGLE_TOOLTIP_ROOT : string ;
let MATH_SUBTRACTION_SYMBOL : string ;
let MATH_TRIG_ACOS : string ;
let MATH_TRIG_ASIN : string ;
let MATH_TRIG_ATAN : string ;
let MATH_TRIG_COS : string ;
let MATH_TRIG_HELPURL : string ;
let MATH_TRIG_SIN : string ;
let MATH_TRIG_TAN : string ;
let MATH_TRIG_TOOLTIP_ACOS : string ;
let MATH_TRIG_TOOLTIP_ASIN : string ;
let MATH_TRIG_TOOLTIP_ATAN : string ;
let MATH_TRIG_TOOLTIP_COS : string ;
let MATH_TRIG_TOOLTIP_SIN : string ;
let MATH_TRIG_TOOLTIP_TAN : string ;
let NEW_COLOUR_VARIABLE : string ;
let NEW_NUMBER_VARIABLE : string ;
let NEW_STRING_VARIABLE : string ;
let NEW_VARIABLE : string ;
let NEW_VARIABLE_TITLE : string ;
let NEW_VARIABLE_TYPE_TITLE : string ;
let ORDINAL_NUMBER_SUFFIX : string ;
let PROCEDURES_ALLOW_STATEMENTS : string ;
let PROCEDURES_BEFORE_PARAMS : string ;
let PROCEDURES_CALLNORETURN_HELPURL : string ;
let PROCEDURES_CALLNORETURN_TOOLTIP : string ;
let PROCEDURES_CALLRETURN_HELPURL : string ;
let PROCEDURES_CALLRETURN_TOOLTIP : string ;
let PROCEDURES_CALL_BEFORE_PARAMS : string ;
let PROCEDURES_CREATE_DO : string ;
let PROCEDURES_DEFNORETURN_COMMENT : string ;
let PROCEDURES_DEFNORETURN_DO : string ;
let PROCEDURES_DEFNORETURN_HELPURL : string ;
let PROCEDURES_DEFNORETURN_PROCEDURE : string ;
let PROCEDURES_DEFNORETURN_TITLE : string ;
let PROCEDURES_DEFNORETURN_TOOLTIP : string ;
let PROCEDURES_DEFRETURN_COMMENT : string ;
let PROCEDURES_DEFRETURN_DO : string ;
let PROCEDURES_DEFRETURN_HELPURL : string ;
let PROCEDURES_DEFRETURN_PROCEDURE : string ;
let PROCEDURES_DEFRETURN_RETURN : string ;
let PROCEDURES_DEFRETURN_TITLE : string ;
let PROCEDURES_DEFRETURN_TOOLTIP : string ;
let PROCEDURES_DEF_DUPLICATE_WARNING : string ;
let PROCEDURES_HIGHLIGHT_DEF : string ;
let PROCEDURES_HUE : string ;
let PROCEDURES_IFRETURN_HELPURL : string ;
let PROCEDURES_IFRETURN_TOOLTIP : string ;
let PROCEDURES_IFRETURN_WARNING : string ;
let PROCEDURES_MUTATORARG_TITLE : string ;
let PROCEDURES_MUTATORARG_TOOLTIP : string ;
let PROCEDURES_MUTATORCONTAINER_TITLE : string ;
let PROCEDURES_MUTATORCONTAINER_TOOLTIP : string ;
let REDO : string ;
let REMOVE_COMMENT : string ;
let RENAME_VARIABLE : string ;
let RENAME_VARIABLE_TITLE : string ;
let TEXTS_HUE : string ;
let TEXT_APPEND_HELPURL : string ;
let TEXT_APPEND_TITLE : string ;
let TEXT_APPEND_TOOLTIP : string ;
let TEXT_APPEND_VARIABLE : string ;
let TEXT_CHANGECASE_HELPURL : string ;
let TEXT_CHANGECASE_OPERATOR_LOWERCASE : string ;
let TEXT_CHANGECASE_OPERATOR_TITLECASE : string ;
let TEXT_CHANGECASE_OPERATOR_UPPERCASE : string ;
let TEXT_CHANGECASE_TOOLTIP : string ;
let TEXT_CHARAT_FIRST : string ;
let TEXT_CHARAT_FROM_END : string ;
let TEXT_CHARAT_FROM_START : string ;
let TEXT_CHARAT_HELPURL : string ;
let TEXT_CHARAT_LAST : string ;
let TEXT_CHARAT_RANDOM : string ;
let TEXT_CHARAT_TAIL : string ;
let TEXT_CHARAT_TITLE : string ;
let TEXT_CHARAT_TOOLTIP : string ;
let TEXT_COUNT_HELPURL : string ;
let TEXT_COUNT_MESSAGE0 : string ;
let TEXT_COUNT_TOOLTIP : string ;
let TEXT_CREATE_JOIN_ITEM_TITLE_ITEM : string ;
let TEXT_CREATE_JOIN_ITEM_TOOLTIP : string ;
let TEXT_CREATE_JOIN_TITLE_JOIN : string ;
let TEXT_CREATE_JOIN_TOOLTIP : string ;
let TEXT_GET_SUBSTRING_END_FROM_END : string ;
let TEXT_GET_SUBSTRING_END_FROM_START : string ;
let TEXT_GET_SUBSTRING_END_LAST : string ;
let TEXT_GET_SUBSTRING_HELPURL : string ;
let TEXT_GET_SUBSTRING_INPUT_IN_TEXT : string ;
let TEXT_GET_SUBSTRING_START_FIRST : string ;
let TEXT_GET_SUBSTRING_START_FROM_END : string ;
let TEXT_GET_SUBSTRING_START_FROM_START : string ;
let TEXT_GET_SUBSTRING_TAIL : string ;
let TEXT_GET_SUBSTRING_TOOLTIP : string ;
let TEXT_INDEXOF_HELPURL : string ;
let TEXT_INDEXOF_OPERATOR_FIRST : string ;
let TEXT_INDEXOF_OPERATOR_LAST : string ;
let TEXT_INDEXOF_TITLE : string ;
let TEXT_INDEXOF_TOOLTIP : string ;
let TEXT_ISEMPTY_HELPURL : string ;
let TEXT_ISEMPTY_TITLE : string ;
let TEXT_ISEMPTY_TOOLTIP : string ;
let TEXT_JOIN_HELPURL : string ;
let TEXT_JOIN_TITLE_CREATEWITH : string ;
let TEXT_JOIN_TOOLTIP : string ;
let TEXT_LENGTH_HELPURL : string ;
let TEXT_LENGTH_TITLE : string ;
let TEXT_LENGTH_TOOLTIP : string ;
let TEXT_PRINT_HELPURL : string ;
let TEXT_PRINT_TITLE : string ;
let TEXT_PRINT_TOOLTIP : string ;
let TEXT_PROMPT_HELPURL : string ;
let TEXT_PROMPT_TOOLTIP_NUMBER : string ;
let TEXT_PROMPT_TOOLTIP_TEXT : string ;
let TEXT_PROMPT_TYPE_NUMBER : string ;
let TEXT_PROMPT_TYPE_TEXT : string ;
let TEXT_REPLACE_HELPURL : string ;
let TEXT_REPLACE_MESSAGE0 : string ;
let TEXT_REPLACE_TOOLTIP : string ;
let TEXT_REVERSE_HELPURL : string ;
let TEXT_REVERSE_MESSAGE0 : string ;
let TEXT_REVERSE_TOOLTIP : string ;
let TEXT_TEXT_HELPURL : string ;
let TEXT_TEXT_TOOLTIP : string ;
let TEXT_TRIM_HELPURL : string ;
let TEXT_TRIM_OPERATOR_BOTH : string ;
let TEXT_TRIM_OPERATOR_LEFT : string ;
let TEXT_TRIM_OPERATOR_RIGHT : string ;
let TEXT_TRIM_TOOLTIP : string ;
let TODAY : string ;
let UNDO : string ;
let UNNAMED_KEY : string ;
let VARIABLES_DEFAULT_NAME : string ;
let VARIABLES_DYNAMIC_HUE : string ;
let VARIABLES_GET_CREATE_SET : string ;
let VARIABLES_GET_HELPURL : string ;
let VARIABLES_GET_TOOLTIP : string ;
let VARIABLES_HUE : string ;
let VARIABLES_SET : string ;
let VARIABLES_SET_CREATE_GET : string ;
let VARIABLES_SET_HELPURL : string ;
let VARIABLES_SET_TOOLTIP : string ;
let VARIABLE_ALREADY_EXISTS : string ;
let VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE : string ;
let WORKSPACE_ARIA_LABEL : string ;
let WORKSPACE_COMMENT_DEFAULT_TEXT : string ;
} | the_stack |
'use strict';
import * as vscode from 'vscode';
interface DuplicateDefinitionDiagnostic extends vscode.Diagnostic {
firstsym: vscode.DocumentSymbol
newsym: vscode.DocumentSymbol
}
export async function validateLocale(document: vscode.Uri|vscode.TextDocument): Promise<vscode.Diagnostic[]> {
if (document instanceof vscode.Uri)
{
document = await vscode.workspace.openTextDocument(document);
}
const locale = document.getText().split(/\r?\n/);
const diags: vscode.Diagnostic[] = [];
const symbols = <vscode.DocumentSymbol[]>await vscode.commands.executeCommand<(vscode.SymbolInformation|vscode.DocumentSymbol)[]>("vscode.executeDocumentSymbolProvider", document.uri);
let currentSection:string|undefined;
const sections = new Map<string|undefined,Set<String>>();
sections.set(undefined,new Set<string>());
for (let i = 0; i < locale.length; i++) {
const line = locale[i];
if (line.match(/^[ \r\t]*[#;]/))
{
// nothing to check in comments
}
else if(line.match(/^[ \r\t]*\[/))
{
const secname = line.match(/^[ \r\t]*\[([^\[]+)\][ \r\t]*$/);
if(secname)
{
// save current category, check for duplicates
currentSection = secname[1];
if (sections.has(currentSection))
{
const matching = symbols.filter(sym=>sym.name === currentSection);
const previous = matching.reduce((syma,symb)=>syma.range.start.line < symb.range.start.line?syma:symb);
const newsym = matching.find(sym=>sym.range.start.line === i);
diags.push(<DuplicateDefinitionDiagnostic>{
"message": "Duplicate Section",
"source": "factorio-locale",
"severity": vscode.DiagnosticSeverity.Error,
"range": new vscode.Range(i, line.indexOf(currentSection), i, line.indexOf(currentSection)+currentSection.length),
"relatedInformation": [new vscode.DiagnosticRelatedInformation(
new vscode.Location(document.uri,previous.range.start),
"First defined here"
)],
"code": "section.merge",
"firstsym": previous,
"newsym": newsym,
});
}
else if (sections.get(undefined)!.has(currentSection))
{
const matching = symbols.filter(sym=>sym.name === currentSection);
const previous = matching.reduce((syma,symb)=>syma.range.start.line < symb.range.start.line?syma:symb);
diags.push({
"message": "Section Name conflicts with Key in Root",
"source": "factorio-locale",
"severity": vscode.DiagnosticSeverity.Error,
"range": new vscode.Range(i, line.indexOf(currentSection), i, line.indexOf(currentSection)+currentSection.length),
"relatedInformation": [new vscode.DiagnosticRelatedInformation(
new vscode.Location(document.uri,previous.range.start),
"First defined here"
)],
});
sections.set(currentSection,new Set<String>());
}
else
{
sections.set(currentSection,new Set<String>());
}
}
else
{
diags.push({
"message": "Invalid Section Header",
"source": "factorio-locale",
"severity": vscode.DiagnosticSeverity.Error,
"range": new vscode.Range(i, 0, i, line.length)
});
}
}
else if (line.trim().length > 0)
{
const keyval = line.match(/^[ \r\t]*([^=]*)=(.*)$/);
if (keyval)
{
const key = keyval[1];
if (sections.get(currentSection)!.has(key))
{
const previous = symbols
.filter(sym=>sym.name === currentSection && sym.kind === vscode.SymbolKind.Namespace)
.map(sym=>sym.children.filter(sym=>sym.name === key))
.reduce(
(a,b)=> a.concat(b),
symbols.filter(sym=>sym.name === key && sym.kind === vscode.SymbolKind.String)
)
.reduce((syma,symb)=>syma.range.start.line < symb.range.start.line?syma:symb);
diags.push({
"message": "Duplicate Key",
"source": "factorio-locale",
"severity": vscode.DiagnosticSeverity.Error,
"range": new vscode.Range(i, line.indexOf(key), i, line.indexOf(key)+key.length),
"relatedInformation": [new vscode.DiagnosticRelatedInformation(
new vscode.Location(document.uri,previous.range.start),
"First defined here"
)],
});
}
else
{
sections.get(currentSection)!.add(key);
}
//TODO: validate tags in value (keyval[2])
}
else
{
diags.push({
"message": "Invalid Key",
"source": "factorio-locale",
"severity": vscode.DiagnosticSeverity.Error,
"range": new vscode.Range(i, 0, i, line.length)
});
}
}
}
return diags;
}
export class LocaleCodeActionProvider implements vscode.CodeActionProvider {
public provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken): vscode.CodeAction[] {
if (document.languageId === "factorio-locale") {
return context.diagnostics.filter(diag => !!diag.code).map((diag) => {
switch (diag.code) {
case "section.merge":
{
const ca = new vscode.CodeAction("Merge Sections", vscode.CodeActionKind.QuickFix.append("section").append("merge"));
const dupediag = <DuplicateDefinitionDiagnostic>diag;
ca.diagnostics = [diag];
ca.edit = new vscode.WorkspaceEdit();
const insertAt = dupediag.firstsym.range.end;
ca.edit.set(document.uri, [
vscode.TextEdit.delete(dupediag.newsym.range),
vscode.TextEdit.insert(insertAt,
document.getText(
dupediag.newsym.range.with(dupediag.newsym.selectionRange.end.translate(0,1))
))
]);
return ca;
}
default:
return new vscode.CodeAction("Dummy", vscode.CodeActionKind.Empty);
}
}).filter(diag => !(diag.kind && diag.kind.intersects(vscode.CodeActionKind.Empty)));
}
return [];
}
}
export class LocaleColorProvider implements vscode.DocumentColorProvider {
private readonly constColors = new Map([
["default", new vscode.Color(1.000, 0.630, 0.259, 1)],
["red", new vscode.Color(1.000, 0.166, 0.141, 1)],
["green", new vscode.Color(0.173, 0.824, 0.250, 1)],
["blue", new vscode.Color(0.343, 0.683, 1.000, 1)],
["orange", new vscode.Color(1.000, 0.630, 0.259, 1)],
["yellow", new vscode.Color(1.000, 0.828, 0.231, 1)],
["pink", new vscode.Color(1.000, 0.520, 0.633, 1)],
["purple", new vscode.Color(0.821, 0.440, 0.998, 1)],
["white", new vscode.Color(0.9, 0.9, 0.9, 1)],
["black", new vscode.Color(0.5, 0.5, 0.5, 1)],
["gray", new vscode.Color(0.7, 0.7, 0.7, 1)],
["brown", new vscode.Color(0.757, 0.522, 0.371, 1)],
["cyan", new vscode.Color(0.335, 0.918, 0.866, 1)],
["acid", new vscode.Color(0.708, 0.996, 0.134, 1)]
]);
private colorFromString(str: string): vscode.Color | undefined {
// color name from utility constants
if (this.constColors.has(str))
{return this.constColors.get(str);}
// #rrggbb or #rrggbbaa
if (str.startsWith("#")) {
const matches = str.match(/#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})?/);
if (matches) {
return new vscode.Color(parseInt(matches[1], 16) / 255, parseInt(matches[2], 16) / 255, parseInt(matches[3], 16) / 255, matches[4] ? parseInt(matches[4], 16) / 255 : 1);
}
}
// r,g,b as int 1-255 or float 0-1
const matches = str.match(/\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*,?\s*(\d+(?:\.\d+)?))?\s*/);
if (matches) {
let r = parseFloat(matches[1]);
let g = parseFloat(matches[2]);
let b = parseFloat(matches[3]);
let a = matches[4] ? parseFloat(matches[4]) : undefined;
if (r>1 || g>1 || b>1 || a && a>1)
{
r = r/255;
g = g/255;
b = b/255;
if (a)
{
a = a/255;
}
}
if (!a)
{
a = 1;
}
return new vscode.Color(r,g,b,a);
}
return undefined;
}
private padHex(i: number): string {
let hex = Math.floor(i).toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
return hex;
}
private roundTo(f:number,places:number):number {
return Math.round(f*Math.pow(10,places))/Math.pow(10,places);
}
private colorToStrings(color: vscode.Color): string[] {
const names:string[] = [];
for (const [constname,constcolor] of this.constColors) {
if (Math.abs(constcolor.red-color.red) < 0.004 &&
Math.abs(constcolor.green-color.green) < 0.004 &&
Math.abs(constcolor.blue-color.blue) < 0.004 &&
Math.abs(constcolor.alpha-color.alpha) < 0.004)
{
names.push(constname);
break;
}
}
if (color.alpha > 0.996)
{
names.push(`#${this.padHex(color.red * 255)}${this.padHex(color.green * 255)}${this.padHex(color.blue * 255)}`);
names.push(`${Math.floor(color.red * 255)}, ${Math.floor(color.green * 255)}, ${Math.floor(color.blue * 255)}`);
names.push(`${this.roundTo(color.red,3)}, ${this.roundTo(color.green,3)}, ${this.roundTo(color.blue,3)}`);
}
else
{
names.push(`#${this.padHex(color.red * 255)}${this.padHex(color.green * 255)}${this.padHex(color.blue * 255)}${this.padHex(color.alpha * 255)}`);
names.push(`${Math.floor(color.red * 255)}, ${Math.floor(color.green * 255)}, ${Math.floor(color.blue * 255)}, ${Math.floor(color.alpha * 255)}`);
names.push(`${this.roundTo(color.red,3)}, ${this.roundTo(color.green,3)}, ${this.roundTo(color.blue,3)}, ${this.roundTo(color.alpha,3)}`);
}
return names;
}
public provideDocumentColors(document: vscode.TextDocument, token: vscode.CancellationToken): vscode.ColorInformation[] {
const colors: vscode.ColorInformation[] = [];
for (let i = 0; i < document.lineCount; i++) {
const element = document.lineAt(i);
const re = /\[color=([^\]]+)\]/g;
let matches = re.exec(element.text);
while (matches) {
//if (matches[1])
{
let color = this.colorFromString(matches[1]);
if (color) {
colors.push(new vscode.ColorInformation(new vscode.Range(i, matches.index + 7, i, matches.index + 7 + matches[1].length), color));
}
}
matches = re.exec(element.text);
}
}
return colors;
}
public provideColorPresentations(color: vscode.Color, context: {
document: vscode.TextDocument
range: vscode.Range
}, token: vscode.CancellationToken): vscode.ColorPresentation[] {
return this.colorToStrings(color).map(colorstring=>{
const p = new vscode.ColorPresentation(colorstring);
p.textEdit = new vscode.TextEdit(context.range, colorstring);
return p;
});
}
}
export class LocaleDocumentSymbolProvider implements vscode.DocumentSymbolProvider {
public provideDocumentSymbols(document: vscode.TextDocument, token: vscode.CancellationToken): vscode.DocumentSymbol[] {
const symbols: vscode.DocumentSymbol[] = [];
let category: vscode.DocumentSymbol | undefined;
for (let i = 0; i < document.lineCount; i++) {
const element = document.lineAt(i);
if (element.text.match(/^\[([^\]])+\]$/)) {
category = new vscode.DocumentSymbol(element.text.substr(1, element.text.length - 2), "", vscode.SymbolKind.Namespace, element.range, new vscode.Range(element.range.start.translate(0, 1), element.range.end.translate(0, -1)));
symbols.push(category);
}
else if(element.text.match(/^[#;]/))
{
// nothing to do for comments...
}
else {
const matches = element.text.match(/^([^=]+)=(.+)$/);
if (matches) {
const s = new vscode.DocumentSymbol(matches[1], matches[2], vscode.SymbolKind.String, element.range, new vscode.Range(element.range.start, element.range.start.translate(0, matches[2].length)));
if (category) {
category.children.push(s);
category.range = category.range.union(element.range);
} else {
symbols.push(s);
}
}
}
}
return symbols;
}
} | the_stack |
import "jest-environment-puppeteer";
import Flash from "../helpers/flash";
import { IFlash, IMarket, Outcome } from "../types/types";
import { UnlockedAccounts } from "../constants/accounts";
import { toDisputing } from "../helpers/navigation-helper";
import {
createYesNoMarket,
createCategoricalMarket,
createScalarMarket
} from "../helpers/create-markets";
import { waitNextBlock } from "../helpers/wait-new-block";
require("../helpers/beforeAll");
// TODO: Replace uses of `url` with calls to functions in navigation-helper
const url = `${process.env.AUGUR_URL}`;
const SMALL_TIMEOUT = 80000;
const BIG_TIMEOUT = 160000;
jest.setTimeout(200000);
let flash: IFlash = new Flash();
const disputeOnAllOutcomes = async (
marketId: string,
outcomes: Outcome[],
isScalar: boolean = false
) => {
const amount = "0.3000";
for (let i = 0; i < outcomes.length; i++) {
if (!outcomes[i].tentativeWinning) {
await disputeOnOutcome(marketId, outcomes[i], amount);
await verifyDisputedOutcome(marketId, outcomes[i].id, amount);
}
}
if (isScalar) {
const values: string[] = ["-2", ".2", "-.2", "10", "-10"];
for (const value of values) {
await disputeOnScalarOutcome(marketId, value, amount);
}
}
return;
};
const disputeOnOutcome = async (
marketId: string,
outcome: Outcome,
amount: string
) => {
await expect(page).toClick("[data-testid='link-" + marketId + "']", {
text: "dispute",
timeout: BIG_TIMEOUT
});
await expect(page).toClick("[data-testid='button-" + outcome.id + "']", {
timeout: BIG_TIMEOUT
});
await expect(page).toFill("#sr__input--stake", amount, {
timeout: SMALL_TIMEOUT
});
await expect(page).toClick("button", {
text: "Review",
timeout: SMALL_TIMEOUT
});
await expect(page).toClick("button", {
text: "Submit",
timeout: BIG_TIMEOUT
});
return;
};
const disputeOnScalarOutcome = async (
marketId: string,
outcomeValue: string,
amount: string
) => {
await expect(page).toClick("[data-testid='link-" + marketId + "']", {
text: "dispute",
timeout: BIG_TIMEOUT
});
await expect(page).toClick("[data-testid='scalar-dispute-button']", {
timeout: BIG_TIMEOUT
});
await expect(page).toFill("#sr__input--outcome-scalar", outcomeValue, {
timeout: SMALL_TIMEOUT
});
await expect(page).toFill("#sr__input--stake", amount, {
timeout: SMALL_TIMEOUT
});
await expect(page).toClick("button", {
text: "Review",
timeout: SMALL_TIMEOUT
});
await expect(page).toClick("button", {
text: "Submit",
timeout: BIG_TIMEOUT
});
return;
};
const verifyDisputedOutcome = async (
marketId: string,
outcomeId: string,
amount: string
) => {
// TODO: need to be aware of "+ more" button
await expect(page).toMatchElement(
"[data-testid='disputeBond-" + marketId + "-" + outcomeId + "']",
{
text: amount,
timeout: BIG_TIMEOUT
}
);
return;
};
describe("Disputing", () => {
let market: IMarket;
beforeAll(async () => {
await toDisputing();
market = await createYesNoMarket();
await waitNextBlock(10);
await flash.initialReport(market.id, "0", false, false);
await flash.pushWeeks(1); // push into dispute window
});
afterAll(async () => {
flash.dispose();
});
describe("Basics", () => {
it("should be shown the 'No-REP' message if your account has no REP", async () => {
await page.evaluate(
account => window.integrationHelpers.updateAccountAddress(account),
UnlockedAccounts.SECONDARY_ACCOUNT
);
await toDisputing();
await expect(page).toMatch(
"You have 0 REP available. Add funds to dispute markets or purchase participation tokens.",
{ timeout: SMALL_TIMEOUT }
);
});
it("should not be able to submit a dispute without REP", async () => {
// check that button is disabled
await expect(page).toMatchElement(
"[data-testid='link-" + market.id + "']",
{ text: "dispute", timeout: SMALL_TIMEOUT }
);
});
});
describe("Disputing Mechanisms", () => {
let yesNoMarket: IMarket;
let categoricalMarket: IMarket;
let scalarMarket: IMarket;
let outcomes: { [key: string]: Outcome[] };
beforeAll(async () => {
await page.evaluate(() => window.integrationHelpers.getRep());
await waitNextBlock(2);
});
describe("Yes/No Market", () => {
beforeAll(async () => {
yesNoMarket = await createYesNoMarket();
await waitNextBlock(15);
await flash.initialReport(yesNoMarket.id, "0", false, false);
await flash.pushWeeks(1);
await waitNextBlock(15);
outcomes = await page.evaluate(() =>
window.integrationHelpers.getMarketDisputeOutcomes()
);
});
it("should be able to dispute on all outcomes", async () => {
await disputeOnAllOutcomes(
yesNoMarket.id,
outcomes[yesNoMarket.id],
false
);
});
});
describe("Categorical Market", () => {
beforeAll(async () => {
categoricalMarket = await createCategoricalMarket(4);
await waitNextBlock(15);
await flash.initialReport(categoricalMarket.id, "0", false, false);
await flash.pushWeeks(1);
await waitNextBlock(15);
outcomes = await page.evaluate(() =>
window.integrationHelpers.getMarketDisputeOutcomes()
);
});
it("should be able to dispute on all outcomes", async () => {
await disputeOnAllOutcomes(
categoricalMarket.id,
outcomes[categoricalMarket.id],
false
);
});
});
describe("Scalar Market", () => {
beforeAll(async () => {
scalarMarket = await createScalarMarket();
await waitNextBlock(15);
await flash.initialReport(scalarMarket.id, "0", false, false);
await flash.pushWeeks(1);
await waitNextBlock(15);
outcomes = await page.evaluate(() =>
window.integrationHelpers.getMarketDisputeOutcomes()
);
});
it("should be able to dispute on all outcomes", async () => {
await disputeOnAllOutcomes(
scalarMarket.id,
outcomes[scalarMarket.id],
true
);
});
});
});
describe("Dispute Window", () => {
let daysLeft: number;
let reportingWindowStats;
it("should have days remaining be correct", async () => {
await toDisputing();
reportingWindowStats = await page.evaluate(() =>
window.integrationHelpers.getReportingWindowStats()
);
let currentTimestamp = await page.evaluate(() =>
window.integrationHelpers.getCurrentTimestamp()
);
currentTimestamp = currentTimestamp / 1000;
daysLeft = await page.evaluate(
(endTime, startTime) =>
window.integrationHelpers.getDaysRemaining(endTime, startTime),
reportingWindowStats.endTime,
currentTimestamp
);
let denomination = daysLeft === 1 ? " day" : " days";
if (daysLeft === 0) {
const hoursLeft = await page.evaluate(
(endTime, startTime) =>
window.integrationHelpers.getHoursRemaining(endTime, startTime),
reportingWindowStats.endTime,
currentTimestamp
);
denomination = hoursLeft === 1 ? " hour" : " hours";
if (hoursLeft === 0) {
const minutesLeft = await page.evaluate(
(endTime, startTime) =>
window.integrationHelpers.getMinutesRemaining(endTime, startTime),
reportingWindowStats.endTime,
currentTimestamp
);
denomination = minutesLeft === 1 ? " minute" : " minutes";
// check that days left is expected number
await expect(page).toMatchElement("[data-testid='daysLeft']", {
text: minutesLeft + denomination + " left",
timeout: SMALL_TIMEOUT
});
} else {
// check that days left is expected number
await expect(page).toMatchElement("[data-testid='daysLeft']", {
text: hoursLeft + denomination + " left",
timeout: SMALL_TIMEOUT
});
}
} else {
// check that days left is expected number
await expect(page).toMatchElement("[data-testid='daysLeft']", {
text: daysLeft + denomination + " left",
timeout: SMALL_TIMEOUT
});
}
});
it("should have days remaining increment properly", async () => {
// push time
await flash.pushDays(1);
let daysLeftIncr = daysLeft === 0 ? 6 : daysLeft - 1;
let denomination = daysLeftIncr === 1 ? " day" : " days";
if (daysLeftIncr === 0) {
let currentTimestamp = await page.evaluate(() =>
window.integrationHelpers.getCurrentTimestamp()
);
currentTimestamp = currentTimestamp / 1000;
daysLeftIncr = await page.evaluate(
(endTime, startTime) =>
window.integrationHelpers.getHoursRemaining(endTime, startTime),
reportingWindowStats.endTime,
currentTimestamp
);
denomination = daysLeftIncr === 1 ? " hour" : " hours";
if (daysLeftIncr === 0) {
daysLeftIncr = await page.evaluate(
(endTime, startTime) =>
window.integrationHelpers.getMinutesRemaining(endTime, startTime),
reportingWindowStats.endTime,
currentTimestamp
);
denomination = daysLeftIncr === 1 ? " minute" : " minutes";
}
} else if (daysLeftIncr === 6) {
daysLeftIncr = 0;
denomination = " minutes";
}
// check that days left is previous calculation - time pushed
await expect(page).toMatchElement("[data-testid='daysLeft']", {
text: daysLeftIncr + denomination + " left",
timeout: SMALL_TIMEOUT
});
});
it("should have correct end date", async () => {
// get new stats because endTime could be different because of time push
reportingWindowStats = await page.evaluate(() =>
window.integrationHelpers.getReportingWindowStats()
);
const formattedDate = await page.evaluate(
date => window.integrationHelpers.convertUnixToFormattedDate(date),
reportingWindowStats.endTime
);
// check that dispute window ends is displayed correctly
await expect(page).toMatchElement("[data-testid='endTime']", {
text: formattedDate.clockTimeLocal,
timeout: BIG_TIMEOUT
});
});
it("should update correctly when time is pushed and a new dispute window starts", async () => {
// push into new dispute window
await flash.pushDays(7);
// get new stats
reportingWindowStats = await page.evaluate(() =>
window.integrationHelpers.getReportingWindowStats()
);
const formattedDate = await page.evaluate(
date => window.integrationHelpers.convertUnixToFormattedDate(date),
reportingWindowStats.endTime
);
// check that dispute window ends is displayed correctly
await expect(page).toMatchElement("[data-testid='endTime']", {
text: formattedDate.clockTimeLocal,
timeout: BIG_TIMEOUT
});
});
it("should create a new dispute window properly even when no markets were reported on or disputed in the previous dispute window", async () => {});
});
describe("Market Card", () => {
let market: IMarket;
describe("Dispute Bonds", () => {
it("should have all of the dispute bonds on a market be equal to one another in the first dispute round", async () => {
// create new yes/no market
market = await createYesNoMarket();
await waitNextBlock(10);
// put yes/no market into disputing
await flash.initialReport(market.id, "0", false, false);
await waitNextBlock(2);
// check that dispute bonds for outcomes yes and market is invalid are expected
// TODO: make .6994 not hard coded, and make this reusable for different market types -- use outcomes selector
await expect(page).toMatchElement(
"[data-testid='disputeBondTarget-" + market.id + "-1']",
{
text: "0.6994 REP",
timeout: BIG_TIMEOUT
}
);
await expect(page).toMatchElement(
"[data-testid='disputeBondTarget-" + market.id + "-0.5']",
{
text: "0.6994 REP",
timeout: BIG_TIMEOUT
}
);
});
it("should have dispute bonds be equal to twice the amount placed by the initial reporter in the first dispute round", async () => {
// TODO:
// With markets reported on by the Designated Reporter, this is twice the stake placed by the Designated Reporter.
// With markets reported on in Open Reporting, this is twice the no-show bond.
// Test both.
});
});
describe("Round Numbers", () => {
it("should have round number be 1 while a market is waiting for its first Dispute window and while in its first round number", async () => {
await expect(page).toMatchElement(
"[data-testid='roundNumber-" + market.id + "']",
{
text: "1",
timeout: SMALL_TIMEOUT
}
);
});
it("should have round number increase if a dispute is successful and a market is waiting for or is in its next dispute window", async () => {
await flash.disputeContribute(market.id, "1", false, false);
await expect(page).toMatchElement(
"[data-testid='roundNumber-" + market.id + "']",
{
text: "2",
timeout: SMALL_TIMEOUT
}
);
});
});
describe("Listed Outcomes", () => {
describe("Yes/No Market", () => {
let yesNoMarket: IMarket;
it("should have the market's reported-on outcome display correctly on the market card", async () => {
yesNoMarket = await createYesNoMarket();
await waitNextBlock(10);
await flash.initialReport(yesNoMarket.id, "0", false, false);
await flash.pushWeeks(1);
await waitNextBlock(2);
// expect not to have a dispute bond for winning outcome
await expect(page).not.toMatchElement(
"[data-testid='disputeBondTarget-" + yesNoMarket.id + "-0']"
);
});
it("should have 'Yes', 'No', and 'Market is Invalid' outcomes be present", async () => {
await expect(page).toMatch("Yes");
await expect(page).toMatch("Invalid");
await expect(page).toMatch("No");
});
});
describe("Categorical Market", () => {
it("should have the market's reported-on outcome display correctly on the market card", async () => {
const categoricalMarket = await createCategoricalMarket(4);
await waitNextBlock(10);
await flash.initialReport(categoricalMarket.id, "0", false, false);
await flash.pushWeeks(1);
await waitNextBlock(2);
// expect not to have a dispute bond for winning outcome
await expect(page).not.toMatchElement(
"[data-testid='disputeBondTarget-" + categoricalMarket.id + "-0']"
);
});
});
describe("Scalar Market", () => {
it("should have the market's reported-on outcome display correctly on the market card", async () => {
const scalarMarket = await createScalarMarket();
await waitNextBlock(10);
await flash.initialReport(scalarMarket.id, "1", false, false);
await waitNextBlock(2);
await flash.pushWeeks(1);
await expect(page).toMatch("Invalid", { timeout: SMALL_TIMEOUT });
// expect not to have a dispute bond for winning outcome
await expect(page).toMatchElement(
"[data-testid='winning-" + scalarMarket.id + "-1']"
);
});
it("should have no other outcomes listed when the tentative winning outcome is 'Market is Invalid'", async () => {
const scalarMarket = await createScalarMarket();
await waitNextBlock(10);
await flash.initialReport(scalarMarket.id, "0", true, false);
await waitNextBlock(2);
await flash.pushWeeks(1);
await expect(page).toMatch("Invalid", { timeout: SMALL_TIMEOUT });
// expect not to have a dispute bond for winning outcome
await expect(page).not.toMatchElement(
"[data-testid='disputeBondTarget-" + scalarMarket.id + "-0']"
);
});
});
});
});
}); | the_stack |
declare namespace adone {
namespace I {
namespace datetime {
type RelativeTimeKey = "s" | "m" | "mm" | "h" | "hh" | "d" | "dd" | "M" | "MM" | "y" | "yy";
type CalendarKey = "sameDay" | "nextDay" | "lastDay" | "nextWeek" | "lastWeek" | "sameElse";
type LongDateFormatKey = "LTS" | "LT" | "L" | "LL" | "LLL" | "LLLL" | "lts" | "lt" | "l" | "ll" | "lll" | "llll";
interface Locale {
calendar(key?: CalendarKey, m?: Datetime, now?: Datetime): string;
longDateFormat(key: LongDateFormatKey): string;
invalidDate(): string;
ordinal(n: number): string;
preparse(inp: string): string;
postformat(inp: string): string;
relativeTime(n: number, withoutSuffix: boolean, key: RelativeTimeKey, isFuture: boolean): string;
pastFuture(diff: number, absRelTime: string): string;
set(config: object): void;
months(): string[];
months(m: Datetime, format?: string): string;
monthsShort(): string[];
monthsShort(m: Datetime, format?: string): string;
monthsParse(monthName: string, format: string, strict: boolean): number;
monthsRegex(strict: boolean): RegExp;
monthsShortRegex(strict: boolean): RegExp;
week(m: Datetime): number;
firstDayOfYear(): number;
firstDayOfWeek(): number;
weekdays(): string[];
weekdays(m: Datetime, format?: string): string;
weekdaysMin(): string[];
weekdaysMin(m: Datetime): string;
weekdaysShort(): string[];
weekdaysShort(m: Datetime): string;
weekdaysParse(weekdayName: string, format: string, strict: boolean): number;
weekdaysRegex(strict: boolean): RegExp;
weekdaysShortRegex(strict: boolean): RegExp;
weekdaysMinRegex(strict: boolean): RegExp;
isPM(input: string): boolean;
meridiem(hour: number, minute: number, isLower: boolean): string;
}
interface StandaloneFormatSpec {
format: string[];
standalone: string[];
isFormat?: RegExp;
}
interface WeekSpec {
dow: number;
doy: number;
}
type CalendarSpecVal = string | ((m?: DatetimeInput, now?: Datetime) => string);
interface CalendarSpec {
sameDay?: CalendarSpecVal;
nextDay?: CalendarSpecVal;
lastDay?: CalendarSpecVal;
nextWeek?: CalendarSpecVal;
lastWeek?: CalendarSpecVal;
sameElse?: CalendarSpecVal;
// any additional properties might be used with datetime.calendarFormat
[x: string]: CalendarSpecVal | undefined;
}
type RelativeTimeSpecVal = (
string |
((n: number, withoutSuffix: boolean, key: RelativeTimeKey, isFuture: boolean) => string)
);
type RelativeTimeFuturePastVal = string | ((relTime: string) => string);
interface RelativeTimeSpec {
future: RelativeTimeFuturePastVal;
past: RelativeTimeFuturePastVal;
s: RelativeTimeSpecVal;
m: RelativeTimeSpecVal;
mm: RelativeTimeSpecVal;
h: RelativeTimeSpecVal;
hh: RelativeTimeSpecVal;
d: RelativeTimeSpecVal;
dd: RelativeTimeSpecVal;
M: RelativeTimeSpecVal;
MM: RelativeTimeSpecVal;
y: RelativeTimeSpecVal;
yy: RelativeTimeSpecVal;
}
interface LongDateFormatSpec {
LTS: string;
LT: string;
L: string;
LL: string;
LLL: string;
LLLL: string;
// lets forget for a sec that any upper/lower permutation will also work
lts?: string;
lt?: string;
l?: string;
ll?: string;
lll?: string;
llll?: string;
}
type MonthWeekdayFn = (datetimeToFormat: Datetime, format?: string) => string;
type WeekdaySimpleFn = (datetimeToFormat: Datetime) => string;
interface LocaleSpecification {
months?: string[] | StandaloneFormatSpec | MonthWeekdayFn;
monthsShort?: string[] | StandaloneFormatSpec | MonthWeekdayFn;
weekdays?: string[] | StandaloneFormatSpec | MonthWeekdayFn;
weekdaysShort?: string[] | StandaloneFormatSpec | WeekdaySimpleFn;
weekdaysMin?: string[] | StandaloneFormatSpec | WeekdaySimpleFn;
meridiemParse?: RegExp;
meridiem?(hour: number, minute: number, isLower: boolean): string;
isPM?(input: string): boolean;
longDateFormat?: LongDateFormatSpec;
calendar?: CalendarSpec;
relativeTime?: RelativeTimeSpec;
invalidDate?: string;
ordinal?(n: number): string;
ordinalParse?: RegExp;
week?: WeekSpec;
// Allow anything: in general any property that is passed as locale spec is
// put in the locale object so it can be used by locale functions
[x: string]: any;
}
interface DatetimeObjectOutput {
years: number;
/* One digit */
months: number;
/* Day of the month */
date: number;
hours: number;
minutes: number;
seconds: number;
milliseconds: number;
}
interface Duration {
/**
* Returns a human readable representation
*/
humanize(withSuffix?: boolean): string;
abs(): Duration;
/**
* Returns the length of the duration in the given units
*/
as(units: unitOfTime.Base): number;
/**
* Returns the value of the given unit
*/
get(units: unitOfTime.Base): number;
/**
* Returns the number of milliseconds in the duration
*/
milliseconds(): number;
/**
* Returns the length of the duration in milliseconds
*/
asMilliseconds(): number;
/**
* Returns the number of seconds in the duration
*/
seconds(): number;
/**
* Returns the length of the duration in seconds
*/
asSeconds(): number;
/**
* Returns the number of minutes in the duration
*/
minutes(): number;
/**
* Returns the length of the duration in minutes
*/
asMinutes(): number;
/**
* Returns the number of hours in the duration
*/
hours(): number;
/**
* Returns the length of the duration in hours
*/
asHours(): number;
/**
* Returns the number of days in the duration
*/
days(): number;
/**
* Returns the length of the duration in days
*/
asDays(): number;
/**
* Returns the number of weeks in the duration
*/
weeks(): number;
/**
* Returns the length of the duration in weeks
*/
asWeeks(): number;
/**
* Returns the number of months in the duration
*/
months(): number;
/**
* Returns the length of the duration in months
*/
asMonths(): number;
/**
* Returns the number of years in the duration
*/
years(): number;
/**
* Returns the length of the duration in years
*/
asYears(): number;
/**
* Mutates the original duration by adding time
*/
add(inp?: DurationInputArg1, unit?: DurationInputArg2): Duration;
/**
* Mutates the original duration by subtracting time.
*/
subtract(inp?: DurationInputArg1, unit?: DurationInputArg2): Duration;
/**
* Returns the using locale
*/
locale(): string;
/**
* Sets a new locale
*/
locale(locale: LocaleSpecifier): Duration;
/**
* Returns the data of the using locale
*/
localeData(): Locale;
/**
* Returns duration in string as specified by ISO 8601 standard.
*/
toISOString(): string;
/**
* When serializing a duration object to JSON, it will be represented as an ISO8601 string.
*/
toJSON(): string;
}
interface DatetimeParsingFlags {
empty: boolean;
unusedTokens: string[];
unusedInput: string[];
overflow: number;
charsLeftOver: number;
nullInput: boolean;
invalidMonth: string | null;
invalidFormat: boolean;
userInvalidated: boolean;
iso: boolean;
parsedDateParts: any[];
meridiem: string | null;
}
interface DatetimeParsingFlagsOpt {
empty?: boolean;
unusedTokens?: string[];
unusedInput?: string[];
overflow?: number;
charsLeftOver?: number;
nullInput?: boolean;
invalidMonth?: string;
invalidFormat?: boolean;
userInvalidated?: boolean;
iso?: boolean;
parsedDateParts?: any[];
meridiem?: string;
}
type DatetimeFormatSpecification = string | string[];
namespace unitOfTime {
type Base = (
"year" | "years" | "y" |
"month" | "months" | "M" |
"week" | "weeks" | "w" |
"day" | "days" | "d" |
"hour" | "hours" | "h" |
"minute" | "minutes" | "m" |
"second" | "seconds" | "s" |
"millisecond" | "milliseconds" | "ms"
);
type _quarter = "quarter" | "quarters" | "Q";
type _isoWeek = "isoWeek" | "isoWeeks" | "W";
type _date = "date" | "dates" | "D";
type DurationConstructor = Base | _quarter;
type DurationAs = Base;
type StartOf = Base | _quarter | _isoWeek | _date;
type Diff = Base | _quarter;
type DatetimeConstructor = Base | _date;
type All = Base | _quarter | _isoWeek | _date |
"weekYear" | "weekYears" | "gg" |
"isoWeekYear" | "isoWeekYears" | "GG" |
"dayOfYear" | "dayOfYears" | "DDD" |
"weekday" | "weekdays" | "e" |
"isoWeekday" | "isoWeekdays" | "E";
}
interface DatetimeInputObject {
/**
* Year
*/
years?: number;
/**
* Year
*/
year?: number;
/**
* Year
*/
y?: number;
/**
* Month, 0..11
*/
months?: number;
/**
* Month, 0..11
*/
month?: number;
/**
* Month, 0..11
*/
M?: number;
/**
* Day of week, 0..6
*/
days?: number;
/**
* Day of week, 0..6
*/
day?: number;
/**
* Day of week, 0..6
*/
d?: number;
/**
* Day of month, 1..31
*/
dates?: number;
/**
* Day of month, 1..31
*/
date?: number;
/**
* Day of month, 1..31
*/
D?: number;
/**
* Hour, 0..23
*/
hours?: number;
/**
* Hour, 0..23
*/
hour?: number;
/**
* Hour, 0..23
*/
h?: number;
/**
* Minute, 0..59
*/
minutes?: number;
/**
* Minute, 0..59
*/
minute?: number;
/**
* Minute, 0..59
*/
m?: number;
/**
* Second, 0..59
*/
seconds?: number;
/**
* Second, 0..59
*/
second?: number;
/**
* Second, 0..59
*/
s?: number;
/**
* Millisecond, 0..999
*/
milliseconds?: number;
/**
* Millisecond, 0..999
*/
millisecond?: number;
/**
* Millisecond, 0..999
*/
ms?: number;
}
interface DurationInputObject extends DatetimeInputObject {
/**
* Quarter, 1..4
*/
quarters?: number;
/**
* Quarter, 1..4
*/
quarter?: number;
/**
* Quarter, 1..4
*/
Q?: number;
/**
* Week of the year, 1..53
*/
weeks?: number;
/**
* Week of the year, 1..53
*/
week?: number;
/**
* Week of the year, 1..53
*/
w?: number;
}
interface DatetimeSetObject extends DatetimeInputObject {
/**
* Week-year according to the locale
*/
weekYears?: number;
/**
* Week-year according to the locale
*/
weekYear?: number;
/**
* Week-year according to the locale
*/
gg?: number;
/**
* ISO week-year
*/
isoWeekYears?: number;
/**
* ISO week-year
*/
isoWeekYear?: number;
/**
* ISO week-year
*/
GG?: number;
/**
* Quarter, 1..4
*/
quarters?: number;
/**
* Quarter, 1..4
*/
quarter?: number;
/**
* Quarter, 1..4
*/
Q?: number;
/**
* Week of the year, 1..53
*/
weeks?: number;
/**
* Week of the year, 1..53
*/
week?: number;
/**
* Week of the year, 1..53
*/
w?: number;
/**
* ISO week of the year, 1..53
*/
isoWeeks?: number;
/**
* ISO week of the year, 1..53
*/
isoWeek?: number;
/**
* ISO week of the year, 1..53
*/
W?: number;
/**
* Day of the year, 1..366
*/
dayOfYears?: number;
/**
* Day of the year, 1..366
*/
dayOfYear?: number;
/**
* Day of the year, 1..366
*/
DDD?: number;
/**
* Day of Week according to the locale
*/
weekdays?: number;
/**
* Day of Week according to the locale
*/
weekday?: number;
/**
* Day of Week according to the locale
*/
e?: number;
/**
* ISO Day of Week
*/
isoWeekdays?: number;
/**
* ISO Day of Week
*/
isoWeekday?: number;
/**
* ISO Day of Week
*/
E?: number;
}
interface FromTo {
from: DatetimeInput;
to: DatetimeInput;
}
type DatetimeInput = string | number | Array<number | string> | DatetimeInputObject | Datetime | Date | null | undefined;
type DurationInputArg1 = Duration | number | string | FromTo | DurationInputObject | null | undefined;
type DurationInputArg2 = unitOfTime.DurationConstructor;
type LocaleSpecifier = string | Datetime | Duration | string[] | boolean;
interface DatetimeCreationData {
input: DatetimeInput;
format?: DatetimeFormatSpecification;
locale: Locale;
isUTC: boolean;
strict?: boolean;
}
interface MSDOSFormat {
/**
* an unsigned 16-bit integer represents MS-DOS date
*/
date: number;
/**
* an unsigned 16-bit integer represents MS-DOS time
*/
time: number;
}
interface Datetime extends Object {
/**
* Formats the datetime using the given format.
* It takes a string of tokens and replaces them with their corresponding values
*/
format(format?: string): string;
/**
* Mutates the original datetime by setting it to the start of a unit of time
*/
startOf(unitOfTime: unitOfTime.StartOf): Datetime;
/**
* Mutates the original moment by setting it to the end of a unit of time
*/
endOf(unitOfTime: unitOfTime.StartOf): Datetime;
/**
* Mutates the original moment by adding time, by default milliseconds
*/
add(amount?: DurationInputArg1, unit?: DurationInputArg2): Datetime;
/**
* Mutates the original moment by subtracting time, by default milliseconds
*/
subtract(amount?: DurationInputArg1, unit?: DurationInputArg2): Datetime;
/**
* Calendar time displays time relative to a given referenceTime (defaults to now)
*/
calendar(time?: DatetimeInput, formats?: CalendarSpec): string;
/**
* Clones the datetime object
*/
clone(): Datetime;
/**
* Returns unix timestamp in milliseconds
*/
valueOf(): number;
/**
* Sets a flag on the original datetime to use local time to display a datetime instead of the original datetime's time
*/
local(keepLocalTime?: boolean): Datetime;
/**
* Returns true if local flag is set
*/
isLocal(): boolean;
/**
* Sets a flag on the original datetime to use UTC to display a datetime instead of the original datetime's time
*/
utc(keepLocalTime?: boolean): Datetime;
/**
* Return true if utc flag is set
*/
isUTC(): boolean;
/**
* Return true if utc flag is set
*/
isUtc(): boolean;
parseZone(): Datetime;
/**
* Return true if the datetime object is valid
*/
isValid(): boolean;
/**
* Returns the index of the first overflowed unit
*
* 0 - years
* 1 - months
* 2 - days
* 3 - hours
* 4 - minutes
* 5 - seconds
* 6 - milliseconds
*/
invalidAt(): number;
hasAlignedHourOffset(other?: DatetimeInput): boolean;
/**
* Returns all the constructor inputs of this datatime object
*/
creationData(): DatetimeCreationData;
parsingFlags(): DatetimeParsingFlags;
/**
* Gets the year
*/
year(): number;
/**
* Sets the year
*/
year(y: number): Datetime;
/**
* Gets the year
*
* @deprecated use year(y)
*/
years(y: number): Datetime;
/**
* Sets the year
* @deprecated use year()
*/
years(): number;
/**
* Gets the quarter, 1..4
*/
quarter(): number;
/**
* Sets the quarter, 1..4
*/
quarter(q: number): Datetime;
/**
* Gets the quarter, 1..4
*/
quarters(): number;
/**
* Sets the quarter, 1..4
*/
quarters(q: number): Datetime;
/**
* Gets the month, 0..11
*/
month(): number;
/**
* Sets the month, 0..11.
* If the range is exceeded, it will bubble up to the year
*/
month(M: number | string): Datetime;
/**
* Sets the month, 0..11.
* If the range is exceeded, it will bubble up to the year
*
* @deprecated use month(M)
*/
months(M: number | string): Datetime;
/**
* Gets the month, 0..11
*
* @deprecated use month()
*/
months(): number;
/**
* Gets the day of week, 0(Sunday)..6(Saturday)
*/
day(): number;
/**
* Sets the day of week, 0(Sunday)..6(Saturday).
* If the range is exceeded, it will bubble up to other weeks
*/
day(d: number | string): Datetime;
/**
* Sets the day of week, 0(Sunday)..6(Saturday).
* If the range is exceeded, it will bubble up to other weeks
*/
days(d: number | string): Datetime;
/**
* Gets the day of week, 0(Sunday)..6(Saturday)
*/
days(): number;
/**
* Gets the day of the month, 1..31
*/
date(): number;
/**
* Sets the day of the month, 1..31.
* If the range is exceeded, it will bubble up to the months.
*/
date(d: number): Datetime;
/**
* Gets the day of the month, 1..31
*
* @deprecated use date(d)
*/
dates(d: number): Datetime;
/**
* Sets the day of the month, 1..31.
* If the range is exceeded, it will bubble up to the months.
*
* @deprecated use date()
*/
dates(): number;
/**
* Gets the hour, 0..23
*/
hour(): number;
/**
* Sets the hour, 0..23.
* If the range is exceeded, it will bubble up to the day.
*/
hour(h: number): Datetime;
/**
* Gets the hour, 0..23
*/
hours(): number;
/**
* Sets the hour, 0..23.
* If the range is exceeded, it will bubble up to the day.
*/
hours(h: number): Datetime;
/**
* Gets the minute, 0..59
*/
minute(): number;
/**
* Sets the minute, 0..59.
* If the range is exceeded, it will bubble up to the hour.
*/
minute(m: number): Datetime;
/**
* Gets the minute, 0..59
*/
minutes(): number;
/**
* Sets the minute, 0..59.
* If the range is exceeded, it will bubble up to the hour.
*/
minutes(m: number): Datetime;
/**
* Gets the second, 0..59
*/
second(): number;
/**
* Sets the second, 0..59.
* If the range is exceeded, it will bubble up to the minutes.
*/
second(s: number): Datetime;
/**
* Gets the second, 0..59
*/
seconds(): number;
/**
* Sets the second, 0..59.
* If the range is exceeded, it will bubble up to the minutes.
*/
seconds(s: number): Datetime;
/**
* Gets the millisecond, 0..999
*/
millisecond(): number;
/**
* Sets the millisecond, 0..999.
* If the range is exceeded, it will bubble up to the seconds.
*/
millisecond(ms: number): Datetime;
/**
* Gets the millisecond, 0..999
*/
milliseconds(): number;
/**
* Sets the millisecond, 0..999.
* If the range is exceeded, it will bubble up to the seconds.
*/
milliseconds(ms: number): Datetime;
/**
* Gets the day of the week according to the locale, 0..6.
* If the locale assigns Monday as the first day of the week, datetime().weekday() will be Monday (0).
*/
weekday(): number;
/**
* Sets the day of the week according to the locale, 0..6.
* If the locale assigns Monday as the first day of the week, datetime().weekday(0) will be Monday.
* If Sunday is the first day of the week, moment().weekday(0) will be Sunday.
*/
weekday(d: number): Datetime;
/**
* Gets the ISO day of the week, 1(Monday)..7(Sunday)
*/
isoWeekday(): number;
/**
* Sets the ISO day of the week, 1(Monday)..7(Sunday)
* If the range is exceeded, it will bubble up to other weeks.
*/
isoWeekday(d: number | string): Datetime;
/**
* Gets the week-year according to the locale
*/
weekYear(): number;
/**
* Gets or sets the week-year according to the locale
*
*/
weekYear(d: number): Datetime;
/**
* Gets the ISO week-year
*/
isoWeekYear(): number;
/**
* Sets the ISO week-year
*/
isoWeekYear(d: number): Datetime;
/**
* Gets the week of the year, 1..53
*/
week(): number;
/**
* Sets the week of the year, 1..53
*/
week(d: number): Datetime;
/**
* Gets the week of the year, 1..53
*/
weeks(): number;
/**
* Sets the week of the year, 1..53
*/
weeks(d: number): Datetime;
/**
* Gets the ISO week of the year, 1..53
*/
isoWeek(): number;
/**
* Sets the ISO week of the year, 1..53
*/
isoWeek(d: number): Datetime;
/**
* Gets the ISO week of the year, 1..53
*/
isoWeeks(): number;
/**
* Sets the ISO week of the year, 1..53
*/
isoWeeks(d: number): Datetime;
/**
* Gets the number of weeks according to locale in the current datetime's year
*/
weeksInYear(): number;
/**
* Gets the number of weeks in the current datetime's year, according to ISO weeks
*/
isoWeeksInYear(): number;
/**
* Gets the day of the year, 1..366
*/
dayOfYear(): number;
/**
* Sets the day of the year, 1..366.
* If the range is exceeded, it will bubble up to the years
*/
dayOfYear(d: number): Datetime;
/**
* Displays a datetime in relation to a time other than now
*/
from(inp: DatetimeInput, suffix?: boolean): string;
/**
* Displays the datetime in relation to a time other than now
*/
to(inp: DatetimeInput, suffix?: boolean): string;
/**
* Displays the datatime in relation to now
*/
fromNow(withoutSuffix?: boolean): string;
/**
* Displays the datatime in relation to now
*/
toNow(withoutPrefix?: boolean): string;
/**
* Returns the difference in the given unit, default is milliseconds
*/
diff(b: DatetimeInput, unitOfTime?: unitOfTime.Diff, precise?: boolean): number;
/**
* Returns an array that mirrors the parameters from new Date()
*/
toArray(): number[];
/**
* Conver the datetime to MS-DOS date/time format
*/
toDOS(): MSDOSFormat;
/**
* Returns a copy of the native Date object that the datetime wraps
*/
toDate(): Date;
/**
* Formats a string to the ISO8601 standard
*/
toISOString(): string;
/**
* Returns a machine readable string, that can be evaluated to produce the same datetime
*/
inspect(): string;
/**
* When serializing a duration object to JSON, it will be represented as an ISO8601 string
*/
toJSON(): string;
/**
* Returns a Unix timestamp (the number of seconds since the Unix Epoch)
*/
unix(): number;
/**
* Returns true if that year is a leap year, and false if it is not.
*/
isLeapYear(): boolean;
/**
* Get the UTC offset in minutes.
*/
utcOffset(): number;
/**
* Sets the UTC offset
*/
utcOffset(b: number | string, keepLocalTime?: boolean): Datetime;
isUtcOffset(): boolean;
/**
* Returns the number of days in the current month
*/
daysInMonth(): number;
/**
* Checks if the current moment is in daylight saving time
*/
isDST(): boolean;
/**
* Returns the zone abbreviation
*/
zoneAbbr(): string;
/**
* Returns the zone name
*/
zoneName(): string;
/**
* Check if the datetime is before another datetime.
*/
isBefore(inp?: DatetimeInput, granularity?: unitOfTime.StartOf): boolean;
/**
* Check if the datetime is after another datetime.
*/
isAfter(inp?: DatetimeInput, granularity?: unitOfTime.StartOf): boolean;
/**
* Check if the datetime is the same as another datetime.
*/
isSame(inp?: DatetimeInput, granularity?: unitOfTime.StartOf): boolean;
/**
* Check if a datetime is after or the same as another datetime.
*/
isSameOrAfter(inp?: DatetimeInput, granularity?: unitOfTime.StartOf): boolean;
/**
* Check if a datetime is before or the same as another datetime.
*/
isSameOrBefore(inp?: DatetimeInput, granularity?: unitOfTime.StartOf): boolean;
/**
* Check if a datetime is between two other datetimes, optionally looking at unit scale (minutes, hours, days, etc).
* The match is exclusive.
*/
isBetween(a: DatetimeInput, b: DatetimeInput, granularity?: unitOfTime.StartOf, inclusivity?: "()" | "[)" | "(]" | "[]"): boolean;
/**
* Returns the using locale
*/
locale(): string;
/**
* Sets a new locale
*/
locale(locale: LocaleSpecifier): Datetime;
/**
* Returns the data of the using locale
*/
localeData(): Locale;
/**
* @deprecated no reliable implementation
*/
isDSTShifted(): boolean;
/**
* Returns the value of the given unit
*/
get(unit: unitOfTime.All): number;
/**
* Sets the value of the given unit
*/
set(unit: unitOfTime.All, value: number): Datetime;
/**
* Sets the values of the given units represented as an object
*/
set(objectLiteral: DatetimeSetObject): Datetime;
/**
* Returns an object containing year, month, day-of-month, hour, minute, seconds, milliseconds.
*/
toObject(): DatetimeObjectOutput;
}
interface DatetimeFunction {
(inp?: DatetimeInput, format?: DatetimeFormatSpecification, strict?: boolean): Datetime;
(inp?: DatetimeInput, format?: DatetimeFormatSpecification, language?: string, strict?: boolean): Datetime;
/**
* Creates a datetime in UTC
*/
utc(inp?: DatetimeInput, format?: DatetimeFormatSpecification, strict?: boolean): Datetime;
utc(inp?: DatetimeInput, format?: DatetimeFormatSpecification, language?: string, strict?: boolean): Datetime;
/**
* Creates a datetime from the given UNIX timestamp
*/
unix(timestamp: number): Datetime;
/**
* Creates a datetime from the given MS-DOS date and time
*/
dos(inp: MSDOSFormat): Datetime;
/**
* Crates an invalid datetime object
*/
invalid(flags?: DatetimeParsingFlagsOpt): Datetime;
/**
* Checks whether the given object is a Duration
*/
isDuration(d: any): d is Duration;
/**
* Changes the using locale
*/
locale(language?: string): string;
/**
* Changes the using locale, will use the first one it has localizations for.
*/
locale(language?: string[]): string;
/**
* Changes the using locale with customization
*/
locale(language?: string, definition?: LocaleSpecification | null): string;
/**
* Returns a locale by the given key or the current locale
*/
localeData(key?: string | string[]): Locale;
/**
* Creates a new Duration object
*/
duration(inp?: DurationInputArg1, unit?: DurationInputArg2): Duration;
parseZone(inp?: DatetimeInput, format?: DatetimeFormatSpecification, strict?: boolean): Datetime;
parseZone(inp?: DatetimeInput, format?: DatetimeFormatSpecification, language?: string, strict?: boolean): Datetime;
/**
* Returns the months of the current locale
*/
months(): string[];
/**
* Returns a month of the current locale at the given index
*/
months(index: number): string;
months(format: string): string[];
months(format: string, index: number): string;
/**
* Returns the short form of the months of the current locale
*/
monthsShort(): string[];
monthsShort(index: number): string;
monthsShort(format: string): string[];
monthsShort(format: string, index: number): string;
/**
* Returns the weekdays of the current locale
*/
weekdays(): string[];
weekdays(index: number): string;
weekdays(format: string): string[];
weekdays(format: string, index: number): string;
weekdays(localeSorted: boolean): string[];
weekdays(localeSorted: boolean, index: number): string;
weekdays(localeSorted: boolean, format: string): string[];
weekdays(localeSorted: boolean, format: string, index: number): string;
/**
* Returns the short form of the weekdays of the current locale
*/
weekdaysShort(): string[];
weekdaysShort(index: number): string;
weekdaysShort(format: string): string[];
weekdaysShort(format: string, index: number): string;
weekdaysShort(localeSorted: boolean): string[];
weekdaysShort(localeSorted: boolean, index: number): string;
weekdaysShort(localeSorted: boolean, format: string): string[];
weekdaysShort(localeSorted: boolean, format: string, index: number): string;
/**
* Returns the min form of the weekdays of the current locale
*/
weekdaysMin(): string[];
weekdaysMin(index: number): string;
weekdaysMin(format: string): string[];
weekdaysMin(format: string, index: number): string;
weekdaysMin(localeSorted: boolean): string[];
weekdaysMin(localeSorted: boolean, index: number): string;
weekdaysMin(localeSorted: boolean, format: string): string[];
weekdaysMin(localeSorted: boolean, format: string, index: number): string;
/**
* Returns the minimum of the given datetimes
*/
min(...datetimes: DatetimeInput[]): Datetime;
/**
* Returns the maximum of the given datetimes
*/
max(...datetimes: DatetimeInput[]): Datetime;
/**
* Returns the number of milliseconds since the Unix epoch (January 1, 1970)
*/
now(): number;
/**
* Defines a new locale
*/
defineLocale(language: string, localeSpec: LocaleSpecification | null): Locale;
/**
* Updates an existing locale
*/
updateLocale(language: string, localeSpec: LocaleSpecification | null): Locale;
/**
* Returns a list of the defined locales (lazy-loaded locales are not listed until they are loaded)
*/
locales(): string[];
/**
* Returns the original name of the given unit alias
*/
normalizeUnits(unit: unitOfTime.All): string;
relativeTimeThreshold(threshold: string): number;
relativeTimeThreshold(threshold: string, limit: number): boolean;
relativeTimeRounding(fn: (num: number) => number): boolean;
relativeTimeRounding(): (num: number) => number;
calendarFormat(m: Datetime, now: Datetime): string;
/**
* Default format for datetime.format()
*/
defaultFormat: string;
/**
* Default utc format for datetime.format()
*/
defaultFormatUtc: string;
}
}
}
/**
* Creates a new datetime object
*/
const datetime: I.datetime.DatetimeFunction;
} | the_stack |
import { ccf } from "./global.js";
// This should eventually cover all JSON-compatible values.
// There are attempts at https://github.com/microsoft/TypeScript/issues/1897
// to create such a type but it needs further refinement.
export type JsonCompatible<T> = any;
export interface DataConverter<T> {
encode(val: T): ArrayBuffer;
decode(arr: ArrayBuffer): T;
}
class BoolConverter implements DataConverter<boolean> {
encode(val: boolean): ArrayBuffer {
const buf = new ArrayBuffer(1);
new DataView(buf).setUint8(0, val ? 1 : 0);
return buf;
}
decode(buf: ArrayBuffer): boolean {
return new DataView(buf).getUint8(0) === 1 ? true : false;
}
}
class Int8Converter implements DataConverter<number> {
encode(val: number): ArrayBuffer {
if (val < -128 || val > 127) {
throw new RangeError("value is not within int8 range");
}
const buf = new ArrayBuffer(1);
new DataView(buf).setInt8(0, val);
return buf;
}
decode(buf: ArrayBuffer): number {
return new DataView(buf).getInt8(0);
}
}
class Uint8Converter implements DataConverter<number> {
encode(val: number): ArrayBuffer {
if (val < 0 || val > 255) {
throw new RangeError("value is not within uint8 range");
}
const buf = new ArrayBuffer(2);
new DataView(buf).setUint8(0, val);
return buf;
}
decode(buf: ArrayBuffer): number {
return new DataView(buf).getUint8(0);
}
}
class Int16Converter implements DataConverter<number> {
encode(val: number): ArrayBuffer {
if (val < -32768 || val > 32767) {
throw new RangeError("value is not within int16 range");
}
const buf = new ArrayBuffer(2);
new DataView(buf).setInt16(0, val, true);
return buf;
}
decode(buf: ArrayBuffer): number {
return new DataView(buf).getInt16(0, true);
}
}
class Uint16Converter implements DataConverter<number> {
encode(val: number): ArrayBuffer {
if (val < 0 || val > 65535) {
throw new RangeError("value is not within uint16 range");
}
const buf = new ArrayBuffer(2);
new DataView(buf).setUint16(0, val, true);
return buf;
}
decode(buf: ArrayBuffer): number {
return new DataView(buf).getUint16(0, true);
}
}
class Int32Converter implements DataConverter<number> {
encode(val: number): ArrayBuffer {
if (val < -2147483648 || val > 2147483647) {
throw new RangeError("value is not within int32 range");
}
const buf = new ArrayBuffer(4);
new DataView(buf).setInt32(0, val, true);
return buf;
}
decode(buf: ArrayBuffer): number {
return new DataView(buf).getInt32(0, true);
}
}
class Uint32Converter implements DataConverter<number> {
encode(val: number): ArrayBuffer {
if (val < 0 || val > 4294967295) {
throw new RangeError("value is not within uint32 range");
}
const buf = new ArrayBuffer(4);
new DataView(buf).setUint32(0, val, true);
return buf;
}
decode(buf: ArrayBuffer): number {
return new DataView(buf).getUint32(0, true);
}
}
class Int64Converter implements DataConverter<bigint> {
encode(val: bigint): ArrayBuffer {
const buf = new ArrayBuffer(8);
new DataView(buf).setBigInt64(0, val, true);
return buf;
}
decode(buf: ArrayBuffer): bigint {
return new DataView(buf).getBigInt64(0, true);
}
}
class Uint64Converter implements DataConverter<bigint> {
encode(val: bigint): ArrayBuffer {
const buf = new ArrayBuffer(8);
new DataView(buf).setBigUint64(0, val, true);
return buf;
}
decode(buf: ArrayBuffer): bigint {
return new DataView(buf).getBigUint64(0, true);
}
}
class Float32Converter implements DataConverter<number> {
encode(val: number): ArrayBuffer {
const buf = new ArrayBuffer(4);
new DataView(buf).setFloat32(0, val, true);
return buf;
}
decode(buf: ArrayBuffer): number {
return new DataView(buf).getFloat32(0, true);
}
}
class Float64Converter implements DataConverter<number> {
encode(val: number): ArrayBuffer {
const buf = new ArrayBuffer(8);
new DataView(buf).setFloat64(0, val, true);
return buf;
}
decode(buf: ArrayBuffer): number {
return new DataView(buf).getFloat64(0, true);
}
}
class StringConverter implements DataConverter<string> {
encode(val: string): ArrayBuffer {
return ccf.strToBuf(val);
}
decode(buf: ArrayBuffer): string {
return ccf.bufToStr(buf);
}
}
class JSONConverter<T extends JsonCompatible<T>> implements DataConverter<T> {
encode(val: T): ArrayBuffer {
return ccf.jsonCompatibleToBuf(val);
}
decode(buf: ArrayBuffer): T {
return ccf.bufToJsonCompatible(buf);
}
}
type TypedArray = ArrayBufferView;
interface TypedArrayConstructor<T extends TypedArray> {
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): T;
}
class TypedArrayConverter<T extends TypedArray> implements DataConverter<T> {
constructor(private clazz: TypedArrayConstructor<T>) {}
encode(val: T): ArrayBuffer {
return val.buffer.slice(val.byteOffset, val.byteOffset + val.byteLength);
}
decode(buf: ArrayBuffer): T {
return new this.clazz(buf);
}
}
class IdentityConverter implements DataConverter<ArrayBuffer> {
encode(val: ArrayBuffer): ArrayBuffer {
return val;
}
decode(buf: ArrayBuffer): ArrayBuffer {
return buf;
}
}
/**
* Converter for `boolean` values.
*
* A `boolean` is represented as `uint8` where `true` is `1`
* and `false` is `0`.
*
* Example:
* ```
* const buf = ccfapp.bool.encode(true); // ArrayBuffer of size 1
* const val = ccfapp.bool.decode(buf); // boolean
* ```
*/
export const bool: DataConverter<boolean> = new BoolConverter();
/**
* Converter for `number` values, encoded as `int8`.
*
* Example:
* ```
* const buf = ccfapp.int8.encode(-50); // ArrayBuffer of size 1
* const val = ccfapp.int8.decode(buf); // number
* ```
*/
export const int8: DataConverter<number> = new Int8Converter();
/**
* Converter for `number` values, encoded as `uint8`.
*
* Example:
* ```
* const buf = ccfapp.uint8.encode(255); // ArrayBuffer of size 1
* const val = ccfapp.uint8.decode(buf); // number
* ```
*/
export const uint8: DataConverter<number> = new Uint8Converter();
/**
* Converter for `number` values, encoded as `int16`.
*
* Example:
* ```
* const buf = ccfapp.int16.encode(-1000); // ArrayBuffer of size 2
* const val = ccfapp.int16.decode(buf); // number
* ```
*/
export const int16: DataConverter<number> = new Int16Converter();
/**
* Converter for `number` values, encoded as `uint16`.
*
* Example:
* ```
* const buf = ccfapp.uint16.encode(50000); // ArrayBuffer of size 2
* const val = ccfapp.uint16.decode(buf); // number
* ```
*/
export const uint16: DataConverter<number> = new Uint16Converter();
/**
* Converter for `number` values, encoded as `int32`.
*
* Example:
* ```
* const buf = ccfapp.int32.encode(-50000); // ArrayBuffer of size 4
* const val = ccfapp.int32.decode(buf); // number
* ```
*/
export const int32: DataConverter<number> = new Int32Converter();
/**
* Converter for `number` values, encoded as `uint32`.
*
* Example:
* ```
* const buf = ccfapp.uint32.encode(50000); // ArrayBuffer of size 4
* const val = ccfapp.uint32.decode(buf); // number
* ```
*/
export const uint32: DataConverter<number> = new Uint32Converter();
/**
* Converter for `bigint` values, encoded as `int64`.
*
* Example:
* ```
* const n = 2n ** 53n + 1n; // larger than Number.MAX_SAFE_INTEGER
* const buf = ccfapp.int64.encode(n); // ArrayBuffer of size 8
* const val = ccfapp.int64.decode(buf); // bigint
* ```
*/
export const int64: DataConverter<bigint> = new Int64Converter();
/**
* Converter for `bigint` values, encoded as `uint64`.
*
* Example:
* ```
* const n = 2n ** 53n + 1n; // larger than Number.MAX_SAFE_INTEGER
* const buf = ccfapp.uint64.encode(n); // ArrayBuffer of size 8
* const val = ccfapp.uint64.decode(buf); // bigint
* ```
*/
export const uint64: DataConverter<bigint> = new Uint64Converter();
/**
* Converter for `number` values, encoded as `float32`.
*
* Example:
* ```
* const buf = ccfapp.float32.encode(3.141); // ArrayBuffer of size 4
* const val = ccfapp.float32.decode(buf); // number
* ```
*/
export const float32: DataConverter<number> = new Float32Converter();
/**
* Converter for `number` values, encoded as `float64`.
*
* Example:
* ```
* const buf = ccfapp.float64.encode(3.141); // ArrayBuffer of size 8
* const val = ccfapp.float64.decode(buf); // number
* ```
*/
export const float64: DataConverter<number> = new Float64Converter();
/**
* Converter for `string` values, encoded as UTF-8.
*
* Example:
* ```
* const buf = ccfapp.string.encode('my-string'); // ArrayBuffer
* const val = ccfapp.string.decode(buf); // string
* ```
*/
export const string: DataConverter<string> = new StringConverter();
/**
* Returns a converter for JSON-compatible objects or values.
*
* {@linkcode DataConverter.encode | encode} first serializes the object
* or value to JSON and then converts the resulting string to an `ArrayBuffer`.
* JSON serialization uses `JSON.stringify()` without `replacer` or
* `space` parameters.
*
* {@linkcode DataConverter.decode | decode} converts the `ArrayBuffer`
* to a string and parses it using `JSON.parse()` without `reviver`
* parameter.
*
* Example:
* ```
* interface Person {
* name: string
* age: number
* }
* const person: Person = { name: "John", age: 42 };
* const conv = ccfapp.json<Person>();
* const buffer = conv.encode(person); // ArrayBuffer
* const person2 = conv.decode(buffer); // Person
* ```
*/
export const json: <T extends JsonCompatible<T>>() => DataConverter<T> = <
T extends JsonCompatible<T>
>() => new JSONConverter<T>();
/**
* Returns a converter for [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) objects.
*
* Note that a `TypedArray` is a view into an underlying `ArrayBuffer`.
* This view allows to cover a subset of the `ArrayBuffer`, for example
* when using `TypedArray.prototype.subarray()`.
* For views which are subsets, a roundtrip from `TypedArray` to `ArrayBuffer`
* and back will yield a `TypedArray` that is not a subset anymore.
*
* Example:
* ```
* const arr = new Uint8Array([42]);
* const conv = ccfapp.typedArray(Uint8Array);
* const buffer = conv.encode(arr); // ArrayBuffer of size arr.byteLength
* const arr2 = conv.decode(buffer); // Uint8Array
* ```
*
* @param clazz The TypedArray class, for example `Uint8Array`.
*/
export const typedArray: <T extends TypedArray>(
clazz: TypedArrayConstructor<T>
) => DataConverter<T> = <T extends TypedArray>(
clazz: TypedArrayConstructor<T>
) => new TypedArrayConverter(clazz);
/**
* Identity converter.
* {@linkcode DataConverter.encode | encode} / {@linkcode DataConverter.decode | decode}
* return the input `ArrayBuffer` unchanged. No copy is made.
*
* This converter can be used with {@linkcode kv.typedKv} when the key or value
* type is `ArrayBuffer`, in which case no conversion is applied.
*/
export const arrayBuffer: DataConverter<ArrayBuffer> = new IdentityConverter(); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/recordSetsMappers";
import * as Parameters from "../models/parameters";
import { DnsManagementClientContext } from "../dnsManagementClientContext";
/** Class representing a RecordSets. */
export class RecordSets {
private readonly client: DnsManagementClientContext;
/**
* Create a RecordSets.
* @param {DnsManagementClientContext} client Reference to the service client.
*/
constructor(client: DnsManagementClientContext) {
this.client = client;
}
/**
* Updates a record set within a DNS zone.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param relativeRecordSetName The name of the record set, relative to the name of the zone.
* @param recordType The type of DNS record in this record set. Possible values include: 'A',
* 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param parameters Parameters supplied to the Update operation.
* @param [options] The optional parameters
* @returns Promise<Models.RecordSetsUpdateResponse>
*/
update(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, parameters: Models.RecordSet, options?: Models.RecordSetsUpdateOptionalParams): Promise<Models.RecordSetsUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param relativeRecordSetName The name of the record set, relative to the name of the zone.
* @param recordType The type of DNS record in this record set. Possible values include: 'A',
* 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param parameters Parameters supplied to the Update operation.
* @param callback The callback
*/
update(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, parameters: Models.RecordSet, callback: msRest.ServiceCallback<Models.RecordSet>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param relativeRecordSetName The name of the record set, relative to the name of the zone.
* @param recordType The type of DNS record in this record set. Possible values include: 'A',
* 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param parameters Parameters supplied to the Update operation.
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, parameters: Models.RecordSet, options: Models.RecordSetsUpdateOptionalParams, callback: msRest.ServiceCallback<Models.RecordSet>): void;
update(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, parameters: Models.RecordSet, options?: Models.RecordSetsUpdateOptionalParams | msRest.ServiceCallback<Models.RecordSet>, callback?: msRest.ServiceCallback<Models.RecordSet>): Promise<Models.RecordSetsUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
zoneName,
relativeRecordSetName,
recordType,
parameters,
options
},
updateOperationSpec,
callback) as Promise<Models.RecordSetsUpdateResponse>;
}
/**
* Creates or updates a record set within a DNS zone.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param relativeRecordSetName The name of the record set, relative to the name of the zone.
* @param recordType The type of DNS record in this record set. Record sets of type SOA can be
* updated but not created (they are created when the DNS zone is created). Possible values
* include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param parameters Parameters supplied to the CreateOrUpdate operation.
* @param [options] The optional parameters
* @returns Promise<Models.RecordSetsCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, parameters: Models.RecordSet, options?: Models.RecordSetsCreateOrUpdateOptionalParams): Promise<Models.RecordSetsCreateOrUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param relativeRecordSetName The name of the record set, relative to the name of the zone.
* @param recordType The type of DNS record in this record set. Record sets of type SOA can be
* updated but not created (they are created when the DNS zone is created). Possible values
* include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param parameters Parameters supplied to the CreateOrUpdate operation.
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, parameters: Models.RecordSet, callback: msRest.ServiceCallback<Models.RecordSet>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param relativeRecordSetName The name of the record set, relative to the name of the zone.
* @param recordType The type of DNS record in this record set. Record sets of type SOA can be
* updated but not created (they are created when the DNS zone is created). Possible values
* include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param parameters Parameters supplied to the CreateOrUpdate operation.
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, parameters: Models.RecordSet, options: Models.RecordSetsCreateOrUpdateOptionalParams, callback: msRest.ServiceCallback<Models.RecordSet>): void;
createOrUpdate(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, parameters: Models.RecordSet, options?: Models.RecordSetsCreateOrUpdateOptionalParams | msRest.ServiceCallback<Models.RecordSet>, callback?: msRest.ServiceCallback<Models.RecordSet>): Promise<Models.RecordSetsCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
zoneName,
relativeRecordSetName,
recordType,
parameters,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.RecordSetsCreateOrUpdateResponse>;
}
/**
* Deletes a record set from a DNS zone. This operation cannot be undone.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param relativeRecordSetName The name of the record set, relative to the name of the zone.
* @param recordType The type of DNS record in this record set. Record sets of type SOA cannot be
* deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA',
* 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, options?: Models.RecordSetsDeleteMethodOptionalParams): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param relativeRecordSetName The name of the record set, relative to the name of the zone.
* @param recordType The type of DNS record in this record set. Record sets of type SOA cannot be
* deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA',
* 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param relativeRecordSetName The name of the record set, relative to the name of the zone.
* @param recordType The type of DNS record in this record set. Record sets of type SOA cannot be
* deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA',
* 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, options: Models.RecordSetsDeleteMethodOptionalParams, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, options?: Models.RecordSetsDeleteMethodOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
zoneName,
relativeRecordSetName,
recordType,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Gets a record set.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param relativeRecordSetName The name of the record set, relative to the name of the zone.
* @param recordType The type of DNS record in this record set. Possible values include: 'A',
* 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param [options] The optional parameters
* @returns Promise<Models.RecordSetsGetResponse>
*/
get(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, options?: msRest.RequestOptionsBase): Promise<Models.RecordSetsGetResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param relativeRecordSetName The name of the record set, relative to the name of the zone.
* @param recordType The type of DNS record in this record set. Possible values include: 'A',
* 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param callback The callback
*/
get(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, callback: msRest.ServiceCallback<Models.RecordSet>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param relativeRecordSetName The name of the record set, relative to the name of the zone.
* @param recordType The type of DNS record in this record set. Possible values include: 'A',
* 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.RecordSet>): void;
get(resourceGroupName: string, zoneName: string, relativeRecordSetName: string, recordType: Models.RecordType, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.RecordSet>, callback?: msRest.ServiceCallback<Models.RecordSet>): Promise<Models.RecordSetsGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
zoneName,
relativeRecordSetName,
recordType,
options
},
getOperationSpec,
callback) as Promise<Models.RecordSetsGetResponse>;
}
/**
* Lists the record sets of a specified type in a DNS zone.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param recordType The type of record sets to enumerate. Possible values include: 'A', 'AAAA',
* 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param [options] The optional parameters
* @returns Promise<Models.RecordSetsListByTypeResponse>
*/
listByType(resourceGroupName: string, zoneName: string, recordType: Models.RecordType, options?: Models.RecordSetsListByTypeOptionalParams): Promise<Models.RecordSetsListByTypeResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param recordType The type of record sets to enumerate. Possible values include: 'A', 'AAAA',
* 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param callback The callback
*/
listByType(resourceGroupName: string, zoneName: string, recordType: Models.RecordType, callback: msRest.ServiceCallback<Models.RecordSetListResult>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param recordType The type of record sets to enumerate. Possible values include: 'A', 'AAAA',
* 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
* @param options The optional parameters
* @param callback The callback
*/
listByType(resourceGroupName: string, zoneName: string, recordType: Models.RecordType, options: Models.RecordSetsListByTypeOptionalParams, callback: msRest.ServiceCallback<Models.RecordSetListResult>): void;
listByType(resourceGroupName: string, zoneName: string, recordType: Models.RecordType, options?: Models.RecordSetsListByTypeOptionalParams | msRest.ServiceCallback<Models.RecordSetListResult>, callback?: msRest.ServiceCallback<Models.RecordSetListResult>): Promise<Models.RecordSetsListByTypeResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
zoneName,
recordType,
options
},
listByTypeOperationSpec,
callback) as Promise<Models.RecordSetsListByTypeResponse>;
}
/**
* Lists all record sets in a DNS zone.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param [options] The optional parameters
* @returns Promise<Models.RecordSetsListByDnsZoneResponse>
*/
listByDnsZone(resourceGroupName: string, zoneName: string, options?: Models.RecordSetsListByDnsZoneOptionalParams): Promise<Models.RecordSetsListByDnsZoneResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param callback The callback
*/
listByDnsZone(resourceGroupName: string, zoneName: string, callback: msRest.ServiceCallback<Models.RecordSetListResult>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param zoneName The name of the DNS zone (without a terminating dot).
* @param options The optional parameters
* @param callback The callback
*/
listByDnsZone(resourceGroupName: string, zoneName: string, options: Models.RecordSetsListByDnsZoneOptionalParams, callback: msRest.ServiceCallback<Models.RecordSetListResult>): void;
listByDnsZone(resourceGroupName: string, zoneName: string, options?: Models.RecordSetsListByDnsZoneOptionalParams | msRest.ServiceCallback<Models.RecordSetListResult>, callback?: msRest.ServiceCallback<Models.RecordSetListResult>): Promise<Models.RecordSetsListByDnsZoneResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
zoneName,
options
},
listByDnsZoneOperationSpec,
callback) as Promise<Models.RecordSetsListByDnsZoneResponse>;
}
/**
* Lists the record sets of a specified type in a DNS zone.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.RecordSetsListByTypeNextResponse>
*/
listByTypeNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.RecordSetsListByTypeNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByTypeNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.RecordSetListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByTypeNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.RecordSetListResult>): void;
listByTypeNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.RecordSetListResult>, callback?: msRest.ServiceCallback<Models.RecordSetListResult>): Promise<Models.RecordSetsListByTypeNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByTypeNextOperationSpec,
callback) as Promise<Models.RecordSetsListByTypeNextResponse>;
}
/**
* Lists all record sets in a DNS zone.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.RecordSetsListByDnsZoneNextResponse>
*/
listByDnsZoneNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.RecordSetsListByDnsZoneNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByDnsZoneNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.RecordSetListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByDnsZoneNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.RecordSetListResult>): void;
listByDnsZoneNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.RecordSetListResult>, callback?: msRest.ServiceCallback<Models.RecordSetListResult>): Promise<Models.RecordSetsListByDnsZoneNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByDnsZoneNextOperationSpec,
callback) as Promise<Models.RecordSetsListByDnsZoneNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.zoneName,
Parameters.relativeRecordSetName,
Parameters.recordType,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.ifMatch,
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.RecordSet,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.RecordSet
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.zoneName,
Parameters.relativeRecordSetName,
Parameters.recordType,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.RecordSet,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.RecordSet
},
201: {
bodyMapper: Mappers.RecordSet
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.zoneName,
Parameters.relativeRecordSetName,
Parameters.recordType,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.ifMatch,
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.zoneName,
Parameters.relativeRecordSetName,
Parameters.recordType,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.RecordSet
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByTypeOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.zoneName,
Parameters.recordType,
Parameters.subscriptionId
],
queryParameters: [
Parameters.top,
Parameters.recordsetnamesuffix,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.RecordSetListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByDnsZoneOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets",
urlParameters: [
Parameters.resourceGroupName,
Parameters.zoneName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.top,
Parameters.recordsetnamesuffix,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.RecordSetListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByTypeNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.RecordSetListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByDnsZoneNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.RecordSetListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import { Production } from '../production';
import { WorldInterface } from './worldInterface';
import { Unit } from '../units/unit';
import { GameModel } from '../gameModel';
import { BuyAction, BuyAndUnlockAction, Research, TimeWarp, UpAction, UpHire, UpSpecial, Resupply } from '../units/action';
import { Base } from '../units/base';
import { Cost } from '../cost';
import { TypeList } from '../typeList';
import { World } from '../world';
import { forEach } from '@angular/router/src/utils/collection';
export class Prestige implements WorldInterface {
experience: Unit
expLists = new Array<TypeList>()
expAnt = new Array<Unit>()
expFollower = new Array<Unit>()
expMachinery = new Array<Unit>()
expTech = new Array<Unit>()
allPrestigeUp = new Array<Unit>()
// Ant Follower
pAntPower: Unit
pAntGeo: Unit
pAntHunter1: Unit
pAntHunter2: Unit
pAntFungus: Unit
pAntLum: Unit
// Ant Power
pAntNext: Unit
pGeologistNext: Unit
pScientistNext: Unit
pFarmerNext: Unit
pCarpenterNext: Unit
pLumberjackNext: Unit
// Prestige Machinery
pMachineryPower: Unit
// Prestige Technology
pComposter: Unit
pRefinery: Unit
pLaser: Unit
pHydro: Unit
pPlanter: Unit
// Supply
supplyList: Array<Unit>
// Efficiency
effList = new Array<Unit>()
effListEng = new Array<Unit>()
effListDep = new Array<Unit>()
// World
worldList = new Array<Unit>()
worldBuilder: Unit
worldBetter: Unit
// Time
timeList = new Array<Unit>()
time: Unit
timeMaker: Unit
timeBank: Unit
// Non ant efficiency
otherList = new Array<Unit>()
constructor(public game: GameModel) { }
public declareStuff() {
}
public initStuff() {
const expIncrement = new Decimal(1.3)
this.experience = new Unit(this.game, "exp", "Exp",
"Experience. Experience upgrade do not reset when changing worlds.", true)
this.expLists = new Array<TypeList>()
this.expAnt = new Array<Unit>()
//#region Ants Power
this.pAntPower = new Unit(this.game, "pap", "Ant Power",
"Ants yield 30% more food.", true)
this.pAntGeo = new Unit(this.game, "pAntGeo", "Geologist Power",
"Geologists yield 30% more crystal.", true)
this.pAntHunter1 = new Unit(this.game, "phunt1", "Hunter Power",
"Hunters yield and consume 30% more resources.", true)
this.pAntHunter2 = new Unit(this.game, "phunt2", "Advanced Hunter",
"Advanced Hunters yield and consume 30% more resources.", true)
this.pAntFungus = new Unit(this.game, "paf", "Farmer Power",
"Farmers yield and consume 30% more resources", true)
this.expAnt.push(this.pAntPower)
this.expAnt.push(this.pAntGeo)
this.expAnt.push(this.pAntHunter1)
this.expAnt.push(this.pAntHunter2)
this.expAnt.push(this.pAntFungus)
this.expAnt.forEach(p => {
this.allPrestigeUp.push(p)
p.actions.push(new BuyAction(this.game, p,
[new Cost(this.experience, new Decimal(15), expIncrement)]))
p.unlocked = true
})
this.game.baseWorld.littleAnt.prestigeBonusProduction.push(this.pAntPower)
this.game.baseWorld.geologist.prestigeBonusProduction.push(this.pAntGeo)
this.game.baseWorld.hunter.prestigeBonusProduction.push(this.pAntHunter1)
this.game.baseWorld.advancedHunter.prestigeBonusProduction.push(this.pAntHunter2)
this.game.baseWorld.farmer.prestigeBonusProduction.push(this.pAntFungus)
this.expLists.push(new TypeList("Ant", this.expAnt))
//#endregion
//#region Ants in next world
this.pAntNext = new Unit(this.game, "pan", "Ant follower",
"Start new worlds with 5 more ants.", true)
this.pGeologistNext = new Unit(this.game, "pgn", "Geologist follower",
"Start new worlds with 5 more geologists.", true)
this.pScientistNext = new Unit(this.game, "psn", "Scientist follower",
"Start new worlds with 5 more scientists.", true)
this.pFarmerNext = new Unit(this.game, "pfn", "Farmer follower",
"Start new worlds with 5 more farmers.", true)
this.pCarpenterNext = new Unit(this.game, "pcarn", "Carpenter follower",
"Start new worlds with 5 more carpenters.", true)
this.pLumberjackNext = new Unit(this.game, "plumn", "Lumberjack follower",
"Start new worlds with 5 more lumberjacks.", true)
this.expFollower = [this.pAntNext, this.pGeologistNext, this.pScientistNext,
this.pFarmerNext, this.pCarpenterNext, this.pLumberjackNext]
this.expFollower.forEach(n => {
this.allPrestigeUp.push(n)
n.actions.push(new BuyAction(this.game, n,
[new Cost(this.experience, new Decimal(10), expIncrement)]))
})
this.game.baseWorld.littleAnt.prestigeBonusStart = this.pAntNext
this.game.baseWorld.geologist.prestigeBonusStart = this.pGeologistNext
this.game.science.student.prestigeBonusStart = this.pScientistNext
this.game.baseWorld.farmer.prestigeBonusStart = this.pFarmerNext
this.game.baseWorld.carpenter.prestigeBonusStart = this.pCarpenterNext
this.game.baseWorld.lumberjack.prestigeBonusStart = this.pLumberjackNext
this.expLists.push(new TypeList("Ant Followers", this.expFollower))
//#endregion
//#region Machinery
this.expMachinery = new Array<Unit>()
this.pMachineryPower = new Unit(this.game, "pMach", "Machinery Power",
"Machinery yields and consume 30% more resources.", true)
this.pMachineryPower.actions.push(new BuyAction(this.game, this.pMachineryPower,
[new Cost(this.experience, new Decimal(20), expIncrement)]))
this.expMachinery.push(this.pMachineryPower)
this.game.machines.listMachinery.forEach(m => m.prestigeBonusProduction.push(this.pMachineryPower))
this.expLists.push(new TypeList("Machinery", this.expMachinery))
//#endregion
//#region Technology
this.expTech = new Array<Unit>()
this.pComposter = new Unit(this.game, "pComposter", "Compost",
"Composter units yield and consume 30% more resources.", true)
this.pRefinery = new Unit(this.game, "pRefinery", "Refinery",
"Refinery units yield and consume 30% more resources.", true)
this.pLaser = new Unit(this.game, "pLaser", "Laser",
"Laser units yield and consume 30% more resources.", true)
this.pHydro = new Unit(this.game, "pHydro", "Hydroponics",
"Hydroponics units yield and consume 30% more resources.", true)
this.pPlanter = new Unit(this.game, "pPlanter", "Planting",
"Planting units yield and consume 30% more resources.", true)
this.expTech.push(this.pComposter)
this.expTech.push(this.pRefinery)
this.expTech.push(this.pLaser)
this.expTech.push(this.pHydro)
this.expTech.push(this.pPlanter)
this.expTech.forEach(p => {
p.actions.push(new BuyAction(this.game, p,
[new Cost(this.experience, new Decimal(30), expIncrement)]))
})
this.expLists.push(new TypeList("Technology", this.expTech))
this.game.machines.composterStation.prestigeBonusProduction.push(this.pComposter)
this.game.baseWorld.composterAnt.prestigeBonusProduction.push(this.pComposter)
this.game.machines.refineryStation.prestigeBonusProduction.push(this.pRefinery)
this.game.baseWorld.refineryAnt.prestigeBonusProduction.push(this.pRefinery)
this.game.machines.laserStation.prestigeBonusProduction.push(this.pLaser)
this.game.baseWorld.laserAnt.prestigeBonusProduction.push(this.pLaser)
this.game.machines.hydroFarm.prestigeBonusProduction.push(this.pHydro)
this.game.baseWorld.hydroAnt.prestigeBonusProduction.push(this.pHydro)
this.game.machines.plantingMachine.prestigeBonusProduction.push(this.pPlanter)
this.game.baseWorld.planterAnt.prestigeBonusProduction.push(this.pPlanter)
//#endregion
//#region Supply
const supplyMaterials = [
this.game.baseWorld.food,
this.game.baseWorld.crystal,
this.game.baseWorld.soil,
this.game.baseWorld.wood,
this.game.baseWorld.sand
]
supplyMaterials.forEach(sm => sm.prestigeBonusQuantityValue = new Decimal(1000))
this.supplyList = supplyMaterials.map(sm =>
new Unit(this.game, "supp_" + sm.id, sm.name + " supply.",
"Start new worlds with 1000 more " + sm.name + ".", true))
for (let i = 0; i < supplyMaterials.length; i++) {
const n = this.supplyList[i]
const resup = new Resupply(this.game, supplyMaterials[i], n)
this.allPrestigeUp.push(n)
n.actions.push(new BuyAndUnlockAction(this.game, n,
[new Cost(this.experience, new Decimal(12), expIncrement)],
[resup]))
supplyMaterials[i].prestigeBonusStart = this.supplyList[i]
supplyMaterials[i].actions.push(resup)
}
this.expLists.push(new TypeList("Supply", this.supplyList))
//#endregion
//#region Efficiency
this.effList = new Array<Unit>()
const names = [
"Composter", "Refinery", "Laser", "Hydroponics", "Planting"
]
const effMatrix = [
[
[this.game.baseWorld.composterAnt, this.game.machines.composterStation]
],
[
[this.game.baseWorld.refineryAnt, this.game.machines.refineryStation]
],
[
[this.game.baseWorld.laserAnt, this.game.machines.laserStation]
],
[
[this.game.baseWorld.hydroAnt, this.game.machines.hydroFarm]
],
[
[this.game.baseWorld.planterAnt, this.game.machines.plantingMachine]
]
]
for (let i = 0; i < 5; i++) {
const eff = new Unit(this.game, "eff" + names[i], names[i],
names[i] + " units consume 5% less resources. Max -50%.", true)
const ba = new BuyAction(this.game, eff,
[new Cost(this.experience, new Decimal(50), expIncrement)])
ba.limit = new Decimal(10)
eff.actions.push(ba)
effMatrix[i].forEach(u => u.forEach(u2 => u2.produces
.filter(p => p.efficiency.lessThanOrEqualTo(0))
.forEach(prod => {
if (!prod.bonusList)
prod.bonusList = new Array<[Base, decimal.Decimal]>()
prod.bonusList.push([eff, new Decimal(-0.05)])
})
))
this.effList.push(eff)
}
this.expLists.push(new TypeList("Efficiency", this.effList))
//#endregion
//#region Efficiency 2
this.effListEng = new Array<Unit>()
this.game.engineers.listEnginer.forEach(eng => {
const eff = new Unit(this.game, "effEng" + eng.id, eng.name,
eng.name + " consume 5% less resources. Max -50%.", true)
const ba = new BuyAction(this.game, eff,
[new Cost(this.experience, new Decimal(50), expIncrement)])
ba.limit = new Decimal(10)
eff.actions.push(ba)
eng.produces.filter(p => p.efficiency.lessThanOrEqualTo(0))
.forEach(prod => {
if (!prod.bonusList)
prod.bonusList = new Array<[Base, decimal.Decimal]>()
prod.bonusList.push([eff, new Decimal(-0.05)])
})
this.effListEng.push(eff)
})
this.expLists.push(new TypeList("Engineering", this.effListEng))
//#endregion
//#region Efficiency 3
this.effListDep = new Array<Unit>()
this.game.engineers.listDep.forEach(dep => {
const eff = new Unit(this.game, "effDep" + dep.id, dep.name,
dep.name + " consume 5% less resources. Max -50%.", true)
const ba = new BuyAction(this.game, eff,
[new Cost(this.experience, new Decimal(60), expIncrement)])
ba.limit = new Decimal(10)
eff.actions.push(ba)
dep.produces.filter(p => p.efficiency.lessThanOrEqualTo(0))
.forEach(prod => {
if (!prod.bonusList)
prod.bonusList = new Array<[Base, decimal.Decimal]>()
prod.bonusList.push([eff, new Decimal(-0.05)])
})
this.effListDep.push(eff)
})
this.expLists.push(new TypeList("Departments", this.effListDep))
//#endregion
//#region Time
this.time = new Unit(this.game, "ptime", "Time",
"Time can be used to go to the future. One unit of time corresponds to one second.", true)
this.timeMaker = new Unit(this.game, "ptimeMaker", "Time Generator",
"Time Generator generates time at 1/10 of real life speed. It's not affected by pause and time warps.", true)
this.timeMaker.percentage = 100
this.timeMaker.alwaysOn = true
this.timeBank = new Unit(this.game, "ptimeBank", "Time Bank",
"Time Bank increases the maxium time storage by 1 hour. Base storage is 4 hours.", true)
this.timeMaker.actions.push(new BuyAction(this.game, this.timeMaker,
[new Cost(this.experience, new Decimal(25), expIncrement)]))
this.timeBank.actions.push(new BuyAction(this.game, this.timeBank,
[new Cost(this.experience, new Decimal(100), expIncrement)]))
this.game.actMin = new TimeWarp(this.game, new Decimal(60), "Minutes")
this.game.actHour = new TimeWarp(this.game, new Decimal(3600), "Hours")
this.time.actions.push(this.game.actMin)
this.time.actions.push(this.game.actHour)
this.time.actions.push(new TimeWarp(this.game, new Decimal(3600 * 24), "Days"))
// this.time.addProductor(new Production(this.timeMaker, new Decimal(0.1)))
this.timeList = [this.time, this.timeMaker, this.timeBank]
this.expLists.push(new TypeList("Time Management", this.timeList))
//#endregion
//#region Other
this.otherList = new Array<Unit>()
const otherLists: (Unit[] | string)[][] =
[
[this.game.bee.listBee, "Bee"],
[this.game.beach.beachList, "Sea"],
[this.game.forest.listForest, "Beetle"]
]
this.otherList = otherLists.map(ol => {
const u = new Unit(this.game, "otherL" + ol[1], ol[1] + " efficienty.",
ol[1] + " units yield 100% more.")
const ul = <Unit[]>ol[0]
ul.forEach(unit => {
unit.produces.filter(p => p.efficiency.greaterThan(0))
.forEach(prod => {
prod.bonusList.push([u, new Decimal(1)])
})
});
u.actions.push(new BuyAction(this.game, u,
[new Cost(this.experience, new Decimal(12), expIncrement)]))
return u
})
this.expLists.push(new TypeList("Non Ant", this.otherList))
//#endregion
//#region World
this.worldBuilder = new Unit(this.game, "worldBuilder", "World Builder",
"Unlock the world builder ! (one time purchase)")
this.worldBuilder.actions.push(new BuyAction(this.game, this.worldBuilder,
[new Cost(this.experience, new Decimal(1E3), expIncrement)]))
// this.worldBuilder.buyAction.oneTime = true
this.worldBuilder.buyAction.limit = new Decimal(1)
this.worldBetter = new Unit(this.game, "worldBetter", "World Adaption",
"Increase positive effects of new worlds. +50% 'production of.. ' and 'yields and consume'")
this.worldBetter.actions.push(new BuyAction(this.game, this.worldBetter,
[new Cost(this.experience, new Decimal(10), expIncrement)]))
this.worldList = [this.worldBuilder, this.worldBetter]
this.expLists.push(new TypeList("World", this.worldList))
//#endregion
this.expLists.map(l => l.list).forEach(al => al.forEach(l => {
l.unlocked = true
l.showTables = false
l.neverEnding = true
l.actions.forEach(a => a.unlocked = true)
}))
}
public addWorld() {
}
} | the_stack |
import Player from './player'
import validateTarget from 'validate-target'
import { checkSupportFullScreen, getCSSTransitionDuration } from 'shared/utils/utils'
import LoaderTemplate from '../../components/loader/assets/scripts/loader'
import BigPlayTemplate from '../../components/big-play/assets/scripts/big-play'
import OverlayTemplate from '../../components/overlay/assets/scripts/overlay'
import PosterTemplate from '../../components/poster/assets/scripts/poster'
import { Options, FullScreenSupport } from 'shared/assets/interfaces/interfaces'
import { registerProvider, getProviderInstance } from '../../../providers/provider'
import { getPluginInstance, registerPlugin, initializePlugins } from '../../../plugins/plugin'
type TimerHandle = number
export interface interfaceDefaultOptions {
[key: string]: {
[key: string]: any
}
}
const DEFAULT_OPTIONS: interfaceDefaultOptions = {
audio: {
controls: true,
autoplay: false,
playPause: true,
progressBar: true,
time: true,
volume: true,
loop: false
},
video: {
controls: true,
autoplay: false,
playPause: true,
progressBar: true,
time: true,
volume: true,
fullscreen: true,
poster: null,
bigPlay: true,
playsinline: false,
loop: false,
muted: false,
autoHide: false,
providerParams: {}
}
}
/**
* Vlitejs entrypoint
* @module vLite/entrypoint
*/
class Vlitejs {
Player: any
media: HTMLVideoElement | HTMLAudioElement | HTMLDivElement
provider: string
onReady: Function | Boolean
delayAutoHide: number
type: string
supportFullScreen: FullScreenSupport
options: Options
autoHideGranted: Boolean
container: HTMLElement
player: any
controlBar: any
registerPlugin!: Function
registerProvider!: Function
timerAutoHide!: TimerHandle
/**
* @constructor
* @param {(String|HTMLElement)} selector CSS selector or HTML element
* @param {Object} options
* @param {Object} options.options Player options
* @param {String} options.provider Player provider
* @param {Object} options.plugins Player plugins
* @param {Function} options.onReady Callback function when the player is ready
*/
constructor(
selector: string | HTMLElement,
{
options = {},
provider = 'html5',
plugins = [],
onReady = false
}: {
options?: Options | Object
provider?: string
plugins?: Array<string>
onReady?: Function | Boolean
} = {}
) {
// Detect the type of the selector (string or HTMLElement)
if (typeof selector === 'string') {
// @ts-ignore: Object is possibly 'null'.
this.media = document.querySelector(selector)
} else if (
selector instanceof HTMLVideoElement ||
selector instanceof HTMLAudioElement ||
selector instanceof HTMLDivElement
) {
this.media = selector
} else {
throw new TypeError('vlitejs :: The element or selector supplied is not valid.')
}
this.provider = provider
this.onReady = onReady
this.delayAutoHide = 3000
this.type = this.media instanceof HTMLAudioElement ? 'audio' : 'video'
// Check fullscreen support API on different browsers and cached prefixs
this.supportFullScreen = checkSupportFullScreen()
// Update config from element attributes
const htmlAttributes: Array<string> = ['autoplay', 'playsinline', 'muted', 'loop']
htmlAttributes.forEach((item: string) => {
if (this.media.hasAttribute(item)) {
// @ts-ignore
options[item] = true
// @ts-ignore
} else if (options[item]) {
this.media.setAttribute(item, '')
}
})
this.options = { ...DEFAULT_OPTIONS[this.type], ...options } as Options
this.autoHideGranted =
this.type === 'video' && !!this.options.autoHide && !!this.options.controls
this.onClickOnPlayer = this.onClickOnPlayer.bind(this)
this.onDoubleClickOnPlayer = this.onDoubleClickOnPlayer.bind(this)
this.onKeydown = this.onKeydown.bind(this)
this.onMousemove = this.onMousemove.bind(this)
this.onChangeFullScreen = this.onChangeFullScreen.bind(this)
const ProviderInstance = getProviderInstance(provider, Player)
this.wrapElement()
this.container = this.media.parentNode as HTMLElement
this.type === 'video' && this.renderLayout()
this.player = new ProviderInstance({
type: this.type,
Vlitejs: this
})
this.player.build()
this.addEvents()
initializePlugins({
plugins,
provider,
type: this.type,
player: this.player
})
}
/**
* Wrap the media element
*/
wrapElement() {
const wrapper = document.createElement('div')
wrapper.classList.add('v-vlite', 'v-firstStart', 'v-paused', 'v-loading', `v-${this.type}`)
wrapper.setAttribute('tabindex', '0')
const parentElement = this.media.parentNode as HTMLElement
parentElement.insertBefore(wrapper, this.media)
wrapper.appendChild(this.media)
}
/**
* Build the HTML of the player
*/
renderLayout() {
const template = `
${OverlayTemplate()}
${LoaderTemplate()}
${this.options.poster ? PosterTemplate({ posterUrl: this.options.poster }) : ''}
${this.options.bigPlay ? BigPlayTemplate() : ''}
`
this.container.insertAdjacentHTML('beforeend', template)
}
/**
* Add evnets listeners
*/
addEvents() {
if (this.type === 'video') {
this.container.addEventListener('click', this.onClickOnPlayer)
this.container.addEventListener('dblclick', this.onDoubleClickOnPlayer)
this.autoHideGranted && this.container.addEventListener('mousemove', this.onMousemove)
window.addEventListener(this.supportFullScreen.changeEvent, this.onChangeFullScreen)
}
this.container.addEventListener('keydown', this.onKeydown)
}
/**
* On click on the player
* @param {Event} e Event data
*/
onClickOnPlayer(e: Event) {
const target = e.target as HTMLElement
const validateTargetPlayPauseButton = validateTarget({
target,
selectorString: '.v-poster, .v-overlay, .v-bigPlay',
nodeName: ['div', 'button']
})
if (validateTargetPlayPauseButton) {
this.player.controlBar.togglePlayPause(e)
target.matches('.v-bigPlay') && this.container.focus()
}
}
/**
* On double click on the player
* @param {Event} e Event data
*/
onDoubleClickOnPlayer(e: Event) {
const target = e.target
const validateTargetOverlay = validateTarget({
target,
selectorString: '.v-overlay',
nodeName: ['div']
})
if (validateTargetOverlay) {
this.player.controlBar.toggleFullscreen(e)
}
}
/**
* On keydown event on the media element
* @param {KeyboardEvent} e Event listener datas
*/
onKeydown(e: KeyboardEvent) {
const activeElement = document.activeElement
const { keyCode } = e
// Stop and start the auto hide timer on selected key code
if (
[9, 32, 37, 39].includes(keyCode) &&
this.autoHideGranted &&
(activeElement === this.container || activeElement?.closest('.v-vlite'))
) {
this.stopAutoHideTimer()
this.startAutoHideTimer()
}
// Backward or forward video with arrow keys
if (
[37, 39].includes(keyCode) &&
(activeElement === this.container || activeElement === this.player.elements.progressBar)
) {
// Prevent default behavior on input range
e.preventDefault()
if (keyCode === 37) {
this.fastForward('backward')
} else if (keyCode === 39) {
this.fastForward('forward')
}
}
// Increase or decrease volume with arrow keys
if (
[38, 40].includes(keyCode) &&
(activeElement === this.container || activeElement === this.player.elements.volume)
) {
if (keyCode === 38) {
this.animateVolumeButton()
this.increaseVolume()
} else if (keyCode === 40) {
this.animateVolumeButton()
this.decreaseVolume()
}
}
// Toggle the media playback with spacebar key
if (keyCode === 32 && activeElement === this.container) {
this.player.controlBar.togglePlayPause(e)
}
}
/**
* On mousemove on the player
*/
onMousemove() {
if (!this.player.isPaused) {
this.stopAutoHideTimer()
this.startAutoHideTimer()
}
}
/**
* On fullscreen change (espace key pressed)
* @doc https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
* @param {Event} e Event data
*/
onChangeFullScreen(e: Event) {
if (!document[this.supportFullScreen.isFullScreen] && this.player.isFullScreen) {
this.player.exitFullscreen({ escKey: true })
}
}
/**
* Trigger the video fast forward (front and rear)
* @param {String} direction Direction (backward|forward)
*/
fastForward(direction: string) {
this.player.getCurrentTime().then((seconds: number) => {
this.player.seekTo(direction === 'backward' ? seconds - 5 : seconds + 5)
})
}
/**
* Increase the player volume
*/
increaseVolume() {
const volume = this.player.getVolume().then((volume: number) => {
this.player.setVolume(volume + 0.05)
})
}
/**
* Decrease the player volume
*/
decreaseVolume() {
const volume = this.player.getVolume().then((volume: number) => {
this.player.setVolume(volume - 0.05)
})
}
/**
* Animate the volume button in CSS
*/
animateVolumeButton() {
if (this.player.elements.volume) {
const duration = getCSSTransitionDuration({
target: this.player.elements.volume,
isMilliseconds: true
})
this.player.elements.volume.classList.add('v-animate')
setTimeout(() => this.player.elements.volume.classList.remove('v-animate'), duration)
}
}
/**
* Stop the auto hide timer and show the video control bar
*/
stopAutoHideTimer() {
if (this.type === 'video' && this.player.elements.controlBar) {
this.player.elements.controlBar.classList.remove('hidden')
clearTimeout(this.timerAutoHide)
}
}
/**
* Start the auto hide timer and hide the video control bar after a delay
*/
startAutoHideTimer() {
if (this.type === 'video' && !this.player.isPaused && this.player.elements.controlBar) {
this.timerAutoHide = window.setTimeout(() => {
this.player.elements.controlBar.classList.add('hidden')
}, this.delayAutoHide)
}
}
/**
* Remove events listeners
*/
removeEvents() {
this.container.removeEventListener('keydown', this.onKeydown)
if (this.type === 'video') {
this.container.removeEventListener('click', this.onClickOnPlayer)
this.container.removeEventListener('dblclick', this.onDoubleClickOnPlayer)
this.autoHideGranted &&
this.container.removeEventListener('mousemove', this.onMousemove)
window.removeEventListener(this.supportFullScreen.changeEvent, this.onChangeFullScreen)
}
}
/**
* Destroy the player
*/
destroy() {
this.removeEvents()
this.player.destroy()
this.player.controlBar.destroy()
}
}
// Expose the provider registration
// @ts-ignore
Vlitejs.registerProvider = registerProvider
// Expose the plugin registration
// @ts-ignore
Vlitejs.registerPlugin = registerPlugin
export default Vlitejs | the_stack |
import React from 'react';
import 'jest-styled-components';
import 'regenerator-runtime/runtime';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { getByText, screen } from '@testing-library/dom';
import { axe } from 'jest-axe';
import 'jest-axe/extend-expect';
import { Search } from 'grommet-icons';
import { createPortal, expectPortal } from '../../../utils/portal';
import { Grommet } from '../../Grommet';
import { TextInput } from '..';
import { Keyboard } from '../../Keyboard';
import { Text } from '../../Text';
describe('TextInput', () => {
beforeEach(createPortal);
test('should not have accessibility violations', async () => {
const { container } = render(
<Grommet>
<TextInput a11yTitle="aria-test" name="item" />
</Grommet>,
);
const results = await axe(container);
expect(container.firstChild).toMatchSnapshot();
expect(results).toHaveNoViolations();
});
test('basic', () => {
const { container } = render(<TextInput name="item" />);
expect(container.firstChild).toMatchSnapshot();
});
test('a11yTitle or aria-label', () => {
const { container, getByLabelText } = render(
<Grommet>
<TextInput a11yTitle="aria-test" name="item" />
<TextInput aria-label="aria-test-2" name="item-2" />
</Grommet>,
);
expect(getByLabelText('aria-test')).toBeTruthy();
expect(getByLabelText('aria-test-2')).toBeTruthy();
expect(container.firstChild).toMatchSnapshot();
});
test('disabled', () => {
const { container } = render(<TextInput disabled name="item" />);
expect(container.firstChild).toMatchSnapshot();
});
test('icon', () => {
const { container } = render(<TextInput icon={<Search />} name="item" />);
expect(container.firstChild).toMatchSnapshot();
});
test('icon reverse', () => {
const { container } = render(
<TextInput icon={<Search />} reverse name="item" />,
);
expect(container.firstChild).toMatchSnapshot();
});
test('suggestions', (done) => {
const onChange = jest.fn();
const onFocus = jest.fn();
const { getByTestId, container } = render(
<TextInput
data-testid="test-input"
id="item"
name="item"
suggestions={['test', 'test1']}
onChange={onChange}
onFocus={onFocus}
/>,
);
expect(container.firstChild).toMatchSnapshot();
fireEvent.focus(getByTestId('test-input'));
fireEvent.change(getByTestId('test-input'), { target: { value: ' ' } });
setTimeout(() => {
expectPortal('text-input-drop__item').toMatchSnapshot();
expect(onChange).toBeCalled();
expect(onFocus).toBeCalled();
fireEvent(
document,
new MouseEvent('mousedown', { bubbles: true, cancelable: true }),
);
expect(document.getElementById('text-input-drop__item')).toBeNull();
done();
}, 50);
});
test('complex suggestions', (done) => {
const { getByTestId, container } = render(
<Grommet>
<TextInput
data-testid="test-input"
id="item"
name="item"
suggestions={[{ label: 'test', value: 'test' }, { value: 'test1' }]}
/>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
fireEvent.focus(getByTestId('test-input'));
fireEvent.change(getByTestId('test-input'), { target: { value: ' ' } });
setTimeout(() => {
expectPortal('text-input-drop__item').toMatchSnapshot();
fireEvent(
document,
new MouseEvent('mousedown', { bubbles: true, cancelable: true }),
);
expect(document.getElementById('text-input-drop__item')).toBeNull();
done();
}, 50);
});
test('close suggestion drop', (done) => {
const { getByTestId, container } = render(
<Grommet>
<TextInput
data-testid="test-input"
id="item"
name="item"
suggestions={['test', 'test1']}
/>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
fireEvent.focus(getByTestId('test-input'));
fireEvent.change(getByTestId('test-input'), { target: { value: ' ' } });
setTimeout(() => {
expectPortal('text-input-drop__item').toMatchSnapshot();
fireEvent.keyDown(getByTestId('test-input'), {
key: 'Esc',
keyCode: 27,
which: 27,
});
setTimeout(() => {
expect(document.getElementById('text-input-drop__item')).toBeNull();
expect(container.firstChild).toMatchSnapshot();
done();
}, 50);
}, 50);
});
test('let escape events propagage if there are no suggestions', (done) => {
const callback = jest.fn();
const { getByTestId } = render(
<Grommet>
<Keyboard onEsc={callback}>
<TextInput data-testid="test-input" id="item" name="item" />
</Keyboard>
</Grommet>,
);
fireEvent.change(getByTestId('test-input'), { target: { value: ' ' } });
setTimeout(() => {
fireEvent.keyDown(getByTestId('test-input'), {
key: 'Esc',
keyCode: 27,
which: 27,
});
expect(callback).toBeCalled();
done();
}, 50);
});
test('calls onSuggestionsOpen', (done) => {
const onSuggestionsOpen = jest.fn();
const { getByTestId } = render(
<Grommet>
<TextInput
data-testid="test-input"
id="item"
name="item"
suggestions={['test', 'test1']}
onSuggestionsOpen={onSuggestionsOpen}
/>
</Grommet>,
);
fireEvent.focus(getByTestId('test-input'));
setTimeout(() => {
expectPortal('text-input-drop__item').toMatchSnapshot();
expect(onSuggestionsOpen).toBeCalled();
done();
}, 50);
});
test('calls onSuggestionsClose', (done) => {
const onSuggestionsClose = jest.fn();
const { getByTestId, container } = render(
<Grommet>
<TextInput
data-testid="test-input"
id="item"
name="item"
suggestions={['test', 'test1']}
onSuggestionsClose={onSuggestionsClose}
/>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
fireEvent.focus(getByTestId('test-input'));
setTimeout(() => {
expectPortal('text-input-drop__item').toMatchSnapshot();
fireEvent.keyDown(getByTestId('test-input'), {
key: 'Esc',
keyCode: 27,
which: 27,
});
setTimeout(() => {
expect(document.getElementById('text-input-drop__item')).toBeNull();
expect(onSuggestionsClose).toBeCalled();
expect(container.firstChild).toMatchSnapshot();
done();
}, 50);
}, 50);
});
test('select suggestion', (done) => {
const onSelect = jest.fn();
const { getByTestId, container } = render(
<Grommet>
<TextInput
data-testid="test-input"
plain
size="large"
id="item"
name="item"
suggestions={['test', 'test1']}
onSelect={onSelect}
/>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
fireEvent.focus(getByTestId('test-input'));
fireEvent.change(getByTestId('test-input'), { target: { value: ' ' } });
setTimeout(() => {
expectPortal('text-input-drop__item').toMatchSnapshot();
// Casting a custom to a primitive by erasing type with unknown.
fireEvent.click(getByText(document as unknown as HTMLElement, 'test1'));
expect(container.firstChild).toMatchSnapshot();
expect(document.getElementById('text-input-drop__item')).toBeNull();
expect(onSelect).toBeCalledWith(
expect.objectContaining({ suggestion: 'test1' }),
);
done();
}, 50);
});
test('select a suggestion with onSelect', () => {
const onSelect = jest.fn();
const { getByTestId, container } = render(
<Grommet>
<TextInput
data-testid="test-input"
id="item"
name="item"
suggestions={['test', { value: 'test1' }]}
onSelect={onSelect}
/>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
const input = getByTestId('test-input');
// pressing enter here nothing will happen
fireEvent.keyDown(input, { keyCode: 13 }); // enter
fireEvent.keyDown(input, { keyCode: 40 }); // down
fireEvent.keyDown(input, { keyCode: 40 }); // down
fireEvent.keyDown(input, { keyCode: 38 }); // up
fireEvent.keyDown(input, { keyCode: 13 }); // enter
expect(onSelect).toBeCalledWith(
expect.objectContaining({
suggestion: 'test',
}),
);
});
test('auto-select 2nd suggestion with defaultSuggestion', () => {
const onSelect = jest.fn();
const suggestions = ['test1', 'test2'];
const defaultSuggestionIndex = 1;
const { getByTestId } = render(
<Grommet>
<TextInput
data-testid="test-input"
id="item"
name="item"
defaultSuggestion={defaultSuggestionIndex}
suggestions={suggestions}
onSuggestionSelect={onSelect}
/>
</Grommet>,
);
const input = getByTestId('test-input');
// open drop - second should be automatically highlighted
fireEvent.keyDown(input, { keyCode: 40 }); // down
// pressing enter here will select the second suggestion
fireEvent.keyDown(input, { keyCode: 13 }); // enter
expect(onSelect).toBeCalledWith(
expect.objectContaining({
suggestion: suggestions[defaultSuggestionIndex],
}),
);
});
test('auto-select 1st suggestion via typing with defaultSuggestion', () => {
const onSelect = jest.fn();
const suggestions = ['nodefault1', 'default', 'nodefault2'];
const defaultSuggestionIndex = 1;
const { getByTestId } = render(
<Grommet>
<TextInput
data-testid="test-input"
id="item"
name="item"
defaultSuggestion={defaultSuggestionIndex}
suggestions={suggestions}
onSuggestionSelect={onSelect}
/>
</Grommet>,
);
const input = getByTestId('test-input');
// Set focus so drop opens and we track activeSuggestionIndex
fireEvent.focus(input);
// Fire a change event so that onChange is triggered.
fireEvent.change(input, { target: { value: 'ma' } });
// Each time we type, the active suggestion should reset to the suggestion
// matching the entered text, or the default suggestion index if no
// suggestion matches. Now, when we hit enter, there's no match yet, so
// the default suggestion should be selected.
fireEvent.keyDown(input, { keyCode: 13 }); // enter
expect(onSelect).toBeCalledWith(
expect.objectContaining({
suggestion: 'default',
}),
);
});
test('do not select any suggestion without defaultSuggestion', () => {
const onSelect = jest.fn();
const { getByTestId } = render(
<Grommet>
<TextInput
data-testid="test-input"
id="item"
name="item"
suggestions={['test1', 'test2']}
onSuggestionSelect={onSelect}
/>
</Grommet>,
);
const input = getByTestId('test-input');
// open drop
fireEvent.keyDown(input, { keyCode: 40 }); // down
// pressing enter here closes drop but doesn't select
fireEvent.keyDown(input, { keyCode: 13 }); // enter
// if no suggestion had been selected, don't call onSelect
expect(onSelect).not.toBeCalled();
// open drop
fireEvent.keyDown(input, { keyCode: 40 }); // down
// highlight first
fireEvent.keyDown(input, { keyCode: 40 }); // down
// highlight second
fireEvent.keyDown(input, { keyCode: 40 }); // down
// select highlighted
fireEvent.keyDown(input, { keyCode: 13 }); // enter
expect(onSelect).toBeCalledWith(
expect.objectContaining({
suggestion: 'test2',
}),
);
});
test('select a suggestion with onSuggestionSelect', () => {
const onSuggestionSelect = jest.fn();
const { getByTestId, container } = render(
<Grommet>
<TextInput
data-testid="test-input"
id="item"
name="item"
suggestions={['test', { value: 'test1' }]}
onSuggestionSelect={onSuggestionSelect}
/>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
const input = getByTestId('test-input');
// pressing enter here nothing will happen
fireEvent.keyDown(input, { keyCode: 13 }); // enter
fireEvent.keyDown(input, { keyCode: 40 }); // down
fireEvent.keyDown(input, { keyCode: 40 }); // down
fireEvent.keyDown(input, { keyCode: 38 }); // up
fireEvent.keyDown(input, { keyCode: 13 }); // enter
expect(onSuggestionSelect).toBeCalledWith(
expect.objectContaining({
suggestion: 'test',
}),
);
});
test('select with onSuggestionSelect when onSelect is present', () => {
const onSelect = jest.fn();
const onSuggestionSelect = jest.fn();
const { getByTestId, container } = render(
<Grommet>
<TextInput
data-testid="test-input"
id="item"
name="item"
suggestions={['test', { value: 'test1' }]}
onSelect={onSelect}
onSuggestionSelect={onSuggestionSelect}
/>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
const input = getByTestId('test-input');
// pressing enter here nothing will happen
fireEvent.keyDown(input, { keyCode: 13 }); // enter
fireEvent.keyDown(input, { keyCode: 40 }); // down
fireEvent.keyDown(input, { keyCode: 40 }); // down
fireEvent.keyDown(input, { keyCode: 38 }); // up
fireEvent.keyDown(input, { keyCode: 13 }); // enter
expect(onSuggestionSelect).toBeCalledWith(
expect.objectContaining({
suggestion: 'test',
}),
);
});
test('handles next and previous without suggestion', () => {
const onSelect = jest.fn();
const { getByTestId, container } = render(
<Grommet>
<TextInput
data-testid="test-input"
id="item"
name="item"
onSelect={onSelect}
/>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
const input = getByTestId('test-input');
fireEvent.keyDown(input, { keyCode: 40 });
fireEvent.keyDown(input, { keyCode: 40 });
fireEvent.keyDown(input, { keyCode: 38 });
fireEvent.keyDown(input, { keyCode: 13 }); // enter
expect(onSelect).not.toBeCalled();
expect(container.firstChild).toMatchSnapshot();
});
['small', 'medium', 'large'].forEach((dropHeight) => {
test(`${dropHeight} drop height`, (done) => {
const { getByTestId } = render(
<TextInput
data-testid="test-input"
id="item"
name="item"
suggestions={['test', 'test1']}
dropHeight={dropHeight}
/>,
);
fireEvent.focus(getByTestId('test-input'));
setTimeout(() => {
expectPortal('text-input-drop__item').toMatchSnapshot();
done();
}, 50);
});
});
test('should return focus to input on select', async () => {
const onSelect = jest.fn();
const { getByPlaceholderText } = render(
<Grommet>
<TextInput
data-testid="test-input-focus"
id="input-focus"
name="input-focus"
placeholder="Type to search..."
suggestions={['option0', 'option1', 'option2']}
onSelect={onSelect}
/>
</Grommet>,
);
const input = getByPlaceholderText('Type to search...');
expect(document.activeElement).not.toEqual(input);
fireEvent.focus(input);
expect(document.activeElement).not.toEqual(input);
const selection = await waitFor(() => screen.getByText('option1'));
fireEvent.click(selection);
expect(document.activeElement).toEqual(input);
});
test('should return focus to ref on select', async () => {
const inputRef = React.createRef<HTMLInputElement>();
const onSelect = jest.fn();
const { getByPlaceholderText } = render(
<Grommet>
<TextInput
ref={inputRef}
data-testid="test-input-focus"
id="input-focus"
name="input-focus"
placeholder="Type to search..."
suggestions={['option0', 'option1', 'option2']}
onSelect={onSelect}
/>
</Grommet>,
);
const input = getByPlaceholderText('Type to search...');
expect(document.activeElement).not.toEqual(input);
fireEvent.focus(input);
expect(document.activeElement).not.toEqual(input);
const selection = await waitFor(() => screen.getByText('option2'));
fireEvent.click(selection);
expect(document.activeElement).toEqual(input);
});
test('should not have padding when plain="full"', async () => {
const { container } = render(
<Grommet>
<TextInput
plain="full"
name="name"
placeholder="should not have padding"
/>
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test('should have padding when plain', async () => {
const { container } = render(
<Grommet>
<TextInput plain name="name" placeholder="should still have padding" />
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test('should show non-string placeholder', () => {
const { container } = render(
<Grommet>
<TextInput
data-testid="test-styled-placeholder"
id="styled-placeholder"
name="styled-placeholder"
placeholder={<Text>placeholder text</Text>}
/>
</Grommet>,
);
const placeholder = screen.getByText('placeholder text');
expect(placeholder).toBeTruthy();
expect(container.firstChild).toMatchSnapshot();
});
test('should hide non-string placeholder when having a value', () => {
const { container } = render(
<Grommet>
<TextInput
data-testid="styled-placeholder"
id="styled-placeholder"
name="styled-placeholder"
placeholder={<Text>placeholder text</Text>}
value="test"
/>
</Grommet>,
);
const placeholder = screen.queryByText('placeholder text');
expect(placeholder).toBeNull();
expect(container.firstChild).toMatchSnapshot();
});
test(`should only show default placeholder when placeholder is a
string`, () => {
const { container, getByTestId } = render(
<Grommet>
<TextInput
data-testid="placeholder"
id="placeholder"
name="placeholder"
placeholder="placeholder text"
/>
</Grommet>,
);
const placeholder = screen.queryByText('placeholder text');
fireEvent.change(getByTestId('placeholder'), {
target: { value: 'something' },
});
expect(placeholder).toBeNull();
expect(container.firstChild).toMatchSnapshot();
// after value is removed, only one placeholder should be present
// nothing from styled placeholder should appear since placeholder
// is a string
fireEvent.change(getByTestId('placeholder'), { target: { value: '' } });
expect(container.firstChild).toMatchSnapshot();
});
test('textAlign end', () => {
const { container } = render(
<Grommet>
<TextInput value="1234" textAlign="end" />
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test('custom theme input font size', () => {
const { container } = render(
<Grommet theme={{ global: { input: { font: { size: '16px' } } } }}>
<TextInput />
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test('renders size', () => {
const { container } = render(
<Grommet>
<TextInput size="xsmall" />
<TextInput size="small" />
<TextInput size="medium" />
<TextInput size="large" />
<TextInput size="xlarge" />
<TextInput size="xxlarge" />
<TextInput size="2xl" />
<TextInput size="3xl" />
<TextInput size="4xl" />
<TextInput size="5xl" />
<TextInput size="6xl" />
<TextInput size="16px" />
<TextInput size="1rem" />
<TextInput size="100%" />
</Grommet>,
);
expect(container.children).toMatchSnapshot();
});
}); | the_stack |
import { IntervalSet, Interval } from "antlr4ts/misc";
// This structure contains all currently defined Unicode blocks (according to https://unicode-table.com/en/blocks/)
// together with a weight value that determines the probability to select a given block in the random block selection.
const UnicodeBlocks: Array<[Interval, string, number]> = [
[new Interval(0x0000, 0x001F), "Control character", 0],
[new Interval(0x0020, 0x007F), "Basic Latin", 100],
[new Interval(0x0080, 0x00FF), "Latin-1 Supplement", 30],
[new Interval(0x0100, 0x017F), "Latin Extended-A", 20],
[new Interval(0x0180, 0x024F), "Latin Extended-B", 20],
[new Interval(0x0250, 0x02AF), "IPA Extensions", 5],
[new Interval(0x02B0, 0x02FF), "Spacing Modifier Letters", 3],
[new Interval(0x0300, 0x036F), "Combining Diacritical Marks", 4],
[new Interval(0x0370, 0x03FF), "Greek and Coptic", 20],
[new Interval(0x0400, 0x04FF), "Cyrillic", 20],
[new Interval(0x0500, 0x052F), "Cyrillic Supplement", 20],
[new Interval(0x0530, 0x058F), "Armenian", 5],
[new Interval(0x0590, 0x05FF), "Hebrew", 5],
[new Interval(0x0600, 0x06FF), "Arabic", 5],
[new Interval(0x0700, 0x074F), "Syriac", 5],
[new Interval(0x0750, 0x077F), "Arabic Supplement", 5],
[new Interval(0x0780, 0x07BF), "Thaana", 5],
[new Interval(0x07C0, 0x07FF), "NKo", 5],
[new Interval(0x0800, 0x083F), "Samaritan", 5],
[new Interval(0x0840, 0x085F), "Mandaic", 5],
[new Interval(0x0860, 0x086F), "Syriac Supplement", 5],
[new Interval(0x08A0, 0x08FF), "Arabic Extended-A", 5],
[new Interval(0x0900, 0x097F), "Devanagari", 5],
[new Interval(0x0980, 0x09FF), "Bengali", 5],
[new Interval(0x0A00, 0x0A7F), "Gurmukhi", 5],
[new Interval(0x0A80, 0x0AFF), "Gujarati", 5],
[new Interval(0x0B00, 0x0B7F), "Oriya", 5],
[new Interval(0x0B80, 0x0BFF), "Tamil", 5],
[new Interval(0x0C00, 0x0C7F), "Telugu", 5],
[new Interval(0x0C80, 0x0CFF), "Kannada", 5],
[new Interval(0x0D00, 0x0D7F), "Malayalam", 5],
[new Interval(0x0D80, 0x0DFF), "Sinhala", 5],
[new Interval(0x0E00, 0x0E7F), "Thai", 5],
[new Interval(0x0E80, 0x0EFF), "Lao", 5],
[new Interval(0x0F00, 0x0FFF), "Tibetan", 5],
[new Interval(0x1000, 0x109F), "Myanmar", 5],
[new Interval(0x10A0, 0x10FF), "Georgian", 5],
[new Interval(0x1100, 0x11FF), "Hangul Jamo", 5],
[new Interval(0x1200, 0x137F), "Ethiopic", 5],
[new Interval(0x1380, 0x139F), "Ethiopic Supplement", 5],
[new Interval(0x13A0, 0x13FF), "Cherokee", 5],
[new Interval(0x1400, 0x167F), "Unified Canadian Aboriginal Syllabics", 5],
[new Interval(0x1680, 0x169F), "Ogham", 5],
[new Interval(0x16A0, 0x16FF), "Runic", 5],
[new Interval(0x1700, 0x171F), "Tagalog", 5],
[new Interval(0x1720, 0x173F), "Hanunoo", 5],
[new Interval(0x1740, 0x175F), "Buhid", 5],
[new Interval(0x1760, 0x177F), "Tagbanwa", 5],
[new Interval(0x1780, 0x17FF), "Khmer", 5],
[new Interval(0x1800, 0x18AF), "Mongolian", 5],
[new Interval(0x18B0, 0x18FF), "Unified Canadian Aboriginal Syllabics Extended", 5],
[new Interval(0x1900, 0x194F), "Limbu", 5],
[new Interval(0x1950, 0x197F), "Tai Le", 5],
[new Interval(0x1980, 0x19DF), "New Tai Lue", 5],
[new Interval(0x19E0, 0x19FF), "Khmer Symbols", 4],
[new Interval(0x1A00, 0x1A1F), "Buginese", 5],
[new Interval(0x1A20, 0x1AAF), "Tai Tham", 5],
[new Interval(0x1AB0, 0x1AFF), "Combining Diacritical Marks Extended", 3],
[new Interval(0x1B00, 0x1B7F), "Balinese", 5],
[new Interval(0x1B80, 0x1BBF), "Sundanese", 5],
[new Interval(0x1BC0, 0x1BFF), "Batak", 5],
[new Interval(0x1C00, 0x1C4F), "Lepcha", 5],
[new Interval(0x1C50, 0x1C7F), "Ol Chiki", 5],
[new Interval(0x1C80, 0x1C8F), "Cyrillic Extended C", 20],
[new Interval(0x1CC0, 0x1CCF), "Sundanese Supplement", 5],
[new Interval(0x1CD0, 0x1CFF), "Vedic Extensions", 5],
[new Interval(0x1D00, 0x1D7F), "Phonetic Extensions", 5],
[new Interval(0x1D80, 0x1DBF), "Phonetic Extensions Supplement", 5],
[new Interval(0x1DC0, 0x1DFF), "Combining Diacritical Marks Supplement", 5],
[new Interval(0x1E00, 0x1EFF), "Latin Extended Additional", 20],
[new Interval(0x1F00, 0x1FFF), "Greek Extended", 20],
[new Interval(0x2000, 0x206F), "General Punctuation", 3],
[new Interval(0x2070, 0x209F), "Superscripts and Subscripts", 3],
[new Interval(0x20A0, 0x20CF), "Currency Symbols", 3],
[new Interval(0x20D0, 0x20FF), "Combining Diacritical Marks for Symbols", 1],
[new Interval(0x2100, 0x214F), "Letterlike Symbols", 5],
[new Interval(0x2150, 0x218F), "Number Forms", 5],
[new Interval(0x2190, 0x21FF), "Arrows", 3],
[new Interval(0x2200, 0x22FF), "Mathematical Operators", 3],
[new Interval(0x2300, 0x23FF), "Miscellaneous Technical", 3],
[new Interval(0x2400, 0x243F), "Control Pictures", 3],
[new Interval(0x2440, 0x245F), "Optical Character Recognition", 3],
[new Interval(0x2460, 0x24FF), "Enclosed Alphanumerics", 4],
[new Interval(0x2500, 0x257F), "Box Drawing", 3],
[new Interval(0x2580, 0x259F), "Block Elements", 3],
[new Interval(0x25A0, 0x25FF), "Geometric Shapes", 3],
[new Interval(0x2600, 0x26FF), "Miscellaneous Symbols", 3],
[new Interval(0x2700, 0x27BF), "Dingbats", 3],
[new Interval(0x27C0, 0x27EF), "Miscellaneous Mathematical Symbols-A", 3],
[new Interval(0x27F0, 0x27FF), "Supplemental Arrows-A", 3],
[new Interval(0x2800, 0x28FF), "Braille Patterns", 10],
[new Interval(0x2900, 0x297F), "Supplemental Arrows-B", 3],
[new Interval(0x2980, 0x29FF), "Miscellaneous Mathematical Symbols-B", 3],
[new Interval(0x2A00, 0x2AFF), "Supplemental Mathematical Operators", 3],
[new Interval(0x2B00, 0x2BFF), "Miscellaneous Symbols and Arrows", 3],
[new Interval(0x2C00, 0x2C5F), "Glagolitic", 5],
[new Interval(0x2C60, 0x2C7F), "Latin Extended-C", 20],
[new Interval(0x2C80, 0x2CFF), "Coptic", 10],
[new Interval(0x2D00, 0x2D2F), "Georgian Supplement", 20],
[new Interval(0x2D30, 0x2D7F), "Tifinagh", 5],
[new Interval(0x2D80, 0x2DDF), "Ethiopic Extended", 10],
[new Interval(0x2DE0, 0x2DFF), "Cyrillic Extended-A", 20],
[new Interval(0x2E00, 0x2E7F), "Supplemental Punctuation", 3],
[new Interval(0x2E80, 0x2EFF), "CJK Radicals Supplement", 5],
[new Interval(0x2F00, 0x2FDF), "Kangxi Radicals", 5],
[new Interval(0x2FF0, 0x2FFF), "Ideographic Description Characters", 4],
[new Interval(0x3000, 0x303F), "CJK Symbols and Punctuation", 5],
[new Interval(0x3040, 0x309F), "Hiragana", 10],
[new Interval(0x30A0, 0x30FF), "Katakana", 10],
[new Interval(0x3100, 0x312F), "Bopomofo", 10],
[new Interval(0x3130, 0x318F), "Hangul Compatibility Jamo", 5],
[new Interval(0x3190, 0x319F), "Kanbun", 5],
[new Interval(0x31A0, 0x31BF), "Bopomofo Extended", 5],
[new Interval(0x31C0, 0x31EF), "CJK Strokes", 5],
[new Interval(0x31F0, 0x31FF), "Katakana Phonetic Extensions", 4],
[new Interval(0x3200, 0x32FF), "Enclosed CJK Letters and Months", 4],
[new Interval(0x3300, 0x33FF), "CJK Compatibility", 5],
[new Interval(0x3400, 0x4DBF), "CJK Unified Ideographs Extension A", 5],
[new Interval(0x4DC0, 0x4DFF), "Yijing Hexagram Symbols", 5],
[new Interval(0x4E00, 0x9FFF), "CJK Unified Ideographs", 5],
[new Interval(0xA000, 0xA48F), "Yi Syllables", 5],
[new Interval(0xA490, 0xA4CF), "Yi Radicals", 5],
[new Interval(0xA4D0, 0xA4FF), "Lisu", 5],
[new Interval(0xA500, 0xA63F), "Vai", 5],
[new Interval(0xA640, 0xA69F), "Cyrillic Extended-B", 20],
[new Interval(0xA6A0, 0xA6FF), "Bamum", 5],
[new Interval(0xA700, 0xA71F), "Modifier Tone Letters", 4],
[new Interval(0xA720, 0xA7FF), "Latin Extended-D", 20],
[new Interval(0xA800, 0xA82F), "Syloti Nagri", 5],
[new Interval(0xA830, 0xA83F), "Common Indic Number Forms", 5],
[new Interval(0xA840, 0xA87F), "Phags-pa", 5],
[new Interval(0xA880, 0xA8DF), "Saurashtra", 5],
[new Interval(0xA8E0, 0xA8FF), "Devanagari Extended", 10],
[new Interval(0xA900, 0xA92F), "Kayah Li", 5],
[new Interval(0xA930, 0xA95F), "Rejang", 5],
[new Interval(0xA960, 0xA97F), "Hangul Jamo Extended-A", 10],
[new Interval(0xA980, 0xA9DF), "Javanese", 5],
[new Interval(0xA9E0, 0xA9FF), "Myanmar Extended-B", 5],
[new Interval(0xAA00, 0xAA5F), "Cham", 5],
[new Interval(0xAA60, 0xAA7F), "Myanmar Extended-A", 10],
[new Interval(0xAA80, 0xAADF), "Tai Viet", 10],
[new Interval(0xAAE0, 0xAAFF), "Meetei Mayek Extensions", 5],
[new Interval(0xAB00, 0xAB2F), "Ethiopic Extended-A", 10],
[new Interval(0xAB30, 0xAB6F), "Latin Extended-E", 20],
[new Interval(0xAB70, 0xABBF), "Cherokee Supplement", 5],
[new Interval(0xABC0, 0xABFF), "Meetei Mayek", 5],
[new Interval(0xAC00, 0xD7AF), "Hangul Syllables", 5],
[new Interval(0xD7B0, 0xD7FF), "Hangul Jamo Extended-B", 5],
[new Interval(0xD800, 0xDB7F), "High Surrogates", 0],
[new Interval(0xDB80, 0xDBFF), "High Private Use Surrogates", 0],
[new Interval(0xDC00, 0xDFFF), "Low Surrogates", 0],
[new Interval(0xE000, 0xF8FF), "Private Use Area", 0],
[new Interval(0xF900, 0xFAFF), "CJK Compatibility Ideographs", 5],
[new Interval(0xFB00, 0xFB4F), "Alphabetic Presentation Forms", 3],
[new Interval(0xFB50, 0xFDFF), "Arabic Presentation Forms-A", 5],
[new Interval(0xFE00, 0xFE0F), "Variation Selectors", 4],
[new Interval(0xFE10, 0xFE1F), "Vertical Forms", 3],
[new Interval(0xFE20, 0xFE2F), "Combining Half Marks", 4],
[new Interval(0xFE30, 0xFE4F), "CJK Compatibility Forms", 5],
[new Interval(0xFE50, 0xFE6F), "Small Form Variants", 4],
[new Interval(0xFE70, 0xFEFF), "Arabic Presentation Forms-B", 5],
[new Interval(0xFF00, 0xFFEF), "Halfwidth and Fullwidth Forms", 5],
[new Interval(0xFFF0, 0xFFFF), "Specials", 3],
[new Interval(0x10000, 0x1007F), "Linear B Syllabary", 5],
[new Interval(0x10080, 0x100FF), "Linear B Ideograms", 5],
[new Interval(0x10100, 0x1013F), "Aegean Numbers", 4],
[new Interval(0x10140, 0x1018F), "Ancient Greek Numbers", 4],
[new Interval(0x10190, 0x101CF), "Ancient Symbols", 4],
[new Interval(0x101D0, 0x101FF), "Phaistos Disc", 4],
[new Interval(0x10280, 0x1029F), "Lycian", 4],
[new Interval(0x102A0, 0x102DF), "Carian", 4],
[new Interval(0x102E0, 0x102FF), "Coptic Epact Numbers", 3],
[new Interval(0x10300, 0x1032F), "Old Italic", 3],
[new Interval(0x10330, 0x1034F), "Gothic", 4],
[new Interval(0x10350, 0x1037F), "Old Permic", 3],
[new Interval(0x10380, 0x1039F), "Ugaritic", 4],
[new Interval(0x103A0, 0x103DF), "Old Persian", 3],
[new Interval(0x10400, 0x1044F), "Deseret", 4],
[new Interval(0x10450, 0x1047F), "Shavian", 4],
[new Interval(0x10480, 0x104AF), "Osmanya", 4],
[new Interval(0x104B0, 0x104FF), "Osage", 4],
[new Interval(0x10500, 0x1052F), "Elbasan", 4],
[new Interval(0x10530, 0x1056F), "Caucasian Albanian", 4],
[new Interval(0x10600, 0x1077F), "Linear A", 3],
[new Interval(0x10800, 0x1083F), "Cypriot Syllabary", 5],
[new Interval(0x10840, 0x1085F), "Imperial Aramaic", 4],
[new Interval(0x10860, 0x1087F), "Palmyrene", 4],
[new Interval(0x10880, 0x108AF), "Nabataean", 4],
[new Interval(0x108E0, 0x108FF), "Hatran", 5],
[new Interval(0x10900, 0x1091F), "Phoenician", 4],
[new Interval(0x10920, 0x1093F), "Lydian", 4],
[new Interval(0x10980, 0x1099F), "Meroitic Hieroglyphs", 3],
[new Interval(0x109A0, 0x109FF), "Meroitic Cursive", 3],
[new Interval(0x10A00, 0x10A5F), "Kharoshthi", 5],
[new Interval(0x10A60, 0x10A7F), "Old South Arabian", 4],
[new Interval(0x10A80, 0x10A9F), "Old North Arabian", 4],
[new Interval(0x10AC0, 0x10AFF), "Manichaean", 5],
[new Interval(0x10B00, 0x10B3F), "Avestan", 5],
[new Interval(0x10B40, 0x10B5F), "Inscriptional Parthian", 4],
[new Interval(0x10B60, 0x10B7F), "Inscriptional Pahlavi", 4],
[new Interval(0x10B80, 0x10BAF), "Psalter Pahlavi", 5],
[new Interval(0x10C00, 0x10C4F), "Old Turkic", 4],
[new Interval(0x10C80, 0x10CFF), "Old Hungarian", 4],
[new Interval(0x10E60, 0x10E7F), "Rumi Numeral Symbols", 4],
[new Interval(0x11000, 0x1107F), "Brahmi", 5],
[new Interval(0x11080, 0x110CF), "Kaithi", 5],
[new Interval(0x110D0, 0x110FF), "Sora Sompeng", 5],
[new Interval(0x11100, 0x1114F), "Chakma", 5],
[new Interval(0x11150, 0x1117F), "Mahajani", 5],
[new Interval(0x11180, 0x111DF), "Sharada", 5],
[new Interval(0x111E0, 0x111FF), "Sinhala Archaic Numbers", 4],
[new Interval(0x11200, 0x1124F), "Khojki", 5],
[new Interval(0x11280, 0x112AF), "Multani", 5],
[new Interval(0x112B0, 0x112FF), "Khudawadi", 5],
[new Interval(0x11300, 0x1137F), "Grantha", 5],
[new Interval(0x11400, 0x1147F), "Newa", 5],
[new Interval(0x11480, 0x114DF), "Tirhuta", 5],
[new Interval(0x11580, 0x115FF), "Siddham", 5],
[new Interval(0x11600, 0x1165F), "Modi", 5],
[new Interval(0x11660, 0x1167F), "Mongolian Supplement", 5],
[new Interval(0x11680, 0x116CF), "Takri", 5],
[new Interval(0x11700, 0x1173F), "Ahom", 5],
[new Interval(0x118A0, 0x118FF), "Warang Citi", 5],
[new Interval(0x11A00, 0x11A4F), "Zanabazar Square", 5],
[new Interval(0x11A50, 0x11AAF), "Soyombo", 5],
[new Interval(0x11AC0, 0x11AFF), "Pau Cin Hau", 5],
[new Interval(0x11C00, 0x11C6F), "Bhaiksuki", 5],
[new Interval(0x11C70, 0x11CBF), "Marchen", 5],
[new Interval(0x11D00, 0x11D5F), "Masaram Gondi", 5],
[new Interval(0x12000, 0x123FF), "Cuneiform", 5],
[new Interval(0x12400, 0x1247F), "Cuneiform Numbers and Punctuation", 5],
[new Interval(0x12480, 0x1254F), "Early Dynastic Cuneiform", 4],
[new Interval(0x13000, 0x1342F), "Egyptian Hieroglyphs", 4],
[new Interval(0x14400, 0x1467F), "Anatolian Hieroglyphs", 4],
[new Interval(0x16800, 0x16A3F), "Bamum Supplement", 5],
[new Interval(0x16A40, 0x16A6F), "Mro", 5],
[new Interval(0x16AD0, 0x16AFF), "Bassa Vah", 5],
[new Interval(0x16B00, 0x16B8F), "Pahawh Hmong", 5],
[new Interval(0x16F00, 0x16F9F), "Miao", 5],
[new Interval(0x16FE0, 0x16FFF), "Ideographic Symbols and Punctuation", 4],
[new Interval(0x17000, 0x187FF), "Tangut", 5],
[new Interval(0x18800, 0x18AFF), "Tangut Components", 5],
[new Interval(0x1B000, 0x1B0FF), "Kana Supplement", 5],
[new Interval(0x1B100, 0x1B12F), "Kana Extended-A", 5],
[new Interval(0x1B170, 0x1B2FF), "Nushu", 5],
[new Interval(0x1BC00, 0x1BC9F), "Duployan", 5],
[new Interval(0x1BCA0, 0x1BCAF), "Shorthand Format Controls", 1],
[new Interval(0x1D000, 0x1D0FF), "Byzantine Musical Symbols", 3],
[new Interval(0x1D100, 0x1D1FF), "Musical Symbols", 3],
[new Interval(0x1D200, 0x1D24F), "Ancient Greek Musical Notation", 3],
[new Interval(0x1D300, 0x1D35F), "Tai Xuan Jing Symbols", 5],
[new Interval(0x1D360, 0x1D37F), "Counting Rod Numerals", 2],
[new Interval(0x1D400, 0x1D7FF), "Mathematical Alphanumeric Symbols", 5],
[new Interval(0x1D800, 0x1DAAF), "Sutton SignWriting", 5],
[new Interval(0x1E000, 0x1E02F), "Glagolitic Supplement", 5],
[new Interval(0x1E800, 0x1E8DF), "Mende Kikakui", 5],
[new Interval(0x1E900, 0x1E95F), "Adlam", 5],
[new Interval(0x1EE00, 0x1EEFF), "Arabic Mathematical Alphabetic Symbols", 5],
[new Interval(0x1F000, 0x1F02F), "Mahjong Tiles", 2],
[new Interval(0x1F030, 0x1F09F), "Domino Tiles", 2],
[new Interval(0x1F0A0, 0x1F0FF), "Playing Cards", 2],
[new Interval(0x1F100, 0x1F1FF), "Enclosed Alphanumeric Supplement", 5],
[new Interval(0x1F200, 0x1F2FF), "Enclosed Ideographic Supplement", 5],
[new Interval(0x1F300, 0x1F5FF), "Miscellaneous Symbols and Pictographs", 2],
[new Interval(0x1F600, 0x1F64F), "Emoticons (Emoji)", 2],
[new Interval(0x1F650, 0x1F67F), "Ornamental Dingbats", 2],
[new Interval(0x1F680, 0x1F6FF), "Transport and Map Symbols", 3],
[new Interval(0x1F700, 0x1F77F), "Alchemical Symbols", 3],
[new Interval(0x1F780, 0x1F7FF), "Geometric Shapes Extended", 3],
[new Interval(0x1F800, 0x1F8FF), "Supplemental Arrows-C", 3],
[new Interval(0x1F900, 0x1F9FF), "Supplemental Symbols and Pictographs", 5],
[new Interval(0x20000, 0x2A6DF), "CJK Unified Ideographs Extension B", 5],
[new Interval(0x2A700, 0x2B73F), "CJK Unified Ideographs Extension C", 5],
[new Interval(0x2B740, 0x2B81F), "CJK Unified Ideographs Extension D", 5],
[new Interval(0x2B820, 0x2CEAF), "CJK Unified Ideographs Extension E", 5],
[new Interval(0x2CEB0, 0x2EBEF), "CJK Unified Ideographs Extension F", 5],
[new Interval(0x2F800, 0x2FA1F), "CJK Compatibility Ideographs Supplement", 5],
[new Interval(0xE0000, 0xE007F), "Tags", 1],
[new Interval(0xE0100, 0xE01EF), "Variation Selectors Supplement", 1],
];
let predefinedWeightSum = 0;
let assignedIntervals: IntervalSet;
export const FULL_UNICODE_SET = new IntervalSet([new Interval(0, 0x10FFFF)]);
export interface UnicodeOptions {
// The CJK scripts consist of so many code points, any generated random string will contain mostly CJK
// characters (Chinese/Japanese/Korean), if not excluded. However, only the largest scripts are
// removed by this setting, namely:
// - CJK Unified Ideographs (+ Extension A)
// - Yi Syllables
// - Hangul Syllables
// - CJK Compatibility Ideographs
excludeCJK?: boolean;
// Right-to-left characters don't fit well in the standard left-to-right direction, especially when
// generated randomly, so allow excluding them as well.
excludeRTL?: boolean;
// Exclude any character beyond the basic multilingual pane (0x10000 and higher).
limitToBMP?: boolean;
// When set to true include all Unicode line terminators (LF, VT, FF, CR, NEL, LS, PS) as valid output.
includeLineTerminators?: boolean;
}
/**
* Creates an interval set with all printable Unicode characters.
*
* @param options Values that specify the Unicode set to create.
*
* @returns A set of intervals with the requested Unicode code points.
*/
export const printableUnicodePoints = (options: UnicodeOptions): IntervalSet => {
if (!assignedIntervals) {
// Create a set with all Unicode code points that are assigned and not in categories with unprintable chars,
// surrogate pairs, formatting + private codes.
let intervalsToExclude = codePointsToIntervals("General_Category/Unassigned/code-points.js");
intervalsToExclude = codePointsToIntervals("General_Category/Control/code-points.js", intervalsToExclude);
intervalsToExclude = codePointsToIntervals("General_Category/Format/code-points.js", intervalsToExclude);
intervalsToExclude = codePointsToIntervals("General_Category/Surrogate/code-points.js", intervalsToExclude);
intervalsToExclude = codePointsToIntervals("General_Category/Private_Use/code-points.js", intervalsToExclude);
if (options.excludeCJK) {
intervalsToExclude = codePointsToIntervals("Block/CJK_Unified_Ideographs/code-points.js",
intervalsToExclude);
intervalsToExclude = codePointsToIntervals("Block/CJK_Unified_Ideographs_Extension_A/code-points.js",
intervalsToExclude);
intervalsToExclude = codePointsToIntervals("Block/CJK_Compatibility_Ideographs/code-points.js",
intervalsToExclude);
intervalsToExclude = codePointsToIntervals("Block/Hangul_Syllables/code-points.js", intervalsToExclude);
intervalsToExclude = codePointsToIntervals("Block/Yi_Syllables/code-points.js", intervalsToExclude);
}
if (options.excludeRTL) {
// Note: there are also a few top-to-bottom scripts (e.g. mongolian), but these are not considered here.
intervalsToExclude = codePointsToIntervals("Bidi_Class/Right_To_Left/code-points.js", intervalsToExclude);
intervalsToExclude = codePointsToIntervals("Bidi_Class/Right_To_Left_Embedding/code-points.js",
intervalsToExclude);
intervalsToExclude = codePointsToIntervals("Bidi_Class/Right_To_Left_Isolate/code-points.js",
intervalsToExclude);
intervalsToExclude = codePointsToIntervals("Bidi_Class/Right_To_Left_Override/code-points.js",
intervalsToExclude);
}
if (options.includeLineTerminators) {
// Unicode line terminators are implicitly taken out by the above code, so we add them in here.
intervalsToExclude.remove(0x0A); // NL, New Line.
intervalsToExclude.remove(0x0B); // VT, Vertical Tab
intervalsToExclude.remove(0x0C); // FF, Form Feed
intervalsToExclude.remove(0x0D); // CR, Carriage Return
intervalsToExclude.remove(0x85); // NEL, Next Line
intervalsToExclude.remove(0x2028); // LS, Line Separator
intervalsToExclude.remove(0x2029); // PS, Paragraph Separator
}
let sourceIntervals: IntervalSet;
if (options.limitToBMP) {
sourceIntervals = IntervalSet.COMPLETE_CHAR_SET;
} else {
sourceIntervals = FULL_UNICODE_SET;
}
assignedIntervals = intervalsToExclude.complement(sourceIntervals);
}
return assignedIntervals;
};
/**
* Returns a random Unicode code block, based on the predefined weights and the overrides given as parameter.
*
* @param blockOverrides Optionally contains name/value pairs to specify custom weights for code blocks.
*
* @returns An interval containing start and stop values for a random code block.
*/
export const randomCodeBlock = (blockOverrides?: Map<string, number>): Interval => {
if (predefinedWeightSum === 0) {
for (const entry of UnicodeBlocks) {
predefinedWeightSum += entry[2];
}
}
let weightSum = 0;
if (!blockOverrides) {
weightSum = predefinedWeightSum;
} else {
for (const entry of UnicodeBlocks) {
if (blockOverrides.has(entry[1])) {
weightSum += blockOverrides.get(entry[1])!;
} else {
weightSum += entry[2];
}
}
}
let randomValue = Math.random() * weightSum;
for (const entry of UnicodeBlocks) {
let weight = entry[2];
if (blockOverrides && blockOverrides.has(entry[1])) {
weight = blockOverrides.get(entry[1])!;
}
randomValue -= weight;
if (randomValue < 0) {
return entry[0];
}
}
return new Interval(0, 0);
};
/**
* Converts the code points from the given file to an interval set.
*
* @param dataFile The name of a file to import.
* @param existing Optionally specifies an interval set with previously red values (to merge with the new ones).
*
* @returns A new set of Unicode code points.
*/
const codePointsToIntervals = (dataFile: string, existing?: IntervalSet): IntervalSet => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-var-requires
const charsToExclude: number[] = require("unicode-11.0.0/" + dataFile);
const result = existing ?? new IntervalSet([]);
// Code points are sorted in increasing order, which we can use to speed up insertion.
let start = charsToExclude[0];
let end = start;
for (let i = 1; i < charsToExclude.length; ++i) {
const code = charsToExclude[i];
if (end + 1 === code) {
++end;
continue;
}
result.add(start, end);
start = code;
end = code;
}
result.add(start, end);
return result;
}; | the_stack |
import _ from 'lodash';
import {
address,
BigNumberable,
} from '../src/lib/types';
import initializePerpetual from './helpers/initializePerpetual';
import { ITestContext, perpetualDescribe } from './helpers/perpetualDescribe';
import { expect, expectBN, expectThrow } from './helpers/Expect';
import { expectMarginBalances, mintAndDeposit } from './helpers/balances';
// Mock parameters.
const initialNonNativeBalance = 125e6;
const nonNativeAmount = 25e6;
const marginAmount = 50e18;
let admin: address;
let account: address;
let otherAddress: address;
let proxyAddress: address;
let exchangeWrapperAddress: address;
// The margin token is the token used as margin/collateral in the PerpetualV1 contract.
let marginToken: address;
// The non-native token is some other token not used within the PerpetualV1 contract.
let nonNativeToken: address;
async function init(ctx: ITestContext): Promise<void> {
await initializePerpetual(ctx);
admin = ctx.accounts[0];
// Default account is accounts[1]. Use other accounts.
account = ctx.accounts[2];
otherAddress = ctx.accounts[3];
proxyAddress = ctx.perpetual.contracts.p1CurrencyConverterProxy.options.address;
exchangeWrapperAddress = ctx.perpetual.testing.exchangeWrapper.address;
marginToken = ctx.perpetual.contracts.testToken.options.address;
nonNativeToken = ctx.perpetual.contracts.testToken2.options.address;
await Promise.all([
// Set allowance on Perpetual for the proxy.
ctx.perpetual.currencyConverterProxy.approveMaximumOnPerpetual(),
// Set allowance on proxy for the account.
ctx.perpetual.token.setMaximumAllowance(
nonNativeToken,
account,
proxyAddress,
),
// Fund the account owner with non-native token.
ctx.perpetual.testing.token.mint(
nonNativeToken,
account,
initialNonNativeBalance,
),
// Fund the exchange wrapper with both tokens.
ctx.perpetual.testing.token.mint(
marginToken,
exchangeWrapperAddress,
1000e18,
),
ctx.perpetual.testing.token.mint(
nonNativeToken,
exchangeWrapperAddress,
1000e6,
),
]);
}
perpetualDescribe('P1CurrencyConverterProxy', init, (ctx: ITestContext) => {
describe('deposit()', () => {
beforeEach(async () => {
// Set test data.
await ctx.perpetual.testing.exchangeWrapper.setMakerAmount(marginAmount);
});
it('deposits', async () => {
// Call the function.
const txResult = await ctx.perpetual.currencyConverterProxy.deposit(
account,
exchangeWrapperAddress,
nonNativeToken,
nonNativeAmount,
getTestOrderData(nonNativeAmount),
{ from: account },
);
// Check balances.
await Promise.all([
expectNonNativeBalances(
[account],
[initialNonNativeBalance - nonNativeAmount],
),
expectMarginBalances(ctx, txResult, [account], [marginAmount]),
expectProxyNoBalances(),
]);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
const filteredLogs = logs.filter(log => log.name === 'LogConvertedDeposit');
expect(filteredLogs.length).to.equal(1);
const log = filteredLogs[0];
expect(log.name).to.equal('LogConvertedDeposit');
expect(log.args.account).to.equal(account);
expect(log.args.source).to.equal(account);
expect(log.args.perpetual).to.equal(ctx.perpetual.contracts.perpetualProxy.options.address);
expect(log.args.exchangeWrapper).to.equal(exchangeWrapperAddress);
expect(log.args.tokenFrom).to.equal(nonNativeToken);
expect(log.args.tokenTo).to.equal(marginToken);
expectBN(log.args.tokenFromAmount).to.equal(nonNativeAmount);
expectBN(log.args.tokenToAmount).to.equal(marginAmount);
});
it('deposits from a sender that is not the account owner', async () => {
// Set allowance on proxy for the other account.
await ctx.perpetual.token.setMaximumAllowance(
nonNativeToken,
otherAddress,
proxyAddress,
);
// Fund the other account with non-native token.
await ctx.perpetual.testing.token.mint(
nonNativeToken,
otherAddress,
nonNativeAmount,
);
// Call the function.
const txResult = await ctx.perpetual.currencyConverterProxy.deposit(
account,
exchangeWrapperAddress,
nonNativeToken,
nonNativeAmount,
getTestOrderData(nonNativeAmount),
{ from: otherAddress },
);
// Check balances.
await Promise.all([
expectNonNativeBalances([account, otherAddress], [initialNonNativeBalance, 0]),
await expectMarginBalances(ctx, txResult, [account], [marginAmount]),
await expectProxyNoBalances(),
]);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
const filteredLogs = logs.filter(log => log.name === 'LogConvertedDeposit');
expect(filteredLogs.length).to.equal(1);
const log = filteredLogs[0];
expect(log.name).to.equal('LogConvertedDeposit');
expect(log.args.account).to.equal(account);
expect(log.args.source).to.equal(otherAddress);
expect(log.args.perpetual).to.equal(ctx.perpetual.contracts.perpetualProxy.options.address);
expect(log.args.exchangeWrapper).to.equal(exchangeWrapperAddress);
expect(log.args.tokenFrom).to.equal(nonNativeToken);
expect(log.args.tokenTo).to.equal(marginToken);
expectBN(log.args.tokenFromAmount).to.equal(nonNativeAmount);
expectBN(log.args.tokenToAmount).to.equal(marginAmount);
});
it('returns the amount deposited after the conversion (when using eth_call)', async () => {
const toTokenAmount = await ctx.perpetual.currencyConverterProxy.getDepositConvertedAmount(
account,
exchangeWrapperAddress,
nonNativeToken,
nonNativeAmount,
getTestOrderData(nonNativeAmount),
{ from: account },
);
expectBN(toTokenAmount).to.equal(marginAmount);
});
});
describe('withdraw()', () => {
beforeEach(async () => {
await Promise.all([
// Add margin funds to the Perpetual account.
mintAndDeposit(ctx, account, marginAmount),
// Set test data.
ctx.perpetual.testing.exchangeWrapper.setMakerAmount(nonNativeAmount),
]);
});
it('withdraws', async () => {
// Call the function.
const txResult = await ctx.perpetual.currencyConverterProxy.withdraw(
account,
account,
exchangeWrapperAddress,
nonNativeToken,
marginAmount,
getTestOrderData(marginAmount),
{ from: account },
);
// Check balances.
await Promise.all([
expectNonNativeBalances(
[account],
[initialNonNativeBalance + nonNativeAmount],
),
expectMarginBalances(ctx, txResult, [account], [0]),
expectProxyNoBalances(),
]);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
const filteredLogs = logs.filter(log => log.name === 'LogConvertedWithdrawal');
expect(filteredLogs.length).to.equal(1);
const log = filteredLogs[0];
expect(log.name).to.equal('LogConvertedWithdrawal');
expect(log.args.account).to.equal(account);
expect(log.args.destination).to.equal(account);
expect(log.args.perpetual).to.equal(ctx.perpetual.contracts.perpetualProxy.options.address);
expect(log.args.exchangeWrapper).to.equal(exchangeWrapperAddress);
expect(log.args.tokenFrom).to.equal(marginToken);
expect(log.args.tokenTo).to.equal(nonNativeToken);
expectBN(log.args.tokenFromAmount).to.equal(marginAmount);
expectBN(log.args.tokenToAmount).to.equal(nonNativeAmount);
});
it('withdraws to another destination', async () => {
// Call the function.
const txResult = await ctx.perpetual.currencyConverterProxy.withdraw(
account,
otherAddress,
exchangeWrapperAddress,
nonNativeToken,
marginAmount,
getTestOrderData(marginAmount),
{ from: account },
);
// Check balances.
await Promise.all([
expectNonNativeBalances(
[account, otherAddress],
[initialNonNativeBalance, nonNativeAmount],
),
expectMarginBalances(ctx, txResult, [account, otherAddress], [0, 0]),
expectProxyNoBalances(),
]);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
const filteredLogs = logs.filter(log => log.name === 'LogConvertedWithdrawal');
expect(filteredLogs.length).to.equal(1);
const log = filteredLogs[0];
expect(log.name).to.equal('LogConvertedWithdrawal');
expect(log.args.account).to.equal(account);
expect(log.args.destination).to.equal(otherAddress);
expect(log.args.perpetual).to.equal(ctx.perpetual.contracts.perpetualProxy.options.address);
expect(log.args.exchangeWrapper).to.equal(exchangeWrapperAddress);
expect(log.args.tokenFrom).to.equal(marginToken);
expect(log.args.tokenTo).to.equal(nonNativeToken);
expectBN(log.args.tokenFromAmount).to.equal(marginAmount);
expectBN(log.args.tokenToAmount).to.equal(nonNativeAmount);
});
describe('withdrawal permissions', () => {
it('succeeds if the sender is a local operator', async () => {
// Set local operator.
await ctx.perpetual.operator.setLocalOperator(otherAddress, true, { from: account });
// Call the function.
const txResult = await ctx.perpetual.currencyConverterProxy.withdraw(
account,
account,
exchangeWrapperAddress,
nonNativeToken,
marginAmount,
getTestOrderData(marginAmount),
{ from: otherAddress },
);
// Check balances.
await Promise.all([
expectNonNativeBalances(
[account],
[initialNonNativeBalance + nonNativeAmount],
),
expectMarginBalances(ctx, txResult, [account], [0]),
expectProxyNoBalances(),
]);
});
it('succeeds if the sender is a global operator', async () => {
// Set global operator.
await ctx.perpetual.admin.setGlobalOperator(otherAddress, true, { from: admin });
// Call the function.
const txResult = await ctx.perpetual.currencyConverterProxy.withdraw(
account,
account,
exchangeWrapperAddress,
nonNativeToken,
marginAmount,
getTestOrderData(marginAmount),
{ from: otherAddress },
);
// Check balances.
await Promise.all([
expectNonNativeBalances(
[account],
[initialNonNativeBalance + nonNativeAmount],
),
expectMarginBalances(ctx, txResult, [account], [0]),
expectProxyNoBalances(),
]);
});
it('fails if the sender is not the account owner or operator', async () => {
// Call the function.
await expectThrow(
ctx.perpetual.currencyConverterProxy.withdraw(
account,
account,
exchangeWrapperAddress,
nonNativeToken,
marginAmount,
getTestOrderData(marginAmount),
{ from: otherAddress },
),
'msg.sender cannot operate the account',
);
});
});
it('returns the amount withdrawn after the conversion (when using eth_call)', async () => {
const toTokenAmount = await ctx.perpetual.currencyConverterProxy.getWithdrawConvertedAmount(
account,
otherAddress,
exchangeWrapperAddress,
nonNativeToken,
marginAmount,
getTestOrderData(marginAmount),
{ from: account },
);
expectBN(toTokenAmount).to.equal(nonNativeAmount);
});
});
/**
* Check non-native token balances.
*/
async function expectNonNativeBalances(
accounts: address[],
expectedBalances: BigNumberable[],
): Promise<void> {
const actualBalances = await Promise.all(accounts.map((account: address) => {
return ctx.perpetual.token.getBalance(nonNativeToken, account);
}));
for (const i in expectedBalances) {
const expectedBalance = expectedBalances[i];
expectBN(actualBalances[i], `accounts[${i}] non-native balance`).to.equal(expectedBalance);
}
}
/**
* Verify that the proxy contract does not have any token balances.
*/
async function expectProxyNoBalances(): Promise<void> {
const balances = await Promise.all([
ctx.perpetual.token.getBalance(
marginToken,
proxyAddress,
),
ctx.perpetual.token.getBalance(
nonNativeToken,
proxyAddress,
),
]);
expectBN(balances[0], 'proxy margin token balance').to.equal(0);
expectBN(balances[1], 'proxy non-native token balance').to.equal(0);
}
/**
* Construct a data string for use with the test exchange wrapper.
*/
function getTestOrderData(
amount: BigNumberable,
): string {
return ctx.perpetual.testing.exchangeWrapper.testOrderToBytes({ amount });
}
}); | the_stack |
import {buildColFilter} from 'app/common/ColumnFilterFunc';
import {RowRecord} from 'app/common/DocActions';
import {DocData} from 'app/common/DocData';
import * as gristTypes from 'app/common/gristTypes';
import * as gutil from 'app/common/gutil';
import {buildRowFilter} from 'app/common/RowFilterFunc';
import {SchemaTypes} from 'app/common/schema';
import {SortFunc} from 'app/common/SortFunc';
import {TableData} from 'app/common/TableData';
import {DocumentSettings} from 'app/common/DocumentSettings';
import {ActiveDoc} from 'app/server/lib/ActiveDoc';
import {RequestWithLogin} from 'app/server/lib/Authorizer';
import {docSessionFromRequest} from 'app/server/lib/DocSession';
import {optIntegerParam, optJsonParam, stringParam} from 'app/server/lib/requestUtils';
import {ServerColumnGetters} from 'app/server/lib/ServerColumnGetters';
import * as express from 'express';
import * as _ from 'underscore';
// Helper type for Cell Accessor
type Access = (row: number) => any;
// Helper interface with information about the column
interface ExportColumn {
id: number;
colId: string;
label: string;
type: string;
widgetOptions: any;
parentPos: number;
}
// helper for empty column
const emptyCol: ExportColumn = {
id: 0,
colId: '',
label: '',
type: '',
widgetOptions: null,
parentPos: 0
};
/**
* Bare data that is exported - used to convert to various formats.
*/
export interface ExportData {
/**
* Table name or table id.
*/
tableName: string;
/**
* Document name.
*/
docName: string;
/**
* Row ids (filtered and sorted).
*/
rowIds: number[];
/**
* Accessor for value in a column.
*/
access: Access[];
/**
* Columns information (primary used for formatting).
*/
columns: ExportColumn[];
/**
* Document settings
*/
docSettings: DocumentSettings;
}
/**
* Export parameters that identifies a section, filters, sort order.
*/
export interface ExportParameters {
tableId: string;
viewSectionId: number | undefined;
sortOrder: number[];
filters: Filter[];
}
/**
* Gets export parameters from a request.
*/
export function parseExportParameters(req: express.Request): ExportParameters {
const tableId = stringParam(req.query.tableId);
const viewSectionId = optIntegerParam(req.query.viewSection);
const sortOrder = optJsonParam(req.query.activeSortSpec, []) as number[];
const filters: Filter[] = optJsonParam(req.query.filters, []);
return {
tableId,
viewSectionId,
sortOrder,
filters
};
}
// Makes assertion that value does exists or throws an error
function safe<T>(value: T, msg: string) {
if (!value) { throw new Error(msg); }
return value as NonNullable<T>;
}
// Helper to for getting table from docData.
const safeTable = (docData: DocData, name: keyof SchemaTypes) => safe(docData.getTable(name),
`No table '${name}' in document with id ${docData}`);
// Helper for getting record safe
const safeRecord = (table: TableData, id: number) => safe(table.getRecord(id),
`No record ${id} in table ${table.tableId}`);
/**
* Builds export for all raw tables that are in doc.
* @param activeDoc Active document
* @param req Request
*/
export async function exportDoc(
activeDoc: ActiveDoc,
req: express.Request) {
const docData = safe(activeDoc.docData, "No docData in active document");
const tables = safeTable(docData, '_grist_Tables');
// select raw tables
const tableIds = tables.filterRowIds({ summarySourceTable: 0 });
const tableExports = await Promise.all(
tableIds
.map(tId => exportTable(activeDoc, tId, req))
);
return tableExports;
}
/**
* Builds export data for section that can be used to produce files in various formats (csv, xlsx).
*/
export async function exportTable(
activeDoc: ActiveDoc,
tableId: number,
req: express.Request): Promise<ExportData> {
const docData = safe(activeDoc.docData, "No docData in active document");
const tables = safeTable(docData, '_grist_Tables');
const table = safeRecord(tables, tableId) as GristTables;
const tableColumns = (safeTable(docData, '_grist_Tables_column')
.getRecords() as GristTablesColumn[])
// remove manual sort column
.filter(col => col.colId !== gristTypes.MANUALSORT);
// Produce a column description matching what user will see / expect to export
const tableColsById = _.indexBy(tableColumns, 'id');
const columns = tableColumns.map(tc => {
// remove all columns that don't belong to this table
if (tc.parentId !== tableId) {
return emptyCol;
}
// remove all helpers
if (gristTypes.isHiddenCol(tc.colId)) {
return emptyCol;
}
// for reference columns, return display column, and copy settings from visible column
const displayCol = tableColsById[tc.displayCol || tc.id];
const colOptions = gutil.safeJsonParse(tc.widgetOptions, {});
const displayOptions = gutil.safeJsonParse(displayCol.widgetOptions, {});
const widgetOptions = Object.assign(displayOptions, colOptions);
return {
id: displayCol.id,
colId: displayCol.colId,
label: tc.label,
type: displayCol.type,
widgetOptions,
parentPos: tc.parentPos
};
}).filter(tc => tc !== emptyCol);
// fetch actual data
const data = await activeDoc.fetchTable(docSessionFromRequest(req as RequestWithLogin), table.tableId, true);
const rowIds = data[2];
const dataByColId = data[3];
// sort rows
const getters = new ServerColumnGetters(rowIds, dataByColId, columns);
// create cell accessors
const access = columns.map(col => getters.getColGetter(col.id)!);
let tableName = table.tableId;
// since tables ids are not very friendly, borrow name from a primary view
if (table.primaryViewId) {
const viewId = table.primaryViewId;
const views = safeTable(docData, '_grist_Views');
const view = safeRecord(views, viewId) as GristView;
tableName = view.name;
}
const docInfo = safeRecord(safeTable(docData, '_grist_DocInfo'), 1) as DocInfo;
const docSettings = gutil.safeJsonParse(docInfo.documentSettings, {});
return {
tableName,
docName: activeDoc.docName,
rowIds,
access,
columns,
docSettings
};
}
/**
* Builds export data for section that can be used to produce files in various formats (csv, xlsx).
*/
export async function exportSection(
activeDoc: ActiveDoc,
viewSectionId: number,
sortOrder: number[] | null,
filters: Filter[] | null,
req: express.Request): Promise<ExportData> {
const docData = safe(activeDoc.docData, "No docData in active document");
const viewSections = safeTable(docData, '_grist_Views_section');
const viewSection = safeRecord(viewSections, viewSectionId) as GristViewsSection;
const tables = safeTable(docData, '_grist_Tables');
const table = safeRecord(tables, viewSection.tableRef) as GristTables;
const columns = safeTable(docData, '_grist_Tables_column')
.filterRecords({ parentId: table.id }) as GristTablesColumn[];
const viewSectionFields = safeTable(docData, '_grist_Views_section_field');
const fields = viewSectionFields.filterRecords({ parentId: viewSection.id }) as GristViewsSectionField[];
const tableColsById = _.indexBy(columns, 'id');
// Produce a column description matching what user will see / expect to export
const viewify = (col: GristTablesColumn, field: GristViewsSectionField) => {
field = field || {};
const displayCol = tableColsById[field.displayCol || col.displayCol || col.id];
const colWidgetOptions = gutil.safeJsonParse(col.widgetOptions, {});
const fieldWidgetOptions = gutil.safeJsonParse(field.widgetOptions, {});
const filterString = (filters || []).find(x => x.colRef === field.colRef)?.filter || field.filter;
const filterFunc = buildColFilter(filterString, col.type);
return {
id: displayCol.id,
colId: displayCol.colId,
label: col.label,
type: col.type,
parentPos: col.parentPos,
filterFunc,
widgetOptions: Object.assign(colWidgetOptions, fieldWidgetOptions)
};
};
const viewColumns = _.sortBy(fields, 'parentPos').map(
(field) => viewify(tableColsById[field.colRef], field));
// The columns named in sort order need to now become display columns
sortOrder = sortOrder || gutil.safeJsonParse(viewSection.sortColRefs, []);
const fieldsByColRef = _.indexBy(fields, 'colRef');
sortOrder = sortOrder!.map((directionalColRef) => {
const colRef = Math.abs(directionalColRef);
const col = tableColsById[colRef];
if (!col) {
return 0;
}
const effectiveColRef = viewify(col, fieldsByColRef[colRef]).id;
return directionalColRef > 0 ? effectiveColRef : -effectiveColRef;
});
// fetch actual data
const data = await activeDoc.fetchTable(docSessionFromRequest(req as RequestWithLogin), table.tableId, true);
let rowIds = data[2];
const dataByColId = data[3];
// sort rows
const getters = new ServerColumnGetters(rowIds, dataByColId, columns);
const sorter = new SortFunc(getters);
sorter.updateSpec(sortOrder);
rowIds.sort((a, b) => sorter.compare(a, b));
// create cell accessors
const access = viewColumns.map(col => getters.getColGetter(col.id)!);
// create row filter based on all columns filter
const rowFilter = viewColumns
.map((col, c) => buildRowFilter(access[c], col.filterFunc))
.reduce((prevFilter, curFilter) => (id) => prevFilter(id) && curFilter(id), () => true);
// filter rows numbers
rowIds = rowIds.filter(rowFilter);
const docInfo = safeRecord(safeTable(docData, '_grist_DocInfo'), 1) as DocInfo;
const docSettings = gutil.safeJsonParse(docInfo.documentSettings, {});
return {
tableName: table.tableId,
docName: activeDoc.docName,
rowIds,
access,
docSettings,
columns: viewColumns
};
}
// Type helpers for types used in this export
type RowModel<TName extends keyof SchemaTypes> = RowRecord & {
[ColId in keyof SchemaTypes[TName]]: SchemaTypes[TName][ColId];
};
type GristViewsSection = RowModel<'_grist_Views_section'>
type GristTables = RowModel<'_grist_Tables'>
type GristViewsSectionField = RowModel<'_grist_Views_section_field'>
type GristTablesColumn = RowModel<'_grist_Tables_column'>
type GristView = RowModel<'_grist_Views'>
type DocInfo = RowModel<'_grist_DocInfo'>
// Type for filters passed from the client
export interface Filter { colRef: number, filter: string } | the_stack |
import {DictValue} from './units';
import {ClearCacheOptions, DispatchOptions} from './operations';
/**
* The common events that every fundamental ActiveJS construct (Units, Systems, Action and Cluster) emits.
* @event
* @category Common
*/
export type BaseEvents<T> = EventReplay<T>;
/**
* The common events that are emitted by all the Units.
* @event
* @category Common Units
*/
export type UnitEvents<T> =
| BaseEvents<T>
| EventUnitDispatch<T>
| EventUnitDispatchFail<T>
| EventUnitUnmute
| EventUnitFreeze
| EventUnitUnfreeze
| EventUnitJump
| EventUnitClearCache
| EventUnitClearValue
| EventUnitClear
| EventUnitResetValue
| EventUnitReset
| EventUnitClearPersistedValue;
/**
* The events that are triggered by a DictUnit.
* @event
* @category DictUnit
*/
export type DictUnitEvents<
T extends DictValue<any>,
K extends keyof T = keyof T,
V extends T[K] = T[K]
> = UnitEvents<T> | EventDictUnitSet<K, V> | EventDictUnitDelete<T> | EventDictUnitAssign<T>;
/**
* The events that are emitted by a ListUnit.
* @event
* @category ListUnit
*/
export type ListUnitEvents<Item> =
| UnitEvents<Item[]>
| EventListUnitSet<Item>
| EventListUnitPop<Item>
| EventListUnitPush<Item>
| EventListUnitShift<Item>
| EventListUnitUnshift<Item>
| EventListUnitDelete<Item>
| EventListUnitRemove<Item>
| EventListUnitSplice<Item>
| EventListUnitFill<Item>
| EventListUnitCopyWithin<Item>
| EventListUnitReverse
| EventListUnitSort;
// ____________________________ Common Events ____________________________ //
// _______________________________________________________________________ //
/**
* An event that gets emitted on successful replay by using the `replay` method.
* @event
* @category Common
*/
export class EventReplay<T> {
/**
* @param value The current value that got replayed.
*/
constructor(public value: T) {}
}
// _________________________ Common Units Events _________________________ //
// _______________________________________________________________________ //
/**
* An event that gets emitted on successful dispatch by using the Units' `dispatch` method.
* @event
* @category Common Units
*/
export class EventUnitDispatch<T> {
/**
* @param value The value that was passed to the dispatch method.
* @param options The options that were passed to the dispatch method.
*/
constructor(public value: T, public options?: DispatchOptions) {}
}
/**
* All the reasons for why a Unit dispatch might fail.
*/
export enum DispatchFailReason {
/**
* The first reason, if the Unit is frozen.
*/
FROZEN_UNIT = 'FROZEN_UNIT',
/**
* The second reason, if the dispatched value is invalid.
*/
INVALID_VALUE = 'INVALID_VALUE',
/**
* The third reason, if {@link UnitConfig.customDispatchCheck} returns a `falsy` value.
*/
CUSTOM_DISPATCH_CHECK = 'CUSTOM_DISPATCH_CHECK',
/**
* The fourth reason, if {@link UnitConfig.distinctDispatchCheck} is not `false` and the dispatched value is same as current value.
*/
DISTINCT_CHECK = 'DISTINCT_CHECK',
}
/**
* An event that gets emitted on failed dispatch using the Units' `dispatch` method.
* @event
* @category Common Units
*/
export class EventUnitDispatchFail<T> {
/**
* @param value The value that was passed to the dispatch method.
* @param reason The reason for why the dispatch failed.
* @param options The options that were passed to the dispatch method.
*/
constructor(
public value: T,
public reason: DispatchFailReason,
public options?: DispatchOptions
) {}
}
/**
* An event that gets emitted on successful unmute using the Units' `unmute` method.
* @event
* @category Common Units
*/
export class EventUnitUnmute {}
/**
* An event that gets emitted when a Unit gets frozen.
* @event
* @category Common Units
*/
export class EventUnitFreeze {}
/**
* An event that gets emitted when a Unit gets unfrozen after being frozen.
* @event
* @category Common Units
*/
export class EventUnitUnfreeze {}
/**
* An event that gets emitted on successful cache-navigation,
* using the Units' several cache-navigation methods like `goBack`, `goForward`, `jump`, etc.
* @event
* @category Common Units
*/
export class EventUnitJump {
/**
* @param steps The number of steps jumped represented as a number,
* positive for forward navigation and negative for backwards.
* @param newCacheIndex The new `cacheIndex` of the emitted value.
*/
constructor(public steps: number, public newCacheIndex: number) {}
}
/**
* An event that gets emitted on successful execution of Units' `clearCache` method.
* @event
* @category Common Units
*/
export class EventUnitClearCache {
/**
* @param options The options that were directly or indirectly passed to the `clearCache` method.
*/
constructor(public options?: ClearCacheOptions) {}
}
/**
* An event that gets emitted on successful execution of Units' `clearValue` method.
* @event
* @category Common Units
*/
export class EventUnitClearValue {}
/**
* An event that gets emitted on successful execution of Units' `clear` method.
* @event
* @category Common Units
*/
export class EventUnitClear {
/**
* @param options The options that were passed for the implicitly called `clearCache` method.
*/
constructor(public options?: ClearCacheOptions) {}
}
/**
* An event that gets emitted on successful execution of Units' `resetValue` method.
* @event
* @category Common Units
*/
export class EventUnitResetValue {}
/**
* An event that gets emitted on successful execution of Units' `reset` method.
* @event
* @category Common Units
*/
export class EventUnitReset {
/**
* @param options The options that were passed for the implicitly called `clearCache` method.
*/
constructor(public options?: ClearCacheOptions) {}
}
/**
* An event that gets emitted on successful execution of Units' `clearPersistentValue` method.
* @event
* @category Common Units
*/
export class EventUnitClearPersistedValue {}
// ____________________________ DictUnit Events ____________________________ //
// _________________________________________________________________________ //
/**
* An event that gets emitted on successful execution of DictUnit's `set` method.
* @event
* @category DictUnit
*/
export class EventDictUnitSet<K, V> {
/**
* @param key The name of the property that was passed to the `set` method.
* @param value The value of the property that was passed to the `set` method.
*/
constructor(public key: K, public value: V) {}
}
/**
* An event that gets emitted on successful execution of DictUnit's `assign` method.
* @event
* @category DictUnit
*/
export class EventDictUnitAssign<T> {
/**
* @param sources The source objects that were passed to the `assign` method.
* @param newProps The new properties that finally got added to the DictUnit's value.
*/
constructor(public sources: T[], public newProps: T) {}
}
/**
* An event that gets emitted on successful execution of DictUnit's `delete` or `deleteIf` method.
* @event
* @category DictUnit
*/
export class EventDictUnitDelete<T> {
/**
* @param deletedProps The properties that were deleted by the `delete` or `deleteIf` method.
*/
constructor(public deletedProps: T) {}
}
// ____________________________ ListUnit Events ____________________________ //
// _________________________________________________________________________ //
/**
* An event that gets emitted on successful execution of ListUnit's `set` method.
* @event
* @category ListUnit
*/
export class EventListUnitSet<Item> {
/**
* @param index The index for the item passed to the `set` method.
* @param item The item passed to the `set` method.
*/
constructor(public index: number, public item: Item) {}
}
/**
* An event that gets emitted on successful execution of ListUnit's `pop` method.
* @event
* @category ListUnit
*/
export class EventListUnitPop<Item> {
/**
* @param item The item that got popped from the ListUnit's value.
*/
constructor(public item: Item) {}
}
/**
* An event that gets emitted on successful execution of ListUnit's `push` method.
* @event
* @category ListUnit
*/
export class EventListUnitPush<Item> {
/**
* @param items The items that were passed to the `push` method.
*/
constructor(public items: Item[]) {}
}
/**
* An event that gets emitted on successful execution of ListUnit's `shift` method.
* @event
* @category ListUnit
*/
export class EventListUnitShift<Item> {
/**
* @param item The item that got shifted out.
*/
constructor(public item: Item) {}
}
/**
* An event that gets emitted on successful execution of ListUnit's `unshift` method.
* @event
* @category ListUnit
*/
export class EventListUnitUnshift<Item> {
/**
* @param items The items that were passed to the `unshift` method.
*/
constructor(public items: Item[]) {}
}
/**
* An event that gets emitted on successful execution of ListUnit's `delete` or `deleteIf` method.
* @event
* @category ListUnit
*/
export class EventListUnitDelete<Item> {
/**
* @param indices The indices that were passed to the `delete` method explicitly,
* or implicitly by `deleteIf` method.
* @param deletedItems The items that got deleted from the ListUnit's value.
*/
constructor(public indices: number[], public deletedItems: Item[]) {}
}
/**
* An event that gets emitted on successful execution of ListUnit's `remove` or `removeIf` method.
* @event
* @category ListUnit
*/
export class EventListUnitRemove<Item> {
/**
* @param indices The indices that were passed to the `remove` method explicitly,
* or implicitly by `removeIf` method.
* @param removedItems The items that got removed from the ListUnit's value.
*/
constructor(public indices: number[], public removedItems: Item[]) {}
}
/**
* An event that gets emitted on successful execution of ListUnit's `splice` or `insert` method.
* @event
* @category ListUnit
*/
export class EventListUnitSplice<Item> {
/**
* @param start The zero-based location that was passed to the `splice` method.
* @param deleteCount The number of items that were to be removed.
* @param removedItems The items that got removed.
* @param addedItems The items that were passed as `items` to be added.
*/
constructor(
public start: number,
public deleteCount: number,
public removedItems: Item[],
public addedItems: Item[]
) {}
}
/**
* An event that gets emitted on successful execution of ListUnit's `fill` method.
* @event
* @category ListUnit
*/
export class EventListUnitFill<Item> {
/**
* @param item The item that was passed to the `fill` method.
* @param start The starting position where the filling started.
* @param end The last position where the filling stopped.
*/
constructor(public item: Item, public start?: number, public end?: number) {}
}
/**
* An event that gets emitted on successful execution of ListUnit's `copyWithin` method.
* @event
* @category ListUnit
*/
export class EventListUnitCopyWithin<Item> {
/**
* @param target The target position from where the copied section starts replacing.
* @param start The starting position of the copied section.
* @param end The ending position of the copied section.
*/
constructor(public target: number, public start: number, public end?: number) {}
}
/**
* An event that gets emitted on successful execution of ListUnit's `reverse` method.
* @event
* @category ListUnit
*/
export class EventListUnitReverse {}
/**
* An event that gets emitted on successful execution of ListUnit's `sort` method.
* @event
* @category ListUnit
*/
export class EventListUnitSort {} | the_stack |
* @fileoverview Logic for laying out items in a grid.
*/
import * as SortingModule from './sorting';
export type Key = SortingModule.Key;
// Unicode characters for separating string fields.
const UNIT_SEPARATOR = '\u001F';
const RECORD_SEPARATOR = '\u001E';
/**
* A Grid works by arranging a collection of Items. They can be anything, but
* creating an explicit type makes it clear that we're not just bailing out of
* specifying a type.
*/
export type Item = any;
/**
* A Cell is identified by a vertical and horizontal key (row and column
* respectively) and contains items. A grid contains a collection of such cells.
*
* Cells are positioned in world coordinates (x/y) and have dimensions
* determined by the aspect ratio of the cell, the aspect ratio of the grid's
* items, and the number of items in the cell.
*/
export interface Cell {
/**
* Items contained in this Cell.
*/
items: Item[];
/**
* The cell's vertical key (identifies which row it's in).
*/
verticalKey: Key;
/**
* The cell's horizontal key (identifies which column it's in).
*/
horizontalKey: Key;
/**
* The cell's compound key, composed of the vertical and horizontal keys.
* Suitable for use as a unique hash identifying this cell.
*/
compoundKey: string;
/**
* X coordinate of lower-left-hand corner in world coordinates.
*/
x?: number;
/**
* Y coordinate of lower-left-hand corner in world coordinates.
*/
y?: number;
/**
* Width of the cell in world coordinates.
*/
width?: number;
/**
* Height of the cell in world coordinates.
*/
height?: number;
/**
* Minimum width necessary to stack all the items using the computed optimal
* cell aspect ratio.
*/
minWidth?: number;
/**
* Minimum height necessary to stack all the items using the computed optimal
* cell aspect ratio.
*/
minHeight?: number;
/**
* Width of the inner portion of the cell, where items would be placed, after
* accounting for cell padding.
*/
innerWidth?: number;
/**
* Height of the inner portion of the cell, where items would be placed, after
* accounting for cell padding.
*/
innerHeight?: number;
/**
* X position of the lower-left hand corner of the cell's content area, after
* accounting for cell padding.
*/
contentX?: number;
/**
* Y position of the lower-left hand corner of the cell's content area, after
* accounting for cell padding.
*/
contentY?: number;
/**
* A cell may have siblings above, below, to the left, or to the right.
*/
siblings: {
above?: Cell | null; below?: Cell | null; left?: Cell | null;
right?: Cell | null;
};
}
/**
* Maximum number of attempts to perform when computing optimization tasks like
* determining the optimal cell aspect ratio to achive a given overall grid
* aspect ratio.
*/
const MAX_OPTIMIZATION_ATTEMPTS = 20;
/**
* Due to floating point division and rounding, in particular with 4:3 aspect
* ratio items, some cell position calculations can be off by imperceptible
* amounts (billionths of a world coordinate unit) before rounding. This value
* is sometimes needed in stacking calculations to avoid these errors.
*/
const ROUNDING_EPSILON = 1e-6;
/**
* The position of an item within a cell. Both X and Y are relative and should
* be normalized to 0-1.
*/
export type ItemPosition = {
x: number,
y: number
};
/**
* Method signature for a callback function that can compute the relative X and
* Y coordinates for an item within a cell.
*/
export type ComputeItemPosition =
(item: Item, index: number, cell: Cell, grid: Grid) => ItemPosition;
/**
* The default method of computing the X coordinate for an item within a cell,
* using only its index within the cell item list. The output will be a
* cell-relative coordinate in the range 0-1.
*/
export const X_SCATTER_POSITION_FROM_INDEX =
(item: Item, index: number, cell: Cell, grid: Grid) => {
// TODO(jimbo): Investigate replacing the non-null assertion (!) with
// a runtime check.
// If you are certain the expression is always non-null/undefined, remove
// this comment.
const numColumns =
Math.floor(ROUNDING_EPSILON + cell.minWidth! / grid.itemAspectRatio);
return numColumns > 1 ? (index % numColumns) / (numColumns - 1) : 0;
};
/**
* The default method of computing the Y coordinate for an item within a cell,
* using only its index within the cell item list. The output will be a
* cell-relative coordinate in the range 0-1.
*/
export const Y_SCATTER_POSITION_FROM_INDEX =
(item: Item, index: number, cell: Cell, grid: Grid) => {
// TODO(jimbo): Investigate replacing the non-null assertion (!) with
// a runtime check.
// If you are certain the expression is always non-null/undefined, remove
// this comment.
const numColumns =
Math.floor(ROUNDING_EPSILON + cell.minWidth! / grid.itemAspectRatio);
const numRows = Math.ceil(cell.items.length / numColumns);
return numRows > 1 ? Math.floor(index / numColumns) / (numRows - 1) : 0;
};
/**
* This generator produces a positioning function with the desired centering
* vertically and horizontally.
*/
export const stackItems =
(verticalAlign?: string, horizontalAlign?: string): ComputeItemPosition => {
const offsetX = horizontalAlign === 'right' ?
1 :
horizontalAlign === 'middle' ? 0.5 : 0;
const offsetY =
verticalAlign === 'top' ? 1 : verticalAlign === 'middle' ? 0.5 : 0;
return (item: Item, index: number, cell: Cell, grid: Grid) => {
const x = X_SCATTER_POSITION_FROM_INDEX(item, index, cell, grid);
const y = Y_SCATTER_POSITION_FROM_INDEX(item, index, cell, grid);
// TODO(jimbo): Investigate replacing the non-null assertion (!)
// with a runtime check.
// If you are certain the expression is always non-null/undefined,
// remove this comment.
const innerWidth = cell.innerWidth! - grid.itemAspectRatio;
// TODO(jimbo): Investigate replacing the non-null assertion (!)
// with a runtime check.
// If you are certain the expression is always non-null/undefined,
// remove this comment.
const innerHeight = cell.innerHeight! - 1;
// TODO(jimbo): Investigate replacing the non-null assertion (!)
// with a runtime check.
// If you are certain the expression is always non-null/undefined,
// remove this comment.
return {
x: (x / innerWidth * (cell.minWidth! - grid.itemAspectRatio)) +
(offsetX * (cell.innerWidth! - cell.minWidth!) / innerWidth),
y: (y / innerHeight * (cell.minHeight! - 1)) +
(offsetY * (cell.innerHeight! - cell.minHeight!) / innerHeight),
};
};
};
/**
* The default method of positioning items within a cell is to stack them
* starting in the lower left and proceeding upwards in rows.
*/
export const STACK_ITEMS = stackItems('bottom', 'left');
/**
* Grid alignment options.
*/
export enum GridAlignment {
/**
* Tight grid alignmment causes each column to be wide enough to
* accomodate the widest cell in that column, or each row to be tall enough
* to accomodate that row's tallest cell.
*
* +----+--------------+
* | |oo |
* |o |ooo |
* +----+--------------+
* | |oooooooooo |
* | |oooooooooooooo|
* | |oooooooooooooo|
* |oo |oooooooooooooo|
* |oooo|oooooooooooooo|
* |oooo|oooooooooooooo|
* +----+--------------+
*/
Tight,
/**
* Uniform grid alignmment forces all cells to be the same uniform width and
* height, large enough to accomodate stacking the items in the largest cell.
*
* +--------------+--------------+
* | | |
* | | |
* | | |
* | | |
* | |oo |
* |o |ooo |
* +--------------+--------------+
* | |oooooooooo |
* | |oooooooooooooo|
* | |oooooooooooooo|
* |oo |oooooooooooooo|
* |oooo |oooooooooooooo|
* |oooo |oooooooooooooo|
* +--------------+--------------+
*/
Uniform,
}
/**
* A faceting function takes an item and returns a key (or null) into which to
* bucket that item. For example, a histogram faceting function may look at each
* item as a number and use it to determine a bucket index. Then, for items that
* cannot be interpreted as a number return null.
*/
export type FacetingFunction = (item: Item) => (Key | null);
export class Grid {
// SETTINGS.
/**
* The array of objects to be bucketed and positioned. These objects will be
* directly modified to set their target position and opacity.
*/
items: Item[];
/**
* The aspect ratio (width / height) of the items. Default is 1 (square).
*
* Ratio: 1/2 1 2
*
* - +---+ - +---+ - +-------+
* . | | 1 | | 1 | |
* 2 | | - +---+ - +-------+
* . | | |.1.| |. .2. .|
* - +---+
* |.1.|
*/
itemAspectRatio: number;
/**
* The cell margin is the amount of space to preserve between cells, both
* vertically and horizontally, measured in item widths. Default is 1, meaning
* there's enough space to place one item in between adjacent columns.
*
* For example, say the itemAspectRatio is 2, meaning items are twice as wide
* as they are tall.
*
* - +-------+
* 1 | |
* - +-------+
* |. .2. .|
*
* When placed in a grid with the default cell margin of 1, there'll be 1 item
* width (that is, 2 item heights) worth of space between every cell.
*
* |. . 2 . .|
* - +-------+ +-------+
* . | | | |
* . +-------+ +-------+ -
* . .
* 4 2
* . .
* . +-------+ +-------+ -
* . | | | |
* - +-------+ +-------+
* |. . . . . . 6 . . . . . .|
*/
cellMargin: number;
/**
* Cell padding describes the amount of space to preserve within cells, much
* like padding in a DOM element. It's broken up into four parts: top, left,
* right and bottom. All padding defaults to 0.
*
* Like cellMargin, cellPadding is measured in item widths.
*/
cellPadding: {bottom: number; left: number; right: number; top: number;};
/**
* Target aspect ratio to achieve for the whole grid. Defaults to 1 (square).
*/
targetGridAspectRatio: number;
/**
* Faceting function used for vertical bucketing. Given an item, this must
* produce either a number or string key.
*
* The default faceting function returns null for any input, placing all items
* into the same row.
*/
verticalFacet: FacetingFunction;
/**
* Faceting function used for horizontal bucketing. Given an item, this must
* produce either a number or string key.
*
* The default faceting function returns null for any input, placing all items
* into the same column.
*/
horizontalFacet: FacetingFunction;
/**
* Comparison function for sorting keys vertically.
*
* For numbers, higher values should come later (like positive Y on a scatter
* plot), but for strings, alphabetically later values should actually come
* earlier. This is because we read text left-to-right and top-to-bottom, but
* we expect numbers on charts to go left-to-right and bottom-to-top.
*
* In addition, unexpected values (like finding a string when sorting numbers,
* or vice versa) should come especially "early" to the comparator so they
* appear towards the bottom of the screen.
*/
verticalKeyCompare: (a: Key, b: Key) => number;
/**
* Comparison function for sorting keys horizontally.
*
* Unexpected values (like finding a string when sorting numbers, or vice
* versa) should come especially "early" to the comparator so they appear
* towards the left hand side.
*/
horizontalKeyCompare: (a: Key, b: Key) => number;
/**
* When arranging items in a grid, this callback method will be used to set
* the coordinates for a given item. If left unspecified, the default callback
* function will simply set the x and y properties of the item objects.
*/
itemPositionSetter: (item: Item, x: number, y: number) => void;
/**
* Method to use to compute positions of items within a cell. By default,
* this will use an algorithm which stacks items starting from the lower-left
* and building up in rows.
*
* The return value should be the X and Y coordinates of the item, relative to
* the cell. That is, an X value of 0 would be on the far left, and 1 would
* be on the far right. Likewile a Y value of 0 would be on the bottom, and 1
* would be on the top.
*/
computeItemPosition: ComputeItemPosition;
/**
* How to align and size grid cells relative to each other vertically.
*/
verticalGridAlignment: GridAlignment;
/**
* How to align and size grid cells relative to each other horizontally.
*/
horizontalGridAlignment: GridAlignment;
/**
* Minimum allowed cell aspect ratio. Defaults to 0.
*/
minCellAspectRatio: number;
/**
* Maximum allowed cell aspect ratio. Defaults to positive infinity.
*/
maxCellAspectRatio: number;
/**
* Optional method for sorting items within each Cell prior to updating item
* positions.
*/
cellItemComparator: ((a: Item, b: Item) => number)|null;
// READ-ONLY PROPERTIES.
/**
* Sorted array of keys discovered from vertical, row-based bucketing.
*/
verticalKeys: Key[];
/**
* Hash of verticalKeys for fast lookup prior to insertion.
*/
verticalKeysHash: {[key: string]: Key};
/**
* Sorted array of keys discovered from horizontal, column-based bucketing.
*/
horizontalKeys: Key[];
/**
* Hash of horizontalKeys for fast lookup prior to insertion.
*/
horizontalKeysHash: {[key: string]: Key};
/**
* Hash of Cells in the grid. The keys of this hash are constructed from a
* pair of vertical and horizontal keys.
* See getCompoundKey().
*/
cells: {[key: string]: Cell};
/**
* Length of the items array of the cell with the most items.
*/
longestCellLength: number;
/**
* Width of the laid out grid after arrange() has been called.
*/
width: number;
/**
* Height of the laid out grid after arrange() has been called.
*/
height: number;
constructor(items: Item[]) {
this.items = items;
this.itemAspectRatio = 1;
this.cellMargin = 1;
this.cellPadding = {
bottom: 0,
left: 0,
right: 0,
top: 0,
};
this.targetGridAspectRatio = 1;
this.minCellAspectRatio = 0;
this.maxCellAspectRatio = Infinity;
// Default faceting functions put everything in the same null bucket.
this.verticalFacet = item => null!;
this.horizontalFacet = item => null!;
// Default key sorting assumes primarily string values.
this.verticalKeyCompare = SortingModule.verticalStringCompare;
this.horizontalKeyCompare = SortingModule.horizontalStringCompare;
// Initialize local state.
this.verticalKeys = [];
this.verticalKeysHash = {};
this.horizontalKeys = [];
this.horizontalKeysHash = {};
this.cells = {};
this.longestCellLength = 0;
this.width = 0;
this.height = 0;
// Generate default item position setter.
this.itemPositionSetter = (item: any, x: number, y: number) => {
item.x = x;
item.y = y;
};
// Use default 'stacked' algorithm to position items in their cells.
this.computeItemPosition = STACK_ITEMS;
// Use the default Tight grid alighnment.
this.verticalGridAlignment = GridAlignment.Tight;
this.horizontalGridAlignment = GridAlignment.Tight;
// By default, don't sort cell items before positioning.
this.cellItemComparator = null;
}
/**
* Clear and re-initialize internal computed state.
*/
clear() {
this.verticalKeys = [];
this.verticalKeysHash = {};
this.horizontalKeys = [];
this.horizontalKeysHash = {};
this.cells = {};
this.longestCellLength = 0;
this.width = 0;
this.height = 0;
}
/**
* Arrange the items into a grid by bucketing them and then laying them out.
*/
arrange() {
this.facetItemsIntoCells();
// Compute the optimal cell aspect ratio, given the target grid ratio, then
// constrain it based on the min and max allowed.
const optimalCellAspectRatio =
this.computeOptimalCellAspectRatio(this.targetGridAspectRatio);
const cellAspectRatio = Math.min(
this.maxCellAspectRatio,
Math.max(this.minCellAspectRatio, optimalCellAspectRatio));
// Determine cell, row, and column minimum and maximum sizes.
const rowHeights: number[] = [];
const columnWidths: number[] = [];
for (let i = 0; i < this.verticalKeys.length; i++) {
for (let j = 0; j < this.horizontalKeys.length; j++) {
const cell =
this.getOrCreateCell(this.verticalKeys[i], this.horizontalKeys[j]);
[cell.minWidth, cell.minHeight] =
this.computeCellDimensions(cellAspectRatio, cell.items.length);
rowHeights[i] = Math.max(rowHeights[i] || 0, cell.minHeight);
columnWidths[j] = Math.max(columnWidths[j] || 0, cell.minWidth);
}
}
// Fill in cell siblings.
for (let i = 0; i < this.verticalKeys.length; i++) {
for (let j = 0; j < this.horizontalKeys.length; j++) {
const cell =
this.getCell(this.verticalKeys[i], this.horizontalKeys[j])!;
if (i < this.verticalKeys.length - 1) {
cell.siblings.above =
this.getCell(this.verticalKeys[i + 1], this.horizontalKeys[j]);
}
if (i > 0) {
cell.siblings.below =
this.getCell(this.verticalKeys[i - 1], this.horizontalKeys[j]);
}
if (j > 0) {
cell.siblings.left =
this.getCell(this.verticalKeys[i], this.horizontalKeys[j - 1]);
}
if (j < this.horizontalKeys.length - 1) {
cell.siblings.right =
this.getCell(this.verticalKeys[i], this.horizontalKeys[j + 1]);
}
}
}
// Force uniform row heights and column widths when alignment is uniform.
if (this.verticalGridAlignment === GridAlignment.Uniform) {
const maxRowHeight = Math.max(...rowHeights);
for (let i = 0; i < rowHeights.length; i++) {
rowHeights[i] = maxRowHeight;
}
}
if (this.horizontalGridAlignment === GridAlignment.Uniform) {
const maxColumnWidth = Math.max(...columnWidths);
for (let j = 0; j < columnWidths.length; j++) {
columnWidths[j] = maxColumnWidth;
}
}
// Backfill cell true width and height based on row and column dimensions.
for (let i = 0; i < this.verticalKeys.length; i++) {
for (let j = 0; j < this.horizontalKeys.length; j++) {
const cell =
this.getCell(this.verticalKeys[i], this.horizontalKeys[j])!;
cell.height = rowHeights[i];
cell.width = columnWidths[j];
cell.innerHeight =
cell.height - this.cellPadding.top - this.cellPadding.bottom;
cell.innerWidth =
cell.width - this.cellPadding.left - this.cellPadding.right;
}
}
// Fill in cell positions.
const margin = this.cellMargin * this.itemAspectRatio;
for (let i = 0; i < this.verticalKeys.length; i++) {
for (let j = 0; j < this.horizontalKeys.length; j++) {
const cell =
this.getCell(this.verticalKeys[i], this.horizontalKeys[j])!;
if (i) {
const prevRow =
this.getCell(this.verticalKeys[i - 1], this.horizontalKeys[j])!;
// TODO(jimbo): Investigate replacing the non-null assertion (!)
// with a runtime check.
// If you are certain the expression is always non-null/undefined,
// remove this comment.
cell.y = prevRow.y! + rowHeights[i - 1] + margin;
} else {
cell.y = 0;
}
cell.contentY = cell.y + this.cellPadding.bottom;
if (j) {
const prevColumn =
this.getCell(this.verticalKeys[i], this.horizontalKeys[j - 1])!;
// TODO(jimbo): Investigate replacing the non-null assertion (!)
// with a runtime check.
// If you are certain the expression is always non-null/undefined,
// remove this comment.
cell.x = prevColumn.x! + columnWidths[j - 1] + margin;
} else {
cell.x = 0;
}
cell.contentX = cell.x + this.cellPadding.left;
}
}
// Compute overall width and height of grid.
this.eachCell(cell => {
// TODO(jimbo): Investigate replacing the non-null assertion (!) with
// a runtime check.
// If you are certain the expression is always non-null/undefined, remove
// this comment.
this.width = Math.max(this.width, cell.x! + cell.width!);
// TODO(jimbo): Investigate replacing the non-null assertion (!) with
// a runtime check.
// If you are certain the expression is always non-null/undefined, remove
// this comment.
this.height = Math.max(this.height, cell.y! + cell.height!);
});
// Use cell positions to set each item's position.
this.positionItems();
}
/**
* Position each item in each cell. This uses the computeItemPosition() method
* to get the relative X and Y coordinates for each item, and uses the
* itemPositionSetter() method to set the absolute X and Y.
*/
positionItems() {
this.eachCell(cell => {
// The maximum allowable X and Y values must account for the size of the
// items being displayed, characterized by itemAspectRatio.
// TODO(jimbo): Investigate replacing the non-null assertion (!) with
// a runtime check.
// If you are certain the expression is always non-null/undefined, remove
// this comment.
const width = Math.max(0, cell.innerWidth! - this.itemAspectRatio);
// TODO(jimbo): Investigate replacing the non-null assertion (!) with
// a runtime check.
// If you are certain the expression is always non-null/undefined, remove
// this comment.
const height = Math.max(0, cell.innerHeight! - 1);
// Create a copy of items, then sort if there is a comparator.
const items = cell.items.slice(0);
if (this.cellItemComparator) {
items.sort(this.cellItemComparator);
}
for (let i = 0; i < items.length; i++) {
// First, compute the desired item position.
const computed = this.computeItemPosition(items[i], i, cell, this);
// Clamp the X and Y coordinates to the range from 0-1.
// TODO(jimbo): What to do with NaNs? Currently casting to 0.
const x = !computed || isNaN(computed.x) ?
0 :
Math.max(0, Math.min(1, computed.x));
const y = !computed || isNaN(computed.y) ?
0 :
Math.max(0, Math.min(1, computed.y));
// Set the item position within the cell's content area.
// TODO(jimbo): Investigate replacing the non-null assertion (!)
// with a runtime check.
// If you are certain the expression is always non-null/undefined,
// remove this comment.
this.itemPositionSetter(
items[i], cell.contentX! + x * width, cell.contentY! + y * height);
}
});
}
/**
* Apply faceting functions to each item to put them into their proper cells.
*/
facetItemsIntoCells() {
this.clear();
// Perform faceting on each item, assigning each to the correct Cell.
this.eachItem(item => {
const cell = this.getOrCreateCell(
this.verticalFacet(item)!, this.horizontalFacet(item)!);
cell.items.push(item);
this.longestCellLength =
Math.max(this.longestCellLength, cell.items.length);
});
// Create vertical and horizontal key lists and sort them.
for (const hashKey in this.verticalKeysHash) {
this.verticalKeys.push(this.verticalKeysHash[hashKey]);
}
this.verticalKeys.sort(this.verticalKeyCompare);
for (const hashKey in this.horizontalKeysHash) {
this.horizontalKeys.push(this.horizontalKeysHash[hashKey]);
}
this.horizontalKeys.sort(this.horizontalKeyCompare);
}
/**
* Call the provided function once for each item in items.
*/
eachItem(callback: (item: Item) => any) {
if (!this.items) {
return;
}
for (let i = 0; i < this.items.length; i++) {
callback.call(this, this.items[i]);
}
}
/**
* Call the provided function once for each cell in the grid.
*/
eachCell(callback: (cell: Cell) => any) {
for (const key in this.cells) {
callback.call(this, this.cells[key])
}
}
/**
* Given a pair of vertical and horizontal keys, return a single compound
* key which can be used to look up the cell with those keys in the hash.
*/
getCompoundKey(verticalKey: Key, horizontalKey: Key) {
return (typeof verticalKey) + UNIT_SEPARATOR + verticalKey +
RECORD_SEPARATOR + (typeof horizontalKey) + UNIT_SEPARATOR +
horizontalKey;
}
/**
* Given a particular pair of vertical and horizontal keys, get the Cell
* with those keys. If there isn't one, return null.
*/
getCell(verticalKey: Key, horizontalKey: Key): Cell|null {
const compoundKey = this.getCompoundKey(verticalKey, horizontalKey);
return compoundKey in this.cells ? this.cells[compoundKey] : null;
}
/**
* Get an array of all cells.
*/
getCells() { return Object.keys(this.cells).map(key => this.cells[key]); }
/**
* Given a particular pair of vertial and horizontal faceting keys, get the
* Cell with those keys. If there isn't one, create it, insert it, and then
* return it.
*/
getOrCreateCell(verticalKey: Key, horizontalKey: Key): Cell {
let cell = this.getCell(verticalKey, horizontalKey);
if (cell) {
return cell;
}
this.addVerticalKey(verticalKey);
this.addHorizontalKey(horizontalKey);
const compoundKey = this.getCompoundKey(verticalKey, horizontalKey);
cell = {verticalKey, horizontalKey, compoundKey, items: [], siblings: {}};
this.cells[compoundKey] = cell;
return cell;
}
/**
* Given a particular vertical key, return the row of Cells with that key,
* ordered by their horizontal key.
*/
getRow(verticalKey: Key): Cell[] {
const row: Cell[] = [];
for (let i = 0; i < this.horizontalKeys.length; i++) {
const cell = this.getCell(verticalKey, this.horizontalKeys[i]);
if (cell) {
row.push(cell);
}
}
return row;
}
/**
* Given a particular horizontal key, return the column of Cells with that
* key, ordered by their horizontal key.
*/
getColumn(horizontalKey: Key): Cell[] {
const column: Cell[] = [];
for (let i = 0; i < this.verticalKeys.length; i++) {
const cell = this.getCell(this.verticalKeys[i], horizontalKey);
if (cell) {
column.push(cell);
}
}
return column;
}
/**
* Add a vertical key to the verticalKeysHash.
*/
addVerticalKey(verticalKey: Key) {
const key = (typeof verticalKey) + UNIT_SEPARATOR + verticalKey;
if (!(key in this.verticalKeysHash)) {
this.verticalKeysHash[key] = verticalKey;
}
}
/**
* Add a horizontal key to the horizontalKeys array, return its index.
*/
addHorizontalKey(horizontalKey: Key) {
const key = (typeof horizontalKey) + UNIT_SEPARATOR + horizontalKey;
if (!(key in this.horizontalKeysHash)) {
this.horizontalKeysHash[key] = horizontalKey;
}
}
/**
* Given an overall target aspect ratio for the whole grid, compute the
* optimal cell aspect ratio to use to achieve it.
*
* This algorithm proposes a cell aspect ratio to inform item stacking, then
* measures what the overall grid aspect ratio would be if the proposed cell
* aspect ratio was chosen. So the more items there are in the cells of the
* grid, the more flexibility there is, and the better the computed optimal
* cell aspect ratio will be.
*
* Since any non-empty cell has a minimum possible width and height, it may be
* that the final grid aspect ratio differs noticeably from the target,
* irrespective of the cell aspect ratio.
*
* @param targetGridAspectRatio The desired overall grid aspect ratio.
*/
computeOptimalCellAspectRatio(targetGridAspectRatio: number): number {
const numRows = this.verticalKeys.length;
const numColumns = this.horizontalKeys.length;
if (!numRows || !numColumns) {
return 1;
}
// Start with a naive guess that ignores the effect of margins.
let proposedCellAspectRatio = numRows / numColumns;
let bestCellAspectRatio = proposedCellAspectRatio;
const epsilon = 0.001;
let bestErr = Infinity;
// Keep track of the lowest and highest possible cell aspect ratios as we
// search. The algorithm doubles its initial estimate until a highBound is
// discovered, and performs a binary search after that.
let lowBound = 0;
let highBound = Infinity;
// Limit the number of optimization attempts so that we don't go over the
// maximum, but otherwise try the greater of the number of rows, columns, or
// items in the largest cell.
const maxAttempts = Math.min(
MAX_OPTIMIZATION_ATTEMPTS,
Math.max(numRows, numColumns, this.longestCellLength));
let attempts = 0;
while (attempts < maxAttempts) {
attempts++;
const computedGridAspectRatio =
this.computeGridAspectRatio(proposedCellAspectRatio);
const err =
Math.abs(1 - (computedGridAspectRatio / targetGridAspectRatio));
if (err < bestErr) {
bestCellAspectRatio = proposedCellAspectRatio;
bestErr = err;
}
if (err < epsilon) {
break;
}
if (computedGridAspectRatio > targetGridAspectRatio) {
// If the computed grid aspect ratio is too high, that means our
// proposed cell aspect ratio is too high and we should lower it.
highBound = proposedCellAspectRatio;
proposedCellAspectRatio -= (highBound - lowBound) / 2;
} else {
// When the computed aspect ratio is too low, that means our proposed
// cell aspect ratio is too low and we should raise it.
lowBound = proposedCellAspectRatio;
if (isFinite(highBound)) {
proposedCellAspectRatio += (highBound - lowBound) / 2;
} else {
proposedCellAspectRatio *= 2;
}
}
}
return bestCellAspectRatio;
}
/**
* Given a proposed cell aspect ratio, compute what the overall grid aspect
* ratio would be, taking settings into account.
*/
computeGridAspectRatio(proposedCellAspectRatio: number): number {
const numRows = this.verticalKeys.length;
const numColumns = this.horizontalKeys.length;
// These values are used in computing the grid aspect ratio when the grid
// alignment is row dominant, column dominant or uniform.
const rowHeights: number[] = [];
const columnWidths: number[] = [];
let maxRowWidth = -Infinity;
let maxRowHeight = -Infinity;
let maxColumnWidth = -Infinity;
let maxColumnHeight = -Infinity;
// Keep track of the cumulative cell sizes, adding widths across columns and
// heights across rows. These values are used to determine the widest row
// and tallest column.
const cumulativeCellSizes: {height: number, width: number}[][] = [];
// Compute the individual and maximum row widths and column heights.
for (let i = 0; i < numRows; i++) {
cumulativeCellSizes[i] = [];
for (let j = 0; j < numColumns; j++) {
const cumulativeCellSize = cumulativeCellSizes[i][j] = {
width: j ? cumulativeCellSizes[i][j - 1].width : 0,
height: i ? cumulativeCellSizes[i - 1][j].height : 0,
};
const cell = this.getCell(this.verticalKeys[i], this.horizontalKeys[j]);
if (!cell || !cell.items || !cell.items.length) {
continue;
}
const [cellWidth, cellHeight] = this.computeCellDimensions(
proposedCellAspectRatio, cell.items.length);
columnWidths[j] = Math.max(columnWidths[j] || 0, cellWidth);
rowHeights[i] = Math.max(rowHeights[i] || 0, cellHeight);
// Update cumulative cell width/height.
cumulativeCellSize.width += cellWidth;
cumulativeCellSize.height += cellHeight;
// Update maximums.
maxRowWidth = Math.max(maxRowWidth, cumulativeCellSize.width);
maxRowHeight = Math.max(maxRowHeight, cellHeight);
maxColumnWidth = Math.max(maxColumnWidth, cellWidth);
maxColumnHeight = Math.max(maxColumnHeight, cumulativeCellSize.height);
}
}
// When using Uniform alignment, the true maxRowWidth will be the width of
// the widest column times the number of columns. Likewise, the true
// maxColumnHeight will be the height of the tallest row times the number
// of rows.
if (this.verticalGridAlignment === GridAlignment.Uniform) {
maxColumnHeight = maxRowHeight * numRows;
}
if (this.horizontalGridAlignment === GridAlignment.Uniform) {
maxRowWidth = maxColumnWidth * numColumns;
}
// TODO(jimbo): Use columnWidths/rowHeights + grid alignment once available.
const totalMargin = this.cellMargin * this.itemAspectRatio;
const totalWidth = maxRowWidth + totalMargin * (numColumns - 1);
const totalHeight = maxColumnHeight + totalMargin * (numRows - 1);
return totalWidth / totalHeight;
}
/**
* Compute the size of a cell, given the cell's aspect ratio and the number
* of items it has.
*/
computeCellDimensions(cellAspectRatio: number, itemCount: number): number[] {
const dimensions = [
this.itemAspectRatio * (this.cellPadding.left + this.cellPadding.right),
this.itemAspectRatio * (this.cellPadding.top + this.cellPadding.bottom)
];
// Short-circuit if there are no items.
if (!itemCount) {
return dimensions;
}
// Compute the width of the cell as measured in items.
const cellItemWidth = Math.min(
itemCount,
Math.ceil(
Math.sqrt(cellAspectRatio * itemCount) / this.itemAspectRatio));
// Compute full cell width and height, accounting for item aspect ratio.
dimensions[0] += this.itemAspectRatio * cellItemWidth;
dimensions[1] += Math.ceil(itemCount / cellItemWidth);
return dimensions;
}
} | the_stack |
declare namespace adone {
/**
* File system stuff
*/
namespace fs {
namespace I {
type URL = nodestd.url.URL;
type Stats = nodestd.fs.Stats;
type Flag = "r" | "r+" | "rs+" | "w" | "wx" | "w+" | "wx+" | "a" | "ax" | "a+" | "ax+";
type Encoding = "ascii" | "utf8" | "utf16le" | "usc2" | "base64" | "latin1" | "binary" | "hex";
type SymlinkType = "dir" | "file" | "junction";
type ReadStream = nodestd.fs.ReadStream;
type WriteStream = nodestd.fs.WriteStream;
type FD = number;
}
/**
* Reads the value of a symbolic link
*/
function readlink(path: string | Buffer | I.URL, encoding: null): Promise<Buffer>;
function readlink(path: string | Buffer | I.URL, encoding: I.Encoding): Promise<string>;
function readlink(path: string | Buffer | I.URL, options: { encoding: null }): Promise<Buffer>;
function readlink(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): Promise<string>;
/**
* Reads the value of a symbolic link
*/
function readlinkSync(path: string | Buffer | I.URL, encoding: null): Buffer;
function readlinkSync(path: string | Buffer | I.URL, encoding: I.Encoding): string;
function readlinkSync(path: string | Buffer | I.URL, options: { encoding: null }): Buffer;
function readlinkSync(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): string;
/**
* Deletes a name and possibly the file it refers to
*/
function unlink(path: string | Buffer | I.URL): Promise<void>;
/**
* Deletes a name and possibly the file it refers to
*/
function unlinkSync(path: string | Buffer | I.URL): void;
/**
* Changes the file system timestamps of the object referenced by path
*/
function utimes(path: string | Buffer | I.URL, atime: number | string | Date, mtime: number | string | Date): Promise<void>;
/**
* Changes the file system timestamps of the object referenced by path
*/
function utimesSync(path: string | Buffer | I.URL, atime: number | string | Date, mtime: number | string | Date): void;
/**
* Changes the file system timestamps of the object referenced by path
*/
function utimesMillis(path: string | Buffer | I.URL, atime: number, mtime: number): Promise<void>;
/**
* Changes permissions of a file
*/
function chmod(path: string | Buffer | I.URL, mode: number): Promise<void>;
/**
* Changes ownership of a file
*/
function chown(path: string | Buffer | I.URL, uid: number, gid: number): Promise<void>;
/**
* Changes ownership recursively for a given path
*/
function chownr(path: string | Buffer | I.URL, uid: number, gid: number): Promise<void>;
/**
* Deletes a directory
*/
function rmdir(path: string | Buffer | I.URL): Promise<void>;
/**
* Reads a directory
*/
function readdir(path: string | Buffer | I.URL, encoding: null): Promise<Buffer[]>;
function readdir(path: string | Buffer | I.URL, encoding: I.Encoding): Promise<string[]>;
function readdir(path: string | Buffer | I.URL, options: { encoding: null }): Promise<Buffer[]>;
function readdir(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): Promise<string[]>;
/**
* Reads a directory
*/
function readdirSync(path: string | Buffer | I.URL, encoding: null): Buffer[];
function readdirSync(path: string | Buffer | I.URL, encoding: I.Encoding): string[];
function readdirSync(path: string | Buffer | I.URL, options: { encoding: null }): Buffer[];
function readdirSync(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): string[];
namespace I {
interface ReaddirpEntry {
/**
* filename
*/
name: string;
/**
* full path to a file
*/
fullPath: string;
/**
* relative path to a file
*/
path: string;
/**
* relative path to the parent dir
*/
parentDir: string;
/**
* full path to the parent dir
*/
fullParentDir: string;
/**
* file stats
*/
stat: fs.I.Stats;
}
type ReaddirpFilter = string | ((entry: ReaddirpEntry) => boolean);
interface ReaddirpOptions {
/**
* filter for files
*/
fileFilter?: ReaddirpFilter | ReaddirpFilter[];
/**
* filter for directories
*/
directoryFilter?: ReaddirpFilter | ReaddirpFilter[];
/**
* maximum recursion depth
*
* Infinity by default
*/
depth?: number;
/**
* whether to emit files
*
* true by default
*/
files?: boolean;
/**
* whether to emit directories
*
* true by default
*/
directories?: boolean;
/**
* whether to use lstat for stating
*
* false by default
*/
lstat?: boolean;
}
}
/**
* Traverses the given path
*/
function readdirp(root: string | Buffer | I.URL, options?: I.ReaddirpOptions): stream.core.Stream<never, I.ReaddirpEntry>;
/**
* Gets file status, identical to stat, except that if pathname is a symbolic link,
* then it returns information about the link itself, not the file that it refers to
*/
function lstat(path: string | Buffer | I.URL): Promise<I.Stats>;
/**
* Gets file status, identical to stat, except that if pathname is a symbolic link,
* then it returns information about the link itself, not the file that it refers to
*/
function lstatSync(path: string | Buffer | I.URL): I.Stats;
/**
* Gets file status
*/
function stat(path: string | Buffer | I.URL): Promise<I.Stats>;
/**
* Gets file status
*/
function statSync(path: string | Buffer | I.URL): I.Stats;
/**
* Truncates file to the given length
*/
function truncate(path: string | Buffer, length?: number): Promise<void>;
/**
* Writes data to a file, replacing the file if it already exists
*/
function writeFile(file: string | Buffer | number, data: string | Buffer | Uint8Array, options?: {
encoding?: I.Encoding,
mode?: number,
flag?: I.Flag
}): Promise<void>;
/**
* Writes data to a file, replacing the file if it already exists
*/
function writeFileSync(file: string | Buffer | number, data: string | Buffer | Uint8Array, options?: {
encoding?: I.Encoding,
mode?: number,
flag?: I.Flag
}): void;
/**
* Appends data to a file, creating the file if it does not yet exist
*/
function appendFile(file: string | Buffer | number, data: string | Buffer, options?: {
encoding?: I.Encoding,
mode?: number,
flag?: I.Flag
}): Promise<void>;
/**
* Appends data to a file, creating the file if it does not yet exist
*/
function appendFileSync(file: string | Buffer | number, data: string | Buffer, options?: {
encoding?: I.Encoding,
mode?: number,
flag?: I.Flag
}): void;
/**
* Tests a user's permissions for the file or directory specified by path
*/
function access(file: string | Buffer | I.URL, mode?: number): Promise<void>;
/**
* Tests a user's permissions for the file or directory specified by path
*/
function accessSync(file: string | Buffer | I.URL, mode?: number): void;
/**
* Makes a new name for a file
*/
function symlink(target: string | Buffer | I.URL, path: string | Buffer | I.URL, type?: I.SymlinkType): Promise<void>;
/**
* Recursively deletes the given path, that can be a glob pattern
*/
function rm(path: string, options?: {
/**
* Whether to consider the given path as a glob pattern
*/
glob?: boolean,
/**
* Maximum busy tries, errors when cannot remove a file due to EBUSY, ENOTEMPTY, EPERM
*/
maxBusyTries?: number,
/**
* The delay to wait between busy tries
*/
emfileWait?: number
/**
* cwd to use
*/
cwd?: string
}): Promise<void>;
/**
* Recursively deletes empty directiries inside the given directory
*/
function rmEmpty(path: string, options?: {
cwd?: string;
filter?: (filename: string) => boolean
}): Promise<void>;
namespace I {
interface Access {
read: boolean;
write: boolean;
execute: boolean;
}
}
/**
* Represents the permissions of a file
*/
class Mode {
stat: I.Stats;
owner: I.Access;
group: I.Access;
others: I.Access;
constructor(stat: I.Stats);
valueOf(): number;
}
/**
* Represents a file
*/
class File {
constructor(...path: string[]);
/**
* Sets the file encoding
*/
encoding(name: I.Encoding | "buffer"): this;
/**
* Returns the file stats
*/
stat(): Promise<I.Stats>;
/**
* Returns the file stats synchronously
*/
statSync(): I.Stats;
/**
* Returns the files stats, for links the link stats
*/
lstat(): Promise<I.Stats>;
/**
* Returns the files stats, for links the link stats, works synchronously
*/
lstatSync(): I.Stats;
/**
* Returns the file mode
*/
mode(): Mode;
/**
* Returns the file absoulte path
*/
path(): string;
/**
* Returns normalized file path, with only / and removed redundant slashes
*/
normalizedPath(): string;
/**
* Returns the file dirname
*/
dirname(): string;
/**
* Returns the filename
*/
filename(): string;
/**
* Returns the file extension
*/
extname(): string;
/**
* Returns the filename with no extension
*/
stem(): string;
/**
* Returns a relative path
*/
relativePath(path: string | Directory): string;
/**
* Returns true if the file exists, visible by the process
*/
exists(): Promise<boolean>;
/**
* Creates the file, writes an empty string
*/
create(options?: { mode?: number }): Promise<void>;
/**
* Writes the given data to the file
*/
write(buffer: string | Buffer, options?: { encoding?: I.Encoding, mode?: number, flag?: I.Flag }): Promise<void>;
/**
* Appends the given data to the file
*/
append(buffer: string | Buffer, options?: { encoding?: I.Encoding, mode?: number, flag?: I.Flag }): Promise<void>;
/**
* Removes the file
*/
unlink(): Promise<void>;
/**
* Returns the contents as a buffer
*/
contents(encoding: "buffer"): Promise<Buffer>;
/**
* Returns the contents as a string
*/
contents(encoding?: I.Encoding): Promise<string>;
/**
* Returns the contents as a buffer synchronously
*/
contentsSync(encoding: "buffer"): Buffer;
/**
* Returns the contents as a string synchronously
*/
contentsSync(encoding?: I.Encoding): string;
/**
* Returns a read stream for this file
*/
contentsStream(encoding?: "buffer" | I.Encoding): I.ReadStream;
/**
* Changes the file premissions
*/
chmod(mode: number | Mode): Promise<void>;
/**
* Renames the file
*/
rename(name: string | File): Promise<void>;
/**
* Creates a symbolic link to this file
*/
symbolicLink(path: string | File): SymbolicLinkFile;
/**
* Returns the file size in bytes
*/
size(): Promise<number>;
}
namespace I.Directory {
interface AddFileOptions {
contents?: string | Buffer;
encoding?: string;
mode?: number;
}
}
/**
* Represents a directory
*/
class Directory {
constructor(...path: string[]);
/**
* Returns dirname
*/
dirname(): string;
/**
* Returns filename
*/
filename(): string;
/**
* Returns absoulte path
*/
path(): string;
/**
* Returns normalized file path, with only / and removed redundant slashes
*/
normalizedPath(): string;
/**
* Returns relative path
*/
relativePath(path: string | Directory): string;
/**
* Returns directory stats
*/
stat(): Promise<I.Stats>;
/**
* Returns the files stats, for links the link stats
*/
lstat(): Promise<I.Stats>;
/**
* Returns true if the directory exists
*/
exists(): Promise<boolean>;
/**
* Creates the directory if doesnt exist
*/
create(options?: { mode?: number }): Promise<void>;
/**
* Returns path relative to this directory
*/
resolve(...path: string[]): string;
/**
* Returns directory relative to this directory
*/
getDirectory(...path: string[]): Directory;
/**
* Returns file relative to this directory
*/
getFile(...path: string[]): File;
/**
* Returns file that is a symbolic link
*/
getSymbolicLinkFile(...path: string[]): SymbolicLinkFile;
/**
* Returns directory that is a symbolic link
*/
getSymbolicLinkDirectory(...path: string[]): SymbolicLinkDirectory;
/**
* Adds a new file
*/
addFile(filename: string, options?: I.Directory.AddFileOptions): Promise<File>;
addFile(a: string, filename: string, options?: I.Directory.AddFileOptions): Promise<File>;
addFile(a: string, b: string, filename: string, options?: I.Directory.AddFileOptions): Promise<File>;
addFile(a: string, b: string, c: string, filename: string, options?: I.Directory.AddFileOptions): Promise<File>;
addFile(a: string, b: string, c: string, d: string, filename: string, options?: I.Directory.AddFileOptions): Promise<File>;
addFile(a: string, ...filename: Array<Array<string | I.Directory.AddFileOptions>>): Promise<File>;
/**
* Adds a new directory
*/
addDirectory(...path: string[]): Promise<Directory>;
/**
* Returns files inside this directory
*/
files(): Promise<Array<File | Directory | SymbolicLinkFile | SymbolicLinkDirectory>>;
/**
* Returns files inside this directory synchronously
*/
filesSync(): Array<File | Directory | SymbolicLinkFile | SymbolicLinkDirectory>;
/**
* Deletes all the file inside this directory, but not the directory
*/
clean(): Promise<void>;
/**
* Deletes the directory
*/
unlink(options?: { retries?: number, delay?: number }): Promise<void>;
/**
* Searches all nested files and directories
*/
find(options?: { files?: boolean, dirs?: boolean }): Promise<Array<File | Directory | SymbolicLinkFile | SymbolicLinkDirectory>>;
/**
* Searches all nested files and directories synchronously
*/
findSync(options?: { files?: boolean, dirs?: boolean }): Array<File | Directory | SymbolicLinkFile | SymbolicLinkDirectory>;
/**
* Renames the directory
*/
rename(name: string | Directory): Promise<void>;
/**
* Create a symbolic link for this directory
*/
symbolicLink(path: string | Directory): Promise<SymbolicLinkDirectory>;
/**
* Copies this from this directory to the given path
*/
copyTo(destPath: string, options?: I.CopyToOptions): Promise<void>;
/**
* Copies files from the given path to this directory
*/
copyFrom(srcPath: string, options?: I.CopyToOptions): Promise<void>;
/**
* Creates a new directory with the given path
*/
static create(...path: string[]): Promise<Directory>;
/**
* Creates a new temporary directory
*/
static createTmp(options?: I.TmpNameOptions): Promise<Directory>;
}
/**
* Represents a file that is a symbolic link to another file
*/
class SymbolicLinkFile extends File {
/**
* Returns the path of the file it refers to
*/
realpath(): Promise<string>;
/**
* Returns the contents of the original file as a buffer
*/
contents(encoding: "buffer"): Promise<Buffer>;
/**
* Returns the contents of the original file as a string
*/
contents(encoding?: I.Encoding): Promise<string>;
/**
* Returns the contents of the original file as a buffer synchronously
*/
contentsSync(encoding: "buffer"): Buffer;
/**
* Returns the contents of the original file as a string synchronously
*/
contentsSync(encoding?: I.Encoding): string;
/**
* Returns a read stream for the original file
*/
contentsStream(encoding?: "buffer" | I.Encoding): I.ReadStream;
}
/**
* Represents a directory that is a symbolic link to another directory
*/
class SymbolicLinkDirectory extends Directory {
/**
* Returns the path of the directory it refers to
*/
realpath(): Promise<string>;
/**
* Removes the link, not the directory it refers to
*/
unlink(): Promise<void>;
}
namespace I.RandomAccessFile {
interface ConstructorOptions {
/**
* Whether the file should be open as readable
*/
readable?: boolean;
/**
* Whether the file should be open as writable
*/
writable?: boolean;
/**
* Whether the file should be open as appendable
*/
appendable?: boolean;
/**
* Predefined mtime
*/
mtime?: number;
/**
* Predefined atime
*/
atime?: number;
/**
* Base direcotry for the file
*/
cwd?: string;
}
}
/**
* Represents a file that supports random access
*/
class RandomAccessFile extends event.Emitter {
constructor(filename: string, options?: I.RandomAccessFile.ConstructorOptions);
/**
* Reads a buffer at the given offset
*/
read(length: number, offset?: number): Promise<Buffer>;
/**
* Writes the given buffer at the given offset
*/
write(buf: string | Buffer, offset?: number): Promise<number>;
/**
* Closes the file
*/
close(): Promise<void>;
/**
* Writes atime and mtime properties of the file
*/
end(options?: { atime?: number, mtime?: number }): Promise<void>;
/**
* Truncates the file to the given length
*/
truncate(size: number): Promise<void>;
/**
* Removes this file
*/
unlink(): Promise<void>;
/**
* Opens the given file with the given options
*/
static open(filename: string, options?: I.RandomAccessFile.ConstructorOptions): Promise<RandomAccessFile>;
}
/**
* Represents an abstract random access reader
*/
class AbstractRandomAccessReader extends event.Emitter {
/**
* Increments the reference counter
*/
ref(): void;
/**
* Decrements the reference counter
*/
unref(): void;
/**
* Creates a readable stream for the given range
*/
createReadStream(options?: {
/**
* Start offset, inslusive
*/
start?: number,
/**
* End offset, exclusive
*/
end?: number
}): nodestd.stream.Readable;
/**
* Reads data and writes to the given buffer
*
* @param buffer buffer to write to
* @param offset buffer offset to write to
* @param length number of bytes to read
* @param position position to read from
*/
read(buffer: Buffer, offset: number, length: number, position: number): Promise<void>;
/**
* Must be implemented in derived classes and return a readable stream for the given range [start, end]
*/
_readStreamFromRange(start: number, end: number): nodestd.stream.Readable;
}
/**
* Represents a random access reader for a file by its file descriptor
*/
class RandomAccessFdReader extends AbstractRandomAccessReader {
constructor(fd: number);
}
/**
* Represents a random access reader for a buffer
*/
class RandomAccessBufferReader extends AbstractRandomAccessReader {
constructor(buffer: Buffer);
}
namespace I.Glob {
interface Options {
/**
* The current working directory in which to search. Defaults to process.cwd()
*/
cwd?: string;
/**
* The place where patterns starting with / will be mounted onto
*/
root?: string;
/**
* Include .dot files in normal matches and globstar matches
*/
dot?: boolean;
/**
* By default, a pattern starting with a forward-slash will be "mounted" onto the root setting,
* so that a valid filesystem path is returned
*/
nomount?: boolean;
/**
* Add a / character to directory matches. Note that this requires additional stat calls
*/
mark?: boolean;
/**
* Don't sort the results
*/
nosort?: boolean;
/**
* Set to true to stat all results
*/
stat?: boolean;
/**
* When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr.
* Set the option to true to suppress these warnings.
*/
silent?: boolean;
/**
* When an unusual error is encountered when attempting to read a directory,
* the process will just continue on in search of other matches.
* Set the option to raise an error in these cases
*/
strict?: boolean;
/**
* Pass in a previously generated cache object to save some fs calls
*/
cache?: Map<string, string>;
/**
* A cache of results of filesystem information, to prevent unnecessary stat calls
*/
statCache?: Map<string, Stats>;
/**
* A cache of results of filesystem information, to prevent unnecessary realpath calls
*/
realpathCache?: Map<string, string>;
/**
* A cache of known symbolic links
*/
symlinks?: object;
/**
* In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set.
* By default, this implementation prevents duplicates in the result set.
* Set this flag to disable that behavior
*/
nounique?: boolean;
/**
* Set to never return an empty set, instead returning a set containing the pattern itself.
* This is the default in glob(3).
*/
nonull?: boolean;
/**
* Do not expand {a,b} and {1..3} brace sets.
*/
nobrace?: boolean;
/**
* Do not match ** against multiple filenames. (Ie, treat it as a normal * instead.)
*/
noglobstar?: boolean;
/**
* Do not match +(a|b) "extglob" patterns.
*/
noext?: boolean;
/**
* Perform a case-insensitive match.
* Note: on case-insensitive filesystems, non-magic patterns will match by default, since stat and readdir will not raise errors.
*/
nocase?: boolean;
/**
* Perform a basename-only match if the pattern does not contain any slash characters.
* That is, *.js would be treated as equivalent to **\/*.js, matching all js files in all directories
*/
matchBase?: boolean;
/**
* Do not match directories, only files
*/
nodir?: boolean;
/**
* Add a pattern or an array of glob patterns to exclude matches
*/
ignore?: string | string[];
/**
* Follow symlinked directories when expanding ** patterns.
* Note that this can result in a lot of duplicate references in the presence of cyclic links
*/
follow?: boolean;
/**
* Set to true to call fs.realpath on all of the results
*/
realpath?: boolean;
/**
* Set to true to always receive absolute paths for matched files
*/
absolute?: boolean;
}
interface StreamOptions extends Options {
/**
* Add the index of the matching pattern to the result
*/
patternIndex?: boolean;
}
interface StreamConstructor {
new(patterns: string | string[], options: StreamOptions & { stat: true, patternIndex: true }): Stream<{
path: string,
stat: Stats,
patternIndex: number
}>;
new(patterns: string | string[], options: StreamOptions & { stat: true }): Stream<{
path: string,
stat: Stats
}>;
new(patterns: string | string[], options: StreamOptions & { patternIndex: true }): Stream<{
path: string,
patternIndex: number
}>;
new(patterns: string | string[], options?: StreamOptions): Stream<string>;
prototype: Stream<string | {
path: string,
stat?: Stats,
patternIndex?: number
}>;
}
type Stream<T> = stream.core.Stream<never, T>;
interface EmitterConstructor {
new(pattern: string, optons: Options, callback?: (error: any, matches: string[]) => void): Emitter;
new(pattern: string, callback?: (error: any, matches: string[]) => void): Emitter;
prototype: Emitter;
}
interface Emitter extends event.Emitter {
isIgnored(path: string): boolean;
/**
* Stops the search permanently
*/
abort(): void;
/**
* Temporarely stops the search
*/
pause(): void;
/**
* Resumes the search
*/
resume(): void;
on(event: "match", callback: (match: string, stat?: Stats) => void): this;
on(event: "end", callback: (matches: string[]) => void): this;
}
interface GlobFunction {
(patterns: string | string[], options: StreamOptions & { stat: true, patternIndex: true }): Stream<{
/**
* File path
*/
path: string,
/**
* File stats
*/
stat: Stats,
/**
* Pattern index
*/
patternIndex: number
}>;
(patterns: string | string[], options: StreamOptions & { stat: true }): Stream<{
/**
* File path
*/
path: string,
/**
* File stats
*/
stat: Stats
}>;
(patterns: string | string[], options: StreamOptions & { patternIndex: true }): Stream<{
/**
* File path
*/
path: string,
/**
* Pattern index
*/
patternIndex: number
}>;
(patterns: string | string[], options?: StreamOptions): Stream<string>;
/**
* low level glob emitter
*/
Glob: EmitterConstructor;
/**
* Glob stream class
*/
Core: StreamConstructor;
}
}
/**
* Creates a glob stream
*/
const glob: I.Glob.GlobFunction;
namespace I.Watcher {
interface ConstructorOptions {
/**
* Indicates whether the process should continue to run as long as files are being watched
*/
persistent?: boolean;
/**
* If set to false then add/addDir events are also emitted for matching paths
* while instantiating the watching as watcher discovers these file paths
*/
ignoreInitial?: boolean;
/**
* Indicates whether to watch files that don't have read permissions if possible
*/
ignorePermissionErrors?: boolean;
/**
* Interval of file system polling (used when usePolling = true)
*/
interval?: number;
/**
* Interval of file system polling for binary files (used when usePolling = true)
*/
binaryInterval?: number;
/**
* If set to true then the strings passed to .watch() and .add() are treated as literal path names,
* even if they look like globs
*/
disableGlobbing?: boolean;
/**
* Whether to use the fsevents watching interface if available (true on mac by default)
*/
useFsEvents?: boolean;
/**
* Whether to use fs.watchFile (backed by polling), or fs.watch.
*/
usePolling?: boolean;
/**
* Automatically filters out artifacts that occur when using editors that use "atomic writes"
* instead of writing directly to the source file. If a file is re-added within 100 ms of being deleted,
* wather emits a change event rather than unlink then add
*/
atomic?: boolean | number;
/**
* When false, only the symlinks themselves will be watched for changes
* instead of following the link references and bubbling events through the link's path
*/
followSymlinks?: boolean;
/**
* If truthy, defines settings to control how long a file must not change after add/change events and only then emit the event
*/
awaitWriteFinish?: boolean | {
/**
* Amount of time in milliseconds for a file size to remain constant before emitting its event
*/
stabilityThreshold?: number,
/**
* File size polling interval
*/
pollInterval?: number
};
/**
* Defines files/paths to be ignored
*/
ignored?: string[];
/**
* Always passes fs.Stat file with `add`, `addDir` events
*/
alwaysStat?: boolean;
/**
* If set, limits how many levels of subdirectories will be traversed
*/
depth?: number;
/**
* The base directory from which watch paths are to be derived
*/
cwd?: string;
}
type Event = "add" | "addDir" | "change" | "unlink" | "unlinkDir" | "ready" | "raw" | "error";
}
/**
* Represents a file watcher
*/
class Watcher extends event.Emitter {
constructor(options?: I.Watcher.ConstructorOptions);
/**
* Adds files, directories, or glob patterns for tracking
*/
add(path: string | string[]): this;
/**
* Stops watching files, directories, or glob patterns.
*/
unwatch(path: string | string[]): this;
/**
* Removes all listeners from watched files
*/
close(): this;
/**
* Returns an object representing all the paths on the file system being watched by this watcher
*/
getWatched(): { [path: string]: string[] };
on(event: "all", callback: (event: I.Watcher.Event, path: string, stat?: I.Stats) => void): this;
on(event: "raw", callback: (event: string, path: string, details: object) => void): this;
on(event: I.Watcher.Event, callback: (path: string, stat?: I.Stats) => void): this;
}
/**
* Creates a Watcher instance with the given options and starts watching the given paths
*/
function watch(paths: string | string[], options?: I.Watcher.ConstructorOptions): Watcher;
/**
* Returns true if the given path refers to a file
*/
function isFile(path: string): Promise<boolean>;
/**
* Returns true if the given path refers to a file
*/
function isFileSync(path: string): boolean;
/**
* Returns true if the given path refers to a direcotry
*/
function isDirectory(path: string): Promise<boolean>;
/**
* Returns true if the given path refers to a direcotry
*/
function isDirectorySync(path: string): boolean;
/**
* Returns true if the given path refers to an executable file
*/
function isExecutable(path: string): Promise<boolean>;
/**
* Returns true if the given path refers to an executable file
*/
function isExecutableSync(path: string): boolean;
namespace I.Which {
interface Options {
colon?: string;
path?: string;
pathExt?: string;
nothrow?: boolean;
all?: boolean;
}
interface OptionsAll extends Options {
all: true;
}
interface OptionsNothrow extends Options {
nothrow: true;
}
interface OptionsAllNothrow extends Options {
all: true;
nothrow: true;
}
}
/**
* Finds instances of a specified executable in the PATH environment variable
*/
function which(cmd: string, options: I.Which.OptionsAllNothrow): Promise<string[] | null>;
/**
* Finds instances of a specified executable in the PATH environment variable
*/
function which(cmd: string, options: I.Which.OptionsAll): Promise<string[]>;
/**
* Finds the first instance of a specified executable in the PATH environment variable
*/
function which(cmd: string, options: I.Which.OptionsNothrow): Promise<string | null>;
/**
* Finds instances of a specified executable in the PATH environment variable
*/
function which(cmd: string, options?: I.Which.Options): Promise<string>;
/**
* Finds instances of a specified executable in the PATH environment variable
*/
function whichSync(cmd: string, options: I.Which.OptionsAllNothrow): string[] | null;
/**
* Finds instances of a specified executable in the PATH environment variable
*/
function whichSync(cmd: string, options: I.Which.OptionsAll): string[];
/**
* Finds the first instance of a specified executable in the PATH environment variable
*/
function whichSync(cmd: string, options: I.Which.OptionsNothrow): string | null;
/**
* Finds instances of a specified executable in the PATH environment variable
*/
function whichSync(cmd: string, options?: I.Which.Options): string;
/**
* Opens and possibly creates a file
*/
function open(path: string | Buffer | I.URL, flags: I.Flag | number, mode?: number): Promise<I.FD>;
/**
* Opens and possibly creates a file
*/
function openSync(path: string | Buffer | I.URL, flags: I.Flag | number, mode?: number): I.FD;
/**
* Closes a file descriptor
*/
function close(fd: I.FD): Promise<void>;
/**
* Closes a file descriptor
*/
function closeSync(fd: I.FD): void;
/**
* Changes the file timestamps of a file referenced by the supplied file descriptor
*/
function futimes(fd: I.FD, atime: number, mtime: number): Promise<void>;
/**
* Changes the file timestamps of a file referenced by the supplied file descriptor
*/
function futimesSync(fd: I.FD, atime: number, mtime: number): void;
/**
* Gets file status
*/
function fstat(fd: I.FD): Promise<I.Stats>;
/**
* Gets file status
*/
function fstatSync(fd: I.FD): I.Stats;
/**
* Truncates a file to a specified length
*/
function ftruncate(fd: I.FD, length?: number): Promise<void>;
/**
* Truncates a file to a specified length
*/
function ftruncateSync(fd: I.FD, length?: number): void;
/**
* Read data from the file specified by fd
*/
function read(
fd: I.FD,
/**
* The buffer that the data will be written to
*/
buffer: Buffer | Uint8Array,
/**
* The offset in the buffer to start writing at
*/
offset: number,
/**
* An integer specifying the number of bytes to read
*/
length: number,
/**
* An argument specifying where to begin reading from in the file
*/
position: number
): Promise<number>;
function readSync(
fd: I.FD,
/**
* The buffer that the data will be written to
*/
buffer: Buffer | Uint8Array,
/**
* The offset in the buffer to start writing at
*/
offset: number,
/**
* An integer specifying the number of bytes to read
*/
length: number,
/**
* An argument specifying where to begin reading from in the file
*/
position: number
): number;
/**
* Writes buffer to the file specified by fd
*/
function write(
fd: I.FD,
buffer: Buffer | Uint8Array,
/**
* Determines the part of the buffer to be written
*/
offset?: number,
/**
* An integer specifying the number of bytes to write
*/
length?: number,
/**
* The offset from the beginning of the file where this data should be written
*/
position?: number
): Promise<number>;
/**
* Writes string to the file specified by fd
*/
function write(
fd: I.FD,
string: string,
/**
* The offset from the beginning of the file where this data should be written
*/
position?: number,
/**
* The expected string encoding
*/
encoding?: I.Encoding
): Promise<number>;
/**
* Writes buffer to the file specified by fd
*/
function writeSync(
fd: I.FD,
buffer: Buffer | Uint8Array,
/**
* Determines the part of the buffer to be written
*/
offset?: number,
/**
* An integer specifying the number of bytes to write
*/
length?: number,
/**
* The offset from the beginning of the file where this data should be written
*/
position?: number
): number;
/**
* Writes string to the file specified by fd
*/
function writeSync(
fd: I.FD,
string: string,
/**
* The offset from the beginning of the file where this data should be written
*/
position?: number,
/**
* The expected string encoding
*/
encoding?: I.Encoding
): number;
/**
* Synchronizes a file's in-core state with storage
*/
function fsync(fd: I.FD): Promise<void>;
/**
* Synchronizes a file's in-core state with storage
*/
function fsyncSync(fd: I.FD): void;
/**
* Changes ownership of a file
*/
function fchown(fd: I.FD, uid: number, gid: number): Promise<void>;
/**
* Changes ownership of a file
*/
function fchownSync(fd: I.FD, uid: number, gid: number): void;
/**
* Changes permissions of a file
*/
function fchmod(fd: I.FD, mode: number): Promise<void>;
/**
* Changes permissions of a file
*/
function fchmodSync(fd: I.FD, mode: number): void;
/**
* Repositions read/write file offset
*/
function seek(fd: I.FD, offset: number, whence: number): Promise<number>;
/**
* Applies or removes an advisory lock on an open file
*/
function flock(fd: I.FD, flags: "sh" | "ex" | "shnb" | "exnb" | "un" | number): Promise<void>;
namespace constants {
const F_OK: number;
const LOCK_EX: number;
const LOCK_NB: number;
const LOCK_SH: number;
const LOCK_UN: number;
const O_APPEND: number;
const O_CREAT: number;
const O_DIRECT: number;
const O_DIRECTORY: number;
const O_EXCL: number;
const O_NOATIME: number;
const O_NOCTTY: number;
const O_NOFOLLOW: number;
const O_NONBLOCK: number;
const O_RDONLY: number;
const O_RDWR: number;
const O_SYNC: number;
const O_TRUNC: number;
const O_WRONLY: number;
const R_OK: number;
const SEEK_CUR: number;
const SEEK_END: number;
const SEEK_SET: number;
const S_IFBLK: number;
const S_IFCHR: number;
const S_IFDIR: number;
const S_IFIFO: number;
const S_IFLNK: number;
const S_IFMT: number;
const S_IFREG: number;
const S_IFSOCK: number;
const S_IRGRP: number;
const S_IROTH: number;
const S_IRUSR: number;
const S_IRWXG: number;
const S_IRWXO: number;
const S_IRWXU: number;
const S_IWGRP: number;
const S_IWOTH: number;
const S_IWUSR: number;
const S_IXGRP: number;
const S_IXOTH: number;
const S_IXUSR: number;
const W_OK: number;
const X_OK: number;
}
/**
* Returns the canonicalized absolute pathname
*/
function realpath(path: string | Buffer | I.URL, encoding: "buffer"): Promise<Buffer>;
function realpath(path: string | Buffer | I.URL, encoding: I.Encoding): Promise<string>;
function realpath(path: string | Buffer | I.URL, options: { encoding: "buffer" }): Promise<Buffer>;
function realpath(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): Promise<string>;
/**
* Returns the canonicalized absolute pathname
*/
function realpathSync(path: string | Buffer | I.URL, encoding: "buffer"): Buffer;
function realpathSync(path: string | Buffer | I.URL, encoding: I.Encoding): string;
function realpathSync(path: string | Buffer | I.URL, options: { encoding: "buffer" }): Buffer;
function realpathSync(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): string;
namespace I {
interface ReadFileOptions {
check?: boolean;
flags?: Flag;
encoding?: null | Encoding;
}
}
/**
* Reads a file
*/
function readFile(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { check: true, encoding: null }): Promise<Buffer | null>;
function readFile(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { check: true, encoding: I.Encoding }): Promise<string | null>;
function readFile(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { check: true }): Promise<Buffer | null>;
function readFile(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { encoding: null }): Promise<Buffer>;
function readFile(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { encoding: I.Encoding }): Promise<string>;
function readFile(filepath: string | Buffer | I.URL, options: I.ReadFileOptions): Promise<Buffer>;
function readFile(filepath: string | Buffer | I.URL, encoding: null): Promise<Buffer>;
function readFile(filepath: string | Buffer | I.URL, encoding: I.Encoding): Promise<string>;
function readFile(filepath: string | Buffer | I.URL): Promise<Buffer>;
/**
* Reads a file
*/
function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { check: true, encoding: null }): Buffer | null;
function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { check: true, encoding: I.Encoding }): string | null;
function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { check: true }): Buffer | null;
function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { encoding: null }): Buffer;
function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { encoding: I.Encoding }): string;
function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions): Buffer;
function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions): Buffer;
function readFileSync(filepath: string | Buffer | I.URL, encoding: null): Buffer;
function readFileSync(filepath: string | Buffer | I.URL, encoding: I.Encoding): string;
function readFileSync(filepath: string | Buffer | I.URL): Buffer;
/**
* Reads lines from a file
*/
function readLines(filepath: string | Buffer | I.URL, options: { check: true, flags?: I.Flag, encoding?: null | I.Encoding }): Promise<string[] | null>;
function readLines(filepath: string | Buffer | I.URL, options: { check?: false, flags?: I.Flag, encoding?: null | I.Encoding }): Promise<string[]>;
function readLines(filepath: string | Buffer | I.URL, encoding?: null | I.Encoding): Promise<string[]>;
/**
* Reads lines from a file
*/
function readLinesSync(filepath: string | Buffer | I.URL, options: { check: true, flags?: I.Flag, encoding?: null | I.Encoding }): string[] | null;
function readLinesSync(filepath: string | Buffer | I.URL, options: { check?: false, flags?: I.Flag, encoding?: null | I.Encoding }): string[];
function readLinesSync(filepath: string | Buffer | I.URL, encoding?: null | I.Encoding): string[];
/**
* Reads words from a file
*/
function readWords(filepath: string | Buffer | I.URL, options: { check: true, flags?: I.Flag, encoding?: null | I.Encoding }): Promise<string[] | null>;
function readWords(filepath: string | Buffer | I.URL, options: { check?: false, flags?: I.Flag, encoding?: null | I.Encoding }): Promise<string[]>;
function readWords(filepath: string | Buffer | I.URL, encoding?: null | I.Encoding): Promise<string[]>;
/**
* Reads words from a file
*/
function readWordsSync(filepath: string | Buffer | I.URL, options: { check: true, flags?: I.Flag, encoding?: null | I.Encoding }): string[] | null;
function readWordsSync(filepath: string | Buffer | I.URL, options: { check?: false, flags?: I.Flag, encoding?: null | I.Encoding }): string[];
function readWordsSync(filepath: string | Buffer | I.URL, encoding?: null | I.Encoding): string[];
/**
* Checks whether a file exists
*/
function exists(path: string | Buffer | I.URL): Promise<boolean>;
/**
* Checks whether a file exists
*/
function existsSync(path: string | Buffer | I.URL): boolean;
/**
* Creates a new directory
*/
function mkdir(path: string, mode?: number): Promise<void>;
/**
* Creates a new directory
*/
function mkdirSync(path: string, mode?: number): Promise<void>;
/**
* Creates a new directory and any necessary subdirectories
*/
function mkdirp(path: string, mode?: number): Promise<void>;
/**
* Creates a new directory and any necessary subdirectories
*/
function mkdirpSync(path: string, mode?: number): Promise<void>;
namespace I {
interface CopyOptions {
/**
* regexp or function against which each filename is tested whether to copy it or not
*/
filter?: RegExp | ((src: string, dst: string) => boolean);
/**
* transform function which applies when files are streamed
*/
transform?(
readStream: NodeJS.ReadableStream,
writeStream: NodeJS.WritableStream,
file: {
name: string,
mode: number,
mtime: Date,
atime: Date,
stats: adone.fs.I.Stats
}
): void;
/**
* Whether to overwrite destination files if they exist.
*
* true by default
*/
clobber?: boolean; // ???
/**
* Whether to overwrite destination files if they exist.
*
* true by default
*/
overwrite?: boolean;
}
interface CopyToOptions {
/**
* Do not replace existing files
*/
ignoreExisting?: boolean;
/**
* Base direcotry for paths
*/
cwd?: string;
}
}
/**
* Recursively copies all the files from src to dst
*/
function copy(src: string, dst: string, options?: I.CopyOptions): Promise<void>;
/**
* Copies all files from src to dst
*/
function copyTo(src: string, dst: string, options?: I.CopyToOptions): Promise<void>;
/**
* Renames a file
*/
function rename(oldPath: string, newPath: string, options?: {
/**
* Will retry if fails with EPERM or EACCESS errors
*/
retries?: number,
/**
* Will retry after this delay
*/
delay?: number
}): Promise<void>;
/**
* Returns the last lines of a file
*
* @param path path to a file
* @param n number of lines to return
*/
function tail(path: string, n: number, options?: {
/**
* Line separator
*
* By default "\r\n" for windows and "\n" for others
*/
separator?: string,
/**
* The number of bytes to read at once
*
* By default 4096
*/
chunkLength?: number
/**
* Position from which to start reading (from the end)
*
* By default stats.size of the file
*/
pos?: number
}): Promise<Buffer[]>;
namespace I {
interface StatVFS {
/**
* Maximum filename length
*/
f_namemax: number;
/**
* File system block size
*/
f_bsize: number;
/**
* Fragment size
*/
f_frsize: number;
/**
* Size of fs in f_frsize units
*/
f_blocks: number;
/**
* # free blocks for unprivileged users
*/
f_bavail: number;
/**
* # free blocks
*/
f_bfree: number;
/**
* # inodes
*/
f_files: number;
/**
* # free inodes for unprivileged users
*/
f_favail: number;
/**
* # free inodes
*/
f_ffree: number;
}
}
/**
* Returns information about a mounted file system
*/
function statVFS(path: string): Promise<I.StatVFS>;
namespace I {
interface ReadStreamOptions {
flags?: Flag;
encoding?: Encoding | null;
/**
* File mode
*/
mode?: number;
/**
* Inclusive start of the reading range
*/
start?: number;
/**
* Inclusive end of the reading range
*/
end?: number;
}
interface ReadStreamOptionsFD extends ReadStreamOptions {
/**
* Use the specified file descriptor for reading instead of `path`
*/
fd: number;
/**
* Whether to close the file descriptor
*/
autoClose?: boolean;
}
}
/**
* Returns a read stream for the given file
*/
function createReadStream(path: null | undefined, options: I.ReadStreamOptionsFD): I.ReadStream;
function createReadStream(path: string | Buffer | I.URL, options?: I.ReadStreamOptions): I.ReadStream;
function createReadStream(path: string | Buffer | I.URL, encoding: I.Encoding | null): I.ReadStream;
namespace I {
interface WriteStreamOptions {
flags?: Flag;
defaultEncoding?: Encoding | null;
/**
* File mode
*/
mode?: number;
/**
* Start position to write data at some position past the beginning of the file
*/
start?: number;
}
interface WriteStreamOptionsFD extends WriteStreamOptions {
/**
* Use the specified file descriptor for writing instead of `path`
*/
fd: number;
/**
* Whether to close the file descriptor
*/
autoClose?: boolean;
}
}
/**
* Returns a write stream to the given file
*/
function createWriteStream(path: null | undefined, options: I.WriteStreamOptionsFD): I.WriteStream;
function createWriteStream(path: string | Buffer | I.URL, options?: I.WriteStreamOptions): I.WriteStream;
function createWriteStream(path: string | Buffer | I.URL, encoding: I.Encoding | null): I.WriteStream;
namespace I {
interface TmpNameOptions {
name?: string;
tries?: number;
template?: RegExp;
dir?: string;
prefix?: string;
ext?: string;
}
}
/**
* Generates a temporary filepath
*/
function tmpName(options?: I.TmpNameOptions): Promise<string>;
/**
* Returns the current user homedir
*/
function homeDir(): string;
/**
* TODO
*/
function lookup(path: string): Promise<string>;
namespace I.TailWatcher {
interface ConstructorOptions {
/**
* Uses this separator to split lines
*/
separator?: string | RegExp;
/**
* Options for fs.watch
*/
fsWatchOptions?: object;
/**
* Start from the beginning of the file
*/
fromBeginning?: boolean;
/**
* Follow the file when it renames
*/
follow?: boolean;
/**
* use fs.watchFile
*/
useWatchFile?: boolean;
/**
* Use the given encoding for reading
*/
encoding?: Encoding | null;
/**
* Start watching from the given position
*/
pos?: number;
}
}
/**
* Represents an event emitter that watches for a file growing,
* emits "line" event for each new line in a file
*/
class TailWatcher extends event.Emitter {
constructor(filename: string, options?: I.TailWatcher.ConstructorOptions);
/**
* Stop watching
*/
unwatch(): void;
on(event: "line", callback: (line: string) => void): this;
}
/**
* Creates a new TailWatcher instance with the given arguments
*/
function watchTail(filename: string, options?: I.TailWatcher.ConstructorOptions): TailWatcher;
namespace I {
interface WriteFileAtomicOptions {
chown?: {
gid?: number;
uid?: number;
};
encoding?: string | null;
fsync?: boolean;
mode?: number;
}
}
function writeFileAtomic(filename: string, data: Buffer | string | Uint8Array, options?: I.WriteFileAtomicOptions): Promise<void>;
}
} | the_stack |
import {SerializableMemoryObject} from "./serializable-memory-object";
/* Helper Types */
type StructMemberType = "uint8" | "uint16" | "uint32" | "uint8array" | "uint8array-reversed" | "struct";
type StructBuildOmitKeys = "member" | "method" | "padding" | "build" | "default";
type StructChild = { offset:number, struct: Struct };
export type BuiltStruct<T = Struct> = Omit<T, StructBuildOmitKeys>;
export type StructFactorySignature<T = Struct> = (data?: Buffer) => T;
export type StructMemoryAlignment = "unaligned" | "aligned";
/**
* Struct provides a builder-like interface to create Buffer-based memory
* structures for read/write interfacing with data structures from adapters.
*/
export class Struct implements SerializableMemoryObject {
/**
* Creates an empty struct. Further calls to `member()` and `method()` functions will form the structure.
* Finally call to `build()` will type the resulting structure appropriately without internal functions.
*/
public static new(): Struct {
return new Struct();
}
private buffer: Buffer;
private defaultData: Buffer;
private members: { key: string, offset: number, type: StructMemberType, length?: number }[] = [];
private childStructs: { [key: string]: StructChild } = {};
private length = 0;
private paddingByte = 0x00;
private constructor() { }
/**
* Returns raw contents of the structure as a sliced Buffer.
* Mutations to the returned buffer will not be reflected within struct.
*/
public serialize(alignment: StructMemoryAlignment = "unaligned", padLength = true, parentOffset = 0): Buffer {
switch (alignment) {
case "unaligned": {
/* update child struct values and return as-is (unaligned) */
/* istanbul ignore next */
for (const key of Object.keys(this.childStructs)) {
const child = this.childStructs[key];
this.buffer.set(child.struct.serialize(alignment), child.offset);
}
return Buffer.from(this.buffer);
}
case "aligned": {
/* create 16-bit aligned buffer */
const aligned = Buffer.alloc(this.getLength(alignment, padLength, parentOffset), this.paddingByte);
let offset = 0;
for (const member of this.members) {
switch (member.type) {
case "uint8":
aligned.set(this.buffer.slice(member.offset, member.offset + 1), offset);
offset += 1;
break;
case "uint16":
offset += offset % 2;
aligned.set(this.buffer.slice(member.offset, member.offset + 2), offset);
offset += 2;
break;
case "uint32":
offset += offset % 2;
aligned.set(this.buffer.slice(member.offset, member.offset + 4), offset);
offset += 4;
break;
case "uint8array":
case "uint8array-reversed":
aligned.set(this.buffer.slice(member.offset, member.offset + member.length), offset);
offset += member.length;
break;
case "struct":
const structData = this.childStructs[member.key].struct.serialize(alignment, false, offset);
aligned.set(structData, offset);
offset += structData.length;
break;
}
}
return aligned;
}
}
}
/**
* Returns total length of the struct. Struct length is always fixed and configured
* by calls to `member()` methods.
*/
/* istanbul ignore next */
public getLength(alignment: StructMemoryAlignment = "unaligned", padLength = true, parentOffset = 0): number {
switch (alignment) {
case "unaligned": {
/* return actual length */
return this.length;
}
case "aligned": {
/* compute aligned length and return */
let length = this.members.reduce((offset, member) => {
switch (member.type) {
case "uint8": offset += 1; break;
case "uint16": offset += ((parentOffset + offset) % 2) + 2; break;
case "uint32": offset += ((parentOffset + offset) % 2) + 4; break;
case "uint8array":
case "uint8array-reversed": offset += member.length; break;
case "struct": offset += this.childStructs[member.key].struct.getLength(alignment, false); break;
}
return offset;
}, 0);
if (padLength) {
length += length % 2;
}
return length;
}
}
}
/**
* Returns structure contents in JS object format.
*/
// eslint-disable-next-line max-len
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types,@typescript-eslint/explicit-function-return-type
public toJSON() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return this.members.reduce((a, c) => { a[c.key] = (this as any)[c.key]; return a; }, {} as any);
}
/**
* Adds a numeric member of `uint8`, `uint16` or `uint32` type.
* Internal representation is always little endian.
*
* *This method is stripped from type on struct `build()`.*
*
* @param type Underlying data type (uint8, uint16 or uint32).
* @param name Name of the struct member.
*/
public member<T extends number, N extends string, R extends this & Record<N, T>>
(type: "uint8" | "uint16" | "uint32", name: N): R;
/**
* Adds an uint8 array (byte array) as a struct member.
*
* *This method is stripped from type on struct `build()`.*
*
* @param type Underlying data type. Must be `uint8array`.
* @param name Name of the struct member.
* @param length Length of the byte array.
*/
public member<T extends Buffer, N extends string, R extends this & Record<N, T>>
(type: "uint8array" | "uint8array-reversed", name: N, length: number): R;
/**
* Adds another struct type as a struct member. Struct factory is provided
* as a child struct definition source.
*
* *This method is stripped from type on struct `build()`.*
*
* @param type Underlying data type. Must be `struct`.
* @param name Name of the struct member.
* @param structFactory Factory providing the wanted child struct.
*/
public member<T extends BuiltStruct, N extends string, R extends this & Record<N, T>>
(type: "struct", name: N, structFactory: StructFactorySignature<T>): R;
public member<T extends number | BuiltStruct, N extends string, R extends this & Record<N, T>>
(type: StructMemberType, name: N, lengthOrStructFactory?: number | StructFactorySignature<T>): R {
const offset = this.length;
const structFactory = type === "struct" ? lengthOrStructFactory as StructFactorySignature<T> : undefined;
const length = type === "struct" ?
(structFactory() as unknown as Struct).length :
lengthOrStructFactory as number;
switch (type) {
case "uint8": {
Object.defineProperty(this, name,{
enumerable: true,
get: () => this.buffer.readUInt8(offset),
set: (value: number) => this.buffer.writeUInt8(value, offset)
});
this.length += 1;
break;
}
case "uint16": {
Object.defineProperty(this, name,{
enumerable: true,
get: () => this.buffer.readUInt16LE(offset),
set: (value: number) => this.buffer.writeUInt16LE(value, offset)
});
this.length += 2;
break;
}
case "uint32": {
Object.defineProperty(this, name,{
enumerable: true,
get: () => this.buffer.readUInt32LE(offset),
set: (value: number) => this.buffer.writeUInt32LE(value, offset)
});
this.length += 4;
break;
}
case "uint8array":
case "uint8array-reversed": {
/* istanbul ignore next */
if (!length) {
throw new Error("Struct builder requires length for `uint8array` and `uint8array-reversed` type");
}
Object.defineProperty(this, name,{
enumerable: true,
get: () => type === "uint8array-reversed" ?
Buffer.from(this.buffer.slice(offset, offset + length)).reverse() :
Buffer.from(this.buffer.slice(offset, offset + length)),
set: (value: Buffer) => {
if (value.length !== length) {
throw new Error(`Invalid length for member ${name} (expected=${length}, got=${value.length})`);
}
if (type === "uint8array-reversed") {
value = Buffer.from(value).reverse();
}
for (let i = 0; i < length; i++) {
this.buffer[offset + i] = value[i];
}
}
});
this.length += length;
break;
}
case "struct": {
this.childStructs[name] = {offset, struct: structFactory() as unknown as Struct};
Object.defineProperty(this, name, {
enumerable: true,
get: () => this.childStructs[name].struct
});
this.length += length;
}
}
this.members.push({key: name, offset, type, length});
return this as R;
}
/**
* Adds a custom method to the struct.
*
* *This method is stripped from type on struct `build()`.*
*
* @param name Name of the method to be appended.
* @param returnType Return type (eg. `Buffer.prototype`).
* @param body Function implementation. Takes struct as a first and single input parameter.
*/
public method<T, N extends string, R extends this & Record<N, () => T>>
(name: N, returnType: T, body: (struct: R) => T): R {
Object.defineProperty(this, name, {
enumerable: true,
configurable: false,
writable: false,
value: () => body.bind(this)(this)
});
return this as R;
}
/**
* Sets default data to initialize empty struct with.
*
* @param data Data to initialize empty struct with.
*/
/* istanbul ignore next */
public default(data: Buffer): this {
if (data.length !== this.length) {
throw new Error("Default value needs to have the length of unaligned structure.");
}
this.defaultData = Buffer.from(data);
return this;
}
/**
* Sets byte to use for padding.
*
* @param padding Byte to use for padding
*/
/* istanbul ignore next */
public padding(padding = 0x00): this {
this.paddingByte = padding;
return this;
}
/**
* Creates the struct and optionally fills it with data. If data is provided, the length
* of the provided buffer needs to match the structure length.
*
* *This method is stripped from type on struct `build()`.*
*/
public build(data?: Buffer): BuiltStruct<this> {
if (data) {
if (data.length === this.getLength("unaligned")) {
this.buffer = Buffer.from(data);
for (const key of Object.keys(this.childStructs)) {
const child = this.childStructs[key];
child.struct.build(this.buffer.slice(child.offset, child.offset + child.struct.length));
}
} else if (data.length === this.getLength("aligned")) {
this.buffer = Buffer.alloc(this.length, this.paddingByte);
let offset = 0;
for (const member of this.members) {
switch (member.type) {
case "uint8":
this.buffer.set(data.slice(offset, offset + 1), member.offset);
offset += 1;
break;
case "uint16":
offset += offset % 2;
this.buffer.set(data.slice(offset, offset + 2), member.offset);
offset += 2;
break;
case "uint32":
offset += offset % 2;
this.buffer.set(data.slice(offset, offset + 4), member.offset);
offset += 4;
break;
case "uint8array":
case "uint8array-reversed":
this.buffer.set(data.slice(offset, offset + member.length), member.offset);
offset += member.length;
break;
case "struct":
const child = this.childStructs[member.key];
child.struct.build(data.slice(offset, offset + child.struct.length));
this.buffer.set(child.struct.serialize(), member.offset);
offset += child.struct.length;
break;
}
}
} else {
const expectedLengths = `${this.getLength("unaligned")}/${this.getLength("aligned")}`;
throw new Error(`Struct length mismatch (expected=${expectedLengths}, got=${data.length})`);
}
} else {
this.buffer = this.defaultData ? Buffer.from(this.defaultData) : Buffer.alloc(this.length);
}
return this;
}
} | the_stack |
// Type definitions for es2015-i18n-tag
// Project: i18n Tagged Template Literals
// Definitions by: Steffen Kolmer <https://github.com/skolmer/es2015-i18n-tag>
declare module 'es2015-i18n-tag' {
type NumberConfig = {
/**
* The locale matching algorithm to use. The default is "best fit".
* For information about this option, see https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation
*/
localeMatcher?: "lookup" | "best fit",
/**
* The formatting style to use.
* Possible values are "decimal" for plain number formatting, "currency" for currency formatting, and "percent" for percent formatting; the default is "decimal".
*/
style?: "decimal" | "currency" | "percent",
/**
* The currency to use in currency formatting. Possible values are the ISO 4217 currency codes, such as "USD" for the US dollar, "EUR" for the euro, or "CNY" for the Chinese RMB
* See the Current currency & funds code list. http://www.currency-iso.org/en/home/tables/table-a1.html
* If the style is "currency", the currency property must be provided.
*/
currency?: string,
/**
* How to display the currency in currency formatting.
* Possible values are "symbol" to use a localized currency symbol such as €, "code" to use the ISO currency code, "name" to use a localized currency name such as "dollar"; the default is "symbol".
*/
currencyDisplay?: "symbol" | "code" | "name",
/**
* Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators. The default is true.
*/
useGrouping?: boolean,
/**
* The minimum number of integer digits to use. Possible values are from 1 to 21; the default is 1.
*/
minimumIntegerDigits?: 1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21,
/**
* The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information).
*/
minimumFractionDigits?: 0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|20,
/**
* The maximum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number formatting is the larger of minimumFractionDigits and 3; the default for currency formatting is the larger of minimumFractionDigits and the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information); the default for percent formatting is the larger of minimumFractionDigits and 0.
*/
maximumFractionDigits?: 0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|20,
/**
* The minimum number of significant digits to use. Possible values are from 1 to 21; the default is 1.
*/
minimumSignificantDigits?: 1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21,
/**
* The maximum number of significant digits to use. Possible values are from 1 to 21; the default is minimumSignificantDigits.
*/
maximumSignificantDigits?: 1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21,
};
type DateConfig = {
/**
* The locale matching algorithm to use. The default is "best fit".
* For information about this option, see https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation
*/
localeMatcher?: "lookup" | "best fit",
/**
* The time zone to use. The default is the runtime's default time zone.
*/
timeZone?: string,
/**
* Whether to use 12-hour time (as opposed to 24-hour time). The default is locale dependent.
*/
hour12?: boolean,
/**
* The format matching algorithm to use. The default is "best fit".
*/
formatMatcher?: "basic" | "best fit",
/**
* The representation of the weekday.
*/
weekday?: "narrow" | "short" | "long",
/**
* The representation of the era
*/
era?: "narrow" | "short" | "long",
/**
* The representation of the year.
*/
year?: "numeric" | "2-digit",
/**
* The representation of the month.
*/
month?: "numeric" | "2-digit" | "narrow" | "short" | "long",
/**
* The representation of the day.
*/
day?: "numeric" | "2-digit",
/**
* The representation of the hour.
*/
hour?: "numeric" | "2-digit",
/**
* The representation of the minute.
*/
minute?: "numeric" | "2-digit",
/**
* The representation of the second.
*/
second?: "numeric" | "2-digit",
/**
* The representation of the time zone name.
*/
timeZoneName?: "short" | "long",
};
type Config = {
/**
* A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation
*/
locales?: string | Array<string>,
/**
* An object that contains translations as key-value-pairs
*/
translations?: {
[key: string]: string | { [key: string]: string }
},
/**
* The name of the current configuration group. This option is recommended for libraries.
* To avoid configuration override, set a group that is unique to your library.
*/
group?: string,
/**
* For more information about NumberFormat options, see https://goo.gl/pDwbG2
*/
number?: NumberConfig,
/**
* For more information about DateTimeFormat options, see https://goo.gl/lslekB
*/
date?: DateConfig,
/**
* Can be used to define custom standard formatters for date, number and string suffix functions. `${ new Date() }:t([formatter])`
*/
standardFormatters?: {
date?: {
[name : string] : (locales : string | Array<string>, dateOptions : DateConfig, value : Date) => string
}
number?: {
[name : string] : (locales : string | Array<string>, numberOptions : NumberConfig, value : number) => string
}
string?: {
[name : string] : (locales : string | Array<string>, stringOptions : { [key: string]: any }, value : string) => string
}
}
};
interface i18nTemplateTag {
/**
* Transforms i18n tagged template literals.
*
* @param literals Template literals.
* @param values Template values.
*
* @example
*
* // common syntax:
* i18n`The date is ${date}:t(D).`;
* @example
*
* // with group settings:
* i18n('test-group', 'test-config')`Time: ${new Date()}:t(T)`;
*
* @example
*
* // with i18nGroup decorator:
* this.i18n`Time: ${new Date()}:t(T)`;
*/
(literals: TemplateStringsArray, ...values: Array<any>) : any;
/**
* Translates i18n translation key.
*
* @param key the translation key.
* @param values the translation parameters.
*
* @example
*
* // common syntax:
* i18n.translate('number: ${0}; text: ${1}', 24, 'test');
* i18n.translate('The date is ${0}', { value: new Date(), formatter: 't', format: 'D' });
*
* @example
*
* // with group settings:
* i18n('test-group', 'test-config').translate('Time: ${0}', { value: new Date(), formatter: 't', format: 'D' });
*
* @example
*
* // with i18nGroup decorator:
* this.i18n.translate('Time: ${0}', { value: new Date(), formatter: 't', format: 'D' });
*/
translate(key: string, ...values: Array<any>): any;
}
interface i18nTag extends i18nTemplateTag {
/**
* Returns the i18n template tag for a translation or config group.
*
* @param group the name of the translation group.
* @param config the name of the configuration group. This option is recommended for libraries. To avoid configuration override, set a group that is unique to your library.
*
* @example
*
* // with custom translation group:
* i18n('components/Clock.js')`Time`;
*
* @example
*
* // with file module group and configuration group:
* i18n(__translationGroup, 'my-lib')`Welcome`;
*/
(group: string, config?: string): i18nTemplateTag;
}
/**
* i18n Template Literal Tag
*/
const i18n: i18nTag;
export default i18n;
/**
* Sets i18n tagged template literals configuration.
*
* @param config Configuration object.
*
* @example
*
* // sample configuration:
* i18nConfig({
* locales: 'de-DE',
* group: 'my-lib', // Optional, can be used to avoid configuration overrides. This is recommended for libraries!
* translations: {
* "Hello ${0}, you have ${1} in your bank account.": "Hallo ${0}, Sie haben ${1} auf Ihrem Bankkonto."
* },
* number: {
* [...options] // Intl NumberFormat options as described here: https://goo.gl/pDwbG2
* },
* date: {
* [...options] // Intl DateTimeFormat options as described here: https://goo.gl/lslekB
* }
* })
*/
export function i18nConfig(config: Config) : void;
/**
* i18n translation and configuration group class decorator.
*
* @param group the name of the translation group.
* @param config the name of the configuration group. This option is recommended for libraries. To avoid configuration override, set a group that is unique to your library.
*
* @example
*
* // default syntax:
* class Clock {
* tick() {
* return this.i18n`Time: ${new Date()}:t(T)`
* }
* }
* export default i18nGroup(__translationGroup, 'my-lib')(Clock)
*
* @example
*
* // experimental class decorator syntax:
* @i18nGroup(__translationGroup, 'my-lib')
* class Clock {
* tick() {
* return this.i18n`Time: ${new Date()}:t(T)`
* }
* }
* export default Clock
*/
export function i18nGroup(group: string, config?: string): <TFunction extends Function>(target: TFunction) => TFunction & Group;
type GroupClass = {
/**
* i18n Template Literal Tag
*/
i18n: i18nTemplateTag
}
interface Group {
new (...args): GroupClass;
prototype: GroupClass;
}
} | the_stack |
import {
createStubInstance,
expect,
sinon,
StubbedInstanceWithSinonAccessor,
} from '@loopback/testlab';
import {OriginatorController} from '../../controllers';
import {IdArrays, Message, StatusMarker} from '../../models';
import {
AttachmentRepository,
GroupRepository,
MessageRepository,
ThreadRepository,
} from '../../repositories';
import {PartyTypeMarker, StorageMarker, VisibilityMarker} from '../../types';
import {
getSampleDataWithOutGroup,
getSampleMailData,
group,
message,
messageIds,
thread,
transactionStub,
user,
attachment,
} from './sample-data';
const sampleMessageId = 'sample-message-id';
const sampleExtId = 'sample-ext-id';
const sampleMarkMail = 'read';
const sampleAttachmentId = 'sample-attachment-id';
const sampleIdArray = new IdArrays({
messageIds: ['sample=message-id'],
threadIds: ['sample-thread-id'],
});
let messageRepository: StubbedInstanceWithSinonAccessor<MessageRepository>;
let threadRepository: StubbedInstanceWithSinonAccessor<ThreadRepository>;
let groupRepository: StubbedInstanceWithSinonAccessor<GroupRepository>;
let attachmentRepository: StubbedInstanceWithSinonAccessor<AttachmentRepository>;
let controller: OriginatorController;
const setUpStub = () => {
messageRepository = createStubInstance(MessageRepository);
threadRepository = createStubInstance(ThreadRepository);
groupRepository = createStubInstance(GroupRepository);
attachmentRepository = createStubInstance(AttachmentRepository);
controller = new OriginatorController(
messageRepository,
threadRepository,
groupRepository,
attachmentRepository,
user,
);
};
describe('originatorcontroller(unit) as', () => {
describe('POST /mails', () => {
it('compose a mail with attachments and meta-data', async () => {
setUpStub();
const threadCreate = threadRepository.stubs.incrementOrCreate;
threadCreate.resolves(thread);
const transaction = messageRepository.stubs.beginTransaction;
transaction.resolves(transactionStub);
const mailStub = messageRepository.stubs.createRelational;
mailStub.resolves(message);
const controllerResult = await controller.composeMail(getSampleMailData);
// eslint-disable-next-line no-unused-expressions
expect(controllerResult).to.have.a.property('id').which.is.a.String;
sinon.assert.calledOnce(threadCreate);
sinon.assert.calledOnce(transaction);
sinon.assert.calledOnce(mailStub);
});
it("throws an error if there isn't any recipient", async () => {
setUpStub();
const controllerResult = await controller
.composeMail(getSampleDataWithOutGroup)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
});
describe('PUT /mails/{messageId}', () => {
it('throws error if attachment is not present in mail', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(message);
const transaction = messageRepository.stubs.beginTransaction;
transaction.resolves(transactionStub);
const mailStub = messageRepository.stubs.updateById;
mailStub.resolves();
const controllerResult = await controller
.updateDraft(getSampleMailData, sampleMessageId)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
sinon.assert.calledOnce(transaction);
});
it('throws error if mail is not present', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves();
const mailStub = messageRepository.stubs.updateById;
mailStub.resolves();
const controllerResult = await controller
.updateDraft(getSampleMailData, sampleMessageId)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
it('throws error if mail is not draft', async () => {
setUpStub();
const messageChange = message;
messageChange.status = StatusMarker.send;
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(messageChange);
const mailStub = messageRepository.stubs.updateById;
mailStub.resolves();
const controllerResult = await controller
.updateDraft(getSampleMailData, sampleMessageId)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
});
describe('POST /mails/{messageId}/attachments', () => {
it('throws error if attachment is not present', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(message);
const mailStub = messageRepository.stubs.updateById;
mailStub.resolves();
const filter: Partial<Message> = {id: sampleMessageId};
const attachmentArray = [attachment];
const controllerResult = await controller
.addAttachment({attachments: attachmentArray}, sampleMessageId, filter)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
it('throws error if message is not present', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves();
const mailStub = messageRepository.stubs.updateById;
mailStub.resolves();
const filter: Partial<Message> = {id: sampleMessageId};
const attachmentArray = [attachment];
const controllerResult = await controller
.addAttachment({attachments: attachmentArray}, sampleMessageId, filter)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
it('throws error if message status is not draft', async () => {
setUpStub();
const messageChange = message;
messageChange.status = StatusMarker.send;
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(messageChange);
const mailStub = messageRepository.stubs.updateById;
mailStub.resolves();
const filter: Partial<Message> = {id: sampleMessageId};
const attachmentArray = [attachment];
const controllerResult = await controller
.addAttachment({attachments: attachmentArray}, sampleMessageId, filter)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
});
describe('DELETE /mails/{messageId}/attachments/{attachmentId}', () => {
it('throws error if attachment is not present while deleting', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(message);
const mailStub = messageRepository.stubs.updateById;
mailStub.resolves();
const filter: Partial<Message> = {id: sampleMessageId};
const controllerResult = await controller
.removeAttachment(sampleMessageId, sampleAttachmentId, filter)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
it('throws error if message is not present', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves();
const mailStub = messageRepository.stubs.updateById;
mailStub.resolves();
const filter: Partial<Message> = {id: sampleMessageId};
const controllerResult = await controller
.removeAttachment(sampleMessageId, sampleAttachmentId, filter)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
it('throws error if message status is not draft', async () => {
setUpStub();
const messageChange = message;
messageChange.status = StatusMarker.send;
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(messageChange);
const mailStub = messageRepository.stubs.updateById;
mailStub.resolves();
const filter: Partial<Message> = {id: sampleMessageId};
const controllerResult = await controller
.removeAttachment(sampleMessageId, sampleAttachmentId, filter)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
});
describe('DELETE /mails/bulk/{storage}/{action}', () => {
it('trashes mails of inbox', async () => {
setUpStub();
const groupFind = groupRepository.stubs.find;
groupFind.resolves([group]);
const groupUpdate = groupRepository.stubs.update;
groupUpdate.resolves();
const storage: StorageMarker = StorageMarker.inbox;
const action = 'trash';
const controllerResult = await controller.trashBulk(
storage,
action,
{
extId: sampleExtId,
},
messageIds,
);
// eslint-disable-next-line no-unused-expressions
expect(controllerResult).to.have.a.property('items').which.is.an.Array;
sinon.assert.calledOnce(groupFind);
sinon.assert.calledOnce(groupUpdate);
});
it('deletes mails of trash', async () => {
setUpStub();
const groupFind = groupRepository.stubs.find;
groupFind.resolves([group]);
const groupUpdate = groupRepository.stubs.update;
groupUpdate.resolves();
const storage: StorageMarker = StorageMarker.trash;
const action = 'delete';
const controllerResult = await controller.trashBulk(
storage,
action,
{
extId: sampleExtId,
},
messageIds,
);
// eslint-disable-next-line no-unused-expressions
expect(controllerResult).to.have.a.property('items').which.is.an.Array;
sinon.assert.calledOnce(groupFind);
sinon.assert.calledOnce(groupUpdate);
});
it('throws error if storage is in draft', async () => {
setUpStub();
const groupFind = groupRepository.stubs.find;
groupFind.resolves([group]);
const groupUpdate = groupRepository.stubs.update;
groupUpdate.resolves();
const storage: StorageMarker = StorageMarker.draft;
const action = 'trash';
const controllerResult = await controller
.trashBulk(
storage,
action,
{
extId: sampleExtId,
},
messageIds,
)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
it('throws error if storage is not trash or draft', async () => {
setUpStub();
const groupFind = groupRepository.stubs.find;
groupFind.resolves([group]);
const groupUpdate = groupRepository.stubs.update;
groupUpdate.resolves();
const storage: StorageMarker = StorageMarker.inbox;
const action = 'delete';
const controllerResult = await controller
.trashBulk(
storage,
action,
{
extId: sampleExtId,
},
messageIds,
)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
it('throws an error if an group is not found', async () => {
setUpStub();
const groupFind = groupRepository.stubs.find;
groupFind.resolves([]);
const storage: StorageMarker = StorageMarker.trash;
const action = 'delete';
const controllerResult = await controller
.trashBulk(
storage,
action,
{
extId: sampleExtId,
},
messageIds,
)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
sinon.assert.calledOnce(groupFind);
});
it('throws an error if we trash a mail which is already in trash', async () => {
setUpStub();
const groupFind = groupRepository.stubs.find;
groupFind.resolves([group]);
const storage: StorageMarker = StorageMarker.trash;
const action = 'trash';
const controllerResult = await controller
.trashBulk(
storage,
action,
{
extId: sampleExtId,
},
messageIds,
)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
sinon.assert.calledOnce(groupFind);
});
});
describe('PATCH /mails/bulk/restore', () => {
it('Restores mail from trash', async () => {
setUpStub();
const groupFind = groupRepository.stubs.find;
groupFind.resolves([group]);
const groupUpdate = groupRepository.stubs.update;
groupUpdate.resolves();
const controllerResult = await controller.restore({}, messageIds);
// eslint-disable-next-line no-unused-expressions
expect(controllerResult).has.property('item').which.is.a.Object;
sinon.assert.calledOnce(groupFind);
sinon.assert.calledOnce(groupUpdate);
});
it('Throws an Error if a group is not found', async () => {
setUpStub();
const groupFind = groupRepository.stubs.find;
groupFind.resolves();
const controllerResult = await controller
.restore({}, messageIds)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
sinon.assert.calledOnce(groupFind);
});
it('Throws error if group length is 0', async () => {
setUpStub();
const groupFind = groupRepository.stubs.find;
groupFind.resolves([]);
const controllerResult = await controller
.restore({}, messageIds)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
});
describe('PATCH mails/{messageId}/send', () => {
it('Sends a Drafted message', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(message);
const groupFindStub = groupRepository.stubs.find;
groupFindStub.resolves([group]);
const messageUpdateStub = messageRepository.stubs.updateById;
messageUpdateStub.resolves();
const groupUpdateStub = groupRepository.stubs.update;
groupUpdateStub.resolves();
const controllerResult = await controller.sendDraft(sampleMessageId, {
extId: sampleExtId,
});
// eslint-disable-next-line no-unused-expressions
expect(controllerResult).to.have.a.property('id').which.is.a.String;
sinon.assert.calledOnce(messageUpdateStub);
sinon.assert.calledOnce(groupFindStub);
sinon.assert.calledOnce(messageUpdateStub);
sinon.assert.calledOnce(groupUpdateStub);
});
it('Sends a Drafted message with type changed', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(message);
const groupChange = group;
groupChange.type = PartyTypeMarker.bcc;
const groupFindStub = groupRepository.stubs.find;
groupFindStub.resolves([groupChange]);
const messageUpdateStub = messageRepository.stubs.updateById;
messageUpdateStub.resolves();
const groupUpdateStub = groupRepository.stubs.update;
groupUpdateStub.resolves();
const controllerResult = await controller.sendDraft(sampleMessageId, {
extId: sampleExtId,
});
// eslint-disable-next-line no-unused-expressions
expect(controllerResult).to.have.a.property('id').which.is.a.String;
});
it('Throws an Error if a message is not found', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves();
const controllerError = await controller
.sendDraft(sampleMessageId, {
extId: sampleExtId,
})
.catch(error => error);
expect(controllerError).instanceOf(Error);
sinon.assert.calledOnce(messageFindOneStub);
});
it('Throws an Error if a group is not found', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(message);
const groupRepositoryStub = groupRepository.stubs.find;
groupRepositoryStub.resolves();
const controllerError = await controller
.sendDraft(sampleMessageId, {
extId: sampleExtId,
})
.catch(error => error);
expect(controllerError).instanceOf(Error);
sinon.assert.calledOnce(messageFindOneStub);
sinon.assert.calledOnce(groupRepositoryStub);
});
});
describe('PATCH mails/marking/{markType}', () => {
it('Sends true for read category', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(message);
const groupFindStub = groupRepository.stubs.find;
groupFindStub.resolves([group]);
const messageUpdateStub = messageRepository.stubs.updateById;
messageUpdateStub.resolves();
const groupUpdateStub = groupRepository.stubs.update;
groupUpdateStub.resolves();
const controllerResult = await controller.markMail(
sampleMarkMail,
sampleIdArray,
);
// eslint-disable-next-line no-unused-expressions
expect(controllerResult).to.have.a.property('success').which.is.a.Boolean;
});
it('Sends true for unread category', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(message);
const groupFindStub = groupRepository.stubs.find;
groupFindStub.resolves([group]);
const messageUpdateStub = messageRepository.stubs.updateById;
messageUpdateStub.resolves();
const groupUpdateStub = groupRepository.stubs.update;
groupUpdateStub.resolves();
const controllerResult = await controller.markMail(
'unread',
sampleIdArray,
);
// eslint-disable-next-line no-unused-expressions
expect(controllerResult).to.have.a.property('success').which.is.a.Boolean;
});
it('Sends true for important category', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(message);
const groupFindStub = groupRepository.stubs.find;
groupFindStub.resolves([group]);
const messageUpdateStub = messageRepository.stubs.updateById;
messageUpdateStub.resolves();
const groupUpdateStub = groupRepository.stubs.update;
groupUpdateStub.resolves();
const controllerResult = await controller.markMail(
'important',
sampleIdArray,
);
// eslint-disable-next-line no-unused-expressions
expect(controllerResult).to.have.a.property('success').which.is.a.Boolean;
});
it('Sends true for not-important category', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(message);
const groupFindStub = groupRepository.stubs.find;
groupFindStub.resolves([group]);
const messageUpdateStub = messageRepository.stubs.updateById;
messageUpdateStub.resolves();
const groupUpdateStub = groupRepository.stubs.update;
groupUpdateStub.resolves();
const controllerResult = await controller.markMail(
'not-important',
sampleIdArray,
);
// eslint-disable-next-line no-unused-expressions
expect(controllerResult).to.have.a.property('success').which.is.a.Boolean;
});
it('Throws an Error if a category is not found', async () => {
setUpStub();
const messageFindOneStub = messageRepository.stubs.findOne;
messageFindOneStub.resolves(message);
const groupFindStub = groupRepository.stubs.find;
groupFindStub.resolves([group]);
const messageUpdateStub = messageRepository.stubs.updateById;
messageUpdateStub.resolves();
const groupUpdateStub = groupRepository.stubs.update;
groupUpdateStub.resolves();
const controllerResult = await controller
.markMail(VisibilityMarker.new, sampleIdArray)
.catch(error => error);
expect(controllerResult).instanceOf(Error);
});
});
}); | the_stack |
namespace game {
/**
* Ask the player for a number value.
* @param message The message to display on the text-entry screen
* @param answerLength The maximum number of digits the user can enter (1 - 10)
*/
//% group="Gameplay"
//% weight=10 help=game/ask-for-number
//% blockId=gameaskfornumber block="ask for number %message || and max length %answerLength"
//% message.shadow=text
//% message.defl=""
//% answerLength.defl="6"
//% answerLength.min=1
//% answerLength.max=10
//% group="Prompt"
export function askForNumber(message: any, answerLength = 6) {
answerLength = Math.max(0, Math.min(10, answerLength));
let p = new game.NumberPrompt();
const result = p.show(console.inspect(message), answerLength);
return result;
}
//% whenUsed=true
const font = image.font8;
//% whenUsed=true
const PADDING_HORIZONTAL = 40;
//% whenUsed=true
const PADDING_VERTICAL = 4;
//% whenUsed=true
const PROMPT_LINE_SPACING = 2;
//% whenUsed=true
const NUM_LETTERS = 12;
//% whenUsed=true
const NUMPAD_ROW_LENGTH = 3;
//% whenUsed=true
const NUM_ROWS = Math.ceil(NUM_LETTERS / NUMPAD_ROW_LENGTH);
//% whenUsed=true
const INPUT_ROWS = 1;
//% whenUsed=true
const CONTENT_WIDTH = screen.width - PADDING_HORIZONTAL * 2;
//% whenUsed=true
const CONTENT_HEIGHT = screen.height - PADDING_VERTICAL * 2;
//% whenUsed=true
const CONTENT_TOP = PADDING_VERTICAL;
// Dimensions of a "cell" that contains a letter
//% whenUsed=true
const CELL_HEIGHT = Math.floor(CONTENT_HEIGHT / (NUM_ROWS + 4));
//% whenUsed=true
const CELL_WIDTH = CELL_HEIGHT//Math.floor(CONTENT_WIDTH / NUMPAD_ROW_LENGTH);
//% whenUsed=true
const LETTER_OFFSET_X = Math.floor((CELL_WIDTH - font.charWidth) / 2);
//% whenUsed=true
const LETTER_OFFSET_Y = Math.floor((CELL_HEIGHT - font.charHeight) / 2);
//% whenUsed=true
const BLANK_PADDING = 1;
//% whenUsed=true
const ROW_LEFT = PADDING_HORIZONTAL + CELL_WIDTH / 2 + Math.floor((CONTENT_WIDTH - (CELL_WIDTH * NUMPAD_ROW_LENGTH)) / 2);
// Dimensions of the bottom bar
//% whenUsed=true
const BOTTOM_BAR_NUMPAD_MARGIN = 4;
//% whenUsed=true
const BOTTOM_BAR_HEIGHT = PADDING_VERTICAL + BOTTOM_BAR_NUMPAD_MARGIN + CELL_HEIGHT;
//% whenUsed=true
const BOTTOM_BAR_TOP = screen.height - BOTTOM_BAR_HEIGHT;
//% whenUsed=true
const BOTTOM_BAR_BUTTON_WIDTH = PADDING_HORIZONTAL * 2 + font.charWidth * 3;
//% whenUsed=true
const BOTTOM_BAR_TEXT_Y = (BOTTOM_BAR_HEIGHT - font.charHeight) / 2;
//% whenUsed=true
const BOTTOM_BAR_CONFIRM_X = (BOTTOM_BAR_BUTTON_WIDTH - font.charWidth * 2) / 2;
// Dimensions of the numpad area
//% whenUsed=true
const NUMPAD_HEIGHT = NUM_ROWS * CELL_HEIGHT;
//% whenUsed=true
const NUMPAD_TOP = screen.height - NUMPAD_HEIGHT - BOTTOM_BAR_HEIGHT;
//% whenUsed=true
const NUMPAD_INPUT_MARGIN = 4;
// Dimensions of area where text is input
//% whenUsed=true
const INPUT_HEIGHT = INPUT_ROWS * CELL_HEIGHT;
//% whenUsed=true
const INPUT_TOP = NUMPAD_TOP - INPUT_HEIGHT - NUMPAD_INPUT_MARGIN;
// Pixels kept blank on left and right sides of prompt
//% whenUsed=true
const PROMPT_MARGIN_HORIZ = 3;
// Dimensions of prompt message area
//% whenUsed=true
const PROMPT_HEIGHT = INPUT_TOP - CONTENT_TOP;
//% whenUsed=true
const PROMPT_WIDTH = screen.width - PROMPT_MARGIN_HORIZ * 2
//% whenUsed=true
const confirmText = "OK";
export class NumberPrompt {
theme: PromptTheme;
message: string;
answerLength: number;
result: string;
private cursor: Sprite;
private confirmButton: Sprite;
private numbers: Sprite[];
private inputs: Sprite[];
private confirmPressed: boolean;
private cursorRow: number;
private cursorColumn: number;
private hasDecimal: boolean;
private inputIndex: number;
private blink: boolean;
private frameCount: number;
constructor(theme?: PromptTheme) {
if (theme) {
this.theme = theme;
}
else {
this.theme = {
colorPrompt: 1,
colorInput: 3,
colorInputHighlighted: 5,
colorInputText: 1,
colorAlphabet: 1,
colorCursor: 7,
colorBackground: 15,
colorBottomBackground: 3,
colorBottomText: 1,
};
}
this.cursorRow = 0;
this.cursorColumn = 0;
this.hasDecimal = false;
this.inputIndex = 0;
}
show(message: string, answerLength: number) : number {
this.message = message;
this.answerLength = answerLength;
this.inputIndex = 0;
controller._setUserEventsEnabled(false);
game.pushScene()
this.draw();
this.registerHandlers();
this.confirmPressed = false;
pauseUntil(() => this.confirmPressed);
game.popScene();
controller._setUserEventsEnabled(true);
return parseFloat(this.result);
}
private draw() {
this.drawPromptText();
this.drawNumpad();
this.drawInputarea();
this.drawBottomBar();
}
private drawPromptText() {
const prompt = sprites.create(layoutText(this.message, PROMPT_WIDTH, PROMPT_HEIGHT, this.theme.colorPrompt), -1);
prompt.x = screen.width / 2
prompt.y = CONTENT_TOP + Math.floor((PROMPT_HEIGHT - prompt.height) / 2) + Math.floor(prompt.height / 2);
}
private drawInputarea() {
const answerLeft = (screen.width - this.answerLength * CELL_WIDTH) / 2
this.inputs = [];
for (let i = 0; i < this.answerLength; i++) {
const blank = image.create(CELL_WIDTH, CELL_HEIGHT);
this.drawInput(blank, "", this.theme.colorInput);
const s = sprites.create(blank, -1);
s.left = answerLeft + i * CELL_WIDTH;
s.y = INPUT_TOP;
this.inputs.push(s);
}
}
private drawNumpad() {
const cursorImage = image.create(CELL_WIDTH, CELL_HEIGHT);
cursorImage.fill(this.theme.colorCursor);
this.cursor = sprites.create(cursorImage, -1);
this.cursor.z = -1;
this.updateCursor();
this.numbers = [];
for (let j = 0; j < NUM_LETTERS; j++) {
const letter = image.create(CELL_WIDTH, CELL_HEIGHT);
const col2 = j % NUMPAD_ROW_LENGTH;
const row2 = Math.floor(j / NUMPAD_ROW_LENGTH);
const t = sprites.create(letter, -1);
t.x = ROW_LEFT + col2 * CELL_WIDTH;
t.y = NUMPAD_TOP + row2 * CELL_HEIGHT;
this.numbers.push(t);
}
this.updateKeyboard();
}
private drawBottomBar() {
const bg = image.create(screen.width, BOTTOM_BAR_HEIGHT);
bg.fill(this.theme.colorBottomBackground);
const bgSprite = sprites.create(bg, -1);
bgSprite.x = screen.width / 2;
bgSprite.y = BOTTOM_BAR_TOP + BOTTOM_BAR_HEIGHT / 2;
bgSprite.z = -1;
this.confirmButton = sprites.create(image.create(BOTTOM_BAR_BUTTON_WIDTH, BOTTOM_BAR_HEIGHT), -1);
this.confirmButton.right = screen.width;
this.confirmButton.y = BOTTOM_BAR_TOP + Math.ceil(BOTTOM_BAR_HEIGHT / 2);
this.updateButtons();
}
private updateButtons() {
if (this.cursorRow === 4) {
this.confirmButton.image.fill(this.theme.colorCursor);
}
else {
this.confirmButton.image.fill(this.theme.colorBottomBackground);
}
this.confirmButton.image.print(confirmText, BOTTOM_BAR_CONFIRM_X, BOTTOM_BAR_TEXT_Y);
}
private updateCursor() {
if (this.cursorRow === 4) {
this.cursor.image.fill(0);
this.updateButtons();
}
else {
this.cursor.x = ROW_LEFT + this.cursorColumn * CELL_WIDTH;
this.cursor.y = NUMPAD_TOP + this.cursorRow * CELL_HEIGHT;
}
}
private updateSelectedInput() {
if (this.inputIndex < this.answerLength) {
const u = this.inputs[this.inputIndex];
if (this.blink) {
this.drawInput(u.image, "", this.theme.colorInput);
}
else {
this.drawInput(u.image, "", this.theme.colorInputHighlighted)
}
}
}
private updateKeyboard() {
const len = this.numbers.length;
for (let k = 0; k < len; k++) {
const img = this.numbers[k].image;
img.fill(0);
img.print(getSymbolFromIndex(k), LETTER_OFFSET_X, LETTER_OFFSET_Y);
}
}
private drawInput(img: Image, char: string, color: number) {
img.fill(0);
img.fillRect(BLANK_PADDING, CELL_HEIGHT - 1, CELL_WIDTH - BLANK_PADDING * 2, 1, color)
if (char) {
img.print(char, LETTER_OFFSET_X, LETTER_OFFSET_Y, this.theme.colorInputText, font);
}
}
private registerHandlers() {
controller.up.onEvent(SYSTEM_KEY_DOWN, () => {
this.moveVertical(true);
})
controller.down.onEvent(SYSTEM_KEY_DOWN, () => {
this.moveVertical(false);
})
controller.right.onEvent(SYSTEM_KEY_DOWN, () => {
this.moveHorizontal(true);
});
controller.left.onEvent(SYSTEM_KEY_DOWN, () => {
this.moveHorizontal(false);
});
controller.A.onEvent(SYSTEM_KEY_DOWN, () => {
this.confirm();
});
controller.B.onEvent(SYSTEM_KEY_DOWN, () => {
this.delete();
});
this.frameCount = 0;
this.blink = true;
game.onUpdate(() => {
this.frameCount = (this.frameCount + 1) % 30;
if (this.frameCount === 0) {
this.blink = !this.blink;
this.updateSelectedInput();
}
})
}
private moveVertical(up: boolean) {
if (up) {
if (this.cursorRow === 4) {
this.cursor.image.fill(this.theme.colorCursor);
this.cursorRow = 3;
this.updateButtons();
}
else {
this.cursorRow = Math.max(0, this.cursorRow - 1);
}
}
else {
this.cursorRow = Math.min(4, this.cursorRow + 1);
}
this.updateCursor();
}
private moveHorizontal(right: boolean) {
if (right) {
this.cursorColumn = (this.cursorColumn + 1) % NUMPAD_ROW_LENGTH;
}
else {
this.cursorColumn = (this.cursorColumn + (NUMPAD_ROW_LENGTH - 1)) % NUMPAD_ROW_LENGTH;
}
this.updateCursor();
}
private confirm() {
if (this.cursorRow === 4) {
this.confirmPressed = true;
} else {
if (this.inputIndex >= this.answerLength) return;
const index = this.cursorColumn + this.cursorRow * NUMPAD_ROW_LENGTH
const letter = getSymbolFromIndex(index);
if (letter === ".") {
if(this.hasDecimal) {
return;
} else {
this.hasDecimal = true;
}
}
if (letter === "-" && (this.result && this.result.length > 0)) {
return;
}
if (!this.result) {
this.result = letter;
}
else {
this.result += letter;
}
const sprite = this.inputs[this.inputIndex];
this.changeInputIndex(1);
this.drawInput(sprite.image, letter, this.theme.colorInput);
}
}
private delete() {
if (this.inputIndex <= 0) return;
if (this.inputIndex < this.answerLength) {
this.drawInput(this.inputs[this.inputIndex].image, "", this.theme.colorInput);
}
if (this.result.charAt(this.result.length - 1) === ".") {
this.hasDecimal = false;
}
this.result = this.result.substr(0, this.result.length - 1);
this.changeInputIndex(-1);
}
private changeInputIndex(delta: number) {
this.inputIndex += delta;
this.frameCount = 0
this.blink = false;
this.updateSelectedInput();
}
}
function layoutText(message: string, width: number, height: number, color: number) {
const lineHeight = font.charHeight + PROMPT_LINE_SPACING;
const lineLength = Math.floor(width / font.charWidth);
const numLines = Math.floor(height / lineHeight);
let lines: string[] = [];
let word: string;
let line: string;
let pushWord = () => {
if (line) {
if (line.length + word.length + 1 > lineLength) {
lines.push(line);
line = word;
}
else {
line = line + " " + word;
}
}
else {
line = word;
}
word = null;
}
for (let l = 0; l < message.length; l++) {
const char = message.charAt(l);
if (char === " ") {
if (word) {
pushWord();
}
else {
word = " ";
}
}
else if (!word) {
word = char;
}
else {
word += char;
}
}
if (word) {
pushWord();
}
if (line) {
lines.push(line);
}
let maxLineWidth = 0;
for (let m = 0; m < lines.length; m++) {
maxLineWidth = Math.max(maxLineWidth, lines[m].length);
}
const actualWidth = maxLineWidth * font.charWidth;
const actualHeight = lines.length * lineHeight;
const res = image.create(actualWidth, actualHeight);
for (let n = 0; n < lines.length; n++) {
if ((n + 1) > numLines) break;
res.print(lines[n], 0, n * lineHeight, color, font);
}
return res;
}
function getSymbolFromIndex(index: number) {
if (index < 9) {
// Calculator Layout
return "" + (3 * Math.idiv(9 - index - 1, 3) + index % 3 + 1);
} else if (index == 9) {
return "-";
} else if (index == 10) {
return "0";
} else if (index == 11) {
return ".";
} else {
return "";
}
}
} | the_stack |
import Client from '@bugsnag/core/client'
import plugin from '../src/koa'
import { EventPayload } from '@bugsnag/core'
import Event from '@bugsnag/core/event'
const noop = () => {}
const id = <T>(a: T) => a
const logger = () => ({
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn()
})
describe('plugin: koa', () => {
it('exports two middleware functions', () => {
const c = new Client({ apiKey: 'api_key', plugins: [plugin] })
c._sessionDelegate = {
startSession: () => c,
pauseSession: () => {},
resumeSession: () => c
}
const middleware = c.getPlugin('koa')
if (!middleware) {
throw new Error('getPlugin("koa") failed')
}
expect(typeof middleware.requestHandler).toBe('function')
expect(middleware.requestHandler.length).toBe(2)
expect(typeof middleware.errorHandler).toBe('function')
expect(middleware.errorHandler.length).toBe(2)
})
describe('requestHandler', () => {
it('should start a session and attach a client to the context', async () => {
const client = new Client({ apiKey: 'api_key', plugins: [plugin] })
const startSession = jest.fn().mockReturnValue(client)
const pauseSession = jest.fn()
const resumeSession = jest.fn().mockReturnValue(client)
client._sessionDelegate = { startSession, pauseSession, resumeSession }
client._logger = logger()
const middleware = client.getPlugin('koa')
if (!middleware) {
throw new Error('getPlugin("koa") failed')
}
const context = {} as any
const next = jest.fn()
await middleware.requestHandler(context, next)
expect(client._logger.warn).not.toHaveBeenCalled()
expect(client._logger.error).not.toHaveBeenCalled()
expect(startSession).not.toHaveBeenCalled()
expect(pauseSession).not.toHaveBeenCalled()
expect(resumeSession).toHaveBeenCalledTimes(1)
expect(context.bugsnag).toBe(client)
expect(next).toHaveBeenCalledTimes(1)
})
it('should record metadata from the request', async () => {
const client = new Client({ apiKey: 'api_key', plugins: [plugin] })
client._sessionDelegate = { startSession: id, pauseSession: noop, resumeSession: id }
client._logger = logger()
client._setDelivery(() => ({
sendEvent (payload: EventPayload, cb: (err: Error|null, obj: unknown) => void) {
expect(payload.events).toHaveLength(1)
cb(null, payload.events[0])
},
sendSession: noop
}))
const middleware = client.getPlugin('koa')
if (!middleware) {
throw new Error('getPlugin("koa") failed')
}
const context = {
req: {
headers: { referer: '/abc' },
httpVersion: '1.0',
method: 'GET',
url: '/xyz',
connection: {
remoteAddress: '123.456.789.0',
remotePort: 9876,
bytesRead: 192837645,
bytesWritten: 918273465,
address: () => ({ port: 1234, family: 'IPv4', address: '127.0.0.1' })
}
},
res: {},
request: {
href: 'http://localhost:8080/xyz?a=1&b=2',
query: { a: 1, b: 2 },
body: 'the request body'
},
ip: '1.2.3.4'
} as any
const next = jest.fn()
await middleware.requestHandler(context, next)
expect(next).toHaveBeenCalledTimes(1)
const event: Event = await new Promise(resolve => {
client.notify(new Error('abc'), noop, (_, event) => resolve(event as Event))
})
expect(client._logger.warn).not.toHaveBeenCalled()
expect(client._logger.error).not.toHaveBeenCalled()
expect(event.request).toEqual({
body: 'the request body',
clientIp: '1.2.3.4',
headers: { referer: '/abc' },
httpMethod: 'GET',
httpVersion: '1.0',
url: 'http://localhost:8080/xyz?a=1&b=2',
referer: '/abc'
})
expect(event._metadata.request).toEqual({
clientIp: '1.2.3.4',
connection: {
remoteAddress: '123.456.789.0',
remotePort: 9876,
bytesRead: 192837645,
bytesWritten: 918273465,
localPort: 1234,
localAddress: '127.0.0.1',
IPVersion: 'IPv4'
},
headers: { referer: '/abc' },
httpMethod: 'GET',
httpVersion: '1.0',
path: '/xyz',
query: { a: 1, b: 2 },
url: 'http://localhost:8080/xyz?a=1&b=2',
referer: '/abc'
})
})
it('should not throw when no request data is available', async () => {
const client = new Client({ apiKey: 'api_key', plugins: [plugin] })
client._sessionDelegate = { startSession: id, pauseSession: noop, resumeSession: id }
client._logger = logger()
client._setDelivery(() => ({
sendEvent (payload: EventPayload, cb: (err: Error|null, obj: unknown) => void) {
expect(payload.events).toHaveLength(1)
cb(null, payload.events[0])
},
sendSession: noop
}))
const middleware = client.getPlugin('koa')
if (!middleware) {
throw new Error('getPlugin("koa") failed')
}
const context = {
req: { headers: {} },
res: {},
request: {}
} as any
const next = jest.fn()
await middleware.requestHandler(context, next)
expect(next).toHaveBeenCalledTimes(1)
const event: Event = await new Promise(resolve => {
client.notify(new Error('abc'), noop, (_, event) => resolve(event as Event))
})
expect(client._logger.warn).not.toHaveBeenCalled()
expect(client._logger.error).not.toHaveBeenCalled()
expect(event.request).toEqual({
body: undefined,
clientIp: undefined,
headers: {},
httpMethod: undefined,
httpVersion: undefined,
url: 'undefined',
referer: undefined
})
expect(event._metadata.request).toEqual({
clientIp: undefined,
connection: undefined,
headers: {},
httpMethod: undefined,
httpVersion: undefined,
path: undefined,
query: undefined,
url: 'undefined',
referer: undefined
})
})
it('should not track a session when "autoTrackSessions" is disabled', async () => {
const client = new Client({ apiKey: 'api_key', plugins: [plugin], autoTrackSessions: false })
const startSession = jest.fn().mockReturnValue(client)
const pauseSession = jest.fn()
const resumeSession = jest.fn().mockReturnValue(client)
client._sessionDelegate = { startSession, pauseSession, resumeSession }
client._logger = logger()
const middleware = client.getPlugin('koa')
if (!middleware) {
throw new Error('getPlugin("koa") failed')
}
const context = {} as any
const next = jest.fn()
await middleware.requestHandler(context, next)
expect(client._logger.warn).not.toHaveBeenCalled()
expect(client._logger.error).not.toHaveBeenCalled()
expect(startSession).not.toHaveBeenCalled()
expect(pauseSession).not.toHaveBeenCalled()
expect(resumeSession).not.toHaveBeenCalled()
expect(next).toHaveBeenCalledTimes(1)
// the Client should be cloned to ensure any manually started sessions
// do not leak between requests
expect(context.bugsnag).not.toBe(client)
expect(context.bugsnag).toBeInstanceOf(Client)
})
})
describe('errorHandler', () => {
it('should notify using "ctx.bugsnag" when it is defined', async () => {
const client = new Client({ apiKey: 'api_key', plugins: [plugin] })
client._notify = jest.fn()
const middleware = client.getPlugin('koa')
if (!middleware) {
throw new Error('getPlugin("koa") failed')
}
// create a separate client so we can tell which one was used by the errorHandler
const client2 = new Client({ apiKey: 'different_api_key' })
client2._logger = logger()
const events: Event[] = []
client2._setDelivery(() => ({
sendEvent (payload: EventPayload, cb: (err: Error|null, obj: unknown) => void) {
expect(payload.events).toHaveLength(1)
events.push(payload.events[0] as Event)
},
sendSession: noop
}))
const error = new Error('oh no!!')
const context = { req: { headers: {} }, request: {}, bugsnag: client2 } as any
middleware.errorHandler(error, context)
expect(client._notify).not.toHaveBeenCalled()
expect(client2._logger.warn).not.toHaveBeenCalled()
expect(client2._logger.error).not.toHaveBeenCalled()
expect(events).toHaveLength(1)
const event = events[0]
expect(event.originalError).toBe(error)
expect(event.errors).toHaveLength(1)
expect(event.errors[0].errorMessage).toBe('oh no!!')
// these values should come from the requestHandler's onError callback, so we
// expect them to be undefined in this test as we never call the requestHandler
expect(event.request).toEqual({})
expect(event._metadata.request).toBeUndefined()
})
it('should notify using the initial client when "ctx.bugsnag" is not defined', async () => {
const client = new Client({ apiKey: 'api_key', plugins: [plugin] })
client._logger = logger()
const events: Event[] = []
client._setDelivery(() => ({
sendEvent (payload: EventPayload, cb: (err: Error|null, obj: unknown) => void) {
expect(payload.events).toHaveLength(1)
events.push(payload.events[0] as Event)
},
sendSession: noop
}))
const middleware = client.getPlugin('koa')
if (!middleware) {
throw new Error('getPlugin("koa") failed')
}
// create a separate client so we can tell which one was used by the errorHandler
const client2 = new Client({ apiKey: 'different_api_key' })
client2._notify = jest.fn()
const error = new Error('oh no!!')
const context = { req: { headers: {} }, request: {} } as any // no bugsnag!
middleware.errorHandler(error, context)
expect(client2._notify).not.toHaveBeenCalled()
expect(client._logger.warn).toHaveBeenCalledTimes(1)
expect(client._logger.warn).toHaveBeenCalledWith(
'ctx.bugsnag is not defined. Make sure the @bugsnag/plugin-koa requestHandler middleware is added first.'
)
expect(client._logger.error).not.toHaveBeenCalled()
expect(events).toHaveLength(1)
const event = events[0]
expect(event.originalError).toBe(error)
expect(event.errors).toHaveLength(1)
expect(event.errors[0].errorMessage).toBe('oh no!!')
expect(event.request).toEqual({
body: undefined,
clientIp: undefined,
headers: {},
httpMethod: undefined,
httpVersion: undefined,
url: 'undefined',
referer: undefined
})
expect(event._metadata.request).toEqual({
clientIp: undefined,
connection: undefined,
headers: {},
httpMethod: undefined,
httpVersion: undefined,
path: undefined,
query: undefined,
url: 'undefined',
referer: undefined
})
})
it('should do nothing when "autoDetectErrors" is disabled', async () => {
const client = new Client({ apiKey: 'api_key', plugins: [plugin], autoDetectErrors: false })
client._notify = jest.fn()
const middleware = client.getPlugin('koa')
if (!middleware) {
throw new Error('getPlugin("koa") failed')
}
const client2 = new Client({ apiKey: 'different_api_key', autoDetectErrors: false })
client2._notify = jest.fn()
const error = new Error('oh no!!')
const context = { req: { headers: {} }, request: {}, bugsnag: client2 } as any
middleware.errorHandler(error, context)
expect(client._notify).not.toHaveBeenCalled()
expect(client2._notify).not.toHaveBeenCalled()
// ensure notify is not called when using the other client
delete context.bugsnag
middleware.errorHandler(error, context)
expect(client._notify).not.toHaveBeenCalled()
expect(client2._notify).not.toHaveBeenCalled()
})
it('should call the app error handler when there are no other listeners', async () => {
const client = new Client({ apiKey: 'api_key', plugins: [plugin] })
client._notify = jest.fn()
const middleware = client.getPlugin('koa')
if (!middleware) {
throw new Error('getPlugin("koa") failed')
}
const app = {
listenerCount: () => 1,
onerror: jest.fn()
}
const error = new Error('oh no!!')
const context = { req: { headers: {} }, request: {}, bugsnag: client, app } as any
middleware.errorHandler(error, context)
expect(client._notify).toHaveBeenCalled()
expect(app.onerror).toHaveBeenCalledWith(error)
})
it('should not call the app error handler when there are other listeners', async () => {
const client = new Client({ apiKey: 'api_key', plugins: [plugin] })
client._notify = jest.fn()
const middleware = client.getPlugin('koa')
if (!middleware) {
throw new Error('getPlugin("koa") failed')
}
const app = {
listenerCount: () => 2,
onerror: jest.fn()
}
const error = new Error('oh no!!')
const context = { req: { headers: {} }, request: {}, bugsnag: client, app } as any
middleware.errorHandler(error, context)
expect(client._notify).toHaveBeenCalled()
expect(app.onerror).not.toHaveBeenCalled()
})
})
}) | the_stack |
import * as React from 'react';
import { mount, unmount } from '@cypress/react';
import { CLASSES } from '../src/Types';
import { App, twoTabs, threeTabs, withBorders } from './App';
import { AppEx, layoutEx2, layoutEx1 } from './AppEx';
enum Location {
TOP, BOTTOM,LEFT,RIGHT,CENTER,
LEFTEDGE
}
/*
Key elements have data-layout-path attributes:
/ts0 - the first tabset in the root row
/ts1 - the second tabset in the root row
/ts1/tabstrip - the second tabsets tabstrip
/ts1/header - the second tabsets header
/c2/ts0 - the first tabset in the column at position 2 in the root row
/s0 - the first splitter in the root row (the one after the first tabset/column)
/ts1/t2 - the third tab (the tab content) in the second tabset in the root row
/ts1/tb2 - the third tab button (the tab button in the tabstrip) in the second tabset in the root row
/border/top/t1
/border/top/tb1
...
Note: use it.only(... to run a single test
*/
describe('Drag tests', () => {
context("two tabs", () => {
beforeEach(() => {
mount(<App json={twoTabs} />);
findAllTabSets().should("have.length", 2);
// find the first tab button in the first tabset
// the .as() function gives an alias (name) to this element that can be used later using the @ selector
findTabButton("/ts0", 0).as('from');
});
it('tab to tab center', () => {
findPath("/ts1/t0").as('to');
drag("@from", "@to", Location.CENTER); // drag to the center of the @to tabset
findAllTabSets().should("have.length", 1);
checkTab("/ts0", 0, false, "Two");
checkTab("/ts0", 1, true, "One");
})
it('tab to tab top', () => {
findPath("/ts1/t0").as('to');
drag("@from", "@to", Location.TOP);
findAllTabSets().should("have.length", 2);
checkTab("/c0/ts0", 0, true, "One");
checkTab("/c0/ts1", 0, true, "Two");
})
it('tab to tab bottom', () => {
findPath("/ts1/t0").as('to');
drag("@from", "@to", Location.BOTTOM);
findAllTabSets().should("have.length", 2);
checkTab("/c0/ts0", 0, true, "Two");
checkTab("/c0/ts1", 0, true, "One");
})
it('tab to tab left', () => {
findPath("/ts1/t0").as('to');
drag("@from", "@to", Location.LEFT);
findAllTabSets().should("have.length", 2);
checkTab("/ts0", 0, true, "One");
checkTab("/ts1", 0, true, "Two");
})
it('tab to tab right', () => {
findPath("/ts1/t0").as('to');
drag("@from", "@to", Location.RIGHT);
findAllTabSets().should("have.length", 2);
checkTab("/ts0", 0, true, "Two");
checkTab("/ts1", 0, true, "One");
})
it('tab to edge', () => {
dragToEdge("@from", 2);
checkTab("/c0/ts0", 0, true, "Two");
checkTab("/c0/ts1", 0, true, "One");
})
});
context("three tabs", () => {
beforeEach(() => {
mount(<App json={threeTabs} />);
findAllTabSets().should("have.length", 3);
findTabButton("/ts0", 0).as('from');
});
it('tab to tabset', () => {
findPath("/ts1/tabstrip").as('to');
drag("@from", "@to", Location.CENTER);
findAllTabSets().should("have.length", 2);
checkTab("/ts0", 0, false, "Two");
checkTab("/ts0", 1, true, "One");
checkTab("/ts1", 0, true, "Three");
})
it('tab to tab center', () => {
findPath("/ts1/t0").as('to');
drag("@from", "@to", Location.CENTER);
findAllTabSets().should("have.length", 2);
checkTab("/ts0", 0, false, "Two");
checkTab("/ts0", 1, true, "One");
checkTab("/ts1", 0, true, "Three");
})
it('tab to tab top', () => {
findPath("/ts1/t0").as('to');
drag("@from", "@to", Location.TOP);
findAllTabSets().should("have.length", 3);
checkTab("/c0/ts0", 0, true, "One");
checkTab("/c0/ts1", 0, true, "Two");
checkTab("/ts1", 0, true, "Three");
})
it('tab to tab bottom', () => {
findPath("/ts1/t0").as('to');
drag("@from", "@to", Location.BOTTOM);
findAllTabSets().should("have.length", 3);
checkTab("/c0/ts0", 0, true, "Two");
checkTab("/c0/ts1", 0, true, "One");
checkTab("/ts1", 0, true, "Three");
})
it('tab to tab left', () => {
findPath("/ts1/t0").as('to');
drag("@from", "@to", Location.LEFT);
findAllTabSets().should("have.length", 3);
checkTab("/ts0", 0, true, "One");
checkTab("/ts1", 0, true, "Two");
checkTab("/ts2", 0, true, "Three");
})
it('tab to tab right', () => {
findPath("/ts1/t0").as('to');
drag("@from", "@to", Location.RIGHT);
findAllTabSets().should("have.length", 3);
checkTab("/ts0", 0, true, "Two");
checkTab("/ts1", 0, true, "One");
checkTab("/ts2", 0, true, "Three");
})
it('tab to edge top', () => {
dragToEdge("@from", 0);
checkTab("/c0/ts0", 0, true, "One");
checkTab("/c0/r1/ts0", 0, true, "Two");
checkTab("/c0/r1/ts1", 0, true, "Three");
})
it('tab to edge left', () => {
dragToEdge("@from", 1);
checkTab("/ts0", 0, true, "One");
checkTab("/ts1", 0, true, "Two");
checkTab("/ts2", 0, true, "Three");
})
it('tab to edge bottom', () => {
dragToEdge("@from", 2);
checkTab("/c0/r0/ts0", 0, true, "Two");
checkTab("/c0/r0/ts1", 0, true, "Three");
checkTab("/c0/ts1", 0, true, "One");
})
it('tab to edge right', () => {
dragToEdge("@from", 3);
checkTab("/ts0", 0, true, "Two");
checkTab("/ts1", 0, true, "Three");
checkTab("/ts2", 0, true, "One");
})
it('row to column', () => {
findPath("/ts2/t0").as('to');
drag("@from", "@to", Location.BOTTOM);
findTabButton("/ts0", 0).as('from');
findPath("/c1/ts0/t0").as('to');
drag("@from", "@to", Location.BOTTOM);
findAllTabSets().should("have.length", 3);
checkTab("/c0/ts0", 0, true, "Three");
checkTab("/c0/ts1", 0, true, "Two");
checkTab("/c0/ts2", 0, true, "One");
})
it('row to single tabset', () => {
findPath("/ts2/t0").as('to');
drag("@from", "@to", Location.CENTER);
findTabButton("/ts0", 0).as('from');
findPath("/ts1/t1").as('to');
drag("@from", "@to", Location.CENTER);
findAllTabSets().should("have.length", 1);
checkTab("/ts0", 0, false, "Three");
checkTab("/ts0", 1, false, "One");
checkTab("/ts0", 2, true, "Two");
})
it('move tab in tabstrip', () => {
findPath("/ts2/t0").as('to');
drag("@from", "@to", Location.CENTER);
findTabButton("/ts0", 0).as('from');
findPath("/ts1/t1").as('to');
drag("@from", "@to", Location.CENTER);
checkTab("/ts0", 0, false, "Three");
checkTab("/ts0", 1, false, "One");
checkTab("/ts0", 2, true, "Two");
// now all in single tabstrip
findTabButton("/ts0", 2).as('from');
findTabButton("/ts0", 0).as('to');
drag("@from", "@to", Location.LEFT);
checkTab("/ts0", 0, true, "Two");
checkTab("/ts0", 1, false, "Three");
checkTab("/ts0", 2, false, "One");
})
it('move tabstrip', () => {
findPath("/ts2/tabstrip").as('from');
findPath("/ts0/t0").as('to');
drag("@from", "@to", Location.CENTER);
checkTab("/ts0", 0, true, "One");
checkTab("/ts0", 1, false, "Three");
checkTab("/ts1", 0, true, "Two");
findPath("/ts0/tabstrip").as('from');
findPath("/ts1/tabstrip").as('to');
drag("@from", "@to", Location.CENTER);
checkTab("/ts0", 0, true, "Two");
checkTab("/ts0", 1, false, "One");
checkTab("/ts0", 2, false, "Three");
})
it('move using header', () => {
findPath("/ts1/header").as('from');
findPath("/ts0/t0").as('to');
drag("@from", "@to", Location.TOP);
checkTab("/c0/ts0", 0, true, "Two");
checkTab("/c0/ts1", 0, true, "One");
checkTab("/ts1", 0, true, "Three");
})
})
context("borders", () => {
beforeEach(() => {
mount(<App json={withBorders} />);
findAllTabSets().should("have.length", 3);
});
const borderToTabTest = (border, tabtext, index) => {
findTabButton(border, 0).as('from');
findPath("/ts0/t0").as('to');
drag("@from", "@to", Location.CENTER);
findAllTabSets().should("have.length", 3);
checkTab("/ts0", 0, false, "One");
checkTab("/ts0", index, true, tabtext);
};
it('border top to tab', () => {
borderToTabTest("/border/top", "top1", 1);
})
it('border bottom to tab', () => {
borderToTabTest("/border/bottom", "bottom1", 1);
})
it('border left to tab', () => {
borderToTabTest("/border/left", "left1", 1);
})
it('border right to tab', () => {
borderToTabTest("/border/right", "right1", 1);
})
const tabToBorderTest = (border, tabtext, index) => {
findTabButton("/ts0", 0).as('from');
findTabButton(border, 0).as('to');
drag("@from", "@to", Location.CENTER);
findAllTabSets().should("have.length", 2);
checkBorderTab(border, 0, false, tabtext);
checkBorderTab(border, index, false, "One");
};
it('tab to border top', () => {
tabToBorderTest("/border/top", "top1", 1);
})
it('tab to border bottom', () => {
tabToBorderTest("/border/bottom", "bottom1", 1);
})
it('tab to border left', () => {
tabToBorderTest("/border/left", "left1", 1);
})
it('tab to border right', () => {
tabToBorderTest("/border/right", "right1", 1);
})
const openTabTest = (border, tabtext, index) => {
findTabButton(border, 0).as('to').click();
findTabButton("/ts0", 0).as('from');
findPath(border).as('to');
drag("@from", "@to", Location.CENTER);
findAllTabSets().should("have.length", 2);
checkBorderTab(border, 0, false, tabtext);
checkBorderTab(border, index, true, "One");
};
it('tab to open border top', () => {
openTabTest("/border/top", "top1", 1);
})
it('tab to open border bottom', () => {
openTabTest("/border/bottom", "bottom1", 2);
})
it('tab to open border left', () => {
openTabTest("/border/left", "left1", 1);
})
it('tab to open border right', () => {
openTabTest("/border/right", "right1", 1);
})
const openTabCenterTest = (border, tabtext, index) => {
findTabButton(border, 0).click();
findTabButton("/ts0", 0).as('from');
findPath(border + "/t0").as('to');
drag("@from", "@to", Location.CENTER);
findAllTabSets().should("have.length", 2);
checkBorderTab(border, 0, false, tabtext);
checkBorderTab(border, index, true, "One");
};
it('tab to open border top center', () => {
openTabCenterTest("/border/top", "top1", 1);
})
it('tab to open border bottom center', () => {
openTabCenterTest("/border/bottom", "bottom1", 2);
})
it('tab to open border left center', () => {
openTabCenterTest("/border/left", "left1", 1);
})
it('tab to open border right center', () => {
openTabCenterTest("/border/right", "right1", 1);
})
const inBorderTabMoveTest = (border, tabtext, index) => {
findTabButton("/ts0", 0).as('from');
findPath(border).as('to');
drag("@from", "@to", Location.CENTER);
findAllTabSets().should("have.length", 2);
checkBorderTab(border, 0, false, tabtext);
checkBorderTab(border, index, false, "One");
findTabButton(border, 0).as('from');
findTabButton(border, index).as('to');
drag("@from", "@to", Location.RIGHT);
checkBorderTab(border, index, false, tabtext);
};
it('move tab in border top', () => {
inBorderTabMoveTest("/border/top", "top1", 1);
})
it('move tab in border bottom', () => {
inBorderTabMoveTest("/border/bottom", "bottom1", 2);
})
it('move tab in border left', () => {
inBorderTabMoveTest("/border/left", "left1", 1);
})
it('move tab in border right', () => {
inBorderTabMoveTest("/border/right", "right1", 1);
})
})
context("Splitters", () => {
beforeEach(() => {
mount(<App json={twoTabs} />);
});
it('vsplitter', () => {
findPath("/s0").as('from');
dragsplitter("@from", false, 100); // right 100px
findPath("/ts1").then(e1 => {
const w1 = e1.width();
findPath("/ts0").then(e2 => {
const w2 = e2.width();
assert.isTrue(w2 - w1 > 99);
});
});
})
it('vsplitter to edge', () => {
findPath("/s0").as('from');
dragsplitter("@from", false, 1000); // to right edge
dragsplitter("@from", false, -100); // 100px back
findPath("/ts1").then(e1 => {
const w1 = e1.width();
assert.isTrue(Math.abs(w1 - 100) < 2);
});
})
it('vsplitter to edge left', () => {
findPath("/s0").as('from');
dragsplitter("@from", false, -1000); // to left edge
dragsplitter("@from", false, 100); // 100px back
findPath("/ts0").then(e1 => {
const w1 = e1.width();
assert.isTrue(Math.abs(w1 - 100) < 2);
});
})
context("horizontal", () => {
beforeEach(() => {
findTabButton("/ts0", 0).as('from');
findPath("/ts1/t0").as('to');
drag("@from", "@to", Location.BOTTOM);
findAllTabSets().should("have.length", 2);
checkTab("/c0/ts0", 0, true, "Two");
checkTab("/c0/ts1", 0, true, "One");
});
it('hsplitter', () => {
findPath("/c0/s0").as('from');
dragsplitter("@from", true, 100); // down 100px
findPath("/c0/ts1").then(e1 => {
const h1 = e1.height();
findPath("/c0/ts0").then(e2 => {
const h2 = e2.height();
assert.isTrue(h2 - h1 > 99);
});
});
})
it('hsplitter to edge', () => {
findPath("/c0/s0").as('from');
dragsplitter("@from", true, 1000); // to bottom edge
dragsplitter("@from", true, -100); // 100px back
findPath("/c0/ts1").then(e1 => {
const h1 = e1.height();
assert.isTrue(Math.abs(h1 - 100) < 2);
});
})
it('hsplitter to edge top', () => {
findPath("/c0/s0").as('from');
dragsplitter("@from", true, -1000); // to top edge
dragsplitter("@from", true, 100); // 100px back
findPath("/c0/ts0").then(e1 => {
const h1 = e1.height();
assert.isTrue(Math.abs(h1 - 100) < 2);
});
})
})
})
})
context("Overflow menu", () => {
beforeEach(() => {
mount(<App json={withBorders} />);
findPath("/ts0/tabstrip").click();
cy.get('[data-id=add-active').click();
cy.get('[data-id=add-active').click();
});
it('show menu', () => {
findPath("/ts0/button/overflow").should("not.exist");
findPath("/s0").as('from');
dragsplitter("@from", false, -1000); // to left edge
dragsplitter("@from", false, 150); // 100px back
checkTab("/ts0", 2, true, "Text1").should("be.visible");
checkTab("/ts0", 0, false, "One").should("not.be.visible");
findPath("/ts0/button/overflow")
.should("exist")
.click();
findPath("/popup-menu")
.should("exist");
findPath("/popup-menu/tb0")
.click();
checkTab("/ts0", 2, false, "Text1").should("not.be.visible");
checkTab("/ts0", 0, true, "One").should("be.visible");
// now expand the tabset so oveflow menu dissapears
dragsplitter("@from", false, 300);
findPath("/ts0/button/overflow").should("not.exist");
})
})
context("Add methods", () => {
beforeEach(() => {
mount(<App json={withBorders} />);
findAllTabSets().should("have.length", 3);
});
it('drag to tabset', () => {
cy.get('[data-id=add-drag').as('from');
findPath("/ts1/tabstrip").as('to'); // drag to the second tabset
drag("@from", "@to", Location.CENTER);
findAllTabSets().should("have.length", 3);
checkTab("/ts1", 0, false, "Two");
checkTab("/ts1", 1, true, "Text0");
})
it('drag to border', () => {
cy.get('[data-id=add-drag').as('from');
findPath("/border/right").as('to');
drag("@from", "@to", Location.CENTER);
findAllTabSets().should("have.length", 3);
checkBorderTab("/border/right", 0, false, "right1");
checkBorderTab("/border/right", 1, false, "Text0");
})
it('drag indirect to tabset', () => {
cy.get('[data-id=add-indirect').click();
findPath("/drag-rectangle").as('from');
findPath("/ts1/tabstrip").as('to'); // drag to the second tabset
drag("@from", "@to", Location.CENTER);
findAllTabSets().should("have.length", 3);
checkTab("/ts1", 0, false, "Two");
checkTab("/ts1", 1, true, "Text0");
})
it('drag indirect to border', () => {
cy.get('[data-id=add-indirect').click();
findPath("/drag-rectangle").as('from');
findPath("/border/right").as('to');
drag("@from", "@to", Location.CENTER);
findAllTabSets().should("have.length", 3);
checkBorderTab("/border/right", 0, false, "right1");
checkBorderTab("/border/right", 1, false, "Text0");
})
it('add to tabset with id #1', () => {
cy.get('[data-id=add-byId').click();
findAllTabSets().should("have.length", 3);
checkTab("/ts1", 0, false, "Two");
checkTab("/ts1", 1, true, "Text0");
})
it('add to active tabset', () => {
findPath("/ts1/tabstrip").click();
cy.get('[data-id=add-active').click();
findAllTabSets().should("have.length", 3);
checkTab("/ts1", 0, false, "Two");
checkTab("/ts1", 1, true, "Text0");
})
})
context("Delete methods", () => {
beforeEach(() => {
mount(<App json={withBorders} />);
findAllTabSets().should("have.length", 3);
});
it('delete tab', () => {
findPath("/ts1/tb0/button/close").click();
findAllTabSets().should("have.length", 2);
checkTab("/ts0", 0, true, "One");
checkTab("/ts1", 0, true, "Three");
})
it('delete all tabs', () => {
findPath("/ts1/tb0/button/close").click();
findPath("/ts1/tb0/button/close").click();
findPath("/ts0/tb0/button/close").click();
findAllTabSets().should("have.length", 1);
findPath("/ts1/tb0").should("not.exist");
})
it('delete tab in border', () => {
checkBorderTab("/border/bottom", 0, false, "bottom1");
findPath("/border/bottom/tb0/button/close").click({ force: true });
checkBorderTab("/border/bottom", 0, false, "bottom2");
})
})
context("Maximize methods", () => {
beforeEach(() => {
mount(<App json={withBorders} />);
findAllTabSets().should("have.length", 3);
});
it('maximize tabset using max button', () => {
findPath("/ts1/button/max").click();
findPath("/ts0").should("not.be.visible");
findPath("/ts1").should("be.visible");
findPath("/ts2").should("not.be.visible");
findPath("/ts1/button/max").click();
findPath("/ts0").should("be.visible");
findPath("/ts1").should("be.visible");
findPath("/ts2").should("be.visible");
})
it('maximize tabset using double click', () => {
findPath("/ts1/tabstrip").dblclick();
findPath("/ts0").should("not.be.visible");
findPath("/ts1").should("be.visible");
findPath("/ts2").should("not.be.visible");
findPath("/ts1/button/max").click();
findPath("/ts0").should("be.visible");
findPath("/ts1").should("be.visible");
findPath("/ts2").should("be.visible");
})
})
context("Others", () => {
beforeEach(() => {
});
it('rename tab', () => {
mount(<App json={withBorders} />);
findPath("/ts1/tb0").dblclick();
findPath("/ts1/tb0/textbox")
.should("exist")
.should("contain.value", "Two")
.type("Renamed{enter}");
checkTab("/ts1", 0, true, "Renamed");
})
it('rename tab cancelled with esc', () => {
mount(<App json={withBorders} />);
findPath("/ts1/tb0").dblclick();
findPath("/ts1/tb0/textbox").should("exist").type("Renamed{esc}");
checkTab("/ts1", 0, true, "Two");
})
it('click on tab contents causes tabset activate', () => {
mount(<App json={withBorders} />);
findPath("/ts1/t0").click();
findPath("/ts0/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts1/tabstrip").should("have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts2/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts0/t0").click();
findPath("/ts0/tabstrip").should("have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts1/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts2/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts2/t0").click();
findPath("/ts0/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts1/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts2/tabstrip").should("have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
})
it('click on tab button causes tabset activate', () => {
mount(<App json={withBorders} />);
findPath("/ts1/tb0").click();
findPath("/ts0/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts1/tabstrip").should("have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts2/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts0/tb0").click();
findPath("/ts0/tabstrip").should("have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts1/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts2/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts2/tb0").click();
findPath("/ts0/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts1/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts2/tabstrip").should("have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
})
it('click on tabstrip causes tabset activate', () => {
mount(<App json={withBorders} />);
findPath("/ts1/tabstrip").click();
findPath("/ts0/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts1/tabstrip").should("have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts2/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts0/tabstrip").click();
findPath("/ts0/tabstrip").should("have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts1/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts2/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts2/tabstrip").click();
findPath("/ts0/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts1/tabstrip").should("not.have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
findPath("/ts2/tabstrip").should("have.class", CLASSES.FLEXLAYOUT__TABSET_SELECTED);
})
it('tab can have icon', () => {
mount(<App json={threeTabs} />);
findPath("/ts1/tb0")
.find("." + CLASSES.FLEXLAYOUT__TAB_BUTTON_LEADING)
.find("img")
.should("have.attr", "src", "/test/images/settings.svg");
})
})
context("Extended App", () => {
beforeEach(() => {
mount(<AppEx json={layoutEx1} />);
});
it('title factory', () => {
findPath("/ts0/tb0").should("contain.text", "[titleFactory]");
})
it('icon factory', () => {
findPath("/ts2/tb0").should("contain.text", "[iconFactory]").should("contain.text", "Three");
})
it('onRenderTab', () => {
findPath("/ts1/tb0")
.find("." + CLASSES.FLEXLAYOUT__TAB_BUTTON_LEADING)
.find("img")
.should("have.attr", "src", "/test/images/settings.svg");
findPath("/ts1/tb0")
.find("img").eq(1)
.should("have.attr", "src", "/test/images/folder.svg");
})
it('onRenderTab in border', () => {
findPath("/border/top/tb0")
.find("." + CLASSES.FLEXLAYOUT__BORDER_BUTTON_LEADING)
.find("img")
.should("have.attr", "src", "/test/images/settings.svg");
findPath("/ts1/tb0")
.find("img").eq(1)
.should("have.attr", "src", "/test/images/folder.svg");
})
it('onRenderTabSet', () => {
findPath("/ts1/tabstrip")
.find("." + CLASSES.FLEXLAYOUT__TAB_TOOLBAR)
.find("img").eq(0)
.should("have.attr", "src", "/test/images/folder.svg");
findPath("/ts1/tabstrip")
.find("." + CLASSES.FLEXLAYOUT__TAB_TOOLBAR)
.find("img").eq(1)
.should("have.attr", "src", "/test/images/settings.svg");
})
it('onRenderTabSet sticky buttons', () => {
findPath("/ts2/tabstrip")
.find("." + CLASSES.FLEXLAYOUT__TAB_TOOLBAR_STICKY_BUTTONS_CONTAINER)
.find("img").eq(0)
.should("have.attr", "src", "/test/images/add.svg");
})
it('onRenderTabSet for header', () => {
findPath("/ts1/header")
.find("." + CLASSES.FLEXLAYOUT__TAB_TOOLBAR)
.find("img").eq(0)
.should("have.attr", "src", "/test/images/settings.svg");
findPath("/ts1/header")
.find("." + CLASSES.FLEXLAYOUT__TAB_TOOLBAR)
.find("img").eq(1)
.should("have.attr", "src", "/test/images/folder.svg");
})
it('onRenderTabSet for border', () => {
findPath("/border/top")
.find("." + CLASSES.FLEXLAYOUT__BORDER_TOOLBAR)
.find("img").eq(0)
.should("have.attr", "src", "/test/images/folder.svg");
findPath("/border/top")
.find("." + CLASSES.FLEXLAYOUT__BORDER_TOOLBAR)
.find("img").eq(1)
.should("have.attr", "src", "/test/images/settings.svg");
})
})
context("Extended layout2", () => {
beforeEach(() => {
mount(<AppEx json={layoutEx2} />);
});
it('check tabset min size', () => {
findPath("/s0").as('from');
dragsplitter("@from", false, -1000);
findPath("/ts0").then(e1 => {
const w1 = e1.width();
assert.isTrue(Math.abs(w1 - 100) < 2);
});
findPath("/s1").as('from');
dragsplitter("@from", false, 1000);
findPath("/c2/ts0").then(e1 => {
const w1 = e1.width();
assert.isTrue(Math.abs(w1 - 100) < 2);
});
findPath("/c2/s0").as('from');
dragsplitter("@from", true, -1000);
findPath("/c2/ts0").then(e1 => {
const w1 = e1.height();
assert.isTrue(Math.abs(w1 - 100) < 2);
});
findPath("/c2/s0").as('from');
dragsplitter("@from", true, 1000);
findPath("/c2/ts1").then(e1 => {
const w1 = e1.height();
assert.isTrue(Math.abs(w1 - 100) < 2);
});
})
it('check border top min size', () => {
findPath("/border/top/tb0").click();
findPath("/border/top/s").as('from');
dragsplitter("@from", true, -1000);
findPath("/border/top/t0").then(e1 => {
const w1 = e1.height();
assert.isTrue(Math.abs(w1 - 100) < 2);
});
});
it('check border bottom min size', () => {
findPath("/border/bottom/tb0").click();
findPath("/border/bottom/s").as('from');
dragsplitter("@from", true, 1000);
findPath("/border/bottom/t0").then(e1 => {
const w1 = e1.height();
assert.isTrue(Math.abs(w1 - 100) < 2);
});
});
it('check border left min size', () => {
findPath("/border/left/tb0").click();
findPath("/border/left/s").as('from');
dragsplitter("@from", false, -1000);
findPath("/border/left/t0").then(e1 => {
const w1 = e1.width();
assert.isTrue(Math.abs(w1 - 100) < 2);
});
});
it('check border right min size', () => {
findPath("/border/right/tb0").click();
findPath("/border/right/s").as('from');
dragsplitter("@from", false, 1000);
findPath("/border/right/t0").then(e1 => {
const w1 = e1.width();
assert.isTrue(Math.abs(w1 - 100) < 2);
});
});
it('tabset close', () => {
findPath("/ts0").should("exist");
findPath("/ts1").should("exist");
findPath("/ts2").should("not.exist");
findPath("/c2/ts0/button/close").click();
findPath("/c2/ts0").should("not.exist");
findPath("/ts0").should("exist");
findPath("/ts1").should("exist");
findPath("/ts2").should("exist");
});
it('borders autohide top', () => {
findPath("/border/top/tb0/button/close").click({ force: true });
findPath("/border/top").should("not.exist");
findTabButton("/ts0", 0).as('from');
findTabButton("/ts0", 0).as('to');
drag("@from", "@to", Location.TOP);
findPath("/border/top").should("exist");
});
it('borders autohide left', () => {
findPath("/border/left/tb0/button/close").click({ force: true });
findPath("/border/left").should("not.exist");
findTabButton("/ts0", 0).as('from');
findTabButton("/ts0", 0).as('to');
drag("@from", "@to", Location.LEFTEDGE);
findPath("/border/left").should("exist");
});
})
// ---------------------------- helpers ------------------------
function drag(from: string, to: string, loc: Location) {
cy.get(from)
.trigger('mousedown', { which: 1 }).then(e => {
const fr = e[0].getBoundingClientRect();
const cf = getLocation(fr, Location.CENTER)
cy.get(to).then(e => {
const tr = e[0].getBoundingClientRect();
const ct = getLocation(tr, loc);
cy.document()
.trigger('mousemove', { clientX: cf.x + 10, clientY: cf.y + 10 })
.trigger('mousemove', { clientX: (cf.x + ct.x) / 2, clientY: (cf.y + ct.y) / 2 })
.trigger('mousemove', { clientX: ct.x, clientY: ct.y })
.trigger('mouseup', { clientX: ct.x, clientY: ct.y });
});
});
}
function dragToEdge(from: string, edgeIndex: number) {
cy.get(from)
.trigger('mousedown', { which: 1 }).then(e => {
const fr = e[0].getBoundingClientRect();
const cf = { x: fr.x + fr.width / 2, y: fr.y + fr.height / 2 };
cy.document() // need to start move for edges to show
.trigger('mousemove', { clientX: cf.x + 10, clientY: cf.y + 10 });
cy.get('.flexlayout__edge_rect').eq(edgeIndex).then(e => {
const tr = e[0].getBoundingClientRect();
const ct = { x: tr.x + tr.width / 2, y: tr.y + tr.height / 2 };
cy.document()
.trigger('mousemove', { clientX: (cf.x + ct.x) / 2, clientY: (cf.y + ct.y) / 2 })
.trigger('mousemove', { clientX: ct.x, clientY: ct.y })
.trigger('mouseup', { clientX: ct.x, clientY: ct.y });
});
});
}
function dragsplitter(from: string, upDown: boolean, distance: number) {
cy.get(from)
.trigger('mousedown', { which: 1 })
.then(e => {
const fr = e[0].getBoundingClientRect();
const cf = { x: fr.x + fr.width / 2, y: fr.y + fr.height / 2 };
const ct = { x: cf.x + (upDown ? 0 : distance), y: cf.y + (upDown ? distance : 0) };
cy.document()
.trigger('mousemove', { clientX: cf.x + 10, clientY: cf.y + 10 })
.trigger('mousemove', { clientX: (cf.x + ct.x) / 2, clientY: (cf.y + ct.y) / 2 })
.trigger('mousemove', { clientX: ct.x, clientY: ct.y })
.trigger('mouseup', { clientX: ct.x, clientY: ct.y });
});
}
beforeEach(() => {
unmount();
});
const findAllTabSets = () => {
return cy.get('.flexlayout__tabset');
}
const findPath = (path: string) => {
return cy.get('[data-layout-path="' + path + '"]');
}
const findTabButton = (path: string, index: number) => {
return findPath(path + "/tb" + index);
}
const checkTab = (path: string, index: number, selected: boolean, text: string) => {
findTabButton(path, index)
.should("exist")
.should("have.class", selected ? "flexlayout__tab_button--selected" : "flexlayout__tab_button--unselected")
.find(".flexlayout__tab_button_content")
.should("contain.text", text);
return findPath(path + "/t" + index)
.should("exist")
.should("contain.text", text);
}
const checkBorderTab = (path: string, index: number, selected: boolean, text: string) => {
findTabButton(path, index)
.should("exist")
.should("have.class", selected ? "flexlayout__border_button--selected" : "flexlayout__border_button--unselected")
.find(".flexlayout__border_button_content")
.should("contain.text", text);
if (selected) {
findPath(path + "/t" + index)
.should("exist")
.should("contain.text", text);
}
}
const getLocation = (r: { x: number, y: number, width: number, height: number }, location: Location) => {
switch (location) {
case Location.CENTER:
return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
case Location.TOP:
return { x: r.x + r.width / 2, y: r.y + r.height / 8 };
case Location.BOTTOM:
return { x: r.x + r.width / 2, y: r.y + (r.height / 8) * 7 };
case Location.LEFT:
return { x: r.x + r.width / 8, y: r.y + r.height / 2 };
case Location.LEFTEDGE:
return { x: r.x , y: r.y + r.height / 2 };
case Location.RIGHT:
return { x: r.x + (r.width / 8) * 7, y: r.y + r.height / 2 };
}
} | the_stack |
import * as coreClient from "@azure/core-client";
export type NodeBaseUnion =
| NodeBase
| SourceNodeBaseUnion
| ProcessorNodeBaseUnion
| SinkNodeBaseUnion;
export type AuthenticationBaseUnion = AuthenticationBase | JwtAuthentication;
export type EndpointBaseUnion = EndpointBase | UnsecuredEndpoint | TlsEndpoint;
export type CredentialsBaseUnion =
| CredentialsBase
| UsernamePasswordCredentials;
export type TunnelBaseUnion = TunnelBase | SecureIotDeviceRemoteTunnel;
export type CertificateSourceUnion = CertificateSource | PemCertificateList;
export type TimeSequenceBaseUnion =
| TimeSequenceBase
| VideoSequenceAbsoluteTimeMarkers;
export type EncoderPresetBaseUnion =
| EncoderPresetBase
| EncoderSystemPreset
| EncoderCustomPreset;
export type AudioEncoderBaseUnion = AudioEncoderBase | AudioEncoderAac;
export type VideoEncoderBaseUnion = VideoEncoderBase | VideoEncoderH264;
export type TokenKeyUnion = TokenKey | RsaTokenKey | EccTokenKey;
export type SourceNodeBaseUnion = SourceNodeBase | RtspSource | VideoSource;
export type ProcessorNodeBaseUnion = ProcessorNodeBase | EncoderProcessor;
export type SinkNodeBaseUnion = SinkNodeBase | VideoSink;
/** A collection of EdgeModuleEntity items. */
export interface EdgeModuleEntityCollection {
/** A collection of EdgeModuleEntity items. */
value?: EdgeModuleEntity[];
/** A link to the next page of the collection (when the collection contains too many results to return in one response). */
nextLink?: string;
}
/** Common fields that are returned in the response for all Azure Resource Manager resources */
export interface Resource {
/**
* Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The name of the resource
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* Azure Resource Manager metadata containing createdBy and modifiedBy information.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly systemData?: SystemData;
}
/** Metadata pertaining to creation and last modification of the resource. */
export interface SystemData {
/** The identity that created the resource. */
createdBy?: string;
/** The type of identity that created the resource. */
createdByType?: CreatedByType;
/** The timestamp of resource creation (UTC). */
createdAt?: Date;
/** The identity that last modified the resource. */
lastModifiedBy?: string;
/** The type of identity that last modified the resource. */
lastModifiedByType?: CreatedByType;
/** The timestamp of resource last modification (UTC) */
lastModifiedAt?: Date;
}
/** Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). */
export interface ErrorResponse {
/** The error object. */
error?: ErrorDetail;
}
/** The error detail. */
export interface ErrorDetail {
/**
* The error code.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly code?: string;
/**
* The error message.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly message?: string;
/**
* The error target.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly target?: string;
/**
* The error details.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly details?: ErrorDetail[];
/**
* The error additional info.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly additionalInfo?: ErrorAdditionalInfo[];
}
/** The resource management error additional info. */
export interface ErrorAdditionalInfo {
/**
* The additional info type.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The additional info.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly info?: Record<string, unknown>;
}
/** The input parameters to generate registration token for the Azure Video Analyzer IoT edge module. */
export interface ListProvisioningTokenInput {
/** The desired expiration date of the registration token. The Azure Video Analyzer IoT edge module must be initialized and connected to the Internet prior to the token expiration date. */
expirationDate: Date;
}
/** Provisioning token properties. A provisioning token allows for a single instance of Azure Video analyzer IoT edge module to be initialized and authorized to the cloud account. The provisioning token itself is short lived and it is only used for the initial handshake between IoT edge module and the cloud. After the initial handshake, the IoT edge module will agree on a set of authentication keys which will be auto-rotated as long as the module is able to periodically connect to the cloud. A new provisioning token can be generated for the same IoT edge module in case the module state lost or reset. */
export interface EdgeModuleProvisioningToken {
/**
* The expiration date of the registration token. The Azure Video Analyzer IoT edge module must be initialized and connected to the Internet prior to the token expiration date.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly expirationDate?: Date;
/**
* The token blob to be provided to the Azure Video Analyzer IoT edge module through the Azure IoT Edge module twin properties.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly token?: string;
}
/** A collection of PipelineTopology items. */
export interface PipelineTopologyCollection {
/** A collection of PipelineTopology items. */
value?: PipelineTopology[];
/** A link to the next page of the collection (when the collection contains too many results to return in one response). */
nextLink?: string;
}
/** Single topology parameter declaration. Declared parameters can and must be referenced throughout the topology and can optionally have default values to be used when they are not defined in the pipelines. */
export interface ParameterDeclaration {
/** Name of the parameter. */
name: string;
/** Type of the parameter. */
type: ParameterType;
/** Description of the parameter. */
description?: string;
/** The default value for the parameter to be used if the pipeline does not specify a value. */
default?: string;
}
/** Base class for nodes. */
export interface NodeBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
type:
| "#Microsoft.VideoAnalyzer.SourceNodeBase"
| "#Microsoft.VideoAnalyzer.ProcessorNodeBase"
| "#Microsoft.VideoAnalyzer.SinkNodeBase"
| "#Microsoft.VideoAnalyzer.RtspSource"
| "#Microsoft.VideoAnalyzer.VideoSource"
| "#Microsoft.VideoAnalyzer.EncoderProcessor"
| "#Microsoft.VideoAnalyzer.VideoSink";
/** Node name. Must be unique within the topology. */
name: string;
}
/** Describes an input signal to be used on a pipeline node. */
export interface NodeInput {
/** The name of the upstream node in the pipeline which output is used as input of the current node. */
nodeName: string;
}
/** The SKU details. */
export interface Sku {
/** The SKU name. */
name: SkuName;
/**
* The SKU tier.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly tier?: SkuTier;
}
/** A collection of LivePipeline items. */
export interface LivePipelineCollection {
/** A collection of LivePipeline items. */
value?: LivePipeline[];
/** A link to the next page of the collection (when the collection contains too many results to return in one response). */
nextLink?: string;
}
/** Defines the parameter value of an specific pipeline topology parameter. See pipeline topology parameters for more information. */
export interface ParameterDefinition {
/** Name of the parameter declared in the pipeline topology. */
name: string;
/** Parameter value to be applied on this specific pipeline. */
value?: string;
}
/** A collection of PipelineJob items. */
export interface PipelineJobCollection {
/** A collection of PipelineJob items. */
value?: PipelineJob[];
/** A link to the next page of the collection (when the collection contains too many results to return in one response). */
nextLink?: string;
}
/** Details about the error for a failed pipeline job. */
export interface PipelineJobError {
/** The error code. */
code?: string;
/** The error message. */
message?: string;
}
/** Used for tracking the status of an operation on the live pipeline. */
export interface LivePipelineOperationStatus {
/**
* The name of the live pipeline operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The status of the live pipeline operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly status?: string;
/**
* The error details for the live pipeline operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly error?: ErrorDetail;
}
/** Used for tracking the status of an operation on the pipeline job. */
export interface PipelineJobOperationStatus {
/**
* The name of the pipeline job operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The status of the pipeline job operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly status?: string;
/**
* The error details for the pipeline job operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly error?: ErrorDetail;
}
/** A collection of Operation items. */
export interface OperationCollection {
/** A collection of Operation items. */
value?: Operation[];
}
/** An operation. */
export interface Operation {
/** The operation name. */
name: string;
/** The operation display name. */
display?: OperationDisplay;
/** Origin of the operation. */
origin?: string;
/** Operation properties format. */
properties?: Properties;
/** Whether the operation applies to data-plane. */
isDataAction?: boolean;
/** Indicates the action type. */
actionType?: ActionType;
}
/** Operation details. */
export interface OperationDisplay {
/** The service provider. */
provider?: string;
/** Resource on which the operation is performed. */
resource?: string;
/** The operation type. */
operation?: string;
/** The operation description. */
description?: string;
}
/** Metric properties. */
export interface Properties {
/**
* The service specifications.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly serviceSpecification?: ServiceSpecification;
}
/** The service metric specifications. */
export interface ServiceSpecification {
/**
* List of log specifications.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly logSpecifications?: LogSpecification[];
/**
* List of metric specifications.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly metricSpecifications?: MetricSpecification[];
}
/** A diagnostic log emitted by service. */
export interface LogSpecification {
/**
* The diagnostic log category name.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The diagnostic log category display name.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly displayName?: string;
/**
* The time range for requests in each blob.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly blobDuration?: string;
}
/** A metric emitted by service. */
export interface MetricSpecification {
/**
* The metric name.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The metric display name.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly displayName?: string;
/**
* The metric display description.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly displayDescription?: string;
/**
* The metric unit
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly unit?: MetricUnit;
/**
* The metric aggregation type
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly aggregationType?: MetricAggregationType;
/**
* The metric lock aggregation type
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly lockAggregationType?: MetricAggregationType;
/** Supported aggregation types. */
supportedAggregationTypes?: string[];
/**
* The metric dimensions.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly dimensions?: MetricDimension[];
/**
* Indicates whether regional MDM account is enabled.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly enableRegionalMdmAccount?: boolean;
/**
* The source MDM account.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly sourceMdmAccount?: string;
/**
* The source MDM namespace.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly sourceMdmNamespace?: string;
/**
* The supported time grain types.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly supportedTimeGrainTypes?: string[];
}
/** A metric dimension. */
export interface MetricDimension {
/**
* The metric dimension name.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The display name for the dimension.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly displayName?: string;
/**
* Whether to export metric to shoebox.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly toBeExportedForShoebox?: boolean;
}
/** A collection of VideoAnalyzer items. */
export interface VideoAnalyzerCollection {
/** A collection of VideoAnalyzer items. */
value?: VideoAnalyzer[];
}
/** The details about the associated storage account. */
export interface StorageAccount {
/** The ID of the storage account resource. Video Analyzer relies on tables, queues, and blobs. The primary storage account must be a Standard Storage account (either Microsoft.ClassicStorage or Microsoft.Storage). */
id: string;
/** A managed identity that Video Analyzer will use to access the storage account. */
identity?: ResourceIdentity;
/**
* The current status of the storage account mapping.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly status?: string;
}
/** The user assigned managed identity to use when accessing a resource. */
export interface ResourceIdentity {
/** The user assigned managed identity's resource identifier to use when accessing a resource. */
userAssignedIdentity: string;
}
/** The endpoint details. */
export interface Endpoint {
/** The URL of the endpoint. */
endpointUrl?: string;
/** The type of the endpoint. */
type: VideoAnalyzerEndpointType;
}
/** Defines how the Video Analyzer account is (optionally) encrypted. */
export interface AccountEncryption {
/** The type of key used to encrypt the Account Key. */
type: AccountEncryptionKeyType;
/** The properties of the key used to encrypt the account. */
keyVaultProperties?: KeyVaultProperties;
/** The Key Vault identity. */
identity?: ResourceIdentity;
/**
* The current status of the Key Vault mapping.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly status?: string;
}
/** The details for accessing the encryption keys in Key Vault. */
export interface KeyVaultProperties {
/** The URL of the Key Vault key used to encrypt the account. The key may either be versioned (for example https://vault/keys/mykey/version1) or reference a key without a version (for example https://vault/keys/mykey). */
keyIdentifier: string;
/**
* The current key used to encrypt Video Analyzer account, including the key version.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly currentKeyIdentifier?: string;
}
/** The IoT Hub details. */
export interface IotHub {
/** The IoT Hub resource identifier. */
id: string;
/** The IoT Hub identity. */
identity: ResourceIdentity;
/**
* The current status of the Iot Hub mapping.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly status?: string;
}
/** Network access control for video analyzer account. */
export interface NetworkAccessControl {
/** Public network access for integration group. */
integration?: GroupLevelAccessControl;
/** Public network access for ingestion group. */
ingestion?: GroupLevelAccessControl;
/** Public network access for consumption group. */
consumption?: GroupLevelAccessControl;
}
/** Group level network access control. */
export interface GroupLevelAccessControl {
/** Whether or not public network access is allowed for specified resources under the Video Analyzer account. */
publicNetworkAccess?: PublicNetworkAccess;
}
/** The Private Endpoint resource. */
export interface PrivateEndpoint {
/**
* The ARM identifier for Private Endpoint
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
}
/** A collection of information about the state of the connection between service consumer and provider. */
export interface PrivateLinkServiceConnectionState {
/** Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. */
status?: PrivateEndpointServiceConnectionStatus;
/** The reason for approval/rejection of the connection. */
description?: string;
/** A message indicating if changes on the service provider require any updates on the consumer. */
actionsRequired?: string;
}
/** The managed identity for the Video Analyzer resource. */
export interface VideoAnalyzerIdentity {
/** The identity type. */
type: string;
/** The User Assigned Managed Identities. */
userAssignedIdentities?: {
[propertyName: string]: UserAssignedManagedIdentity;
};
}
/** The details of the user assigned managed identity used by the Video Analyzer resource. */
export interface UserAssignedManagedIdentity {
/**
* The client ID.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly clientId?: string;
/**
* The principal ID.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly principalId?: string;
}
/** The update operation for a Video Analyzer account. */
export interface VideoAnalyzerUpdate {
/** Resource tags. */
tags?: { [propertyName: string]: string };
/** The identities associated to the Video Analyzer resource. */
identity?: VideoAnalyzerIdentity;
/** The storage accounts for this resource. */
storageAccounts?: StorageAccount[];
/**
* The endpoints associated with this resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly endpoints?: Endpoint[];
/** The account encryption properties. */
encryption?: AccountEncryption;
/** The IoT Hubs for this resource. */
iotHubs?: IotHub[];
/** Whether or not public network access is allowed for resources under the Video Analyzer account. */
publicNetworkAccess?: PublicNetworkAccess;
/** Network access control for Video Analyzer. */
networkAccessControl?: NetworkAccessControl;
/**
* Provisioning state of the Video Analyzer account.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: ProvisioningState;
/**
* Private Endpoint Connections created under Video Analyzer account.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly privateEndpointConnections?: PrivateEndpointConnection[];
}
/** A list of private link resources */
export interface PrivateLinkResourceListResult {
/** Array of private link resources */
value?: PrivateLinkResource[];
}
/** List of private endpoint connection associated with the specified storage account */
export interface PrivateEndpointConnectionListResult {
/** Array of private endpoint connections */
value?: PrivateEndpointConnection[];
}
/** Status of private endpoint connection operation. */
export interface VideoAnalyzerPrivateEndpointConnectionOperationStatus {
/** Operation identifier. */
name: string;
/** Operation resource ID. */
id?: string;
/** Operation start time. */
startTime?: string;
/** Operation end time. */
endTime?: string;
/** Operation status. */
status?: string;
/** The error detail. */
error?: ErrorDetail;
}
/** Status of video analyzer operation. */
export interface VideoAnalyzerOperationStatus {
/** Operation identifier. */
name: string;
/** Operation resource ID. */
id?: string;
/** Operation start time. */
startTime?: string;
/** Operation end time. */
endTime?: string;
/** Operation status. */
status?: string;
/** The error detail. */
error?: ErrorDetail;
}
/** The check availability request body. */
export interface CheckNameAvailabilityRequest {
/** The name of the resource for which availability needs to be checked. */
name?: string;
/** The resource type. */
type?: string;
}
/** The check availability result. */
export interface CheckNameAvailabilityResponse {
/** Indicates if the resource name is available. */
nameAvailable?: boolean;
/** The reason why the given name is not available. */
reason?: CheckNameAvailabilityReason;
/** Detailed reason why the given name is available. */
message?: string;
}
/** A collection of VideoEntity items. */
export interface VideoEntityCollection {
/** A collection of VideoEntity items. */
value?: VideoEntity[];
/** A link to the next page of the collection (when the collection contains too many results to return in one response). */
nextLink?: string;
}
/** Video flags contain information about the available video actions and its dynamic properties based on the current video state. */
export interface VideoFlags {
/** Value indicating whether or not the video can be streamed. Only "archive" type videos can be streamed. */
canStream: boolean;
/** Value indicating whether or not there has ever been data recorded or uploaded into the video. Newly created videos have this value set to false. */
hasData: boolean;
/** Value indicating whether or not the video is currently being referenced be an active pipeline. The fact that is being referenced, doesn't necessarily indicate that data is being received. For example, video recording may be gated on events or camera may not be accessible at the time. */
isInUse: boolean;
}
/** Set of URLs to the video content. */
export interface VideoContentUrls {
/** Video file download URL. This URL can be used in conjunction with the video content authorization token to download the video MP4 file. The resulting MP4 file can be played on any standard media player. It is available when the video type is 'file' and video file is available for consumption. */
downloadUrl?: string;
/**
* Video archive streaming base URL. The archived content can be automatically played by the Azure Video Analyzer player widget. Alternatively, this URL can be used in conjunction with the video content authorization token on any compatible DASH or HLS players by appending the following to the base URL:
*
* - HLSv4: /manifest(format=m3u8-aapl).m3u8
* - HLS CMAF: /manifest(format=m3u8-cmaf)
* - DASH CMAF: /manifest(format=mpd-time-cmaf)
*
* Moreover, an ongoing video recording can be played in "live mode" with latencies which are approximately double of the chosen video segment length. It is available when the video type is 'archive' and video archiving is enabled.
*/
archiveBaseUrl?: string;
/** Video low-latency streaming URL. The live content can be automatically played by the Azure Video Analyzer player widget. Alternatively, this URL can be used in conjunction with the video content authorization token to expose a WebSocket tunneled RTSP stream. It is available when the video type is 'archive' and a live, low-latency feed is available from the source. */
rtspTunnelUrl?: string;
/** Video preview image URLs. These URLs can be used in conjunction with the video content authorization token to download the most recent still image from the video archive in different resolutions. They are available when the video type is 'archive' and preview images are enabled. */
previewImageUrls?: VideoPreviewImageUrls;
}
/** Video preview image URLs. These URLs can be used in conjunction with the video content authorization token to download the most recent still image from the video archive in different resolutions. They are available when the video type is 'archive' and preview images are enabled. */
export interface VideoPreviewImageUrls {
/** Low resolution preview image URL. */
small?: string;
/** Medium resolution preview image URL. */
medium?: string;
/** High resolution preview image URL. */
large?: string;
}
/** Contains information about the video and audio content. */
export interface VideoMediaInfo {
/** Video segment length indicates the length of individual video files (segments) which are persisted to storage. Smaller segments provide lower archive playback latency but generate larger volume of storage transactions. Larger segments reduce the amount of storage transactions while increasing the archive playback latency. Value must be specified in ISO8601 duration format (i.e. "PT30S" equals 30 seconds) and can vary between 30 seconds to 5 minutes, in 30 seconds increments. */
segmentLength?: string;
}
/** Video archival properties. */
export interface VideoArchival {
/** Video retention period indicates the maximum age of the video archive segments which are intended to be kept in storage. It must be provided in the ISO8601 duration format in the granularity of days, up to a maximum of 10 years. For example, if this is set to P30D (30 days), content older than 30 days will be periodically deleted. This value can be updated at any time and the new desired retention period will be effective within 24 hours. */
retentionPeriod?: string;
}
/** "Video content token grants access to the video content URLs." */
export interface VideoContentToken {
/**
* The content token expiration date in ISO8601 format (eg. 2021-01-01T00:00:00Z).
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly expirationDate?: Date;
/**
* The content token value to be added to the video content URL as the value for the "token" query string parameter. The token is specific to a single video.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly token?: string;
}
/** A collection of AccessPolicyEntity items. */
export interface AccessPolicyEntityCollection {
/** A collection of AccessPolicyEntity items. */
value?: AccessPolicyEntity[];
/** A link to the next page of the collection (when the collection contains too many results to return in one response). */
nextLink?: string;
}
/** Base class for access policies authentication methods. */
export interface AuthenticationBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.JwtAuthentication";
}
/** Base class for endpoints. */
export interface EndpointBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
type:
| "#Microsoft.VideoAnalyzer.UnsecuredEndpoint"
| "#Microsoft.VideoAnalyzer.TlsEndpoint";
/** Credentials to be presented to the endpoint. */
credentials: CredentialsBaseUnion;
/** The endpoint URL for Video Analyzer to connect to. */
url: string;
/** Describes the tunnel through which Video Analyzer can connect to the endpoint URL. This is an optional property, typically used when the endpoint is behind a firewall. */
tunnel?: TunnelBaseUnion;
}
/** Base class for credential objects. */
export interface CredentialsBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.UsernamePasswordCredentials";
}
/** Base class for tunnel objects. */
export interface TunnelBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.SecureIotDeviceRemoteTunnel";
}
/** Base class for certificate sources. */
export interface CertificateSource {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.PemCertificateList";
}
/** Options for controlling the validation of TLS endpoints. */
export interface TlsValidationOptions {
/** When set to 'true' causes the certificate subject name validation to be skipped. Default is 'false'. */
ignoreHostname?: string;
/** When set to 'true' causes the certificate chain trust validation to be skipped. Default is 'false'. */
ignoreSignature?: string;
}
/** A sequence of datetime ranges as a string. */
export interface TimeSequenceBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.VideoSequenceAbsoluteTimeMarkers";
}
/** Base type for all encoder presets, which define the recipe or instructions on how the input content should be processed. */
export interface EncoderPresetBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
type:
| "#Microsoft.VideoAnalyzer.EncoderSystemPreset"
| "#Microsoft.VideoAnalyzer.EncoderCustomPreset";
}
/** Base type for all audio encoder presets, which define the recipe or instructions on how audio should be processed. */
export interface AudioEncoderBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.AudioEncoderAac";
/** Bitrate, in kilobits per second or Kbps, at which audio should be encoded (2-channel stereo audio at a sampling rate of 48 kHz). Allowed values are 96, 112, 128, 160, 192, 224, and 256. If omitted, the bitrate of the input audio is used. */
bitrateKbps?: string;
}
/** Base type for all video encoding presets, which define the recipe or instructions on how the input video should be processed. */
export interface VideoEncoderBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.VideoEncoderH264";
/** The maximum bitrate, in kilobits per second or Kbps, at which video should be encoded. If omitted, encoder sets it automatically to try and match the quality of the input video. */
bitrateKbps?: string;
/** The frame rate (in frames per second) of the encoded video. The value must be greater than zero, and less than or equal to 300. If omitted, the encoder uses the average frame rate of the input video. */
frameRate?: string;
/** Describes the resolution of the encoded video. If omitted, the encoder uses the resolution of the input video. */
scale?: VideoScale;
}
/** The video scaling information. */
export interface VideoScale {
/** The desired output video height. */
height?: string;
/** The desired output video width. */
width?: string;
/** Describes the video scaling mode to be applied. Default mode is 'Pad'. If the mode is 'Pad' or 'Stretch' then both width and height must be specified. Else if the mode is 'PreserveAspectRatio' then only one of width or height need be provided. */
mode?: VideoScaleMode;
}
/** Optional properties to be used in case a new video resource needs to be created on the service. These will not take effect if the video already exists. */
export interface VideoCreationProperties {
/** Optional title provided by the user. Value can be up to 256 characters long. */
title?: string;
/** Optional description provided by the user. Value can be up to 2048 characters long. */
description?: string;
/** Segment length indicates the length of individual content files (segments) which are persisted to storage. Smaller segments provide lower archive playback latency but generate larger volume of storage transactions. Larger segments reduce the amount of storage transactions while increasing the archive playback latency. Value must be specified in ISO8601 duration format (i.e. "PT30S" equals 30 seconds) and can vary between 30 seconds to 5 minutes, in 30 seconds increments. Changing this value after the initial call to create the video resource can lead to errors when uploading content to the archive. Default value is 30 seconds. This property is only allowed for topologies where "kind" is set to "live". */
segmentLength?: string;
/** Video retention period indicates how long the video is kept in storage. Value must be specified in ISO8601 duration format (i.e. "P1D" equals 1 day) and can vary between 1 day to 10 years, in 1 day increments. When absent (null), all video content is retained indefinitely. This property is only allowed for topologies where "kind" is set to "live". */
retentionPeriod?: string;
}
/** Optional flags used to change how video is published. These are only allowed for topologies where "kind" is set to "live". */
export interface VideoPublishingOptions {
/** When set to 'true' content will not be archived or recorded. This is used, for example, when the topology is used only for low latency video streaming. Default is 'false'. If set to 'true', then "disableRtspPublishing" must be set to 'false'. */
disableArchive?: string;
/** When set to 'true' the RTSP playback URL will not be published, disabling low latency streaming. This is used, for example, when the topology is used only for archiving content. Default is 'false'. If set to 'true', then "disableArchive" must be set to 'false'. */
disableRtspPublishing?: string;
}
/** Properties for expected token claims. */
export interface TokenClaim {
/** Name of the claim which must be present on the token. */
name: string;
/** Expected value of the claim to be present on the token. */
value: string;
}
/** Key properties for JWT token validation. */
export interface TokenKey {
/** Polymorphic discriminator, which specifies the different types this object can be */
type:
| "#Microsoft.VideoAnalyzer.RsaTokenKey"
| "#Microsoft.VideoAnalyzer.EccTokenKey";
/** JWT token key id. Validation keys are looked up based on the key id present on the JWT token header. */
kid: string;
}
/** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */
export type ProxyResource = Resource & {};
/** The Private Endpoint Connection resource. */
export type PrivateEndpointConnection = Resource & {
/** The resource of private end point. */
privateEndpoint?: PrivateEndpoint;
/** A collection of information about the state of the connection between service consumer and provider. */
privateLinkServiceConnectionState?: PrivateLinkServiceConnectionState;
/**
* The provisioning state of the private endpoint connection resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: PrivateEndpointConnectionProvisioningState;
};
/** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */
export type TrackedResource = Resource & {
/** Resource tags. */
tags?: { [propertyName: string]: string };
/** The geo-location where the resource lives */
location: string;
};
/** A private link resource */
export type PrivateLinkResource = Resource & {
/**
* The private link resource group id.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly groupId?: string;
/**
* The private link resource required member names.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly requiredMembers?: string[];
/** The private link resource Private link DNS zone name. */
requiredZoneNames?: string[];
};
/** Base class for topology source nodes. */
export type SourceNodeBase = NodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type:
| "#Microsoft.VideoAnalyzer.SourceNodeBase"
| "#Microsoft.VideoAnalyzer.RtspSource"
| "#Microsoft.VideoAnalyzer.VideoSource";
};
/** Base class for topology processor nodes. */
export type ProcessorNodeBase = NodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type:
| "#Microsoft.VideoAnalyzer.ProcessorNodeBase"
| "#Microsoft.VideoAnalyzer.EncoderProcessor";
/** An array of upstream node references within the topology to be used as inputs for this node. */
inputs: NodeInput[];
};
/** Base class for topology sink nodes. */
export type SinkNodeBase = NodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type:
| "#Microsoft.VideoAnalyzer.SinkNodeBase"
| "#Microsoft.VideoAnalyzer.VideoSink";
/** An array of upstream node references within the topology to be used as inputs for this node. */
inputs: NodeInput[];
};
/** Properties for access validation based on JSON Web Tokens (JWT). */
export type JwtAuthentication = AuthenticationBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.JwtAuthentication";
/** List of expected token issuers. Token issuer is valid if it matches at least one of the given values. */
issuers?: string[];
/** List of expected token audiences. Token audience is valid if it matches at least one of the given values. */
audiences?: string[];
/** List of additional token claims to be validated. Token must contains all claims and respective values for it to be valid. */
claims?: TokenClaim[];
/** List of keys which can be used to validate access tokens. Having multiple keys allow for seamless key rotation of the token signing key. Token signature must match exactly one key. */
keys?: TokenKeyUnion[];
};
/** Unsecured endpoint describes an endpoint that the pipeline can connect to over clear transport (no encryption in transit). */
export type UnsecuredEndpoint = EndpointBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.UnsecuredEndpoint";
};
/** TLS endpoint describes an endpoint that the pipeline can connect to over TLS transport (data is encrypted in transit). */
export type TlsEndpoint = EndpointBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.TlsEndpoint";
/** List of trusted certificate authorities when authenticating a TLS connection. A null list designates that Azure Video Analyzer's list of trusted authorities should be used. */
trustedCertificates?: CertificateSourceUnion;
/** Validation options to use when authenticating a TLS connection. By default, strict validation is used. */
validationOptions?: TlsValidationOptions;
};
/** Username and password credentials. */
export type UsernamePasswordCredentials = CredentialsBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.UsernamePasswordCredentials";
/** Username to be presented as part of the credentials. */
username: string;
/** Password to be presented as part of the credentials. It is recommended that this value is parameterized as a secret string in order to prevent this value to be returned as part of the resource on API requests. */
password: string;
};
/** A remote tunnel securely established using IoT Hub device information. */
export type SecureIotDeviceRemoteTunnel = TunnelBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.SecureIotDeviceRemoteTunnel";
/** Name of the IoT Hub. */
iotHubName: string;
/** The IoT device id to use when establishing the remote tunnel. This string is case-sensitive. */
deviceId: string;
};
/** A list of PEM formatted certificates. */
export type PemCertificateList = CertificateSource & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.PemCertificateList";
/** PEM formatted public certificates. One certificate per entry. */
certificates: string[];
};
/** A sequence of absolute datetime ranges as a string. The datetime values should follow IS08601, and the sum of the ranges should add up to 24 hours or less. Currently, there can be only one range specified in the sequence. */
export type VideoSequenceAbsoluteTimeMarkers = TimeSequenceBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.VideoSequenceAbsoluteTimeMarkers";
/** The sequence of datetime ranges. Example: '[["2021-10-05T03:30:00Z", "2021-10-05T03:40:00Z"]]'. */
ranges: string;
};
/** Describes a built-in preset for encoding the input content using the encoder processor. */
export type EncoderSystemPreset = EncoderPresetBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.EncoderSystemPreset";
/** Name of the built-in encoding preset. */
name: EncoderSystemPresetType;
};
/** Describes a custom preset for encoding the input content using the encoder processor. */
export type EncoderCustomPreset = EncoderPresetBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.EncoderCustomPreset";
/** Describes a custom preset for encoding audio. */
audioEncoder?: AudioEncoderBaseUnion;
/** Describes a custom preset for encoding video. */
videoEncoder?: VideoEncoderBaseUnion;
};
/** A custom preset for encoding audio with the AAC codec. */
export type AudioEncoderAac = AudioEncoderBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.AudioEncoderAac";
};
/** A custom preset for encoding video with the H.264 (AVC) codec. */
export type VideoEncoderH264 = VideoEncoderBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.VideoEncoderH264";
};
/** Required validation properties for tokens generated with RSA algorithm. */
export type RsaTokenKey = TokenKey & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.RsaTokenKey";
/** RSA algorithm to be used: RS256, RS384 or RS512. */
alg: AccessPolicyRsaAlgo;
/** RSA public key modulus. */
n: string;
/** RSA public key exponent. */
e: string;
};
/** Required validation properties for tokens generated with Elliptical Curve algorithm. */
export type EccTokenKey = TokenKey & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.EccTokenKey";
/** Elliptical curve algorithm to be used: ES256, ES384 or ES512. */
alg: AccessPolicyEccAlgo;
/** X coordinate. */
x: string;
/** Y coordinate. */
y: string;
};
/** The representation of an edge module. */
export type EdgeModuleEntity = ProxyResource & {
/**
* Internal ID generated for the instance of the Video Analyzer edge module.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly edgeModuleId?: string;
};
/**
* Pipeline topology describes the processing steps to be applied when processing content for a particular outcome. The topology should be defined according to the scenario to be achieved and can be reused across many pipeline instances which share the same processing characteristics. For instance, a pipeline topology which captures content from a RTSP camera and archives the content can be reused across many different cameras, as long as the same processing is to be applied across all the cameras. Individual instance properties can be defined through the use of user-defined parameters, which allow for a topology to be parameterized. This allows individual pipelines refer to different values, such as individual cameras' RTSP endpoints and credentials. Overall a topology is composed of the following:
*
* - Parameters: list of user defined parameters that can be references across the topology nodes.
* - Sources: list of one or more data sources nodes such as an RTSP source which allows for content to be ingested from cameras.
* - Processors: list of nodes which perform data analysis or transformations.
* - Sinks: list of one or more data sinks which allow for data to be stored or exported to other destinations.
*/
export type PipelineTopology = ProxyResource & {
/** Topology kind. */
kind: Kind;
/** Describes the properties of a SKU. */
sku: Sku;
/** An optional description of the pipeline topology. It is recommended that the expected use of the topology to be described here. */
description?: string;
/** List of the topology parameter declarations. Parameters declared here can be referenced throughout the topology nodes through the use of "${PARAMETER_NAME}" string pattern. Parameters can have optional default values and can later be defined in individual instances of the pipeline. */
parameters?: ParameterDeclaration[];
/** List of the topology source nodes. Source nodes enable external data to be ingested by the pipeline. */
sources?: SourceNodeBaseUnion[];
/** List of the topology processor nodes. Processor nodes enable pipeline data to be analyzed, processed or transformed. */
processors?: ProcessorNodeBaseUnion[];
/** List of the topology sink nodes. Sink nodes allow pipeline data to be stored or exported. */
sinks?: SinkNodeBaseUnion[];
};
/**
* Pipeline topology describes the processing steps to be applied when processing content for a particular outcome. The topology should be defined according to the scenario to be achieved and can be reused across many pipeline instances which share the same processing characteristics. For instance, a pipeline topology which captures content from a RTSP camera and archives the content can be reused across many different cameras, as long as the same processing is to be applied across all the cameras. Individual instance properties can be defined through the use of user-defined parameters, which allow for a topology to be parameterized. This allows individual pipelines refer to different values, such as individual cameras' RTSP endpoints and credentials. Overall a topology is composed of the following:
*
* - Parameters: list of user defined parameters that can be references across the topology nodes.
* - Sources: list of one or more data sources nodes such as an RTSP source which allows for content to be ingested from cameras.
* - Processors: list of nodes which perform data analysis or transformations.
* - Sinks: list of one or more data sinks which allow for data to be stored or exported to other destinations.
*/
export type PipelineTopologyUpdate = ProxyResource & {
/** Topology kind. */
kind?: Kind;
/** Describes the properties of a SKU. */
sku?: Sku;
/** An optional description of the pipeline topology. It is recommended that the expected use of the topology to be described here. */
description?: string;
/** List of the topology parameter declarations. Parameters declared here can be referenced throughout the topology nodes through the use of "${PARAMETER_NAME}" string pattern. Parameters can have optional default values and can later be defined in individual instances of the pipeline. */
parameters?: ParameterDeclaration[];
/** List of the topology source nodes. Source nodes enable external data to be ingested by the pipeline. */
sources?: SourceNodeBaseUnion[];
/** List of the topology processor nodes. Processor nodes enable pipeline data to be analyzed, processed or transformed. */
processors?: ProcessorNodeBaseUnion[];
/** List of the topology sink nodes. Sink nodes allow pipeline data to be stored or exported. */
sinks?: SinkNodeBaseUnion[];
};
/** Live pipeline represents a unique instance of a live topology, used for real-time ingestion, archiving and publishing of content for a unique RTSP camera. */
export type LivePipeline = ProxyResource & {
/** The reference to an existing pipeline topology defined for real-time content processing. When activated, this live pipeline will process content according to the pipeline topology definition. */
topologyName?: string;
/** An optional description for the pipeline. */
description?: string;
/** Maximum bitrate capacity in Kbps reserved for the live pipeline. The allowed range is from 500 to 3000 Kbps in increments of 100 Kbps. If the RTSP camera exceeds this capacity, then the service will disconnect temporarily from the camera. It will retry to re-establish connection (with exponential backoff), checking to see if the camera bitrate is now below the reserved capacity. Doing so will ensure that one 'noisy neighbor' does not affect other live pipelines in your account. */
bitrateKbps?: number;
/**
* Current state of the pipeline (read-only).
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly state?: LivePipelineState;
/** List of the instance level parameter values for the user-defined topology parameters. A pipeline can only define or override parameters values for parameters which have been declared in the referenced topology. Topology parameters without a default value must be defined. Topology parameters with a default value can be optionally be overridden. */
parameters?: ParameterDefinition[];
};
/** Live pipeline represents a unique instance of a live topology, used for real-time ingestion, archiving and publishing of content for a unique RTSP camera. */
export type LivePipelineUpdate = ProxyResource & {
/** The reference to an existing pipeline topology defined for real-time content processing. When activated, this live pipeline will process content according to the pipeline topology definition. */
topologyName?: string;
/** An optional description for the pipeline. */
description?: string;
/** Maximum bitrate capacity in Kbps reserved for the live pipeline. The allowed range is from 500 to 3000 Kbps in increments of 100 Kbps. If the RTSP camera exceeds this capacity, then the service will disconnect temporarily from the camera. It will retry to re-establish connection (with exponential backoff), checking to see if the camera bitrate is now below the reserved capacity. Doing so will ensure that one 'noisy neighbor' does not affect other live pipelines in your account. */
bitrateKbps?: number;
/**
* Current state of the pipeline (read-only).
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly state?: LivePipelineState;
/** List of the instance level parameter values for the user-defined topology parameters. A pipeline can only define or override parameters values for parameters which have been declared in the referenced topology. Topology parameters without a default value must be defined. Topology parameters with a default value can be optionally be overridden. */
parameters?: ParameterDefinition[];
};
/** Pipeline job represents a unique instance of a batch topology, used for offline processing of selected portions of archived content. */
export type PipelineJob = ProxyResource & {
/** Reference to an existing pipeline topology. When activated, this pipeline job will process content according to the pipeline topology definition. */
topologyName?: string;
/** An optional description for the pipeline. */
description?: string;
/**
* Current state of the pipeline (read-only).
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly state?: PipelineJobState;
/**
* The date-time by when this pipeline job will be automatically deleted from your account.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly expiration?: Date;
/**
* Details about the error, in case the pipeline job fails.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly error?: PipelineJobError;
/** List of the instance level parameter values for the user-defined topology parameters. A pipeline can only define or override parameters values for parameters which have been declared in the referenced topology. Topology parameters without a default value must be defined. Topology parameters with a default value can be optionally be overridden. */
parameters?: ParameterDefinition[];
};
/** Pipeline job represents a unique instance of a batch topology, used for offline processing of selected portions of archived content. */
export type PipelineJobUpdate = ProxyResource & {
/** Reference to an existing pipeline topology. When activated, this pipeline job will process content according to the pipeline topology definition. */
topologyName?: string;
/** An optional description for the pipeline. */
description?: string;
/**
* Current state of the pipeline (read-only).
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly state?: PipelineJobState;
/**
* The date-time by when this pipeline job will be automatically deleted from your account.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly expiration?: Date;
/**
* Details about the error, in case the pipeline job fails.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly error?: PipelineJobError;
/** List of the instance level parameter values for the user-defined topology parameters. A pipeline can only define or override parameters values for parameters which have been declared in the referenced topology. Topology parameters without a default value must be defined. Topology parameters with a default value can be optionally be overridden. */
parameters?: ParameterDefinition[];
};
/** Represents a video resource within Azure Video Analyzer. Videos can be ingested from RTSP cameras through live pipelines or can be created by exporting sequences from existing captured video through a pipeline job. Videos ingested through live pipelines can be streamed through Azure Video Analyzer Player Widget or compatible players. Exported videos can be downloaded as MP4 files. */
export type VideoEntity = ProxyResource & {
/** Optional video title provided by the user. Value can be up to 256 characters long. */
title?: string;
/** Optional video description provided by the user. Value can be up to 2048 characters long. */
description?: string;
/**
* Video content type. Different content types are suitable for different applications and scenarios.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly typePropertiesType?: VideoType;
/**
* Video flags contain information about the available video actions and its dynamic properties based on the current video state.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly flags?: VideoFlags;
/**
* Set of URLs to the video content.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly contentUrls?: VideoContentUrls;
/** Contains information about the video and audio content. */
mediaInfo?: VideoMediaInfo;
/** Video archival properties. */
archival?: VideoArchival;
};
/** Access policies help define the authentication rules, and control access to specific video resources. */
export type AccessPolicyEntity = ProxyResource & {
/** Defines the access level granted by this policy. */
role?: AccessPolicyRole;
/** Authentication method to be used when validating client API access. */
authentication?: AuthenticationBaseUnion;
};
/** The Video Analyzer account. */
export type VideoAnalyzer = TrackedResource & {
/** The identities associated to the Video Analyzer resource. */
identity?: VideoAnalyzerIdentity;
/** The storage accounts for this resource. */
storageAccounts?: StorageAccount[];
/**
* The endpoints associated with this resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly endpoints?: Endpoint[];
/** The account encryption properties. */
encryption?: AccountEncryption;
/** The IoT Hubs for this resource. */
iotHubs?: IotHub[];
/** Whether or not public network access is allowed for resources under the Video Analyzer account. */
publicNetworkAccess?: PublicNetworkAccess;
/** Network access control for Video Analyzer. */
networkAccessControl?: NetworkAccessControl;
/**
* Provisioning state of the Video Analyzer account.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: ProvisioningState;
/**
* Private Endpoint Connections created under Video Analyzer account.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly privateEndpointConnections?: PrivateEndpointConnection[];
};
/** RTSP source allows for media from an RTSP camera or generic RTSP server to be ingested into a pipeline. */
export type RtspSource = SourceNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.RtspSource";
/** Network transport utilized by the RTSP and RTP exchange: TCP or HTTP. When using TCP, the RTP packets are interleaved on the TCP RTSP connection. When using HTTP, the RTSP messages are exchanged through long lived HTTP connections, and the RTP packages are interleaved in the HTTP connections alongside the RTSP messages. */
transport?: RtspTransport;
/** RTSP endpoint information for Video Analyzer to connect to. This contains the required information for Video Analyzer to connect to RTSP cameras and/or generic RTSP servers. */
endpoint: EndpointBaseUnion;
};
/** Video source allows for content from a Video Analyzer video resource to be ingested into a pipeline. Currently supported only with batch pipelines. */
export type VideoSource = SourceNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.VideoSource";
/** Name of the Video Analyzer video resource to be used as the source. */
videoName: string;
/** Describes a sequence of datetime ranges. The video source only picks up recorded media within these ranges. */
timeSequences: TimeSequenceBaseUnion;
};
/** Encoder processor allows for encoding of the input content. For example, it can used to change the resolution from 4K to 1280x720. */
export type EncoderProcessor = ProcessorNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.EncoderProcessor";
/** The encoder preset, which defines the recipe or instructions on how the input content should be processed. */
preset: EncoderPresetBaseUnion;
};
/** Video sink in a live topology allows for video and audio to be captured, optionally archived, and published via a video resource. If archiving is enabled, this results in a video of type 'archive'. If used in a batch topology, this allows for video and audio to be stored as a file, and published via a video resource of type 'file' */
export type VideoSink = SinkNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
type: "#Microsoft.VideoAnalyzer.VideoSink";
/** Name of a new or existing video resource used to capture and publish content. Note: if downstream of RTSP source, and if disableArchive is set to true, then no content is archived. */
videoName: string;
/** Optional video properties to be used in case a new video resource needs to be created on the service. */
videoCreationProperties?: VideoCreationProperties;
/** Options to change how the video sink publishes content via the video resource. This property is only allowed for topologies where "kind" is set to "live". */
videoPublishingOptions?: VideoPublishingOptions;
};
/** Defines headers for VideoAnalyzers_createOrUpdate operation. */
export interface VideoAnalyzersCreateOrUpdateHeaders {
/** The recommended number of seconds to wait before calling the URI specified in Azure-AsyncOperation. */
retryAfter?: number;
/** The URI to poll for completion status. */
location?: string;
/** The URI to poll for completion status. */
azureAsyncOperation?: string;
}
/** Defines headers for VideoAnalyzers_update operation. */
export interface VideoAnalyzersUpdateHeaders {
/** The recommended number of seconds to wait before calling the URI specified in Azure-AsyncOperation. */
retryAfter?: number;
/** The URI to poll for completion status. */
location?: string;
/** The URI to poll for completion status. */
azureAsyncOperation?: string;
}
/** Defines headers for PrivateEndpointConnections_createOrUpdate operation. */
export interface PrivateEndpointConnectionsCreateOrUpdateHeaders {
/** The recommended number of seconds to wait before calling the URI specified in Azure-AsyncOperation. */
retryAfter?: number;
/** The URI to poll for completion status. */
location?: string;
/** The URI to poll for completion status. */
azureAsyncOperation?: string;
}
/** Known values of {@link CreatedByType} that the service accepts. */
export enum KnownCreatedByType {
User = "User",
Application = "Application",
ManagedIdentity = "ManagedIdentity",
Key = "Key"
}
/**
* Defines values for CreatedByType. \
* {@link KnownCreatedByType} can be used interchangeably with CreatedByType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **User** \
* **Application** \
* **ManagedIdentity** \
* **Key**
*/
export type CreatedByType = string;
/** Known values of {@link ParameterType} that the service accepts. */
export enum KnownParameterType {
/** The parameter's value is a string. */
String = "String",
/** The parameter's value is a string that holds sensitive information. */
SecretString = "SecretString",
/** The parameter's value is a 32-bit signed integer. */
Int = "Int",
/** The parameter's value is a 64-bit double-precision floating point. */
Double = "Double",
/** The parameter's value is a boolean value that is either true or false. */
Bool = "Bool"
}
/**
* Defines values for ParameterType. \
* {@link KnownParameterType} can be used interchangeably with ParameterType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **String**: The parameter's value is a string. \
* **SecretString**: The parameter's value is a string that holds sensitive information. \
* **Int**: The parameter's value is a 32-bit signed integer. \
* **Double**: The parameter's value is a 64-bit double-precision floating point. \
* **Bool**: The parameter's value is a boolean value that is either true or false.
*/
export type ParameterType = string;
/** Known values of {@link Kind} that the service accepts. */
export enum KnownKind {
/** Live pipeline topology resource. */
Live = "Live",
/** Batch pipeline topology resource. */
Batch = "Batch"
}
/**
* Defines values for Kind. \
* {@link KnownKind} can be used interchangeably with Kind,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Live**: Live pipeline topology resource. \
* **Batch**: Batch pipeline topology resource.
*/
export type Kind = string;
/** Known values of {@link SkuName} that the service accepts. */
export enum KnownSkuName {
/** Represents the Live S1 SKU name. Using this SKU you can create live pipelines to capture, record, and stream live video from RTSP-capable cameras at bitrate settings from 0.5 Kbps to 3000 Kbps. */
LiveS1 = "Live_S1",
/** Represents the Batch S1 SKU name. Using this SKU you can create pipeline jobs to process recorded content. */
BatchS1 = "Batch_S1"
}
/**
* Defines values for SkuName. \
* {@link KnownSkuName} can be used interchangeably with SkuName,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Live_S1**: Represents the Live S1 SKU name. Using this SKU you can create live pipelines to capture, record, and stream live video from RTSP-capable cameras at bitrate settings from 0.5 Kbps to 3000 Kbps. \
* **Batch_S1**: Represents the Batch S1 SKU name. Using this SKU you can create pipeline jobs to process recorded content.
*/
export type SkuName = string;
/** Known values of {@link SkuTier} that the service accepts. */
export enum KnownSkuTier {
/** Standard tier. */
Standard = "Standard"
}
/**
* Defines values for SkuTier. \
* {@link KnownSkuTier} can be used interchangeably with SkuTier,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Standard**: Standard tier.
*/
export type SkuTier = string;
/** Known values of {@link LivePipelineState} that the service accepts. */
export enum KnownLivePipelineState {
/** The live pipeline is idle and not processing media. */
Inactive = "Inactive",
/** The live pipeline is transitioning into the active state. */
Activating = "Activating",
/** The live pipeline is active and able to process media. If your data source is not available, for instance, if your RTSP camera is powered off or unreachable, the pipeline will still be active and periodically retrying the connection. Your Azure subscription will be billed for the duration in which the live pipeline is in the active state. */
Active = "Active",
/** The live pipeline is transitioning into the inactive state. */
Deactivating = "Deactivating"
}
/**
* Defines values for LivePipelineState. \
* {@link KnownLivePipelineState} can be used interchangeably with LivePipelineState,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Inactive**: The live pipeline is idle and not processing media. \
* **Activating**: The live pipeline is transitioning into the active state. \
* **Active**: The live pipeline is active and able to process media. If your data source is not available, for instance, if your RTSP camera is powered off or unreachable, the pipeline will still be active and periodically retrying the connection. Your Azure subscription will be billed for the duration in which the live pipeline is in the active state. \
* **Deactivating**: The live pipeline is transitioning into the inactive state.
*/
export type LivePipelineState = string;
/** Known values of {@link PipelineJobState} that the service accepts. */
export enum KnownPipelineJobState {
/** Pipeline job is processing. */
Processing = "Processing",
/** Pipeline job is canceled. */
Canceled = "Canceled",
/** Pipeline job completed. */
Completed = "Completed",
/** Pipeline job failed. */
Failed = "Failed"
}
/**
* Defines values for PipelineJobState. \
* {@link KnownPipelineJobState} can be used interchangeably with PipelineJobState,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Processing**: Pipeline job is processing. \
* **Canceled**: Pipeline job is canceled. \
* **Completed**: Pipeline job completed. \
* **Failed**: Pipeline job failed.
*/
export type PipelineJobState = string;
/** Known values of {@link MetricUnit} that the service accepts. */
export enum KnownMetricUnit {
/** The number of bytes. */
Bytes = "Bytes",
/** The count. */
Count = "Count",
/** The number of milliseconds. */
Milliseconds = "Milliseconds"
}
/**
* Defines values for MetricUnit. \
* {@link KnownMetricUnit} can be used interchangeably with MetricUnit,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Bytes**: The number of bytes. \
* **Count**: The count. \
* **Milliseconds**: The number of milliseconds.
*/
export type MetricUnit = string;
/** Known values of {@link MetricAggregationType} that the service accepts. */
export enum KnownMetricAggregationType {
/** The average. */
Average = "Average",
/** The count of a number of items, usually requests. */
Count = "Count",
/** The sum. */
Total = "Total"
}
/**
* Defines values for MetricAggregationType. \
* {@link KnownMetricAggregationType} can be used interchangeably with MetricAggregationType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Average**: The average. \
* **Count**: The count of a number of items, usually requests. \
* **Total**: The sum.
*/
export type MetricAggregationType = string;
/** Known values of {@link ActionType} that the service accepts. */
export enum KnownActionType {
/** An internal action. */
Internal = "Internal"
}
/**
* Defines values for ActionType. \
* {@link KnownActionType} can be used interchangeably with ActionType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Internal**: An internal action.
*/
export type ActionType = string;
/** Known values of {@link VideoAnalyzerEndpointType} that the service accepts. */
export enum KnownVideoAnalyzerEndpointType {
/** The client API endpoint. */
ClientApi = "ClientApi"
}
/**
* Defines values for VideoAnalyzerEndpointType. \
* {@link KnownVideoAnalyzerEndpointType} can be used interchangeably with VideoAnalyzerEndpointType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **ClientApi**: The client API endpoint.
*/
export type VideoAnalyzerEndpointType = string;
/** Known values of {@link AccountEncryptionKeyType} that the service accepts. */
export enum KnownAccountEncryptionKeyType {
/** The Account Key is encrypted with a System Key. */
SystemKey = "SystemKey",
/** The Account Key is encrypted with a Customer Key. */
CustomerKey = "CustomerKey"
}
/**
* Defines values for AccountEncryptionKeyType. \
* {@link KnownAccountEncryptionKeyType} can be used interchangeably with AccountEncryptionKeyType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **SystemKey**: The Account Key is encrypted with a System Key. \
* **CustomerKey**: The Account Key is encrypted with a Customer Key.
*/
export type AccountEncryptionKeyType = string;
/** Known values of {@link PublicNetworkAccess} that the service accepts. */
export enum KnownPublicNetworkAccess {
/** Public network access is enabled. */
Enabled = "Enabled",
/** Public network access is disabled. */
Disabled = "Disabled"
}
/**
* Defines values for PublicNetworkAccess. \
* {@link KnownPublicNetworkAccess} can be used interchangeably with PublicNetworkAccess,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Enabled**: Public network access is enabled. \
* **Disabled**: Public network access is disabled.
*/
export type PublicNetworkAccess = string;
/** Known values of {@link ProvisioningState} that the service accepts. */
export enum KnownProvisioningState {
/** Provisioning state failed. */
Failed = "Failed",
/** Provisioning state in progress. */
InProgress = "InProgress",
/** Provisioning state succeeded. */
Succeeded = "Succeeded"
}
/**
* Defines values for ProvisioningState. \
* {@link KnownProvisioningState} can be used interchangeably with ProvisioningState,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Failed**: Provisioning state failed. \
* **InProgress**: Provisioning state in progress. \
* **Succeeded**: Provisioning state succeeded.
*/
export type ProvisioningState = string;
/** Known values of {@link PrivateEndpointServiceConnectionStatus} that the service accepts. */
export enum KnownPrivateEndpointServiceConnectionStatus {
Pending = "Pending",
Approved = "Approved",
Rejected = "Rejected"
}
/**
* Defines values for PrivateEndpointServiceConnectionStatus. \
* {@link KnownPrivateEndpointServiceConnectionStatus} can be used interchangeably with PrivateEndpointServiceConnectionStatus,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Pending** \
* **Approved** \
* **Rejected**
*/
export type PrivateEndpointServiceConnectionStatus = string;
/** Known values of {@link PrivateEndpointConnectionProvisioningState} that the service accepts. */
export enum KnownPrivateEndpointConnectionProvisioningState {
Succeeded = "Succeeded",
Creating = "Creating",
Deleting = "Deleting",
Failed = "Failed"
}
/**
* Defines values for PrivateEndpointConnectionProvisioningState. \
* {@link KnownPrivateEndpointConnectionProvisioningState} can be used interchangeably with PrivateEndpointConnectionProvisioningState,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Succeeded** \
* **Creating** \
* **Deleting** \
* **Failed**
*/
export type PrivateEndpointConnectionProvisioningState = string;
/** Known values of {@link CheckNameAvailabilityReason} that the service accepts. */
export enum KnownCheckNameAvailabilityReason {
Invalid = "Invalid",
AlreadyExists = "AlreadyExists"
}
/**
* Defines values for CheckNameAvailabilityReason. \
* {@link KnownCheckNameAvailabilityReason} can be used interchangeably with CheckNameAvailabilityReason,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Invalid** \
* **AlreadyExists**
*/
export type CheckNameAvailabilityReason = string;
/** Known values of {@link VideoType} that the service accepts. */
export enum KnownVideoType {
/** Archive is flexible format that represents a video stream associated with wall-clock time. The video archive can either be continuous or discontinuous. An archive is discontinuous when there are gaps in the recording due to various reasons, such as the live pipeline being stopped, camera being disconnected or due to the use of event based recordings through the use of a signal gate. There is no limit to the archive duration and new video data can be appended to the existing archive at any time, as long as the same video codec and codec parameters are being used. Videos of this type are suitable for appending and long term archival. */
Archive = "Archive",
/** File represents a video which is stored as a single media file, such as MP4. Videos of this type are suitable to be downloaded for external consumption. */
File = "File"
}
/**
* Defines values for VideoType. \
* {@link KnownVideoType} can be used interchangeably with VideoType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Archive**: Archive is flexible format that represents a video stream associated with wall-clock time. The video archive can either be continuous or discontinuous. An archive is discontinuous when there are gaps in the recording due to various reasons, such as the live pipeline being stopped, camera being disconnected or due to the use of event based recordings through the use of a signal gate. There is no limit to the archive duration and new video data can be appended to the existing archive at any time, as long as the same video codec and codec parameters are being used. Videos of this type are suitable for appending and long term archival. \
* **File**: File represents a video which is stored as a single media file, such as MP4. Videos of this type are suitable to be downloaded for external consumption.
*/
export type VideoType = string;
/** Known values of {@link AccessPolicyRole} that the service accepts. */
export enum KnownAccessPolicyRole {
/** Reader role allows for read-only operations to be performed through the client APIs. */
Reader = "Reader"
}
/**
* Defines values for AccessPolicyRole. \
* {@link KnownAccessPolicyRole} can be used interchangeably with AccessPolicyRole,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Reader**: Reader role allows for read-only operations to be performed through the client APIs.
*/
export type AccessPolicyRole = string;
/** Known values of {@link RtspTransport} that the service accepts. */
export enum KnownRtspTransport {
/** HTTP transport. RTSP messages are exchanged over long running HTTP requests and RTP packets are interleaved within the HTTP channel. */
Http = "Http",
/** TCP transport. RTSP is used directly over TCP and RTP packets are interleaved within the TCP channel. */
Tcp = "Tcp"
}
/**
* Defines values for RtspTransport. \
* {@link KnownRtspTransport} can be used interchangeably with RtspTransport,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Http**: HTTP transport. RTSP messages are exchanged over long running HTTP requests and RTP packets are interleaved within the HTTP channel. \
* **Tcp**: TCP transport. RTSP is used directly over TCP and RTP packets are interleaved within the TCP channel.
*/
export type RtspTransport = string;
/** Known values of {@link EncoderSystemPresetType} that the service accepts. */
export enum KnownEncoderSystemPresetType {
/** Produces an MP4 file where the video is encoded with H.264 codec at a picture height of 540 pixels, and at a maximum bitrate of 2000 Kbps. Encoded video has the same average frame rate as the input. The aspect ratio of the input is preserved. If the input content has audio, then it is encoded with AAC-LC codec at 96 Kbps */
SingleLayer540PH264AAC = "SingleLayer_540p_H264_AAC",
/** Produces an MP4 file where the video is encoded with H.264 codec at a picture height of 720 pixels, and at a maximum bitrate of 3500 Kbps. Encoded video has the same average frame rate as the input. The aspect ratio of the input is preserved. If the input content has audio, then it is encoded with AAC-LC codec at 96 Kbps */
SingleLayer720PH264AAC = "SingleLayer_720p_H264_AAC",
/** Produces an MP4 file where the video is encoded with H.264 codec at a picture height of 1080 pixels, and at a maximum bitrate of 6000 Kbps. Encoded video has the same average frame rate as the input. The aspect ratio of the input is preserved. If the input content has audio, then it is encoded with AAC-LC codec at 128 Kbps */
SingleLayer1080PH264AAC = "SingleLayer_1080p_H264_AAC",
/** Produces an MP4 file where the video is encoded with H.264 codec at a picture height of 2160 pixels, and at a maximum bitrate of 16000 Kbps. Encoded video has the same average frame rate as the input. The aspect ratio of the input is preserved. If the input content has audio, then it is encoded with AAC-LC codec at 128 Kbps */
SingleLayer2160PH264AAC = "SingleLayer_2160p_H264_AAC"
}
/**
* Defines values for EncoderSystemPresetType. \
* {@link KnownEncoderSystemPresetType} can be used interchangeably with EncoderSystemPresetType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **SingleLayer_540p_H264_AAC**: Produces an MP4 file where the video is encoded with H.264 codec at a picture height of 540 pixels, and at a maximum bitrate of 2000 Kbps. Encoded video has the same average frame rate as the input. The aspect ratio of the input is preserved. If the input content has audio, then it is encoded with AAC-LC codec at 96 Kbps \
* **SingleLayer_720p_H264_AAC**: Produces an MP4 file where the video is encoded with H.264 codec at a picture height of 720 pixels, and at a maximum bitrate of 3500 Kbps. Encoded video has the same average frame rate as the input. The aspect ratio of the input is preserved. If the input content has audio, then it is encoded with AAC-LC codec at 96 Kbps \
* **SingleLayer_1080p_H264_AAC**: Produces an MP4 file where the video is encoded with H.264 codec at a picture height of 1080 pixels, and at a maximum bitrate of 6000 Kbps. Encoded video has the same average frame rate as the input. The aspect ratio of the input is preserved. If the input content has audio, then it is encoded with AAC-LC codec at 128 Kbps \
* **SingleLayer_2160p_H264_AAC**: Produces an MP4 file where the video is encoded with H.264 codec at a picture height of 2160 pixels, and at a maximum bitrate of 16000 Kbps. Encoded video has the same average frame rate as the input. The aspect ratio of the input is preserved. If the input content has audio, then it is encoded with AAC-LC codec at 128 Kbps
*/
export type EncoderSystemPresetType = string;
/** Known values of {@link VideoScaleMode} that the service accepts. */
export enum KnownVideoScaleMode {
/** Pads the video with black horizontal stripes (letterbox) or black vertical stripes (pillar-box) so the video is resized to the specified dimensions while not altering the content aspect ratio. */
Pad = "Pad",
/** Preserves the same aspect ratio as the input video. If only one video dimension is provided, the second dimension is calculated based on the input video aspect ratio. When 2 dimensions are provided, the video is resized to fit the most constraining dimension, considering the input video size and aspect ratio. */
PreserveAspectRatio = "PreserveAspectRatio",
/** Stretches the original video so it resized to the specified dimensions. */
Stretch = "Stretch"
}
/**
* Defines values for VideoScaleMode. \
* {@link KnownVideoScaleMode} can be used interchangeably with VideoScaleMode,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Pad**: Pads the video with black horizontal stripes (letterbox) or black vertical stripes (pillar-box) so the video is resized to the specified dimensions while not altering the content aspect ratio. \
* **PreserveAspectRatio**: Preserves the same aspect ratio as the input video. If only one video dimension is provided, the second dimension is calculated based on the input video aspect ratio. When 2 dimensions are provided, the video is resized to fit the most constraining dimension, considering the input video size and aspect ratio. \
* **Stretch**: Stretches the original video so it resized to the specified dimensions.
*/
export type VideoScaleMode = string;
/** Known values of {@link AccessPolicyRsaAlgo} that the service accepts. */
export enum KnownAccessPolicyRsaAlgo {
/** RS256 */
RS256 = "RS256",
/** RS384 */
RS384 = "RS384",
/** RS512 */
RS512 = "RS512"
}
/**
* Defines values for AccessPolicyRsaAlgo. \
* {@link KnownAccessPolicyRsaAlgo} can be used interchangeably with AccessPolicyRsaAlgo,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **RS256**: RS256 \
* **RS384**: RS384 \
* **RS512**: RS512
*/
export type AccessPolicyRsaAlgo = string;
/** Known values of {@link AccessPolicyEccAlgo} that the service accepts. */
export enum KnownAccessPolicyEccAlgo {
/** ES265 */
ES256 = "ES256",
/** ES384 */
ES384 = "ES384",
/** ES512 */
ES512 = "ES512"
}
/**
* Defines values for AccessPolicyEccAlgo. \
* {@link KnownAccessPolicyEccAlgo} can be used interchangeably with AccessPolicyEccAlgo,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **ES256**: ES265 \
* **ES384**: ES384 \
* **ES512**: ES512
*/
export type AccessPolicyEccAlgo = string;
/** Optional parameters. */
export interface EdgeModulesListOptionalParams
extends coreClient.OperationOptions {
/** Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to but not greater than the specified value n. */
top?: number;
}
/** Contains response data for the list operation. */
export type EdgeModulesListResponse = EdgeModuleEntityCollection;
/** Optional parameters. */
export interface EdgeModulesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type EdgeModulesGetResponse = EdgeModuleEntity;
/** Optional parameters. */
export interface EdgeModulesCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the createOrUpdate operation. */
export type EdgeModulesCreateOrUpdateResponse = EdgeModuleEntity;
/** Optional parameters. */
export interface EdgeModulesDeleteOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface EdgeModulesListProvisioningTokenOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listProvisioningToken operation. */
export type EdgeModulesListProvisioningTokenResponse = EdgeModuleProvisioningToken;
/** Optional parameters. */
export interface EdgeModulesListNextOptionalParams
extends coreClient.OperationOptions {
/** Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to but not greater than the specified value n. */
top?: number;
}
/** Contains response data for the listNext operation. */
export type EdgeModulesListNextResponse = EdgeModuleEntityCollection;
/** Optional parameters. */
export interface PipelineTopologiesListOptionalParams
extends coreClient.OperationOptions {
/** Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to but not greater than the specified value n. */
top?: number;
/** Restricts the set of items returned. */
filter?: string;
}
/** Contains response data for the list operation. */
export type PipelineTopologiesListResponse = PipelineTopologyCollection;
/** Optional parameters. */
export interface PipelineTopologiesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type PipelineTopologiesGetResponse = PipelineTopology;
/** Optional parameters. */
export interface PipelineTopologiesCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the createOrUpdate operation. */
export type PipelineTopologiesCreateOrUpdateResponse = PipelineTopology;
/** Optional parameters. */
export interface PipelineTopologiesDeleteOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PipelineTopologiesUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the update operation. */
export type PipelineTopologiesUpdateResponse = PipelineTopology;
/** Optional parameters. */
export interface PipelineTopologiesListNextOptionalParams
extends coreClient.OperationOptions {
/** Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to but not greater than the specified value n. */
top?: number;
/** Restricts the set of items returned. */
filter?: string;
}
/** Contains response data for the listNext operation. */
export type PipelineTopologiesListNextResponse = PipelineTopologyCollection;
/** Optional parameters. */
export interface LivePipelinesListOptionalParams
extends coreClient.OperationOptions {
/** Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to but not greater than the specified value n. */
top?: number;
/** Restricts the set of items returned. */
filter?: string;
}
/** Contains response data for the list operation. */
export type LivePipelinesListResponse = LivePipelineCollection;
/** Optional parameters. */
export interface LivePipelinesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type LivePipelinesGetResponse = LivePipeline;
/** Optional parameters. */
export interface LivePipelinesCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the createOrUpdate operation. */
export type LivePipelinesCreateOrUpdateResponse = LivePipeline;
/** Optional parameters. */
export interface LivePipelinesDeleteOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface LivePipelinesUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the update operation. */
export type LivePipelinesUpdateResponse = LivePipeline;
/** Optional parameters. */
export interface LivePipelinesActivateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface LivePipelinesDeactivateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface LivePipelinesListNextOptionalParams
extends coreClient.OperationOptions {
/** Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to but not greater than the specified value n. */
top?: number;
/** Restricts the set of items returned. */
filter?: string;
}
/** Contains response data for the listNext operation. */
export type LivePipelinesListNextResponse = LivePipelineCollection;
/** Optional parameters. */
export interface PipelineJobsListOptionalParams
extends coreClient.OperationOptions {
/** Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to but not greater than the specified value n. */
top?: number;
/** Restricts the set of items returned. */
filter?: string;
}
/** Contains response data for the list operation. */
export type PipelineJobsListResponse = PipelineJobCollection;
/** Optional parameters. */
export interface PipelineJobsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type PipelineJobsGetResponse = PipelineJob;
/** Optional parameters. */
export interface PipelineJobsCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the createOrUpdate operation. */
export type PipelineJobsCreateOrUpdateResponse = PipelineJob;
/** Optional parameters. */
export interface PipelineJobsDeleteOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface PipelineJobsUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the update operation. */
export type PipelineJobsUpdateResponse = PipelineJob;
/** Optional parameters. */
export interface PipelineJobsCancelOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface PipelineJobsListNextOptionalParams
extends coreClient.OperationOptions {
/** Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to but not greater than the specified value n. */
top?: number;
/** Restricts the set of items returned. */
filter?: string;
}
/** Contains response data for the listNext operation. */
export type PipelineJobsListNextResponse = PipelineJobCollection;
/** Optional parameters. */
export interface LivePipelineOperationStatusesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type LivePipelineOperationStatusesGetResponse = LivePipelineOperationStatus;
/** Optional parameters. */
export interface PipelineJobOperationStatusesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type PipelineJobOperationStatusesGetResponse = PipelineJobOperationStatus;
/** Optional parameters. */
export interface OperationsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type OperationsListResponse = OperationCollection;
/** Optional parameters. */
export interface VideoAnalyzersListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type VideoAnalyzersListResponse = VideoAnalyzerCollection;
/** Optional parameters. */
export interface VideoAnalyzersGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type VideoAnalyzersGetResponse = VideoAnalyzer;
/** Optional parameters. */
export interface VideoAnalyzersCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the createOrUpdate operation. */
export type VideoAnalyzersCreateOrUpdateResponse = VideoAnalyzer;
/** Optional parameters. */
export interface VideoAnalyzersDeleteOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface VideoAnalyzersUpdateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the update operation. */
export type VideoAnalyzersUpdateResponse = VideoAnalyzersUpdateHeaders &
VideoAnalyzer;
/** Optional parameters. */
export interface VideoAnalyzersListBySubscriptionOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listBySubscription operation. */
export type VideoAnalyzersListBySubscriptionResponse = VideoAnalyzerCollection;
/** Optional parameters. */
export interface PrivateLinkResourcesListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type PrivateLinkResourcesListResponse = PrivateLinkResourceListResult;
/** Optional parameters. */
export interface PrivateLinkResourcesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type PrivateLinkResourcesGetResponse = PrivateLinkResource;
/** Optional parameters. */
export interface PrivateEndpointConnectionsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type PrivateEndpointConnectionsListResponse = PrivateEndpointConnectionListResult;
/** Optional parameters. */
export interface PrivateEndpointConnectionsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type PrivateEndpointConnectionsGetResponse = PrivateEndpointConnection;
/** Optional parameters. */
export interface PrivateEndpointConnectionsCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the createOrUpdate operation. */
export type PrivateEndpointConnectionsCreateOrUpdateResponse = PrivateEndpointConnectionsCreateOrUpdateHeaders &
PrivateEndpointConnection;
/** Optional parameters. */
export interface PrivateEndpointConnectionsDeleteOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface OperationStatusesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type OperationStatusesGetResponse = VideoAnalyzerPrivateEndpointConnectionOperationStatus;
/** Optional parameters. */
export interface OperationResultsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type OperationResultsGetResponse = PrivateEndpointConnection;
/** Optional parameters. */
export interface VideoAnalyzerOperationStatusesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type VideoAnalyzerOperationStatusesGetResponse = VideoAnalyzerOperationStatus;
/** Optional parameters. */
export interface VideoAnalyzerOperationResultsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type VideoAnalyzerOperationResultsGetResponse = VideoAnalyzer;
/** Optional parameters. */
export interface LocationsCheckNameAvailabilityOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the checkNameAvailability operation. */
export type LocationsCheckNameAvailabilityResponse = CheckNameAvailabilityResponse;
/** Optional parameters. */
export interface VideosListOptionalParams extends coreClient.OperationOptions {
/** Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to but not greater than the specified value n. */
top?: number;
}
/** Contains response data for the list operation. */
export type VideosListResponse = VideoEntityCollection;
/** Optional parameters. */
export interface VideosGetOptionalParams extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type VideosGetResponse = VideoEntity;
/** Optional parameters. */
export interface VideosCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the createOrUpdate operation. */
export type VideosCreateOrUpdateResponse = VideoEntity;
/** Optional parameters. */
export interface VideosDeleteOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface VideosUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the update operation. */
export type VideosUpdateResponse = VideoEntity;
/** Optional parameters. */
export interface VideosListContentTokenOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listContentToken operation. */
export type VideosListContentTokenResponse = VideoContentToken;
/** Optional parameters. */
export interface VideosListNextOptionalParams
extends coreClient.OperationOptions {
/** Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to but not greater than the specified value n. */
top?: number;
}
/** Contains response data for the listNext operation. */
export type VideosListNextResponse = VideoEntityCollection;
/** Optional parameters. */
export interface AccessPoliciesListOptionalParams
extends coreClient.OperationOptions {
/** Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to but not greater than the specified value n. */
top?: number;
}
/** Contains response data for the list operation. */
export type AccessPoliciesListResponse = AccessPolicyEntityCollection;
/** Optional parameters. */
export interface AccessPoliciesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type AccessPoliciesGetResponse = AccessPolicyEntity;
/** Optional parameters. */
export interface AccessPoliciesCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the createOrUpdate operation. */
export type AccessPoliciesCreateOrUpdateResponse = AccessPolicyEntity;
/** Optional parameters. */
export interface AccessPoliciesDeleteOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface AccessPoliciesUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the update operation. */
export type AccessPoliciesUpdateResponse = AccessPolicyEntity;
/** Optional parameters. */
export interface AccessPoliciesListNextOptionalParams
extends coreClient.OperationOptions {
/** Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to but not greater than the specified value n. */
top?: number;
}
/** Contains response data for the listNext operation. */
export type AccessPoliciesListNextResponse = AccessPolicyEntityCollection;
/** Optional parameters. */
export interface VideoAnalyzerManagementClientOptionalParams
extends coreClient.ServiceClientOptions {
/** server parameter */
$host?: string;
/** Api Version */
apiVersion?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
import { HttpClient, HttpResponse, HttpEvent } from '@angular/common/http';
import { Inject, Injectable, Optional } from '@angular/core';
import { UserAPIClientInterface } from './user-api-client.interface';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { USE_DOMAIN, USE_HTTP_OPTIONS, UserAPIClient } from './user-api-client.service';
import { DefaultHttpOptions, HttpOptions } from '../../types';
import * as models from '../../models';
import * as guards from '../../guards';
@Injectable()
export class GuardedUserAPIClient extends UserAPIClient implements UserAPIClientInterface {
constructor(
readonly httpClient: HttpClient,
@Optional() @Inject(USE_DOMAIN) domain?: string,
@Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions,
) {
super(httpClient, domain, options);
}
/**
* Get the authenticated user.
* Response generated for [ 200 ] HTTP response code.
*/
getUser(
args?: UserAPIClientInterface['getUserParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.User>;
getUser(
args?: UserAPIClientInterface['getUserParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.User>>;
getUser(
args?: UserAPIClientInterface['getUserParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.User>>;
getUser(
args: UserAPIClientInterface['getUserParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.User | HttpResponse<models.User> | HttpEvent<models.User>> {
return super.getUser(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUser(res) || console.error(`TypeGuard for response 'models.User' caught inconsistency.`, res)));
}
/**
* Update the authenticated user.
* Response generated for [ 200 ] HTTP response code.
*/
patchUser(
args: Exclude<UserAPIClientInterface['patchUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.User>;
patchUser(
args: Exclude<UserAPIClientInterface['patchUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.User>>;
patchUser(
args: Exclude<UserAPIClientInterface['patchUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.User>>;
patchUser(
args: Exclude<UserAPIClientInterface['patchUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.User | HttpResponse<models.User> | HttpEvent<models.User>> {
return super.patchUser(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUser(res) || console.error(`TypeGuard for response 'models.User' caught inconsistency.`, res)));
}
/**
* Delete email address(es).
* You can include a single email address or an array of addresses.
*
* Response generated for [ 204 ] HTTP response code.
*/
deleteUserEmails(
args: Exclude<UserAPIClientInterface['deleteUserEmailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteUserEmails(
args: Exclude<UserAPIClientInterface['deleteUserEmailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteUserEmails(
args: Exclude<UserAPIClientInterface['deleteUserEmailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteUserEmails(
args: Exclude<UserAPIClientInterface['deleteUserEmailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deleteUserEmails(args, requestHttpOptions, observe);
}
/**
* List email addresses for a user.
* In the final version of the API, this method will return an array of hashes
* with extended information for each email address indicating if the address
* has been verified and if it's primary email address for GitHub.
* Until API v3 is finalized, use the application/vnd.github.v3 media type to
* get other response format.
*
* Response generated for [ 200 ] HTTP response code.
*/
getUserEmails(
args?: UserAPIClientInterface['getUserEmailsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.UserEmails>;
getUserEmails(
args?: UserAPIClientInterface['getUserEmailsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.UserEmails>>;
getUserEmails(
args?: UserAPIClientInterface['getUserEmailsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.UserEmails>>;
getUserEmails(
args: UserAPIClientInterface['getUserEmailsParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.UserEmails | HttpResponse<models.UserEmails> | HttpEvent<models.UserEmails>> {
return super.getUserEmails(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUserEmails(res) || console.error(`TypeGuard for response 'models.UserEmails' caught inconsistency.`, res)));
}
/**
* Add email address(es).
* You can post a single email address or an array of addresses.
*
* Response generated for [ default ] HTTP response code.
*/
postUserEmails(
args: Exclude<UserAPIClientInterface['postUserEmailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
postUserEmails(
args: Exclude<UserAPIClientInterface['postUserEmailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
postUserEmails(
args: Exclude<UserAPIClientInterface['postUserEmailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
postUserEmails(
args: Exclude<UserAPIClientInterface['postUserEmailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.postUserEmails(args, requestHttpOptions, observe);
}
/**
* List the authenticated user's followers
* Response generated for [ 200 ] HTTP response code.
*/
getUserFollowers(
args?: UserAPIClientInterface['getUserFollowersParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Users>;
getUserFollowers(
args?: UserAPIClientInterface['getUserFollowersParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Users>>;
getUserFollowers(
args?: UserAPIClientInterface['getUserFollowersParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Users>>;
getUserFollowers(
args: UserAPIClientInterface['getUserFollowersParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> {
return super.getUserFollowers(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUsers(res) || console.error(`TypeGuard for response 'models.Users' caught inconsistency.`, res)));
}
/**
* List who the authenticated user is following.
* Response generated for [ 200 ] HTTP response code.
*/
getUserFollowing(
args?: UserAPIClientInterface['getUserFollowingParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Users>;
getUserFollowing(
args?: UserAPIClientInterface['getUserFollowingParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Users>>;
getUserFollowing(
args?: UserAPIClientInterface['getUserFollowingParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Users>>;
getUserFollowing(
args: UserAPIClientInterface['getUserFollowingParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> {
return super.getUserFollowing(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUsers(res) || console.error(`TypeGuard for response 'models.Users' caught inconsistency.`, res)));
}
/**
* Unfollow a user.
* Unfollowing a user requires the user to be logged in and authenticated with
* basic auth or OAuth with the user:follow scope.
*
* Response generated for [ 204 ] HTTP response code.
*/
deleteUserFollowingUsername(
args: Exclude<UserAPIClientInterface['deleteUserFollowingUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteUserFollowingUsername(
args: Exclude<UserAPIClientInterface['deleteUserFollowingUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteUserFollowingUsername(
args: Exclude<UserAPIClientInterface['deleteUserFollowingUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteUserFollowingUsername(
args: Exclude<UserAPIClientInterface['deleteUserFollowingUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deleteUserFollowingUsername(args, requestHttpOptions, observe);
}
/**
* Check if you are following a user.
* Response generated for [ 204 ] HTTP response code.
*/
getUserFollowingUsername(
args: Exclude<UserAPIClientInterface['getUserFollowingUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getUserFollowingUsername(
args: Exclude<UserAPIClientInterface['getUserFollowingUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getUserFollowingUsername(
args: Exclude<UserAPIClientInterface['getUserFollowingUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getUserFollowingUsername(
args: Exclude<UserAPIClientInterface['getUserFollowingUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.getUserFollowingUsername(args, requestHttpOptions, observe);
}
/**
* Follow a user.
* Following a user requires the user to be logged in and authenticated with
* basic auth or OAuth with the user:follow scope.
*
* Response generated for [ 204 ] HTTP response code.
*/
putUserFollowingUsername(
args: Exclude<UserAPIClientInterface['putUserFollowingUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
putUserFollowingUsername(
args: Exclude<UserAPIClientInterface['putUserFollowingUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
putUserFollowingUsername(
args: Exclude<UserAPIClientInterface['putUserFollowingUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
putUserFollowingUsername(
args: Exclude<UserAPIClientInterface['putUserFollowingUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.putUserFollowingUsername(args, requestHttpOptions, observe);
}
/**
* List issues.
* List all issues across owned and member repositories for the authenticated
* user.
*
* Response generated for [ 200 ] HTTP response code.
*/
getUserIssues(
args: Exclude<UserAPIClientInterface['getUserIssuesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Issues>;
getUserIssues(
args: Exclude<UserAPIClientInterface['getUserIssuesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Issues>>;
getUserIssues(
args: Exclude<UserAPIClientInterface['getUserIssuesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Issues>>;
getUserIssues(
args: Exclude<UserAPIClientInterface['getUserIssuesParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Issues | HttpResponse<models.Issues> | HttpEvent<models.Issues>> {
return super.getUserIssues(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isIssues(res) || console.error(`TypeGuard for response 'models.Issues' caught inconsistency.`, res)));
}
/**
* List your public keys.
* Lists the current user's keys. Management of public keys via the API requires
* that you are authenticated through basic auth, or OAuth with the 'user', 'write:public_key' scopes.
*
* Response generated for [ 200 ] HTTP response code.
*/
getUserKeys(
args?: UserAPIClientInterface['getUserKeysParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Gitignore>;
getUserKeys(
args?: UserAPIClientInterface['getUserKeysParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Gitignore>>;
getUserKeys(
args?: UserAPIClientInterface['getUserKeysParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Gitignore>>;
getUserKeys(
args: UserAPIClientInterface['getUserKeysParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Gitignore | HttpResponse<models.Gitignore> | HttpEvent<models.Gitignore>> {
return super.getUserKeys(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isGitignore(res) || console.error(`TypeGuard for response 'models.Gitignore' caught inconsistency.`, res)));
}
/**
* Create a public key.
* Response generated for [ 201 ] HTTP response code.
*/
postUserKeys(
args: Exclude<UserAPIClientInterface['postUserKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.UserKeysKeyId>;
postUserKeys(
args: Exclude<UserAPIClientInterface['postUserKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.UserKeysKeyId>>;
postUserKeys(
args: Exclude<UserAPIClientInterface['postUserKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.UserKeysKeyId>>;
postUserKeys(
args: Exclude<UserAPIClientInterface['postUserKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.UserKeysKeyId | HttpResponse<models.UserKeysKeyId> | HttpEvent<models.UserKeysKeyId>> {
return super.postUserKeys(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUserKeysKeyId(res) || console.error(`TypeGuard for response 'models.UserKeysKeyId' caught inconsistency.`, res)));
}
/**
* Delete a public key. Removes a public key. Requires that you are authenticated via Basic Auth or via OAuth with at least admin:public_key scope.
* Response generated for [ 204 ] HTTP response code.
*/
deleteUserKeysKeyId(
args: Exclude<UserAPIClientInterface['deleteUserKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteUserKeysKeyId(
args: Exclude<UserAPIClientInterface['deleteUserKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteUserKeysKeyId(
args: Exclude<UserAPIClientInterface['deleteUserKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteUserKeysKeyId(
args: Exclude<UserAPIClientInterface['deleteUserKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deleteUserKeysKeyId(args, requestHttpOptions, observe);
}
/**
* Get a single public key.
* Response generated for [ 200 ] HTTP response code.
*/
getUserKeysKeyId(
args: Exclude<UserAPIClientInterface['getUserKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.UserKeysKeyId>;
getUserKeysKeyId(
args: Exclude<UserAPIClientInterface['getUserKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.UserKeysKeyId>>;
getUserKeysKeyId(
args: Exclude<UserAPIClientInterface['getUserKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.UserKeysKeyId>>;
getUserKeysKeyId(
args: Exclude<UserAPIClientInterface['getUserKeysKeyIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.UserKeysKeyId | HttpResponse<models.UserKeysKeyId> | HttpEvent<models.UserKeysKeyId>> {
return super.getUserKeysKeyId(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUserKeysKeyId(res) || console.error(`TypeGuard for response 'models.UserKeysKeyId' caught inconsistency.`, res)));
}
/**
* List public and private organizations for the authenticated user.
* Response generated for [ 200 ] HTTP response code.
*/
getUserOrgs(
args?: UserAPIClientInterface['getUserOrgsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Gitignore>;
getUserOrgs(
args?: UserAPIClientInterface['getUserOrgsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Gitignore>>;
getUserOrgs(
args?: UserAPIClientInterface['getUserOrgsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Gitignore>>;
getUserOrgs(
args: UserAPIClientInterface['getUserOrgsParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Gitignore | HttpResponse<models.Gitignore> | HttpEvent<models.Gitignore>> {
return super.getUserOrgs(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isGitignore(res) || console.error(`TypeGuard for response 'models.Gitignore' caught inconsistency.`, res)));
}
/**
* List repositories for the authenticated user. Note that this does not include
* repositories owned by organizations which the user can access. You can lis
* user organizations and list organization repositories separately.
*
* Response generated for [ 200 ] HTTP response code.
*/
getUserRepos(
args?: UserAPIClientInterface['getUserReposParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Repos>;
getUserRepos(
args?: UserAPIClientInterface['getUserReposParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Repos>>;
getUserRepos(
args?: UserAPIClientInterface['getUserReposParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Repos>>;
getUserRepos(
args: UserAPIClientInterface['getUserReposParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Repos | HttpResponse<models.Repos> | HttpEvent<models.Repos>> {
return super.getUserRepos(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isRepos(res) || console.error(`TypeGuard for response 'models.Repos' caught inconsistency.`, res)));
}
/**
* Create a new repository for the authenticated user. OAuth users must supply
* repo scope.
*
* Response generated for [ 201 ] HTTP response code.
*/
postUserRepos(
args: Exclude<UserAPIClientInterface['postUserReposParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Repos>;
postUserRepos(
args: Exclude<UserAPIClientInterface['postUserReposParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Repos>>;
postUserRepos(
args: Exclude<UserAPIClientInterface['postUserReposParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Repos>>;
postUserRepos(
args: Exclude<UserAPIClientInterface['postUserReposParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Repos | HttpResponse<models.Repos> | HttpEvent<models.Repos>> {
return super.postUserRepos(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isRepos(res) || console.error(`TypeGuard for response 'models.Repos' caught inconsistency.`, res)));
}
/**
* List repositories being starred by the authenticated user.
* Response generated for [ 200 ] HTTP response code.
*/
getUserStarred(
args?: UserAPIClientInterface['getUserStarredParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Gitignore>;
getUserStarred(
args?: UserAPIClientInterface['getUserStarredParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Gitignore>>;
getUserStarred(
args?: UserAPIClientInterface['getUserStarredParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Gitignore>>;
getUserStarred(
args: UserAPIClientInterface['getUserStarredParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Gitignore | HttpResponse<models.Gitignore> | HttpEvent<models.Gitignore>> {
return super.getUserStarred(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isGitignore(res) || console.error(`TypeGuard for response 'models.Gitignore' caught inconsistency.`, res)));
}
/**
* Unstar a repository
* Response generated for [ 204 ] HTTP response code.
*/
deleteUserStarredOwnerRepo(
args: Exclude<UserAPIClientInterface['deleteUserStarredOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteUserStarredOwnerRepo(
args: Exclude<UserAPIClientInterface['deleteUserStarredOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteUserStarredOwnerRepo(
args: Exclude<UserAPIClientInterface['deleteUserStarredOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteUserStarredOwnerRepo(
args: Exclude<UserAPIClientInterface['deleteUserStarredOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deleteUserStarredOwnerRepo(args, requestHttpOptions, observe);
}
/**
* Check if you are starring a repository.
* Response generated for [ 204 ] HTTP response code.
*/
getUserStarredOwnerRepo(
args: Exclude<UserAPIClientInterface['getUserStarredOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getUserStarredOwnerRepo(
args: Exclude<UserAPIClientInterface['getUserStarredOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getUserStarredOwnerRepo(
args: Exclude<UserAPIClientInterface['getUserStarredOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getUserStarredOwnerRepo(
args: Exclude<UserAPIClientInterface['getUserStarredOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.getUserStarredOwnerRepo(args, requestHttpOptions, observe);
}
/**
* Star a repository.
* Response generated for [ 204 ] HTTP response code.
*/
putUserStarredOwnerRepo(
args: Exclude<UserAPIClientInterface['putUserStarredOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
putUserStarredOwnerRepo(
args: Exclude<UserAPIClientInterface['putUserStarredOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
putUserStarredOwnerRepo(
args: Exclude<UserAPIClientInterface['putUserStarredOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
putUserStarredOwnerRepo(
args: Exclude<UserAPIClientInterface['putUserStarredOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.putUserStarredOwnerRepo(args, requestHttpOptions, observe);
}
/**
* List repositories being watched by the authenticated user.
* Response generated for [ 200 ] HTTP response code.
*/
getUserSubscriptions(
args?: UserAPIClientInterface['getUserSubscriptionsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.UserIdSubscribitions>;
getUserSubscriptions(
args?: UserAPIClientInterface['getUserSubscriptionsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.UserIdSubscribitions>>;
getUserSubscriptions(
args?: UserAPIClientInterface['getUserSubscriptionsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.UserIdSubscribitions>>;
getUserSubscriptions(
args: UserAPIClientInterface['getUserSubscriptionsParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.UserIdSubscribitions | HttpResponse<models.UserIdSubscribitions> | HttpEvent<models.UserIdSubscribitions>> {
return super.getUserSubscriptions(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUserIdSubscribitions(res) || console.error(`TypeGuard for response 'models.UserIdSubscribitions' caught inconsistency.`, res)));
}
/**
* Stop watching a repository
* Response generated for [ 204 ] HTTP response code.
*/
deleteUserSubscriptionsOwnerRepo(
args: Exclude<UserAPIClientInterface['deleteUserSubscriptionsOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteUserSubscriptionsOwnerRepo(
args: Exclude<UserAPIClientInterface['deleteUserSubscriptionsOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteUserSubscriptionsOwnerRepo(
args: Exclude<UserAPIClientInterface['deleteUserSubscriptionsOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteUserSubscriptionsOwnerRepo(
args: Exclude<UserAPIClientInterface['deleteUserSubscriptionsOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deleteUserSubscriptionsOwnerRepo(args, requestHttpOptions, observe);
}
/**
* Check if you are watching a repository.
* Response generated for [ 204 ] HTTP response code.
*/
getUserSubscriptionsOwnerRepo(
args: Exclude<UserAPIClientInterface['getUserSubscriptionsOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getUserSubscriptionsOwnerRepo(
args: Exclude<UserAPIClientInterface['getUserSubscriptionsOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getUserSubscriptionsOwnerRepo(
args: Exclude<UserAPIClientInterface['getUserSubscriptionsOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getUserSubscriptionsOwnerRepo(
args: Exclude<UserAPIClientInterface['getUserSubscriptionsOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.getUserSubscriptionsOwnerRepo(args, requestHttpOptions, observe);
}
/**
* Watch a repository.
* Response generated for [ 204 ] HTTP response code.
*/
putUserSubscriptionsOwnerRepo(
args: Exclude<UserAPIClientInterface['putUserSubscriptionsOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
putUserSubscriptionsOwnerRepo(
args: Exclude<UserAPIClientInterface['putUserSubscriptionsOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
putUserSubscriptionsOwnerRepo(
args: Exclude<UserAPIClientInterface['putUserSubscriptionsOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
putUserSubscriptionsOwnerRepo(
args: Exclude<UserAPIClientInterface['putUserSubscriptionsOwnerRepoParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.putUserSubscriptionsOwnerRepo(args, requestHttpOptions, observe);
}
/**
* List all of the teams across all of the organizations to which the authenticated user belongs. This method requires user or repo scope when authenticating via OAuth.
* Response generated for [ 200 ] HTTP response code.
*/
getUserTeams(
args?: UserAPIClientInterface['getUserTeamsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.TeamsList>;
getUserTeams(
args?: UserAPIClientInterface['getUserTeamsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.TeamsList>>;
getUserTeams(
args?: UserAPIClientInterface['getUserTeamsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.TeamsList>>;
getUserTeams(
args: UserAPIClientInterface['getUserTeamsParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.TeamsList | HttpResponse<models.TeamsList> | HttpEvent<models.TeamsList>> {
return super.getUserTeams(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isTeamsList(res) || console.error(`TypeGuard for response 'models.TeamsList' caught inconsistency.`, res)));
}
} | the_stack |
import * as xmldom from '@xmldom/xmldom';
import fsExtra from 'fs-extra';
import * as pathLib from 'path';
import type {Config} from '../types/config.js';
import type {XliffConfig} from '../types/formatters.js';
import type {Locale} from '../types/locale.js';
import {Formatter} from './index.js';
import {KnownError, unreachable} from '../error.js';
import {
Bundle,
Message,
ProgramMessage,
Placeholder,
makeMessageIdMap,
} from '../messages.js';
import {
getOneElementByTagNameOrThrow,
getNonEmptyAttributeOrThrow,
} from './xml-utils.js';
/**
* Create an XLIFF formatter from a main config object.
*/
export function xliffFactory(config: Config) {
return new XliffFormatter(config);
}
/**
* Formatter for XLIFF v1.2
* https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
*/
export class XliffFormatter implements Formatter {
private config: Config;
private xliffConfig: XliffConfig;
constructor(config: Config) {
if (config.interchange.format !== 'xliff') {
throw new Error(
`Internal error: expected interchange.format "xliff", ` +
`got ${config.interchange.format}`
);
}
this.config = config;
this.xliffConfig = config.interchange;
}
/**
* For each target locale, look for the file "<xliffDir>/<locale>.xlf", and if
* it exists, parse out translations.
*/
readTranslations(): Bundle[] {
const bundles: Array<Bundle> = [];
for (const locale of this.config.targetLocales) {
const path = pathLib.join(
this.config.resolve(this.xliffConfig.xliffDir),
locale + '.xlf'
);
let xmlStr;
try {
xmlStr = fsExtra.readFileSync(path, 'utf8');
} catch (err) {
if ((err as Error & {code: string}).code === 'ENOENT') {
// It's ok if the file doesn't exist, it's probably just the first
// time we're running for this locale.
continue;
}
throw err;
}
bundles.push(this.parseXliff(xmlStr));
}
return bundles;
}
/**
* Parse the given XLIFF XML string and return its translations.
*/
private parseXliff(xmlStr: string): Bundle {
const doc = new xmldom.DOMParser().parseFromString(xmlStr);
const file = getOneElementByTagNameOrThrow(doc, 'file');
const locale = getNonEmptyAttributeOrThrow(
file,
'target-language'
) as Locale;
const messages: Message[] = [];
const transUnits = file.getElementsByTagName('trans-unit');
for (let t = 0; t < transUnits.length; t++) {
const transUnit = transUnits[t];
const name = getNonEmptyAttributeOrThrow(transUnit, 'id');
const targets = transUnit.getElementsByTagName('target');
if (targets.length === 0) {
// No <target> means it's not translated yet.
continue;
}
if (targets.length > 1) {
throw new KnownError(
`Expected 0 or 1 <target> in <trans-unit>, got ${targets.length}`
);
}
const target = targets[0];
const contents: Array<string | Placeholder> = [];
for (let c = 0; c < target.childNodes.length; c++) {
const child = target.childNodes[c];
if (child.nodeType === doc.TEXT_NODE) {
contents.push(child.nodeValue || '');
} else if (
child.nodeType === doc.ELEMENT_NODE &&
child.nodeName === 'x'
) {
const phText = getNonEmptyAttributeOrThrow(
child as Element,
'equiv-text'
);
const index = Number(
getNonEmptyAttributeOrThrow(child as Element, 'id')
);
contents.push({untranslatable: phText, index});
} else if (
child.nodeType === doc.ELEMENT_NODE &&
child.nodeName === 'ph'
) {
const phText = child.childNodes[0];
if (
child.childNodes.length !== 1 ||
!phText ||
phText.nodeType !== doc.TEXT_NODE
) {
throw new KnownError(
`Expected <${child.nodeName}> to have exactly one text node`
);
}
const index = Number(
getNonEmptyAttributeOrThrow(child as Element, 'id')
);
contents.push({untranslatable: phText.nodeValue || '', index});
} else {
throw new KnownError(
`Unexpected node in <trans-unit>: ${child.nodeType} ${child.nodeName}`
);
}
}
messages.push({name, contents});
}
return {locale, messages};
}
/**
* Write a "<xliffDir>/<locale>.xlf" file for each target locale. If a message
* has already been translated, it will have both a <source> and a <target>.
* Otherwise, it will only have a <source>.
*/
async writeOutput(
sourceMessages: ProgramMessage[],
translations: Map<Locale, Message[]>
): Promise<void> {
const xliffDir = this.config.resolve(this.xliffConfig.xliffDir);
try {
await fsExtra.ensureDir(xliffDir);
} catch (e) {
throw new KnownError(
`Error creating XLIFF directory: ${xliffDir}\n` +
`Do you have write permission?\n` +
(e as Error).message
);
}
const writes: Array<Promise<void>> = [];
for (const targetLocale of this.config.targetLocales) {
const xmlStr = this.encodeLocale(
sourceMessages,
targetLocale,
translations.get(targetLocale) || []
);
const path = pathLib.join(xliffDir, `${targetLocale}.xlf`);
writes.push(
fsExtra.writeFile(path, xmlStr, 'utf8').catch((e) => {
throw new KnownError(
`Error creating XLIFF file: ${path}\n` +
`Do you have write permission?\n` +
(e as Error).message
);
})
);
}
await Promise.all(writes);
}
/**
* Encode the given locale in XLIFF format.
*/
private encodeLocale(
sourceMessages: ProgramMessage[],
targetLocale: Locale,
targetMessages: Message[]
): string {
const translationsByName = makeMessageIdMap(targetMessages);
const doc = new xmldom.DOMImplementation().createDocument('', '', null);
const indent = (node: Element | Document, level = 0) =>
node.appendChild(doc.createTextNode('\n' + Array(level + 1).join(' ')));
doc.appendChild(
doc.createProcessingInstruction('xml', 'version="1.0" encoding="UTF-8"')
);
indent(doc);
// https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#xliff
const xliff = doc.createElement('xliff');
xliff.setAttribute('version', '1.2');
xliff.setAttribute('xmlns', 'urn:oasis:names:tc:xliff:document:1.2');
doc.appendChild(xliff);
indent(xliff);
// https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#file
const file = doc.createElement('file');
xliff.appendChild(file);
file.setAttribute('target-language', targetLocale);
file.setAttribute('source-language', this.config.sourceLocale);
// TODO The spec requires the source filename in the "original" attribute,
// but we don't currently track filenames.
file.setAttribute('original', 'lit-localize-inputs');
// Plaintext seems right, as opposed to HTML, since our translatable message
// text is just text, and all HTML markup is encoded into <x> or <ph>
// elements.
file.setAttribute('datatype', 'plaintext');
indent(file);
// https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#body
const body = doc.createElement('body');
file.appendChild(body);
indent(body);
for (const {name, contents: sourceContents, desc} of sourceMessages) {
// https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#trans-unit
const transUnit = doc.createElement('trans-unit');
body.appendChild(transUnit);
indent(transUnit, 1);
transUnit.setAttribute('id', name);
// https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#source
const source = doc.createElement('source');
for (const child of this.encodeContents(doc, sourceContents)) {
source.appendChild(child);
}
transUnit.appendChild(source);
const translation = translationsByName.get(name);
if (translation !== undefined) {
// https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#target
const target = doc.createElement('target');
for (const child of this.encodeContents(doc, translation.contents)) {
target.appendChild(child);
}
indent(transUnit, 1);
transUnit.appendChild(target);
}
if (desc) {
// https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#note
const note = doc.createElement('note');
note.appendChild(doc.createTextNode(desc));
indent(transUnit, 1);
transUnit.appendChild(note);
}
indent(transUnit);
indent(body);
}
indent(file);
indent(xliff);
indent(doc);
const serializer = new xmldom.XMLSerializer();
const xmlStr = serializer.serializeToString(doc);
return xmlStr;
}
/**
* Encode the given message contents in XLIFF format.
*/
private encodeContents(doc: Document, contents: Message['contents']): Node[] {
const nodes = [];
// We need a unique ID within each source for each placeholder. The index
// will do.
let phIdx = 0;
for (const content of contents) {
if (typeof content === 'string') {
nodes.push(doc.createTextNode(content));
} else {
nodes.push(this.createPlaceholder(doc, String(phIdx++), content));
}
}
return nodes;
}
private createPlaceholder(
doc: Document,
id: string,
{untranslatable}: Placeholder
): HTMLElement {
const style = this.xliffConfig.placeholderStyle ?? 'x';
if (style === 'x') {
// https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#x
const el = doc.createElement('x');
el.setAttribute('id', id);
el.setAttribute('equiv-text', untranslatable);
return el;
} else if (style === 'ph') {
// https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#ph
const el = doc.createElement('ph');
el.setAttribute('id', id);
el.appendChild(doc.createTextNode(untranslatable));
return el;
} else {
throw new Error(
`Internal error: unknown xliff placeholderStyle: ${unreachable(style)}`
);
}
}
} | the_stack |
import { BigNumber, ApiClient } from '../.'
/**
* icxorderbook RPCs for DeFi Blockchain
*/
export class ICXOrderBook {
private readonly client: ApiClient
constructor (client: ApiClient) {
this.client = client
}
/**
* Create and submits an ICX order creation transaction.
*
* @param {ICXOrder} order
* @param {string} [order.tokenFrom] Symbol or id of selling token
* @param {string} [order.chainFrom] Symbol or id of selling chain
* @param {string} [order.chainTo] Symbol or id of buying chain
* @param {string} [order.tokenTo] Symbol or id of buying token
* @param {string} [order.ownerAddress] Address of DFI token for fees and selling tokens in case of DFC/BTC order type
* @param {string} [order.receivePubkey] pubkey which can claim external HTLC in case of EXT/DFC order type
* @param {BigNumber} order.amountFrom tokenFrom coins amount
* @param {BigNumber} order.orderPrice Price per unit
* @param {number} [order.expiry=2880] Number of blocks until the order expires, default 2880 DFI blocks
* @param {UTXO[]} [utxos = []] Specific utxos to spend
* @param {string} utxos.txid transaction Id
* @param {number} utxos.vout The output number
* @return {Promise<ICXGenericResult>} Object including transaction id of the the result transaction
*/
async createOrder (order: ICXOrder, utxos: UTXO[] = []): Promise<ICXGenericResult> {
return await this.client.call(
'icx_createorder',
[
order, utxos
],
'bignumber'
)
}
/**
* Create and submits a makeoffer transaction.
*
* @param {ICXOffer} offer
* @param {string} offer.orderTx Transaction id of the order tx for which is the offer
* @param {BigNumber} offer.amount Amount fulfilling the order
* @param {string} offer.ownerAddress Address of DFI token and for receiving tokens in case of EXT/DFC order
* @param {string} [offer.receivePubkey] Pubkey which can claim external HTLC in case of EXT/DFC order type
* @param {number} [order.expiry = 10] Number of blocks until the offer expires, default 10 DFI blocks
* @param {UTXO[]} [utxos = []] Specific utxos to spend
* @param {string} utxos.txid transaction Id
* @param {number} utxos.vout The output number
* @return {Promise<ICXGenericResult>} Object including transaction id of the the transaction
*/
async makeOffer (offer: ICXOffer, utxos: UTXO[] = []): Promise<ICXGenericResult> {
return await this.client.call(
'icx_makeoffer',
[
offer, utxos
],
'bignumber'
)
}
/**
* Closes offer transaction.
*
* @param {string} offerTx Transaction Id of maker offer
* @param {UTXO[]} [utxos = []] Specific utxos to spend
* @param {string} utxos.txid transaction Id
* @param {number} utxos.vout The output number
* @return {Promise<ICXGenericResult>} Object including transaction id of the the transaction
*/
async closeOffer (offerTx: string, utxos: UTXO[] = []): Promise<ICXGenericResult> {
return await this.client.call(
'icx_closeoffer',
[
offerTx, utxos
],
'bignumber'
)
}
/**
* Create and submit a DFC HTLC transaction
*
* @param {HTLC} htlc
* @param {string} htlc.offerTx Transaction Id of the offer transaction for which the HTLC is
* @param {BigNumber} htlc.amount Amount in HTLC
* @param {string} htlc.hash Hash of seed used for the hash lock part
* @param {number} [htlc.timeout] Timeout (absolute in blocks) for expiration of HTLC in DFI blocks
* @param {UTXO[]} [utxos = []] Specific utxos to spend
* @param {string} utxos.txid transaction Id
* @param {number} utxos.vout The output number
* @return {Promise<ICXGenericResult>} Object including transaction id of the the transaction
*/
async submitDFCHTLC (htlc: HTLC, utxos: UTXO[] = []): Promise<ICXGenericResult> {
return await this.client.call(
'icx_submitdfchtlc',
[
htlc, utxos
],
'bignumber'
)
}
/**
* Create and submit an external(EXT) HTLC transaction
*
* @param {ExtHTLC} htlc
* @param {string} htlc.offerTx Transaction Id of the offer transaction for which the HTLC is
* @param {BigNumber} htlc.amount Amount in HTLC
* @param {string} htlc.htlcScriptAddress Script address of external HTLC
* @param {string} htlc.hash Hash of seed used for the hash lock part
* @param {string} htlc.ownerPubkey Pubkey of the owner to which the funds are refunded if HTLC timeouts
* @param {number} htlc.timeout Timeout (absolute in blocks) for expiration of HTLC in DFI blocks
* @param {UTXO[]} [utxos = []] Specific utxos to spend
* @param {string} utxos.txid transaction Id
* @param {number} utxos.vout The output number
* @return {Promise<ICXGenericResult>} Object including transaction id of the the transaction
*/
async submitExtHTLC (htlc: ExtHTLC, utxos: UTXO[] = []): Promise<ICXGenericResult> {
return await this.client.call(
'icx_submitexthtlc',
[
htlc, utxos
],
'bignumber'
)
}
/**
* Claims a DFC HTLC
*
* @param {string} DFCHTLCTxId Transaction id of DFC HTLC transaction for which the claim is
* @param {string} seed Secret seed for claiming HTLC
* @param {UTXO[]} [utxos = []] Specific utxos to spend
* @param {string} utxos.txid transaction Id
* @param {number} utxos.vout The output number
* @return {Promise<ICXGenericResult>} Object including transaction id of the the transaction
*/
async claimDFCHTLC (DFCHTLCTxId: string, seed: string, utxos: UTXO[] = []): Promise<ICXGenericResult> {
const htlc = {
dfchtlcTx: DFCHTLCTxId,
seed: seed
}
return await this.client.call(
'icx_claimdfchtlc',
[
htlc, utxos
],
'bignumber'
)
}
/**
* Closes ICX order
*
* @param {string} orderTx Transaction id of maker order
* @param {UTXO[]} [utxos = []] Specific utxos to spend
* @param {string} utxos.txid transaction Id
* @param {number} utxos.vout The output number
* @return {Promise<ICXGenericResult>} Object indluding transaction id of the the transaction
*/
async closeOrder (orderTx: string, utxos: UTXO[] = []): Promise<ICXGenericResult> {
return await this.client.call(
'icx_closeorder',
[
orderTx, utxos
],
'bignumber'
)
}
/**
* Returns information about order or fillorder
*
* @param {string} orderTx Transaction id of createorder or fulfillorder transaction
* @return {Promise<Record<string, ICXOrderInfo | ICXOfferInfo>>} Object including details of the transaction.
*/
async getOrder (orderTx: string): Promise<Record<string, ICXOrderInfo | ICXOfferInfo>> {
return await this.client.call(
'icx_getorder',
[
orderTx
],
'bignumber'
)
}
/**
* Returns information about offers based on order and ICXListOrderOptions passed
*
* @param {} options
* @param {string} options.orderTx Order txid to list all offers for this order
* @param {ICXListOrderOptions} options
* @param {string} [options.token] Token asset
* @param {string} [options.chain] Chain asset
* @param {string} [options.orderTx] Order txid to list all offers for this order
* @param {number} [options.limit = 50] Maximum number of orders to return (default: 50)
* @param {boolean} [options.closed = false] Display closed orders (default: false)
* @return {Promise<Record<string, ICXOfferInfo>>} Object including details of offers.
*/
async listOrders (options: { orderTx: string } & ICXListOrderOptions): Promise<Record<string, ICXOfferInfo>>
/**
* Returns information about orders or fillorders based on ICXListOrderOptions passed
*
* @param {ICXListOrderOptions} options
* @param {string} [options.token] Token asset
* @param {string} [options.chain] Chain asset
* @param {string} [options.orderTx] Order txid to list all offers for this order
* @param {number} [options.limit = 50] Maximum number of orders to return (default: 50)
* @param {boolean} [options.closed = false] Display closed orders (default: false)
* @return {Promise<Record<string, ICXOrderInfo | ICXOfferInfo>>} Object including details of orders and offers.
*/
async listOrders (options?: ICXListOrderOptions): Promise<Record<string, ICXOrderInfo | ICXOfferInfo>>
/**
* Returns information about orders or fillorders based on ICXListOrderOptions passed
*
* @param {ICXListOrderOptions} options
* @param {string} [options.token] Token asset
* @param {string} [options.chain] Chain asset
* @param {string} [options.orderTx] Order txid to list all offers for this order
* @param {number} [options.limit = 50] Maximum number of orders to return (default: 50)
* @param {boolean} [options.closed = false] Display closed orders (default: false)
* @return {Promise<Record<string, ICXOrderInfo | ICXOfferInfo>>} Object including details of the transaction.
*/
async listOrders (options: ICXListOrderOptions = {}): Promise<Record<string, ICXOrderInfo | ICXOfferInfo>> {
return await this.client.call(
'icx_listorders',
[
options
],
'bignumber'
)
}
/**
* Returns information about HTLCs based on ICXListHTLCOptions passed
*
* @param {ICXListHTLCOptions} options
* @param {string} options.offerTx Offer txid for which to list all HTLCS
* @param {number} [options.limit = 20] Maximum number of orders to return (default: 20)
* @param {boolean} [options.refunded = false] Display refunded HTLC (default: false)
* @param {boolean} [options.closed = false] Display claimed HTLCs (default: false)
* @return {Promise<Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo>>} Object indluding details of the HTLCS.
*/
async listHTLCs (options: ICXListHTLCOptions): Promise<Record<string, ICXDFCHTLCInfo| ICXEXTHTLCInfo| ICXClaimDFCHTLCInfo>> {
return await this.client.call(
'icx_listhtlcs',
[
options
],
'bignumber'
)
}
}
/** ICX order */
export interface ICXOrder {
/** Symbol or id of selling token */
tokenFrom?: string
/** Symbol or id of selling chain */
chainFrom?: string
/** Symbol or id of buying chain */
chainTo?: string
/** Symbol or id of buying token */
tokenTo?: string
/** Address of DFI token for fees and selling tokens in case of DFC/BTC order type */
ownerAddress?: string
/** pubkey which can claim external HTLC in case of EXT/DFC order type */
receivePubkey?: string
/** tokenFrom coins amount */
amountFrom: BigNumber
/** Price per unit */
orderPrice: BigNumber
/** Number of blocks until the order expires, default 2880 DFI blocks */
expiry?: number
}
/** Input UTXO */
export interface UTXO {
/** transaction id */
txid: string
/** output number */
vout: number
}
/** ICX RPC call Generic result */
export interface ICXGenericResult {
/** Experimental warning notice */
WARNING: string
/** Transaction id of the transaction. */
txid: string
}
/** ICX offer */
export interface ICXOffer {
/** Transaction id of the order tx for which is the offer */
orderTx: string
/** Amount fulfilling the order */
amount: BigNumber
/** Address of DFI token and for receiving tokens in case of EXT/DFC order */
ownerAddress: string
/** Pubkey which can claim external HTLC in case of EXT/DFC order type */
receivePubkey?: string
/** Number of blocks until the offer expires, default 10 DFI blocks */
expiry?: number
}
/** HTLC */
export interface HTLC {
/** Transaction Id of the offer transaction for which the HTLC is */
offerTx: string
/** Amount in HTLC */
amount: BigNumber
/** Hash of seed used for the hash lock part */
hash: string
/** Timeout (absolute in blocks) for expiration of HTLC in DFI blocks */
timeout?: number
}
/** External HTLC */
export interface ExtHTLC {
/** Transaction Id of the offer transaction for which the HTLC is */
offerTx: string
/** Amount in HTLC */
amount: BigNumber
/** Script address of external HTLC */
htlcScriptAddress: string
/** Hash of seed used for the hash lock part */
hash: string
/** Pubkey of the owner to which the funds are refunded if HTLC timeouts */
ownerPubkey: string
/** Timeout (absolute in blocks) for expiration of HTLC in DFI blocks */
timeout: number
}
export enum ICXOrderStatus {
OPEN = 'OPEN',
CLOSED = 'CLOSED',
FILLED = 'FILLED',
EXPIRED = 'EXPIRED'
}
export enum ICXOrderType {
INTERNAL = 'INTERNAL',
EXTERNAL = 'EXTERNAL',
}
export enum ICXHTLCType {
CLAIM_DFC = 'CLAIM DFC',
DFC = 'DFC',
EXTERNAL = 'EXTERNAL'
}
export enum ICXHTLCStatus {
OPEN = 'OPEN',
CLAIMED = 'CLAIMED',
REFUNDED = 'REFUNDED',
EXPIRED = 'EXPIRED',
CLOSED = 'CLOSED'
}
/** ICX order info */
export interface ICXOrderInfo {
/** Order status */
status: ICXOrderStatus
/** Order type. DFI as [ICXOrderType.INTERNAL] */
type: ICXOrderType
/** Symbol or id of selling token */
tokenFrom: string
/** Symbol or id of buying chain */
chainTo?: string
/** Pubkey which can claim external HTLC in case of EXT/DFC order type */
receivePubkey?: string
/** Symbol or id of selling chain */
chainFrom?: string
/** Symbol or id of buying token */
tokenTo?: string
/** Address of DFI token for fees and selling tokens in case of DFC/BTC order type */
ownerAddress: string
/** tokenFrom coins amount */
amountFrom: BigNumber
/** Remaining amount to fill */
amountToFill: BigNumber
/** Price per unit */
orderPrice: BigNumber
/** */
amountToFillInToAsset: BigNumber
/** creation height */
height: BigNumber
/** Number of blocks until the order expires */
expireHeight: BigNumber
/** Close height */
closeHeight?: BigNumber
/** Close order transaction Id */
closeTx?: string
/** Expired or not */
expired?: boolean
}
/** ICX offer info */
export interface ICXOfferInfo {
/** Transaction id of the order tx for which is the offer */
orderTx: string
/** Offer status */
status: ICXOrderStatus
/** Amount fulfilling the order */
amount: BigNumber
/** Amount fulfilling from asset */
amountInFromAsset: BigNumber
/** Address of DFI token and for receiving tokens in case of EXT/DFC order */
ownerAddress: string
/** Pubkey which can claim external HTLC in case of EXT/DFC order type */
receivePubkey?: string
/** Taker fee */
takerFee: BigNumber
/** Expire height */
expireHeight: BigNumber
}
/** ICX listOrder options */
export interface ICXListOrderOptions {
/** Token asset */
token?: string
/** Chain asset */
chain?: string
/** Order txid to list all offers for this order */
orderTx?: string
/** Maximum number of orders to return (default: 50) */
limit?: number
/** Display closed orders (default: false) */
closed?: boolean
}
/** ICX listHTLC options */
export interface ICXListHTLCOptions {
/** Offer txid for which to list all HTLCS */
offerTx: string
/** Maximum number of orders to return (default: 20) */
limit?: number
/** Display also claimed, expired and refunded HTLCs (default: false) */
closed?: boolean
}
/** ICX claimed DFCHTLC info */
export interface ICXClaimDFCHTLCInfo {
/** HTLC type */
type: ICXHTLCType
/** HTLC Transaction Id */
dfchtlcTx: string
/** HTLC claim secret */
seed: string
/** HTLC creation height */
height: BigNumber
}
/** ICX DFCHTLC info */
export interface ICXDFCHTLCInfo {
/** HTLC type */
type: ICXHTLCType
/** Status of the HTLC */
status: ICXHTLCStatus
/** Offer Transaction Id */
offerTx: string
/** Amount */
amount: BigNumber
/** Amount in external asset */
amountInEXTAsset: BigNumber
/** Hash of DFCHTLC */
hash: string
/** Timeout in blocks */
timeout: BigNumber
/** HTLC creation height */
height: BigNumber
/** HTLC refund height */
refundHeight: BigNumber
}
/** ICX EXTHTLC info */
export interface ICXEXTHTLCInfo {
/** HTLC type */
type: ICXHTLCType
/** Status of the HTLC */
status: ICXHTLCStatus
/** Offer Transaction Id */
offerTx: string
/** Amount */
amount: BigNumber
/** Amount in external asset */
amountInDFCAsset: BigNumber
/** Hash of EXTHTLC */
hash: string
/** HTLC script address */
htlcScriptAddress: string
/** Pubkey of the owner to which the funds are refunded if HTLC timeouts */
ownerPubkey: string
/** Timeout in blocks */
timeout: BigNumber
/** HTLC creation height */
height: BigNumber
} | the_stack |
import * as t from '@aws-accelerator/common-types';
/**
* Translation definition that is used as base for all other translations.
*/
export interface FieldTranslations {
title?: string;
description?: string;
url?: string;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type InterfaceFieldTranslations<P, K extends keyof P> = P[K] extends t.InterfaceType<any>
? FieldTranslations | undefined | never
: FieldTranslations;
/**
* Translation definition for interface types.
*
* @template P The properties type of the interface type.
*/
export interface InterfaceTranslations<P> extends FieldTranslations {
fields: {
[K in keyof P]: FieldTranslations;
};
}
/**
* Translation definition for enum types.
*
* @template E The enum values type of the enum type.
*/
export interface EnumTranslations<E extends string | number> extends FieldTranslations {
enumLabels?: Partial<Record<E, string>>;
}
/**
* Translation definition for sized types.
*/
export interface SizedTranslations extends FieldTranslations {
errorMessage?: string;
}
/**
* Helper type that delegates to the correct translation definition based on the type.
*/
export type TypeTranslations<T> = T extends t.InterfaceType<infer P>
? InterfaceTranslations<P>
: T extends t.EnumType<infer P>
? EnumTranslations<P>
: // eslint-disable-next-line @typescript-eslint/no-explicit-any
T extends t.SizedType<any, any>
? SizedTranslations
: FieldTranslations;
export interface I18nTranslations {
menu: {
accelerator_configuration: string;
graphical_editor: string;
code_editor: string;
properties: string;
wizard: string;
};
labels: {
empty: string;
codecommit_repository: string;
codecommit_repository_description: string;
codecommit_branch: string;
codecommit_branch_description: string;
codecommit_file: string;
codecommit_file_description: string;
export_as_file: string;
export_introduction: string;
configuration_is_valid: string;
array_element: string;
object_element: string;
required: string;
toggle_replacement: string;
loading: string;
selected_configuration_is_valid: string;
import_with_errors: string;
import_with_errors_description: string;
import_configuration_introduction: string;
configuration_file: string;
configuration_file_description: string;
configuration_file_constraint: string;
choose_language: string;
};
headers: {
add_dictionary_field: string;
configure_credentials: string;
import_configuration: string;
export_configuration: string;
choose_codecommit_file: string;
import_codecommit: string;
import_file: string;
};
buttons: {
add: string;
export: string;
remove: string;
save: string;
cancel: string;
choose: string;
choose_file: string;
edit: string;
import: string;
next: string;
previous: string;
save_changes: string;
};
wizard: {
steps: {
configure_global_settings: string;
select_security_guardrails: string;
select_security_services: string;
structure_organization: string;
structure_accounts: string;
configure_network: string;
configure_ad: string;
review: string;
};
headers: {
aws_configuration: string;
aws_configuration_desc: string;
framework: string;
framework_desc: string;
basic_settings: string;
basic_settings_desc: string;
security_notifications: string;
security_notifications_desc: string;
security_guardrails_always_on: string;
security_guardrails_always_on_desc: string;
security_guardrails_opt_in: string;
security_guardrails_opt_in_desc: string;
security_services: string;
security_services_desc: string;
security_services_logging: string;
security_services_logging_desc: string;
cidr_pools: string;
cidr_pools_desc: string;
add_cidr_pool: string;
edit_cidr_pool: string;
add_organizational_unit: string;
edit_organizational_unit: string;
organizational_units: string;
organizational_units_desc: string;
mandatory_accounts: string;
mandatory_accounts_desc: string;
workload_accounts: string;
workload_accounts_desc: string;
add_mandatory_account: string;
add_workload_account: string;
edit_mandatory_account: string;
edit_workload_account: string;
vpcs: string;
vpcs_desc: string;
add_vpc: string;
edit_vpc: string;
mads: string;
mads_desc: string;
edit_mad: string;
zones: string;
zones_desc: string;
edit_zone: string;
};
labels: {
alert_success_file: string;
credentials_not_set: string;
credentials_valid: string;
credentials_not_valid: string;
ct_enabled_not_authenticated: string;
ct_disabled_not_authenticated: string;
ct_detected_and_enabled: string;
ct_detected_and_disabled: string;
ct_not_detected_and_enabled: string;
ct_not_detected_and_disabled: string;
security_notifications_text: string;
security_notifications_email_not_unique: string;
security_guardrails_always_on_text: string;
security_guardrails_opt_in_text: string;
security_services_text: string;
security_services_logging_text: string;
cidr_pools_use_graphical_editor: string;
ou_key: string;
ou_name: string;
ou_default_per_account_budget: string;
ou_default_per_account_email: string;
ou_name_email_change_text: string;
ou_email_uniqueness_text: string;
account_key: string;
account_budget_use_ou: string;
account_budget_amount: string;
account_budget_email: string;
account_name_email_change_text: string;
account_email_uniqueness_text: string;
account_existing_account_text: string;
vpcs_use_graphical_editor: string;
zone_account: string;
zone_vpc_name: string;
zone_central_vpc: string;
zone_has_zones: string;
zone_has_resolvers: string;
};
fields: {
aws_credentials: string;
aws_credentials_desc: string;
architecture_template: string;
architecture_template_desc: string;
installation_region: string;
installation_region_desc: string;
installation_type: string;
installation_type_desc: string;
high_priority_email: string;
high_priority_email_desc: string;
medium_priority_email: string;
medium_priority_email_desc: string;
low_priority_email: string;
low_priority_email_desc: string;
aws_config: string;
aws_config_desc: string;
aws_config_rules: string;
aws_config_remediations: string;
cwl_centralized_access: string;
cwl_centralized_access_desc: string;
cwl_central_security_services_account: string;
cwl_central_security_services_account_desc: string;
cwl_central_operations_account: string;
cwl_central_operations_account_desc: string;
retention_periods_for: string;
retention_periods_for_desc: string;
vpc_flow_logs_all_vcps: string;
vpc_flow_logs_all_vcps_desc: string;
vpc_flow_logs_s3: string;
vpc_flow_logs_cwl: string;
ssm_logs_to: string;
ssm_logs_to_desc: string;
dns_resolver_logging_all_vpcs: string;
};
buttons: {
configure_aws_credentials: string;
select_configuration_file: string;
export_configure_credentials: string;
};
};
splash: {
category: string;
title: string;
subtitle: string;
description: string;
create_configuration: string;
next_step: string;
};
languages: { [key: string]: string };
}
export type I18nKey =
| `menu.${keyof I18nTranslations['menu']}`
| `labels.${keyof I18nTranslations['labels']}`
| `headers.${keyof I18nTranslations['headers']}`
| `buttons.${keyof I18nTranslations['buttons']}`
| `wizard.${keyof I18nTranslations['wizard']}`
| `wizard.steps.${keyof I18nTranslations['wizard']['steps']}`
| `wizard.headers.${keyof I18nTranslations['wizard']['headers']}`
| `wizard.labels.${keyof I18nTranslations['wizard']['labels']}`
| `wizard.fields.${keyof I18nTranslations['wizard']['fields']}`
| `wizard.buttons.${keyof I18nTranslations['wizard']['buttons']}`
| `splash.${keyof I18nTranslations['splash']}`
| `languages.${keyof I18nTranslations['languages']}`;
/**
* Translation interface for a specific language.
*/
export interface Translation {
languageCode: string;
translations: I18nTranslations;
add<T extends t.Any>(type: T, translations: TypeTranslations<T>): this;
tr<T extends t.Any>(type: T): TypeTranslations<T> | undefined;
currency(value: number, currency?: string): string;
}
export interface I18nFormatters {
currency(value: number, currency?: string): string;
}
/**
* Function that creates a new translation for the given language code.
*/
export function translation(
languageCode: string,
translations: I18nTranslations,
formatters: I18nFormatters,
): Translation {
const typeTranslations = new Map<t.Any, FieldTranslations>();
return {
languageCode,
translations,
/**
* Add a translation for a given type.
*/
add<T extends t.Any>(type: T, translations: TypeTranslations<T>) {
typeTranslations.set(type, copyOmitEmpty(translations)!);
return this;
},
/**
* Find the translations for a given type.
*/
tr<T extends t.Any>(type: T) {
return typeTranslations.get(type) as TypeTranslations<T>;
},
currency(value: number, currency?: string) {
return formatters.currency(value, currency);
},
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function isInterfaceTranslations(value: FieldTranslations): value is InterfaceTranslations<any> {
return 'fields' in value;
}
/**
* Copy an object and omit empty values.
*/
function copyOmitEmpty<T>(value: T): T | undefined {
if (typeof value === 'object') {
return Object.fromEntries(
Object.entries(value)
.map(([key, value]) => [key, copyOmitEmpty(value)])
.filter(([, value]) => value != null),
);
} else if (typeof value === 'string') {
return isStringEmpty(value) ? undefined : value;
}
throw new Error(`Unknown type ${typeof value}`);
}
function isStringEmpty(value: string) {
return value.length === 0;
} | the_stack |
import { bottom, collides, compact, moveElement, sortLayoutItemsByRowCol, validateLayout } from '../react-grid-layout.utils';
import objectContaining = jasmine.objectContaining;
/**
* IMPORTANT:
* This tests are taken from the project: https://github.com/STRML/react-grid-layout.
* The code should be as less modified as possible for easy maintenance.
*/
describe('bottom', () => {
it('Handles an empty layout as input', () => {
expect(bottom([])).toEqual(0);
});
it('Returns the bottom coordinate of the layout', () => {
expect(
bottom([
{id: '1', x: 0, y: 1, w: 1, h: 1},
{id: '2', x: 1, y: 2, w: 1, h: 1}
])
).toEqual(3);
});
});
describe('sortLayoutItemsByRowCol', () => {
it('should sort by top to bottom right', () => {
const layout = [
{x: 1, y: 1, w: 1, h: 1, id: '2'},
{x: 1, y: 0, w: 1, h: 1, id: '1'},
{x: 0, y: 1, w: 2, h: 2, id: '3'}
];
expect(sortLayoutItemsByRowCol(layout)).toEqual([
{x: 1, y: 0, w: 1, h: 1, id: '1'},
{x: 0, y: 1, w: 2, h: 2, id: '3'},
{x: 1, y: 1, w: 1, h: 1, id: '2'}
]);
});
});
describe('collides', () => {
it('Returns whether the layout items collide', () => {
expect(
collides(
{id: '1', x: 0, y: 1, w: 1, h: 1},
{id: '2', x: 1, y: 2, w: 1, h: 1}
)
).toEqual(false);
expect(
collides(
{id: '1', x: 0, y: 1, w: 1, h: 1},
{id: '2', x: 0, y: 1, w: 1, h: 1}
)
).toEqual(true);
});
});
describe('validateLayout', () => {
it('Validates an empty layout', () => {
validateLayout([]);
});
it('Validates a populated layout', () => {
validateLayout([
{id: '1', x: 0, y: 1, w: 1, h: 1},
{id: '2', x: 1, y: 2, w: 1, h: 1}
]);
});
it('Throws errors on invalid input', () => {
expect(() => {
validateLayout([
{id: '1', x: 0, y: 1, w: 1, h: 1},
{id: '2', x: 1, y: 2, w: 1} as any
]);
}).toThrowError(/layout\[1\]\.h must be a number!/i);
});
});
describe('moveElement', () => {
function compactAndMove(
layout,
layoutItem,
x,
y,
isUserAction,
preventCollision,
compactType,
cols
) {
return compact(
moveElement(
layout,
layoutItem,
x,
y,
isUserAction,
preventCollision,
compactType,
cols
),
compactType,
cols
);
}
it('Does not change layout when colliding on no rearrangement mode', () => {
const layout = [
{id: '1', x: 0, y: 1, w: 1, h: 1, moved: false},
{id: '2', x: 1, y: 2, w: 1, h: 1, moved: false}
];
const layoutItem = layout[0];
expect(
moveElement(
layout,
layoutItem,
1,
2, // x, y
true,
true, // isUserAction, preventCollision
null,
2 // compactType, cols
)
).toEqual([
{id: '1', x: 0, y: 1, w: 1, h: 1, moved: false},
{id: '2', x: 1, y: 2, w: 1, h: 1, moved: false}
]);
});
it('Does change layout when colliding in rearrangement mode', () => {
const layout = [
{id: '1', x: 0, y: 0, w: 1, h: 1, moved: false},
{id: '2', x: 1, y: 0, w: 1, h: 1, moved: false}
];
const layoutItem = layout[0];
expect(
moveElement(
layout,
layoutItem,
1,
0, // x, y
true,
false, // isUserAction, preventCollision
'vertical',
2 // compactType, cols
)
).toEqual([
{id: '1', x: 1, y: 0, w: 1, h: 1, moved: true},
{id: '2', x: 1, y: 1, w: 1, h: 1, moved: true}
]);
});
it('Moves elements out of the way without causing panel jumps when compaction is vertical', () => {
const layout = [
{x: 0, y: 0, w: 1, h: 10, id: 'A'},
{x: 0, y: 10, w: 1, h: 1, id: 'B'},
{x: 0, y: 11, w: 1, h: 1, id: 'C'}
];
// move A down slightly so it collides with C; can cause C to jump above B.
// We instead want B to jump above A (it has the room)
const itemA = layout[0];
expect(
compactAndMove(
layout,
itemA,
0,
1, // x, y
true,
false, // isUserAction, preventCollision
'vertical',
10 // compactType, cols
)
).toEqual([
objectContaining({x: 0, y: 1, w: 1, h: 10, id: 'A'}),
objectContaining({x: 0, y: 0, w: 1, h: 1, id: 'B'}),
objectContaining({x: 0, y: 11, w: 1, h: 1, id: 'C'})
]);
});
it('Calculates the correct collision when moving large object far', () => {
const layout = [
{x: 0, y: 0, w: 1, h: 10, id: 'A'},
{x: 0, y: 10, w: 1, h: 1, id: 'B'},
{x: 0, y: 11, w: 1, h: 1, id: 'C'}
];
// Move A down by 2. This should move B above, but since we don't compact in between,
// C should move below.
const itemA = layout[0];
expect(
moveElement(
layout,
itemA,
0,
2, // x, y
true,
false, // isUserAction, preventCollision
'vertical',
10 // compactType, cols
)
).toEqual([
objectContaining({x: 0, y: 2, w: 1, h: 10, id: 'A'}),
objectContaining({x: 0, y: 1, w: 1, h: 1, id: 'B'}),
objectContaining({x: 0, y: 12, w: 1, h: 1, id: 'C'})
]);
});
it('Moves elements out of the way without causing panel jumps when compaction is vertical (example case 13)', () => {
const layout = [
{x: 0, y: 0, w: 1, h: 1, id: 'A'},
{x: 1, y: 0, w: 1, h: 1, id: 'B'},
{x: 0, y: 1, w: 2, h: 2, id: 'C'}
];
// move A over slightly so it collides with B; can cause C to jump above B
// this test will check that that does not happen
const itemA = layout[0];
expect(
moveElement(
layout,
itemA,
1,
0, // x, y
true,
false, // isUserAction, preventCollision
'vertical',
2 // compactType, cols
)
).toEqual([
{x: 1, y: 0, w: 1, h: 1, id: 'A', moved: true},
{x: 1, y: 1, w: 1, h: 1, id: 'B', moved: true},
{x: 0, y: 2, w: 2, h: 2, id: 'C', moved: true}
]);
});
it('Moves elements out of the way without causing panel jumps when compaction is horizontal', () => {
const layout = [
{y: 0, x: 0, h: 1, w: 10, id: 'A'},
{y: 0, x: 11, h: 1, w: 1, id: 'B'},
{y: 0, x: 12, h: 1, w: 1, id: 'C'}
];
// move A over slightly so it collides with C; can cause C to jump left of B
// this test will check that that does not happen
const itemA = layout[0];
expect(
moveElement(
layout,
itemA,
2,
0, // x, y
true,
false, // isUserAction, preventCollision
'horizontal',
10 // compactType, cols
)
).toEqual([
{y: 0, x: 2, h: 1, w: 10, moved: true, id: 'A'},
{y: 0, x: 1, h: 1, w: 1, moved: true, id: 'B'},
{y: 0, x: 12, h: 1, w: 1, id: 'C'}
]);
});
it('Moves one element to another should cause moving down panels, vert compact, example 1', () => {
// | A | B |
// |C| D |
const layout = [
{x: 0, y: 0, w: 2, h: 1, id: 'A'},
{x: 2, y: 0, w: 2, h: 1, id: 'B'},
{x: 0, y: 1, w: 1, h: 1, id: 'C'},
{x: 1, y: 1, w: 3, h: 1, id: 'D'}
];
// move B left slightly so it collides with A; can cause C to jump above A
// this test will check that that does not happen
const itemB = layout[1];
expect(
compactAndMove(
layout,
itemB,
1,
0, // x, y
true,
false, // isUserAction, preventCollision
'vertical',
4 // compactType, cols
)
).toEqual([
objectContaining({x: 0, y: 1, w: 2, h: 1, id: 'A'}),
objectContaining({x: 1, y: 0, w: 2, h: 1, id: 'B'}),
objectContaining({x: 0, y: 2, w: 1, h: 1, id: 'C'}),
objectContaining({x: 1, y: 2, w: 3, h: 1, id: 'D'})
]);
});
it('Moves one element to another should cause moving down panels, vert compact, example 2', () => {
// | A |
// |B|C|
// | |
//
// Moving C above A should not move B above A
const layout = [
{x: 0, y: 0, w: 2, h: 1, id: 'A'},
{x: 0, y: 1, w: 1, h: 1, id: 'B'},
{x: 1, y: 1, w: 1, h: 2, id: 'C'}
];
// Move C up.
const itemB = layout[2];
expect(
compactAndMove(
layout,
itemB,
1,
0, // x, y
true,
false, // isUserAction, preventCollision
'vertical',
4 // compactType, cols
)
).toEqual([
objectContaining({x: 0, y: 2, w: 2, h: 1, id: 'A'}),
objectContaining({x: 0, y: 3, w: 1, h: 1, id: 'B'}),
objectContaining({x: 1, y: 0, w: 1, h: 2, id: 'C'})
]);
});
});
describe('compact vertical', () => {
it('Removes empty vertical space above item', () => {
const layout = [{id: '1', x: 0, y: 1, w: 1, h: 1}];
expect(compact(layout, 'vertical', 10)).toEqual([
{id: '1', x: 0, y: 0, w: 1, h: 1, moved: false, static: false}
]);
});
it('Resolve collision by moving item further down in array', () => {
const layout = [
{x: 0, y: 0, w: 1, h: 5, id: '1'},
{x: 0, y: 1, w: 1, h: 1, id: '2'}
];
expect(compact(layout, 'vertical', 10)).toEqual([
{x: 0, y: 0, w: 1, h: 5, id: '1', moved: false, static: false},
{x: 0, y: 5, w: 1, h: 1, id: '2', moved: false, static: false}
]);
});
it('Handles recursive collision by moving new collisions out of the way before moving item down', () => {
const layout = [
{x: 0, y: 0, w: 2, h: 5, id: '1'},
{x: 0, y: 0, w: 10, h: 1, id: '2'},
{x: 5, y: 1, w: 1, h: 1, id: '3'},
{x: 5, y: 2, w: 1, h: 1, id: '4'},
{x: 5, y: 3, w: 1, h: 1, id: '5', static: true}
];
expect(compact(layout, 'vertical', 10)).toEqual([
{x: 0, y: 0, w: 2, h: 5, id: '1', moved: false, static: false},
{x: 0, y: 5, w: 10, h: 1, id: '2', moved: false, static: false},
{x: 5, y: 6, w: 1, h: 1, id: '3', moved: false, static: false},
{x: 5, y: 7, w: 1, h: 1, id: '4', moved: false, static: false},
{x: 5, y: 3, w: 1, h: 1, id: '5', moved: false, static: true}
]);
});
it('Clones layout items (does not modify input)', () => {
const layout = [
{x: 0, y: 0, w: 2, h: 5, id: '1'},
{x: 0, y: 0, w: 10, h: 1, id: '2'}
];
const out = compact(layout, 'vertical', 10);
layout.forEach(item => {
expect(out.includes(item)).toEqual(false);
});
});
});
describe('compact horizontal', () => {
it('compact horizontal should remove empty horizontal space to left of item', () => {
const layout = [{x: 5, y: 5, w: 1, h: 1, id: '1'}];
expect(compact(layout, 'horizontal', 10)).toEqual([
{x: 0, y: 0, w: 1, h: 1, id: '1', moved: false, static: false}
]);
});
it('Resolve collision by moving item further to the right in array', () => {
const layout = [
{y: 0, x: 0, h: 1, w: 5, id: '1'},
{y: 0, x: 1, h: 1, w: 1, id: '2'}
];
expect(compact(layout, 'horizontal', 10)).toEqual([
{y: 0, x: 0, h: 1, w: 5, id: '1', moved: false, static: false},
{y: 0, x: 5, h: 1, w: 1, id: '2', moved: false, static: false}
]);
});
it('Handles recursive collision by moving new collisions out of the way before moving item to the right', () => {
const layout = [
{y: 0, x: 0, h: 2, w: 5, id: '1'},
{y: 1, x: 0, h: 10, w: 1, id: '2'},
{y: 5, x: 1, h: 1, w: 1, id: '3'},
{y: 5, x: 2, h: 1, w: 1, id: '4'},
{y: 5, x: 2, h: 1, w: 1, id: '5', static: true}
];
expect(compact(layout, 'horizontal', 10)).toEqual([
{y: 0, x: 0, h: 2, w: 5, id: '1', moved: false, static: false},
{y: 1, x: 5, h: 10, w: 1, id: '2', moved: false, static: false},
{y: 5, x: 6, h: 1, w: 1, id: '3', moved: false, static: false},
{y: 5, x: 7, h: 1, w: 1, id: '4', moved: false, static: false},
{y: 5, x: 2, h: 1, w: 1, id: '5', moved: false, static: true}
]);
});
}); | the_stack |
import BaseController from '~/src/controller/api/base'
import { Request } from 'express'
import { JsonController, Req, Get, Post, UseBefore } from 'routing-controllers'
import LoginMiddleware from '~/src/middleware/login'
import MPageRecord, { TypePageRecord } from '~/src/model/page/record'
import MPagePublishHistory from '~/src/model/page/publish_history'
import MPageDraft from '~/src/model/page/draft'
import MProject, { TypeProject } from '~/src/model/project'
import env from '~/src/config/env'
import _ from 'lodash'
import Knex from '~/src/library/mysql'
@JsonController()
@UseBefore(LoginMiddleware)
class PageController extends BaseController {
// 增
@Post('/api/page/record/create')
async create(@Req() request: Request) {
const userInfo = await this.asyncGetUserInfo(request)
const create_ucid = `${userInfo.id}`
const create_user_name = userInfo.name
// 创建页面时额外接收content参数, 作为草稿页的初始值
let { path, name, projectId, content = '' } = request.body
// path, name 支持从content中获取, 方便导入页面配置
if (!path) {
let pageConfig = {}
try {
pageConfig = JSON.parse(content)
} catch (e) {
return this.showError(`content=>${content}不合法:${e.message}`)
}
path = _.get(pageConfig, 'route', path)
name = _.get(pageConfig, 'title', name)
}
if (_.isUndefined(name)) {
return this.showError(`name=>${name}不能为空`)
}
if (_.isUndefined(projectId)) {
return this.showError(`projectId=>${projectId}不能为空`)
}
// @todo(yaozeyuan) 具体路径需要和元元确认一下
if (/^\/project\/[\d_\w]+/.test(path) === false) {
return this.showError(`path=>${path}路径不规范, path必须以/project/{项目代号}开头`)
}
// 检查path是否存在
let isExist = await MPageRecord.asyncGetId(path)
if (isExist > 0) {
return this.showError(`路径${path}已存在`)
}
let pageId = await MPageRecord.asyncCreate(path, name, projectId, create_ucid, create_user_name)
if (pageId <= 0) {
return this.showError(`记录创建失败, 请重试`)
}
// 创建草稿
let draftId = await MPageDraft.asyncCreate(pageId, content, create_ucid, create_user_name)
return this.showResult(
{
path,
pageId,
draftId,
},
`创建成功`,
)
}
// 删
@Post('/api/page/record/delete')
async delete(@Req() request: Request) {
const userInfo = await this.asyncGetUserInfo(request)
let { pageId, projectId } = request.body
if (!pageId) {
return this.showError('页面pageId不能为空')
}
let page = await MPageRecord.asyncGet(pageId)
if (_.isEmpty(page)) {
return this.showResult(`${pageId}对应页面不存在`)
}
const hasPermission = await MProject.hasPermission(`${userInfo.id}`, projectId)
if (!hasPermission) {
return this.showError(`您无权删除该页面`)
}
// 删除历史记录
let removePublishHistoryRowCount = await MPagePublishHistory.asyncDeleteByPageId(pageId)
// 删除所有草稿
let removeDraftRowCount = await MPageDraft.asyncDeleteByPageId(pageId)
// 删除页面记录
let removePageRowCount = await MPageRecord.asyncDelete(pageId)
if (removePageRowCount) {
return this.showResult(
{
removePublishHistoryRowCount,
removeDraftRowCount,
removePageRowCount,
},
'删除页面成功',
)
} else {
return this.showError(`删除页面失败`, {
removePublishHistoryRowCount,
removeDraftRowCount,
removePageRowCount,
})
}
}
// 查
@Get('/api/page/record/get')
async get(@Req() request: Request) {
let { path = '', draftId } = request.query as any //获取路径
let pageId = await MPageRecord.asyncGetId(path)
if (pageId === 0) {
return this.showError(`页面${path}不存在`)
}
let page = await MPageRecord.asyncGet(pageId)
let draft
if (draftId) {
draft = await MPageDraft.asyncGetByPageId(pageId, draftId)
if (_.isEmpty(draft)) {
return this.showError(`页面${path}指定对应的${draftId}不存在`)
}
} else {
draftId = await MPagePublishHistory.asyncGetPublishDraftId(env, pageId)
if (draftId === 0) {
return this.showError(`页面${path}在${env}环境中的发布记录不存在`)
}
draft = await MPageDraft.asyncGet(draftId)
}
if (_.isEmpty(draft)) {
return this.showError(`页面${path}在${env}环境中对应的配置内容不存在`)
}
const project_id = page.project_id
// 获取页面对应的项目
const project = await MProject.asyncGetByProjectId(project_id as number)
if (!project.id) {
return this.showError(`页面${path}对应的项目不存在:project_id=${project_id}`)
}
return this.showResult({
page,
draft,
})
}
@Get('/api/page/record/get_list')
async list(@Req() request: Request) {
const { projectId, name, path, pageSize = 100, pageNum = 1, createUcid } = request.query as any
let requestParamsTip = `projectId=>${projectId}`
if (_.isUndefined(projectId)) {
return this.showError(`projectId不能为空=>${requestParamsTip}`)
}
const userInfo = await this.asyncGetUserInfo(request)
const actor_ucid = `${userInfo.id}`
const hasPermission = await MProject.hasPermission(actor_ucid, projectId)
if (!hasPermission) {
return this.showError(`抱歉, 您无权访问该项目`, {}, 403)
}
let totalCount = await MPageRecord.asyncGetListCount(projectId, { name, path, createUcid })
let rawRecordList = await MPageRecord.asyncGetList(projectId, pageNum, pageSize, { name, path, createUcid })
let recordList: Array<TypePageRecord | { content: string }> = []
for (let rawRecord of rawRecordList) {
let content = ''
let pageId = rawRecord.id as number
let draftId = await MPagePublishHistory.asyncGetPublishDraftId(env, pageId)
let draft = await MPageDraft.asyncGetByPageId(pageId)
const page_draft_id_latest = _.get(draft, 'id')
let is_latest = draftId === page_draft_id_latest
if (draftId) {
// 避免发布记录不存在
let draft = await MPageDraft.asyncGet(draftId)
content = _.get(draft, ['content'], '') as string
}
let record = {
...rawRecord,
content: content,
is_latest,
page_draft_id: draftId,
page_draft_id_latest,
create_at: _.isNumber(rawRecord.create_at) && rawRecord.create_at * 1000,
update_at: _.isNumber(rawRecord.update_at) && rawRecord.update_at * 1000,
}
recordList.push(record)
}
return this.showResult({
total: totalCount,
pageNum,
pageSize,
list: recordList,
})
}
@Get('/api/v2/page/record/list')
async listV2(@Req() request: Request) {
const { project_id, content, pageSize = 50, pageNum = 1 } = request.query as any
let offset = (pageNum - 1) * pageSize
offset = offset < 0 ? 0 : offset
if (!project_id) {
return this.showError(`缺少参数project_id`)
}
if (project_id === 'unknow') {
// 无主项目
const projects = await Knex.queryBuilder().select('*').from('project_new')
const project_ids: string[] = projects.map((v: any) => v.id)
const pages = await Knex.queryBuilder().select('*').from('page_record').whereNotIn('project_id', project_ids)
return this.showResult({
list: pages,
total: pages.length,
})
}
if (project_id === 'all') {
const projects = await Knex.queryBuilder().select('*').from('project_new')
const project_ids: string[] = projects.map((v: any) => v.id)
const pages: any[] = await Knex.queryBuilder()
.select('*')
.from('page_record')
.whereIn('project_id', project_ids)
.offset(offset)
.limit(pageSize)
const item = await Knex.queryBuilder()
.select('*')
.from('page_record')
.whereIn('project_id', project_ids)
.count({ total: '*' })
const total = _.get(item, [0, 'total'], 0)
let results = []
for (let i = 0; i < pages.length; i++) {
let page = pages[i]
const page_draft = await Knex.queryBuilder()
.select('*')
.from('page_draft')
.where('page_id', page.id)
.orderBy('id', 'desc')
.first()
if (!page_draft) {
continue
}
let isMatch = true
if (content) {
isMatch = page_draft.content.indexOf(content) !== -1
}
if (isMatch) {
results.push(page)
}
}
return this.showResult({
list: results,
total,
})
}
}
@Post('/api/page/record/batch_publish')
async batchPublish(@Req() request: Request) {
const { projectId, pageIdList, releaseNote = '批量发布', env } = request.body
let userInfo = await this.asyncGetUserInfo(request)
let requestParamsTip = `projectId=>${projectId},pageIdList=>${pageIdList},releaseNote=>${releaseNote},env=>${env}`
if (_.isUndefined(projectId) || _.isUndefined(pageIdList) || _.isUndefined(releaseNote) || _.isUndefined(env)) {
return this.showError(`projectId/pageIdList/releaseNote/env不能为空=>${requestParamsTip}`)
}
const actor_ucid = `${userInfo.id}`
const actor_user_name = userInfo.name
const hasPermission = await MProject.hasPermission(actor_ucid, projectId)
if (!hasPermission) {
return this.showError(`抱歉, 您没有权限发布页面`)
}
let publishFailedList = []
let publishSuccessList = []
let _pageIdList = pageIdList.split(',')
// 批量发布
for (let pageId of _pageIdList) {
let page = await MPageRecord.asyncGet(pageId)
if (_.isEmpty(page)) {
publishFailedList.push({
pageId,
projectId,
page,
reason: 'pageId不存在',
})
continue
}
if (page.project_id != projectId) {
publishFailedList.push({
pageId,
projectId,
page,
reason: `pageId${pageId}不属于项目=>${projectId}`,
})
continue
}
let draft = await MPageDraft.asyncGetByPageId(pageId)
let draftId = _.get(draft, ['id'], 0)
if (draftId === 0) {
publishFailedList.push({
pageId,
projectId,
page,
reason: `pageId${pageId}没有对应的草稿记录`,
})
continue
}
let publishHistoryId = await MPagePublishHistory.asyncCreatePublishHistory(
env,
pageId,
draftId,
releaseNote,
actor_ucid,
actor_user_name,
)
if (publishHistoryId === 0) {
publishFailedList.push({
pageId,
projectId,
page,
reason: `pageId${pageId}发布记录创建失败`,
})
continue
}
publishSuccessList.push({
pageId,
projectId,
page,
reason: `pageId${pageId}在${env}环境下发布成功`,
})
}
let message = `共提交了${_.get(_pageIdList, ['length'], 0)}条记录, 发布成功${
publishSuccessList.length
}条, 发布失败${publishFailedList.length}条`
return this.showResult(
{
publishSuccessList,
publishFailedList,
},
message,
)
}
}
export default PageController | the_stack |
declare var PolyBool:any;
module labelling_tool {
/*
Polygonal label model
*/
interface PolygonalLabelModel extends AbstractLabelModel {
regions: Vector2[][];
}
export function new_PolygonalLabelModel(label_class: string, source: string): PolygonalLabelModel {
return {label_type: 'polygon', label_class: label_class, source: source, anno_data: {}, regions: []};
}
let shape_line: any = d3.svg.line()
.x(function (d: any) { return d.x; })
.y(function (d: any) { return d.y; })
.interpolate("linear-closed");
function multi_path(regions: Vector2[][]) {
let lines: string[] = [];
for (var i = 0; i < regions.length; i++) {
lines.push(shape_line(regions[i]));
}
return lines.join(' ');
}
function convert_model(model: PolygonalLabelModel): PolygonalLabelModel {
let m: any = model as any;
if (m.hasOwnProperty('vertices')) {
m.regions = [m.vertices];
delete m.vertices;
}
return m as PolygonalLabelModel;
}
/*
Polygonal label entity
*/
export class PolygonalLabelEntity extends AbstractLabelEntity<PolygonalLabelModel> {
_polyk_polys: number[][];
_centroid: Vector2;
_bounding_box: AABox;
poly: any;
constructor(view: RootLabelView, model: PolygonalLabelModel) {
model = convert_model(model);
super(view, model);
this._polyk_polys = [];
this._centroid = null;
this._bounding_box = null;
this.poly = null;
}
attach() {
super.attach();
let self = this;
// let paths = this.root_view.world.append("g").selectAll("path").data(this.model.polys).join("path");
// paths.attr("d", function(d: SinglePolyLabel) {self.shape_line(d.vertices)});
this.poly = this.root_view.world.append("path")
.attr("class", "anno_label")
.attr('fill-rule', 'evenodd');
this.poly.data(this.model.regions).attr("d", multi_path(this.model.regions));
this.poly.on("mouseover", () => {
for (var i = 0; i < this._event_listeners.length; i++) {
this._event_listeners[i].on_mouse_in(this);
}
});
this.poly.on("mouseout", () => {
for (var i = 0; i < this._event_listeners.length; i++) {
this._event_listeners[i].on_mouse_out(this);
}
});
this._update_polyk_polys();
this._update_style();
};
detach() {
this.poly.remove();
this.poly = null;
this._polyk_polys = [];
super.detach();
};
_update_polyk_polys() {
this._polyk_polys = [];
for (var region_i = 0; region_i < this.model.regions.length; region_i++) {
let region = this.model.regions[region_i];
let pkpoly: number[] = [];
for (var vert_i = 0; vert_i < region.length; vert_i++) {
pkpoly.push(region[vert_i].x);
pkpoly.push(region[vert_i].y);
}
this._polyk_polys.push(pkpoly);
}
}
update() {
let self = this;
this.poly.data(this.model.regions).attr("d", multi_path(this.model.regions));
this._update_polyk_polys();
this._centroid = null;
this._bounding_box = null;
this._update_style();
}
commit() {
this.root_view.commit_model(this.model);
}
_update_style() {
if (this._attached) {
var vis: LabelVisibility = this.get_visibility();
if (vis == LabelVisibility.HIDDEN) {
this.poly.attr("visibility", "hidden");
}
else {
var stroke_and_fill = this._get_stroke_and_fill_colour();
var stroke_colour = stroke_and_fill[0];
var fill_colour = stroke_and_fill[1];
this.poly.attr("style", "fill:" + fill_colour.to_rgba_string() + ";stroke:" + stroke_colour.to_rgba_string() + ";stroke-width:1")
.attr("visibility", "visible");
}
}
}
_get_stroke_and_fill_colour(): Colour4[] {
var vis: LabelVisibility = this.get_visibility();
var stroke_colour: Colour4 = this._outline_colour();
var fill_colour: Colour4 = this.root_view.view.colour_for_label_class(this.model.label_class);
if (vis == LabelVisibility.FAINT) {
stroke_colour = stroke_colour.with_alpha(0.2);
if (this._hover) {
fill_colour = fill_colour.lighten(0.4);
}
if (this._selected) {
fill_colour = fill_colour.lerp(new Colour4(255, 128, 0.0, 1.0), 0.2);
}
fill_colour = fill_colour.with_alpha(0.1);
}
else if (vis == LabelVisibility.FULL) {
if (this._hover) {
fill_colour = fill_colour.lighten(0.4);
}
if (this._selected) {
fill_colour = fill_colour.lerp(new Colour4(255, 128, 0.0, 1.0), 0.2);
}
fill_colour = fill_colour.with_alpha(0.35);
}
return [stroke_colour, fill_colour];
}
compute_centroid(): Vector2 {
if (this._centroid === null) {
let centroids: Vector2[] = [];
for (var region_i = 0; region_i < this.model.regions.length; region_i++) {
centroids.push(mean_of_points(this.model.regions[region_i]));
}
this._centroid = mean_of_points(centroids);
}
return this._centroid;
}
compute_bounding_box(): AABox {
if (this._bounding_box === null) {
let boxes: AABox[] = [];
for (var region_i = 0; region_i < this.model.regions.length; region_i++) {
boxes.push(AABox_from_points(this.model.regions[region_i]));
}
this._bounding_box = AABox_from_aaboxes(boxes);
}
return this._bounding_box;
}
contains_pointer_position(point: Vector2): boolean {
if (this.compute_bounding_box().contains_point(point)) {
let contain_count: number = 0;
for (var region_i = 0; region_i < this._polyk_polys.length; region_i++) {
if (PolyK.ContainsPoint(this._polyk_polys[region_i], point.x, point.y)) {
contain_count += 1;
}
}
return (contain_count % 2) == 1;
}
else {
return false;
}
}
distance_to_point(point: Vector2): number {
let contain_count: number = 0;
for (var region_i = 0; region_i < this._polyk_polys.length; region_i++) {
if (PolyK.ContainsPoint(this._polyk_polys[region_i], point.x, point.y)) {
contain_count += 1;
}
}
if ((contain_count % 2) == 1) {
return 0.0;
}
var e = PolyK.ClosestEdge(this._polyk_polys[0], point.x, point.y);
let dist: number = e.dist;
for (var region_i = 1; region_i < this._polyk_polys.length; region_i++) {
var e = PolyK.ClosestEdge(this._polyk_polys[region_i], point.x, point.y);
if (e.dist < dist) {
dist = e.dist;
}
}
return dist;
}
/*
Create group label
*/
static merge_polygonal_labels(root_view: RootLabelView) {
let selection: AbstractLabelEntity<AbstractLabelModel>[] = root_view.get_selection().slice();
root_view.unselect_all_entities();
if (selection.length > 1) {
// Can only merge if all entities are polygonal labels
// Also compute a class frequency table
let can_merge: boolean = true;
var class_freq: { [class_name: string]: number; } = {};
for (var i = 0; i < selection.length; i++) {
if (selection[i] instanceof PolygonalLabelEntity) {
// Get the class of the component
var component_class = selection[i].model.label_class;
if (component_class in class_freq) {
class_freq[component_class] += 1;
}
else {
class_freq[component_class] = 1;
}
}
else {
can_merge = false;
break;
}
}
if (can_merge) {
// Choose the label class with the highest frequency
let best_class: string = null;
var best_freq = 0;
for (let cls in class_freq) {
if (class_freq[cls] > best_freq) {
best_class = cls;
best_freq = class_freq[cls];
}
}
let merged_pb = null;
for (var i = 0; i < selection.length; i++) {
let poly_entity: PolygonalLabelEntity = selection[i] as PolygonalLabelEntity;
let entity_pb = EditPolyTool._model_regions_to_polybool(poly_entity.model.regions);
if (merged_pb === null) {
merged_pb = entity_pb;
} else {
merged_pb = PolyBool.union(merged_pb, entity_pb);
}
}
var merged_model = new_PolygonalLabelModel(best_class, "manual");
merged_model.regions = EditPolyTool._polybool_to_model(merged_pb);
for (var i = 0; i < selection.length; i++) {
var entity = selection[i];
entity.destroy();
}
var merged_entity = root_view.get_or_create_entity_for_model(merged_model);
root_view.add_child(merged_entity);
return merged_entity;
}
}
return null;
}
}
register_entity_factory('polygon', (root_view: RootLabelView, model: AbstractLabelModel) => {
return new PolygonalLabelEntity(root_view, model as PolygonalLabelModel);
});
enum BooleanMode {
NEW,
ADD,
SUBTRACT,
SPLIT,
}
export class EditPolyTool extends ProxyTool {
entity: PolygonalLabelEntity;
draw_poly_tool: DrawSinglePolygonTool;
draw_brush_tool: DrawBrushTool;
ui: JQuery;
ui_radio_boolean_new: JQuery;
ui_radio_boolean_add: JQuery;
ui_radio_boolean_sub: JQuery;
ui_radio_boolean_split: JQuery;
ui_radio_draw_poly: JQuery;
ui_radio_draw_brush: JQuery;
boolean_mode: BooleanMode;
constructor(view: RootLabelView, entity: PolygonalLabelEntity) {
super(view, null);
var self = this;
this.entity = entity;
this.boolean_mode = BooleanMode.NEW;
this.draw_poly_tool = new DrawSinglePolygonTool(view, entity, self);
this.draw_brush_tool = new DrawBrushTool(view, entity, self);
}
on_init() {
super.on_init();
let self = this;
this.ui = $('.tool_edit_multi_poly');
this.ui.removeClass('anno_hidden');
this.ui_radio_boolean_new = this.ui.find('#multi_poly_boolean_new');
this.ui_radio_boolean_add = this.ui.find('#multi_poly_boolean_add');
this.ui_radio_boolean_sub = this.ui.find('#multi_poly_boolean_subtract');
this.ui_radio_boolean_split = this.ui.find('#multi_poly_boolean_split');
this.ui_radio_boolean_new.on('change', function(event: any, ui: any) {
if (event.target.checked) {
self.change_boolean_mode(BooleanMode.NEW);
}
});
this.ui_radio_boolean_add.on('change', function(event: any, ui: any) {
if (event.target.checked) {
self.change_boolean_mode(BooleanMode.ADD);
}
});
this.ui_radio_boolean_sub.on('change', function(event: any, ui: any) {
if (event.target.checked) {
self.change_boolean_mode(BooleanMode.SUBTRACT);
}
});
this.ui_radio_boolean_split.on('change', function(event: any, ui: any) {
if (event.target.checked) {
self.change_boolean_mode(BooleanMode.SPLIT);
}
});
// Read existing state
if (this.ui_radio_boolean_new.parent().hasClass('active')) {
self.change_boolean_mode(BooleanMode.NEW);
}
else if (this.ui_radio_boolean_add.parent().hasClass('active')) {
self.change_boolean_mode(BooleanMode.ADD);
}
else if (this.ui_radio_boolean_sub.parent().hasClass('active')) {
self.change_boolean_mode(BooleanMode.SUBTRACT);
}
else if (this.ui_radio_boolean_split.parent().hasClass('active')) {
self.change_boolean_mode(BooleanMode.NEW);
self.ui_radio_boolean_split.closest('label.btn').removeClass('active');
self.ui_radio_boolean_new.closest('label.btn').addClass('active');
}
this.ui_radio_draw_poly = this.ui.find('#multi_poly_draw_poly');
this.ui_radio_draw_brush = this.ui.find('#multi_poly_draw_brush');
this.ui_radio_draw_poly.on('change', function(event: any, ui: any) {
if (event.target.checked) {
self.draw_mode_poly();
}
});
this.ui_radio_draw_brush.on('change', function(event: any, ui: any) {
if (event.target.checked) {
self.draw_mode_brush();
}
});
// Read existing state
if (this.ui_radio_draw_poly.parent().hasClass('active')) {
self.draw_mode_poly();
}
else if (this.ui_radio_draw_brush.parent().hasClass('active')) {
self.draw_mode_brush();
}
}
on_shutdown() {
super.on_init();
this.ui.addClass('anno_hidden');
this.ui_radio_boolean_new.off('change');
this.ui_radio_boolean_add.off('change');
this.ui_radio_boolean_sub.off('change');
this.ui_radio_boolean_split.off('change');
this.ui_radio_draw_poly.off('change');
this.ui_radio_draw_brush.off('change');
}
on_cancel(pos: Vector2): boolean {
if (super.on_cancel(pos)) {
return true;
}
if (this.entity !== null) {
this.entity.commit();
this.entity = null;
}
else {
this._view.unselect_all_entities();
this._view.view.set_current_tool(new SelectEntityTool(this._view));
}
return true;
};
on_key_down(event: any): boolean {
if (super.on_key_down(event)) {
return true;
}
var handled = false;
var key: string = event.key;
if (key === '/') {
// Cycle between new, add and subtract; do not enter split mode
// The use should choose split explicitly
if (this.boolean_mode === BooleanMode.NEW) {
this.change_boolean_mode(BooleanMode.ADD);
this.ui_radio_boolean_add.closest('div.btn-group').find('label.btn').removeClass('active');
this.ui_radio_boolean_add.closest('label.btn').addClass('active');
}
else if (this.boolean_mode === BooleanMode.ADD) {
this.change_boolean_mode(BooleanMode.SUBTRACT);
this.ui_radio_boolean_sub.closest('div.btn-group').find('label.btn').removeClass('active');
this.ui_radio_boolean_sub.closest('label.btn').addClass('active');
}
else if (this.boolean_mode === BooleanMode.SUBTRACT || this.boolean_mode === BooleanMode.SPLIT) {
this.change_boolean_mode(BooleanMode.NEW);
this.ui_radio_boolean_new.closest('div.btn-group').find('label.btn').removeClass('active');
this.ui_radio_boolean_new.closest('label.btn').addClass('active');
}
else {
throw "Unknown boolean mode= " + this.boolean_mode;
}
handled = true;
}
else if (event.key === ',') {
if (this.underlying_tool === this.draw_poly_tool) {
this.set_underlying_tool(this.draw_brush_tool);
this.ui_radio_draw_brush.closest('div.btn-group').find('label.btn').removeClass('active');
this.ui_radio_draw_brush.closest('label.btn').addClass('active');
}
else if (this.underlying_tool === this.draw_brush_tool) {
this.set_underlying_tool(this.draw_poly_tool);
this.ui_radio_draw_poly.closest('div.btn-group').find('label.btn').removeClass('active');
this.ui_radio_draw_poly.closest('label.btn').addClass('active');
}
else {
throw "Unknown boolean mode= " + this.boolean_mode;
}
handled = true;
}
return handled;
};
notify_entity_deleted(entity: labelling_tool.AbstractLabelEntity<labelling_tool.AbstractLabelModel>) {
this.draw_poly_tool.notify_entity_deleted(entity);
this.draw_brush_tool.notify_entity_deleted(entity);
if (entity === this.entity) {
this.entity = null;
}
super.notify_entity_deleted(entity);
}
change_boolean_mode(mode: BooleanMode) {
this.boolean_mode = mode;
this.draw_poly_tool._update_style();
this.draw_brush_tool._update_style();
}
draw_mode_poly() {
this.set_underlying_tool(this.draw_poly_tool);
}
draw_mode_brush() {
this.set_underlying_tool(this.draw_brush_tool);
}
static _model_regions_to_polybool(regions: Vector2[][]): any {
let pb_regions: number[][][] = [];
for (var reg_i = 0; reg_i < regions.length; reg_i++) {
let region: Vector2[] = regions[reg_i];
let pb_verts: number [][] = [];
for (var i = 0; i < region.length; i++) {
pb_verts.push([region[i].x, region[i].y]);
}
pb_regions.push(pb_verts);
}
return {'regions': pb_regions, 'inverted': false};
}
static _polybool_to_model(p: any): Vector2[][] {
let regions: Vector2[][] = [];
for (var region_i = 0; region_i < p.regions.length; region_i++) {
let pb_region = p.regions[region_i];
let verts: Vector2[] = [];
for (var vert_i = 0; vert_i < pb_region.length; vert_i++) {
verts.push({x: pb_region[vert_i][0], y: pb_region[vert_i][1]});
}
regions.push(verts);
}
return regions;
}
create_entity() {
var label_class = this._view.view.get_label_class_for_new_label();
var model = new_PolygonalLabelModel(label_class, "manual");
var entity = this._view.get_or_create_entity_for_model(model);
this.entity = entity;
this._view.add_child(entity);
this._view.select_entity(entity, false, false);
};
notify_draw(regions: Vector2[][]) {
if (this.entity === null || this.boolean_mode === BooleanMode.NEW) {
// Create a new label if we are in an appropriate mode
if (this.boolean_mode === BooleanMode.NEW || this.boolean_mode === BooleanMode.ADD) {
this.create_entity();
this.entity.model.regions = regions;
this.entity.model.source = "manual";
this.entity.update();
}
}
else {
let existing_pb = EditPolyTool._model_regions_to_polybool(this.entity.model.regions);
let new_pb = EditPolyTool._model_regions_to_polybool(regions);
if (this.boolean_mode === BooleanMode.ADD) {
let composite_pb = PolyBool.union(existing_pb, new_pb);
this.entity.model.regions = EditPolyTool._polybool_to_model(composite_pb);
this.entity.model.source = "manual";
this.entity.commit();
this.entity.update();
}
else if (this.boolean_mode === BooleanMode.SUBTRACT) {
let composite_pb = PolyBool.difference(existing_pb, new_pb);
if (composite_pb.regions.length === 0) {
// There's nothing left...
this.entity.destroy();
this.entity = null;
}
else {
this.entity.model.regions = EditPolyTool._polybool_to_model(composite_pb);
this.entity.model.source = "manual";
this.entity.commit();
this.entity.update();
}
}
else if (this.boolean_mode === BooleanMode.SPLIT) {
let remaining_pb = PolyBool.difference(existing_pb, new_pb);
let split_pb = PolyBool.intersect(existing_pb, new_pb);
// Only split into two labels if:
// there are regions on *both* sides of the split, otherwise we are either
// leaving everything in the current/selected entity or we are splitting everything into
// a new entity.
if (remaining_pb.regions.length > 0 && split_pb.regions.length > 0) {
this.entity.model.regions = EditPolyTool._polybool_to_model(remaining_pb);
this.entity.model.source = "manual";
// No need to commit this entity as adding the new one below will send the changes
this.entity.update();
var split_model = new_PolygonalLabelModel(this.entity.model.label_class, "manual");
split_model.regions = EditPolyTool._polybool_to_model(split_pb);
var split_entity = this._view.get_or_create_entity_for_model(split_model);
this._view.add_child(split_entity);
}
}
else {
// Default: Add
let composite_pb = PolyBool.union(existing_pb, new_pb);
this.entity.model.regions = EditPolyTool._polybool_to_model(composite_pb);
this.entity.model.source = "manual";
this.entity.commit();
this.entity.update();
}
}
}
}
/*
Draw polygon tool
*/
class DrawSinglePolygonTool extends AbstractTool {
edit_tool: EditPolyTool;
entity: PolygonalLabelEntity;
vertices: Vector2[];
poly: any;
_last_vertex_marker: any;
_last_vertex_marker_visible: boolean;
constructor(view: RootLabelView, entity: PolygonalLabelEntity, edit_tool: EditPolyTool) {
super(view);
var self = this;
this.edit_tool = edit_tool;
this.entity = entity;
this.vertices = [];
this.poly = null;
this._last_vertex_marker = null;
this._last_vertex_marker_visible = false;
}
_create_poly() {
this.poly = this._view.world.append("path")
.attr("class", "anno_label");
this.poly.data(this.vertices).attr("d", shape_line(this.vertices));
this._update_style();
}
_update_style() {
if (this.poly !== null) {
let marker_colour: Colour4 = null;
let stroke_colour: Colour4 = null;
let fill_colour: Colour4 = null;
if (this.edit_tool.boolean_mode == BooleanMode.NEW) {
marker_colour = new Colour4(64, 160, 255, 1.0);
stroke_colour = new Colour4(0, 128, 255, 1.0);
fill_colour = new Colour4(64, 80, 96, 1.0);
} else if (this.edit_tool.boolean_mode == BooleanMode.ADD) {
marker_colour = new Colour4(64, 255, 80, 1.0);
stroke_colour = new Colour4(0, 255, 64, 1.0);
fill_colour = new Colour4(64, 96, 80, 1.0);
} else if (this.edit_tool.boolean_mode == BooleanMode.SUBTRACT) {
marker_colour = new Colour4(255, 64, 128, 1.0);
stroke_colour = new Colour4(255, 0, 128, 1.0);
fill_colour = new Colour4(96, 64, 80, 1.0);
} else if (this.edit_tool.boolean_mode == BooleanMode.SPLIT) {
marker_colour = new Colour4(255, 64, 255, 1.0);
stroke_colour = new Colour4(255, 0, 255, 1.0);
fill_colour = new Colour4(96, 64, 96, 1.0);
}
fill_colour = fill_colour.with_alpha(0.35);
if (this._last_vertex_marker !== null) {
this._last_vertex_marker.style("stroke", marker_colour.to_rgba_string());
}
this.poly.attr("style", "fill:" + fill_colour.to_rgba_string() + ";stroke:" + stroke_colour.to_rgba_string() + ";stroke-width:1")
.attr("visibility", "visible");
}
}
on_init() {
this._create_poly();
this._last_vertex_marker = this._view.world.append("circle");
this._last_vertex_marker.attr("r", "3.0");
this._last_vertex_marker.attr("visibility", "hidden");
this._last_vertex_marker.style("fill", "rgba(128,0,192,0.1)");
this._last_vertex_marker.style("stroke-width", "1.5");
this._last_vertex_marker.style("stroke", "rgba(0,128,255,1.0)");
this._last_vertex_marker_visible = false;
};
on_shutdown() {
this._last_vertex_marker.remove();
this._last_vertex_marker = null;
this.poly.remove();
this.poly = null;
};
on_switch_in(pos: Vector2) {
this.add_point(pos);
this._last_vertex_marker_visible = true;
};
on_switch_out(pos: Vector2) {
this._last_vertex_marker_visible = false;
this.remove_last_point();
};
on_cancel(pos: Vector2): boolean {
let handled = false;
this._last_vertex_marker_visible = false;
if (this.vertices.length > 0) {
this.remove_last_point();
if (this.vertices.length >= 3) {
this.edit_tool.notify_draw([this.vertices]);
}
handled = this.vertices.length > 0;
}
this.vertices = [];
this.add_point(pos);
this.poly.remove();
this._create_poly();
return handled;
};
on_left_click(pos: Vector2, event: any) {
this.add_point(pos);
};
on_move(pos: Vector2) {
this.update_last_point(pos);
};
on_drag(pos: Vector2, event: any) {
if (event.shiftKey) {
this.add_point(pos);
return true;
}
return false;
};
notify_entity_deleted(entity: labelling_tool.AbstractLabelEntity<labelling_tool.AbstractLabelModel>) {
if (entity === this.entity) {
this.entity = null;
this.vertices = [];
if (this.poly !== null) {
this.poly.remove();
}
this._create_poly();
}
super.notify_entity_deleted(entity);
}
update_poly() {
this.poly.data(this.vertices).attr("d", shape_line(this.vertices));
var last_vertex_pos: Vector2 = null;
if (this.vertices.length >= 1 && this._last_vertex_marker_visible) {
last_vertex_pos = this.vertices[this.vertices.length - 1];
}
this.show_last_vertex_at(last_vertex_pos);
};
show_last_vertex_at(pos: Vector2) {
if (pos === null) {
this._last_vertex_marker.attr("visibility", "hidden");
} else {
this._last_vertex_marker.attr("visibility", "visible");
this._last_vertex_marker.attr("cx", pos.x);
this._last_vertex_marker.attr("cy", pos.y);
}
}
add_point(pos: Vector2) {
this.vertices.push(pos);
this.update_poly();
};
update_last_point(pos: Vector2) {
this.vertices[this.vertices.length - 1] = pos;
this.update_poly();
};
remove_last_point() {
if (this.vertices.length > 0) {
this.vertices.splice(this.vertices.length - 1, 1);
this.update_poly();
}
};
}
/*
Draw brush tool
*/
class DrawBrushTool extends AbstractTool {
edit_tool: EditPolyTool;
entity: PolygonalLabelEntity;
regions: Vector2[][];
poly: any;
last_pos: Vector2;
_brush_radius: number;
_brush_circle: any;
_brush_segments: number;
constructor(view: RootLabelView, entity: PolygonalLabelEntity, edit_tool: EditPolyTool) {
super(view);
var self = this;
this.edit_tool = edit_tool;
this.entity = entity;
this.regions = [];
this.poly = null;
this.last_pos = null;
this._brush_radius = 10.0;
this._brush_circle = null;
this._brush_segments = 12;
}
_create_poly() {
this.poly = this._view.world.append("path")
.attr("class", "anno_label");
this.poly.data(this.regions).attr("d", multi_path(this.regions));
this._update_style();
}
_update_style() {
if (this.poly !== null) {
let stroke_colour: Colour4 = null;
let fill_colour: Colour4 = null;
let brush_fill_colour: Colour4 = null;
if (this.edit_tool.boolean_mode == BooleanMode.NEW) {
stroke_colour = new Colour4(0, 128, 255, 1.0);
fill_colour = new Colour4(64, 80, 96, 1.0);
} else if (this.edit_tool.boolean_mode == BooleanMode.ADD) {
stroke_colour = new Colour4(0, 255, 64, 1.0);
fill_colour = new Colour4(64, 96, 80, 1.0);
} else if (this.edit_tool.boolean_mode == BooleanMode.SUBTRACT) {
stroke_colour = new Colour4(255, 0, 128, 1.0);
fill_colour = new Colour4(96, 64, 80, 1.0);
} else if (this.edit_tool.boolean_mode == BooleanMode.SPLIT) {
stroke_colour = new Colour4(255, 0, 255, 1.0);
fill_colour = new Colour4(96, 64, 96, 1.0);
}
brush_fill_colour = fill_colour.with_alpha(0.05);
fill_colour = fill_colour.with_alpha(0.35);
this.poly.attr("style", "fill:" + fill_colour.to_rgba_string() + ";stroke:" + stroke_colour.to_rgba_string() + ";stroke-width:1")
.attr("visibility", "visible");
if (this._brush_circle !== null) {
this._brush_circle.attr("style", "fill:" + brush_fill_colour.to_rgba_string() + ";stroke:" + stroke_colour.to_rgba_string() + ";stroke-width:1");
}
}
}
on_init() {
this._brush_circle = this._view.world.append("circle");
this._brush_circle.attr("r", this._brush_radius);
this._brush_circle.attr("visibility", "hidden");
this._brush_circle.style("fill", "rgba(128,0,0,0.05)");
this._brush_circle.style("stroke-width", "1.0");
this._brush_circle.style("stroke", "red");
this._create_poly();
};
on_shutdown() {
this.poly.remove();
this.poly = null;
this._brush_circle.remove();
this._brush_circle = null;
};
on_switch_in(pos: Vector2) {
this._brush_circle.attr("visibility", "visible");
};
on_switch_out(pos: Vector2) {
this._brush_circle.attr("visibility", "hidden");
};
on_button_down(pos: Vector2, event: any) {
this.last_pos = pos;
return true;
};
on_button_up(pos: Vector2, event: any) {
this.last_pos = null;
if (this.regions.length > 0) {
this.edit_tool.notify_draw(this.regions);
}
this.regions = [];
this.poly.remove();
this._create_poly();
return true;
};
on_move(pos: Vector2) {
this._brush_circle.attr("cx", pos.x);
this._brush_circle.attr("cy", pos.y);
};
on_drag(pos: Vector2, event: any): boolean {
let brush_poly = this.make_brush_poly(this.last_pos, pos);
this.last_pos = pos;
this._brush_circle.attr("cx", pos.x);
this._brush_circle.attr("cy", pos.y);
let existing_pb = EditPolyTool._model_regions_to_polybool(this.regions);
let new_pb = EditPolyTool._model_regions_to_polybool([brush_poly]);
let composite_pb: any = PolyBool.union(existing_pb, new_pb);
this.regions = EditPolyTool._polybool_to_model(composite_pb);
this.poly.data(this.regions).attr("d", multi_path(this.regions));
return true;
};
on_wheel(pos: Vector2, wheelDeltaX: number, wheelDeltaY: number): boolean {
let wheel_rate = this._view.get_settings().brushWheelRate;
if (typeof wheel_rate != "number") {
wheel_rate = 0.025;
}
this._brush_radius += wheelDeltaY * wheel_rate;
this._brush_radius = Math.max(this._brush_radius, 1.0);
this._brush_circle.attr("r", this._brush_radius);
return true;
};
on_key_down(event: any): boolean {
var handled = false;
let key_rate = this._view.get_settings().brushKeyRate;
if (typeof key_rate != "number") {
key_rate = 2.0;
}
if (event.keyCode == 219) {
this._brush_radius -= key_rate;
handled = true;
}
else if (event.keyCode == 221) {
this._brush_radius += key_rate;
handled = true;
}
if (handled) {
this._brush_radius = Math.max(this._brush_radius, 1.0);
this._brush_circle.attr("r", this._brush_radius);
}
return handled;
};
notify_entity_deleted(entity: labelling_tool.AbstractLabelEntity<labelling_tool.AbstractLabelModel>) {
if (entity === this.entity) {
this.entity = null;
this.regions = [];
if (this.poly !== null) {
this.poly.remove();
}
this._create_poly();
}
super.notify_entity_deleted(entity);
}
make_brush_poly(start: Vector2, end: Vector2) {
let poly: Vector2[] = [];
let delta: Vector2 = sub_Vector2(end, start);
let theta: number = 0;
let d_theta: number = Math.PI * 2.0 / this._brush_segments;
for (var vert_i = 0; vert_i < this._brush_segments; vert_i++) {
let offset: Vector2 = {
x: Math.cos(theta) * this._brush_radius,
y: Math.sin(theta) * this._brush_radius
};
if (dot_Vector2(offset, delta) >= 0.0) {
// Leading edge
poly.push(add_Vector2(end, offset));
}
else {
// Trailing edge
poly.push(add_Vector2(start, offset));
}
theta += d_theta
}
return poly;
}
}
} | the_stack |
import { createThemedStyles, Theme } from '../../themes';
import type { TagOverrides } from './types';
import { TAG_KIND, TAG_VARIANT, TAG_SIZE } from './constants';
export const stylesCreator = createThemedStyles<TagOverrides>(
(
theme,
kind: TAG_KIND,
variant: TAG_VARIANT,
size: TAG_SIZE,
disabled: boolean,
clickable: boolean
) => {
const { color, backgroundColor, borderColor } = colorMap[kind][
getColorStateFromProps(variant, disabled)
](theme);
const font = labelSizeMap(theme, size);
const paddingHorizontal = paddingMagnitudeMap(theme, size);
const height = sizeMap[size];
const iconMargin = iconMarginMap(theme, size);
return {
button: {
margin: clickable ? theme.sizing.scale200 : 0,
},
container: {
flexDirection: 'row',
alignContent: 'center',
justifyContent: 'center',
alignItems: 'center',
borderWidth: !disabled && variant === TAG_VARIANT.solid ? 0 : 2,
borderStyle: 'solid',
borderColor: borderColor,
borderRadius: 24,
height,
margin: clickable ? 0 : theme.sizing.scale200,
paddingVertical: theme.sizing.scale0,
paddingHorizontal: paddingHorizontal,
backgroundColor,
},
label: {
...font,
color,
},
iconContainer: {
overflow: 'hidden',
width: font.fontSize,
height: font.fontSize,
marginLeft: iconMargin,
},
icon: {
marginLeft: ((font.fontSize * 1.75) / 100) * -21,
marginTop: ((font.fontSize * 1.75) / 100) * -21,
fontSize: font.fontSize * 1.75,
color,
},
};
}
);
//#region variables
const COLOR_STATE = {
disabled: 'disabled',
solid: 'solid',
outline: 'outline',
} as const;
const getColorStateFromProps = (variant: TAG_VARIANT, disabled: boolean) => {
if (disabled) return COLOR_STATE.disabled;
if (variant === TAG_VARIANT.solid) return COLOR_STATE.solid;
return COLOR_STATE.outline;
};
const neutralColorStates = {
[COLOR_STATE.disabled]: (theme: Theme) => ({
color: theme.colors.tagNeutralFontDisabled,
backgroundColor: 'transparent',
borderColor: theme.colors.tagNeutralOutlinedDisabled,
}),
[COLOR_STATE.solid]: (theme: Theme) => ({
color: theme.colors.tagNeutralSolidFont,
backgroundColor: theme.colors.tagNeutralSolidBackground,
borderColor: 'transparent',
}),
[COLOR_STATE.outline]: (theme: Theme) => ({
color: theme.colors.tagNeutralOutlinedFont,
backgroundColor: 'transparent',
borderColor: theme.colors.tagNeutralOutlinedBackground,
}),
};
const primaryColorStates = {
[COLOR_STATE.disabled]: (theme: Theme) => ({
color: theme.colors.tagPrimaryFontDisabled,
backgroundColor: 'transparent',
borderColor: theme.colors.tagPrimaryOutlinedDisabled,
}),
[COLOR_STATE.solid]: (theme: Theme) => ({
color: theme.colors.tagPrimarySolidFont,
backgroundColor: theme.colors.tagPrimarySolidBackground,
borderColor: 'transparent',
}),
[COLOR_STATE.outline]: (theme: Theme) => ({
color: theme.colors.tagPrimaryOutlinedFont,
backgroundColor: 'transparent',
borderColor: theme.colors.tagPrimaryOutlinedBackground,
}),
};
const accentColorStates = {
[COLOR_STATE.disabled]: (theme: Theme) => ({
color: theme.colors.tagAccentFontDisabled,
backgroundColor: 'transparent',
borderColor: theme.colors.tagAccentOutlinedDisabled,
}),
[COLOR_STATE.solid]: (theme: Theme) => ({
color: theme.colors.tagAccentSolidFont,
backgroundColor: theme.colors.tagAccentSolidBackground,
borderColor: 'transparent',
}),
[COLOR_STATE.outline]: (theme: Theme) => ({
color: theme.colors.tagAccentOutlinedFont,
backgroundColor: 'transparent',
borderColor: theme.colors.tagAccentOutlinedBackground,
}),
};
const positiveColorStates = {
[COLOR_STATE.disabled]: (theme: Theme) => ({
color: theme.colors.tagPositiveFontDisabled,
backgroundColor: 'transparent',
borderColor: theme.colors.tagPositiveOutlinedDisabled,
}),
[COLOR_STATE.solid]: (theme: Theme) => ({
color: theme.colors.tagPositiveSolidFont,
backgroundColor: theme.colors.tagPositiveSolidBackground,
borderColor: 'transparent',
}),
[COLOR_STATE.outline]: (theme: Theme) => ({
color: theme.colors.tagPositiveOutlinedFont,
backgroundColor: 'transparent',
borderColor: theme.colors.tagPositiveOutlinedBackground,
}),
};
const warningColorStates = {
[COLOR_STATE.disabled]: (theme: Theme) => ({
color: theme.colors.tagWarningFontDisabled,
backgroundColor: 'transparent',
borderColor: theme.colors.tagWarningOutlinedDisabled,
}),
[COLOR_STATE.solid]: (theme: Theme) => ({
color: theme.colors.tagWarningSolidFont,
backgroundColor: theme.colors.tagWarningSolidBackground,
borderColor: 'transparent',
}),
[COLOR_STATE.outline]: (theme: Theme) => ({
color: theme.colors.tagWarningOutlinedFont,
backgroundColor: 'transparent',
borderColor: theme.colors.tagWarningOutlinedBackground,
}),
};
const negativeColorStates = {
[COLOR_STATE.disabled]: (theme: Theme) => ({
color: theme.colors.tagNegativeFontDisabled,
backgroundColor: 'transparent',
borderColor: theme.colors.tagNegativeOutlinedDisabled,
}),
[COLOR_STATE.solid]: (theme: Theme) => ({
color: theme.colors.tagNegativeSolidFont,
backgroundColor: theme.colors.tagNegativeSolidBackground,
borderColor: 'transparent',
}),
[COLOR_STATE.outline]: (theme: Theme) => ({
color: theme.colors.tagNegativeOutlinedFont,
backgroundColor: 'transparent',
borderColor: theme.colors.tagNegativeOutlinedBackground,
}),
};
const orangeColorStates = {
[COLOR_STATE.disabled]: (theme: Theme) => ({
color: theme.colors.tagOrangeFontDisabled,
backgroundColor: 'transparent',
borderColor: theme.colors.tagOrangeOutlinedDisabled,
}),
[COLOR_STATE.solid]: (theme: Theme) => ({
color: theme.colors.tagOrangeSolidFont,
backgroundColor: theme.colors.tagOrangeSolidBackground,
borderColor: 'transparent',
}),
[COLOR_STATE.outline]: (theme: Theme) => ({
color: theme.colors.tagOrangeOutlinedFont,
backgroundColor: 'transparent',
borderColor: theme.colors.tagOrangeOutlinedBackground,
}),
};
const purpleColorStates = {
[COLOR_STATE.disabled]: (theme: Theme) => ({
color: theme.colors.tagPurpleFontDisabled,
backgroundColor: 'transparent',
borderColor: theme.colors.tagPurpleOutlinedDisabled,
}),
[COLOR_STATE.solid]: (theme: Theme) => ({
color: theme.colors.tagPurpleSolidFont,
backgroundColor: theme.colors.tagPurpleSolidBackground,
borderColor: 'transparent',
}),
[COLOR_STATE.outline]: (theme: Theme) => ({
color: theme.colors.tagPurpleOutlinedFont,
backgroundColor: 'transparent',
borderColor: theme.colors.tagPurpleOutlinedBackground,
}),
};
const brownColorStates = {
[COLOR_STATE.disabled]: (theme: Theme) => ({
color: theme.colors.tagBrownFontDisabled,
backgroundColor: 'transparent',
borderColor: theme.colors.tagBrownOutlinedDisabled,
}),
[COLOR_STATE.solid]: (theme: Theme) => ({
color: theme.colors.tagBrownSolidFont,
backgroundColor: theme.colors.tagBrownSolidBackground,
borderColor: 'transparent',
}),
[COLOR_STATE.outline]: (theme: Theme) => ({
color: theme.colors.tagBrownOutlinedFont,
backgroundColor: 'transparent',
borderColor: theme.colors.tagBrownOutlinedBackground,
}),
};
// const customColorStates = {
// [COLOR_STATE.disabled]: (theme: Theme, color: string) => ({
// color: customOnRamp(color, theme.colors.tagFontDisabledRampUnit),
// backgroundColor: 'transparent',
// borderColor: customOnRamp(color, theme.colors.tagOutlinedDisabledRampUnit),
// }),
// [COLOR_STATE.solid]: (theme: Theme, color: string) => ({
// color: customOnRamp(color, theme.colors.tagSolidFontRampUnit),
// backgroundColor: customOnRamp(color, theme.colors.tagSolidRampUnit),
// borderColor: 'transparent',
// }),
// [COLOR_STATE.outline]: (theme: Theme, color: string) => ({
// color: customOnRamp(color, theme.colors.tagOutlinedFontRampUnit),
// backgroundColor: 'transparent',
// borderColor: customOnRamp(color, theme.colors.tagOutlinedRampUnit),
// }),
// };
// // Probably best to bake this into the theme once we hit our next major.
// const pick = (theme, light, dark) =>
// theme.name && theme.name.includes('dark') ? dark : light;
const colorMap = {
[TAG_KIND.neutral]: neutralColorStates,
[TAG_KIND.primary]: primaryColorStates,
[TAG_KIND.accent]: accentColorStates,
[TAG_KIND.positive]: positiveColorStates,
[TAG_KIND.warning]: warningColorStates,
[TAG_KIND.negative]: negativeColorStates,
[TAG_KIND.black]: primaryColorStates,
[TAG_KIND.blue]: accentColorStates,
[TAG_KIND.green]: positiveColorStates,
[TAG_KIND.red]: negativeColorStates,
[TAG_KIND.yellow]: warningColorStates,
[TAG_KIND.orange]: orangeColorStates,
[TAG_KIND.purple]: purpleColorStates,
[TAG_KIND.brown]: brownColorStates,
// [TAG_KIND.custom]: customColorStates,
};
const sizeMap = {
[TAG_SIZE.small]: 24,
[TAG_SIZE.medium]: 32,
[TAG_SIZE.large]: 40,
};
const paddingMagnitudeMap = (theme: Theme, size: TAG_SIZE) => {
switch (size) {
case TAG_SIZE.small:
return theme.sizing.scale300;
case TAG_SIZE.medium:
return theme.sizing.scale500;
case TAG_SIZE.large:
return theme.sizing.scale600;
}
};
const labelSizeMap = (theme: Theme, size: TAG_SIZE) => {
switch (size) {
case TAG_SIZE.small:
return theme.typography.LabelSmall;
case TAG_SIZE.medium:
return theme.typography.LabelMedium;
case TAG_SIZE.large:
return theme.typography.LabelLarge;
}
};
const iconMarginMap = (theme: Theme, size: TAG_SIZE) => {
switch (size) {
case TAG_SIZE.small:
return theme.sizing.scale300;
case TAG_SIZE.medium:
return theme.sizing.scale500;
case TAG_SIZE.large:
return theme.sizing.scale600;
}
}; | the_stack |
import Link from '@docusaurus/Link';
// import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import { Button } from '@mui/material';
import WhatshotIcon from '@mui/icons-material/Whatshot';
import Layout from '@theme/Layout';
import React from 'react';
import { CoverFlowImages } from '../components/CoverFlowImages';
import styles from './index.module.css';
import Head from '@docusaurus/Head';
export default function Home() {
// const { siteConfig } = useDocusaurusContext();
return (
<Layout
title="Cromwell CMS - next-gen e-commerce and blogging platform that unites bleeding-edge web techs in extraordinary user-friendly format"
description="Cromwell CMS - next-gen e-commerce and blogging platform that unites bleeding-edge web techs in extraordinary user-friendly format"
>
<Head>
<meta charSet="utf-8" />
<meta property="og:image" content={'/img/icon_small.png'} />
</Head>
<div className={styles.IndexPage}>
<div className={styles.content}>
<div className={styles.moon}></div>
<h1 className={styles.header}><span style={{ display: 'none' }}>C</span><span>romwell CMS</span></h1>
<p className={styles.subheader}>It's time for everyone to make blazing-fast websites
<WhatshotIcon className={styles.fireIcon} style={{ width: '20px', height: '20px' }} />
</p>
<div>
<p className={styles.quote}>
Cromwell CMS is a next-gen e-commerce and blogging
platform that unites bleeding-edge web techs in extraordinary user-friendly format.</p>
</div>
<div className={styles.mainActions}>
<Link href="/docs/overview/intro">
<Button
variant="contained"
className={styles.getStartedBtn}
>Get started</Button>
</Link>
</div>
</div>
<div className={styles.content}>
<br style={{ height: '10px' }} />
<h3 className={styles.header3}>The most advanced visual editor for Next.js apps</h3>
<p className={styles.sectionSubHeader}>Install properly crafted themes by frontend developers.
Drag and drop theme blocks. Add plugins, change content,
styles and more. Make it yours!</p>
<br style={{ height: '20px' }} />
</div>
<CoverFlowImages images={[
"/img/demo-theme-editor.mp4",
]} />
<div className={styles.content}>
<br style={{ height: '20px' }} />
<br style={{ height: '20px' }} />
<h3 className={styles.header3}>Modern block styled rich text editor</h3>
<p className={styles.sectionSubHeader}>Embed video links or upload images. Manage your media with file manager.</p>
<br style={{ height: '10px' }} />
</div>
<CoverFlowImages images={[
"/img/demo-editor.jpg",
"/img/demo-filemanager.png",
]} />
<div className={styles.content}>
<br style={{ height: '20px' }} />
<br style={{ height: '20px' }} />
<h3 className={styles.header3}>Customizable statistics dashboard</h3>
<p className={styles.sectionSubHeader}>Move and resize dashboard blocks. Monitor server load.</p>
<br style={{ height: '20px' }} />
</div>
<CoverFlowImages images={[
"/img/demo-dashboard.mp4",
"/img/demo-sysusage.png",
]} />
<div className={styles.content}>
<br style={{ height: '10px' }} />
<br style={{ height: '10px' }} />
<h3 className={styles.header3}>Custom data types</h3>
<p className={styles.sectionSubHeader}>Add custom fields or create new custom entities. Store any kind of data.</p>
<br style={{ height: '10px' }} />
</div>
<CoverFlowImages images={[
"/img/demo-custom1.png",
"/img/demo-custom-entities.mp4",
"/img/demo-custom2.png",
]} />
<div className={styles.content}>
<br style={{ height: '10px' }} />
<br style={{ height: '10px' }} />
<h3 className={styles.header3}>Good looking default themes</h3>
<p className={styles.sectionSubHeader}>Fully featured free online store and blog out of
the box.</p>
<br style={{ height: '10px' }} />
</div>
<CoverFlowImages images={[
"/img/demo-site1.png",
"/img/demo-site2.png",
"/img/demo-site3.png",
"/img/demo-site4.png",
]} />
<div className={styles.content}>
<br style={{ height: '10px' }} />
<br style={{ height: '10px' }} />
<h3 className={styles.header3}>Developer?</h3>
<p className={styles.sectionSubHeader} >Make plugins that work with themes and can be
statically pre-rendered by Next.js. Publish them to the market and let
everyone use with a couple of clicks.</p>
<br style={{ height: '10px' }} />
</div>
<CoverFlowImages images={[
"/img/demo-install-plugin.mp4",
]} />
<div className={styles.content}>
<br style={{ height: '10px' }} />
<br style={{ height: '10px' }} />
<h3 className={styles.header3}>Use the power of React and Next.js</h3>
<p className={styles.sectionSubHeader}>
Make themes by writing JSX code. We will build your Next.js app so
representation of your code can be fully customized by your customers.
Yes, these React components
will be dragged/dropped/removed/styles in the theme editor!</p>
<br style={{ height: '10px' }} />
</div>
<CoverFlowImages images={[
"/img/demo-theme-dev.png",
]} />
<div className={styles.content}>
<br style={{ height: '10px' }} />
<br style={{ height: '10px' }} />
<h3 className={styles.header3}>Extend server API</h3>
<p className={styles.sectionSubHeader}>Make plugins to extend server API with the
best enterprise-grade
TypeScript frameworks: Nest.js, TypeGraphQL and TypeORM.</p>
<br style={{ height: '10px' }} />
</div>
<CoverFlowImages images={[
"/img/demo-plugins-api.jpg",
]} />
<div className={styles.content}>
<br style={{ height: '10px' }} />
<br style={{ height: '10px' }} />
<h3 className={styles.header3}>Go headless</h3>
<p className={styles.sectionSubHeader}>Cromwell CMS follows principles of
headless CMS. You can
make any kind of custom frontend and query our API server with GraphQL.
</p>
<br style={{ height: '10px' }} />
</div>
<CoverFlowImages images={[
"/img/demo-headless.png",
]} />
<div className={styles.content}>
<br style={{ height: '20px' }} />
<br style={{ height: '20px' }} />
<div style={{
display: 'flex',
alignItems: 'center',
width: '100%',
justifyContent: 'center',
}}>
<Link href="/docs/overview/intro">
<Button
style={{ margin: '0' }}
variant="contained"
className={styles.getStartedBtn}
>Get started</Button>
</Link>
<Link href="/docs/overview/intro#examples" style={{ marginLeft: '30px' }}>
<Button
variant="contained"
className={styles.examplesBtn}
>Examples</Button>
</Link>
</div>
<br />
<br />
<br />
</div>
<div className={styles.content}>
<div className={styles.features}>
<div className={styles.feature}>
<div className={styles.featureImg} style={{
// minWidth: '90px',
// height: '90px',
backgroundSize: '70%',
backgroundImage: 'url("/img/content.svg")'
}}></div>
<div>
<p className={styles.featureTitle}>Online store and blogging platform.</p>
<p>Manage your products, posts and other content with ease.</p>
</div>
</div>
<div className={styles.feature}>
<div className={styles.featureImg} style={{
backgroundImage: 'url("/img/puzzle.svg")',
backgroundSize: '68%',
// minWidth: '90px',
// height: '90px',
}}></div>
<div>
<p className={styles.featureTitle}>Powerful admin panel with themes and plugins.</p>
<p>Customize your theme, install plugins. WordPress-like user experience.</p>
</div>
</div>
<div className={styles.feature}>
<div className={styles.featureImg} style={{
// minWidth: '120px',
// height: '120px',
// marginLeft: '-50px',
backgroundSize: '97%',
backgroundImage: 'url("/img/seo.svg")',
}}></div>
<div>
<p className={styles.featureTitle}>SEO optimized.</p>
<p>Modifiable meta tags for all content and custom pages. Auto-generated Sitemap.</p>
</div>
</div>
<div className={styles.feature}>
<div className={styles.featureImg} style={{
backgroundImage: 'url("/img/magic-wand.svg")'
}}></div>
<div>
<p className={styles.featureTitle}>Theme editor</p>
<p>Fully customize your Theme layout in drag-and-drop Theme editor.</p>
</div>
</div>
<div className={styles.feature}>
<div className={styles.featureImg} style={{
backgroundSize: '73%',
backgroundImage: 'url("/img/rocket.svg")',
}}></div>
<div>
<p className={styles.featureTitle}>Node.js.</p>
<p>Designed to be a better version of PHP web servers,
it greatly outperforms backend of well known CMS.</p>
</div>
</div>
<div className={styles.feature}>
<div className={styles.featureImg} style={{
backgroundImage: 'url("/img/open-source.svg")',
}}></div>
<div>
<p className={styles.featureTitle}>Free and open source</p>
<p>Cromwell CMS with default themes and plugins will stay forever free of
charge and open source.</p>
</div>
</div>
</div>
<br style={{ height: '20px' }} />
</div>
</div>
</Layout >
);
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Manages an Azure IoT Time Series Insights EventHub Event Source.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleEventHubNamespace = new azure.eventhub.EventHubNamespace("exampleEventHubNamespace", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* sku: "Standard",
* });
* const exampleEventHub = new azure.eventhub.EventHub("exampleEventHub", {
* namespaceName: exampleEventHubNamespace.name,
* resourceGroupName: exampleResourceGroup.name,
* partitionCount: 2,
* messageRetention: 7,
* });
* const exampleConsumerGroup = new azure.eventhub.ConsumerGroup("exampleConsumerGroup", {
* namespaceName: exampleEventHubNamespace.name,
* eventhubName: exampleEventHub.name,
* resourceGroupName: exampleResourceGroup.name,
* });
* const exampleAuthorizationRule = new azure.eventhub.AuthorizationRule("exampleAuthorizationRule", {
* namespaceName: exampleEventHubNamespace.name,
* eventhubName: exampleEventHub.name,
* resourceGroupName: exampleResourceGroup.name,
* listen: true,
* send: false,
* manage: false,
* });
* const exampleAccount = new azure.storage.Account("exampleAccount", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* accountTier: "Standard",
* accountReplicationType: "LRS",
* });
* const exampleTimeSeriesInsightsGen2Environment = new azure.iot.TimeSeriesInsightsGen2Environment("exampleTimeSeriesInsightsGen2Environment", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* skuName: "L1",
* idProperties: ["id"],
* storage: {
* name: exampleAccount.name,
* key: exampleAccount.primaryAccessKey,
* },
* });
* const exampleTimeSeriesInsightsEventSourceEventhub = new azure.iot.TimeSeriesInsightsEventSourceEventhub("exampleTimeSeriesInsightsEventSourceEventhub", {
* location: exampleResourceGroup.location,
* environmentId: exampleTimeSeriesInsightsGen2Environment.id,
* eventhubName: exampleEventHub.name,
* namespaceName: exampleEventHubNamespace.name,
* sharedAccessKey: exampleAuthorizationRule.primaryKey,
* sharedAccessKeyName: exampleAuthorizationRule.name,
* consumerGroupName: exampleConsumerGroup.name,
* eventSourceResourceId: exampleEventHub.id,
* });
* ```
*
* ## Import
*
* Azure IoT Time Series Insights EventHub Event Source can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:iot/timeSeriesInsightsEventSourceEventhub:TimeSeriesInsightsEventSourceEventhub example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.TimeSeriesInsights/environments/environment1/eventSources/example
* ```
*/
export class TimeSeriesInsightsEventSourceEventhub extends pulumi.CustomResource {
/**
* Get an existing TimeSeriesInsightsEventSourceEventhub resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: TimeSeriesInsightsEventSourceEventhubState, opts?: pulumi.CustomResourceOptions): TimeSeriesInsightsEventSourceEventhub {
return new TimeSeriesInsightsEventSourceEventhub(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:iot/timeSeriesInsightsEventSourceEventhub:TimeSeriesInsightsEventSourceEventhub';
/**
* Returns true if the given object is an instance of TimeSeriesInsightsEventSourceEventhub. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is TimeSeriesInsightsEventSourceEventhub {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === TimeSeriesInsightsEventSourceEventhub.__pulumiType;
}
/**
* Specifies the name of the EventHub Consumer Group that holds the partitions from which events will be read.
*/
public readonly consumerGroupName!: pulumi.Output<string>;
/**
* Specifies the id of the IoT Time Series Insights Environment that the Event Source should be associated with. Changing this forces a new resource to created.
*/
public readonly environmentId!: pulumi.Output<string>;
/**
* Specifies the resource id where events will be coming from.
*/
public readonly eventSourceResourceId!: pulumi.Output<string>;
/**
* Specifies the name of the EventHub which will be associated with this resource.
*/
public readonly eventhubName!: pulumi.Output<string>;
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
public readonly location!: pulumi.Output<string>;
/**
* Specifies the name of the Azure IoT Time Series Insights EventHub Event Source. Changing this forces a new resource to be created. Must be globally unique.
*/
public readonly name!: pulumi.Output<string>;
/**
* Specifies the EventHub Namespace name.
*/
public readonly namespaceName!: pulumi.Output<string>;
/**
* Specifies the value of the Shared Access Policy key that grants the Time Series Insights service read access to the EventHub.
*/
public readonly sharedAccessKey!: pulumi.Output<string>;
/**
* Specifies the name of the Shared Access key that grants the Event Source access to the EventHub.
*/
public readonly sharedAccessKeyName!: pulumi.Output<string>;
/**
* A mapping of tags to assign to the resource.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Specifies the value that will be used as the event source's timestamp. This value defaults to the event creation time.
*/
public readonly timestampPropertyName!: pulumi.Output<string>;
/**
* Create a TimeSeriesInsightsEventSourceEventhub resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: TimeSeriesInsightsEventSourceEventhubArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: TimeSeriesInsightsEventSourceEventhubArgs | TimeSeriesInsightsEventSourceEventhubState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as TimeSeriesInsightsEventSourceEventhubState | undefined;
inputs["consumerGroupName"] = state ? state.consumerGroupName : undefined;
inputs["environmentId"] = state ? state.environmentId : undefined;
inputs["eventSourceResourceId"] = state ? state.eventSourceResourceId : undefined;
inputs["eventhubName"] = state ? state.eventhubName : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["namespaceName"] = state ? state.namespaceName : undefined;
inputs["sharedAccessKey"] = state ? state.sharedAccessKey : undefined;
inputs["sharedAccessKeyName"] = state ? state.sharedAccessKeyName : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["timestampPropertyName"] = state ? state.timestampPropertyName : undefined;
} else {
const args = argsOrState as TimeSeriesInsightsEventSourceEventhubArgs | undefined;
if ((!args || args.consumerGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'consumerGroupName'");
}
if ((!args || args.environmentId === undefined) && !opts.urn) {
throw new Error("Missing required property 'environmentId'");
}
if ((!args || args.eventSourceResourceId === undefined) && !opts.urn) {
throw new Error("Missing required property 'eventSourceResourceId'");
}
if ((!args || args.eventhubName === undefined) && !opts.urn) {
throw new Error("Missing required property 'eventhubName'");
}
if ((!args || args.namespaceName === undefined) && !opts.urn) {
throw new Error("Missing required property 'namespaceName'");
}
if ((!args || args.sharedAccessKey === undefined) && !opts.urn) {
throw new Error("Missing required property 'sharedAccessKey'");
}
if ((!args || args.sharedAccessKeyName === undefined) && !opts.urn) {
throw new Error("Missing required property 'sharedAccessKeyName'");
}
inputs["consumerGroupName"] = args ? args.consumerGroupName : undefined;
inputs["environmentId"] = args ? args.environmentId : undefined;
inputs["eventSourceResourceId"] = args ? args.eventSourceResourceId : undefined;
inputs["eventhubName"] = args ? args.eventhubName : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["namespaceName"] = args ? args.namespaceName : undefined;
inputs["sharedAccessKey"] = args ? args.sharedAccessKey : undefined;
inputs["sharedAccessKeyName"] = args ? args.sharedAccessKeyName : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["timestampPropertyName"] = args ? args.timestampPropertyName : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(TimeSeriesInsightsEventSourceEventhub.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering TimeSeriesInsightsEventSourceEventhub resources.
*/
export interface TimeSeriesInsightsEventSourceEventhubState {
/**
* Specifies the name of the EventHub Consumer Group that holds the partitions from which events will be read.
*/
consumerGroupName?: pulumi.Input<string>;
/**
* Specifies the id of the IoT Time Series Insights Environment that the Event Source should be associated with. Changing this forces a new resource to created.
*/
environmentId?: pulumi.Input<string>;
/**
* Specifies the resource id where events will be coming from.
*/
eventSourceResourceId?: pulumi.Input<string>;
/**
* Specifies the name of the EventHub which will be associated with this resource.
*/
eventhubName?: pulumi.Input<string>;
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* Specifies the name of the Azure IoT Time Series Insights EventHub Event Source. Changing this forces a new resource to be created. Must be globally unique.
*/
name?: pulumi.Input<string>;
/**
* Specifies the EventHub Namespace name.
*/
namespaceName?: pulumi.Input<string>;
/**
* Specifies the value of the Shared Access Policy key that grants the Time Series Insights service read access to the EventHub.
*/
sharedAccessKey?: pulumi.Input<string>;
/**
* Specifies the name of the Shared Access key that grants the Event Source access to the EventHub.
*/
sharedAccessKeyName?: pulumi.Input<string>;
/**
* A mapping of tags to assign to the resource.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Specifies the value that will be used as the event source's timestamp. This value defaults to the event creation time.
*/
timestampPropertyName?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a TimeSeriesInsightsEventSourceEventhub resource.
*/
export interface TimeSeriesInsightsEventSourceEventhubArgs {
/**
* Specifies the name of the EventHub Consumer Group that holds the partitions from which events will be read.
*/
consumerGroupName: pulumi.Input<string>;
/**
* Specifies the id of the IoT Time Series Insights Environment that the Event Source should be associated with. Changing this forces a new resource to created.
*/
environmentId: pulumi.Input<string>;
/**
* Specifies the resource id where events will be coming from.
*/
eventSourceResourceId: pulumi.Input<string>;
/**
* Specifies the name of the EventHub which will be associated with this resource.
*/
eventhubName: pulumi.Input<string>;
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* Specifies the name of the Azure IoT Time Series Insights EventHub Event Source. Changing this forces a new resource to be created. Must be globally unique.
*/
name?: pulumi.Input<string>;
/**
* Specifies the EventHub Namespace name.
*/
namespaceName: pulumi.Input<string>;
/**
* Specifies the value of the Shared Access Policy key that grants the Time Series Insights service read access to the EventHub.
*/
sharedAccessKey: pulumi.Input<string>;
/**
* Specifies the name of the Shared Access key that grants the Event Source access to the EventHub.
*/
sharedAccessKeyName: pulumi.Input<string>;
/**
* A mapping of tags to assign to the resource.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Specifies the value that will be used as the event source's timestamp. This value defaults to the event creation time.
*/
timestampPropertyName?: pulumi.Input<string>;
} | the_stack |
import * as assert from 'assert';
import * as fs from 'fs';
import * as path from 'path';
import * as ps from 'ps-node';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
import * as myExtension from '../../extension';
import * as myExplorer from '../../explorer';
import { TextDocument, TextEditor, Uri } from 'vscode';
import { assertWorkspace, dumpJava, prepareProject } from './testutils';
suite('Extension Test Suite', () => {
vscode.window.showInformationMessage('Start all tests.');
myExtension.enableConsoleLog();
test('VSNetBeans is present', async () => {
let nbcode = vscode.extensions.getExtension('asf.apache-netbeans-java');
assert.ok(nbcode, "Apache NetBeans Extension is present");
let api = await nbcode.activate();
assert.ok(api.version, "Some version is specified");
let cannotReassignVersion = false;
try {
api.version = "different";
} catch (e) {
cannotReassignVersion = true;
}
assert.ok(cannotReassignVersion, "Cannot reassign value of version");
});
test('Find clusters', async () => {
const nbcode = vscode.extensions.getExtension('asf.apache-netbeans-java');
assert.ok(nbcode);
const extraCluster = path.join(nbcode.extensionPath, "nbcode", "extra");
let clusters = myExtension.findClusters('non-existent').
// ignore 'extra' cluster in the extension path, since nbjavac is there during development:
filter(s => !s.startsWith(extraCluster));
let found : string[] = [];
function assertCluster(name : string) {
for (let c of clusters) {
if (c.endsWith('/' + name)) {
found.push(c);
return;
}
}
assert.fail(`Cannot find ${name} among ${clusters}`);
}
assertCluster('extide');
assertCluster('ide');
assertCluster('java');
assertCluster('nbcode');
assertCluster('platform');
assertCluster('webcommon');
assertCluster('harness');
for (let c of found) {
assert.ok(c.startsWith(nbcode.extensionPath), `All extensions are below ${nbcode.extensionPath}, but: ${c}`);
}
});
async function demo(where: number) {
let folder: string = assertWorkspace();
await prepareProject(folder);
vscode.workspace.saveAll();
if (where === 6) return;
try {
console.log("Test: invoking compile");
let res = await vscode.commands.executeCommand("java.workspace.compile");
console.log(`Test: compile finished with ${res}`);
} catch (error) {
dumpJava();
throw error;
}
if (where === 7) return;
let mainClass = path.join(folder, 'target', 'classes', 'pkg', 'Main.class');
if (where === 8) return;
assert.ok(fs.statSync(mainClass).isFile(), "Class created by compilation: " + mainClass);
myExplorer.createViewProvider(await myExtension.awaitClient(), "foundProjects").then(async (lvp) => {
const firstLevelChildren = await (lvp.getChildren() as Thenable<any[]>);
assert.strictEqual(firstLevelChildren.length, 1, "One child under the root");
const item = await (lvp.getTreeItem(firstLevelChildren[0]) as Thenable<vscode.TreeItem>);
assert.strictEqual(item?.label, "basicapp", "Element is named as the Maven project");
})
}
test("Compile workspace6", async() => demo(6));
test("Compile workspace7", async() => demo(7));
test("Compile workspace8", async() => demo(8));
test("Compile workspace9", async() => demo(9));
/**
* Checks that maven-managed process can be started, and forcefully terminated by vscode
* although it does not run in debugging mode.
*/
async function mavenTerminateWithoutDebugger() {
let folder: string = assertWorkspace();
await prepareProject(folder);
vscode.workspace.saveAll();
let u : Uri = vscode.Uri.file(path.join(folder, 'src', 'main', 'java', 'pkg', 'Main.java'));
let doc : TextDocument = await vscode.workspace.openTextDocument(u);
let e : TextEditor = await vscode.window.showTextDocument(doc);
try {
let r = new Promise((resolve, reject) => {
function waitUserApplication(cnt : number, running: boolean, cb : () => void) {
ps.lookup({
command: "^.*[/\\\\]java",
arguments: "pkg.Main"
}, (err, list ) => {
let success : boolean = (list && list.length > 0) == running;
if (success) {
cb();
} else {
if (cnt == 0) {
reject(new Error("Timeout waiting for user application"));
return;
}
setTimeout(() => waitUserApplication(cnt - 1, running, cb), 1000);
return;
}
});
}
function onProcessStarted() {
console.log("Test: invoking debug.stop");
// attempt to terminate:
vscode.commands.executeCommand("workbench.action.debug.stop").
then(() => waitUserApplication(5, false, () => resolve(true)));
}
console.log("Test: invoking debug debug.run");
const workspaceFolder = (vscode.workspace.workspaceFolders!)[0];
vscode.debug.startDebugging(workspaceFolder, {type: "java8+", name: "Launch Java 8+ App", request: "launch"}, {}).
then(() => waitUserApplication(5, true, onProcessStarted));
});
return r;
} catch (error) {
dumpJava();
throw error;
}
}
test("Maven run termination", async() => mavenTerminateWithoutDebugger());
async function getProjectInfo() {
let folder: string = assertWorkspace();
await prepareProject(folder);
vscode.workspace.saveAll();
try {
console.log("Test: get project java source roots");
let res: any = await vscode.commands.executeCommand("java.get.project.source.roots", Uri.file(folder).toString());
console.log(`Test: get project java source roots finished with ${res}`);
assert.ok(res, "No java source root returned");
assert.strictEqual(res.length, 2, `Invalid number of java roots returned`);
assert.strictEqual(res[0], path.join('file:', folder, 'src', 'main', 'java') + path.sep, `Invalid java main source root returned`);
assert.strictEqual(res[1], path.join('file:', folder, 'src', 'test', 'java') + path.sep, `Invalid java test source root returned`);
console.log("Test: get project resource roots");
res = await vscode.commands.executeCommand("java.get.project.source.roots", Uri.file(folder).toString(), 'resources');
console.log(`Test: get project resource roots finished with ${res}`);
assert.ok(res, "No resource root returned");
assert.strictEqual(res.length, 1, `Invalid number of resource roots returned`);
assert.strictEqual(res[0], path.join('file:', folder, 'src', 'main', 'resources') + path.sep, `Invalid resource root returned`);
console.log("Test: get project compile classpath");
res = await vscode.commands.executeCommand("java.get.project.classpath", Uri.file(folder).toString());
console.log(`Test: get project compile classpath finished with ${res}`);
assert.ok(res, "No compile classpath returned");
assert.strictEqual(res.length, 9, `Invalid number of compile classpath roots returned`);
assert.ok(res.find((item: any) => item === path.join('file:', folder, 'target', 'classes') + path.sep, `Invalid compile classpath root returned`));
console.log("Test: get project source classpath");
res = await vscode.commands.executeCommand("java.get.project.classpath", Uri.file(folder).toString(), 'SOURCE');
console.log(`Test: get project source classpath finished with ${res}`);
assert.ok(res, "No source classpath returned");
assert.strictEqual(res.length, 3, `Invalid number of source classpath roots returned`);
assert.ok(res.find((item: any) => item === path.join('file:', folder, 'src', 'main', 'java') + path.sep, `Invalid source classpath root returned`));
assert.ok(res.find((item: any) => item === path.join('file:', folder, 'src', 'main', 'resources') + path.sep, `Invalid source classpath root returned`));
assert.ok(res.find((item: any) => item === path.join('file:', folder, 'src', 'test', 'java') + path.sep, `Invalid source classpath root returned`));
console.log("Test: get project boot classpath");
res = await vscode.commands.executeCommand("java.get.project.classpath", Uri.file(folder).toString(), 'BOOT');
console.log(`Test: get project boot classpath finished with ${res}`);
assert.ok(res, "No boot classpath returned");
assert.ok(res.length > 0, `Invalid number of boot classpath roots returned`);
console.log("Test: get project boot source classpath");
res = await vscode.commands.executeCommand("java.get.project.classpath", Uri.file(folder).toString(), 'BOOT', true);
console.log(`Test: get project boot source classpath finished with ${res}`);
assert.ok(res, "No boot source classpath returned");
assert.ok(res.length > 0, `Invalid number of boot source classpath roots returned`);
console.log("Test: get all project packages");
res = await vscode.commands.executeCommand("java.get.project.packages", Uri.file(folder).toString());
console.log(`Test: get all project packages finished with ${res}`);
assert.ok(res, "No packages returned");
assert.ok(res.length > 0, `Invalid number of packages returned`);
console.log("Test: get project source packages");
res = await vscode.commands.executeCommand("java.get.project.packages", Uri.file(folder).toString(), true);
console.log(`Test: get project source packages finished with ${res}`);
assert.ok(res, "No packages returned");
assert.strictEqual(res.length, 1, `Invalid number of packages returned`);
assert.strictEqual(res[0], 'pkg', `Invalid package returned`);
} catch (error) {
dumpJava();
throw error;
}
}
test("Get project sources, classpath, and packages", async() => getProjectInfo());
async function testExplorerTests() {
let folder: string = assertWorkspace();
await prepareProject(folder);
vscode.workspace.saveAll();
try {
console.log("Test: load workspace tests");
let tests: any = await vscode.commands.executeCommand("java.load.workspace.tests", Uri.file(folder).toString());
console.log(`Test: load workspace tests finished with ${tests}`);
assert.ok(tests, "No tests returned for workspace");
assert.strictEqual(tests.length, 2, `Invalid number of test suites returned`);
assert.strictEqual(tests[0].name, 'pkg.MainTest', `Invalid test suite name returned`);
assert.strictEqual(tests[0].tests.length, 1, `Invalid number of tests in suite returned`);
assert.strictEqual(tests[0].tests[0].name, 'testGetName', `Invalid test name returned`);
assert.strictEqual(tests[1].name, 'pkg.MainTest$NestedTest', `Invalid test suite name returned`);
assert.strictEqual(tests[1].tests.length, 1, `Invalid number of tests in suite returned`);
assert.strictEqual(tests[1].tests[0].name, 'testTrue', `Invalid test name returned`);
console.log("Test: run all workspace tests");
const workspaceFolder = (vscode.workspace.workspaceFolders!)[0];
await vscode.commands.executeCommand('java.run.test', workspaceFolder.uri.toString());
console.log(`Test: run all workspace tests finished`);
} catch (error) {
dumpJava();
throw error;
}
}
test("Test Explorer tests", async() => testExplorerTests());
}); | the_stack |
module android.view {
import Rect = android.graphics.Rect;
import ViewConfiguration = android.view.ViewConfiguration;
const tempBound = new Rect();
interface TouchEvent {
touches: TouchList;
changedTouches: TouchList;
type: string;
//targetTouches: TouchList;
//rotation: number;
//scale: number;
}
interface TouchList {
length: number;
[index: number]: Touch;
}
interface Touch {
//identifier: number;
id_fix:number;
target: EventTarget;
screenX: number;
screenY: number;
clientX: number;
clientY: number;
pageX: number;
pageY: number;
//add as history
mEventTime?:number;
}
const ID_FixID_Cache:Array<number> = [];
const tmpTouchEvent:TouchEvent = {
touches: null,
changedTouches: null,
type: null
};
/**
* identifier on iOS safari was not same as other platform
* http://stackoverflow.com/questions/25008690/javascript-ipad-touch-event-identifier-is-continually-incrementing
*/
function fixEventId(e:TouchEvent):TouchEvent {
for (let i = 0, length = e.changedTouches.length; i < length; i++) {
fixTouchId(e.changedTouches[i]);
}
for (let i = 0, length = e.touches.length; i < length; i++) {
fixTouchId(e.touches[i]);
}
if(e.type == 'touchend' || e.type == 'touchcancel'){
ID_FixID_Cache[e.changedTouches[0].id_fix] = null;
}
tmpTouchEvent.type = e.type;
tmpTouchEvent.changedTouches = Array.from(e.changedTouches).map((touch) => fixTouchId(touch));
tmpTouchEvent.touches = Array.from(e.touches).map((touch) => fixTouchId(touch));
return tmpTouchEvent;
}
function fixTouchId(touch:Touch):Touch {
let originID = touch['identifier'];
let fix_id = ID_FixID_Cache.indexOf(originID);
if (fix_id < 0) {
for (let i = 0, length = ID_FixID_Cache.length + 1; i < length; i++) {
if(ID_FixID_Cache[i] == null){
ID_FixID_Cache[i] = originID;
fix_id = i;
break;
}
}
}
return {
id_fix: fix_id,
target: touch.target,
screenX: touch.screenX,
screenY: touch.screenY,
clientX: touch.clientX,
clientY: touch.clientY,
pageX: touch.pageX,
pageY: touch.pageY,
mEventTime: touch.mEventTime,
};
}
/**
* Object used to report movement (mouse, pen, finger, trackball) events.
* Motion events may hold either absolute or relative movements and other data,
* depending on the type of device.
*
* <h3>Overview</h3>
* <p>
* Motion events describe movements in terms of an action code and a set of axis values.
* The action code specifies the state change that occurred such as a pointer going
* down or up. The axis values describe the position and other movement properties.
* </p><p>
* For example, when the user first touches the screen, the system delivers a touch
* event to the appropriate {@link View} with the action code {@link #ACTION_DOWN}
* and a set of axis values that include the X and Y coordinates of the touch and
* information about the pressure, size and orientation of the contact area.
* </p><p>
* Some devices can report multiple movement traces at the same time. Multi-touch
* screens emit one movement trace for each finger. The individual fingers or
* other objects that generate movement traces are referred to as <em>pointers</em>.
* Motion events contain information about all of the pointers that are currently active
* even if some of them have not moved since the last event was delivered.
* </p><p>
* The number of pointers only ever changes by one as individual pointers go up and down,
* except when the gesture is canceled.
* </p><p>
* Each pointer has a unique id that is assigned when it first goes down
* (indicated by {@link #ACTION_DOWN} or {@link #ACTION_POINTER_DOWN}). A pointer id
* remains valid until the pointer eventually goes up (indicated by {@link #ACTION_UP}
* or {@link #ACTION_POINTER_UP}) or when the gesture is canceled (indicated by
* {@link #ACTION_CANCEL}).
* </p><p>
* The MotionEvent class provides many methods to query the position and other properties of
* pointers, such as {@link #getX(int)}, {@link #getY(int)}, {@link #getAxisValue},
* {@link #getPointerId(int)}, {@link #getToolType(int)}, and many others. Most of these
* methods accept the pointer index as a parameter rather than the pointer id.
* The pointer index of each pointer in the event ranges from 0 to one less than the value
* returned by {@link #getPointerCount()}.
* </p><p>
* The order in which individual pointers appear within a motion event is undefined.
* Thus the pointer index of a pointer can change from one event to the next but
* the pointer id of a pointer is guaranteed to remain constant as long as the pointer
* remains active. Use the {@link #getPointerId(int)} method to obtain the
* pointer id of a pointer to track it across all subsequent motion events in a gesture.
* Then for successive motion events, use the {@link #findPointerIndex(int)} method
* to obtain the pointer index for a given pointer id in that motion event.
* </p><p>
* Mouse and stylus buttons can be retrieved using {@link #getButtonState()}. It is a
* good idea to check the button state while handling {@link #ACTION_DOWN} as part
* of a touch event. The application may choose to perform some different action
* if the touch event starts due to a secondary button click, such as presenting a
* context menu.
* </p>
*
* <h3>Batching</h3>
* <p>
* For efficiency, motion events with {@link #ACTION_MOVE} may batch together
* multiple movement samples within a single object. The most current
* pointer coordinates are available using {@link #getX(int)} and {@link #getY(int)}.
* Earlier coordinates within the batch are accessed using {@link #getHistoricalX(int, int)}
* and {@link #getHistoricalY(int, int)}. The coordinates are "historical" only
* insofar as they are older than the current coordinates in the batch; however,
* they are still distinct from any other coordinates reported in prior motion events.
* To process all coordinates in the batch in time order, first consume the historical
* coordinates then consume the current coordinates.
* </p><p>
* Example: Consuming all samples for all pointers in a motion event in time order.
* </p><p><pre><code>
* void printSamples(MotionEvent ev) {
* final int historySize = ev.getHistorySize();
* final int pointerCount = ev.getPointerCount();
* for (int h = 0; h < historySize; h++) {
* System.out.printf("At time %d:", ev.getHistoricalEventTime(h));
* for (int p = 0; p < pointerCount; p++) {
* System.out.printf(" pointer %d: (%f,%f)",
* ev.getPointerId(p), ev.getHistoricalX(p, h), ev.getHistoricalY(p, h));
* }
* }
* System.out.printf("At time %d:", ev.getEventTime());
* for (int p = 0; p < pointerCount; p++) {
* System.out.printf(" pointer %d: (%f,%f)",
* ev.getPointerId(p), ev.getX(p), ev.getY(p));
* }
* }
* </code></pre></p>
*
* <h3>Device Types</h3>
* <p>
* The interpretation of the contents of a MotionEvent varies significantly depending
* on the source class of the device.
* </p><p>
* On pointing devices with source class {@link InputDevice#SOURCE_CLASS_POINTER}
* such as touch screens, the pointer coordinates specify absolute
* positions such as view X/Y coordinates. Each complete gesture is represented
* by a sequence of motion events with actions that describe pointer state transitions
* and movements. A gesture starts with a motion event with {@link #ACTION_DOWN}
* that provides the location of the first pointer down. As each additional
* pointer that goes down or up, the framework will generate a motion event with
* {@link #ACTION_POINTER_DOWN} or {@link #ACTION_POINTER_UP} accordingly.
* Pointer movements are described by motion events with {@link #ACTION_MOVE}.
* Finally, a gesture end either when the final pointer goes up as represented
* by a motion event with {@link #ACTION_UP} or when gesture is canceled
* with {@link #ACTION_CANCEL}.
* </p><p>
* Some pointing devices such as mice may support vertical and/or horizontal scrolling.
* A scroll event is reported as a generic motion event with {@link #ACTION_SCROLL} that
* includes the relative scroll offset in the {@link #AXIS_VSCROLL} and
* {@link #AXIS_HSCROLL} axes. See {@link #getAxisValue(int)} for information
* about retrieving these additional axes.
* </p><p>
* On trackball devices with source class {@link InputDevice#SOURCE_CLASS_TRACKBALL},
* the pointer coordinates specify relative movements as X/Y deltas.
* A trackball gesture consists of a sequence of movements described by motion
* events with {@link #ACTION_MOVE} interspersed with occasional {@link #ACTION_DOWN}
* or {@link #ACTION_UP} motion events when the trackball button is pressed or released.
* </p><p>
* On joystick devices with source class {@link InputDevice#SOURCE_CLASS_JOYSTICK},
* the pointer coordinates specify the absolute position of the joystick axes.
* The joystick axis values are normalized to a range of -1.0 to 1.0 where 0.0 corresponds
* to the center position. More information about the set of available axes and the
* range of motion can be obtained using {@link InputDevice#getMotionRange}.
* Some common joystick axes are {@link #AXIS_X}, {@link #AXIS_Y},
* {@link #AXIS_HAT_X}, {@link #AXIS_HAT_Y}, {@link #AXIS_Z} and {@link #AXIS_RZ}.
* </p><p>
* Refer to {@link InputDevice} for more information about how different kinds of
* input devices and sources represent pointer coordinates.
* </p>
*
* <h3>Consistency Guarantees</h3>
* <p>
* Motion events are always delivered to views as a consistent stream of events.
* What constitutes a consistent stream varies depending on the type of device.
* For touch events, consistency implies that pointers go down one at a time,
* move around as a group and then go up one at a time or are canceled.
* </p><p>
* While the framework tries to deliver consistent streams of motion events to
* views, it cannot guarantee it. Some events may be dropped or modified by
* containing views in the application before they are delivered thereby making
* the stream of events inconsistent. Views should always be prepared to
* handle {@link #ACTION_CANCEL} and should tolerate anomalous
* situations such as receiving a new {@link #ACTION_DOWN} without first having
* received an {@link #ACTION_UP} for the prior gesture.
* </p>
*/
export class MotionEvent {
/**
* An invalid pointer id.
*
* This value (-1) can be used as a placeholder to indicate that a pointer id
* has not been assigned or is not available. It cannot appear as
* a pointer id inside a {@link MotionEvent}.
*/
static INVALID_POINTER_ID:number = -1;
static ACTION_MASK = 0xff;
static ACTION_DOWN = 0;
static ACTION_UP = 1;
static ACTION_MOVE = 2;
static ACTION_CANCEL = 3;
static ACTION_OUTSIDE = 4;
static ACTION_POINTER_DOWN = 5;
static ACTION_POINTER_UP = 6;
static ACTION_HOVER_MOVE = 7;
static ACTION_SCROLL = 8;
static ACTION_HOVER_ENTER = 9;
static ACTION_HOVER_EXIT = 10;
static EDGE_TOP = 0x00000001;
static EDGE_BOTTOM = 0x00000002;
static EDGE_LEFT = 0x00000004;
static EDGE_RIGHT = 0x00000008;
static ACTION_POINTER_INDEX_MASK = 0xff00;
static ACTION_POINTER_INDEX_SHIFT = 8;
static AXIS_VSCROLL = 9;
static AXIS_HSCROLL = 10;
static HistoryMaxSize = 10;
private static TouchMoveRecord = new Map<number, Array<Touch>>();// (id, [])
mAction = 0;
mEdgeFlags = 0;
mDownTime = 0;
mEventTime = 0;
//mActiveActionIndex = 0;
mActivePointerId = 0;
private mTouchingPointers:Array<Touch>;
mXOffset = 0;
mYOffset = 0;
_activeTouch:any;
//_event:any;
private _axisValues = new Map<number, number>();
static obtainWithTouchEvent(e, action:number):MotionEvent {
let event = new MotionEvent();
event.initWithTouch(e, action);
return event;
}
static obtain(event:MotionEvent):MotionEvent {
let newEv = new MotionEvent();
Object.assign(newEv, event);
return newEv;
}
static obtainWithAction(downTime:number, eventTime:number, action:number, x:number, y:number, metaState=0):MotionEvent {
let newEv = new MotionEvent();
newEv.mAction = action;
newEv.mDownTime = downTime;
newEv.mEventTime = eventTime;
let touch:Touch = {
//identifier: 0,
id_fix: 0,
target: null,
screenX: x,
screenY: y,
clientX: x,
clientY: y,
pageX: x,
pageY: y
};
newEv.mTouchingPointers = [touch];
return newEv;
}
private static IdIndexCache = new Map<number, number>();
initWithTouch(event, baseAction:number, windowBound = new Rect() ) {
let e = fixEventId(event);
let now = android.os.SystemClock.uptimeMillis();
//get actionIndex
let action = baseAction;
let actionIndex = -1;
let activeTouch = e.changedTouches[0];
this._activeTouch = activeTouch;
let activePointerId = activeTouch.id_fix;
if (activePointerId == null) console.warn('activePointerId null, activeTouch.identifier: ' + activeTouch['identifier']);
for (let i = 0, length = e.touches.length; i < length; i++) {
if (e.touches[i].id_fix === activePointerId) {
actionIndex = i;
MotionEvent.IdIndexCache.set(activePointerId, i);//cache the index, action_up will use
break;
}
}
if (actionIndex < 0 && (baseAction === MotionEvent.ACTION_UP||baseAction === MotionEvent.ACTION_CANCEL)) {
//if action is touchend, use last index (because it is not exist in webkit event.touches)
actionIndex = MotionEvent.IdIndexCache.get(activePointerId);
}
if (actionIndex < 0) throw Error('not find action index');
//touch move record
switch (baseAction) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
MotionEvent.TouchMoveRecord.set(activePointerId, []);
break;
case MotionEvent.ACTION_MOVE:
let moveHistory = MotionEvent.TouchMoveRecord.get(activePointerId);
if (moveHistory){
activeTouch.mEventTime = now;
moveHistory.push(activeTouch);
if(moveHistory.length>MotionEvent.HistoryMaxSize) moveHistory.shift();
}
break;
}
this.mTouchingPointers = Array.from(e.touches);
if(baseAction === MotionEvent.ACTION_UP || baseAction === MotionEvent.ACTION_CANCEL){//add the touch end to touching list
this.mTouchingPointers.splice(actionIndex, 0, activeTouch);
}
//check if ACTION_POINTER_UP/ACTION_POINTER_DOWN, and mask the action
if (this.mTouchingPointers.length>1) {
//the event is not the first event on screen
switch (action) {
case MotionEvent.ACTION_DOWN:
action = MotionEvent.ACTION_POINTER_DOWN;
action = actionIndex << MotionEvent.ACTION_POINTER_INDEX_SHIFT | action;
break;
case MotionEvent.ACTION_UP:
action = MotionEvent.ACTION_POINTER_UP;
action = actionIndex << MotionEvent.ACTION_POINTER_INDEX_SHIFT | action;
break;
}
}
//let lastAction = this.mAction;
// index & id to action
this.mAction = action;
//this.mActiveActionIndex = actionIndex;
this.mActivePointerId = activePointerId;
if (action == MotionEvent.ACTION_DOWN) {
this.mDownTime = now;
}
this.mEventTime = now;
const density = android.content.res.Resources.getSystem().getDisplayMetrics().density;
this.mXOffset = this.mYOffset = 0;
//set edge flag
let edgeFlag = 0;
let unScaledX = activeTouch.pageX;
let unScaledY = activeTouch.pageY;
let edgeSlop = ViewConfiguration.EDGE_SLOP;
tempBound.set(windowBound);
tempBound.right = tempBound.left + edgeSlop;
if(tempBound.contains(unScaledX, unScaledY)){
edgeFlag |= MotionEvent.EDGE_LEFT;
}
tempBound.set(windowBound);
tempBound.bottom = tempBound.top + edgeSlop;
if(tempBound.contains(unScaledX, unScaledY)){
edgeFlag |= MotionEvent.EDGE_TOP;
}
tempBound.set(windowBound);
tempBound.left = tempBound.right - edgeSlop;
if(tempBound.contains(unScaledX, unScaledY)){
edgeFlag |= MotionEvent.EDGE_RIGHT;
}
tempBound.set(windowBound);
tempBound.top = tempBound.bottom - edgeSlop;
if(tempBound.contains(unScaledX, unScaledY)){
edgeFlag |= MotionEvent.EDGE_BOTTOM;
}
this.mEdgeFlags = edgeFlag;
}
initWithMouseWheel(e:WheelEvent){
this.mAction = MotionEvent.ACTION_SCROLL;
this.mActivePointerId = 0;
let touch:Touch = {
//identifier: 0,
id_fix: 0,
target: null,
screenX: e.screenX,
screenY: e.screenY,
clientX: e.clientX,
clientY: e.clientY,
pageX: e.pageX,
pageY: e.pageY
};
this.mTouchingPointers = [touch];
this.mDownTime = this.mEventTime = android.os.SystemClock.uptimeMillis();
this.mXOffset = this.mYOffset = 0;
this._axisValues.clear();
this._axisValues.set(MotionEvent.AXIS_VSCROLL, -e.deltaY);
this._axisValues.set(MotionEvent.AXIS_HSCROLL, -e.deltaX);
}
/**
* Recycle the MotionEvent, to be re-used by a later caller. After calling
* this function you must not ever touch the event again.
*/
recycle() {
//TODO recycle motionEvent
}
/**
* Return the kind of action being performed -- one of either
* {@link #ACTION_DOWN}, {@link #ACTION_MOVE}, {@link #ACTION_UP}, or
* {@link #ACTION_CANCEL}. Consider using {@link #getActionMasked}
* and {@link #getActionIndex} to retrieve the separate masked action
* and pointer index.
*/
getAction():number {
return this.mAction;
}
/**
* Return the masked action being performed, without pointer index
* information. May be any of the actions: {@link #ACTION_DOWN},
* {@link #ACTION_MOVE}, {@link #ACTION_UP}, {@link #ACTION_CANCEL},
* {@link #ACTION_POINTER_DOWN}, or {@link #ACTION_POINTER_UP}.
* Use {@link #getActionIndex} to return the index associated with
* pointer actions.
*/
getActionMasked():number {
return this.mAction & MotionEvent.ACTION_MASK;
}
getActionIndex():number {
return (this.mAction & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
}
//return in ms(start time of event stream)
getDownTime():number {
return this.mDownTime;
}
//return in ms
getEventTime():number {
return this.mEventTime;
}
getX(pointerIndex = 0):number {
let density = android.content.res.Resources.getDisplayMetrics().density;
return (this.mTouchingPointers[pointerIndex].pageX) * density + this.mXOffset;
}
getY(pointerIndex = 0):number {
let density = android.content.res.Resources.getDisplayMetrics().density;
return (this.mTouchingPointers[pointerIndex].pageY) * density + this.mYOffset;
}
getPointerCount():number {
return this.mTouchingPointers.length;
}
getPointerId(pointerIndex:number):number {
return this.mTouchingPointers[pointerIndex].id_fix;
}
findPointerIndex(pointerId:number):number {
for (let i = 0, length = this.mTouchingPointers.length; i < length; i++) {
if (this.mTouchingPointers[i].id_fix === pointerId) {
return i;
}
}
return -1;
}
getRawX():number {
let density = android.content.res.Resources.getDisplayMetrics().density;
return (this.mTouchingPointers[0].pageX) * density;
}
getRawY():number {
let density = android.content.res.Resources.getDisplayMetrics().density;
return (this.mTouchingPointers[0].pageY) * density;
}
getHistorySize(id=this.mActivePointerId):number {
let moveHistory = MotionEvent.TouchMoveRecord.get(id);
return moveHistory ? moveHistory.length : 0;
}
getHistoricalX(pointerIndex:number, pos:number):number {
let density = android.content.res.Resources.getDisplayMetrics().density;
let moveHistory = MotionEvent.TouchMoveRecord.get(this.mTouchingPointers[pointerIndex].id_fix);
return (moveHistory[pos].pageX) * density + this.mXOffset;
}
getHistoricalY(pointerIndex:number, pos:number):number {
let density = android.content.res.Resources.getDisplayMetrics().density;
let moveHistory = MotionEvent.TouchMoveRecord.get(this.mTouchingPointers[pointerIndex].id_fix);
return (moveHistory[pos].pageY) * density + this.mYOffset;
}
getHistoricalEventTime(pos:number):number;
getHistoricalEventTime(pointerIndex:number, pos:number):number;
getHistoricalEventTime(...args):number{
let pos, activePointerId;
if(args.length===1){
pos = args[0];
activePointerId = this.mActivePointerId;
}else{
pos = args[1];
activePointerId = this.getPointerId(args[0]);
}
let moveHistory = MotionEvent.TouchMoveRecord.get(activePointerId);
return moveHistory[pos].mEventTime;
}
getTouchMajor(pointerIndex?:number):number {
return Math.floor(android.content.res.Resources.getDisplayMetrics().density);//no touch major impl
}
getHistoricalTouchMajor(pointerIndex?:number, pos?:number):number {
return Math.floor(android.content.res.Resources.getDisplayMetrics().density);//no touch major impl
}
/**
* Returns a bitfield indicating which edges, if any, were touched by this
* MotionEvent. For touch events, clients can use this to determine if the
* user's finger was touching the edge of the display.
*
* @see #EDGE_LEFT
* @see #EDGE_TOP
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
getEdgeFlags():number {
return this.mEdgeFlags;
}
/**
* Sets the bitfield indicating which edges, if any, were touched by this
* MotionEvent.
*
* @see #getEdgeFlags()
*/
setEdgeFlags(flags:number) {
this.mEdgeFlags = flags;
}
setAction(action:number) {
this.mAction = action;
}
isTouchEvent():boolean{
let action = this.getActionMasked();
switch (action){
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_OUTSIDE:
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_POINTER_UP:
return true;
}
return false;
}
isPointerEvent():boolean{
return true;//all event was pointer event now
}
offsetLocation(deltaX:number, deltaY:number) {
this.mXOffset += deltaX;
this.mYOffset += deltaY;
}
setLocation(x:number, y:number) {
this.mXOffset = x - this.getRawX();
this.mYOffset = y - this.getRawY();
}
getPointerIdBits():number {
let idBits = 0;
let pointerCount = this.getPointerCount();
for (let i = 0; i < pointerCount; i++) {
idBits |= 1 << this.getPointerId(i);
}
return idBits;
}
split(idBits:number):MotionEvent {
let ev = MotionEvent.obtain(this);
let oldPointerCount = this.getPointerCount();
const oldAction = this.getAction();
const oldActionMasked = oldAction & MotionEvent.ACTION_MASK;
let newPointerIds = [];
for (let i = 0; i < oldPointerCount; i++) {
let pointerId = this.getPointerId(i);
let idBit = 1 << pointerId;
if ((idBit & idBits) != 0) {
newPointerIds.push(pointerId);
}
}
let newActionPointerIndex = newPointerIds.indexOf(this.mActivePointerId);
let newPointerCount = newPointerIds.length;
let newAction;
if (oldActionMasked == MotionEvent.ACTION_POINTER_DOWN || oldActionMasked == MotionEvent.ACTION_POINTER_UP) {
if (newActionPointerIndex < 0) {
// An unrelated pointer changed.
newAction = MotionEvent.ACTION_MOVE;
} else if (newPointerCount == 1) {
// The first/last pointer went down/up.
newAction = oldActionMasked == MotionEvent.ACTION_POINTER_DOWN
? MotionEvent.ACTION_DOWN : MotionEvent.ACTION_UP;
} else {
// A secondary pointer went down/up.
newAction = oldActionMasked | (newActionPointerIndex << MotionEvent.ACTION_POINTER_INDEX_SHIFT);
}
} else {
// Simple up/down/cancel/move or other motion action.
newAction = oldAction;
}
ev.mAction = newAction;
ev.mTouchingPointers = this.mTouchingPointers.filter((item:Touch)=> {
return newPointerIds.indexOf(item.id_fix) >= 0;
});
return ev;
}
getAxisValue(axis:number):number{
let value = this._axisValues.get(axis);
return value ? value : 0;
}
toString() {
return "MotionEvent{action=" + this.getAction() + " x=" + this.getX()
+ " y=" + this.getY() + "}";
}
}
} | the_stack |
import should from "should";
import { ExpectT, IsSameT } from "type-ops";
import Adapt, {
BuiltinProps,
callFirstInstanceWithMethod,
callInstanceMethod,
callNextInstanceWithMethod,
Group,
handle,
Handle,
Style,
useImperativeMethods,
useMethod,
} from "../../src";
import { notReplacedByStyle } from "../../src/hooks";
import { doBuild } from "../testlib";
interface Inst1 {
value: string;
func: () => "funcreturn";
optfunc?: () => "optfuncreturn";
}
interface Inst2 {
getVal?(): number;
add?(x: number, y: number): number;
}
describe("useMethod - 2 parameters", () => {
it("Should return type include undefined", () => {
function tester(h: Handle<Inst1>) {
const ret = useMethod(h, "func");
// Compile-time type test
true as ExpectT<IsSameT<typeof ret, "funcreturn" | undefined>, true>;
}
should(tester).be.ok();
});
it("Should allow null handle", () => {
function tester(h: Handle<Inst1> | null) {
const ret = useMethod(h, "func");
// Compile-time type test
true as ExpectT<IsSameT<typeof ret, "funcreturn" | undefined>, true>;
}
should(tester).be.ok();
});
it("Should allow calling optional instance function", () => {
function tester(h: Handle<Inst1>) {
const ret = useMethod(h, "optfunc");
// Compile-time type test
true as ExpectT<IsSameT<typeof ret, "optfuncreturn" | undefined>, true>;
}
should(tester).be.ok();
});
it("Should generic Handle return type any", () => {
function tester(h: Handle) {
const ret = useMethod(h, "somefunc");
// Compile-time type test
true as ExpectT<IsSameT<typeof ret, any>, true>;
}
should(tester).be.ok();
});
it("Should explicit type param return explict type or undefined", () => {
function tester(h: Handle) {
const ret = useMethod<"explicit">(h, "func");
// Compile-time type test
true as ExpectT<IsSameT<typeof ret, "explicit" | undefined>, true>;
}
should(tester).be.ok();
});
it("Should return undefined and computed value", async () => {
const val: (number | undefined)[] = [];
function Test(props: Partial<BuiltinProps>) {
const hand: Handle<Inst2> = props.handle!;
useImperativeMethods<Inst2>(() => ({
getVal: () => 10
}));
val.push(useMethod(hand, "getVal"));
return null;
}
await Adapt.build(<Test />, null);
should(val).eql([undefined, 10]);
});
it("Should deal with generic handle without default", async () => {
const val: (number | undefined)[] = [];
function Test(props: Partial<BuiltinProps>) {
const hand: Handle = props.handle!;
useImperativeMethods<Inst2>(() => ({
getVal: () => 10
}));
val.push(useMethod(hand, "getVal"));
return null;
}
await Adapt.build(<Test />, null);
should(val).eql([undefined, 10]);
});
});
describe("useMethod - 3 parameters", () => {
it("Should allow null handle", () => {
function tester(h: Handle<Inst1> | null) {
const ret = useMethod(h, "init", "func", 1, 2);
// Compile-time type test
true as ExpectT<IsSameT<typeof ret, "funcreturn" | "init">, true>;
}
should(tester).be.ok();
});
it("Should return type include default", () => {
function tester(h: Handle<Inst1>) {
const ret = useMethod(h, "init", "func");
// Compile-time type test
true as ExpectT<IsSameT<typeof ret, "funcreturn" | "init">, true>;
}
should(tester).be.ok();
});
it("Should generic Handle return type any", () => {
function tester(h: Handle) {
const ret = useMethod(h, "init", "somefunc", 1, 2);
// Compile-time type test
true as ExpectT<IsSameT<typeof ret, any>, true>;
}
should(tester).be.ok();
});
it("Should explicit type param return explict type", () => {
function tester(h: Handle) {
const ret = useMethod<"explicit" | "default">(h, "default", "somefunc", 1, 2);
// Compile-time type test
true as ExpectT<IsSameT<typeof ret, "explicit" | "default">, true>;
}
should(tester).be.ok();
});
it("Should return default and computed value", async () => {
const val: number[] = [];
function Test(props: Partial<BuiltinProps>) {
const hand: Handle<Inst2> = props.handle!;
useImperativeMethods<Inst2>(() => ({
getVal: () => 10
}));
val.push(useMethod(hand, 3, "getVal"));
return null;
}
await Adapt.build(<Test />, null);
should(val).eql([3, 10]);
});
it("Should forward extra arguments", async () => {
const val: number[] = [];
function Test(props: Partial<BuiltinProps>) {
const hand: Handle<Inst2> = props.handle!;
useImperativeMethods<Inst2>(() => ({
add: (x, y) => x + y
}));
val.push(useMethod(hand, 5, "add", 6, 5));
return null;
}
await Adapt.build(<Test />, null);
should(val).eql([5, 11]);
});
it("Should deal with generic handle with default", async () => {
const val: number[] = [];
function Test(props: Partial<BuiltinProps>) {
const hand: Handle = props.handle!;
useImperativeMethods<Inst2>(() => ({
getVal: () => 10
}));
val.push(useMethod(hand, 3, "getVal"));
return null;
}
await Adapt.build(<Test />, null);
should(val).eql([3, 10]);
});
});
describe("notReplacedByStyle", () => {
it("Should return instance of first built element in style chain", async () => {
//FIXME(manishv) This is a hack to allow style sheets to provide reasonable semantics
//under current operation. We need to reevaluate the sematnics of a style sheet and
//implement those better semantics. This behavior can then fall where it may.
const hand = handle();
function ReplaceMe1() { return null; }
function ReplaceMe2() { return null; }
const inst = { field: "Hi there!" };
function Final() {
useImperativeMethods(() => inst);
return null;
}
const root = <ReplaceMe1 handle={hand} />;
const style = <Style>
{ReplaceMe1} {Adapt.rule(() => <ReplaceMe2 />)}
{ReplaceMe2} {Adapt.rule(() => <Final />)}
</Style>;
await doBuild(root, { style, nullDomOk: true });
if (hand.mountedOrig === null) throw should(hand.mountedOrig).not.Null();
if (hand.mountedOrig === undefined) throw should(hand.mountedOrig).not.Undefined();
const el = hand.nextMounted(notReplacedByStyle());
if (el === null) throw should(el).not.be.Null();
if (el === undefined) throw should(el).not.be.Undefined();
should(el.instance).eql(inst);
});
});
describe("callInstanceMethod family", () => {
/*
* Instance methods:
* all: Implemented by all components
* none: Implemented by no components
* only*: Implemented by only the named component
*/
function ReplaceMe1() {
useImperativeMethods(() => ({
all: () => "ReplaceMe1",
onlyReplaceMe1: () => "ReplaceMe1",
}));
return null;
}
function ReplaceMe2() {
useImperativeMethods(() => ({
all: () => "ReplaceMe2",
onlyReplaceMe2: () => "ReplaceMe2",
}));
return null;
}
function Build1() {
useImperativeMethods(() => ({
all: () => "Build1",
onlyBuild1: () => "Build1",
}));
return <Build2 />;
}
function Build2() {
useImperativeMethods(() => ({
all: () => "Build2",
onlyBuild2: () => "Build2",
}));
return <Final />;
}
function Final() {
useImperativeMethods(() => ({
all: () => "Final",
onlyFinal: () => "Final",
}));
return null;
}
function ReplaceNull() {
useImperativeMethods(() => ({
all: () => "ReplaceNull",
onlyReplaceNull: () => "ReplaceNull",
}));
return null;
}
let hFirst: Handle;
let hSecond: Handle;
let hThird: Handle;
before(async () => {
hFirst = handle();
hSecond = handle();
hThird = handle();
const root =
<Group>
<ReplaceMe1 handle={hFirst} />
<ReplaceNull handle={hSecond} />
<Build1 handle={hThird} />
</Group>;
const style = <Style>
{ReplaceMe1} {Adapt.rule(() => <ReplaceMe2 />)}
{ReplaceMe2} {Adapt.rule(() => <Final />)}
{ReplaceNull} {Adapt.rule(() => null)}
</Style>;
await doBuild(root, { style, nullDomOk: true });
if (hFirst.mountedOrig == null) throw should(hFirst.mountedOrig).be.ok();
if (hSecond.mountedOrig == null) throw should(hSecond.mountedOrig).be.ok();
if (hThird.mountedOrig == null) throw should(hThird.mountedOrig).be.ok();
});
it("Should callInstanceMethod return default on unassociated handle", () => {
const hand = handle();
should(callInstanceMethod(hand, "DEFAULT", "all")).equal("DEFAULT");
});
it("Should callInstanceMethod skip elements replaced by style", () => {
should(callInstanceMethod(hFirst, "DEFAULT", "all")).equal("Final");
});
it("Should callInstanceMethod return default if all elements replaced by style", () => {
should(callInstanceMethod(hSecond, "DEFAULT", "all")).equal("DEFAULT");
});
it("Should callInstanceMethod call method on mountedOrig", () => {
should(callInstanceMethod(hThird, "DEFAULT", "all")).equal("Build1");
});
it("Should callFirstInstanceWithMethod return default on unassociated handle", () => {
const hand = handle();
should(callFirstInstanceWithMethod(hand, "DEFAULT", "all")).equal("DEFAULT");
});
it("Should callFirstInstanceWithMethod skip elements replaced by style", () => {
should(callFirstInstanceWithMethod(hFirst, "DEFAULT", "all")).equal("Final");
});
it("Should callFirstInstanceMethod return default if all elements replaced by style", () => {
should(callFirstInstanceWithMethod(hSecond, "DEFAULT", "all")).equal("DEFAULT");
});
it("Should callFirstInstanceWithMethod call method on mountedOrig", () => {
should(callFirstInstanceWithMethod(hThird, "DEFAULT", "all")).equal("Build1");
});
it("Should callFirstInstanceWithMethod skip elements without method", () => {
should(callFirstInstanceWithMethod(hThird, "DEFAULT", "onlyBuild2")).equal("Build2");
should(callFirstInstanceWithMethod(hThird, "DEFAULT", "onlyFinal")).equal("Final");
});
it("Should callFirstInstanceWithMethod return default if no element has method", () => {
should(callFirstInstanceWithMethod(hFirst, "DEFAULT", "none")).equal("DEFAULT");
should(callFirstInstanceWithMethod(hThird, "DEFAULT", "none")).equal("DEFAULT");
});
it("Should callNextInstanceWithMethod throw on unassociated handle", () => {
const hand = handle();
should(() => callNextInstanceWithMethod(hand, "DEFAULT", "all"))
.throwError(`Cannot find next instance when calling all: handle is not associated with any element`);
});
it("Should callNextInstanceWithMethod skip elements replaced by style", () => {
should(callNextInstanceWithMethod(hFirst, "DEFAULT", "all")).equal("Final");
});
it("Should callNextInstanceMethod return default if all elements replaced by style", () => {
should(callNextInstanceWithMethod(hSecond, "DEFAULT", "all")).equal("DEFAULT");
});
it("Should callNextInstanceWithMethod skip method on mountedOrig", () => {
should(callNextInstanceWithMethod(hThird, "DEFAULT", "all")).equal("Build2");
});
it("Should callNextInstanceWithMethod skip elements without method", () => {
should(callNextInstanceWithMethod(hThird, "DEFAULT", "onlyBuild2")).equal("Build2");
should(callNextInstanceWithMethod(hThird, "DEFAULT", "onlyFinal")).equal("Final");
});
it("Should callNextInstanceWithMethod return default if no element has method", () => {
should(callNextInstanceWithMethod(hFirst, "DEFAULT", "none")).equal("DEFAULT");
should(callNextInstanceWithMethod(hThird, "DEFAULT", "none")).equal("DEFAULT");
});
it("Should callNextInstanceWithMethod return default if only mountedOrig has method", () => {
should(callNextInstanceWithMethod(hThird, "DEFAULT", "onlyBuild1")).equal("DEFAULT");
});
}); | the_stack |
import gql from 'graphql-tag';
import { itAsync } from '../../../testing';
import { InMemoryCache } from '../inMemoryCache';
import { visit, FragmentDefinitionNode } from 'graphql';
import { hasOwn } from '../helpers';
describe('fragment matching', () => {
it('can match exact types with or without possibleTypes', () => {
const cacheWithoutPossibleTypes = new InMemoryCache({
addTypename: true,
});
const cacheWithPossibleTypes = new InMemoryCache({
addTypename: true,
possibleTypes: {
Animal: ['Cat', 'Dog'],
},
});
const query = gql`
query AnimalNames {
animals {
id
name
...CatDetails
}
}
fragment CatDetails on Cat {
livesLeft
killsToday
}
`;
const data = {
animals: [
{
__typename: 'Cat',
id: 1,
name: 'Felix',
livesLeft: 8,
killsToday: 2,
},
{
__typename: 'Dog',
id: 2,
name: 'Baxter',
},
],
};
cacheWithoutPossibleTypes.writeQuery({ query, data });
expect(cacheWithoutPossibleTypes.readQuery({ query })).toEqual(data);
cacheWithPossibleTypes.writeQuery({ query, data });
expect(cacheWithPossibleTypes.readQuery({ query })).toEqual(data);
});
it('can match interface subtypes', () => {
const cache = new InMemoryCache({
addTypename: true,
possibleTypes: {
Animal: ['Cat', 'Dog'],
},
});
const query = gql`
query BestFriend {
bestFriend {
id
...AnimalName
}
}
fragment AnimalName on Animal {
name
}
`;
const data = {
bestFriend: {
__typename: 'Dog',
id: 2,
name: 'Beckett',
},
};
cache.writeQuery({ query, data });
expect(cache.readQuery({ query })).toEqual(data);
});
it('can match union member types', () => {
const cache = new InMemoryCache({
addTypename: true,
possibleTypes: {
Status: ['PASSING', 'FAILING', 'SKIPPED'],
},
});
const query = gql`
query {
testResults {
id
output {
... on Status {
stdout
}
... on FAILING {
stderr
}
}
}
}
`;
const data = {
testResults: [
{
__typename: 'TestResult',
id: 123,
output: {
__typename: 'PASSING',
stdout: 'ok!',
},
},
{
__typename: 'TestResult',
id: 456,
output: {
__typename: 'FAILING',
stdout: '',
stderr: 'oh no',
},
},
],
};
cache.writeQuery({ query, data });
expect(cache.readQuery({ query })).toEqual(data);
});
it('can match indirect subtypes while avoiding cycles', () => {
const cache = new InMemoryCache({
addTypename: true,
possibleTypes: {
Animal: ['Animal', 'Bug', 'Mammal'],
Bug: ['Ant', 'Spider', 'RolyPoly'],
Mammal: ['Dog', 'Cat', 'Human'],
Cat: ['Calico', 'Siamese', 'Sphynx', 'Tabby'],
},
});
const query = gql`
query {
animals {
... on Mammal {
hasFur
bodyTemperature
}
... on Bug {
isVenomous
}
}
}
`;
const data = {
animals: [
{
__typename: 'Sphynx',
hasFur: false,
bodyTemperature: 99,
},
{
__typename: 'Dog',
hasFur: true,
bodyTemperature: 102,
},
{
__typename: 'Spider',
isVenomous: 'maybe',
},
],
};
cache.writeQuery({ query, data });
expect(cache.readQuery({ query })).toEqual(data);
});
it('can match against the root Query', () => {
const cache = new InMemoryCache({
addTypename: true,
});
const query = gql`
query AllPeople {
people {
id
name
}
...PeopleTypes
}
fragment PeopleTypes on Query {
__type(name: "Person") {
name
kind
}
}
`;
const data = {
people: [
{
__typename: 'Person',
id: 123,
name: 'Ben',
},
],
__type: {
__typename: '__Type',
name: 'Person',
kind: 'OBJECT',
},
};
cache.writeQuery({ query, data });
expect(cache.readQuery({ query })).toEqual(data);
});
});
describe("policies.fragmentMatches", () => {
const warnings: any[] = [];
const { warn } = console;
beforeEach(() => {
warnings.length = 0;
console.warn = function (message: any) {
warnings.push(message);
};
});
afterEach(() => {
console.warn = warn;
});
itAsync("can infer fuzzy subtypes heuristically", (resolve, reject) => {
const cache = new InMemoryCache({
possibleTypes: {
A: ["B", "C"],
B: ["D"],
C: ["[E-Z]"],
},
});
const fragments = gql`
fragment FragA on A { a }
fragment FragB on B { b }
fragment FragC on C { c }
fragment FragD on D { d }
fragment FragE on E { e }
fragment FragF on F { f }
`;
function checkTypes(
expected: Record<string, Record<string, boolean>>,
) {
const checked = new Set<FragmentDefinitionNode>();
visit(fragments, {
FragmentDefinition(frag) {
function check(typename: string, result: boolean) {
if (result !== cache.policies.fragmentMatches(frag, typename)) {
reject(`fragment ${
frag.name.value
} should${result ? "" : " not"} have matched typename ${typename}`);
}
}
const supertype = frag.typeCondition.name.value;
expect("ABCDEF".split("")).toContain(supertype);
if (hasOwn.call(expected, supertype)) {
Object.keys(expected[supertype]).forEach(subtype => {
check(subtype, expected[supertype][subtype]);
});
checked.add(frag);
}
},
});
return checked;
}
expect(checkTypes({
A: {
A: true,
B: true,
C: true,
D: true,
E: false,
F: false,
G: false,
},
B: {
A: false,
B: true,
C: false,
D: true,
E: false,
F: false,
G: false,
},
C: {
A: false,
B: false,
C: true,
D: false,
E: false,
F: false,
G: false,
},
D: {
A: false,
B: false,
C: false,
D: true,
E: false,
F: false,
G: false,
},
E: {
A: false,
B: false,
C: false,
D: false,
E: true,
F: false,
G: false,
},
F: {
A: false,
B: false,
C: false,
D: false,
E: false,
F: true,
G: false,
},
G: {
A: false,
B: false,
C: false,
D: false,
E: false,
F: false,
G: true,
},
}).size).toBe("ABCDEF".length);
cache.writeQuery({
query: gql`
query {
objects {
...FragC
}
}
${fragments}
`,
data: {
objects: [
{ __typename: "E", c: "ce" },
{ __typename: "F", c: "cf" },
{ __typename: "G", c: "cg" },
// The /[E-Z]/ subtype pattern specified for the C supertype
// must match the entire subtype string.
{ __typename: "TooLong", c: "nope" },
// The H typename matches the regular expression for C, but it
// does not pass the heuristic test of having all the fields
// expected if FragC matched.
{ __typename: "H", h: "not c" },
],
},
});
expect(warnings).toEqual([
"Inferring subtype E of supertype C",
"Inferring subtype F of supertype C",
"Inferring subtype G of supertype C",
// Note that TooLong is not inferred here.
]);
expect(checkTypes({
A: {
A: true,
B: true,
C: true,
D: true,
E: true,
F: true,
G: true,
H: false,
},
B: {
A: false,
B: true,
C: false,
D: true,
E: false,
F: false,
G: false,
H: false,
},
C: {
A: false,
B: false,
C: true,
D: false,
E: true,
F: true,
G: true,
H: false,
},
D: {
A: false,
B: false,
C: false,
D: true,
E: false,
F: false,
G: false,
H: false,
},
E: {
A: false,
B: false,
C: false,
D: false,
E: true,
F: false,
G: false,
H: false,
},
F: {
A: false,
B: false,
C: false,
D: false,
E: false,
F: true,
G: false,
H: false,
},
G: {
A: false,
B: false,
C: false,
D: false,
E: false,
F: true,
G: true,
H: false,
},
}).size).toBe("ABCDEF".length);
expect(cache.extract()).toMatchSnapshot();
// Now add the TooLong subtype of C explicitly.
cache.policies.addPossibleTypes({
C: ["TooLong"],
});
expect(checkTypes({
A: {
A: true,
B: true,
C: true,
D: true,
E: true,
F: true,
G: true,
TooLong: true,
H: false,
},
B: {
A: false,
B: true,
C: false,
D: true,
E: false,
F: false,
G: false,
TooLong: false,
H: false,
},
C: {
A: false,
B: false,
C: true,
D: false,
E: true,
F: true,
G: true,
TooLong: true,
H: false,
},
D: {
A: false,
B: false,
C: false,
D: true,
E: false,
F: false,
G: false,
TooLong: false,
H: false,
},
E: {
A: false,
B: false,
C: false,
D: false,
E: true,
F: false,
G: false,
TooLong: false,
H: false,
},
F: {
A: false,
B: false,
C: false,
D: false,
E: false,
F: true,
G: false,
TooLong: false,
H: false,
},
G: {
A: false,
B: false,
C: false,
D: false,
E: false,
F: true,
G: true,
TooLong: false,
H: false,
},
H: {
A: false,
B: false,
C: false,
D: false,
E: false,
F: false,
G: false,
TooLong: false,
H: true,
},
}).size).toBe("ABCDEF".length);
resolve();
});
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.