text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { CollateralizedSimpleInterestTermsContract as ContractArtifacts } from "@dharmaprotocol/contracts"; import * as promisify from "tiny-promisify"; import * as Web3 from "web3"; import { BigNumber } from "../../../utils/bignumber"; import { classUtils } from "../../../utils/class_utils"; import { Web3Utils } from "../../../utils/web3_utils"; import { TxData, TxDataPayable } from "../../types"; import { BaseContract, CONTRACT_WRAPPER_ERRORS } from "./base_contract_wrapper"; export class CollateralizedSimpleInterestTermsContractContract extends BaseContract { public debtKernelAddress = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<string>( self.web3ContractInstance.debtKernelAddress.call, self.web3ContractInstance, )(); return result; }, }; public getValueRepaidToDate = { async callAsync(agreementId: string, defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.getValueRepaidToDate.call, self.web3ContractInstance, )(agreementId); return result; }, }; public DAY_LENGTH_IN_SECONDS = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.DAY_LENGTH_IN_SECONDS.call, self.web3ContractInstance, )(); return result; }, }; public debtKernel = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<string>( self.web3ContractInstance.debtKernel.call, self.web3ContractInstance, )(); return result; }, }; public MONTH_LENGTH_IN_SECONDS = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.MONTH_LENGTH_IN_SECONDS.call, self.web3ContractInstance, )(); return result; }, }; public getTermEndTimestamp = { async callAsync(_agreementId: string, defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.getTermEndTimestamp.call, self.web3ContractInstance, )(_agreementId); return result; }, }; public debtRegistry = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<string>( self.web3ContractInstance.debtRegistry.call, self.web3ContractInstance, )(); return result; }, }; public WEEK_LENGTH_IN_SECONDS = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.WEEK_LENGTH_IN_SECONDS.call, self.web3ContractInstance, )(); return result; }, }; public returnCollateral = { async sendTransactionAsync(agreementId: string, txData: TxData = {}): Promise<string> { const self = this as CollateralizedSimpleInterestTermsContractContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.returnCollateral.estimateGasAsync.bind(self, agreementId), ); const txHash = await promisify<string>( self.web3ContractInstance.returnCollateral, self.web3ContractInstance, )(agreementId, txDataWithDefaults); return txHash; }, async estimateGasAsync(agreementId: string, txData: TxData = {}): Promise<number> { const self = this as CollateralizedSimpleInterestTermsContractContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.returnCollateralAsync.estimateGas, self.web3ContractInstance, )(agreementId, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(agreementId: string, txData: TxData = {}): string { const self = this as CollateralizedSimpleInterestTermsContractContract; const abiEncodedTransactionData = self.web3ContractInstance.returnCollateralAsync.getData(); return abiEncodedTransactionData; }, }; public timestampAdjustedForGracePeriod = { async callAsync( gracePeriodInDays: BigNumber, defaultBlock?: Web3.BlockParam, ): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.timestampAdjustedForGracePeriod.call, self.web3ContractInstance, )(gracePeriodInDays); return result; }, }; public registerRepayment = { async sendTransactionAsync( agreementId: string, payer: string, beneficiary: string, unitsOfRepayment: BigNumber, tokenAddress: string, txData: TxData = {}, ): Promise<string> { const self = this as CollateralizedSimpleInterestTermsContractContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.registerRepayment.estimateGasAsync.bind( self, agreementId, payer, beneficiary, unitsOfRepayment, tokenAddress, ), ); const txHash = await promisify<string>( self.web3ContractInstance.registerRepayment, self.web3ContractInstance, )(agreementId, payer, beneficiary, unitsOfRepayment, tokenAddress, txDataWithDefaults); return txHash; }, async estimateGasAsync( agreementId: string, payer: string, beneficiary: string, unitsOfRepayment: BigNumber, tokenAddress: string, txData: TxData = {}, ): Promise<number> { const self = this as CollateralizedSimpleInterestTermsContractContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.registerRepayment.estimateGas, self.web3ContractInstance, )(agreementId, payer, beneficiary, unitsOfRepayment, tokenAddress, txDataWithDefaults); return gas; }, getABIEncodedTransactionData( agreementId: string, payer: string, beneficiary: string, unitsOfRepayment: BigNumber, tokenAddress: string, txData: TxData = {}, ): string { const self = this as CollateralizedSimpleInterestTermsContractContract; const abiEncodedTransactionData = self.web3ContractInstance.registerRepayment.getData(); return abiEncodedTransactionData; }, }; public SECONDS_IN_DAY = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.SECONDS_IN_DAY.call, self.web3ContractInstance, )(); return result; }, }; public HOUR_LENGTH_IN_SECONDS = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.HOUR_LENGTH_IN_SECONDS.call, self.web3ContractInstance, )(); return result; }, }; public repaymentRouter = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<string>( self.web3ContractInstance.repaymentRouter.call, self.web3ContractInstance, )(); return result; }, }; public INTEREST_RATE_SCALING_FACTOR = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.INTEREST_RATE_SCALING_FACTOR.call, self.web3ContractInstance, )(); return result; }, }; public NUM_AMORTIZATION_UNIT_TYPES = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.NUM_AMORTIZATION_UNIT_TYPES.call, self.web3ContractInstance, )(); return result; }, }; public registerTermStart = { async sendTransactionAsync( agreementId: string, debtor: string, txData: TxData = {}, ): Promise<string> { const self = this as CollateralizedSimpleInterestTermsContractContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.registerTermStart.estimateGasAsync.bind(self, agreementId, debtor), ); const txHash = await promisify<string>( self.web3ContractInstance.registerTermStart, self.web3ContractInstance, )(agreementId, debtor, txDataWithDefaults); return txHash; }, async estimateGasAsync( agreementId: string, debtor: string, txData: TxData = {}, ): Promise<number> { const self = this as CollateralizedSimpleInterestTermsContractContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.registerTermStart.estimateGas, self.web3ContractInstance, )(agreementId, debtor, txDataWithDefaults); return gas; }, getABIEncodedTransactionData( agreementId: string, debtor: string, txData: TxData = {}, ): string { const self = this as CollateralizedSimpleInterestTermsContractContract; const abiEncodedTransactionData = self.web3ContractInstance.registerTermStart.getData(); return abiEncodedTransactionData; }, }; public getExpectedRepaymentValue = { async callAsync( agreementId: string, timestamp: BigNumber, defaultBlock?: Web3.BlockParam, ): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.getExpectedRepaymentValue.call, self.web3ContractInstance, )(agreementId, timestamp); return result; }, }; public tokenRegistry = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<string>( self.web3ContractInstance.tokenRegistry.call, self.web3ContractInstance, )(); return result; }, }; public unpackCollateralParametersFromBytes = { async callAsync( parameters: string, defaultBlock?: Web3.BlockParam, ): Promise<[BigNumber, BigNumber, BigNumber]> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<[BigNumber, BigNumber, BigNumber]>( self.web3ContractInstance.unpackCollateralParametersFromBytes.call, self.web3ContractInstance, )(parameters); return result; }, }; public agreementToCollateralizer = { async callAsync(index: string, defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<string>( self.web3ContractInstance.agreementToCollateralizer.call, self.web3ContractInstance, )(index); return result; }, }; public unpackParametersFromBytes = { async callAsync( parameters: string, defaultBlock?: Web3.BlockParam, ): Promise<[BigNumber, BigNumber, BigNumber, BigNumber, BigNumber]> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<[BigNumber, BigNumber, BigNumber, BigNumber, BigNumber]>( self.web3ContractInstance.unpackParametersFromBytes.call, self.web3ContractInstance, )(parameters); return result; }, }; public seizeCollateral = { async sendTransactionAsync(agreementId: string, txData: TxData = {}): Promise<string> { const self = this as CollateralizedSimpleInterestTermsContractContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.seizeCollateral.estimateGasAsync.bind(self, agreementId), ); const txHash = await promisify<string>( self.web3ContractInstance.seizeCollateral, self.web3ContractInstance, )(agreementId, txDataWithDefaults); return txHash; }, async estimateGasAsync(agreementId: string, txData: TxData = {}): Promise<number> { const self = this as CollateralizedSimpleInterestTermsContractContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.seizeCollateralAsync.estimateGas, self.web3ContractInstance, )(agreementId, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(agreementId: string, txData: TxData = {}): string { const self = this as CollateralizedSimpleInterestTermsContractContract; const abiEncodedTransactionData = self.web3ContractInstance.seizeCollateralAsync.getData(); return abiEncodedTransactionData; }, }; public YEAR_LENGTH_IN_SECONDS = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.YEAR_LENGTH_IN_SECONDS.call, self.web3ContractInstance, )(); return result; }, }; public valueRepaid = { async callAsync(index: string, defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as CollateralizedSimpleInterestTermsContractContract; const result = await promisify<BigNumber>( self.web3ContractInstance.valueRepaid.call, self.web3ContractInstance, )(index); return result; }, }; constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) { super(web3ContractInstance, defaults); classUtils.bindAll(this, ["web3ContractInstance", "defaults"]); } public static async deployed( web3: Web3, defaults: Partial<TxData>, ): Promise<CollateralizedSimpleInterestTermsContractContract> { const web3Utils = new Web3Utils(web3); const currentNetwork = await web3Utils.getNetworkIdAsync(); const { abi, networks }: { abi: any; networks: any } = ContractArtifacts; if (networks[currentNetwork]) { const { address: contractAddress } = networks[currentNetwork]; const contractExists = await web3Utils.doesContractExistAtAddressAsync(contractAddress); if (contractExists) { const web3ContractInstance = web3.eth.contract(abi).at(contractAddress); return new CollateralizedSimpleInterestTermsContractContract( web3ContractInstance, defaults, ); } else { throw new Error( CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK( "CollateralizedSimpleInterestTermsContract", currentNetwork, ), ); } } else { throw new Error( CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK( "CollateralizedSimpleInterestTermsContract", currentNetwork, ), ); } } public static async at( address: string, web3: Web3, defaults: Partial<TxData>, ): Promise<CollateralizedSimpleInterestTermsContractContract> { const web3Utils = new Web3Utils(web3); const { abi }: { abi: any } = ContractArtifacts; const contractExists = await web3Utils.doesContractExistAtAddressAsync(address); const currentNetwork = await web3Utils.getNetworkIdAsync(); if (contractExists) { const web3ContractInstance = web3.eth.contract(abi).at(address); return new CollateralizedSimpleInterestTermsContractContract( web3ContractInstance, defaults, ); } else { throw new Error( CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK( "CollateralizedSimpleInterestTermsContract", currentNetwork, ), ); } } } // tslint:disable:max-file-line-count
the_stack
import * as core from '@spyglassmc/core' import type { TextDocument } from 'vscode-languageserver-textdocument' import * as ls from 'vscode-languageserver/node.js' import { InsertTextFormat } from 'vscode-languageserver/node.js' import type { MyLspInlayHint } from './types.js' const ZeroPosition: ls.Position = { line: 0, character: 0 } const ZeroRange: ls.Range = { start: ZeroPosition, end: ZeroPosition } export function color(color: core.Color): ls.Color { return ls.Color.create(...color) } export function colorInformation(info: core.ColorInfo, doc: TextDocument): ls.ColorInformation { return ls.ColorInformation.create(range(info.range, doc), color(info.color!)) } export function colorInformationArray(info: core.ColorInfo[], doc: TextDocument): ls.ColorInformation[] { return info.map(i => colorInformation(i, doc)) } export function colorPresentation(presentation: core.ColorPresentation, doc: TextDocument): ls.ColorPresentation { const edit = ls.TextEdit.replace(range(presentation.range, doc), presentation.text) return ls.ColorPresentation.create(presentation.label, edit) } export function colorPresentationArray(presentation: core.ColorPresentation[], doc: TextDocument): ls.ColorPresentation[] { return presentation.map(p => colorPresentation(p, doc)) } export function diagnostic(error: core.LanguageError, doc: TextDocument): ls.Diagnostic { const ans = ls.Diagnostic.create(range(error.range, doc), error.message, diagnosticSeverity(error.severity), undefined, 'spyglassmc') if (error.info?.deprecated) { (ans.tags ??= [])?.push(ls.DiagnosticTag.Deprecated) } if (error.info?.unnecessary) { (ans.tags ??= [])?.push(ls.DiagnosticTag.Unnecessary) } if (error.info?.codeAction) { ans.data = { codeAction: error.info?.codeAction, } } if (error.info?.related) { ans.relatedInformation = error.info?.related.map(v => ({ location: location(v.location), message: v.message, })) } return ans } export function diagnostics(errors: readonly core.LanguageError[], doc: TextDocument): ls.Diagnostic[] { return errors.map(e => diagnostic(e, doc)) } export function diagnosticSeverity(severity: core.ErrorSeverity): ls.DiagnosticSeverity { switch (severity) { case core.ErrorSeverity.Hint: return ls.DiagnosticSeverity.Hint case core.ErrorSeverity.Information: return ls.DiagnosticSeverity.Information case core.ErrorSeverity.Warning: return ls.DiagnosticSeverity.Warning case core.ErrorSeverity.Error: return ls.DiagnosticSeverity.Error } } export function documentHighlight(locations: core.SymbolLocations | undefined): ls.DocumentHighlight[] | undefined { return locations?.locations ?.filter(loc => loc.posRange) ?.map(loc => ({ range: loc.posRange! })) } export function documentSelector(meta: core.MetaRegistry): ls.DocumentSelector { const ans: ls.DocumentSelector = meta.getLanguages().map(id => ({ language: id })) return ans } export function documentSymbol(symbol: core.Symbol, symLoc: core.SymbolLocation, doc: TextDocument, hierarchicalSupport: boolean | undefined, supportedKinds: ls.SymbolKind[] = []): ls.DocumentSymbol { return { name: symbol.identifier, kind: symbolKind(symbol.category, symbol.subcategory, supportedKinds), range: symLoc.fullPosRange ?? symLoc.posRange ?? ZeroRange, selectionRange: symLoc.posRange ?? ZeroRange, children: hierarchicalSupport ? documentSymbols(symbol.members, doc, hierarchicalSupport, supportedKinds) : undefined, } } export function documentSymbols(map: core.SymbolMap = {}, doc: TextDocument, hierarchicalSupport: boolean | undefined, supportedKinds: ls.SymbolKind[] = []): ls.DocumentSymbol[] { return Object.values(map) .map(s => [s, [...s.declaration ?? [], ...s.definition ?? [], ...s.implementation ?? [], ...s.typeDefinition ?? []].find(l => l.uri === doc.uri)] as const) .filter(([_s, l]) => !!l) .map(([s, l]) => documentSymbol(s, l!, doc, hierarchicalSupport, supportedKinds)) } export function documentSymbolsFromTable(table: core.SymbolTable, doc: TextDocument, hierarchicalSupport: boolean | undefined, supportedKinds: ls.SymbolKind[] = []): ls.DocumentSymbol[] { return Object.values(table) .map(m => documentSymbols(m, doc, hierarchicalSupport, supportedKinds)) .flat() } export function documentSymbolsFromTables(tables: core.SymbolTable[], doc: TextDocument, hierarchicalSupport: boolean | undefined, supportedKinds: ls.SymbolKind[] = []): ls.DocumentSymbol[] { return tables .map(t => documentSymbolsFromTable(t, doc, hierarchicalSupport, supportedKinds)) .flat() } export function hover(hover: core.Hover, doc: TextDocument): ls.Hover { const ans: ls.Hover = { contents: markupContent(hover.markdown), range: range(hover.range, doc), } return ans } export function inlayHint(hint: core.InlayHint, doc: TextDocument): MyLspInlayHint { return { position: doc.positionAt(hint.offset), text: hint.text, } } export function inlayHints(hints: core.InlayHint[], doc: TextDocument): MyLspInlayHint[] { return hints.map(h => inlayHint(h, doc)) } export function completionItem(completion: core.CompletionItem, doc: TextDocument, requestedOffset: number, insertReplaceSupport: boolean | undefined): ls.CompletionItem { const insertText = completion.insertText ?? completion.label const canInsertReplace = insertReplaceSupport && ![core.CR, core.LF, core.CRLF].includes(insertText) const textEdit: ls.TextEdit | ls.InsertReplaceEdit = canInsertReplace ? ls.InsertReplaceEdit.create( insertText, /* insert */ range(core.Range.create(completion.range.start, requestedOffset), doc), /* replace */ range(completion.range, doc) ) : ls.TextEdit.replace(range(completion.range, doc), insertText) const ans: ls.CompletionItem = { label: completion.label, kind: completion.kind, detail: completion.detail, documentation: completion.documentation, filterText: completion.filterText, sortText: completion.sortText, textEdit, insertTextFormat: InsertTextFormat.Snippet, insertTextMode: ls.InsertTextMode.adjustIndentation, ...completion.deprecated ? { tags: [ls.CompletionItemTag.Deprecated] } : {}, } return ans } export function location(location: { uri: string, posRange: core.PositionRange }): ls.Location { return { uri: location.uri, range: location.posRange, } } export function locationLink(locations: core.SymbolLocations | undefined, doc: TextDocument, linkSupport: false): ls.Location[] | undefined export function locationLink(locations: core.SymbolLocations | undefined, doc: TextDocument, linkSupport: boolean | undefined): ls.LocationLink[] | ls.Location[] | undefined export function locationLink(locations: core.SymbolLocations | undefined, doc: TextDocument, linkSupport: boolean | undefined): ls.LocationLink[] | ls.Location[] | undefined { return locations?.locations ? linkSupport ? locations.locations.map(loc => ({ originSelectionRange: range(locations.range, doc), targetUri: loc.uri, targetRange: loc.fullPosRange ?? loc.posRange ?? ZeroRange, targetSelectionRange: loc.posRange ?? ZeroRange, })) : (locations.locations).map(loc => location({ uri: loc.uri, posRange: loc.posRange ?? ZeroRange })) : undefined } export function markupContent(value: string): ls.MarkupContent { return { kind: ls.MarkupKind.Markdown, value: value, } } export function position(offset: number, doc: TextDocument): ls.Position { return doc.positionAt(offset) } export function range(range: core.Range, doc: TextDocument): ls.Range { return ls.Range.create(position(range.start, doc), position(range.end, doc)) } export function semanticTokenModifier(modifier: core.ColorTokenModifier): number { return core.ColorTokenModifiers.indexOf(modifier) } export function semanticTokenModifiers(modifiers: readonly core.ColorTokenModifier[] = []): number { let ans = 0 for (const modifier of modifiers) { ans += 1 << semanticTokenModifier(modifier) } return ans } const MaxCharacterNumber = 2147483647 export function semanticTokens(tokens: readonly core.ColorToken[], doc: TextDocument, multilineSupport: boolean | undefined): ls.SemanticTokens { const builder = new ls.SemanticTokensBuilder() for (const token of tokens) { const pos = position(token.range.start, doc) const endPos = position(token.range.end, doc) const type = semanticTokenType(token.type) const modifiers = semanticTokenModifiers(token.modifiers) if (multilineSupport || pos.line === endPos.line) { const length = token.range.end - token.range.start builder.push(pos.line, pos.character, length, type, modifiers) } else { const firstLineRemainingLength = doc.getText(ls.Range.create(pos.line, pos.character, pos.line, MaxCharacterNumber)).length const lastLineLeadingLength = doc.getText(ls.Range.create(endPos.line, 0, endPos.line, endPos.character)).length builder.push(pos.line, pos.character, firstLineRemainingLength, type, modifiers) for (let i = pos.line + 1; i < endPos.line - 1; i++) { const lineLength = doc.getText(ls.Range.create(i, 0, i, MaxCharacterNumber)).length builder.push(i, 0, lineLength, type, modifiers) } builder.push(endPos.line, 0, lastLineLeadingLength, type, modifiers) } } return builder.build() } export function semanticTokensLegend(): ls.SemanticTokensLegend { const ans: ls.SemanticTokensLegend = { tokenTypes: core.ColorTokenTypes as unknown as string[], tokenModifiers: core.ColorTokenModifiers as unknown as string[], } return ans } export function semanticTokenType(type: core.ColorTokenType): number { return core.ColorTokenTypes.indexOf(type) } export function signatureHelp(help: core.SignatureHelp | undefined): ls.SignatureHelp | undefined { if (!help || help.signatures.length === 0) { return undefined } return { signatures: help.signatures.map(signatureInformation), activeParameter: help.signatures[help.activeSignature].activeParameter, activeSignature: help.activeSignature, } } export function signatureInformation(info: core.SignatureInfo): ls.SignatureInformation { return { label: info.label, activeParameter: info.activeParameter, documentation: info.documentation ? markupContent(info.documentation) : undefined, parameters: info.parameters.map(parameterInformation), } } export function parameterInformation(info: core.ParameterInfo): ls.ParameterInformation { return { label: info.label, documentation: info.documentation ? markupContent(info.documentation) : undefined, } } export function symbolInformation(symbol: core.Symbol, symLoc: core.SymbolLocation, supportedKinds: ls.SymbolKind[] = []): ls.SymbolInformation { return { name: symbol.identifier, kind: symbolKind(symbol.category, symbol.subcategory, supportedKinds), location: location({ uri: symLoc.uri, posRange: symLoc.fullPosRange ?? symLoc.posRange ?? ZeroRange }), } } export function symbolInformationArray(map: core.SymbolMap = {}, query: string, supportedKinds: ls.SymbolKind[] = []): ls.SymbolInformation[] { return Object.values(map) .filter(s => s.identifier.includes(query)) .map(s => [s, [...s.declaration ?? [], ...s.definition ?? [], ...s.implementation ?? [], ...s.typeDefinition ?? []][0]] as const) .filter(([_s, l]) => !!l) .map(([s, l]) => symbolInformation(s, l, supportedKinds)) } export function symbolInformationArrayFromTable(table: core.SymbolTable, query: string, supportedKinds: ls.SymbolKind[] = []): ls.SymbolInformation[] { return Object.values(table) .map(m => symbolInformationArray(m, query, supportedKinds)) .flat() } export function symbolKind(category: string, subcategory = '', supportedKinds: ls.SymbolKind[] = []): ls.SymbolKind { const UltimateFallback = ls.SymbolKind.Variable const getKind = (kind: ls.SymbolKind, fallback: ls.SymbolKind) => supportedKinds?.includes(kind) ? kind : fallback if (core.ResourceLocationCategory.is(category)) { return ls.SymbolKind.Function } if (category === 'mcdoc') { const map = new Map([ ['enum', ls.SymbolKind.Enum], ['enum_key', getKind(ls.SymbolKind.EnumMember, ls.SymbolKind.Field)], ['compound', getKind(ls.SymbolKind.Struct, ls.SymbolKind.Interface)], ['compound_key', ls.SymbolKind.Field], ['module', ls.SymbolKind.Module], ]) return map.get(subcategory) ?? UltimateFallback } const map = new Map([ ['attribute_modifier_uuid', ls.SymbolKind.Number], ['mcdoc/description', ls.SymbolKind.Constructor], ['objective', ls.SymbolKind.Variable], ['score_holder', ls.SymbolKind.Class], ['tag', ls.SymbolKind.String], ['team', ls.SymbolKind.Array], ]) return map.get(category) ?? UltimateFallback } export function textEdit(editRange: core.Range, text: string, doc: TextDocument) { return ls.TextEdit.replace(range(editRange, doc), text) }
the_stack
import { createAction, createReducer, SimpleActionCreator, BaseActionCreator, EmptyActionCreator, Action } from "redux-act"; import { Reducer } from "redux-act"; import { List, Map, fromJS } from "immutable"; import { Store } from "redux"; import { FxReducer, d, m } from "./reducer"; import { TreeMap } from "../libs/tree"; import merge from "../libs/merge"; import { isProd } from "../libs/utils"; export type ASN = Array<string | number> | string[]; export interface SchemaFormActions { [index: string]: SimpleActionCreator<any, any>; removeForm: SimpleActionCreator<ASN>; createForm: SimpleActionCreator<{ key: string, data: any, keepData?: boolean }>; updateItemData: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, data: any, meta?: any }>; updateItemMeta: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, meta: any, noChange?: boolean; }>; addItem: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, data: any }>; removeItem: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, index: number }>; moveToItem: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, curIndex: number, toIndex: number }>; removeItemData: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, meta?: boolean }>; combineActions: SimpleActionCreator<Action<any, any>[]>; removeMetaKeys: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, removeMetaKeys: Array<ASN> }>; } /** * 解析一个路径上的数据,判断数据格式,做处理 * @param state 当前的state * @param keys 数据路径 * @returns newState */ const resolveKeys = (state: Map<string, any>, keys: Array<string>): Map<string, any> => { if (state.hasIn(keys)) { return state; } for (let i = 0, n = keys.length; i < n; i++) { const mKeys = [...keys].splice(0, i + 1); // 如果key不存在,遍历生成数据结构 if (!state.hasIn(mKeys)) { mKeys.pop(); if (!state.hasIn(mKeys)) { if (keys[i].constructor === Number) { state = state.setIn(mKeys, List()); } else { state = state.setIn(mKeys, Map()); } } } else if (i < n) { // 如果key存在,则判断数据结构是否与结构一致 const data = state.getIn(mKeys); if (!Map.isMap(data) && !List.isList(data)) { if (keys[i + 1].constructor === Number) { state = state.setIn(mKeys, List()); } else { state = state.setIn(mKeys, Map()); } } } } return state; }; export class SchemaFormReducer<T> implements FxReducer { /** * 创建一个表单 */ private createForm: SimpleActionCreator<{ key: string, data: any }> = createAction<{ key: string, data: any, keepData?: boolean }>(isProd() ? "" : "创建一个表单数据"); /** * 更新一个表单数据 */ private updateItemData: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, data: any, meta?: any }> = createAction<{ parentKeys: ASN, keys: ASN, data: any, meta?: any }>(isProd() ? "" : "更新一个表单数据"); /** * 更新一个表单元数据 */ private updateItemMeta: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, meta: any, noChange?: boolean; }> = createAction<{ parentKeys: ASN, keys: ASN, meta: any }>(isProd() ? "" : "更新一个表单元数据"); /** * 添加一个元素到数组 */ private addItem: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, data: any }> = createAction<{ parentKeys: ASN, keys: ASN, data: any }>(isProd() ? "" : "添加一个数据"); /** * 从数组中删除一个元素 */ private removeItem: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, index: number }> = createAction<{ parentKeys: ASN, keys: ASN, index: number }>(isProd() ? "" : "删除一个数据"); /** * 移动一个数组元素 */ private moveToItem: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, curIndex: number, toIndex: number }> = createAction<{ parentKeys: ASN, keys: ASN, curIndex: number, toIndex: number }>(isProd() ? "" : "元素移位"); /** * 删除一个字段的数据以及元数据 */ private removeItemData: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, meta?: boolean }> = createAction<{ parentKeys: ASN, keys: ASN, meta?: boolean }>(isProd() ? "" : "删除一个字段的数据以及meta数据"); /** * 合并多个action,触发一次dispatch */ private combineActions: SimpleActionCreator<Action<any, any>[]> = createAction<Action<any, any>[]>(isProd() ? "" : "合并多个action"); /** * 清除一个form的数据 */ private removeForm: SimpleActionCreator<ASN> = createAction<ASN>(isProd() ? "" : "清除一个form的数据"); /** * 删除meta中的key值 */ private removeMetaKeys: SimpleActionCreator<{ parentKeys: ASN, keys: ASN, removeMetaKeys: Array<ASN> }> = createAction<{ parentKeys: ASN, keys: ASN, removeMetaKeys: Array<ASN> }>(isProd() ? "" : "删除meta中的key值"); /** * 构造 * @param initialState 初始化状态 */ constructor(private initialState: any) { } /** * 获取当前的actions */ public get actions(): SchemaFormActions { return { createForm: this.createForm, updateItemData: this.updateItemData, updateItemMeta: this.updateItemMeta, addItem: this.addItem, removeItem: this.removeItem, moveToItem: this.moveToItem, removeItemData: this.removeItemData, combineActions: this.combineActions, removeForm: this.removeForm, removeMetaKeys: this.removeMetaKeys }; } /** * 初始化actions * @param store Redux中的store实例 */ public init(store: Store<Map<string, any>>): void { for (const key in this.actions) { if (this.actions.hasOwnProperty(key)) { const action = this.actions[key]; if (!action.assigned()) { action.assignTo(store as any); } } } } /** * 返回当前的reducer */ public get reducer(): Reducer<any> { return createReducer<any>({ [this.createForm as any]: this.createFormHandle.bind(this), [this.updateItemData as any]: this.updateItemDataHandle.bind(this), [this.updateItemMeta as any]: this.updateItemMetaHandle.bind(this), [this.addItem as any]: this.addItemDataHandle.bind(this), [this.removeItem as any]: this.removeItemHandle.bind(this), [this.moveToItem as any]: this.moveItemHandle.bind(this), [this.removeItemData as any]: this.removeItemDataMetaHandle.bind(this), [this.combineActions as any]: this.combineActionsHandle.bind(this), [this.removeForm as any]: this.removeFormHandle.bind(this), [this.removeMetaKeys as any]: this.removeMetaKeysHandle.bind(this), }, this.initialState); } /** * 清除一个表单数据 * @param state state * @param param1 参数 */ private removeFormHandle(state: Map<string, any>, parentKeys: ASN) { let dataKeys = parentKeys; if (state.hasIn(dataKeys)) { return state.removeIn(dataKeys); } return state; } /** * 删除指定的meta中的字段 * @param state state * @param data 参数 */ private removeMetaKeysHandle(state: Map<string, any>, { parentKeys, keys, removeMetaKeys } : { parentKeys: ASN, keys: ASN, removeMetaKeys: Array<ASN> }) { let metaKeys: ASN = [...parentKeys, m]; let rootNode: TreeMap = state.getIn(metaKeys); let childNode: TreeMap | null = rootNode.containPath(keys); if (childNode && childNode.value && removeMetaKeys && removeMetaKeys.length) { removeMetaKeys.forEach((rKeys: ASN) => { if (childNode && childNode.value.hasIn(rKeys)) { childNode.value = childNode.value.removeIn(rKeys); } }); } return state; } /** * 合并多个action * @param state state * @param actions 需要调用的action */ private combineActionsHandle(state: Map<string, any>, actions: Action<any, any>[]) { state = actions.reduce((stateNew: Map<string, any>, act2: Action<any>) => { return this.reducer(stateNew, act2); }, state); return state; } /** * 删除一个字段的数据以及meta数据 * @param state 当前的state * @param param1 参数 * parentKeys 父亲的keys * keys 当前元素的keys * meta 是否要删除meta数据 */ private removeItemDataMetaHandle(state: Map<string, any>, { parentKeys, keys, meta }: any) { let dataKeys = parentKeys.concat([d, ...keys]); let metaKeys: ASN = parentKeys.concat([m]); let rootNode: TreeMap = state.getIn(metaKeys); let childNode: TreeMap | null = rootNode.containPath(keys); state = resolveKeys(state, dataKeys); if (state.hasIn(dataKeys)) { state = state.removeIn(dataKeys); } if (childNode && meta) { childNode.removeFromParent(); } return state; } /** * 创建一份表单数据 * @param state 当前的state * @param param1 参数值,key 和 data */ private createFormHandle(state: Map<string, any>, { key, data, keepData }: any): Map<string, any> { let originData = data; // 如果存在key if (state.has(key)) { // 如果要保存数据 if (keepData) { originData = state.getIn([key, "data"]); } state = state.remove(key); } const meta = new TreeMap(key, fromJS({})); const stateData = Map<string, any>({ meta: meta, data: fromJS(originData) }); return state.set(key, stateData); } /** * 修改一个数据 * 合并parrentKeys和keys,中间加入一个“data” * @param state 当前的state * @param param1 参数值,keys,parentKeys和data */ private updateItemDataHandle(state: Map<string, any>, { parentKeys, keys, data, meta }: any): Map<string, any> { let dataKeys = parentKeys.concat([d, ...keys]); state = resolveKeys(state, dataKeys); state = state.setIn(dataKeys, fromJS(data)); if (meta) { state = this.updateItemMetaHandle(state, { parentKeys, keys, meta }); } return state; } /** * 添加一个数组到List * 1. 添加数组 * 2. 修改meta中的collapsing字段为false,使得折叠的状态改变成不折叠的状态 * @param state 当前的state * @param param1 keys,parentKeys和data */ private addItemDataHandle(state: Map<string, any>, { parentKeys, keys, data }: any): Map<string, any> { const dataKeys = parentKeys.concat([d, ...keys]), metaKeys: ASN = parentKeys.concat([m]), rootNode: TreeMap = state.getIn(metaKeys), childNode: TreeMap | null = rootNode.containPath(keys); let formItemData: List<any>; state = resolveKeys(state, dataKeys); formItemData = state.getIn(dataKeys) || List(); formItemData = formItemData.push(fromJS(data)); if (childNode && childNode.value) { childNode.value = childNode.value.merge({ collapsing: false }); } return state.setIn(dataKeys, formItemData); } /** * 删除数组中的一个元素 * 1. 删除元素数组中的数据 * 2. 删除meta信息中的数据 * @param state 当前的state * @param param1 keys,parentKeys和data */ private removeItemHandle(state: Map<string, any>, { parentKeys, keys, index }: any): Map<string, any> { const dataKeys = parentKeys.concat([d, ...keys]), metaKeys: ASN = parentKeys.concat([m]), rootNode: TreeMap = state.getIn(metaKeys), childNode: TreeMap | null = rootNode.addChild(keys.concat([index])); let formItemData: List<any>; state = resolveKeys(state, dataKeys); formItemData = state.getIn(dataKeys); if (!formItemData || !List.isList(formItemData)) { return state; } if (childNode) { childNode.removeFromParent(); } return state.setIn(dataKeys, formItemData.remove(index)); } /** * 交换2个数组的位置 * 1. 交换数组数据 * 2. 交换meta中的位置信息 * @param state 当前的state * @param param1 参数 * parentKeys 父亲的keys * keys 当前item的keys * curIndex 当前item的索引 * toIndex 需要交换的item索引 */ private moveItemHandle(state: Map<string, any>, { parentKeys, keys, curIndex, toIndex }: any): Map<string, any> { const dataKeys = parentKeys.concat([d, ...keys]), metaKeys: ASN = parentKeys.concat([m]), rootNode: TreeMap = state.getIn(metaKeys), offset = (toIndex > curIndex && false ? 1 : 0); let formItemData: List<any> = state.getIn(dataKeys), childNode: TreeMap | null = rootNode.containPath(keys.concat([curIndex])), childNodeTo: TreeMap | null = rootNode.containPath(keys.concat([toIndex])); state = resolveKeys(state, dataKeys); if (!formItemData || toIndex < 0) { return state; } let curItemData = formItemData.get(curIndex); formItemData = formItemData.remove(curIndex); formItemData = formItemData.insert(toIndex - offset, curItemData); if (childNode) { childNode.insertToFromParent(toIndex); } else { if (childNodeTo) { childNodeTo.insertToFromParent(curIndex); } } return state.setIn(dataKeys, formItemData); } /** * 修改一个数据的元数据 * 通过parentKeys取得根节点 * 通过keys合成元素的节点路径,从根节点获取数据 * @param state 当前的state * @param param1 参数值,keys,parentKeys和data */ private updateItemMetaHandle(state: Map<string, any>, { parentKeys, keys, meta, noChange }: any): Map<string, any> { let metaKeys: ASN = parentKeys.concat([m]); let rootNode: TreeMap = state.getIn(metaKeys); let childNode: TreeMap | null = rootNode.containPath(keys); let value = childNode ? childNode.value : null; // 如果childNode不存在,则新建一个 if (!childNode) { childNode = rootNode.addChild(keys); } // 判断childNode,如果存在value,则合并value,否则创建value if (childNode) { if (value) { childNode.value = merge(childNode.value, fromJS(meta), { "*": "replace" }); } else { childNode.value = fromJS(meta); } } if (noChange) { return state; } // 生成新的TreeMap let newRoot = new TreeMap(rootNode.getKey(), rootNode.value); newRoot.children = rootNode.children; return state.setIn(metaKeys, newRoot); } }
the_stack
import {ChangeDetectorRef, Component, ComponentFactoryResolver, ElementRef, Input, NgZone, OnDestroy, OnInit} from '@angular/core'; import {StickyModalRef, StickyModalService, StickyPositionStrategy} from 'ngx-sticky-modal'; import {fromEvent, Subject, Subscription} from 'rxjs'; import {debounceTime, filter} from 'rxjs/operators'; import {ImgEncoder} from '../../../modules/utils/img-encoder.service'; import {NodeTreeSplit} from '../../../modules/utils/node-tree-split'; import {TreeNodeTraverse} from '../../../modules/utils/node/tree-node-traverse'; import {IWallModel} from '../../../wall/model/interfaces/wall-model.interface'; import {BaseTextBrickComponent} from '../../base-text-brick/base-text-brick.component'; import {DIVIDER_BRICK_TAG} from '../../divider-brick/divider-brick.constant'; import {BricksListComponent} from '../bricks-list/bricks-list.component'; import {ITextBrickApi} from '../text-brick-api.interface'; import {TextContextMenuComponent} from '../text-context-menu/text-context-menu.component'; @Component({ selector: 'text-brick', templateUrl: './text-brick.component.html', styleUrls: ['./text-brick.component.scss'] }) export class TextBrickComponent extends BaseTextBrickComponent implements OnInit, OnDestroy, ITextBrickApi { @Input() wallModel: IWallModel; placeholder = null; brickSelectionModalRef: StickyModalRef; contextMenuModalRef: StickyModalRef; up$ = new Subject(); down$ = new Subject(); enter$ = new Subject(); selectedTag$: Subject<string> = new Subject(); subscriptions: Subscription[] = []; selectionInfo: { ranges: Range[], selectedLink: HTMLElement }; api: ITextBrickApi = { bold: this.bold.bind(this), italic: this.italic.bind(this), createLink: this.createLink.bind(this), changeLinkUrl: this.changeLinkUrl.bind(this), isLinkSelected: this.isLinkSelected.bind(this), getSelectedLinkHref: this.getSelectedLinkHref.bind(this), saveSelection: this.saveSelection.bind(this), restoreSelection: this.restoreSelection.bind(this), unlink: this.unlink.bind(this) }; constructor(private zone: NgZone, private ngxStickyModalService: StickyModalService, private cd: ChangeDetectorRef, private componentFactoryResolver: ComponentFactoryResolver, private el: ElementRef) { super(); this.selectedTag$.subscribe((newTag) => { if (newTag) { this.hideBricksList(); this.wallModel.api.core2.turnBrickInto(this.id, newTag); if (newTag === DIVIDER_BRICK_TAG) { const newBrick = this.wallModel.api.core2.addBrickAfterBrickId(this.id, 'text'); // wait one tick for component rendering setTimeout(() => { this.wallUiApi.mode.edit.focusOnBrickId(newBrick.id); }); } } }); this.subscriptions.push( // show sub-menu for selected text fromEvent(this.el.nativeElement, 'mouseup') .pipe( filter(() => Boolean(this.scope.text.length)), debounceTime(500), filter(() => this.el.nativeElement.contains(window.getSelection().anchorNode)) ) .subscribe((e: any) => { this.onTextSelection(); }) ); } ngOnInit() { super.ngOnInit(); } ngOnDestroy() { super.ngOnDestroy(); this.subscriptions.forEach((subscription) => { subscription.unsubscribe(); }); } onBlur() { this.placeholder = null; } onFocus() { this.placeholder = 'Type \'/\' for commands'; } onKeyPress(e: KeyboardEvent) { super.onKeyPress(e); this.hideContextMenuModal(); } // open the link in new window onClick(event: MouseEvent) { const target = event.target as Node; if (this.isHTMLElement(target)) { if (target.tagName === 'A') { window.open(target.getAttribute('href'), '_blank'); } } } topKeyPressed(e: KeyboardEvent) { if (this.brickSelectionModalRef) { e.preventDefault(); e.stopPropagation(); this.up$.next(); } else { super.topKeyPressed(e); } } bottomKeyPressed(e: KeyboardEvent) { if (this.brickSelectionModalRef) { e.preventDefault(); e.stopPropagation(); this.down$.next(); } else { super.bottomKeyPressed(e); } } enterKeyPressed(e: KeyboardEvent) { if (this.brickSelectionModalRef) { this.enter$.next(); setTimeout(() => { this.hideBricksList(); }, 10); } else { if (this.isTag()) { const newTag = this.scope.text.slice(1); this.wallModel.api.core2.turnBrickInto(this.id, newTag); // d - divider tag if (newTag === 'd') { this.wallModel.api.core2.addBrickAfterBrickId(this.id, 'text'); } } else { super.enterKeyPressed(e); } } } getSplittedText(offset: number, target: Node): { left: string, right: string } { const nodeTreeSplit = new NodeTreeSplit(this.editor.nativeElement, target, offset); return { left: nodeTreeSplit.leftTree.innerHTML, right: nodeTreeSplit.rightTree.innerHTML }; } escapeKeyPressed(e: KeyboardEvent) { if (this.brickSelectionModalRef) { e.preventDefault(); e.stopPropagation(); this.hideBricksList(); } } onTextChange() { super.onTextChange(); if (this.brickSelectionModalRef) { if (!this.scope.text.length) { this.hideBricksList(); } } else if (this.scope.text[0] === '/' && this.scope.text.length === 1) { this.editor.nativeElement.blur(); const elementBoundingRect = this.el.nativeElement.getBoundingClientRect(); this.brickSelectionModalRef = this.ngxStickyModalService.open({ component: BricksListComponent, data: { text$: this.textChange, up$: this.up$, down$: this.down$, enter$: this.enter$, selectedTag$: this.selectedTag$ }, positionStrategy: { name: StickyPositionStrategy.coordinate, options: { clientX: elementBoundingRect.x, clientY: elementBoundingRect.y + 35 } }, componentFactoryResolver: this.componentFactoryResolver }); setTimeout(() => { this.editor.nativeElement.focus(); }); } } onPaste(e: ClipboardEvent) { const imageDataTransferItem = this.extractImageDataTransferItem(e.clipboardData.items); if (imageDataTransferItem) { e.preventDefault(); (new ImgEncoder(imageDataTransferItem.getAsFile())).getBase64Representation().then((imgBase64) => { this.wallModel.api.core2.turnBrickInto(this.id, 'image', { src: imgBase64 }); }); } else { super.onPaste(e); } } onTextSelection() { if (!this.contextMenuModalRef) { const selection = window.getSelection(); if (!selection.isCollapsed) { this.showContextModal(); } } } // API bold(): void { document.execCommand('bold', false); } italic(): void { document.execCommand('italic', false); } createLink(url: string): void { document.execCommand('createLink', false, url); } getSelectedLinkHref(): string { if (this.selectionInfo.selectedLink) { return this.selectionInfo.selectedLink.getAttribute('href'); } } unlink(): void { document.execCommand('unlink', false); } changeLinkUrl(url: string): void { if (this.selectionInfo.selectedLink) { this.selectionInfo.selectedLink.setAttribute('href', url); this.triggerEditorChange(); } } isLinkSelected(): boolean { return Boolean(this.selectionInfo && this.selectionInfo.selectedLink); } saveSelection() { this.selectionInfo = { selectedLink: this.getSelectedLink(), ranges: this.getSelectedRanges() }; } restoreSelection() { const sel = window.getSelection(); sel.removeAllRanges(); for (let i = 0, len = this.selectionInfo.ranges.length; i < len; ++i) { sel.addRange(this.selectionInfo.ranges[i]); } } // end API private getSelectedLink(): HTMLElement { const selection = window.getSelection(); let anchorNodeLink; let focusNodeLink; const isAnchorNodeBelongToBrick = this.el.nativeElement.contains(selection.anchorNode); const isFocusNodeBelongToBrick = this.el.nativeElement.contains(selection.focusNode); if (isAnchorNodeBelongToBrick) { anchorNodeLink = this.findParentLink(selection.anchorNode); } if (isFocusNodeBelongToBrick) { focusNodeLink = this.findParentLink(selection.focusNode); } if (anchorNodeLink) { return anchorNodeLink; } else if (focusNodeLink) { return focusNodeLink; } else if (selection.anchorNode !== selection.focusNode && isFocusNodeBelongToBrick && isAnchorNodeBelongToBrick) { return this.findLinkBetweenNodes(selection.anchorNode, selection.focusNode); } } private triggerEditorChange() { this.editor.nativeElement.dispatchEvent(new Event('input')); } private showContextModal() { this.editor.nativeElement.blur(); const sel = window.getSelection(); const elementBoundingRect = sel.getRangeAt(0).getBoundingClientRect(); this.contextMenuModalRef = this.ngxStickyModalService.open({ component: TextContextMenuComponent, data: { api: this.api }, positionStrategy: { name: StickyPositionStrategy.coordinate, options: { clientX: elementBoundingRect.left + ((elementBoundingRect.right - elementBoundingRect.left) / 2.5), clientY: elementBoundingRect.top - 35 } }, overlayConfig: { hasBackdrop: false }, componentFactoryResolver: this.componentFactoryResolver }); this.contextMenuModalRef.result.then(() => { this.hideContextMenuModal(); }, () => { this.hideContextMenuModal(); }); setTimeout(() => { this.editor.nativeElement.focus(); }); } // todo: might be as util method private getSelectedRanges(): Range[] { const sel = window.getSelection(); const ranges = []; for (let i = 0, len = sel.rangeCount; i < len; ++i) { ranges.push(sel.getRangeAt(i)); } return ranges; } private extractImageDataTransferItem(items: DataTransferItemList): DataTransferItem { let index; for (index in items) { if (items.hasOwnProperty(index)) { const item = items[index]; if (item.kind === 'file') { return item; } } } } private isTag() { return this.scope.text && this.scope.text[0] === '/' && this.wallModel.api.core2.isRegisteredBrick(this.scope.text.slice(1)); } private hideBricksList() { if (this.brickSelectionModalRef) { this.brickSelectionModalRef.close(); this.brickSelectionModalRef = null; } } private hideContextMenuModal() { if (this.contextMenuModalRef) { this.contextMenuModalRef.close(); this.contextMenuModalRef = null; } } private findParentLink(node: Node): HTMLElement { let currentNode: Node = node; let linkNode = null; while (!linkNode && currentNode !== this.el.nativeElement) { if ((currentNode as HTMLElement).tagName === 'A') { linkNode = currentNode; } currentNode = currentNode.parentElement; } return linkNode; } private findLinkBetweenNodes(nodeA: Node, nodeB: Node): HTMLElement { const treeNodeTraverse = new TreeNodeTraverse(this.editor.nativeElement); const orderedNodes = treeNodeTraverse.getPostPreOrderNodes(); let nodeAIndex = orderedNodes.indexOf(nodeA); let nodeBIndex = orderedNodes.indexOf(nodeB); if (nodeBIndex < nodeAIndex) { const temp = nodeBIndex; nodeBIndex = nodeAIndex; nodeAIndex = temp; } const orderedNodesBetweenNodes = orderedNodes.slice(nodeAIndex, nodeBIndex); const linkNodes = orderedNodesBetweenNodes.filter((node) => { if (this.isHTMLElement(node)) { return node.tagName === 'A'; } }); return linkNodes[0] as HTMLElement; } private isHTMLElement(node: Node | HTMLElement): node is HTMLElement { return (node as HTMLElement).querySelector !== undefined; } }
the_stack
import { VariableMappingBehavior } from '../interfaces/variable-mapping-type.interface'; export type PROJECT_TYPE = 'project'; export type CUSTOM_MODEL_TYPE = 'model'; export type PROCESS_TYPE = 'process'; export type FORM_TYPE = 'form'; export type CONNECTOR_TYPE = 'connector'; export type DATA_TYPE = 'data'; export type DECISION_TABLE_TYPE = 'decision'; export type UI_TYPE = 'ui'; export type FILE_TYPE = 'file'; export type SCRIPT_TYPE = 'script'; export type TRIGGER_TYPE = 'trigger'; export type FORM_WIDGET_TYPE = 'custom-form-widget'; export type MODEL_TYPE = PROCESS_TYPE | FORM_TYPE | CONNECTOR_TYPE | DATA_TYPE | DECISION_TABLE_TYPE | UI_TYPE | FILE_TYPE | SCRIPT_TYPE | TRIGGER_TYPE | CUSTOM_MODEL_TYPE | FORM_WIDGET_TYPE; export const PROJECT: PROJECT_TYPE = 'project'; export const CUSTOM_MODEL: CUSTOM_MODEL_TYPE = 'model'; export const PROCESS: PROCESS_TYPE = 'process'; export const FORM: FORM_TYPE = 'form'; export const CONNECTOR: CONNECTOR_TYPE = 'connector'; export const DATA: DATA_TYPE = 'data'; export const DECISION_TABLE: DECISION_TABLE_TYPE = 'decision'; export const UI: UI_TYPE = 'ui'; export const FILE: FILE_TYPE = 'file'; export const SCRIPT: SCRIPT_TYPE = 'script'; export const TRIGGER: TRIGGER_TYPE = 'trigger'; export const FORM_WIDGET: FORM_WIDGET_TYPE = 'custom-form-widget'; export interface Project { type: PROJECT_TYPE; id: string; name: string; creationDate: Date; createdBy: string; lastModifiedDate: Date; lastModifiedBy: string; description: string; version: string; } export type CustomModelStatus = 'ACTIVE' | 'DRAFT'; export const ACTIVE_STATUS: CustomModelStatus = 'ACTIVE'; export const INACTIVE_STATUS: CustomModelStatus = 'DRAFT'; export interface CustomTypePayload { name: string; parentName: string; title: string; description?: string; } export interface CustomAspectPayload { name: string; parentName: string; title: string; description?: string; } export interface ApiError { errorKey?: string; statusCode: number; briefSummary: string; stackTrace: string; descriptionURL: string; logId?: string; } export interface ApiErrorResponse { error: ApiError; } export interface ReleaseEntry { entry: Release; } export interface CollaboratorEntry { entry: Collaborator; } export interface Release { id: string; name: string; creationDate: Date; createdBy: string; lastModifiedDate: Date; lastModifiedBy: string; version?: string; projectName?: string; } export interface Collaborator { createdBy: string; id: string; projectId: string; username: string; } export interface MinimalModelSummary { name: string; description?: string; } export interface Model extends MinimalModelSummary { id: string; description: string; version: string; applicationId?: string; // To remove, since BE finally returns it type: string; creationDate: Date; createdBy: string; lastModifiedDate: Date; lastModifiedBy: string; projectIds: string[]; scope: ModelScope; } export enum ModelScope { PROJECT = 'PROJECT', GLOBAL = 'GLOBAL' } export interface Filter extends Model { icon?: string; } export interface Process extends Model { type: PROCESS_TYPE; extensions?: ModelExtensions; } export type ProcessVariableId = string; export enum MappingType { variable = 'variable', value = 'value', static = 'static_value' } export interface ServiceParameterMapping { [name: string]: { type: MappingType, value: any; }; } export interface ServiceParameterMappings { inputs?: ServiceParameterMapping; outputs?: ServiceParameterMapping; mappingType?: VariableMappingBehavior; } export interface ServicesParameterMappings { [serviceTaskId: string]: ServiceParameterMappings; } export interface ServicesConstants { [serviceTaskId: string]: ServicesParameterConstants; } export interface ServicesParameterConstants { [type: string]: { value: string; }; } export enum AssignmentMode { candidates = 'candidates', assignee = 'assignee' } export enum AssignmentType { static = 'static', identity = 'identity', expression = 'expression' } export interface TaskAssignment { id: string; type: AssignmentType; assignment: AssignmentMode; } export interface TaskAssignmentContent { [serviceTaskId: string]: TaskAssignment; } export interface TaskTemplates { [userTaskId: string]: TaskTemplateMapping; } export enum TaskTemplateType { file = 'file', variable = 'variable' } export interface TaskTemplate { type: TaskTemplateType; value: string; } export interface TaskTemplateMapping { assignee?: TaskTemplate; candidate?: TaskTemplate; } export interface TaskTemplateContent { tasks?: TaskTemplates; default?: TaskTemplateMapping; } export interface ProcessExtensionsContent { properties: EntityProperties; mappings: ServicesParameterMappings; constants: ServicesConstants; assignments?: TaskAssignmentContent; templates?: TaskTemplateContent; } export interface ProcessExtensions { id: string; extensions: ProcessExtensionsContent; } export interface ModelExtensions { [processID: string]: ProcessExtensionsContent; } export interface EntityProperty { id: string; name: string; label?: string; type: string; required?: boolean; value?: string; description?: string; } export interface EntityProperties { [propertiesId: string]: EntityProperty; } export type ProcessContent = string; export interface Connector extends Model { type: CONNECTOR_TYPE; template?: string; } export interface ConnectorConfigParameter { name: string; description?: string; required?: boolean; secure?: boolean; value: string; } export interface ConnectorError { name: string; description?: string; code?: string; } export interface ConnectorParameter { id: string; name: string; label?: string; description?: string; type: string; mappingValueType?: string; required?: boolean; readOnly?: boolean; value?: any; } export interface ConnectorContent { name: string; description?: string; actions?: ConnectorFeatureData; events?: ConnectorFeatureData; config?: ConnectorConfigParameter[]; errors?: ConnectorError[]; template?: string; } export interface ConnectorFeatureData { [actionId: string]: ConnectorFeature; } export interface ConnectorFeature { id: string; name: string; description?: string; inputs?: ConnectorParameter[]; outputs?: ConnectorParameter[]; model?: any; } export interface Form extends Model { type: FORM_TYPE; } export interface FormContent { formRepresentation: FormRepresentation; } export interface FormRepresentation { id: string; name: string; description: string; version?: number; formDefinition?: FormDefinition; standAlone?: boolean; contentForm?: boolean; contentType?: string; updateMetadataOnSubmit?: boolean; } export interface FormTab { id: string; title: string; visibilityCondition: any; } export interface FormOutcome { id: string; name: string; } export interface FormDefinition { tabs: FormTab[]; fields: any[]; outcomes: FormOutcome[]; metadata: {}; variables: EntityProperties[]; } export interface UiPlugin { name: string; version: string; order: string; } export interface UiContent { id: string; name: string; description?: string; 'adf-template': string; plugins: UiPlugin[]; configs?: any; extension?: UiContentExtension; } export interface UiContentExtension { $id: string; $name: string; $version: string; $vendor: string; $license: string; $description?: string; appConfig?: any; actions?: UiAction[]; rules?: UiRule[]; features?: UiFeatures; } export interface UiRule { type: UiRuleType; id?: string; value?: string; parameters?: Array<UiRule>; } export enum UiRuleType { NOT = 'core.not', EVERY = 'core.every', SOME = 'core.some', RULE = 'rule', VALUE = 'value', ARGUMENT = 'argument', OPERATOR = 'operator' } export interface UiAction { id: string; type: string; payload: any; } export interface UiFeatures { userActions?: UiFeature[]; header?: UiFeature[]; create?: UiFeature[]; toolbar?: UiFeature[]; contextMenu?: UiFeature[]; viewer?: { openWith?: UiFeature[]; toolbarActions?: UiFeature[]; shared?: { toolbarActions?: UiFeature[]; }; }; sidebar?: { toolbar: UiFeature[]; }; } export interface UiFeature { id: string; order?: number; disabled?: boolean; type?: string; title?: string; description?: string; icon?: string; children?: Array<UiFeature>; component?: string; data?: any; actions?: { click?: string; [key: string]: string; }; rules?: { enabled?: string; visible?: string; [key: string]: string; }; } export interface Ui extends Model { type: UI_TYPE; } export interface DataContent { id: string; name: string; description?: string; } export type DecisionTableContent = string; export interface Data extends Model { type: DATA_TYPE; } export interface DecisionTable extends Model { type: DECISION_TABLE_TYPE; } export interface Pagination { count: number; hasMoreItems: boolean; maxItems: number; skipCount: number; totalItems: number; } export interface ServerSideSorting { key: string; direction: string; } export interface SearchQuery { key: string; value: string; } export interface FetchQueries { skipCount?: number; maxItems?: number; } export interface ErrorResponse { status: number; message: string; error: ErrorResponse; } export interface FileModel { content: ActivitiFileContent; model: ActivitiFile; } export type ActivitiFileContent = File; export interface ActivitiFile extends Model { type: FILE_TYPE; extensions: FileExtensions; } export enum FileVisibility { Public = 'public', Private = 'private', } export interface FileExtensions { id: string; uri: string; name?: string; content?: FileExtensionsContent; createdAt?: Date; visibility?: FileVisibility; } export interface FileExtensionsContent { mimeType?: string; mimeTypeName?: string; sizeInBytes?: number; encoding?: string; } export interface ScriptModel { content: ActivitiScriptContent; model: ActivitiScript; } export type ActivitiScriptContent = string; export interface ActivitiScript extends Model { type: SCRIPT_TYPE; extensions: ScriptExtensions; } export interface ScriptExtensions { uri: string; name?: string; content?: ScriptExtensionsContent; createdAt?: Date; language: string; variables?: EntityProperty[]; errors?: ScriptError[]; } export interface ScriptError { name: string; code?: string; } export interface ScriptExtensionsContent { mimeType?: string; mimeTypeName?: string; sizeInBytes?: number; encoding?: string; } export interface MessagePayload { type: string; value: string | number | null; name: string; } export interface TriggerEvent { source: string; inputs: any; } export interface TriggerAction { source: string; payload: any; } export interface TriggerContent { id: string; name: string; description?: string; event?: TriggerEvent; action?: TriggerAction; } export interface Trigger extends Model { type: TRIGGER_TYPE; } export interface ContentModel extends Model { type: CUSTOM_MODEL_TYPE; } export type ContentModelXML = string; export interface ProcessDropdownStructure { [processName: string]: ProcessInfo[]; } export interface ProcessInfo { processName: string; processDefinitionId: string; processProperties: EntityProperty[]; } export interface WidgetContent { id?: string; name: string; description: string; type: string; isCustomType: boolean; valueType: string; className: string; icon?: string; } export interface Widget extends Model { type: FORM_WIDGET_TYPE; extensions: WidgetContent; } export interface TriggerFeature { id: string; name: string; description?: string; inputs?: TriggerParameter[]; outputs?: TriggerParameter[]; } export interface TriggerParameter { id?: string; name: string; label?: string; description?: string; type: string; mappingValueType?: string; required?: boolean; readOnly?: boolean; value?: any; }
the_stack
import {ParseTreeListener} from "antlr4ts/tree/ParseTreeListener"; import { AtomicContext, AtomicExpressionContext, BinaryExpressionAddContext, BinaryExpressionAndContext, BinaryExpressionDivideContext, BinaryExpressionEqualContext, BinaryExpressionGreaterThanContext, BinaryExpressionGreaterThanOrEqualContext, BinaryExpressionLessThanContext, BinaryExpressionLessThanOrEqualContext, BinaryExpressionMultiplyContext, BinaryExpressionNotEqualContext, BinaryExpressionOrContext, BinaryExpressionSubtractContext, BooleanLiteralContext, ExpressionContext, FloatingLiteralContext, GroupExpressionContext, IntegerLiteralContext, LiteralContext, ReferenceContext, UnaryExpressionNegateContext, UnaryExpressionNotContext } from "./ReactiveParser"; /** * This interface defines a complete listener for a parse tree produced by * `ReactiveParser`. */ export interface ReactiveListener extends ParseTreeListener { /** * Enter a parse tree produced by the `BinaryExpressionDivide` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterBinaryExpressionDivide?: (ctx: BinaryExpressionDivideContext) => void; /** * Exit a parse tree produced by the `BinaryExpressionDivide` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitBinaryExpressionDivide?: (ctx: BinaryExpressionDivideContext) => void; /** * Enter a parse tree produced by the `UnaryExpressionNot` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterUnaryExpressionNot?: (ctx: UnaryExpressionNotContext) => void; /** * Exit a parse tree produced by the `UnaryExpressionNot` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitUnaryExpressionNot?: (ctx: UnaryExpressionNotContext) => void; /** * Enter a parse tree produced by the `BinaryExpressionLessThan` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterBinaryExpressionLessThan?: (ctx: BinaryExpressionLessThanContext) => void; /** * Exit a parse tree produced by the `BinaryExpressionLessThan` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitBinaryExpressionLessThan?: (ctx: BinaryExpressionLessThanContext) => void; /** * Enter a parse tree produced by the `BinaryExpressionAnd` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterBinaryExpressionAnd?: (ctx: BinaryExpressionAndContext) => void; /** * Exit a parse tree produced by the `BinaryExpressionAnd` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitBinaryExpressionAnd?: (ctx: BinaryExpressionAndContext) => void; /** * Enter a parse tree produced by the `Atomic` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterAtomic?: (ctx: AtomicContext) => void; /** * Exit a parse tree produced by the `Atomic` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitAtomic?: (ctx: AtomicContext) => void; /** * Enter a parse tree produced by the `BinaryExpressionGreaterThanOrEqual` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterBinaryExpressionGreaterThanOrEqual?: (ctx: BinaryExpressionGreaterThanOrEqualContext) => void; /** * Exit a parse tree produced by the `BinaryExpressionGreaterThanOrEqual` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitBinaryExpressionGreaterThanOrEqual?: (ctx: BinaryExpressionGreaterThanOrEqualContext) => void; /** * Enter a parse tree produced by the `BinaryExpressionOr` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterBinaryExpressionOr?: (ctx: BinaryExpressionOrContext) => void; /** * Exit a parse tree produced by the `BinaryExpressionOr` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitBinaryExpressionOr?: (ctx: BinaryExpressionOrContext) => void; /** * Enter a parse tree produced by the `GroupExpression` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterGroupExpression?: (ctx: GroupExpressionContext) => void; /** * Exit a parse tree produced by the `GroupExpression` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitGroupExpression?: (ctx: GroupExpressionContext) => void; /** * Enter a parse tree produced by the `BinaryExpressionSubtract` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterBinaryExpressionSubtract?: (ctx: BinaryExpressionSubtractContext) => void; /** * Exit a parse tree produced by the `BinaryExpressionSubtract` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitBinaryExpressionSubtract?: (ctx: BinaryExpressionSubtractContext) => void; /** * Enter a parse tree produced by the `BinaryExpressionGreaterThan` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterBinaryExpressionGreaterThan?: (ctx: BinaryExpressionGreaterThanContext) => void; /** * Exit a parse tree produced by the `BinaryExpressionGreaterThan` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitBinaryExpressionGreaterThan?: (ctx: BinaryExpressionGreaterThanContext) => void; /** * Enter a parse tree produced by the `BinaryExpressionNotEqual` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterBinaryExpressionNotEqual?: (ctx: BinaryExpressionNotEqualContext) => void; /** * Exit a parse tree produced by the `BinaryExpressionNotEqual` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitBinaryExpressionNotEqual?: (ctx: BinaryExpressionNotEqualContext) => void; /** * Enter a parse tree produced by the `UnaryExpressionNegate` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterUnaryExpressionNegate?: (ctx: UnaryExpressionNegateContext) => void; /** * Exit a parse tree produced by the `UnaryExpressionNegate` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitUnaryExpressionNegate?: (ctx: UnaryExpressionNegateContext) => void; /** * Enter a parse tree produced by the `BinaryExpressionEqual` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterBinaryExpressionEqual?: (ctx: BinaryExpressionEqualContext) => void; /** * Exit a parse tree produced by the `BinaryExpressionEqual` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitBinaryExpressionEqual?: (ctx: BinaryExpressionEqualContext) => void; /** * Enter a parse tree produced by the `BinaryExpressionMultiply` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterBinaryExpressionMultiply?: (ctx: BinaryExpressionMultiplyContext) => void; /** * Exit a parse tree produced by the `BinaryExpressionMultiply` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitBinaryExpressionMultiply?: (ctx: BinaryExpressionMultiplyContext) => void; /** * Enter a parse tree produced by the `BinaryExpressionLessThanOrEqual` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterBinaryExpressionLessThanOrEqual?: (ctx: BinaryExpressionLessThanOrEqualContext) => void; /** * Exit a parse tree produced by the `BinaryExpressionLessThanOrEqual` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitBinaryExpressionLessThanOrEqual?: (ctx: BinaryExpressionLessThanOrEqualContext) => void; /** * Enter a parse tree produced by the `BinaryExpressionAdd` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ enterBinaryExpressionAdd?: (ctx: BinaryExpressionAddContext) => void; /** * Exit a parse tree produced by the `BinaryExpressionAdd` * labeled alternative in `ReactiveParser.expression`. * @param ctx the parse tree */ exitBinaryExpressionAdd?: (ctx: BinaryExpressionAddContext) => void; /** * Enter a parse tree produced by `ReactiveParser.expression`. * @param ctx the parse tree */ enterExpression?: (ctx: ExpressionContext) => void; /** * Exit a parse tree produced by `ReactiveParser.expression`. * @param ctx the parse tree */ exitExpression?: (ctx: ExpressionContext) => void; /** * Enter a parse tree produced by `ReactiveParser.reference`. * @param ctx the parse tree */ enterReference?: (ctx: ReferenceContext) => void; /** * Exit a parse tree produced by `ReactiveParser.reference`. * @param ctx the parse tree */ exitReference?: (ctx: ReferenceContext) => void; /** * Enter a parse tree produced by `ReactiveParser.atomicExpression`. * @param ctx the parse tree */ enterAtomicExpression?: (ctx: AtomicExpressionContext) => void; /** * Exit a parse tree produced by `ReactiveParser.atomicExpression`. * @param ctx the parse tree */ exitAtomicExpression?: (ctx: AtomicExpressionContext) => void; /** * Enter a parse tree produced by `ReactiveParser.literal`. * @param ctx the parse tree */ enterLiteral?: (ctx: LiteralContext) => void; /** * Exit a parse tree produced by `ReactiveParser.literal`. * @param ctx the parse tree */ exitLiteral?: (ctx: LiteralContext) => void; /** * Enter a parse tree produced by `ReactiveParser.integerLiteral`. * @param ctx the parse tree */ enterIntegerLiteral?: (ctx: IntegerLiteralContext) => void; /** * Exit a parse tree produced by `ReactiveParser.integerLiteral`. * @param ctx the parse tree */ exitIntegerLiteral?: (ctx: IntegerLiteralContext) => void; /** * Enter a parse tree produced by `ReactiveParser.floatingLiteral`. * @param ctx the parse tree */ enterFloatingLiteral?: (ctx: FloatingLiteralContext) => void; /** * Exit a parse tree produced by `ReactiveParser.floatingLiteral`. * @param ctx the parse tree */ exitFloatingLiteral?: (ctx: FloatingLiteralContext) => void; /** * Enter a parse tree produced by `ReactiveParser.booleanLiteral`. * @param ctx the parse tree */ enterBooleanLiteral?: (ctx: BooleanLiteralContext) => void; /** * Exit a parse tree produced by `ReactiveParser.booleanLiteral`. * @param ctx the parse tree */ exitBooleanLiteral?: (ctx: BooleanLiteralContext) => void; }
the_stack
import objectPath from "object-path"; import { traverse } from "ast-monkey-traverse"; import is from "@sindresorhus/is"; import { version as v } from "../package.json"; const version: string = v; function goUp(pathStr: string) { // console.log(`014 goUp(): INCOMING pathStr = "${pathStr}"`); if (pathStr.includes(".")) { for (let i = pathStr.length; i--; ) { if (pathStr[i] === ".") { // console.log(`017 goUp(): RETURN "${pathStr.slice(0, i)}"`); return pathStr.slice(0, i); } } } // console.log(`021 RETURN pathStr = "${pathStr}"`); return pathStr; } function dropIth(arr: any[], badIdx: number) { return Array.from(arr).filter((_el, i) => i !== badIdx); } interface UnknownValueObj { [key: string]: any; } interface Opts { skipContainers?: boolean; arrayStrictComparison?: boolean; } const defaults: Opts = { skipContainers: true, arrayStrictComparison: false, }; interface Callback { (leftSideVal: any, rightSideVal: any, path: string): void; } interface ErrorCallback { (errStr: string): void; } /** * Like t.same assert on array of objects, where element order doesn't matter. */ function deepContains( tree1: any, tree2: any, cb: Callback, errCb: ErrorCallback, originalOpts?: Opts ): void { const opts = { ...defaults, ...originalOpts }; if (is(tree1) !== is(tree2)) { errCb( `the first input arg is of a type ${is( tree1 ).toLowerCase()} but the second is ${is( tree2 ).toLowerCase()}. Values are - 1st:\n${JSON.stringify( tree1, null, 4 )}\n2nd:\n${JSON.stringify(tree2, null, 4)}` ); } else { // release AST monkey to traverse tree2, check each node's presence in tree1 traverse(tree2, (key, val, innerObj, stop) => { const current = val !== undefined ? val : key; const { path } = innerObj; // retrieve the path of the current node from the monkey console.log("\n"); console.log( `080 ${`\u001b[${90}m${`====================================`}\u001b[${39}m`} ${`\u001b[${36}m${`path`}\u001b[${39}m`}: ${path}; ${`\u001b[${36}m${`current`}\u001b[${39}m`} = ${JSON.stringify( current, null, 0 )} ${`\u001b[${90}m${`====================================`}\u001b[${39}m`}` ); // console.log( // `061 ${`\u001b[${33}m${`innerObj`}\u001b[${39}m`} = ${JSON.stringify( // innerObj, // null, // 4 // )}; typeof current = "${typeof current}"` // ); if (objectPath.has(tree1, path)) { console.log(`095 tree1 does have the path "${path}"`); if ( !opts.arrayStrictComparison && is.plainObject(current) && innerObj.parentType === "array" && innerObj.parent.length > 1 ) { console.log( `103 ${`\u001b[${35}m${`██ object within array`}\u001b[${39}m`}` ); // stop the monkey, we'll go further recursively stop.now = true; const arr1: UnknownValueObj[] = Array.from( innerObj.path.includes(".") ? objectPath.get(tree1, goUp(path)) : tree1 ); console.log( `114 SET ${`\u001b[${33}m${`arr1`}\u001b[${39}m`} = ${JSON.stringify( arr1, null, 4 )}` ); if (arr1.length < innerObj.parent.length) { // source array from tree1 has less elements than array from tree2! // It will not be possible to match them all! errCb( `the first array: ${JSON.stringify( arr1, null, 4 )}\nhas less objects than array we're matching against, ${JSON.stringify( innerObj.parent, null, 4 )}` ); } else { console.log(`136`); const arr2: UnknownValueObj[] = innerObj.parent; console.log( `139 SET ${`\u001b[${33}m${`arr2`}\u001b[${39}m`} = ${JSON.stringify( arr2, null, 4 )}` ); // we extract just indexes: const tree1RefSource = arr1.map((_v, i) => i); const tree2RefSource = arr2.map((_v, i) => i); // [0, 1, 2] for example. // We'll use them to calculate combinations, as in 1st object in tree2 // array against 2nd object in tree1 array... console.log( `154 ${`\u001b[${33}m${`tree1RefSource`}\u001b[${39}m`} = ${JSON.stringify( tree1RefSource, null, 0 )}` ); console.log( `161 ${`\u001b[${33}m${`tree2RefSource`}\u001b[${39}m`} = ${JSON.stringify( tree2RefSource, null, 0 )}` ); // Challenge: Array of objects is compared to another array of objects. // Order is mixed, the intended object is actually slightly off, // it's wrong, test runners will flag it, but we still need to pinpoint which // object did user intend to match against. // Outcome: we can't use strict comparison or even assume that anything // will be matching. The real world bar is the following: we need to // calculate which object is the most resembling which. // // // Plan: let's generate the table combinations of each table vs. each // table. Think about 3 vs. 2 compares: // deepContains( // [ // { key1: "a", key2: "b" }, // { key1: "k", key2: "l" }, <---- we'd ignore this // { key1: "x", key2: "y" } // ], // [ // { key1: "x", key2: "y" }, <---- notice, the order // { key1: "a", key2: "b" } <---- is wrong // ] // // Once we have table of all combinations, we'll calculate the // likeness score of each combination, and whichever is the highest // we'll ping those objects to user-supplied (likely AVA's t.equal()) callback. // // We want to achieve something like this (using example above): // [[0, 0], [1, 1]] // [[0, 0], [1, 2]] // // [[0, 1], [1, 0]] // [[0, 1], [1, 2]] // // [[0, 2], [1, 0]] // [[0, 2], [1, 1]] // where [[0, 0], [1, 1]] means: // [ // [ index 0 from tree2, index 0 from tree1 ] // [ index 1 from tree2, index 1 from tree1 ] // ] // We'll compose the combinations array from two parts: // The first digits are following "tree2RefSource", the tree2 indexes. // The second digits are from iterating tree1, picking one and // iterating what's left for the second variation. // TODO: const secondDigits: [number, number][] = []; // const secondDigits = []; for (let i = 0, len = tree1RefSource.length; i < len; i++) { const currArr: number[] = []; const pickedVal: number = tree1RefSource[i]; console.log( `225 SET ${`\u001b[${33}m${`pickedVal`}\u001b[${39}m`} = ${JSON.stringify( pickedVal, null, 4 )}` ); const disposableArr1 = dropIth(tree1RefSource, i); currArr.push(pickedVal); console.log( `234 PUSH to ${`\u001b[${33}m${`currArr`}\u001b[${39}m`} now = ${JSON.stringify( currArr, null, 4 )}` ); // iterate what's left disposableArr1.forEach((key1) => { secondDigits.push( Array.from(currArr).concat(key1) as [number, number] ); console.log( `246 secondDigits now = ${JSON.stringify( secondDigits, null, 4 )}` ); }); } type FinalCombined = [ [number, number], [number, number], number? ][]; const finalCombined: FinalCombined = secondDigits.map((arr) => { return arr.map((val2, i) => [i, val2]); }) as FinalCombined; console.log( `264 SET ${`\u001b[${33}m${`finalCombined`}\u001b[${39}m`} = ${JSON.stringify( finalCombined, null, 4 )}` ); console.log(" "); console.log(" "); console.log( `274 ${`\u001b[${35}m${`MAPPING TABLE:`}\u001b[${39}m`} ${finalCombined.reduce( (acc, curr, idx) => { return `${acc}${idx % 2 === 0 ? "\n" : ""}\n${JSON.stringify( curr, null, 0 )}`; }, "" )}` ); // now, use the "finalCombined" as a guidance which objects to match against which, and array-push the comparison score as third element into each. Whichever comparison gathers highest score, gets pinged to the callback. console.log(" "); let maxScore = 0; for (let i = 0, len = finalCombined.length; i < len; i++) { let score = 0; // finalCombined[i] === something like [[0,0],[1,1]] // tree1 array: arr1 // tree2 array: arr2 console.log(`\n-----\n#${i + 1}:`); finalCombined[i].forEach((mapping) => { console.log( `302 ${`\u001b[${33}m${`mapping`}\u001b[${39}m`} = ${JSON.stringify( mapping, null, 4 )}` ); console.log( `309 ${JSON.stringify( arr2[(mapping as any)[0]], null, 4 )} vs. ${JSON.stringify(arr1[(mapping as any)[1]], null, 4)}` ); if ( is.plainObject(arr2[(mapping as any)[0]]) && is.plainObject(arr1[(mapping as any)[1]]) ) { Object.keys(arr2[(mapping as any)[0]]).forEach((key2) => { if (Object.keys(arr1[(mapping as any)[1]]).includes(key2)) { score += 1; if ( arr1[(mapping as any)[1]][key2] === arr2[(mapping as any)[0]][key2] ) { score += 5; } } }); } }); console.log( `334 BEFORE PUSHING ${`\u001b[${33}m${`finalCombined[i]`}\u001b[${39}m`} = ${JSON.stringify( finalCombined[i], null, 4 )}` ); finalCombined[i].push(score); console.log( `342 AFTER PUSHING ${`\u001b[${33}m${`finalCombined[i]`}\u001b[${39}m`} = ${JSON.stringify( finalCombined[i], null, 4 )}` ); // finally, push the score as 3rd arg. into mapping array if (score > maxScore) { maxScore = score; } } console.log(" "); console.log(" "); console.log( `357: ${`\u001b[${35}m${`WITH SCORES:`}\u001b[${39}m`} ${finalCombined.reduce( (acc, curr, idx) => { return `${acc}${idx % 2 === 0 ? "\n" : ""}\n${JSON.stringify( curr, null, 0 )}`; }, "" )}` ); console.log(" "); console.log( `370 ${`\u001b[${35}m${`MAX SCORE:`}\u001b[${39}m`} ${maxScore}` ); // FINALLY, ping callbacks with the max score objects for (let i = 0, len = finalCombined.length; i < len; i++) { if (finalCombined[i][2] === maxScore) { console.log( `377 ${`\u001b[${35}m${`PING:`}\u001b[${39}m`} ${JSON.stringify( [finalCombined[i][0], finalCombined[i][1]], null, 0 )}` ); finalCombined[i].forEach((matchPairObj, y) => { // beware score is the last element. if (y < finalCombined[i].length - 1) { // console.log( // `${`\u001b[${33}m${`matchPairObj`}\u001b[${39}m`} = ${JSON.stringify( // matchPairObj, // null, // 4 // )}` // ); console.log( `${JSON.stringify( arr1[(matchPairObj as any)[1]], null, 4 )} vs ${JSON.stringify( arr2[(matchPairObj as any)[0]], null, 4 )}` ); // ping object pairs recursively: deepContains( arr1[(matchPairObj as any)[1]], arr2[(matchPairObj as any)[0]], cb, errCb, opts ); } }); break; } } // } } else { console.log(`423 it is not an object inside an array`); // if tree1 has that path on tree2, call the callback const retrieved = objectPath.get(tree1, path); console.log( `427 ${`\u001b[${33}m${`opts.skipContainers`}\u001b[${39}m`} = ${JSON.stringify( opts.skipContainers, null, 4 )}` ); console.log( `434 ${`\u001b[${33}m${`retrieved`}\u001b[${39}m`} = ${JSON.stringify( retrieved, null, 4 )}; type: ${typeof retrieved}; isObj: ${is.plainObject(retrieved)}` ); if ( !opts.skipContainers || (!is.plainObject(retrieved) && !Array.isArray(retrieved)) ) { console.log(`444 ${`\u001b[${32}m${`PING`}\u001b[${39}m`} cb()`); cb(retrieved, current, path); } } } else { errCb( `the first input: ${JSON.stringify( tree1, null, 4 )}\ndoes not have the path "${path}", we were looking, would it contain a value ${JSON.stringify( current, null, 0 )}.` ); } console.log( `\n\n\n348 ${`\u001b[${90}m${`======================================================`}\u001b[${39}m`} fin. ${`\u001b[${90}m${`======================================================`}\u001b[${39}m`}` ); return current; }); } } // ----------------------------------------------------------------------------- export { deepContains, defaults, version };
the_stack
import React, { ReactNode, Children, ReactChild, ReactFragment, ReactPortal } from 'react'; import cls from 'classnames'; import PropTypes from 'prop-types'; import BaseComponent from "../_base/baseComponent"; import { CarouselProps } from './interface'; import { cssClasses, numbers, strings } from '@douyinfe/semi-foundation/carousel/constants'; import CarouselFoundation, { CarouselAdapter } from '@douyinfe/semi-foundation/carousel/foundation'; import CarouselIndicator from './CarouselIndicator'; import CarouselArrow from './CarouselArrow'; import '@douyinfe/semi-foundation/carousel/carousel.scss'; import { debounce } from 'lodash'; import isNullOrUndefined from '@douyinfe/semi-foundation/utils/isNullOrUndefined'; export interface CarouselState { activeIndex: number; children: (ReactChild | ReactFragment | ReactPortal)[]; preIndex: number; isReverse: boolean; isInit: boolean; } class Carousel extends BaseComponent<CarouselProps, CarouselState> { static propTypes = { activeIndex: PropTypes.number, animation:PropTypes.oneOf(strings.ANIMATION_MAP), arrowProps: PropTypes.object, autoPlay: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]), className: PropTypes.string, defaultActiveIndex: PropTypes.number, indicatorPosition: PropTypes.oneOf(strings.POSITION_MAP), indicatorSize: PropTypes.oneOf(strings.SIZE), indicatorType: PropTypes.oneOf(strings.TYPE_MAP), theme: PropTypes.oneOf(strings.THEME_MAP), onChange: PropTypes.func, arrowType: PropTypes.oneOf(strings.ARROW_MAP), showArrow: PropTypes.bool, showIndicator: PropTypes.bool, slideDirection: PropTypes.oneOf(strings.DIRECTION), speed: PropTypes.number, style: PropTypes.object, trigger: PropTypes.oneOf(strings.TRIGGER) }; static defaultProps: CarouselProps = { children: [], animation: 'slide', autoPlay: true, arrowType: 'always', defaultActiveIndex: numbers.DEFAULT_ACTIVE_INDEX, indicatorPosition: 'center', indicatorSize: 'small', indicatorType: 'dot', theme: 'light', onChange: () => undefined, showArrow: true, showIndicator: true, slideDirection: 'left', speed: numbers.DEFAULT_SPEED, trigger: 'click' }; foundation: CarouselFoundation; constructor(props: CarouselProps) { super(props); this.foundation = new CarouselFoundation(this.adapter); const defaultActiveIndex = this.foundation.getDefaultActiveIndex(); this.state = { activeIndex: defaultActiveIndex, children: this.getChildren(), preIndex: defaultActiveIndex, isReverse: false, isInit: true }; } get adapter(): CarouselAdapter<CarouselProps, CarouselState> { return { ...super.adapter, notifyChange: (activeIndex: number, preIndex: number): void => { this.props.onChange(activeIndex, preIndex); }, setNewActiveIndex: (activeIndex: number): void => { this.setState({ activeIndex }); }, setPreActiveIndex: (preIndex: number): void => { this.setState({ preIndex }); }, setIsReverse: (isReverse: boolean): void => { this.setState({ isReverse }); }, setIsInit: (isInit: boolean): void => { this.setState({ isInit }); } }; } static getDerivedStateFromProps(props: CarouselProps, state: CarouselState): Partial<CarouselState> { const states: Partial<CarouselState> = {}; if (!isNullOrUndefined(props.activeIndex) && props.activeIndex !== state.activeIndex) { states.activeIndex = props.activeIndex; } return states; } componentDidMount(): void { this.handleAutoPlay(); } componentWillUnmount(): void { this.foundation.destroy(); } play = (): void => { return this.foundation.handleAutoPlay(); } stop = (): void => { return this.foundation.stop(); }; goTo = ( targetIndex: number): void => { return this.foundation.goTo(targetIndex); }; prev = (): void => { return this.foundation.prev(); }; next = (): void => { return this.foundation.next(); }; handleAutoPlay = (): void => { if (!this.foundation.getIsControledComponent()){ this.foundation.handleAutoPlay(); } } handleMouseEnter = (): void => { const { autoPlay } = this.props; if (typeof autoPlay !== 'object' || autoPlay.hoverToPause){ this.foundation.stop(); } } handleMouseLeave = (): void => { const { autoPlay } = this.props; if ((typeof autoPlay !== 'object' || autoPlay.hoverToPause) && !this.foundation.getIsControledComponent()){ this.foundation.handleAutoPlay(); } } onIndicatorChange = (activeIndex: number): void => { return this.foundation.onIndicatorChange(activeIndex); }; getChildren = (): (ReactChild | ReactFragment | ReactPortal)[] => { const { children: originChildren } = this.props; return Children.toArray(originChildren).filter(child=>{ return React.isValidElement(child); }); } getValidIndex = (activeIndex: number): number => { return this.foundation.getValidIndex(activeIndex); }; renderChildren = () => { const { speed, animation } = this.props; const { activeIndex, children, preIndex, isInit } = this.state; return ( <> {children.map((child: any, index: number) => { const isCurrent = index === activeIndex; const isPrev = index === this.getValidIndex(activeIndex - 1); const isNext = index === this.getValidIndex(activeIndex + 1); const animateStyle = { transitionTimingFunction: 'ease', transitionDuration: `${speed}ms`, animationTimingFunction: 'ease', animationDuration: `${speed}ms`, }; return React.cloneElement(child, { style: { ...child.props.style, ...animateStyle, }, className: cls(child.props.className, { [`${cssClasses.CAROUSEL_CONTENT}-item-prev`]: isPrev, [`${cssClasses.CAROUSEL_CONTENT}-item-next`]: isNext, [`${cssClasses.CAROUSEL_CONTENT}-item-current`]: isCurrent, [`${cssClasses.CAROUSEL_CONTENT}-item`]: true, [`${cssClasses.CAROUSEL_CONTENT}-item-active`]: isCurrent, [`${cssClasses.CAROUSEL_CONTENT}-item-slide-in`]:animation === 'slide' && !isInit && isCurrent, [`${cssClasses.CAROUSEL_CONTENT}-item-slide-out`]:animation === 'slide' && !isInit && index === preIndex, }) }); })} </> ); } renderIndicator = () => { const { children, activeIndex } = this.state; const { showIndicator, indicatorType, theme, indicatorPosition, indicatorSize, trigger } = this.props; const carouselIndicatorCls = cls({ [cssClasses.CAROUSEL_INDICATOR]: true }); if (showIndicator && children.length > 1){ return ( <div className={carouselIndicatorCls}> <CarouselIndicator type={indicatorType} total={children.length} activeIndex={activeIndex} position={indicatorPosition} trigger={trigger} size={indicatorSize} theme={theme} onIndicatorChange={this.onIndicatorChange} /> </div> ); } return null; } renderArrow = () => { const { children } = this.state; const { showArrow, arrowType, theme, arrowProps } = this.props; if (showArrow && children.length > 1){ return ( <CarouselArrow type={arrowType} theme={theme} prev={this.prev} next={this.next} arrowProps={arrowProps} /> ); } return null; }; render(): ReactNode { const { animation, className, style, slideDirection } = this.props; const { isReverse } = this.state; const carouselWrapperCls = cls(className, { [cssClasses.CAROUSEL]: true }); return ( <div // role='listbox' // tabIndex={0} className={carouselWrapperCls} style={style} onMouseEnter={debounce(this.handleMouseEnter, 400)} onMouseLeave={debounce(this.handleMouseLeave, 400)} // onMouseEnter={this.handleMouseEnter} // onMouseLeave={this.handleMouseLeave} // onKeyDown={e => this.foundation.handleKeyDown(e)} > <div className={cls([`${cssClasses.CAROUSEL_CONTENT}-${animation}`], { [`${cssClasses.CAROUSEL_CONTENT}`]: true, [`${cssClasses.CAROUSEL_CONTENT}-reverse`]: slideDirection === 'left' ? isReverse : !isReverse, })} > {this.renderChildren()} </div> {this.renderIndicator()} {this.renderArrow()} </div> ); } } export default Carousel;
the_stack
import * as path from 'path'; import { ISecurityGroup, IVpc, SecurityGroup, SubnetSelection, SubnetType, } from '@aws-cdk/aws-ec2'; import { IAccessPoint, } from '@aws-cdk/aws-efs'; import { Code, FileSystem as LambdaFilesystem, Function as LambdaFunction, Runtime, } from '@aws-cdk/aws-lambda'; import { RetentionDays, } from '@aws-cdk/aws-logs'; import { Choice, Condition, Fail, InputType, StateMachine, Succeed, }from '@aws-cdk/aws-stepfunctions'; import { LambdaInvoke, } from '@aws-cdk/aws-stepfunctions-tasks'; import { Annotations, Construct, Duration, Size, SizeRoundingBehavior, Stack, } from '@aws-cdk/core'; import { AwsSdkCall, AwsCustomResource, AwsCustomResourcePolicy, PhysicalResourceId, } from '@aws-cdk/custom-resources'; import { tagConstruct, } from './runtime-info'; /** * Input properties for PadEfsStorage. */ export interface PadEfsStorageProps { /** * VPC in which the given access point is deployed. */ readonly vpc: IVpc; /** * PadEfsStorage deploys AWS Lambda Functions that need to contact your Amazon EFS mount target(s). * To do this, AWS Lambda creates network interfaces in these given subnets in your VPC. * These can be any subnet(s) in your VPC that can route traffic to the EFS mount target(s). * * @default All private subnets */ readonly vpcSubnets?: SubnetSelection; /** * Amazon EFS Access Point into which the filesystem padding files will be added. Files will * be added/removed from the root directory of the given access point. * We strongly recommend that you provide an access point that is for a dedicated padding-files * directory in your EFS filesystem, rather than the root directory or some other in-use directory * of the filesystem. */ readonly accessPoint: IAccessPoint; /** * Security group for the AWS Lambdas created by this construct. * * @default Security group with no egress or ingress will be automatically created for each Lambda. */ readonly securityGroup?: ISecurityGroup; /** * The desired total size, in GiB, of files stored in the access point directory. */ readonly desiredPadding: Size; } /** * This construct provides a mechanism that adds 1GB-sized files containing only zero-bytes * to an Amazon EFS filesystem through a given Access Point to that filesystem. This is being * provided to give you a way to increase the baseline throughput of an Amazon EFS filesystem * that has been deployed in bursting throughput mode (see: https://docs.aws.amazon.com/efs/latest/ug/performance.html#throughput-modes). * This is most useful for your Amazon EFS filesystems that contain a very small amount of data and * have a baseline throughput that exceeds the throughput provided by the size of the filesystem. * * When deployed in bursting throughput mode, an Amazon EFS filesystem provides you with a baseline * throughput that is proportional to the amount of data stored in that filesystem. However, usage * of that filesystem is allowed to burst above that throughput; doing so consumes burst credits that * are associated with the filesystem. When all burst credits have been expended, then your filesystem * is no longer allowed to burst throughput and you will be limited in throughput to the greater of 1MiB/s * or the throughput dictated by the amount of data stored in your filesystem; the filesystem will be able * to burst again if it is able to accrue burst credits by staying below its baseline throughput for a time. * * Customers that deploy the Deadline Repository Filesystem on an Amazon EFS filesystem may find that * the filesystem does not contain sufficient data to meet the throughput needs of Deadline; evidenced by * a downward trend in EFS bursting credits over time. When bursting credits are expended, then the render * farm may begin to exhibit failure mode behaviors such as the RenderQueue dropping or refusing connections, * or becoming unresponsive. * * Warning: The implementation of this construct creates and starts an AWS Step Function to add the files * to the filesystem. The execution of this Step Function occurs asynchronously from your deployment. We recommend * verifying that the step function completed successfully via your Step Functions console. * * Resources Deployed * -------------------------- * - Two AWS Lambda Functions, with roles, with full access to the given EFS Access Point. * - An Elastic Network Interface (ENI) for each Lambda Function in each of the selected VPC Subnets, so * that the Lambda Functions can connect to the given EFS Access Point. * - An AWS Step Function to coordinate execution of the two Lambda Functions. * - Security Groups for each AWS Lambda Function. * - A CloudFormation custom resource that executes StepFunctions.startExecution on the Step Function * whenever the stack containing this construct is created or updated. * * Security Considerations * --------------------------- * - The AWS Lambdas that are deployed through this construct will be created from a deployment package * that is uploaded to your CDK bootstrap bucket during deployment. You must limit write access to * your CDK bootstrap bucket to prevent an attacker from modifying the actions performed by these Lambdas. * We strongly recommend that you either enable Amazon S3 server access logging on your CDK bootstrap bucket, * or enable AWS CloudTrail on your account to assist in post-incident analysis of compromised production * environments. * - By default, the network interfaces created by this construct's AWS Lambda Functions have Security Groups * that restrict egress access from the Lambda Function into your VPC such that the Lambda Functions can * access only the given EFS Access Point. */ export class PadEfsStorage extends Construct { constructor(scope: Construct, id: string, props: PadEfsStorageProps) { super(scope, id); /* Implementation: This is implemented as an AWS Step Function that implements the following algorithm: try { du = diskUsage(<efs access point directory>) while (du != desiredPadding) { if (du < desiredPadding) { <grow padding by adding up to 20 1GB numbered files to the filesystem.> } else if (du > desiredPadding) { <delete 1GB numbered files from the filesystem to reduce the padding to the desired amount> // Note: We break here to prevent two separate invocations of the step function (e.g. accidental manual // invocations) from looping indefinitely. Without a break, one invocation trying to grow while another // tries to shrink will infinitely loop both -- the diskUsage will never settle on the value that either // invocation wants. break; } du = diskUsage(<efs access point directory>) } return success } catch (error) { return failure } */ const diskUsageTimeout = Duration.minutes(5); const paddingTimeout = Duration.minutes(15); // Location in the lambda environment where the EFS will be mounted. const efsMountPoint = '/mnt/efs'; let desiredSize; try { desiredSize = props.desiredPadding.toGibibytes({rounding: SizeRoundingBehavior.FAIL}); } catch (err) { Annotations.of(this).addError('Failed to round desiredSize to an integer number of GiB. The size must be in GiB.'); } const securityGroup = props.securityGroup ?? new SecurityGroup(this, 'LambdaSecurityGroup', { vpc: props.vpc, allowAllOutbound: false, }); const lambdaProps: any = { code: Code.fromAsset(path.join(__dirname, '..', '..', 'lambdas', 'nodejs')), runtime: Runtime.NODEJS_14_X, logRetention: RetentionDays.ONE_WEEK, // Required for access point... vpc: props.vpc, vpcSubnets: props.vpcSubnets ?? { subnetType: SubnetType.PRIVATE, }, securityGroups: [ securityGroup ], filesystem: LambdaFilesystem.fromEfsAccessPoint(props.accessPoint, efsMountPoint), }; const diskUsage = new LambdaFunction(this, 'DiskUsage', { description: 'Used by RFDK PadEfsStorage to calculate disk usage of an EFS access point', handler: 'pad-efs-storage.getDiskUsage', timeout: diskUsageTimeout, memorySize: 128, ...lambdaProps, }); // Implicit reference should have been fine, but the lambda is unable to mount the filesystem if // executed before the filesystem has been fully formed. We shouldn't have the lambda created until // after the EFS is created. diskUsage.node.addDependency(props.accessPoint); const doPadding = new LambdaFunction(this, 'PadFilesystem', { description: 'Used by RFDK PadEfsStorage to add or remove numbered 1GB files in an EFS access point', handler: 'pad-efs-storage.padFilesystem', timeout: paddingTimeout, // Execution requires about 70MB for just the lambda, but the filesystem driver will use every available byte. // Larger sizes do not seem to make a difference on filesystem write performance. // Set to 256MB just to give a buffer. memorySize: 256, ...lambdaProps, }); // Implicit reference should have been fine, but the lambda is unable to mount the filesystem if // executed before the filesystem has been fully formed. We shouldn't have the lambda created until // after the EFS is created. doPadding.node.addDependency(props.accessPoint); // Build the step function's state machine. const fail = new Fail(this, 'Fail'); const succeed = new Succeed(this, 'Succeed'); const diskUsageTask = new LambdaInvoke(this, 'QueryDiskUsage', { lambdaFunction: diskUsage, comment: 'Determine the number of GB currently stored in the EFS access point', timeout: diskUsageTimeout, payload: { type: InputType.OBJECT, value: { 'desiredPadding.$': '$.desiredPadding', 'mountPoint': efsMountPoint, }, }, resultPath: '$.diskUsage', }); const growTask = new LambdaInvoke(this, 'GrowTask', { lambdaFunction: doPadding, comment: 'Add up to 20 numbered 1GB files to the EFS access point', timeout: paddingTimeout, payload: { type: InputType.OBJECT, value: { 'desiredPadding.$': '$.desiredPadding', 'mountPoint': efsMountPoint, }, }, resultPath: '$.null', }); const shrinkTask = new LambdaInvoke(this, 'ShrinkTask', { lambdaFunction: doPadding, comment: 'Remove 1GB numbered files from the EFS access point to shrink the padding', timeout: paddingTimeout, payload: { type: InputType.OBJECT, value: { 'desiredPadding.$': '$.desiredPadding', 'mountPoint': efsMountPoint, }, }, resultPath: '$.null', }); const choice = new Choice(this, 'BranchOnDiskUsage') .when(Condition.numberLessThanJsonPath('$.diskUsage.Payload', '$.desiredPadding'), growTask) .when(Condition.numberGreaterThanJsonPath('$.diskUsage.Payload', '$.desiredPadding'), shrinkTask) .otherwise(succeed); diskUsageTask.next(choice); diskUsageTask.addCatch(fail, { // See: https://docs.aws.amazon.com/step-functions/latest/dg/concepts-error-handling.html errors: ['States.ALL'], }); growTask.next(diskUsageTask); growTask.addCatch(fail, { errors: [ 'States.ALL' ], }); shrinkTask.next(succeed); shrinkTask.addCatch(fail, { errors: [ 'States.ALL' ], }); const statemachine = new StateMachine(this, 'StateMachine', { definition: diskUsageTask, }); // ========== // Invoke the step function on stack create & update. const invokeCall: AwsSdkCall = { action: 'startExecution', service: 'StepFunctions', apiVersion: '2016-11-23', region: Stack.of(this).region, physicalResourceId: PhysicalResourceId.fromResponse('executionArn'), parameters: { stateMachineArn: statemachine.stateMachineArn, input: JSON.stringify({ desiredPadding: desiredSize, }), }, }; const resource = new AwsCustomResource(this, 'Default', { installLatestAwsSdk: true, logRetention: RetentionDays.ONE_WEEK, onCreate: invokeCall, onUpdate: invokeCall, policy: AwsCustomResourcePolicy.fromSdkCalls({ resources: [ statemachine.stateMachineArn ], }), }); resource.node.addDependency(statemachine); // Add RFDK tags to the construct tree. tagConstruct(this); } }
the_stack
import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; import * as TextUtils from '../text_utils/text_utils.js'; import type {Project} from './WorkspaceImpl.js'; import {Events as WorkspaceImplEvents, projectTypes} from './WorkspaceImpl.js'; const UIStrings = { /** *@description Text for the index of something */ index: '(index)', /** *@description Text in UISource Code of the DevTools local workspace */ thisFileWasChangedExternally: 'This file was changed externally. Would you like to reload it?', }; const str_ = i18n.i18n.registerUIStrings('models/workspace/UISourceCode.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class UISourceCode extends Common.ObjectWrapper.ObjectWrapper<EventTypes> implements TextUtils.ContentProvider.ContentProvider { private projectInternal: Project; private urlInternal: string; private readonly originInternal: string; private readonly parentURLInternal: string; private nameInternal: string; private contentTypeInternal: Common.ResourceType.ResourceType; private requestContentPromise: Promise<TextUtils.ContentProvider.DeferredContent>|null; private decorations: Platform.MapUtilities.Multimap<string, LineMarker>|null; private hasCommitsInternal: boolean; private messagesInternal: Set<Message>|null; private contentLoadedInternal: boolean; private contentInternal: TextUtils.ContentProvider.DeferredContent|null; private forceLoadOnCheckContentInternal: boolean; private checkingContent: boolean; private lastAcceptedContent: string|null; private workingCopyInternal: string|null; private workingCopyGetter: (() => string)|null; private disableEditInternal: boolean; private contentEncodedInternal?: boolean; constructor(project: Project, url: string, contentType: Common.ResourceType.ResourceType) { super(); this.projectInternal = project; this.urlInternal = url; const parsedURL = Common.ParsedURL.ParsedURL.fromString(url); if (parsedURL) { this.originInternal = parsedURL.securityOrigin(); this.parentURLInternal = this.originInternal + parsedURL.folderPathComponents; this.nameInternal = parsedURL.lastPathComponent; if (parsedURL.queryParams) { this.nameInternal += '?' + parsedURL.queryParams; } } else { this.originInternal = ''; this.parentURLInternal = ''; this.nameInternal = url; } this.contentTypeInternal = contentType; this.requestContentPromise = null; this.decorations = null; this.hasCommitsInternal = false; this.messagesInternal = null; this.contentLoadedInternal = false; this.contentInternal = null; this.forceLoadOnCheckContentInternal = false; this.checkingContent = false; this.lastAcceptedContent = null; this.workingCopyInternal = null; this.workingCopyGetter = null; this.disableEditInternal = false; } requestMetadata(): Promise<UISourceCodeMetadata|null> { return this.projectInternal.requestMetadata(this); } name(): string { return this.nameInternal; } mimeType(): string { return this.projectInternal.mimeType(this); } url(): string { return this.urlInternal; } parentURL(): string { return this.parentURLInternal; } origin(): string { return this.originInternal; } fullDisplayName(): string { return this.projectInternal.fullDisplayName(this); } displayName(skipTrim?: boolean): string { if (!this.nameInternal) { return i18nString(UIStrings.index); } let name: string = this.nameInternal; try { if (this.project().type() === projectTypes.FileSystem) { name = unescape(name); } else { name = decodeURI(name); } } catch (error) { } return skipTrim ? name : Platform.StringUtilities.trimEndWithMaxLength(name, 100); } canRename(): boolean { return this.projectInternal.canRename(); } rename(newName: string): Promise<boolean> { let fulfill: (arg0: boolean) => void; const promise = new Promise<boolean>(x => { fulfill = x; }); this.projectInternal.rename(this, newName, innerCallback.bind(this)); return promise; function innerCallback( this: UISourceCode, success: boolean, newName?: string, newURL?: string, newContentType?: Common.ResourceType.ResourceType): void { if (success) { this.updateName(newName as string, newURL as string, newContentType as Common.ResourceType.ResourceType); } fulfill(success); } } remove(): void { this.projectInternal.deleteFile(this); } private updateName(name: string, url: string, contentType?: Common.ResourceType.ResourceType): void { const oldURL = this.urlInternal; this.urlInternal = this.urlInternal.substring(0, this.urlInternal.length - this.nameInternal.length) + name; this.nameInternal = name; if (url) { this.urlInternal = url; } if (contentType) { this.contentTypeInternal = contentType; } this.dispatchEventToListeners(Events.TitleChanged, this); this.project().workspace().dispatchEventToListeners( WorkspaceImplEvents.UISourceCodeRenamed, {oldURL: oldURL, uiSourceCode: this}); } // TODO(crbug.com/1253323): Cast to RawPathString will be removed when migration to branded types is complete. contentURL(): Platform.DevToolsPath.RawPathString { return this.url() as Platform.DevToolsPath.RawPathString; } contentType(): Common.ResourceType.ResourceType { return this.contentTypeInternal; } async contentEncoded(): Promise<boolean> { await this.requestContent(); return this.contentEncodedInternal || false; } project(): Project { return this.projectInternal; } requestContent(): Promise<TextUtils.ContentProvider.DeferredContent> { if (this.requestContentPromise) { return this.requestContentPromise; } if (this.contentLoadedInternal) { return Promise.resolve(this.contentInternal as TextUtils.ContentProvider.DeferredContent); } this.requestContentPromise = this.requestContentImpl(); return this.requestContentPromise; } private async requestContentImpl(): Promise<TextUtils.ContentProvider.DeferredContent> { try { const content = await this.projectInternal.requestFileContent(this); if (!this.contentLoadedInternal) { this.contentLoadedInternal = true; this.contentInternal = content; this.contentEncodedInternal = content.isEncoded; } } catch (err) { this.contentLoadedInternal = true; this.contentInternal = {content: null, error: err ? String(err) : '', isEncoded: false}; } return this.contentInternal as TextUtils.ContentProvider.DeferredContent; } async checkContentUpdated(): Promise<void> { if (!this.contentLoadedInternal && !this.forceLoadOnCheckContentInternal) { return; } if (!this.projectInternal.canSetFileContent() || this.checkingContent) { return; } this.checkingContent = true; const updatedContent = await this.projectInternal.requestFileContent(this); if ('error' in updatedContent) { return; } this.checkingContent = false; if (updatedContent.content === null) { const workingCopy = this.workingCopy(); this.contentCommitted('', false); this.setWorkingCopy(workingCopy); return; } if (this.lastAcceptedContent === updatedContent.content) { return; } if (this.contentInternal && 'content' in this.contentInternal && this.contentInternal.content === updatedContent.content) { this.lastAcceptedContent = null; return; } if (!this.isDirty() || this.workingCopyInternal === updatedContent.content) { this.contentCommitted(updatedContent.content as string, false); return; } await Common.Revealer.reveal(this); // Make sure we are in the next frame before stopping the world with confirm await new Promise(resolve => setTimeout(resolve, 0)); const shouldUpdate = window.confirm(i18nString(UIStrings.thisFileWasChangedExternally)); if (shouldUpdate) { this.contentCommitted(updatedContent.content as string, false); } else { this.lastAcceptedContent = updatedContent.content; } } forceLoadOnCheckContent(): void { this.forceLoadOnCheckContentInternal = true; } private commitContent(content: string): void { if (this.projectInternal.canSetFileContent()) { this.projectInternal.setFileContent(this, content, false); } this.contentCommitted(content, true); } private contentCommitted(content: string, committedByUser: boolean): void { this.lastAcceptedContent = null; this.contentInternal = {content, isEncoded: false}; this.contentLoadedInternal = true; this.requestContentPromise = null; this.hasCommitsInternal = true; this.innerResetWorkingCopy(); const data = {uiSourceCode: this, content, encoded: this.contentEncodedInternal}; this.dispatchEventToListeners(Events.WorkingCopyCommitted, data); this.projectInternal.workspace().dispatchEventToListeners(WorkspaceImplEvents.WorkingCopyCommitted, data); if (committedByUser) { this.projectInternal.workspace().dispatchEventToListeners(WorkspaceImplEvents.WorkingCopyCommittedByUser, data); } } addRevision(content: string): void { this.commitContent(content); } hasCommits(): boolean { return this.hasCommitsInternal; } workingCopy(): string { if (this.workingCopyGetter) { this.workingCopyInternal = this.workingCopyGetter(); this.workingCopyGetter = null; } if (this.isDirty()) { return this.workingCopyInternal as string; } return (this.contentInternal && 'content' in this.contentInternal && this.contentInternal.content) || ''; } resetWorkingCopy(): void { this.innerResetWorkingCopy(); this.workingCopyChanged(); } private innerResetWorkingCopy(): void { this.workingCopyInternal = null; this.workingCopyGetter = null; } setWorkingCopy(newWorkingCopy: string): void { this.workingCopyInternal = newWorkingCopy; this.workingCopyGetter = null; this.workingCopyChanged(); } setContent(content: string, isBase64: boolean): void { this.contentEncodedInternal = isBase64; if (this.projectInternal.canSetFileContent()) { this.projectInternal.setFileContent(this, content, isBase64); } this.contentCommitted(content, true); } setWorkingCopyGetter(workingCopyGetter: () => string): void { this.workingCopyGetter = workingCopyGetter; this.workingCopyChanged(); } private workingCopyChanged(): void { this.removeAllMessages(); this.dispatchEventToListeners(Events.WorkingCopyChanged, this); this.projectInternal.workspace().dispatchEventToListeners( WorkspaceImplEvents.WorkingCopyChanged, {uiSourceCode: this}); } removeWorkingCopyGetter(): void { if (!this.workingCopyGetter) { return; } this.workingCopyInternal = this.workingCopyGetter(); this.workingCopyGetter = null; } commitWorkingCopy(): void { if (this.isDirty()) { this.commitContent(this.workingCopy()); } } isDirty(): boolean { return this.workingCopyInternal !== null || this.workingCopyGetter !== null; } extension(): string { return Common.ParsedURL.ParsedURL.extractExtension(this.nameInternal); } content(): string { return (this.contentInternal && 'content' in this.contentInternal && this.contentInternal.content) || ''; } loadError(): string|null { return (this.contentInternal && 'error' in this.contentInternal && this.contentInternal.error) || null; } searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<TextUtils.ContentProvider.SearchMatch[]> { const content = this.content(); if (!content) { return this.projectInternal.searchInFileContent(this, query, caseSensitive, isRegex); } return Promise.resolve(TextUtils.TextUtils.performSearchInContent(content, query, caseSensitive, isRegex)); } contentLoaded(): boolean { return this.contentLoadedInternal; } uiLocation(lineNumber: number, columnNumber?: number): UILocation { return new UILocation(this, lineNumber, columnNumber); } messages(): Set<Message> { return this.messagesInternal ? new Set(this.messagesInternal) : new Set(); } addLineMessage( level: Message.Level, text: string, lineNumber: number, columnNumber?: number, clickHandler?: (() => void)): Message { const range = TextUtils.TextRange.TextRange.createFromLocation(lineNumber, columnNumber || 0); const message = new Message(level, text, clickHandler, range); this.addMessage(message); return message; } addMessage(message: Message): void { if (!this.messagesInternal) { this.messagesInternal = new Set(); } this.messagesInternal.add(message); this.dispatchEventToListeners(Events.MessageAdded, message); } removeMessage(message: Message): void { if (this.messagesInternal && this.messagesInternal.delete(message)) { this.dispatchEventToListeners(Events.MessageRemoved, message); } } private removeAllMessages(): void { if (!this.messagesInternal) { return; } for (const message of this.messagesInternal) { this.dispatchEventToListeners(Events.MessageRemoved, message); } this.messagesInternal = null; } addLineDecoration(lineNumber: number, type: string, data: any): void { this.addDecoration(TextUtils.TextRange.TextRange.createFromLocation(lineNumber, 0), type, data); } addDecoration(range: TextUtils.TextRange.TextRange, type: string, data: any): void { const marker = new LineMarker(range, type, data); if (!this.decorations) { this.decorations = new Platform.MapUtilities.Multimap(); } this.decorations.set(type, marker); this.dispatchEventToListeners(Events.LineDecorationAdded, marker); } removeDecorationsForType(type: string): void { if (!this.decorations) { return; } const markers = this.decorations.get(type); this.decorations.deleteAll(type); markers.forEach(marker => { this.dispatchEventToListeners(Events.LineDecorationRemoved, marker); }); } allDecorations(): LineMarker[] { return this.decorations ? this.decorations.valuesArray() : []; } removeAllDecorations(): void { if (!this.decorations) { return; } const decorationList = this.decorations.valuesArray(); this.decorations.clear(); decorationList.forEach(marker => this.dispatchEventToListeners(Events.LineDecorationRemoved, marker)); } decorationsForType(type: string): Set<LineMarker>|null { return this.decorations ? this.decorations.get(type) : null; } disableEdit(): void { this.disableEditInternal = true; } editDisabled(): boolean { return this.disableEditInternal; } } // TODO(crbug.com/1167717): Make this a const enum again // eslint-disable-next-line rulesdir/const_enum export enum Events { WorkingCopyChanged = 'WorkingCopyChanged', WorkingCopyCommitted = 'WorkingCopyCommitted', TitleChanged = 'TitleChanged', MessageAdded = 'MessageAdded', MessageRemoved = 'MessageRemoved', LineDecorationAdded = 'LineDecorationAdded', LineDecorationRemoved = 'LineDecorationRemoved', } export interface WorkingCopyCommitedEvent { uiSourceCode: UISourceCode; content: string; encoded: boolean|undefined; } export type EventTypes = { [Events.WorkingCopyChanged]: UISourceCode, [Events.WorkingCopyCommitted]: WorkingCopyCommitedEvent, [Events.TitleChanged]: UISourceCode, [Events.MessageAdded]: Message, [Events.MessageRemoved]: Message, [Events.LineDecorationAdded]: LineMarker, [Events.LineDecorationRemoved]: LineMarker, }; export class UILocation { uiSourceCode: UISourceCode; lineNumber: number; columnNumber: number|undefined; constructor(uiSourceCode: UISourceCode, lineNumber: number, columnNumber?: number) { this.uiSourceCode = uiSourceCode; this.lineNumber = lineNumber; this.columnNumber = columnNumber; } linkText(skipTrim?: boolean, showColumnNumber?: boolean): string { let linkText = this.uiSourceCode.displayName(skipTrim); if (this.uiSourceCode.mimeType() === 'application/wasm') { // For WebAssembly locations, we follow the conventions described in // github.com/WebAssembly/design/blob/master/Web.md#developer-facing-display-conventions if (typeof this.columnNumber === 'number') { linkText += `:0x${this.columnNumber.toString(16)}`; } } else { linkText += ':' + (this.lineNumber + 1); if (showColumnNumber && typeof this.columnNumber === 'number') { linkText += ':' + (this.columnNumber + 1); } } return linkText; } id(): string { if (typeof this.columnNumber === 'number') { return this.uiSourceCode.project().id() + ':' + this.uiSourceCode.url() + ':' + this.lineNumber + ':' + this.columnNumber; } return this.lineId(); } lineId(): string { return this.uiSourceCode.project().id() + ':' + this.uiSourceCode.url() + ':' + this.lineNumber; } toUIString(): string { return this.uiSourceCode.url() + ':' + (this.lineNumber + 1); } static comparator(location1: UILocation, location2: UILocation): number { return location1.compareTo(location2); } compareTo(other: UILocation): number { if (this.uiSourceCode.url() !== other.uiSourceCode.url()) { return this.uiSourceCode.url() > other.uiSourceCode.url() ? 1 : -1; } if (this.lineNumber !== other.lineNumber) { return this.lineNumber - other.lineNumber; } // We consider `undefined` less than an actual column number, since // UI location without a column number corresponds to the whole line. if (this.columnNumber === other.columnNumber) { return 0; } if (typeof this.columnNumber !== 'number') { return -1; } if (typeof other.columnNumber !== 'number') { return 1; } return this.columnNumber - other.columnNumber; } } /** * A message associated with a range in a `UISourceCode`. The range will be * underlined starting at the range's start and ending at the line end (the * end of the range is currently disregarded). * An icon is going to appear at the end of the line according to the * `level` of the Message. This is only the model; displaying is handled * where UISourceCode displaying is handled. */ export class Message { private readonly levelInternal: Message.Level; private readonly textInternal: string; range: TextUtils.TextRange.TextRange; private readonly clickHandlerInternal?: (() => void); constructor(level: Message.Level, text: string, clickHandler?: (() => void), range?: TextUtils.TextRange.TextRange) { this.levelInternal = level; this.textInternal = text; this.range = range ?? new TextUtils.TextRange.TextRange(0, 0, 0, 0); this.clickHandlerInternal = clickHandler; } level(): Message.Level { return this.levelInternal; } text(): string { return this.textInternal; } clickHandler(): (() => void)|undefined { return this.clickHandlerInternal; } lineNumber(): number { return this.range.startLine; } columnNumber(): number|undefined { return this.range.startColumn; } isEqual(another: Message): boolean { return this.text() === another.text() && this.level() === another.level() && this.range.equal(another.range); } } export namespace Message { // TODO(crbug.com/1167717): Make this a const enum again // eslint-disable-next-line rulesdir/const_enum export enum Level { Error = 'Error', Issue = 'Issue', Warning = 'Warning', } } export class LineMarker { private readonly rangeInternal: TextUtils.TextRange.TextRange; private readonly typeInternal: string; private readonly dataInternal: any; constructor(range: TextUtils.TextRange.TextRange, type: string, data: any) { this.rangeInternal = range; this.typeInternal = type; this.dataInternal = data; } range(): TextUtils.TextRange.TextRange { return this.rangeInternal; } type(): string { return this.typeInternal; } data(): any { return this.dataInternal; } } export class UISourceCodeMetadata { modificationTime: Date|null; contentSize: number|null; constructor(modificationTime: Date|null, contentSize: number|null) { this.modificationTime = modificationTime; this.contentSize = contentSize; } }
the_stack
import {Screen} from "@nativescript/core/platform"; declare const Phaser; const scale = Screen.mainScreen.scale; const maxWidth = Screen.mainScreen.widthPixels; const maxHeight = Screen.mainScreen.heightPixels; /** * * Game configurations. * @name configurations */ /*const configurations = { type: Phaser.AUTO, width: 288, height: 512, physics: { default: "arcade", arcade: { gravity: { y: 300, }, debug: false, }, }, scene: { preload: preload, create: create, update: update, }, }; /** * Game assets. * @name assets */ const assets = { bird: { red: 'bird-red', yellow: 'bird-yellow', blue: 'bird-blue' }, obstacle: { pipe: { green: { top: 'pipe-green-top', bottom: 'pipe-green-bottom' }, red: { top: 'pipe-red-top', bottom: 'pipe-red-bo' } } }, scene: { width: 144, background: { day: 'background-day', night: 'background-night' }, ground: 'ground', gameOver: 'game-over', restart: 'restart-button', messageInitial: 'message-initial' }, scoreboard: { width: 25, base: 'number', number0: 'number0', number1: 'number1', number2: 'number2', number3: 'number3', number4: 'number4', number5: 'number5', number6: 'number6', number7: 'number7', number8: 'number8', number9: 'number9' }, animation: { bird: { red: { clapWings: 'red-clap-wings', stop: 'red-stop' }, blue: { clapWings: 'blue-clap-wings', stop: 'blue-stop' }, yellow: { clapWings: 'yellow-clap-wings', stop: 'yellow-stop' } }, ground: { moving: 'moving-ground', stop: 'stop-ground' } } } // Game /** * The main controller for the entire Phaser game. * @name game * @type {object} */ let game; /** * If it had happened a game over. * @type {boolean} */ let gameOver /** * If the game has been started. * @type {boolean} */ let gameStarted /** * Up button component. * @type {object} */ let upButton /** * Restart button component. * @type {object} */ let restartButton /** * Game over banner component. * @type {object} */ let gameOverBanner /** * Message initial component. * @type {object} */ let messageInitial // Bird /** * Player component. * @type {object} */ let player /** * Bird name asset. * @type {string} */ let birdName /** * Quantity frames to move up. * @type {number} */ let framesMoveUp // Background /** * Day background component. * @type {object} */ let backgroundDay /** * Night background component. * @type {object} */ let backgroundNight /** * Ground component. * @type {object} */ let ground // pipes /** * Pipes group component. * @type {object} */ let pipesGroup /** * Gaps group component. * @type {object} */ let gapsGroup /** * Counter till next pipes to be created. * @type {number} */ let nextPipes /** * Current pipe asset. * @type {object} */ let currentPipe // score variables /** * Scoreboard group component. * @type {object} */ let scoreboardGroup /** * Score counter. * @type {number} */ let score /** * Load the game assets. */ const root = '~/assets/phaser/flappybird'; function preload() { // Backgrounds and ground this.load.image(assets.scene.background.day, root + '/background-day.png') this.load.image(assets.scene.background.night, root + '/background-night.png') this.load.spritesheet(assets.scene.ground, root + '/ground-sprite.png', { frameWidth: 336, frameHeight: 112 }) // Pipes this.load.image(assets.obstacle.pipe.green.top, root + '/pipe-green-top.png') this.load.image(assets.obstacle.pipe.green.bottom, root + '/pipe-green-bottom.png') this.load.image(assets.obstacle.pipe.red.top, root + '/pipe-red-top.png') this.load.image(assets.obstacle.pipe.red.bottom, root + '/pipe-red-bottom.png') // Start game this.load.image(assets.scene.messageInitial, root + '/message-initial.png') // End game this.load.image(assets.scene.gameOver, root + '/gameover.png') this.load.image(assets.scene.restart, root + '/restart-button.png') // Birds this.load.spritesheet(assets.bird.red, root + '/bird-red-sprite.png', { frameWidth: 34, frameHeight: 24 }) this.load.spritesheet(assets.bird.blue, root + '/bird-blue-sprite.png', { frameWidth: 34, frameHeight: 24 }) this.load.spritesheet(assets.bird.yellow, root + '/bird-yellow-sprite.png', { frameWidth: 34, frameHeight: 24 }) // Numbers this.load.image(assets.scoreboard.number0, root + '/number0.png') this.load.image(assets.scoreboard.number1, root + '/number1.png') this.load.image(assets.scoreboard.number2, root + '/number2.png') this.load.image(assets.scoreboard.number3, root + '/number3.png') this.load.image(assets.scoreboard.number4, root + '/number4.png') this.load.image(assets.scoreboard.number5, root + '/number5.png') this.load.image(assets.scoreboard.number6, root + '/number6.png') this.load.image(assets.scoreboard.number7, root + '/number7.png') this.load.image(assets.scoreboard.number8, root + '/number8.png') this.load.image(assets.scoreboard.number9, root + '/number9.png') } /** * Create the game objects (images, groups, sprites and animations). */ function create() { backgroundDay = this.add.image(assets.scene.width, 256, assets.scene.background.day).setInteractive() backgroundDay.on('pointerdown', moveBird) backgroundNight = this.add.image(assets.scene.width, 256, assets.scene.background.night).setInteractive() backgroundNight.visible = false backgroundNight.on('pointerdown', moveBird) gapsGroup = this.physics.add.group() pipesGroup = this.physics.add.group() scoreboardGroup = this.physics.add.staticGroup() ground = this.physics.add.sprite(assets.scene.width, this.scale.height - 400, assets.scene.ground) ground.setCollideWorldBounds(true) ground.setDepth(10) messageInitial = this.add.image(assets.scene.width, 156, assets.scene.messageInitial) messageInitial.setDepth(30) messageInitial.visible = false upButton = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.UP) // Ground animations this.anims.create({ key: assets.animation.ground.moving, frames: this.anims.generateFrameNumbers(assets.scene.ground, { start: 0, end: 2 }), frameRate: 15, repeat: -1 }) this.anims.create({ key: assets.animation.ground.stop, frames: [{ key: assets.scene.ground, frame: 0 }], frameRate: 20 }) // Red Bird Animations this.anims.create({ key: assets.animation.bird.red.clapWings, frames: this.anims.generateFrameNumbers(assets.bird.red, { start: 0, end: 2 }), frameRate: 10, repeat: -1 }) this.anims.create({ key: assets.animation.bird.red.stop, frames: [{ key: assets.bird.red, frame: 1 }], frameRate: 20 }) // Blue Bird animations this.anims.create({ key: assets.animation.bird.blue.clapWings, frames: this.anims.generateFrameNumbers(assets.bird.blue, { start: 0, end: 2 }), frameRate: 10, repeat: -1 }) this.anims.create({ key: assets.animation.bird.blue.stop, frames: [{ key: assets.bird.blue, frame: 1 }], frameRate: 20 }) // Yellow Bird animations this.anims.create({ key: assets.animation.bird.yellow.clapWings, frames: this.anims.generateFrameNumbers(assets.bird.yellow, { start: 0, end: 2 }), frameRate: 10, repeat: -1 }) this.anims.create({ key: assets.animation.bird.yellow.stop, frames: [{ key: assets.bird.yellow, frame: 1 }], frameRate: 20 }) prepareGame(this) gameOverBanner = this.add.image(assets.scene.width, 206, assets.scene.gameOver) gameOverBanner.setDepth(20) gameOverBanner.visible = false restartButton = this.add.image(assets.scene.width, 300, assets.scene.restart).setInteractive() restartButton.on('pointerdown', restartGame) restartButton.setDepth(20) restartButton.visible = false } /** * Update the scene frame by frame, responsible for move and rotate the bird and to create and move the pipes. */ function update() { if (gameOver || !gameStarted) return if (framesMoveUp > 0) framesMoveUp-- else if (Phaser.Input.Keyboard.JustDown(upButton)) moveBird() else { player.setVelocityY(120) if (player.angle < 90) player.angle += 1 } pipesGroup.children.iterate(function (child) { if (child == undefined) return if (child.x < -50) child.destroy() else child.setVelocityX(-100) }) gapsGroup.children.iterate(function (child) { child.body.setVelocityX(-100) }) nextPipes++ if (nextPipes === 130) { makePipes(game.scene.scenes[0]) nextPipes = 0 } } /** * Bird collision event. * @param {object} player - Game object that collided, in this case the bird. */ function hitBird(player) { this.physics.pause() gameOver = true gameStarted = false player.anims.play(getAnimationBird(birdName).stop) ground.anims.play(assets.animation.ground.stop) gameOverBanner.visible = true restartButton.visible = true } /** * Update the scoreboard. * @param {object} _ - Game object that overlapped, in this case the bird (ignored). * @param {object} gap - Game object that was overlapped, in this case the gap. */ function updateScore(_, gap) { score++ gap.destroy() if (score % 10 == 0) { backgroundDay.visible = !backgroundDay.visible backgroundNight.visible = !backgroundNight.visible if (currentPipe === assets.obstacle.pipe.green) currentPipe = assets.obstacle.pipe.red else currentPipe = assets.obstacle.pipe.green } updateScoreboard() } /** * Create pipes and gap in the game. * @param {object} scene - Game scene. */ function makePipes(scene) { if (!gameStarted || gameOver) return const pipeTopY = Phaser.Math.Between(-120, 120) const gap = scene.add.line(288, pipeTopY + 210, 0, 0, 0, 98) gapsGroup.add(gap) gap.body.allowGravity = false gap.visible = false const pipeTop = pipesGroup.create(288, pipeTopY, currentPipe.top) pipeTop.body.allowGravity = false const pipeBottom = pipesGroup.create(288, pipeTopY + 420, currentPipe.bottom) pipeBottom.body.allowGravity = false } /** * Move the bird in the screen. */ function moveBird() { if (gameOver) return if (!gameStarted) startGame(game.scene.scenes[0]) player.setVelocityY(-400) player.angle = -15 framesMoveUp = 5 } /** * Get a random bird color. * @return {string} Bird color asset. */ function getRandomBird() { switch (Phaser.Math.Between(0, 2)) { case 0: return assets.bird.red case 1: return assets.bird.blue case 2: default: return assets.bird.yellow } } /** * Get the animation name from the bird. * @param {string} birdColor - Game bird color asset. * @return {object} - Bird animation asset. */ function getAnimationBird(birdColor) { switch (birdColor) { case assets.bird.red: return assets.animation.bird.red case assets.bird.blue: return assets.animation.bird.blue case assets.bird.yellow: default: return assets.animation.bird.yellow } } /** * Update the game scoreboard. */ function updateScoreboard() { scoreboardGroup.clear(true, true) const scoreAsString = score.toString() if (scoreAsString.length == 1) scoreboardGroup.create(assets.scene.width, 30, assets.scoreboard.base + score).setDepth(10) else { let initialPosition = assets.scene.width - ((score.toString().length * assets.scoreboard.width) / 2) for (let i = 0; i < scoreAsString.length; i++) { scoreboardGroup.create(initialPosition, 30, assets.scoreboard.base + scoreAsString[i]).setDepth(10) initialPosition += assets.scoreboard.width } } } /** * Restart the game. * Clean all groups, hide game over objects and stop game physics. */ function restartGame() { pipesGroup.clear(true, true) pipesGroup.clear(true, true) gapsGroup.clear(true, true) scoreboardGroup.clear(true, true) player.destroy() gameOverBanner.visible = false restartButton.visible = false const gameScene = game.scene.scenes[0] prepareGame(gameScene) gameScene.physics.resume() } /** * Restart all variable and configurations, show main and recreate the bird. * @param {object} scene - Game scene. */ function prepareGame(scene) { framesMoveUp = 0 nextPipes = 0 currentPipe = assets.obstacle.pipe.green score = 0 gameOver = false backgroundDay.visible = true backgroundNight.visible = false messageInitial.visible = true birdName = getRandomBird() player = scene.physics.add.sprite(60, 265, birdName) player.setCollideWorldBounds(true) player.anims.play(getAnimationBird(birdName).clapWings, true) player.body.allowGravity = false scene.physics.add.collider(player, ground, hitBird, null, scene) scene.physics.add.collider(player, pipesGroup, hitBird, null, scene) scene.physics.add.overlap(player, gapsGroup, updateScore, null, scene) ground.anims.play(assets.animation.ground.moving, true) } /** * Start the game, create pipes and hide the main menu. * @param {object} scene - Game scene. */ function startGame(scene) { gameStarted = true messageInitial.visible = false const score0 = scoreboardGroup.create(assets.scene.width, 30, assets.scoreboard.number0) score0.setDepth(20) makePipes(scene) } export function setupGame(canvas) { game = require("@nativescript/canvas-phaser").Game({ canvas, type: 2, scene: { preload, create, update, }, physics: { default: "arcade", arcade: { debug: false, }, }, }); }
the_stack
import {Class, AnyTiming, Timing} from "@swim/util"; import {MemberFastenerClass, Property} from "@swim/component"; import type {Trait} from "@swim/model"; import {ViewRef} from "@swim/view"; import type {GraphicsView} from "@swim/graphics"; import {Controller, TraitViewRef, TraitViewControllerSet} from "@swim/controller"; import type {DialView} from "../dial/DialView"; import type {DialTrait} from "../dial/DialTrait"; import {DialController} from "../dial/DialController"; import {GaugeView} from "./GaugeView"; import {GaugeTitle, GaugeTrait} from "./GaugeTrait"; import type {GaugeControllerObserver} from "./GaugeControllerObserver"; /** @public */ export interface GaugeControllerDialExt { attachDialTrait(dialTrait: DialTrait, dialController: DialController): void; detachDialTrait(dialTrait: DialTrait, dialController: DialController): void; attachDialView(dialView: DialView, dialController: DialController): void; detachDialView(dialView: DialView, dialController: DialController): void; attachDialLabelView(labelView: GraphicsView, dialController: DialController): void; detachDialLabelView(labelView: GraphicsView, dialController: DialController): void; attachDialLegendView(legendView: GraphicsView, dialController: DialController): void; detachDialLegendView(legendView: GraphicsView, dialController: DialController): void; } /** @public */ export class GaugeController extends Controller { override readonly observerType?: Class<GaugeControllerObserver>; protected createTitleView(title: GaugeTitle, gaugeTrait: GaugeTrait): GraphicsView | string | null { if (typeof title === "function") { return title(gaugeTrait); } else { return title; } } protected setTitleView(title: GaugeTitle | null, gaugeTrait: GaugeTrait): void { const gaugeView = this.gauge.view; if (gaugeView !== null) { const titleView = title !== null ? this.createTitleView(title, gaugeTrait) : null; gaugeView.title.setView(titleView); } } protected setLimit(limit: number): void { const gaugeView = this.gauge.view; if (gaugeView !== null) { gaugeView.limit.setState(limit); } } @TraitViewRef<GaugeController, GaugeTrait, GaugeView>({ traitType: GaugeTrait, observesTrait: true, willAttachTrait(gaugeTrait: GaugeTrait): void { this.owner.callObservers("controllerWillAttachGaugeTrait", gaugeTrait, this.owner); }, didAttachTrait(gaugeTrait: GaugeTrait): void { const dialTraits = gaugeTrait.dials.traits; for (const traitId in dialTraits) { const dialTrait = dialTraits[traitId]!; this.owner.dials.addTraitController(dialTrait); } const gaugeView = this.view; if (gaugeView !== null) { this.owner.setTitleView(gaugeTrait.title.value, gaugeTrait); this.owner.setLimit(gaugeTrait.limit.value); } }, willDetachTrait(gaugeTrait: GaugeTrait): void { const gaugeView = this.view; if (gaugeView !== null) { this.owner.setTitleView(null, gaugeTrait); this.owner.setLimit(0); } const dialTraits = gaugeTrait.dials.traits; for (const traitId in dialTraits) { const dialTrait = dialTraits[traitId]!; this.owner.dials.deleteTraitController(dialTrait); } }, didDetachTrait(gaugeTrait: GaugeTrait): void { this.owner.callObservers("controllerDidDetachGaugeTrait", gaugeTrait, this.owner); }, traitDidSetGaugeTitle(newTitle: GaugeTitle | null, oldTitle: GaugeTitle | null, gaugeTrait: GaugeTrait): void { this.owner.setTitleView(newTitle, gaugeTrait); }, traitDidSetGaugeLimit(newLimit: number, oldLimit: number, gaugeTrait: GaugeTrait): void { this.owner.setLimit(newLimit); }, traitWillAttachDial(dialTrait: DialTrait, targetTrait: Trait): void { this.owner.dials.addTraitController(dialTrait, targetTrait); }, traitDidDetachDial(dialTrait: DialTrait): void { this.owner.dials.deleteTraitController(dialTrait); }, viewType: GaugeView, observesView: true, initView(gaugeView: GaugeView): void { const dialControllers = this.owner.dials.controllers; for (const controllerId in dialControllers) { const dialController = dialControllers[controllerId]!; const dialView = dialController.dial.view; if (dialView !== null && dialView.parent === null) { dialController.dial.insertView(gaugeView); } } this.owner.title.setView(gaugeView.title.view); const gaugeTrait = this.trait; if (gaugeTrait !== null) { this.owner.setTitleView(gaugeTrait.title.value, gaugeTrait); this.owner.setLimit(gaugeTrait.limit.value); } }, deinitView(gaugeView: GaugeView): void { this.owner.title.setView(null); }, willAttachView(gaugeView: GaugeView): void { this.owner.callObservers("controllerWillAttachGaugeView", gaugeView, this.owner); }, didDetachView(gaugeView: GaugeView): void { this.owner.callObservers("controllerDidDetachGaugeView", gaugeView, this.owner); }, viewWillAttachGaugeTitle(titleView: GraphicsView): void { this.owner.title.setView(titleView); }, viewDidDetachGaugeTitle(titleView: GraphicsView): void { this.owner.title.setView(null); }, }) readonly gauge!: TraitViewRef<this, GaugeTrait, GaugeView>; static readonly gauge: MemberFastenerClass<GaugeController, "gauge">; @ViewRef<GaugeController, GraphicsView>({ key: true, willAttachView(titleView: GraphicsView): void { this.owner.callObservers("controllerWillAttachGaugeTitleView", titleView, this.owner); }, didDetachView(titleView: GraphicsView): void { this.owner.callObservers("controllerDidDetachGaugeTitleView", titleView, this.owner); }, }) readonly title!: ViewRef<this, GraphicsView>; static readonly title: MemberFastenerClass<GaugeController, "title">; @Property({type: Timing, value: true}) readonly dialTiming!: Property<this, Timing | boolean | undefined, AnyTiming>; @TraitViewControllerSet<GaugeController, DialTrait, DialView, DialController, GaugeControllerDialExt>({ implements: true, type: DialController, binds: true, observes: true, get parentView(): GaugeView | null { return this.owner.gauge.view; }, getTraitViewRef(dialController: DialController): TraitViewRef<unknown, DialTrait, DialView> { return dialController.dial; }, willAttachController(dialController: DialController): void { this.owner.callObservers("controllerWillAttachDial", dialController, this.owner); }, didAttachController(dialController: DialController): void { const dialTrait = dialController.dial.trait; if (dialTrait !== null) { this.attachDialTrait(dialTrait, dialController); } const dialView = dialController.dial.view; if (dialView !== null) { this.attachDialView(dialView, dialController); } }, willDetachController(dialController: DialController): void { const dialView = dialController.dial.view; if (dialView !== null) { this.detachDialView(dialView, dialController); } const dialTrait = dialController.dial.trait; if (dialTrait !== null) { this.detachDialTrait(dialTrait, dialController); } }, didDetachController(dialController: DialController): void { this.owner.callObservers("controllerDidDetachDial", dialController, this.owner); }, controllerWillAttachDialTrait(dialTrait: DialTrait, dialController: DialController): void { this.owner.callObservers("controllerWillAttachDialTrait", dialTrait, dialController, this.owner); this.attachDialTrait(dialTrait, dialController); }, controllerDidDetachDialTrait(dialTrait: DialTrait, dialController: DialController): void { this.detachDialTrait(dialTrait, dialController); this.owner.callObservers("controllerDidDetachDialTrait", dialTrait, dialController, this.owner); }, attachDialTrait(dialTrait: DialTrait, dialController: DialController): void { // hook }, detachDialTrait(dialTrait: DialTrait, dialController: DialController): void { // hook }, controllerWillAttachDialView(dialView: DialView, dialController: DialController): void { this.owner.callObservers("controllerWillAttachDialView", dialView, dialController, this.owner); this.attachDialView(dialView, dialController); }, controllerDidDetachDialView(dialView: DialView, dialController: DialController): void { this.detachDialView(dialView, dialController); this.owner.callObservers("controllerDidDetachDialView", dialView, dialController, this.owner); }, attachDialView(dialView: DialView, dialController: DialController): void { const labelView = dialView.label.view; if (labelView !== null) { this.attachDialLabelView(labelView, dialController); } const legendView = dialView.legend.view; if (legendView !== null) { this.attachDialLegendView(legendView, dialController); } }, detachDialView(dialView: DialView, dialController: DialController): void { const legendView = dialView.legend.view; if (legendView !== null) { this.detachDialLegendView(legendView, dialController); } const labelView = dialView.label.view; if (labelView !== null) { this.detachDialLabelView(labelView, dialController); } dialView.remove(); }, controllerWillSetDialValue(newValue: number, oldValue: number, dialController: DialController): void { this.owner.callObservers("controllerWillSetDialValue", newValue, oldValue, dialController, this.owner); }, controllerDidSetDialValue(newValue: number, oldValue: number, dialController: DialController): void { this.owner.callObservers("controllerDidSetDialValue", newValue, oldValue, dialController, this.owner); }, controllerWillSetDialLimit(newLimit: number, oldLimit: number, dialController: DialController): void { this.owner.callObservers("controllerWillSetDialLimit", newLimit, oldLimit, dialController, this.owner); }, controllerDidSetDialLimit(newLimit: number, oldLimit: number, dialController: DialController): void { this.owner.callObservers("controllerDidSetDialLimit", newLimit, oldLimit, dialController, this.owner); }, controllerWillAttachDialLabelView(labelView: GraphicsView, dialController: DialController): void { this.owner.callObservers("controllerWillAttachDialLabelView", labelView, dialController, this.owner); this.attachDialLabelView(labelView, dialController); }, controllerDidDetachDialLabelView(labelView: GraphicsView, dialController: DialController): void { this.detachDialLabelView(labelView, dialController); this.owner.callObservers("controllerDidDetachDialLabelView", labelView, dialController, this.owner); }, attachDialLabelView(labelView: GraphicsView, dialController: DialController): void { // hook }, detachDialLabelView(labelView: GraphicsView, dialController: DialController): void { // hook }, controllerWillAttachDialLegendView(legendView: GraphicsView, dialController: DialController): void { this.owner.callObservers("controllerWillAttachDialLegendView", legendView, dialController, this.owner); this.attachDialLegendView(legendView, dialController); }, controllerDidDetachDialLegendView(legendView: GraphicsView, dialController: DialController): void { this.detachDialLegendView(legendView, dialController); this.owner.callObservers("controllerDidDetachDialLegendView", legendView, dialController, this.owner); }, attachDialLegendView(legendView: GraphicsView, dialController: DialController): void { // hook }, detachDialLegendView(legendView: GraphicsView, dialController: DialController): void { // hook }, }) readonly dials!: TraitViewControllerSet<this, DialTrait, DialView, DialController> & GaugeControllerDialExt; static readonly dials: MemberFastenerClass<GaugeController, "dials">; }
the_stack
import { ILogger, IContainer, Writable, IDisposable, } from '@aurelia/kernel'; import { IFile, } from '../system/interfaces.js'; import { Intrinsics, } from './intrinsics.js'; import { $EnvRec, $ModuleEnvRec, $GlobalEnvRec, $FunctionEnvRec, $DeclarativeEnvRec, } from './types/environment-record.js'; import { $PropertyDescriptor, } from './types/property-descriptor.js'; import { $DefinePropertyOrThrow, } from './operations.js'; import { $String, } from './types/string.js'; import { $Undefined, } from './types/undefined.js'; import { $Object, } from './types/object.js'; import { $Reference, } from './types/reference.js'; import { $AnyNonEmpty, } from './types/_shared.js'; import { $Function, } from './types/function.js'; import { $Null, } from './types/null.js'; import { $Boolean, } from './types/boolean.js'; import { $Error, } from './types/error.js'; import { $NamespaceExoticObject, } from './exotics/namespace.js'; import { $List, } from './types/list.js'; import { $Number, } from './types/number.js'; import { $TemplateExpression, $TaggedTemplateExpression, } from './ast/expressions.js'; import { $$ESModuleOrScript, } from './ast/modules.js'; import { $GeneratorInstance, } from './globals/generator-function.js'; import { JobQueue, } from './job.js'; import { $AsyncGeneratorInstance, } from './globals/async-generator-function.js'; export class ResolveSet { private readonly modules: IModule[] = []; private readonly exportNames: $String[] = []; private count: number = 0; public has(mod: IModule, exportName: $String): boolean { const modules = this.modules; const exportNames = this.exportNames; const count = this.count; for (let i = 0; i < count; ++i) { if (exportNames[i].is(exportName) && modules[i] === mod) { return true; } } return false; } public add(mod: IModule, exportName: $String): void { const index = this.count; this.modules[index] = mod; this.exportNames[index] = exportName; ++this.count; } public forEach(callback: (mod: IModule, exportName: $String) => void): void { const modules = this.modules; const exportNames = this.exportNames; const count = this.count; for (let i = 0; i < count; ++i) { callback(modules[i], exportNames[i]); } } } export class ResolvedBindingRecord { public get isAbrupt(): false { return false; } public get isNull(): false { return false; } public get isAmbiguous(): false { return false; } public constructor( public readonly Module: IModule, public readonly BindingName: $String, ) { } } // http://www.ecma-international.org/ecma-262/#sec-abstract-module-records export interface IModule extends IDisposable { /** This field is never used. Its only purpose is to help TS distinguish this interface from others. */ readonly '<IModule>': unknown; readonly isAbrupt: false; '[[Environment]]': $ModuleEnvRec | $Undefined; '[[Namespace]]': $NamespaceExoticObject | $Undefined; '[[HostDefined]]': any; readonly realm: Realm; ResolveExport(ctx: ExecutionContext, exportName: $String, resolveSet: ResolveSet): ResolvedBindingRecord | $Null | $String<'ambiguous'> | $Error; GetExportedNames(ctx: ExecutionContext, exportStarSet: Set<IModule>): $List<$String> | $Error; Instantiate(ctx: ExecutionContext): $Undefined | $Error; /** @internal */ _InnerModuleInstantiation(ctx: ExecutionContext, stack: IModule[], index: $Number): $Number | $Error; } export class DeferredModule implements IModule { public readonly '<IModule>': unknown; public '[[Environment]]': $ModuleEnvRec | $Undefined; public '[[Namespace]]': $NamespaceExoticObject | $Undefined; public '[[HostDefined]]': any; public get isAbrupt(): false { return false; } public constructor( public readonly $file: IFile, public readonly realm: Realm, ) { } public ResolveExport(ctx: ExecutionContext, exportName: $String, resolveSet: ResolveSet): ResolvedBindingRecord | $Null | $String<'ambiguous'> | $Error { throw new Error('Method not implemented.'); } public GetExportedNames(ctx: ExecutionContext, exportStarSet: Set<IModule>): $List<$String> | $Error { throw new Error('Method not implemented.'); } public Instantiate(ctx: ExecutionContext): $Undefined | $Error { throw new Error('Method not implemented.'); } public _InnerModuleInstantiation(ctx: ExecutionContext, stack: IModule[], index: $Number): $Number | $Error { throw new Error('Method not implemented.'); } public dispose(): void { throw new Error('Method not implemented.'); } } // http://www.ecma-international.org/ecma-262/#sec-code-realms export class Realm implements IDisposable { public timeout: number = 100; public contextId: number = 0; public readonly stack: ExecutionContextStack; public '[[Intrinsics]]': Intrinsics; public '[[GlobalObject]]': $Object; public '[[GlobalEnv]]': $GlobalEnvRec; public '[[TemplateMap]]': { '[[Site]]': $TemplateExpression | $TaggedTemplateExpression; '[[Array]]': $Object }[]; public get isAbrupt(): false { return false; } private constructor( public readonly container: IContainer, public readonly logger: ILogger, public readonly PromiseJobs: JobQueue, ) { this.stack = new ExecutionContextStack(logger); } // http://www.ecma-international.org/ecma-262/#sec-createrealm // 8.2.1 CreateRealm ( ) public static Create( container: IContainer, promiseJobs: JobQueue, ): Realm { const logger = container.get(ILogger).root.scopeTo('Realm'); logger.debug('Creating new realm'); // 1. Let realmRec be a new Realm Record. const realm = new Realm(container, logger, promiseJobs); // 2. Perform CreateIntrinsics(realmRec). new Intrinsics(realm); // 3. Set realmRec.[[GlobalObject]] to undefined. realm['[[GlobalObject]]'] = (void 0)!; // 4. Set realmRec.[[GlobalEnv]] to undefined. realm['[[GlobalEnv]]'] = (void 0)!; // 5. Set realmRec.[[TemplateMap]] to a new empty List. realm['[[TemplateMap]]'] = []; // 6. Return realmRec. // http://www.ecma-international.org/ecma-262/#sec-initializehostdefinedrealm // 8.5 InitializeHostDefinedRealm ( ) // 1. Let realm be CreateRealm(). const intrinsics = realm['[[Intrinsics]]']; // 2. Let newContext be a new execution context. const newContext = new ExecutionContext(realm); // 3. Set the Function of newContext to null. newContext.Function = intrinsics.null; // 4. Set the Realm of newContext to realm. // 5. Set the ScriptOrModule of newContext to null. newContext.ScriptOrModule = intrinsics.null; // 6. Push newContext onto the execution context stack; newContext is now the running execution context. realm.stack.push(newContext); // 7. If the host requires use of an exotic object to serve as realm's global object, let global be such an object created in an implementation-defined manner. Otherwise, let global be undefined, indicating that an ordinary object should be created as the global object. const globalObj = $Object.ObjectCreate(newContext, 'GlobalObject', intrinsics['%ObjectPrototype%']); // 8. If the host requires that the this binding in realm's global scope return an object other than the global object, let thisValue be such an object created in an implementation-defined manner. Otherwise, let thisValue be undefined, indicating that realm's global this binding should be the global object. const thisValue = globalObj; // Note: the two steps above are consolidated with setrealmglobalobject steps // 9. Perform SetRealmGlobalObject(realm, global, thisValue). // http://www.ecma-international.org/ecma-262/#sec-setrealmglobalobject // 8.2.3 SetRealmGlobalObject ( realmRec , globalObj , thisValue ) // 1. If globalObj is undefined, then // 1. a. Let intrinsics be realmRec.[[Intrinsics]]. // 1. b. Set globalObj to ObjectCreate(intrinsics.[[%ObjectPrototype%]]). // 2. Assert: Type(globalObj) is Object. // 3. If thisValue is undefined, set thisValue to globalObj. // 4. Set realmRec.[[GlobalObject]] to globalObj. realm['[[GlobalObject]]'] = globalObj as $Object; // 5. Let newGlobalEnv be NewGlobalEnvironment(globalObj, thisValue). const newGlobalEnv = new $GlobalEnvRec(logger, realm, globalObj as $Object, thisValue as $Object); // 6. Set realmRec.[[GlobalEnv]] to newGlobalEnv. realm['[[GlobalEnv]]'] = newGlobalEnv; // 7. Return realmRec. // 10. Let globalObj be ? SetDefaultGlobalBindings(realm). // http://www.ecma-international.org/ecma-262/#sec-setdefaultglobalbindings // 8.2.4 SetDefaultGlobalBindings ( realmRec ) // 1. Let global be realmRec.[[GlobalObject]]. const global = realm['[[GlobalObject]]']; // 2. For each property of the Global Object specified in clause 18, do // 2. a. Let name be the String value of the property name. // 2. b. Let desc be the fully populated data property descriptor for the property containing the specified attributes for the property. For properties listed in 18.2, 18.3, or 18.4 the value of the [[Value]] attribute is the corresponding intrinsic object from realmRec. // 2. c. Perform ? DefinePropertyOrThrow(global, name, desc). // 3. Return global. function def(propertyName: string, intrinsicName: Exclude<keyof Intrinsics, 'dispose'>): void { const name = new $String(realm, propertyName); const desc = new $PropertyDescriptor(realm, name); desc['[[Writable]]'] = intrinsics.false; desc['[[Enumerable]]'] = intrinsics.false; desc['[[Configurable]]'] = intrinsics.false; desc['[[Value]]'] = intrinsics[intrinsicName]; $DefinePropertyOrThrow(newContext, global, name, desc); } // http://www.ecma-international.org/ecma-262/#sec-value-properties-of-the-global-object // 18.1 Value Properties of the Global Object def('Infinity', 'Infinity'); def('NaN', 'NaN'); def('undefined', 'undefined'); // http://www.ecma-international.org/ecma-262/#sec-function-properties-of-the-global-object // 18.2 Function Properties of the Global Object def('eval', '%eval%'); def('isFinite', '%isFinite%'); def('isNaN', '%isNaN%'); def('parseFloat', '%parseFloat%'); def('parseInt', '%parseInt%'); def('decodeURI', '%decodeURI%'); def('decodeURIComponent', '%decodeURIComponent%'); def('encodeURI', '%encodeURI%'); def('encodeURIComponent', '%encodeURIComponent%'); // http://www.ecma-international.org/ecma-262/#sec-constructor-properties-of-the-global-object // 18.3 Constructor Properties of the Global Object def('Array', '%Array%'); def('ArrayBuffer', '%ArrayBuffer%'); def('Boolean', '%Boolean%'); def('DataView', '%DataView%'); def('Date', '%Date%'); def('Error', '%Error%'); def('EvalError', '%EvalError%'); def('Float32Array', '%Float32Array%'); def('Float64Array', '%Float64Array%'); def('Function', '%Function%'); def('Int8Array', '%Int8Array%'); def('Int16Array', '%Int16Array%'); def('Int32Array', '%Int32Array%'); def('Map', '%Map%'); def('Number', '%Number%'); def('Object', '%Object%'); def('Promise', '%Promise%'); def('Proxy', '%Proxy%'); def('RangeError', '%RangeError%'); def('ReferenceError', '%ReferenceError%'); def('RegExp', '%RegExp%'); def('Set', '%Set%'); def('SharedArrayBuffer', '%SharedArrayBuffer%'); def('String', '%String%'); def('Symbol', '%Symbol%'); def('SyntaxError', '%SyntaxError%'); def('TypeError', '%TypeError%'); def('Uint8Array', '%Uint8Array%'); def('Uint8ClampedArray', '%Uint8ClampedArray%'); def('Uint16Array', '%Uint16Array%'); def('Uint32Array', '%Uint32Array%'); def('URIError', '%URIError%'); def('WeakMap', '%WeakMap%'); def('WeakSet', '%WeakSet%'); // http://www.ecma-international.org/ecma-262/#sec-other-properties-of-the-global-object // 18.4 Other Properties of the Global Object def('Atomics', '%Atomics%'); def('JSON', '%JSON%'); def('Math', '%Math%'); def('Reflect', '%Reflect%'); // 11. Create any implementation-defined global object properties on globalObj. // 12. Return NormalCompletion(empty). logger.debug('Finished initializing realm'); return realm; } // http://www.ecma-international.org/ecma-262/#sec-getactivescriptormodule // 8.3.1 GetActiveScriptOrModule ( ) public GetActiveScriptOrModule(): $$ESModuleOrScript { const stack = this.stack; // 1. If the execution context stack is empty, return null. if (stack.length === 0) { // We're throwing here for now. Not sure in which scenario this could be null that would not throw at some point. throw new Error(`GetActiveScriptOrModule: stack is empty`); } // 2. Let ec be the topmost execution context on the execution context stack whose ScriptOrModule component is not null. let ec: ExecutionContext; let i = stack.length; while (i-- > 0) { ec = stack[i]; if (!ec.ScriptOrModule.isNull) { return ec.ScriptOrModule; } } // 3. If no such execution context exists, return null. Otherwise, return ec's ScriptOrModule component. // We're throwing here for now. Not sure in which scenario this could be null that would not throw at some point. throw new Error(`GetActiveScriptOrModule: stack has no execution context with an active module`); } // http://www.ecma-international.org/ecma-262/#sec-resolvebinding // 8.3.2 ResolveBinding ( name [ , env ] ) public ResolveBinding(name: $String, env?: $EnvRec): $Reference | $Error { // 1. If env is not present or if env is undefined, then if (env === void 0) { // 1. a. Set env to the running execution context's LexicalEnvironment. env = this.stack.top.LexicalEnvironment; } // 2. Assert: env is a Lexical Environment. // 3. If the code matching the syntactic production that is being evaluated is contained in strict mode code, let strict be true, else let strict be false. const strict = this['[[Intrinsics]]'].true; // TODO: pass strict mode from source node // 4. Return ? GetIdentifierReference(env, name, strict). return this.GetIdentifierReference(env, name, strict); } // http://www.ecma-international.org/ecma-262/#sec-getthisenvironment // 8.3.3 GetThisEnvironment ( ) public GetThisEnvironment(): $FunctionEnvRec | $GlobalEnvRec | $ModuleEnvRec { // 1. Let lex be the running execution context's LexicalEnvironment. let envRec = this.stack.top.LexicalEnvironment; // 2. Repeat, while (true) { // 2. a. Let envRec be lex's EnvironmentRecord. // 2. b. Let exists be envRec.HasThisBinding(). if (envRec.HasThisBinding(this.stack.top).isTruthy) { // 2. c. If exists is true, return envRec. return envRec as $FunctionEnvRec | $GlobalEnvRec | $ModuleEnvRec; } // 2. d. Let outer be the value of lex's outer environment reference. // 2. e. Assert: outer is not null. // 2. f. Set lex to outer. envRec = envRec.outer as $EnvRec; } } // http://www.ecma-international.org/ecma-262/#sec-resolvethisbinding // 8.3.4 ResolveThisBinding ( ) public ResolveThisBinding(): $AnyNonEmpty { // 1. Let envRec be GetThisEnvironment(). const envRec = this.GetThisEnvironment(); // 2. Return ? envRec.GetThisBinding(). return envRec.GetThisBinding(this.stack.top); } // #region helper methods public GetCurrentLexicalEnvironment(): $EnvRec { return this.stack.top.LexicalEnvironment; } public SetCurrentLexicalEnvironment(envRec: $EnvRec) { this.stack.top.LexicalEnvironment = envRec; } // #endregion public dispose(this: Writable<Partial<Realm>>): void { this.stack!.dispose(); this.stack = void 0; this['[[Intrinsics]]']!.dispose(); this['[[Intrinsics]]'] = void 0; this['[[GlobalObject]]']!.dispose(); this['[[GlobalObject]]'] = void 0; this['[[GlobalEnv]]']!.dispose(); this['[[GlobalEnv]]'] = void 0; this.container = void 0; this.logger = void 0; } // http://www.ecma-international.org/ecma-262/#sec-getidentifierreference // 8.1.2.1 GetIdentifierReference ( lex , name , strict ) private GetIdentifierReference( lex: $EnvRec | $Null, name: $String, strict: $Boolean, ): $Reference | $Error { const intrinsics = this['[[Intrinsics]]']; // 1. If lex is the value null, then if (lex.isNull) { // 1. a. Return a value of type Reference whose base value component is undefined, whose referenced name component is name, and whose strict reference flag is strict. return new $Reference(this, intrinsics.undefined, name, strict, intrinsics.undefined); } // 2. Let envRec be lex's EnvironmentRecord. const envRec = lex; // 3. Let exists be ? envRec.HasBinding(name). const exists = envRec.HasBinding(this.stack.top, name); if (exists.isAbrupt) { return exists; } // 4. If exists is true, then if (exists.isTruthy) { // 4. a. Return a value of type Reference whose base value component is envRec, whose referenced name component is name, and whose strict reference flag is strict. return new $Reference(this, envRec, name, strict, intrinsics.undefined); } // 5. Else, else { // 5. a. Let outer be the value of lex's outer environment reference. const outer = lex.outer; // 5. b. Return ? GetIdentifierReference(outer, name, strict). return this.GetIdentifierReference(outer, name, strict); } } } export class ExecutionContextStack extends Array<ExecutionContext> implements IDisposable { public constructor( public readonly logger: ILogger, ) { super(); this.logger = logger.root.scopeTo('ExecutionContextStack'); } public get top(): ExecutionContext { return this[this.length - 1]; } public push(context: ExecutionContext): number { this.logger.debug(`push(#${context.id}) - new stack size: ${this.length + 1}`); return super.push(context); } public pop(): ExecutionContext { this.logger.debug(`pop(#${this.top.id}) - new stack size: ${this.length - 1}`); return super.pop()!; } public toString(): string { let str = ''; for (let i = 0; i < this.length; ++i) { const fn = this[i].Function; if (fn === void 0 || fn.isNull) { str = `${str} at NULL\n`; } else { str = `${str} at ${fn.toString()}\n`; } } return str; } public dispose(this: Writable<Partial<ExecutionContextStack>>): void { this.forEach!(x => { x.dispose(); }); this.length = 0; this.logger = void 0; } } export class ExecutionContext<TLex extends $EnvRec = $EnvRec, TVar extends ($ModuleEnvRec | $FunctionEnvRec | $DeclarativeEnvRec | $GlobalEnvRec) = ($ModuleEnvRec | $FunctionEnvRec | $DeclarativeEnvRec | $GlobalEnvRec)> implements IDisposable { public readonly id: number; public Function!: $Function | $Null; public ScriptOrModule!: $$ESModuleOrScript | $Null; public LexicalEnvironment!: TLex; public VariableEnvironment!: TVar; public Generator: $GeneratorInstance | $AsyncGeneratorInstance | undefined = void 0; public onResume: ((value: $AnyNonEmpty) => $AnyNonEmpty) | undefined = void 0; public suspended: boolean = false; public readonly logger: ILogger; private activityTimestamp: number = Date.now(); private activeTime: number = 0; private timeoutCheck: number = 0; public constructor( public readonly Realm: Realm, ) { this.id = ++Realm.contextId; this.logger = Realm['logger'].root.scopeTo(`ExecutionContext #${this.id}`); this.logger.debug(`constructor()`); } public checkTimeout(): void { if (!this.suspended) { // Reduce the number of calls to the relative expensive Date.now() if (++this.timeoutCheck === 100) { this.timeoutCheck = 0; this.activeTime += (Date.now() - this.activityTimestamp); this.activityTimestamp = Date.now(); if (this.activeTime >= this.Realm.timeout) { throw new Error(`Operation timed out`); } } } } public resume(): void { this.logger.debug(`resume()`); if (!this.suspended) { throw new Error('ExecutionContext is not suspended'); } if (this.Realm.stack.top !== this) { throw new Error('ExecutionContext is not at the top of the stack'); } this.suspended = false; this.activityTimestamp = Date.now(); } public suspend(): void { this.logger.debug(`suspend()`); if (this.suspended) { throw new Error('ExecutionContext is already suspended'); } if (this.Realm.stack.top !== this) { throw new Error('ExecutionContext is not at the top of the stack'); } this.suspended = true; // Timeout on a per-execution context basis, and only count the time that this context was active. // This reduces false positives while still keeping potential infinite loops in deeply nested stacks (with constant popping/pushing) in check. this.activeTime += (Date.now() - this.activityTimestamp); } public makeCopy(): this { const ctx = new ExecutionContext(this.Realm); ctx.Function = this.Function; ctx.ScriptOrModule = this.ScriptOrModule; ctx.LexicalEnvironment = this.LexicalEnvironment; ctx.VariableEnvironment = this.VariableEnvironment; ctx.Generator = this.Generator; ctx.onResume = this.onResume; ctx.suspended = this.suspended; return ctx as this; } public dispose(this: Writable<Partial<ExecutionContext>>): void { this.Function = void 0; (this.ScriptOrModule as IDisposable).dispose(); this.ScriptOrModule = void 0; (this.LexicalEnvironment as IDisposable).dispose(); this.LexicalEnvironment = void 0; (this.VariableEnvironment as IDisposable).dispose(); this.VariableEnvironment = void 0; this.Generator = void 0; this.Realm = void 0; this.logger = void 0; } }
the_stack
import * as luaparse from 'luaparse'; import { Symbol, SymbolKind } from './symbol'; import { Scope } from './scope'; import { getNodeRange } from '../utils'; export class Analysis { public symbols: Symbol[] = []; private scopeStack: Scope[] = []; private globalScope: Scope | null = null; private cursorScope: Scope | null = null; private completionTableName: string | null = null; public constructor() { luaparse.parse({ locations: true, scope: true, wait: true, comments: false, onCreateScope: () => { const newScope = new Scope(); // Flag the first encountered scope as the global scope. if (this.globalScope == null) { this.globalScope = newScope; } newScope.parentScope = this.scopeStack.length ? this.scopeStack[this.scopeStack.length - 1] : null; this.scopeStack.push(newScope); }, onCreateNode: (node) => { // The chunk is meaningless to us, so ignore it. if (node.type === 'Chunk') { return; } if (this.scopeStack.length === 0) { throw new Error('Empty scope stack when encountering node of type ' + node.type); } const scope = this.scopeStack[this.scopeStack.length - 1]; // Assign the scope to the node so we can access it later node.scope = scope; // And add the node to the scope for ease of iteration scope.nodes.push(node); // If the current node is our scope marker, notedown the scope it corresponds to so we know where to // start our search from. if (node.type === 'Identifier' && node.name === '__scope_marker__') { this.cursorScope = scope; } else if (node.type === 'CallExpression' && node.base.type === 'MemberExpression') { const { name, container } = this.getIdentifierName(node.base); if (name === '__completion_helper__') { this.completionTableName = container; } } }, onDestroyScope: () => { this.scopeStack.pop(); } }); } public write(text: string) { luaparse.write(text); } public end(text: string) { luaparse.end(text); } public buildScopedSymbols(isTableScope: boolean = false) { // If we didn't find the scope containing the cursor, we can't provide scope-aware suggestions. // TODO: Fall back to just providing global symbols? if (this.cursorScope === null) { return; } if (isTableScope) { this.addTableScopeSymbols(); return; } this.addScopedSymbols(); } public buildGlobalSymbols() { if (this.globalScope) { this.globalScope.nodes.forEach((n) => this.addSymbolsForNode(n, false)); } } private addTableScopeSymbols() { if (!this.completionTableName) { return; } let currentScope = this.cursorScope; let abortScopeTraversal = false; while (currentScope !== null) { for (const n of currentScope.nodes) { if (n.type === 'LocalStatement') { // If the cursor scope has introduced a shadowing variable, don't continue traversing the scope // parent tree. if (currentScope === this.cursorScope && n.variables.some(ident => ident.name === this.completionTableName)) { abortScopeTraversal = true; } } else if (n.type === 'AssignmentStatement') { // Add any member fields being assigned to the symbol // filter<> specialization due to a bug in the current Typescript. // Should be fixed in 2.7 by https://github.com/Microsoft/TypeScript/pull/17600 n.variables .filter<luaparse.MemberExpression>((v): v is luaparse.MemberExpression => v.type === 'MemberExpression') .forEach(v => { if (v.base.type === 'Identifier' && v.base.name === this.completionTableName) { this.addSymbolHelper(v.identifier, v.identifier.name, 'Variable', undefined, this.completionTableName); } }); } if (n.type === 'LocalStatement' || n.type === 'AssignmentStatement') { // Find the variable that matches the current symbol to provide completions for, if any. let variableIndex = -1; for (const [i, variable] of n.variables.entries()) { if (variable.type === 'Identifier' && variable.name === this.completionTableName) { variableIndex = i; } } if (variableIndex >= 0) { const variableInit = n.init[variableIndex]; // If the field was initialised with a table, add the fields from it. if (variableInit && variableInit.type === 'TableConstructorExpression') { for (const field of variableInit.fields) { switch (field.type) { case 'TableKey': if (field.key.type === 'StringLiteral') { this.addSymbolHelper(field, field.key.value, 'Variable', undefined, this.completionTableName); } break; case 'TableKeyString': if (field.key.type === 'Identifier') { this.addSymbolHelper(field, field.key.name, 'Variable', undefined, this.completionTableName); } break; } } } } } } if (abortScopeTraversal) { break; } currentScope = currentScope.parentScope; } } private addScopedSymbols() { // Add all of the symbols for the current cursor scope let currentScope: Scope | null = this.cursorScope; while (currentScope !== null) { currentScope.nodes.forEach((n) => this.addSymbolsForNode(n, true)); currentScope = currentScope.parentScope; } } // Nodes don't necessarily need to have an identifier name, nor are their identifiers all of type 'Identifier'. // Return an appropriate name, given the context of the node. private getIdentifierName(identifier: luaparse.Identifier | luaparse.MemberExpression | null) { if (identifier) { switch (identifier.type) { case 'Identifier': return { name: identifier.name, container: null }; case 'MemberExpression': switch (identifier.base.type) { case 'Identifier': return { name: identifier.identifier.name, container: identifier.base.name }; default: return { name: identifier.identifier.name, container: null }; } } } return { name: null, container: null }; } private addSymbolsForNode(node: luaparse.Node, scopedQuery: boolean) { switch (node.type) { case 'LocalStatement': case 'AssignmentStatement': this.addLocalAndAssignmentSymbols(node); break; case 'FunctionDeclaration': this.addFunctionSymbols(node, scopedQuery); break; } } private addSymbolHelper(node: luaparse.Node, name: string | null, kind: SymbolKind, container?: string, display?: string) { this.symbols.push({ kind, name, container, display, range: getNodeRange(node), isGlobalScope: node.scope === this.globalScope, isOuterScope: node.scope !== this.cursorScope }); } private addLocalAndAssignmentSymbols(node: luaparse.LocalStatement | luaparse.AssignmentStatement) { for (const variable of node.variables) { switch (variable.type) { case 'Identifier': this.addSymbolHelper(variable, variable.name, 'Variable'); break; } } } private addFunctionSymbols(node: luaparse.FunctionDeclaration, scopedQuery: boolean) { const { name, container } = this.getIdentifierName(node.identifier); // filter<> specialization due to a bug in the current Typescript. // Should be fixed in 2.7 by https://github.com/Microsoft/TypeScript/pull/17600 const parameters = node.parameters .filter<luaparse.Identifier>((v): v is luaparse.Identifier => v.type === 'Identifier'); // Build a represesntation of the function declaration let display = 'function '; if (container) { display += container + ':'; } if (name) { display += name; } display += '('; display += parameters .map((param: luaparse.Identifier) => param.name) .join(', '); display += ')'; this.addSymbolHelper(node, name, 'Function', container || undefined, display); if (scopedQuery) { parameters .filter(param => param.scope.containsScope(this.cursorScope)) .forEach((param: luaparse.Identifier) => { this.addSymbolHelper(param, param.name, 'FunctionParameter'); }); } } }
the_stack
import { IClockTimer } from '../clock/clock'; import { IRQ } from '../irq'; import { RP2040 } from '../rp2040'; import { BasePeripheral, Peripheral } from './peripheral'; export enum DREQChannel { DREQ_PIO0_TX0, DREQ_PIO0_TX1, DREQ_PIO0_TX2, DREQ_PIO0_TX3, DREQ_PIO0_RX0, DREQ_PIO0_RX1, DREQ_PIO0_RX2, DREQ_PIO0_RX3, DREQ_PIO1_TX0, DREQ_PIO1_TX1, DREQ_PIO1_TX2, DREQ_PIO1_TX3, DREQ_PIO1_RX0, DREQ_PIO1_RX1, DREQ_PIO1_RX2, DREQ_PIO1_RX3, DREQ_SPI0_TX, DREQ_SPI0_RX, DREQ_SPI1_TX, DREQ_SPI1_RX, DREQ_UART0_TX, DREQ_UART0_RX, DREQ_UART1_TX, DREQ_UART1_RX, DREQ_PWM_WRAP0, DREQ_PWM_WRAP1, DREQ_PWM_WRAP2, DREQ_PWM_WRAP3, DREQ_PWM_WRAP4, DREQ_PWM_WRAP5, DREQ_PWM_WRAP6, DREQ_PWM_WRAP7, DREQ_I2C0_TX, DREQ_I2C0_RX, DREQ_I2C1_TX, DREQ_I2C1_RX, DREQ_ADC, DREQ_XIP_STREAM, DREQ_XIP_SSITX, DREQ_XIP_SSIRX, DREQ_MAX, } enum TREQ { Timer0 = 0x3b, Timer1 = 0x3c, Timer2 = 0x3d, Timer3 = 0x3e, Permanent = 0x3f, } // Per-channel registers const CHn_READ_ADDR = 0x000; // DMA Channel n Read Address pointer const CHn_WRITE_ADDR = 0x004; // DMA Channel n Write Address pointer const CHn_TRANS_COUNT = 0x008; // DMA Channel n Transfer Count const CHn_CTRL_TRIG = 0x00c; // DMA Channel n Control and Status const CHn_AL1_CTRL = 0x010; // Alias for channel n CTRL register const CHn_AL1_READ_ADDR = 0x014; // Alias for channel n READ_ADDR register const CHn_AL1_WRITE_ADDR = 0x018; // Alias for channel n WRITE_ADDR register const CHn_AL1_TRANS_COUNT_TRIG = 0x01c; // Alias for channel n TRANS_COUNT register const CHn_AL2_CTRL = 0x020; // Alias for channel n CTRL register const CHn_AL2_TRANS_COUNT = 0x024; // Alias for channel n TRANS_COUNT register const CHn_AL2_READ_ADDR = 0x028; // Alias for channel n READ_ADDR register const CHn_AL2_WRITE_ADDR_TRIG = 0x02c; // Alias for channel n WRITE_ADDR register const CHn_AL3_CTRL = 0x030; // Alias for channel n CTRL register const CHn_AL3_WRITE_ADDR = 0x034; // Alias for channel n WRITE_ADDR register const CHn_AL3_TRANS_COUNT = 0x038; // Alias for channel n TRANS_COUNT register const CHn_AL3_READ_ADDR_TRIG = 0x03c; // Alias for channel n READ_ADDR register const CHn_DBG_CTDREQ = 0x800; const CHn_DBG_TCR = 0x804; const CHANNEL_REGISTERS_SIZE = 12 * 0x40; const CHANNEL_REGISTERS_MASK = 0x83f; // General DMA registers const INTR = 0x400; // Interrupt Status (raw) const INTE0 = 0x404; // Interrupt Enables for IRQ 0 const INTF0 = 0x408; // Force Interrupts const INTS0 = 0x40c; // Interrupt Status for IRQ 0 const INTE1 = 0x414; // Interrupt Enables for IRQ 1 const INTF1 = 0x418; // Force Interrupts for IRQ 1 const INTS1 = 0x41c; // Interrupt Status (masked) for IRQ 1 const TIMER0 = 0x420; // Pacing (X/Y) Fractional Timer const TIMER1 = 0x424; // Pacing (X/Y) Fractional Timer const TIMER2 = 0x428; // Pacing (X/Y) Fractional Timer const TIMER3 = 0x42c; // Pacing (X/Y) Fractional Timer const MULTI_CHAN_TRIGGER = 0x430; // Trigger one or more channels simultaneously const SNIFF_CTRL = 0x434; // Sniffer Control const SNIFF_DATA = 0x438; // Data accumulator for sniff hardware const FIFO_LEVELS = 0x440; // Debug RAF, WAF, TDF levels const CHAN_ABORT = 0x444; // Abort an in-progress transfer sequence on one or more channels const N_CHANNELS = 0x448; // CHn_CTRL_TRIG bits const AHB_ERROR = 1 << 31; const READ_ERROR = 1 << 30; const WRITE_ERROR = 1 << 29; const BUSY = 1 << 24; const SNIFF_EN = 1 << 23; const BSWAP = 1 << 22; const IRQ_QUIET = 1 << 21; const TREQ_SEL_MASK = 0x3f; const TREQ_SEL_SHIFT = 15; const CHAIN_TO_MASK = 0xf; const CHAIN_TO_SHIFT = 11; const RING_SEL = 1 << 10; const RING_SIZE_MASK = 0xf; const RING_SIZE_SHIFT = 6; const INCR_WRITE = 1 << 5; const INCR_READ = 1 << 4; const DATA_SIZE_MASK = 0x3; const DATA_SIZE_SHIFT = 2; const HIGH_PRIORITY = 1 << 1; const EN = 1 << 0; const CHn_CTRL_TRIG_WRITE_MASK = 0xffffff; const CHn_CTRL_TRIG_WC_MASK = READ_ERROR | WRITE_ERROR; export class RPDMAChannel { private ctrl = 0; private readAddr = 0; private writeAddr = 0; private transCount = 0; private dreqCounter = 0; private transCountReload = 0; private treqValue = 0; private dataSize = 1; private chainTo = 0; private ringMask = 0; private transferFn: () => void = () => 0; private transferTimer: IClockTimer | null = null; constructor(readonly dma: RPDMA, readonly rp2040: RP2040, readonly index: number) { this.reset(); } start() { if (!(this.ctrl & EN) || this.ctrl & BUSY) { return; } this.ctrl |= BUSY; this.transCount = this.transCountReload; if (this.transCount) { this.scheduleTransfer(); } } get treq() { return this.treqValue; } get active() { return this.ctrl & EN && this.ctrl & BUSY; } transfer8 = () => { const { rp2040 } = this; rp2040.writeUint8(this.writeAddr, rp2040.readUint8(this.readAddr)); }; transfer16 = () => { const { rp2040 } = this; rp2040.writeUint16(this.writeAddr, rp2040.readUint16(this.readAddr)); }; transferSwap16 = () => { const { rp2040 } = this; const input = rp2040.readUint16(this.readAddr); rp2040.writeUint16(this.writeAddr, ((input & 0xff) << 8) | (input >> 8)); }; transfer32 = () => { const { rp2040 } = this; rp2040.writeUint32(this.writeAddr, rp2040.readUint32(this.readAddr)); }; transferSwap32 = () => { const { rp2040 } = this; const input = rp2040.readUint32(this.readAddr); rp2040.writeUint32( this.writeAddr, ((input & 0x000000ff) << 24) | ((input & 0x0000ff00) << 8) | ((input & 0x00ff0000) >> 8) | ((input >> 24) & 0xff) ); }; transfer = () => { const { ctrl, dataSize, ringMask } = this; this.transferTimer = null; this.transferFn(); if (ctrl & INCR_READ) { if (ringMask && !(ctrl & RING_SEL)) { this.readAddr = (this.readAddr & ~ringMask) | ((this.readAddr + dataSize) & ringMask); } else { this.readAddr += dataSize; } } if (ctrl & INCR_WRITE) { if (ringMask && ctrl & RING_SEL) { this.writeAddr = (this.writeAddr & ~ringMask) | ((this.writeAddr + dataSize) & ringMask); } else { this.writeAddr += dataSize; } } this.transCount--; if (this.transCount > 0) { this.scheduleTransfer(); } else { this.ctrl &= ~BUSY; if (!(this.ctrl & IRQ_QUIET)) { this.dma.intRaw |= 1 << this.index; this.dma.checkInterrupts(); } if (this.chainTo !== this.index) { this.dma.channels[this.chainTo]?.start(); } } }; scheduleTransfer() { if (this.transferTimer) { // Already scheduled; do nothing. return; } if (this.dma.dreq[this.treqValue] || this.treqValue === TREQ.Permanent) { this.transferTimer = this.rp2040.clock.createTimer(0, this.transfer); } else { const delay = this.dma.getTimer(this.treqValue); if (delay) { this.transferTimer = this.rp2040.clock.createTimer(delay, this.transfer); } } } abort() { this.ctrl &= ~BUSY; if (this.transferTimer) { this.rp2040.clock.deleteTimer(this.transferTimer); this.transferTimer = null; } } readUint32(offset: number) { switch (offset) { case CHn_READ_ADDR: case CHn_AL1_READ_ADDR: case CHn_AL2_READ_ADDR: case CHn_AL3_READ_ADDR_TRIG: return this.readAddr; case CHn_WRITE_ADDR: case CHn_AL1_WRITE_ADDR: case CHn_AL2_WRITE_ADDR_TRIG: case CHn_AL3_WRITE_ADDR: return this.writeAddr; case CHn_TRANS_COUNT: case CHn_AL1_TRANS_COUNT_TRIG: case CHn_AL2_TRANS_COUNT: case CHn_AL3_TRANS_COUNT: return this.transCount; case CHn_CTRL_TRIG: case CHn_AL1_CTRL: case CHn_AL2_CTRL: case CHn_AL3_CTRL: return this.ctrl; case CHn_DBG_CTDREQ: return this.dreqCounter; case CHn_DBG_TCR: return this.transCountReload; } return 0; } writeUint32(offset: number, value: number) { switch (offset) { case CHn_READ_ADDR: case CHn_AL1_READ_ADDR: case CHn_AL2_READ_ADDR: case CHn_AL3_READ_ADDR_TRIG: this.readAddr = value; break; case CHn_WRITE_ADDR: case CHn_AL1_WRITE_ADDR: case CHn_AL2_WRITE_ADDR_TRIG: case CHn_AL3_WRITE_ADDR: this.writeAddr = value; break; case CHn_TRANS_COUNT: case CHn_AL1_TRANS_COUNT_TRIG: case CHn_AL2_TRANS_COUNT: case CHn_AL3_TRANS_COUNT: this.transCountReload = value; break; case CHn_CTRL_TRIG: case CHn_AL1_CTRL: case CHn_AL2_CTRL: case CHn_AL3_CTRL: { this.ctrl = (this.ctrl & ~CHn_CTRL_TRIG_WRITE_MASK) | (value & CHn_CTRL_TRIG_WRITE_MASK); this.ctrl &= ~(value & CHn_CTRL_TRIG_WC_MASK); // Handle write-clear (WC) bits this.treqValue = (this.ctrl >> TREQ_SEL_SHIFT) & TREQ_SEL_MASK; this.chainTo = (this.ctrl >> CHAIN_TO_SHIFT) & CHAIN_TO_MASK; const ringSize = (this.ctrl >> RING_SIZE_SHIFT) & RING_SIZE_MASK; this.ringMask = ringSize ? (1 << ringSize) - 1 : 0; switch ((this.ctrl >> DATA_SIZE_SHIFT) & DATA_SIZE_MASK) { case 1: this.dataSize = 2; this.transferFn = this.ctrl & BSWAP ? this.transferSwap16 : this.transfer16; break; case 2: this.dataSize = 4; this.transferFn = this.ctrl & BSWAP ? this.transferSwap32 : this.transfer32; break; case 0: default: this.transferFn = this.transfer8; this.dataSize = 1; } if (this.ctrl & EN && this.ctrl & BUSY) { this.scheduleTransfer(); } if (!(this.ctrl & EN) && this.transferTimer) { this.rp2040.clock.deleteTimer(this.transferTimer); this.transferTimer = null; } break; } case CHn_DBG_CTDREQ: this.dreqCounter = 0; break; } if ( offset === CHn_AL3_READ_ADDR_TRIG || offset === CHn_AL2_WRITE_ADDR_TRIG || offset === CHn_AL1_TRANS_COUNT_TRIG || offset === CHn_CTRL_TRIG ) { if (value) { this.start(); } else if (this.ctrl & IRQ_QUIET) { // Null trigger interrupts this.dma.intRaw |= 1 << this.index; this.dma.checkInterrupts(); } } } reset() { this.writeUint32(CHn_CTRL_TRIG, this.index << CHAIN_TO_SHIFT); } } export class RPDMA extends BasePeripheral implements Peripheral { readonly channels = [ new RPDMAChannel(this, this.rp2040, 0), new RPDMAChannel(this, this.rp2040, 1), new RPDMAChannel(this, this.rp2040, 2), new RPDMAChannel(this, this.rp2040, 3), new RPDMAChannel(this, this.rp2040, 4), new RPDMAChannel(this, this.rp2040, 5), new RPDMAChannel(this, this.rp2040, 6), new RPDMAChannel(this, this.rp2040, 7), new RPDMAChannel(this, this.rp2040, 8), new RPDMAChannel(this, this.rp2040, 9), new RPDMAChannel(this, this.rp2040, 10), new RPDMAChannel(this, this.rp2040, 11), ]; intRaw = 0; private intEnable0 = 0; private intForce0 = 0; private intEnable1 = 0; private intForce1 = 0; private timer0 = 0; private timer1 = 0; private timer2 = 0; private timer3 = 0; readonly dreq: boolean[] = Array(DREQChannel.DREQ_MAX); get intStatus0() { return (this.intRaw & this.intEnable0) | this.intForce0; } get intStatus1() { return (this.intRaw & this.intEnable1) | this.intForce1; } readUint32(offset: number) { if ((offset & 0x7ff) <= CHANNEL_REGISTERS_SIZE) { const channelIndex = (offset & 0x7ff) >> 6; return this.channels[channelIndex].readUint32(offset & CHANNEL_REGISTERS_MASK); } switch (offset) { case TIMER0: return this.timer0; case TIMER1: return this.timer1; case TIMER2: return this.timer2; case TIMER3: return this.timer3; case INTR: return this.intRaw; case INTE0: return this.intEnable0; case INTF0: return this.intForce0; case INTS0: return this.intStatus0; case INTE1: return this.intEnable1; case INTF1: return this.intForce1; case INTS1: return this.intStatus1; case N_CHANNELS: return this.channels.length; } return super.readUint32(offset); } writeUint32(offset: number, value: number) { if ((offset & 0x7ff) <= CHANNEL_REGISTERS_SIZE) { const channelIndex = (offset & 0x7ff) >> 6; this.channels[channelIndex].writeUint32(offset & CHANNEL_REGISTERS_MASK, value); return; } switch (offset) { case TIMER0: this.timer0 = value; return; case TIMER1: this.timer1 = value; return; case TIMER2: this.timer2 = value; return; case TIMER3: this.timer3 = value; return; case INTR: case INTS0: case INTS1: this.intRaw &= ~this.rawWriteValue; this.checkInterrupts(); return; case INTE0: this.intEnable0 = value & 0xffff; this.checkInterrupts(); return; case INTF0: this.intForce0 = value & 0xffff; this.checkInterrupts(); return; case INTE1: this.intEnable1 = value & 0xffff; this.checkInterrupts(); return; case INTF1: this.intForce1 = value & 0xffff; this.checkInterrupts(); return; case MULTI_CHAN_TRIGGER: for (const chan of this.channels) { if (value & (1 << chan.index)) { chan.start(); } } return; case CHAN_ABORT: for (const chan of this.channels) { if (value & (1 << chan.index)) { chan.abort(); } } return; default: super.writeUint32(offset, value); } } setDREQ(dreqChannel: DREQChannel) { const { dreq } = this; if (!dreq[dreqChannel]) { dreq[dreqChannel] = true; for (const channel of this.channels) { if (channel.treq === dreqChannel && channel.active) { channel.scheduleTransfer(); } } } } clearDREQ(dreqChannel: DREQChannel) { this.dreq[dreqChannel] = false; } /** * Returns the number of microseconds for a cycle of the given DMA timer, or 0 if the timer is disabled. */ getTimer(treq: TREQ) { let dividend = 0, divisor = 1; switch (treq) { case TREQ.Permanent: dividend = 1; divisor = 1; break; case TREQ.Timer0: dividend = this.timer0 >>> 16; divisor = this.timer0 & 0xffff; break; case TREQ.Timer1: dividend = this.timer1 >>> 16; divisor = this.timer1 & 0xffff; break; case TREQ.Timer2: dividend = this.timer2 >>> 16; divisor = this.timer2 & 0xffff; break; case TREQ.Timer3: dividend = this.timer3 >>> 36; divisor = this.timer3 & 0xffff; break; } if (divisor === 0) { return 0; } return ((dividend / divisor) * 1e6) / this.rp2040.clkSys; } checkInterrupts() { this.rp2040.setInterrupt(IRQ.DMA_IRQ0, !!this.intStatus0); this.rp2040.setInterrupt(IRQ.DMA_IRQ1, !!this.intStatus1); } }
the_stack
import { GraphCommandHandler, mapAppend, NodeListWrapper } from '../shared'; export type NodeId = string; export enum NodeType { Path = 'Path', Request = 'Request', QueryParameters = 'QueryParameters', Response = 'Response', Endpoint = 'Endpoint', Body = 'Body', BatchCommit = 'BatchCommit', } export type Node = | PathNode | RequestNode | ResponseNode | EndpointNode | BodyNode | BatchCommitNode | QueryParametersNode; export type PathNode = { id: NodeId; type: NodeType.Path; data: { absolutePathPattern: string; pathId: string; name: string; isParameterized: boolean; isRemoved: boolean; }; }; export type RequestNode = { id: NodeId; type: NodeType.Request; data: { requestId: string; isRemoved: boolean; }; }; export type ResponseNode = { id: NodeId; type: NodeType.Response; data: { responseId: string; httpStatusCode: number; isRemoved: boolean; }; }; export type EndpointNode = { id: NodeId; type: NodeType.Endpoint; data: { pathId: string; httpMethod: string; id: string; isRemoved: boolean; }; }; export type BodyNode = { id: NodeId; type: NodeType.Body; data: { httpContentType: string; rootShapeId: string; isRemoved: boolean; }; }; export type BatchCommitNode = { id: NodeId; type: NodeType.BatchCommit; data: BatchCommitData; }; export type QueryParametersNode = { id: NodeId; type: NodeType.QueryParameters; data: { queryParametersId: string; rootShapeId: string | null; httpMethod: string; isRemoved: boolean; }; }; export type BatchCommitData = { createdAt: string; batchId: string; commitMessage: string; }; export type NodeWrapper = | BodyNodeWrapper | EndpointNodeWrapper | RequestNodeWrapper | ResponseNodeWrapper | QueryParametersNodeWrapper | PathNodeWrapper | BatchCommitNodeWrapper; // Is there a better way of infering / mapping a type to another type? type NodeTypeToNodeWrapper<T extends NodeType> = T extends NodeType.BatchCommit ? BatchCommitNodeWrapper : T extends NodeType.Body ? BodyNodeWrapper : T extends NodeType.Path ? PathNodeWrapper : T extends NodeType.Request ? RequestNodeWrapper : T extends NodeType.QueryParameters ? QueryParametersNodeWrapper : T extends NodeType.Response ? ResponseNodeWrapper : T extends NodeType.Endpoint ? EndpointNodeWrapper : NodeWrapper; export enum EdgeType { IsChildOf = 'IsChildOf', CreatedIn = 'CreatedIn', UpdatedIn = 'UpdatedIn', RemovedIn = 'RemovedIn', } export type Edge = | { type: EdgeType.IsChildOf; } | { type: EdgeType.UpdatedIn; } | { type: EdgeType.CreatedIn; } | { type: EdgeType.UpdatedIn; }; //////////////////////////////////////////////////////////////////////////////// // A batch commit node can never be removed const isNodeRemoved = (node: Node): boolean => node.type !== NodeType.BatchCommit && node.data.isRemoved; //////////////////////////////////////////////////////////////////////////////// export class GraphIndexer implements GraphCommandHandler<Node, NodeId, Edge> { readonly nodesById: Map<NodeId, Node>; readonly nodesByType: Map<NodeType, Node[]>; readonly outboundNeighbors: Map<NodeId, Map<NodeType, Node[]>>; readonly inboundNeighbors: Map<NodeId, Map<NodeType, Node[]>>; readonly outboundNeighborsByEdgeType: Map<NodeId, Map<EdgeType, Node[]>>; readonly inboundNeighborsByEdgeType: Map<NodeId, Map<EdgeType, Node[]>>; constructor() { this.nodesByType = new Map(); this.nodesById = new Map(); this.outboundNeighbors = new Map(); this.inboundNeighbors = new Map(); this.outboundNeighborsByEdgeType = new Map(); this.inboundNeighborsByEdgeType = new Map(); } addNode(node: Node) { if (this.nodesById.has(node.id)) { throw new Error( `could not add a node with an id that already exists in the graph` ); } this.unsafeAddNode(node); } addEdge(edge: Edge, sourceNodeId: NodeId, targetNodeId: NodeId) { const sourceNode = this.nodesById.get(sourceNodeId); if (!sourceNode) { throw new Error(`expected ${sourceNodeId} to exist`); } const targetNode = this.nodesById.get(targetNodeId); if (!targetNode) { throw new Error(`expected ${targetNodeId} to exist`); } const outboundNeighbors = this.outboundNeighbors.get(sourceNodeId) || new Map(); mapAppend(outboundNeighbors, targetNode.type, targetNode); this.outboundNeighbors.set(sourceNodeId, outboundNeighbors); const outboundNeighborsByEdgeType = this.outboundNeighborsByEdgeType.get(sourceNodeId) || new Map(); mapAppend(outboundNeighborsByEdgeType, edge.type, targetNode); this.outboundNeighborsByEdgeType.set( sourceNodeId, outboundNeighborsByEdgeType ); const inboundNeighbors = this.inboundNeighbors.get(targetNodeId) || new Map(); mapAppend(inboundNeighbors, sourceNode.type, sourceNode); this.inboundNeighbors.set(targetNodeId, inboundNeighbors); const inboundNeighborsByEdgeType = this.inboundNeighborsByEdgeType.get(targetNodeId) || new Map(); mapAppend(inboundNeighborsByEdgeType, edge.type, sourceNode); this.inboundNeighborsByEdgeType.set( targetNodeId, inboundNeighborsByEdgeType ); } unsafeAddNode(node: Node) { this.nodesById.set(node.id, node); mapAppend(this.nodesByType, node.type, node); } } //////////////////////////////////////////////////////////////////////////////// export class BodyNodeWrapper { constructor(public result: BodyNode, private queries: GraphQueries) {} get value() { return this.result.data; } response(): ResponseNodeWrapper | null { const neighbors = this.queries.listOutgoingNeighborsByType( this.result.id, NodeType.Response ); if (neighbors.results.length === 0) { return null; } return neighbors.results[0]; } request(): RequestNodeWrapper | null { const neighbors = this.queries.listOutgoingNeighborsByType( this.result.id, NodeType.Request ); if (neighbors.results.length === 0) { return null; } return neighbors.results[0]; } } export class EndpointNodeWrapper { constructor(public result: EndpointNode, private queries: GraphQueries) {} get value() { return this.result.data; } path() { const neighbors = this.queries.listOutgoingNeighborsByType( this.result.id, NodeType.Path ); if (neighbors.results.length === 0) { throw new Error(`expected endpoint to have a parent Path`); } return neighbors.results[0]; } query(): QueryParametersNodeWrapper | null { const queryParameters = this.queries.listIncomingNeighborsByType( this.result.id, NodeType.QueryParameters ); return queryParameters.results.length > 0 ? queryParameters.results[0] : null; } requests() { return this.queries.listIncomingNeighborsByType( this.result.id, NodeType.Request ); } responses() { return this.queries.listIncomingNeighborsByType( this.result.id, NodeType.Response ); } } export class RequestNodeWrapper { constructor(public result: RequestNode, private queries: GraphQueries) {} get value() { return this.result.data; } // A request node can be orphaned endpoint(): EndpointNodeWrapper | null { const endpoints = this.queries.listOutgoingNeighborsByType( this.result.id, NodeType.Endpoint ); return endpoints.results.length > 0 ? endpoints.results[0] : null; } body(): BodyNodeWrapper | null { const bodies = this.queries.listIncomingNeighborsByType( this.result.id, NodeType.Body ); return bodies.results.length >= 1 ? bodies.results[0] : null; } } export class ResponseNodeWrapper { constructor(public result: ResponseNode, private queries: GraphQueries) {} get value() { return this.result.data; } // A response node can be orphaned endpoint(): EndpointNodeWrapper | null { const endpoints = this.queries.listOutgoingNeighborsByType( this.result.id, NodeType.Endpoint ); return endpoints.results.length > 0 ? endpoints.results[0] : null; } bodies() { return this.queries.listIncomingNeighborsByType( this.result.id, NodeType.Body ); } } export class QueryParametersNodeWrapper { constructor( public result: QueryParametersNode, private queries: GraphQueries ) {} get value() { return this.result.data; } // A response node can be orphaned endpoint(): EndpointNodeWrapper | null { const endpoints = this.queries.listOutgoingNeighborsByType( this.result.id, NodeType.Endpoint ); return endpoints.results.length > 0 ? endpoints.results[0] : null; } } export class PathNodeWrapper { constructor(public result: PathNode, private queries: GraphQueries) {} get value() { return this.result.data; } parentPath() { const parentPaths = this.queries.listOutgoingNeighborsByType( this.result.id, NodeType.Path ); if (parentPaths.results.length === 0) { return null; } const [parentPath] = parentPaths.results; return parentPath; } endpoints() { return this.queries.listIncomingNeighborsByType( this.result.id, NodeType.Endpoint ); } components(): PathNodeWrapper[] { let pathNode = this as PathNodeWrapper; let parentPath = pathNode.parentPath(); const components = [pathNode]; while (parentPath !== null) { components.push(parentPath); pathNode = parentPath; parentPath = pathNode.parentPath(); } return components.reverse(); } get absolutePathPatternWithParameterNames(): string { let path = ''; const components = this.components(); if (components.length === 1 && components[0].value.pathId === 'root') { return '/'; } for (const component of components) { if (component.value.pathId === 'root') continue; if (component.value.isParameterized) { path = `${path}/{${component.value.name}}`; } else { path = `${path}/${component.value.name}`; } } return path; } } export class BatchCommitNodeWrapper { constructor(public result: BatchCommitNode, private queries: GraphQueries) {} get value() { return this.result.data; } requests() { return this.queries.listIncomingNeighborsByType( this.result.id, NodeType.Request ); } responses() { return this.queries.listIncomingNeighborsByType( this.result.id, NodeType.Response ); } createdInEdgeNodes() { return this.queries.listIncomingNeighborsByEdgeType( this.result.id, EdgeType.CreatedIn ); } updatedInEdgeNodes() { return this.queries.listIncomingNeighborsByEdgeType( this.result.id, EdgeType.UpdatedIn ); } removedInEdgeNodes() { return this.queries.listIncomingNeighborsByEdgeType( this.result.id, EdgeType.RemovedIn ); } } //////////////////////////////////////////////////////////////////////////////// export class GraphQueries { constructor(private index: GraphIndexer) {} findNodeById(id: NodeId): NodeWrapper | null { const node = this.index.nodesById.get(id); if (!node) { return null; } return this.wrap(node); } listNodesByType<T extends NodeType>( type: T, { includeRemoved = true, }: { includeRemoved?: boolean; } = {} ): NodeListWrapper<NodeTypeToNodeWrapper<T>> { const nodesByType = this.index.nodesByType.get(type) || []; const filteredNodesByType = includeRemoved ? nodesByType : nodesByType.filter((node) => !isNodeRemoved(node)); return this.wrapList(type, filteredNodesByType) as NodeListWrapper< NodeTypeToNodeWrapper<T> >; } //@TODO add singular find* variant listIncomingNeighborsByType<T extends NodeType>( id: NodeId, incomingNeighborType: T, { includeRemoved = true, }: { includeRemoved?: boolean; } = {} ): NodeListWrapper<NodeTypeToNodeWrapper<T>> { const neighbors = this.index.inboundNeighbors.get(id); if (!neighbors) { return this.wrapList(incomingNeighborType, []) as NodeListWrapper< NodeTypeToNodeWrapper<T> >; } const neighborsOfType = neighbors.get(incomingNeighborType) || []; const filteredNeighborsOfType = includeRemoved ? neighborsOfType : neighborsOfType.filter((node) => !isNodeRemoved(node)); return this.wrapList( incomingNeighborType, filteredNeighborsOfType ) as NodeListWrapper<NodeTypeToNodeWrapper<T>>; } //@TODO add singular find* variant listOutgoingNeighborsByType<T extends NodeType>( id: NodeId, outgoingNeighborType: T, { includeRemoved = true, }: { includeRemoved?: boolean; } = {} ): NodeListWrapper<NodeTypeToNodeWrapper<T>> { const neighbors = this.index.outboundNeighbors.get(id); if (!neighbors) { return this.wrapList(outgoingNeighborType, []) as NodeListWrapper< NodeTypeToNodeWrapper<T> >; } const neighborsOfType = neighbors.get(outgoingNeighborType) || []; const filteredNeighborsOfType = includeRemoved ? neighborsOfType : neighborsOfType.filter((node) => !isNodeRemoved(node)); return this.wrapList( outgoingNeighborType, filteredNeighborsOfType ) as NodeListWrapper<NodeTypeToNodeWrapper<T>>; } listIncomingNeighborsByEdgeType( id: NodeId, edgeType: EdgeType ): NodeListWrapper<NodeWrapper> { const neighbors = this.index.inboundNeighborsByEdgeType.get(id); if (!neighbors) { return this.wrapList(null, []); } const neighborsOfType = neighbors.get(edgeType); return this.wrapList(null, neighborsOfType || []); } listOutgoingNeighborsByEdgeType( id: NodeId, edgeType: EdgeType ): NodeListWrapper<NodeWrapper> { const neighbors = this.index.outboundNeighborsByEdgeType.get(id); if (!neighbors) { return this.wrapList(null, []); } const neighborsOfType = neighbors.get(edgeType); return this.wrapList(null, neighborsOfType || []); } *descendantsIterator( nodeId: NodeId, seenSet: Set<NodeId> = new Set(), { includeRemoved = true, }: { includeRemoved?: boolean; } = {} ): Generator<Node> { const inboundNeighbors = this.index.inboundNeighbors.get(nodeId); if (!inboundNeighbors) { return; } if (seenSet.has(nodeId)) { return; } seenSet.add(nodeId); for (const neighborsByNodeType of inboundNeighbors.values()) { for (const neighborNode of neighborsByNodeType) { if (includeRemoved || !isNodeRemoved(neighborNode)) { yield neighborNode; yield* this.descendantsIterator(neighborNode.id, seenSet); } } } } //@TODO wrap() and wrapList() should be injected? // TODO figure out how to make this generic wrap(node: Node): NodeWrapper { if (node.type === NodeType.Request) { return new RequestNodeWrapper(node, this); } else if (node.type === NodeType.Response) { return new ResponseNodeWrapper(node, this); } else if (node.type === NodeType.Path) { return new PathNodeWrapper(node, this); } else if (node.type === NodeType.Body) { return new BodyNodeWrapper(node, this); } else if (node.type === NodeType.QueryParameters) { return new QueryParametersNodeWrapper(node, this); } else if (node.type === NodeType.BatchCommit) { return new BatchCommitNodeWrapper(node, this); } else if (node.type === NodeType.Endpoint) { return new EndpointNodeWrapper(node, this); } throw new Error(`unexpected node.type`); } //@TODO move away from null here // TODO figure out how to make this generic wrapList(type: NodeType | null, nodes: Node[]): NodeListWrapper<NodeWrapper> { //@TODO add list helpers (map, etc.) return { results: nodes.map((node) => this.wrap(node)), }; } }
the_stack
import * as aws from "@pulumi/aws"; import * as pulumi from "@pulumi/pulumi"; import * as cloudwatch from "../cloudwatch"; export namespace metrics { export type RdsMetricName = "BinLogDiskUsage" | "BurstBalance" | "CPUUtilization" | "CPUCreditUsage" | "CPUCreditBalance" | "DatabaseConnections" | "DiskQueueDepth" | "FailedSQLServerAgentJobsCount" | "FreeableMemory" | "FreeStorageSpace" | "MaximumUsedTransactionIDs" | "NetworkReceiveThroughput" | "NetworkTransmitThroughput" | "OldestReplicationSlotLag" | "ReadIOPS" | "ReadLatency" | "ReadThroughput" | "ReplicaLag" | "ReplicationSlotDiskUsage" | "SwapUsage" | "TransactionLogsDiskUsage" | "TransactionLogsGeneration" | "WriteIOPS" | "WriteLatency" | "WriteThroughput" | // aurora metrics "ActiveTransactions" | "AuroraBinlogReplicaLag" | "AuroraGlobalDBReplicatedWriteIO" | "AuroraGlobalDBDataTransferBytes" | "AuroraGlobalDBReplicationLag" | "AuroraReplicaLag" | "AuroraReplicaLagMaximum" | "AuroraReplicaLagMinimum" | "BacktrackChangeRecordsCreationRate" | "BacktrackChangeRecordsStored" | "BacktrackWindowActual" | "BacktrackWindowAlert" | "BackupRetentionPeriodStorageUsed" | "BinLogDiskUsage" | "BlockedTransactions" | "BufferCacheHitRatio" | "CommitLatency" | "CommitThroughput" | "CPUCreditBalance" | "CPUCreditUsage" | "CPUUtilization" | "DatabaseConnections" | "DDLLatency" | "DDLThroughput" | "Deadlocks" | "DeleteLatency" | "DeleteThroughput" | "DiskQueueDepth" | "DMLLatency" | "DMLThroughput" | "EngineUptime" | "FreeableMemory" | "FreeLocalStorage" | "InsertLatency" | "InsertThroughput" | "LoginFailures" | "MaximumUsedTransactionIDs" | "NetworkReceiveThroughput" | "NetworkThroughput" | "NetworkTransmitThroughput" | "Queries" | "RDSToAuroraPostgreSQLReplicaLag" | "ReadIOPS" | "ReadLatency" | "ReadThroughput" | "ResultSetCacheHitRatio" | "SelectLatency" | "SelectThroughput" | "SnapshotStorageUsed" | "SwapUsage" | "TotalBackupStorageBilled" | "TransactionLogsDiskUsage" | "UpdateLatency" | "UpdateThroughput" | "VolumeBytesUsed" | "VolumeReadIOPs" | "VolumeWriteIOPs" | "WriteIOPS" | "WriteLatency" | "WriteThroughput"; export interface RdsMetricChange extends cloudwatch.MetricChange { /** * Optional [Instance] to filter down events to. */ instance?: aws.rds.Instance; /** * Optional [Cluster] to filter down events to. */ cluster?: aws.rds.Cluster; /** * This dimension filters the data you request for a specific Aurora DB cluster, aggregating * the metric by instance role (WRITER/READER). For example, you can aggregate metrics for * all READER instances that belong to a cluster. * * If this is provided then [cluster] must be provided as well. */ role?: "WRITER" | "READER"; /** * This dimension filters the data you request for all instances in a database class. For * example, you can aggregate metrics for all instances that belong to the database class * [db.m1.small]. */ databaseClass?: string; /** * This dimension filters the data you request for the identified engine name only. For * example, you can aggregate metrics for all instances that have the engine name [mysql]. */ engineName?: string; /** * This dimension filters the data you request for the specified region only. For example, * you can aggregate metrics for all instances in the region [us-east-1]. */ sourceRegion?: aws.Region; } /** * Creates an AWS/RDS metric with the requested [metricName]. See * https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/MonitoringOverview.html#monitoring-cloudwatch * for list of all metric-names. * * Note, individual metrics can easily be obtained without supplying the name using the other * [metricXXX] functions. * * You can monitor DB instances using Amazon CloudWatch, which collects and processes raw data from * Amazon RDS into readable, near real-time metrics. These statistics are recorded for a period of * two weeks, so that you can access historical information and gain a better perspective on how * your web application or service is performing. By default, Amazon RDS metric data is * automatically sent to CloudWatch in 1-minute periods. * * Amazon RDS metrics data can be filtered by using any of the following dimensions: * * 1. "DBInstanceIdentifier": This dimension filters the data you request for a specific database * instance. * 2. "DBClusterIdentifier": This dimension filters the data you request for a specific Amazon * Aurora DB cluster. * 3. "DBClusterIdentifier, Role": This dimension filters the data you request for a specific Aurora * DB cluster, aggregating the metric by instance role (WRITER/READER). For example, you can * aggregate metrics for all READER instances that belong to a cluster. * 4. "DatabaseClass": This dimension filters the data you request for all instances in a database * class. For example, you can aggregate metrics for all instances that belong to the database * class db.m1.small * 5. "EngineName": This dimension filters the data you request for the identified engine name only. * For example, you can aggregate metrics for all instances that have the engine name mysql. * 6. "SourceRegion": This dimension filters the data you request for the specified region only. For * example, you can aggregate metrics for all instances in the region us-east-1. */ function metric(metricName: RdsMetricName, change: RdsMetricChange = {}) { const dimensions: Record<string, pulumi.Input<string>> = {}; if (change.cluster !== undefined) { dimensions.DBClusterIdentifier = change.cluster.id; } if (change.instance !== undefined) { dimensions.DBInstanceIdentifier = change.instance.id; } if (change.role !== undefined) { dimensions.Role = change.role; } if (change.databaseClass !== undefined) { dimensions.DatabaseClass = change.databaseClass; } if (change.engineName !== undefined) { dimensions.EngineName = change.engineName; } if (change.sourceRegion !== undefined) { dimensions.SourceRegion = change.sourceRegion; } return new cloudwatch.Metric({ namespace: "AWS/RDS", name: metricName, ...change, }).withDimensions(dimensions); } /** * The amount of disk space occupied by binary logs on the master. Applies to MySQL read * replicas. * * Units: Bytes */ export function binLogDiskUsage(change?: RdsMetricChange) { return metric("BinLogDiskUsage", { unit: "Bytes", ...change }); } /** * The percent of General Purpose SSD (gp2) burst-bucket I/O credits available. * * Units: Percent */ export function burstBalance(change?: RdsMetricChange) { return metric("BurstBalance", { unit: "Percent", ...change }); } /** * The percentage of CPU utilization. * * Units: Percent */ export function cpuUtilization(change?: RdsMetricChange) { return metric("CPUUtilization", { unit: "Percent", ...change }); } /** * [T2 instances] The number of CPU credits spent by the instance for CPU utilization. One CPU * credit equals one vCPU running at 100% utilization for one minute or an equivalent * combination of vCPUs, utilization, and time (for example, one vCPU running at 50% utilization * for two minutes or two vCPUs running at 25% utilization for two minutes). * * CPU credit metrics are available at a five-minute frequency only. If you specify a period * greater than five minutes, use the Sum statistic instead of the Average statistic. */ export function cpuCreditUsage(change?: RdsMetricChange) { return metric("CPUCreditUsage", change); } /** * [T2 instances] The number of earned CPU credits that an instance has accrued since it was * launched or started. For T2 Standard, the CPUCreditBalance also includes the number of launch * credits that have been accrued. * * Credits are accrued in the credit balance after they are earned, and removed from the credit * balance when they are spent. The credit balance has a maximum limit, determined by the * instance size. Once the limit is reached, any new credits that are earned are discarded. For * T2 Standard, launch credits do not count towards the limit. * * The credits in the CPUCreditBalance are available for the instance to spend to burst beyond * its baseline CPU utilization. * * When an instance is running, credits in the CPUCreditBalance do not expire. When the instance * stops, the CPUCreditBalance does not persist, and all accrued credits are lost. * * CPU credit metrics are available at a five-minute frequency only. */ export function cpuCreditBalance(change?: RdsMetricChange) { return metric("CPUCreditBalance", change); } /** * The number of database connections in use. * * Units: Count */ export function databaseConnections(change?: RdsMetricChange) { return metric("DatabaseConnections", { unit: "Count", ...change }); } /** * The number of outstanding IOs (read/write requests) waiting to access the disk. * * Units: Count */ export function diskQueueDepth(change?: RdsMetricChange) { return metric("DiskQueueDepth", { unit: "Count", ...change }); } /** * The number of failed SQL Server Agent jobs during the last minute. * * Unit: Count/Minute */ export function failedSQLServerAgentJobsCount(change?: RdsMetricChange) { return metric("FailedSQLServerAgentJobsCount", { period: 60, unit: "Count", ...change }); } /** * The amount of available random access memory. * * Units: Bytes */ export function freeableMemory(change?: RdsMetricChange) { return metric("FreeableMemory", { unit: "Bytes", ...change }); } /** * The amount of available storage space. * * Units: Bytes */ export function freeStorageSpace(change?: RdsMetricChange) { return metric("FreeStorageSpace", { unit: "Bytes", ...change }); } /** * The maximum transaction ID that has been used. Applies to PostgreSQL. * * Units: Count */ export function maximumUsedTransactionIDs(change?: RdsMetricChange) { return metric("MaximumUsedTransactionIDs", { unit: "Count", ...change }); } /** * The incoming (Receive) network traffic on the DB instance, including both customer database * traffic and Amazon RDS traffic used for monitoring and replication. * * Units: Bytes/Second */ export function networkReceiveThroughput(change?: RdsMetricChange) { return metric("NetworkReceiveThroughput", { unit: "Bytes/Second", ...change }); } /** * The outgoing (Transmit) network traffic on the DB instance, including both customer database * traffic and Amazon RDS traffic used for monitoring and replication. * * Units: Bytes/Second */ export function networkTransmitThroughput(change?: RdsMetricChange) { return metric("NetworkTransmitThroughput", { unit: "Bytes/Second", ...change }); } /** * The lagging size of the replica lagging the most in terms of WAL data received. Applies to * PostgreSQL. * * Units: Megabytes */ export function oldestReplicationSlotLag(change?: RdsMetricChange) { return metric("OldestReplicationSlotLag", { unit: "Megabytes", ...change }); } /** * The average number of disk read I/O operations per second. * * Units: Count/Second */ export function readIOPS(change?: RdsMetricChange) { return metric("ReadIOPS", { unit: "Count/Second", ...change }); } /** * The average amount of time taken per disk I/O operation. * * Units: Seconds */ export function readLatency(change?: RdsMetricChange) { return metric("ReadLatency", { unit: "Seconds", ...change }); } /** * The average number of bytes read from disk per second. * * Units: Bytes/Second */ export function readThroughput(change?: RdsMetricChange) { return metric("ReadThroughput", { unit: "Bytes/Second", ...change }); } /** * The amount of time a Read Replica DB instance lags behind the source DB instance. Applies to * MySQL, MariaDB, and PostgreSQL Read Replicas. * * Units: Seconds */ export function replicaLag(change?: RdsMetricChange) { return metric("ReplicaLag", { unit: "Seconds", ...change }); } /** * The disk space used by replication slot files. Applies to PostgreSQL. * * Units: Megabytes */ export function replicationSlotDiskUsage(change?: RdsMetricChange) { return metric("ReplicationSlotDiskUsage", { unit: "Megabytes", ...change }); } /** * The amount of swap space used on the DB instance. This metric is not available for SQL * Server. * * Units: Bytes */ export function swapUsage(change?: RdsMetricChange) { return metric("SwapUsage", { unit: "Bytes", ...change }); } /** * The disk space used by transaction logs. Applies to PostgreSQL. * * Units: Megabytes */ export function transactionLogsDiskUsage(change?: RdsMetricChange) { return metric("TransactionLogsDiskUsage", { unit: "Megabytes", ...change }); } /** * The size of transaction logs generated per second. Applies to PostgreSQL. * * Units: Megabytes/Second */ export function transactionLogsGeneration(change?: RdsMetricChange) { return metric("TransactionLogsGeneration", { unit: "Megabytes/Second", ...change }); } /** * The average number of disk write I/O operations per second. * * Units: Count/Second */ export function writeIOPS(change?: RdsMetricChange) { return metric("WriteIOPS", { unit: "Count/Second", ...change }); } /** * The average amount of time taken per disk I/O operation. * * Units: Seconds */ export function writeLatency(change?: RdsMetricChange) { return metric("WriteLatency", { unit: "Seconds", ...change }); } /** * The average number of bytes written to disk per second. * * Units: Bytes/Second */ export function writeThroughput(change?: RdsMetricChange) { return metric("WriteThroughput", { unit: "Bytes/Second", ...change }); } // aurora functions /** * The average number of current transactions executing on an Aurora database instance per * second. By default, Aurora doesn't enable this metric. To begin measuring this value, set * innodb_monitor_enable='all' in the DB parameter group for a specific DB instance. * * Applies to: Aurora MySQL */ export function activeTransactions(change?: RdsMetricChange) { return metric("ActiveTransactions", { ...change }); } /** * The amount of time a replica DB cluster running on Aurora with MySQL compatibility lags * behind the source DB cluster. This metric reports the value of the Seconds_Behind_Master * field of the MySQL SHOW SLAVE STATUS command. This metric is useful for monitoring replica * lag between Aurora DB clusters that are replicating across different AWS Regions. For more * information, see Aurora MySQL Replication. * * Applies to: Aurora MySQL */ export function auroraBinlogReplicaLag(change?: RdsMetricChange) { return metric("AuroraBinlogReplicaLag", { ...change }); } /** * Units: Bytes * * Applies to: Aurora MySQL */ export function auroraGlobalDBReplicatedWriteIO(change?: RdsMetricChange) { return metric("AuroraGlobalDBReplicatedWriteIO", { unit: "Bytes", ...change }); } /** * Units: Bytes * * Applies to: Aurora MySQL */ export function auroraGlobalDBDataTransferBytes(change?: RdsMetricChange) { return metric("AuroraGlobalDBDataTransferBytes", { unit: "Bytes", ...change }); } /** * Units: Milliseconds * * Applies to: Aurora MySQL */ export function auroraGlobalDBReplicationLag(change?: RdsMetricChange) { return metric("AuroraGlobalDBReplicationLag", { unit: "Milliseconds", ...change }); } /** * For an Aurora Replica, the amount of lag when replicating updates from the primary instance, * in milliseconds. * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function auroraReplicaLag(change?: RdsMetricChange) { return metric("AuroraReplicaLag", { unit: "Milliseconds", ...change }); } /** * The maximum amount of lag between the primary instance and each Aurora DB instance in the DB * cluster, in milliseconds. * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function auroraReplicaLagMaximum(change?: RdsMetricChange) { return metric("AuroraReplicaLagMaximum", { unit: "Milliseconds", ...change }); } /** * The minimum amount of lag between the primary instance and each Aurora DB instance in the DB * cluster, in milliseconds. * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function auroraReplicaLagMinimum(change?: RdsMetricChange) { return metric("AuroraReplicaLagMinimum", { unit: "Milliseconds", ...change }); } /** * The number of backtrack change records created over five minutes for your DB cluster. * * Applies to: Aurora MySQL */ export function backtrackChangeRecordsCreationRate(change?: RdsMetricChange) { return metric("BacktrackChangeRecordsCreationRate", { ...change }); } /** * The actual number of backtrack change records used by your DB cluster. * * Applies to: Aurora MySQL */ export function backtrackChangeRecordsStored(change?: RdsMetricChange) { return metric("BacktrackChangeRecordsStored", { ...change }); } /** * The difference between the target backtrack window and the actual backtrack window. * * Applies to: Aurora MySQL */ export function backtrackWindowActual(change?: RdsMetricChange) { return metric("BacktrackWindowActual", { ...change }); } /** * The number of times that the actual backtrack window is smaller than the target backtrack * window for a given period of time. * * Applies to: Aurora MySQL */ export function backtrackWindowAlert(change?: RdsMetricChange) { return metric("BacktrackWindowAlert", { ...change }); } /** * The total amount of backup storage in GiB used to support the point-in-time restore feature * within the Aurora DB cluster's backup retention window. Included in the total reported by the * TotalBackupStorageBilled metric. Computed separately for each Aurora cluster. For * instructions, see Understanding Aurora Backup Storage Usage. Units: Gibibytes (GiB) * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function backupRetentionPeriodStorageUsed(change?: RdsMetricChange) { return metric("BackupRetentionPeriodStorageUsed", { unit: "Gigabytes", ...change }); } /** * The average number of transactions in the database that are blocked per second. * * Applies to: Aurora MySQL */ export function blockedTransactions(change?: RdsMetricChange) { return metric("BlockedTransactions", { ...change }); } /** * The percentage of requests that are served by the buffer cache. * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function bufferCacheHitRatio(change?: RdsMetricChange) { return metric("BufferCacheHitRatio", { ...change }); } /** * The amount of latency for commit operations, in milliseconds. * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function commitLatency(change?: RdsMetricChange) { return metric("CommitLatency", { unit: "Milliseconds", ...change }); } /** * The average number of commit operations per second. * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function commitThroughput(change?: RdsMetricChange) { return metric("CommitThroughput", { ...change }); } /** * The amount of latency for data definition language (DDL) requests, in milliseconds—for * example, create, alter, and drop requests. * * Applies to: Aurora MySQL */ export function ddlLatency(change?: RdsMetricChange) { return metric("DDLLatency", { ...change }); } /** * The average number of DDL requests per second. * * Applies to: Aurora MySQL */ export function ddlThroughput(change?: RdsMetricChange) { return metric("DDLThroughput", { ...change }); } /** * The average number of deadlocks in the database per second. * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function deadlocks(change?: RdsMetricChange) { return metric("Deadlocks", { ...change }); } /** * The amount of latency for delete queries, in milliseconds. * * Applies to: Aurora MySQL */ export function deleteLatency(change?: RdsMetricChange) { return metric("DeleteLatency", { unit: "Milliseconds", ...change }); } /** * The average number of delete queries per second. * * Applies to: Aurora MySQL */ export function deleteThroughput(change?: RdsMetricChange) { return metric("DeleteThroughput", { ...change }); } /** * The amount of latency for inserts, updates, and deletes, in milliseconds. * * Applies to: Aurora MySQL */ export function dmlLatency(change?: RdsMetricChange) { return metric("DMLLatency", { unit: "Milliseconds", ...change }); } /** * The average number of inserts, updates, and deletes per second. * * Applies to: Aurora MySQL */ export function dmlThroughput(change?: RdsMetricChange) { return metric("DMLThroughput", { ...change }); } /** * The amount of time that the instance has been running, in seconds. * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function engineUptime(change?: RdsMetricChange) { return metric("EngineUptime", { unit: "Seconds", ...change }); } /** * The amount of storage available for temporary tables and logs, in bytes. Unlike for other DB * engines, for Aurora DB instances this metric reports the amount of storage available to each * DB instance for temporary tables and logs. This value depends on the DB instance class (for * pricing information, see the Amazon RDS product page). You can increase the amount of free * storage space for an instance by choosing a larger DB instance class for your instance. * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function freeLocalStorage(change?: RdsMetricChange) { return metric("FreeLocalStorage", { unit: "Bytes", ...change }); } /** * The amount of latency for insert queries, in milliseconds. * * Applies to: Aurora MySQL */ export function insertLatency(change?: RdsMetricChange) { return metric("InsertLatency", { unit: "Milliseconds", ...change }); } /** * The average number of insert queries per second. * * Applies to: Aurora MySQL */ export function insertThroughput(change?: RdsMetricChange) { return metric("InsertThroughput", { ...change }); } /** * The average number of failed login attempts per second. * * Applies to: Aurora MySQL */ export function loginFailures(change?: RdsMetricChange) { return metric("LoginFailures", { ...change }); } /** * The amount of network throughput both received from and transmitted to clients by each * instance in the Aurora MySQL DB cluster, in bytes per second. This throughput doesn't include * network traffic between instances in the DB cluster and the cluster volume. * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function networkThroughput(change?: RdsMetricChange) { return metric("NetworkThroughput", { unit: "Bytes/Second", ...change }); } /** * The average number of queries executed per second. * * Applies to: Aurora MySQL */ export function queries(change?: RdsMetricChange) { return metric("Queries", { ...change }); } /** * The amount of lag in seconds when replicating updates from the primary RDS PostgreSQL * instance to other nodes in the cluster. * * Applies to: Aurora PostgreSQL */ export function rdsToAuroraPostgreSQLReplicaLag(change?: RdsMetricChange) { return metric("RDSToAuroraPostgreSQLReplicaLag", { ...change }); } /** * The percentage of requests that are served by the Resultset cache. * * Applies to: Aurora MySQL */ export function resultSetCacheHitRatio(change?: RdsMetricChange) { return metric("ResultSetCacheHitRatio", { ...change }); } /** * The amount of latency for select queries, in milliseconds. * * Applies to: Aurora MySQL */ export function selectLatency(change?: RdsMetricChange) { return metric("SelectLatency", { ...change }); } /** * The average number of select queries per second. * * Applies to: Aurora MySQL */ export function selectThroughput(change?: RdsMetricChange) { return metric("SelectThroughput", { ...change }); } /** * The total amount of backup storage in GiB consumed by all Aurora snapshots for an Aurora DB * cluster outside its backup retention window. Included in the total reported by the * TotalBackupStorageBilled metric. Computed separately for each Aurora cluster. For * instructions, see Understanding Aurora Backup Storage Usage. Units: Gibibytes (GiB) * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function snapshotStorageUsed(change?: RdsMetricChange) { return metric("SnapshotStorageUsed", { unit: "Gigabytes", ...change }); } /** * The total amount of backup storage in GiB for which you are billed for a given Aurora DB * cluster. Includes the backup storage measured by the BackupRetentionPeriodStorageUsed and * SnapshotStorageUsed metrics. Computed separately for each Aurora cluster. For instructions, * see Understanding Aurora Backup Storage Usage. Units: Gibibytes (GiB) * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function totalBackupStorageBilled(change?: RdsMetricChange) { return metric("TotalBackupStorageBilled", { unit: "Gigabytes", ...change }); } /** * The amount of latency for update queries, in milliseconds. * * Applies to: Aurora MySQL */ export function updateLatency(change?: RdsMetricChange) { return metric("UpdateLatency", { ...change }); } /** * The average number of update queries per second. * * Applies to: Aurora MySQL */ export function updateThroughput(change?: RdsMetricChange) { return metric("UpdateThroughput", { ...change }); } /** * The amount of storage used by your Aurora DB instance, in bytes. This value affects the cost * of the Aurora DB cluster (for pricing information, see the Amazon RDS product page). * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function volumeBytesUsed(change?: RdsMetricChange) { return metric("VolumeBytesUsed", { unit: "Bytes", ...change }); } /** * The number of billed read I/O operations from a cluster volume, reported at 5-minute * intervals. Billed read operations are calculated at the cluster volume level, aggregated from * all instances in the Aurora DB cluster, and then reported at 5-minute intervals. The value is * calculated by taking the value of the Read operations metric over a 5-minute period. You can * determine the amount of billed read operations per second by taking the value of the Billed * read operations metric and dividing by 300 seconds. For example, if the Billed read * operations returns 13,686, then the billed read operations per second is 45 (13,686 / 300 = * 45.62). You accrue billed read operations for queries that request database pages that aren't * in the buffer cache and therefore must be loaded from storage. You might see spikes in billed * read operations as query results are read from storage and then loaded into the buffer cache. * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function volumeReadIOPs(change?: RdsMetricChange) { return metric("VolumeReadIOPs", { ...change }); } /** * The number of write disk I/O operations to the cluster volume, reported at 5-minute * intervals. See the description of VolumeReadIOPS above for a detailed description of how * billed write operations are calculated. * * Applies to: Aurora MySQL and Aurora PostgreSQL */ export function volumeWriteIOPs(change?: RdsMetricChange) { return metric("VolumeWriteIOPs", { ...change }); } }
the_stack
import * as k8s from "@kubernetes/client-node"; import * as assert from "power-assert"; import { applicationLabels, labelMatch, labelSelector, matchLabels, safeLabelValue, } from "../../../../lib/pack/k8s/kubernetes/labels"; describe("pack/k8s/kubernetes/labels", () => { describe("safeLabelValue", () => { const validation = /^(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?$/; it("should not change a valid value", () => { const v = "Kat3Bu5h-Cloudbusting.5"; const s = safeLabelValue(v); assert(validation.test(s)); assert(s === v); }); it("should not change an empty value", () => { const v = ""; const s = safeLabelValue(v); assert(validation.test(s)); assert(s === v); }); it("should fix an invalid value", () => { const v = "@atomist/sdm-pack-k8s:1.1.0-k8s.20190125173349?"; const s = safeLabelValue(v); const e = "atomist_sdm-pack-k8s_1.1.0-k8s.20190125173349"; assert(validation.test(s)); assert(s === e); }); it("should fix consecutive invalid characters", () => { const v = "@atomist/sdm-pack-k8s:?*1.1.0-k8s.20190125173349?"; const s = safeLabelValue(v); const e = "atomist_sdm-pack-k8s_1.1.0-k8s.20190125173349"; assert(validation.test(s)); assert(s === e); }); }); describe("matchLabels", () => { it("should return the proper match labels", () => { const r = { name: "cloudbusting", workspaceId: "KAT3BU5H", }; const m = matchLabels(r); const e = { "app.kubernetes.io/name": "cloudbusting", "atomist.com/workspaceId": "KAT3BU5H", }; assert.deepStrictEqual(m, e); }); }); describe("labelSelector", () => { it("should return the proper label selector string", () => { const r = { name: "cloudbusting", workspaceId: "KAT3BU5H", }; const l = labelSelector(r); const e = "app.kubernetes.io/name=cloudbusting,atomist.com/workspaceId=KAT3BU5H"; assert(l === e); }); }); describe("applicatonLabels", () => { it("should return the proper labels", () => { const r = { name: "cloudbusting", workspaceId: "KAT3BU5H", version: "5.1.0", sdmFulfiller: "EMI", }; const l = applicationLabels(r); const e = { "app.kubernetes.io/name": "cloudbusting", "atomist.com/workspaceId": "KAT3BU5H", "app.kubernetes.io/version": "5.1.0", "app.kubernetes.io/part-of": "cloudbusting", "app.kubernetes.io/managed-by": "EMI", }; assert.deepStrictEqual(l, e); }); it("should return optional labels", () => { const r = { name: "cloudbusting", workspaceId: "KAT3BU5H", version: "5.1.0", sdmFulfiller: "EMI", component: "song", instance: "Fifth", }; const l = applicationLabels(r); const e = { "app.kubernetes.io/name": "cloudbusting", "atomist.com/workspaceId": "KAT3BU5H", "app.kubernetes.io/version": "5.1.0", "app.kubernetes.io/part-of": "cloudbusting", "app.kubernetes.io/managed-by": "EMI", "app.kubernetes.io/component": "song", "app.kubernetes.io/instance": "Fifth", }; assert.deepStrictEqual(l, e); }); it("should return a superset of the match labels", () => { const r = { name: "cloudbusting", workspaceId: "KAT3BU5H", version: "5.1.0", sdmFulfiller: "EMI", }; const l = applicationLabels(r); const m = matchLabels(r); Object.keys(m).forEach(k => { assert(Object.keys(l).includes(k)); assert(l[k] === m[k]); }); }); it("should make the fulfiller a valid label value", () => { const r = { name: "cloudbusting", workspaceId: "KAT3BU5H", version: "5.1.0", sdmFulfiller: "@emi/Wickham-Farm::Welling,England_", }; const l = applicationLabels(r); const e = { "app.kubernetes.io/name": "cloudbusting", "atomist.com/workspaceId": "KAT3BU5H", "app.kubernetes.io/version": "5.1.0", "app.kubernetes.io/part-of": "cloudbusting", "app.kubernetes.io/managed-by": "emi_Wickham-Farm_Welling_England", }; assert.deepStrictEqual(l, e); }); }); describe("labelMatch", () => { const r = { apiVersion: "v1", kind: "Service", metadata: { labels: { album: "Younger Than Yesterday", year: "1967", recordLabel: "Columbia", }, name: "so-you-want-to-be-a-rock-n-roll-star", namespace: "byrds", }, }; it("should match when no label selectors", () => { assert(labelMatch(r)); assert(labelMatch(r, undefined)); }); it("should not match when no labels", () => { const n = { apiVersion: "v1", kind: "Service", metadata: { name: "so-you-want-to-be-a-rock-n-roll-star", namespace: "byrds", }, }; const s = { matchLabels: { album: "Younger Than Yesterday", year: "1967", recordLabel: "Columbia", }, }; assert(!labelMatch(n, s)); }); it("should match empty string", () => { const n = { apiVersion: "v1", kind: "Service", metadata: { labels: { why: "", }, name: "so-you-want-to-be-a-rock-n-roll-star", namespace: "byrds", }, }; const s = { matchLabels: { why: "", }, }; assert(labelMatch(n, s)); }); it("should match when matchLabels match", () => { const ss = [ { matchLabels: { album: "Younger Than Yesterday", year: "1967", recordLabel: "Columbia", }, }, { matchLabels: { album: "Younger Than Yesterday", year: "1967", }, }, { matchLabels: { recordLabel: "Columbia", }, }, { matchLabels: {}, }, { matchLabels: undefined, }, ]; ss.forEach(s => { assert(labelMatch(r, s)); }); }); it("should not match when matchLabels do not match", () => { const ss = [ { matchLabels: { album: "Younger Than Yesterday", year: "1968", recordLabel: "Columbia", }, }, { matchLabels: { album: "Older Than Yesterday", year: "1968", }, }, { matchLabels: { recordLabel: "RCA", }, }, { matchLabels: { album: "Younger Than Yesterday", year: "1967", recordLabel: "Columbia", release: "Deluxe Edition", }, }, ]; ss.forEach(s => { assert(!labelMatch(r, s)); }); }); it("should match when matchExpressions match", () => { const ss = [ { matchExpressions: [ { key: "album", operator: "Exists" }, { key: "year", operator: "In", values: ["1966", "1967", "1970"] }, { key: "recordLabel", operator: "Exists" }, ], }, { matchExpressions: [ { key: "album", operator: "In", values: ["Younger Than Yesterday", "Sweetheart of the Rodeo"] }, { key: "year", operator: "Exists" }, ], }, { matchExpressions: [ { key: "recordLabel", operator: "NotIn", values: ["Geffen", "RCA"] }, ], }, { matchExpressions: [ { key: "recordLabel", operator: "NotIn", values: ["Geffen", "RCA"] }, { key: "manager", operator: "DoesNotExist" }, ], }, { matchExpressions: [], }, { matchExpressions: undefined, }, ]; ss.forEach(s => { assert(labelMatch(r, s)); }); }); it("should not match when matchExpressions does not match", () => { const ss = [ { matchExpressions: [ { key: "album", operator: "Exists" }, { key: "year", operator: "In", values: ["1966", "1967", "1970"] }, { key: "recordLabel", operator: "DoesNotExist" }, ], }, { matchExpressions: [ { key: "album", operator: "In", values: ["Mr. Tambourine Man", "Sweetheart of the Rodeo"] }, { key: "year", operator: "Exists" }, ], }, { matchExpressions: [ { key: "recordLabel", operator: "In", values: ["Geffen", "RCA"] }, ], }, { matchExpressions: [ { key: "recordLabel", operator: "NotIn", values: ["Geffen", "RCA"] }, { key: "manager", operator: "Exists" }, ], }, ]; ss.forEach(s => { assert(!labelMatch(r, s)); }); }); it("should match when matchLabels and matchExpressions match", () => { const ss: k8s.V1LabelSelector[] = [ { matchLabels: { album: "Younger Than Yesterday", year: "1967", recordLabel: "Columbia", }, matchExpressions: [ { key: "album", operator: "Exists" }, { key: "year", operator: "In", values: ["1966", "1967", "1970"] }, { key: "recordLabel", operator: "Exists" }, ], }, { matchLabels: { album: "Younger Than Yesterday", year: "1967", }, matchExpressions: [ { key: "album", operator: "In", values: ["Younger Than Yesterday", "Sweetheart of the Rodeo"] }, { key: "year", operator: "Exists" }, ], }, { matchLabels: { recordLabel: "Columbia", }, matchExpressions: [ { key: "manager", operator: "DoesNotExist" }, ], }, { matchLabels: {}, matchExpressions: [], }, { matchLabels: undefined, matchExpressions: undefined, }, ]; ss.forEach(s => { assert(labelMatch(r, s)); }); }); it("should not match when matchLabels and/or matchExpressions do not match", () => { const ss: k8s.V1LabelSelector[] = [ { matchLabels: { album: "Younger Than Yesterday", year: "1967", recordLabel: "Columbia", }, matchExpressions: [ { key: "album", operator: "Exists" }, { key: "year", operator: "In", values: ["1966", "1967", "1970"] }, { key: "recordLabel", operator: "DoesNotExist" }, ], }, { matchLabels: { album: "Younger Than Yesterday", year: "1968", }, matchExpressions: [ { key: "album", operator: "In", values: ["Younger Than Yesterday", "Sweetheart of the Rodeo"] }, { key: "year", operator: "Exists" }, ], }, { matchLabels: { recordLabel: "RCA", }, matchExpressions: [ { key: "manager", operator: "In", values: ["Roger McGuinn", "Chris Hillman"] }, ], }, ]; ss.forEach(s => { assert(!labelMatch(r, s)); }); }); it("should throw an error when match expression operator invalid", () => { assert.throws(() => labelMatch(r, { matchExpressions: [{ key: "manager", operator: "==" }] }), /Unsupported match expression operator: /); }); }); });
the_stack
import { Color } from 'cogl'; import * as Gio from 'gio'; import { byteArray } from 'gjs'; import * as GLib from 'glib'; import { MsManager } from 'src/manager/msManager'; import { getSettings } from 'src/utils/settings'; import { ShellVersionMatch } from 'src/utils/shellVersionMatch'; import * as St from 'st'; import { main as Main } from 'ui'; /** Extension imports */ const Me = imports.misc.extensionUtils.getCurrentExtension(); /* exported VerticalPanelPositionEnum, HorizontalPanelPositionEnum, PanelIconStyleEnum, FocusEffectEnum, MsThemeManager */ export const VerticalPanelPositionEnum = { LEFT: 0, RIGHT: 1, }; export const HorizontalPanelPositionEnum = { TOP: 0, BOTTOM: 1, }; export const PanelIconStyleEnum = { HYBRID: 0, CATEGORY: 1, APPLICATION: 2, }; export const FocusEffectEnum = { NONE: 0, DEFAULT: 1, BORDER: 2, }; function parseCoglColor(color: string): Color { const c = new Color(); c.init_from_4ub( parseInt(color.substring(1, 3), 16), parseInt(color.substring(3, 5), 16), parseInt(color.substring(5, 7), 16), 255 ); return c; } export class MsThemeManager extends MsManager { themeContext: St.ThemeContext; theme: any; themeSettings: Gio.Settings; themeFile: Gio.FilePrototype; themeValue: string; primary: string; primaryColor: Color; constructor() { super(); this.themeContext = St.ThemeContext.get_for_stage(global.stage); this.theme = this.themeContext.get_theme(); this.themeSettings = getSettings('theme'); this.themeFile = Gio.file_new_for_path( `${GLib.get_user_cache_dir()}/${Me.uuid}-theme.css` ); this.themeValue = this.themeSettings.get_string('theme'); this.primary = this.themeSettings.get_string('primary-color'); this.primaryColor = parseCoglColor(this.primary); this.observe(this.themeContext, 'changed', () => { Me.log('theme changed'); this.theme = this.themeContext.get_theme(); if (Main.layoutManager.uiGroup.has_style_class_name('no-theme')) { Main.layoutManager.uiGroup.remove_style_class_name('no-theme'); } if (!this.theme.application_stylesheet) { Main.layoutManager.uiGroup.add_style_class_name('no-theme'); } }); this.observe(this.themeSettings, 'changed::theme', (schema) => { this.themeValue = schema.get_string('theme'); this.regenerateStylesheet(); }); this.observe(this.themeSettings, 'changed::primary-color', (schema) => { this.primary = schema.get_string('primary-color'); this.primaryColor = parseCoglColor(this.primary); this.regenerateStylesheet(); }); this.observe( this.themeSettings, 'changed::vertical-panel-position', () => { this.emit('vertical-panel-position-changed'); } ); this.observe( this.themeSettings, 'changed::horizontal-panel-position', () => { this.emit('horizontal-panel-position-changed'); } ); this.observe(this.themeSettings, 'changed::panel-opacity', () => { this.regenerateStylesheet(); }); this.observe(this.themeSettings, 'changed::surface-opacity', () => { this.regenerateStylesheet(); }); this.observe(this.themeSettings, 'changed::panel-size', () => { this.emit('panel-size-changed'); }); this.observe(this.themeSettings, 'changed::blur-background', () => { this.emit('blur-background-changed'); }); this.observe(this.themeSettings, 'changed::panel-icon-style', () => { this.emit('panel-icon-style-changed'); }); this.observe(this.themeSettings, 'changed::panel-icon-color', () => { this.emit('panel-icon-color-changed'); }); this.observe(this.themeSettings, 'changed::clock-horizontal', () => { this.emit('clock-horizontal-changed'); }); this.observe(this.themeSettings, 'changed::clock-app-launcher', () => { this.emit('clock-app-launcher-changed'); }); this.observe(this.themeSettings, 'changed::focus-effect', () => { this.emit('focus-effect-changed'); }); } get verticalPanelPosition() { return this.themeSettings.get_enum('vertical-panel-position'); } get horizontalPanelPosition() { return this.themeSettings.get_enum('horizontal-panel-position'); } get panelOpacity() { return this.themeSettings.get_int('panel-opacity'); } get panelIconStyle() { return this.themeSettings.get_enum('panel-icon-style'); } set panelIconStyle(value) { this.themeSettings.set_enum('panel-icon-style', value); } get panelIconColor() { return this.themeSettings.get_boolean('panel-icon-color'); } get surfaceOpacity() { return this.themeSettings.get_int('surface-opacity'); } get blurBackground() { return this.themeSettings.get_boolean('blur-background'); } get clockHorizontal() { return this.themeSettings.get_boolean('clock-horizontal'); } get clockAppLauncher() { return this.themeSettings.get_boolean('clock-app-launcher'); } getPanelSize(monitorIndex: number) { return ( this.themeSettings.get_int('panel-size') * global.display.get_monitor_scale(monitorIndex) ); } getPanelSizeNotScaled() { return this.themeSettings.get_int('panel-size'); } get focusEffect() { return this.themeSettings.get_enum('focus-effect'); } isColorDark(color: string) { color = color.replace('#', ''); const r = parseInt(color.substring(0, 2), 16); const g = parseInt(color.substring(2, 4), 16); const b = parseInt(color.substring(4, 6), 16); const linearColors = [r / 255, g / 255, b / 255]; for (let i = 0; i < linearColors.length; ++i) { if (linearColors[i] <= 0.03928) { linearColors[i] = linearColors[i] / 12.92; } else { linearColors[i] = Math.pow( (linearColors[i] + 0.055) / 1.055, 2.4 ); } } const luminance = 0.2126 * linearColors[0] + 0.7152 * linearColors[1] + 0.0722 * linearColors[2]; return luminance < 0.179; } async readFileContent(file: Gio.File) { return new Promise<string>((resolve, reject) => { file.load_contents_async(null, (obj, res) => { const [success, contents] = obj!.load_contents_finish(res); if (success) { //Read the binay content as string const content = byteArray.toString(contents); resolve(content); } else { reject(success); } }); }); } async writeContentToFile(content: string, file: Gio.File) { return new Promise<Gio.File>((resolve, _) => { const contentBytes = new GLib.Bytes(byteArray.fromString(content)); file.replace_async( null, false, Gio.FileCreateFlags.NONE, GLib.PRIORITY_DEFAULT, null, (file, res) => { const stream = file!.replace_finish(res); stream.write_bytes_async( contentBytes, GLib.PRIORITY_DEFAULT, null, (ioStream, wRes) => { ioStream!.write_bytes_finish(wRes); stream.close(null); resolve(file!); } ); } ); }); } async buildThemeStylesheetToFile(file: Gio.FilePrototype) { const originThemeFile = Gio.file_new_for_path( `${Me.path}/style-${this.themeValue}-theme.css` ); let content = await this.readFileContent(originThemeFile); content = content.replace(/#3f51b5/g, this.primary); // color-primary content = content.replace(/0.876/g, `${this.panelOpacity / 100}`); // panel-opacity content = content.replace(/0.987/g, `${this.surfaceOpacity / 100}`); // surface-opacity await this.writeContentToFile(content, file); } async regenerateStylesheet() { this.unloadStylesheet(); if (!this.theme.application_stylesheet) { Main.layoutManager.uiGroup.add_style_class_name('no-theme'); } if (ShellVersionMatch('3.34')) { //TODO The new code may prevent crashes on 3.34 without this, needs testing // This loads an empty theme, cleaning all nodes but causes top panel flash this.themeContext.set_theme(new St.Theme()); } await this.buildThemeStylesheetToFile(this.themeFile); this.theme.load_stylesheet(this.themeFile); GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => { this.themeContext.set_theme(this.theme); Main.reloadThemeResource(); Main.loadTheme(); return GLib.SOURCE_REMOVE; }); } unloadStylesheet() { if (Main.layoutManager.uiGroup.has_style_class_name('no-theme')) { Main.layoutManager.uiGroup.remove_style_class_name('no-theme'); } this.theme.unload_stylesheet(this.themeFile); } destroy() { super.destroy(); // Do not remove the stylesheet in during locking disable if (!Me.locked) { this.unloadStylesheet(); } } }
the_stack
import { BlogCategoryModel, BlogMetaTagModel, BlogModel, BlogDocumentModel, BlogTagModel, BlogResponse, BlogCategoryResponse } from './blog.model'; import {Injectable} from "@angular/core"; import {Observable} from "rxjs/Observable"; import {Config} from "../../../shared/configs/general.config"; import {API_URL} from "../../../shared/configs/env.config"; import {FileOperrationService} from '../../../shared/services/fileOperation.service'; import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http'; import { ErrorObservable } from 'rxjs/observable/ErrorObservable'; import { catchError } from 'rxjs/operators/catchError'; @Injectable() export class BlogService { blogCategoryApiRoute:string = "blogcategory"; blogApiRoute:string = "blog"; blogDocumentApiRoute:string = "blogdocument"; blotTagApiRoute:string = "blogtag"; blogMetaApiRoute:string = "blogseo"; progressObserver:any; progress:any; constructor(private _http:HttpClient, private fileService:FileOperrationService) { // this.progress = Observable.create(observer => { // this.progressObserver = observer // }).share(); } /* Blog Category */ saveBlogCategory(objCategory:BlogCategoryModel) { let body = JSON.stringify(objCategory); return this._http.post(API_URL + this.blogCategoryApiRoute, body) .pipe( catchError(this.handleError) ); } updateBlogCategory(objBlogCat:BlogCategoryModel) { let body = JSON.stringify(objBlogCat); return this._http.put(API_URL + this.blogCategoryApiRoute + "/" + objBlogCat._id, body) .pipe( catchError(this.handleError) ); } getBlogCategoryList(perPage:number, currentPage:number, active?:boolean):Observable < BlogCategoryResponse> { // Initialize Params Object let query = new HttpParams(); // Begin assigning parameters query = query.append('perpage', perPage.toString()); query = query.append('page', currentPage.toString()); if(active) query = query.append('active', active.toString()); return this._http.get(API_URL + this.blogCategoryApiRoute, {params: query} ) .pipe( catchError(this.handleError) ); } getBlogCategoryDetail(objId:string):Observable < BlogCategoryModel> { return this._http.get<BlogCategoryModel>(API_URL + this.blogCategoryApiRoute + "/" + objId) .pipe( catchError(this.handleError) ); } deleteBlogCategory(objDel:BlogCategoryModel):Observable<any> { let body = JSON.stringify({}); return this._http.patch(API_URL + this.blogCategoryApiRoute + "/" + objDel._id, body) .pipe( catchError(this.handleError) ); } /* End News Category */ /* Blog */ saveBlog(objBlog:BlogModel, file:File):Observable<any> { return Observable.create((observer: any) => { let formData:FormData = new FormData(), xhr:XMLHttpRequest = new XMLHttpRequest(); if (file) { formData.append('imageName', file); } formData.append('data', JSON.stringify(objBlog)); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { observer.next(JSON.parse(xhr.response)); observer.complete(); } else { observer.error(JSON.parse(xhr.response)); } } }; xhr.upload.onprogress = (event) => { this.progress = Math.round(event.loaded / event.total * 100); //this.progressObserver.next(this.progress); }; xhr.open('POST', API_URL + this.blogApiRoute, true); xhr.setRequestHeader("Authorization", Config.AuthToken); xhr.send(formData); }); } updateBlog(objBlog:BlogModel, file:File, imageDeleted:boolean):Observable<any> { return Observable.create((observer: any) => { let formData:FormData = new FormData(), xhr:XMLHttpRequest = new XMLHttpRequest(); if (file) { formData.append('imageName', file); } formData.append('data', JSON.stringify(objBlog)); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { observer.next(JSON.parse(xhr.response)); observer.complete(); } else { observer.error(xhr.response); } } }; xhr.upload.onprogress = (event) => { this.progress = Math.round(event.loaded / event.total * 100); //this.progressObserver.next(this.progress); }; xhr.open('PUT', API_URL + this.blogApiRoute + "/" + objBlog._id + "?imagedeleted=" + imageDeleted, true); xhr.setRequestHeader("Authorization", Config.AuthToken); xhr.send(formData); }); } getBlogList(perPage:number, currentPage:number, categoryId?:string):Observable < BlogResponse > { let query = new HttpParams(); query = query.append('perpage', perPage.toString()); query = query.append('page', currentPage.toString()); if(categoryId) query = query.append('categoryid', categoryId.toString()); return this._http.get<BlogResponse>(API_URL + this.blogApiRoute, {params: query}) .pipe( catchError(this.handleError) ); } getBlogDetail(id:string):Observable < BlogModel > { // console.log("BlogDetail", API_URL) return this._http.get<BlogModel>(API_URL + this.blogApiRoute + "/" + id) .pipe( catchError(this.handleError) ); } deleteBlog(objUpdate:BlogModel) { let body = JSON.stringify({}); return this._http.patch(API_URL + this.blogApiRoute + "/" + objUpdate._id, body) .pipe( catchError(this.handleError) ); } /* End Blog */ /* Blog Tag */ getBlogTagList():Observable < BlogTagModel[] > { // console.log("Blog Tag List", API_URL); return this._http.get<BlogTagModel[]>(API_URL + this.blotTagApiRoute) .pipe( catchError(this.handleError) ); } /* END Blog Tag */ deleteImage(fileName:string, orgExt:string, path:string):Observable < any > { return this.fileService.deleteFile(fileName, orgExt, path, "image"); } /* Blog File */ saveDocument(blogId:string, objSave:BlogDocumentModel, file:File):Observable<any> { return Observable.create((observer: any) => { let formData:FormData = new FormData(), xhr:XMLHttpRequest = new XMLHttpRequest(); if (file) { formData.append('documentName', file); } formData.append('data', JSON.stringify(objSave)); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { observer.next(JSON.parse(xhr.response)); observer.complete(); } else { observer.error(JSON.parse(xhr.response)) } } }; xhr.upload.onprogress = (event) => { this.progress = Math.round(event.loaded / event.total * 100); //this.progressObserver.next(this.progress); }; xhr.open('POST', API_URL + this.blogDocumentApiRoute + "/" + blogId, true); xhr.setRequestHeader("Authorization", Config.AuthToken); xhr.send(formData); }); } updateDocumnet(blogId:string, objUpdate:BlogDocumentModel, file:File, fileDeleted:boolean):Observable<any> { return Observable.create((observer: any) => { let formData:FormData = new FormData(), xhr:XMLHttpRequest = new XMLHttpRequest(); if (file) { formData.append('documentName', file); } formData.append('data', JSON.stringify(objUpdate)); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { observer.next(JSON.parse(xhr.response)); observer.complete(); } else { observer.error(JSON.parse(xhr.response)); } } }; xhr.upload.onprogress = (event) => { this.progress = Math.round(event.loaded / event.total * 100); //this.progressObserver.next(this.progress); }; xhr.open('PUT', API_URL + this.blogDocumentApiRoute + "/" + blogId + "/" + objUpdate._id + "?filedeleted=" + fileDeleted, true); xhr.setRequestHeader("Authorization", Config.AuthToken); xhr.send(formData); }); } // // updateNewsCoverImage(newsId:string, prevCoverImageID:string, objBlogImage:NewsImageModel) { // let body = JSON.stringify(objBlogImage); // return this._http.patch(API_URL + this.newsImageApi + "/" + newsId + "/" + prevCoverImageID, body) // .map(res => res.json()) // .pipe( // catchError(this.handleError) // ); // // } // // Use MIME type instead of Org Ext for document deleteDoc(fileName:string, mimeType:string, path:string):Observable < any > { return this.fileService.deleteFile(fileName, mimeType, path, "document"); } getBlogDocList(blogId:string):Observable < BlogDocumentModel[]> { return this._http.get<BlogDocumentModel[]>(API_URL + this.blogDocumentApiRoute + "/" + blogId) .pipe( catchError(this.handleError) ); } getBlogDocDetail(blogId:string, docId:string):Observable < BlogDocumentModel> { return this._http.get<BlogDocumentModel>(API_URL + this.blogDocumentApiRoute + "/" + blogId + "/" + docId) .pipe( catchError(this.handleError) ); } deleteBlogDoc(blogId:string, docId:string):Observable < any> { var body = JSON.stringify({}); return this._http.patch(API_URL + this.blogDocumentApiRoute + "/" + blogId + "/" + docId, body) .pipe( catchError(this.handleError) ); } // // /* End Blog Image */ /* Blog Meta Tag*/ updateBlogMetaTag(objMeta:BlogMetaTagModel) { let body = JSON.stringify(objMeta); return this._http.put(API_URL + this.blogMetaApiRoute + "/" + objMeta._id, body) .pipe( catchError(this.handleError) ); } getBlogMetaTagDetail(blogId:string):Observable < BlogMetaTagModel> { return this._http.get<BlogMetaTagModel>(API_URL + this.blogMetaApiRoute + "/" + blogId) .pipe( catchError(this.handleError) ); } /* End Blog Meta */ handleError(error: HttpErrorResponse) { if (error.error instanceof ErrorEvent) { // A client-side or network error occurred. Handle it accordingly. console.error('An error occurred:', error.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, console.error( `Backend returned code ${error.status}, ` + `body was: ${error.error.message}`); } // return an ErrorObservable with a user-facing error message return new ErrorObservable(error.error.message ? error.error.message : 'Something bad happened; please try again later.'); } }
the_stack
import { query, poolConnect } from './db-connectors/pg-connector.ts'; import { template } from './sql-template.ts'; import { validate } from './validate-strings.ts'; /* ----------------------------- TYPE INTERFACE ----------------------------- */ interface Info { action: { type: null | string; table: null | string; columns: null | string | string[]; values: unknown[]; valuesParam: string; }; join: Joins[]; filter: { where: boolean; condition?: any; }; returning: { active: boolean; columns: string | string[]; }; } interface Joins { type?: string; table?: string; on?: any; } interface Callback { (key: unknown): unknown; } interface Error { id: number; message: string; } /* -------------------------------------------------------------------------- */ /* DORM CLASS */ /* -------------------------------------------------------------------------- */ export class Dorm { callOrder: string[]; error: Error; info: Info; template: any; constructor(url: string) { this.callOrder = []; this.error = { id: 0, message: '', }; this.info = { action: { type: null, table: null, columns: '*', values: [], valuesParam: '', }, join: [], filter: { where: false, condition: null, }, returning: { active: false, columns: '*', }, }; poolConnect(url); this.template = template.bind(this); } /* ------------------------------ ERROR CHECKING ----------------------------- */ checkErrors(group: number) { const errorObj = this.error; const error = (group === 1 && !!this.info.action.type) || (group === 2 && !!this.info.action.table) || (group === 3 && !!this.info.filter.where) || (group === 4 && !!this.info.returning.active); if (error) errorObj.id = group; return error; } setErrorMessage() { const msg: any = { 1: 'No multiple actions', 2: 'No multiple tables', 3: 'No multiple wheres', 4: 'No multiple returning', 5: 'Number of ONs must equal number of JOINs', 7: 'Insert data must be an object or array of objects', 8: 'Cannot have empty array/object of insert/update data', 9: 'No returning on select', 10: 'No delete without where (use deleteAll to delete all rows)', 11: 'deleteAll cannot have where', 12: 'Invalid on clause', 13: 'Invalid where clause', 14: 'No update without where (use updateAll to update all rows)', 15: 'updateAll cannot have where', 98: 'Invalid tables (cannot contain quotes)', 99: 'Invalid columns (cannot contain quotes)', }; this.error.message = msg[this.error.id]; } finalErrorCheck() { if (this.info.action.type === 'SELECT' && this.info.returning.active) { this.error.id = 9; return true; } if ( this.info.action.type === 'DELETE' && (!this.info.filter.where || !this.info.filter.condition) ) { this.error.id = 10; return true; } if (this.info.action.type === 'DELETEALL' && this.info.filter.where) { this.error.id = 11; return true; } for (const el of this.info.join) { if (!validate.columnsTables(el.table)) { this.error.id = 98; return true; } } if (!validate.columnsTables(this.info.action.table)) { this.error.id = 98; return true; } if ( !validate.columnsTables(this.info.action.columns) || !validate.columnsTables(this.info.returning.columns) ) { this.error.id = 99; return true; } return false; } /* ------------------------------ INSERT METHOD ----------------------------- */ insert(arg: any | unknown[]) { this.callOrder.push('INSERT'); if (typeof arg !== 'object') { this.error.id = 7; return this; } if (Array.isArray(arg)) { if (!arg.length) { this.error.id = 8; return this; } } if (this.checkErrors(1)) return this; this.info.action.type = 'INSERT'; const columns: string[] = []; const values: unknown[] = []; if (!Array.isArray(arg)) { if (!Object.keys(arg).length) { this.error.id = 8; return this; } const [column, value] = Object.entries(arg)[0]; columns.push(column); const val: any = []; if (value === undefined) { val.push(null); } else { val.push(value); } values.push(val); } else { arg.forEach((obj: any) => { if (!Object.keys(obj).length) { this.error.id = 8; return this; } Object.keys(obj).forEach((col) => { if (!columns.includes(col)) columns.push(col); }); }); if (!validate.columnsTables(columns)) { this.error.id = 99; return this; } arg.forEach((obj: any) => { const vals: any = []; columns.forEach((col) => { if (obj[col] === undefined) { vals.push(null); } else { arg.forEach((obj: any) => { if (!Object.keys(obj).length) { this.error.id = 8; return this; } Object.keys(obj).forEach((col) => { if (!columns.includes(col)) columns.push(col); }); }); if (!validate.columnsTables(columns)) { this.error.id = 99; return this; } arg.forEach((obj: any) => { const vals: any = []; columns.forEach((col) => { if (obj[col] === undefined) { vals.push(null); } else { vals.push(obj[col]); } }); values.push(vals); }); } }); values.push(vals); }); } this.info.action.columns = columns.join(', '); // create parameter strings this.info.action.values = values.flat(); let paramCount = 0; const valuesBound = values.map((el: any) => el.map((ele: any) => { paramCount++; return `$${paramCount}`; }) ); valuesBound.forEach((data: any, index: number) => { const tail = index === valuesBound.length - 1 ? '' : ', '; this.info.action.valuesParam += `(${data.join(', ')})${tail}`; }); return this; } /* ------------------------------ SELECT METHOD ----------------------------- */ select(arg?: string) { this.callOrder.push('SELECT'); if (this.checkErrors(1)) return this; this.info.action.type = 'SELECT'; if (arg) this.info.action.columns = arg; return this; } /* ------------------------------ UPDATE METHOD ----------------------------- */ update(obj: any) { this.callOrder.push('UPDATE'); if (this.checkErrors(1)) return this; if (!Object.keys(obj).length || Array.isArray(obj)) { this.error.id = 8; return this; } if (!validate.columnsTables(Object.keys(obj))) { this.error.id = 99; return this; } this.info.action.type = 'UPDATE'; this.info.action.columns = ''; Object.keys(obj).forEach((col, index) => { const str = `${col} = $${index + 1}`; this.info.action.values.push(obj[col]); const tail = index === Object.keys(obj).length - 1 ? '' : ', '; this.info.action.columns += `${str + tail}`; }); return this; } /* ------------------------------ DELETE METHODS ----------------------------- */ delete(arg?: string) { this.callOrder.push('DELETE'); if (this.checkErrors(1)) return this; this.info.action.type = 'DELETE'; if (arg) this.info.action.table = arg; return this; } deleteAll(arg?: string) { this.callOrder.push('DELETEALL'); if (this.checkErrors(1)) return this; this.info.action.type = 'DELETEALL'; if (arg) this.info.action.table = arg; return this; } /* ------------------------------- DROP METHOD ------------------------------ */ drop(arg?: string) { this.callOrder.push('DROP'); if (this.checkErrors(1)) return this; this.info.action.type = 'DROP'; if (arg) this.info.action.table = arg; return this; } /* ------------------------------ TABLE METHOD ------------------------------ */ table(arg: string) { this.callOrder.push('TABLE'); if (this.checkErrors(2)) return this; this.info.action.table = arg; return this; } /** * Alias for table method */ from = this.table; into = this.table; /* ------------------------------ JOIN METHODS ------------------------------ */ join(arg: string) { this.callOrder.push('JOIN-INNER'); const joinList = this.info.join; for (const el of joinList) { if (!el.type) { el.type = 'INNER JOIN'; el.table = arg; return this; } } joinList.push({ type: 'INNER JOIN', table: arg }); return this; } leftJoin(arg: string) { this.callOrder.push('JOIN-LEFT'); const joinList = this.info.join; for (const el of joinList) { if (!el.type) { el.type = 'LEFT JOIN'; el.table = arg; return this; } } joinList.push({ type: 'LEFT JOIN', table: arg }); return this; } rightJoin(arg: string) { this.callOrder.push('JOIN-RIGHT'); const joinList = this.info.join; for (const el of joinList) { if (!el.type) { el.type = 'RIGHT JOIN'; el.table = arg; return this; } } joinList.push({ type: 'RIGHT JOIN', table: arg }); return this; } fullJoin(arg: string) { this.callOrder.push('JOIN-FULL'); const joinList = this.info.join; for (const el of joinList) { if (!el.type) { el.type = 'FULL JOIN'; el.table = arg; return this; } } joinList.push({ type: 'FULL JOIN', table: arg }); return this; } /** * Alias for join method */ innerJoin = this.join; leftOuterJoin = this.leftJoin; rightOuterJoin = this.rightJoin; fullOuterJoin = this.fullJoin; /* -------------------------------- ON METHOD ------------------------------- */ on(arg: string) { this.callOrder.push('ON'); const validated = validate.onWhere(arg); if (validated === 'Error') { this.error.id = 12; return this; } const joinList = this.info.join; for (const el of joinList) { if (!el.on) { el.on = validated; return this; } } joinList.push({ on: validated }); return this; } /* ------------------------------ WHERE METHOD ------------------------------ */ where(arg: string) { this.callOrder.push('WHERE'); if (this.checkErrors(3)) return this; const validated = validate.onWhere(arg); if (validated === 'Error') { this.error.id = 13; return this; } this.info.filter.where = true; this.info.filter.condition = validated; return this; } /* ---------------------------- RETURNING METHOD ---------------------------- */ returning(arg?: string) { this.callOrder.push('RETURNING'); if (this.checkErrors(4)) return this; this.info.returning.active = true; if (arg) this.info.returning.columns = arg; return this; } /* -------------------------------------------------------------------------- */ /* QUERY BUILDER FUNCTIONS */ /* -------------------------------------------------------------------------- */ /* ------------------------------ RESET METHOD ------------------------------ */ private _reset() { // clear info for future function this.callOrder = []; this.error = { id: 0, message: '', }; this.info = { action: { type: null, table: null, columns: '*', values: [], valuesParam: '', }, join: [], filter: { where: false, condition: null, }, returning: { active: false, columns: '*', }, }; } /* ------------------------------- THEN METHOD ------------------------------ */ async then(callback: Callback, fail: Callback = (rej) => rej) { this.finalErrorCheck(); if (this.error.id) { this.setErrorMessage(); const { message } = this.error; this._reset(); const cbText = callback.toString(); if (isNative(cbText)) { return await callback(Promise.reject(message)); } return await fail(Promise.reject(message)); } let result: any; try { const params = this.info.action.values; result = await query(this.toString(), params); } catch (e) { this._reset(); const cbText = callback.toString(); if (isNative(cbText)) { return await callback(Promise.reject(e)); } return await fail(Promise.reject(e)); } try { return await callback(result); } catch (error) { throw error; } // thanks to David Walsh at https://davidwalsh.name/detect-native-function function isNative(fn: any) { return /\{\s*\[native code\]\s*\}/.test('' + fn); } } /* ----------------------------- TOSTRING METHOD ---------------------------- */ toString() { this.finalErrorCheck(); if (this.error.id) { this.setErrorMessage(); const { message } = this.error; this._reset(); throw message; } const action = this.info.action.type; const joinList = this.info.join; const filter = this.info.filter.where; const returning = this.info.returning.active; let queryTemplate = ''; if (action) queryTemplate = this.template(action); while (joinList.length) { const el = joinList[0]; if (el.type?.includes('JOIN') && el.on) { queryTemplate += this.template('JOIN'); const params = validate.insertParams( el.on.tokens, this.info.action.values.length + 1 ); this.info.action.values.push(...el.on.values); el.on = params.join(' '); queryTemplate += this.template('ON'); } else { this.error.id = 5; this.setErrorMessage(); const { message } = this.error; this._reset(); throw message; } joinList.shift(); } if (this.info.filter.where) { const whereCondition = this.info.filter.condition; const params = validate.insertParams( whereCondition.tokens, this.info.action.values.length + 1 ); this.info.action.values.push(...whereCondition.values); this.info.filter.condition = params.join(' '); queryTemplate += this.template('WHERE'); } if (returning) queryTemplate += this.template('RETURNING'); this._reset(); return queryTemplate; } toObj() { const values = this.info.action.values; const text = this.toString(); return { text, values, }; } /** * Alias for toObj method */ toObject = this.toObj; /* ------------------------------ RAW METHOD ------------------------------ */ async raw(arg: string, vals: unknown[] = []) { return await query(arg, vals); } rawr = this.raw; rawrr = this.raw; }
the_stack
import { AttributeDirective } from "../vdom/attribute_directive"; import { CSSStyleProps } from "./style"; /* tslint:disable:max-line-length no-empty-interface */ export declare interface ElementAttrs { style?: CSSStyleProps; /** * The id global attribute defines a unique identifier (ID) which must be unique in the whole document. Its purpose * is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS). * * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id} */ id?: string | number; /** * innerHTML attribute is disabled, unsafeHTML attribute is used to assign innerHTML. * * @example * * const n = div("", { unsafeHTML: UNSAFE_HTML("<span></span>") }); */ innerHTML?: never; /** * unsafeHTML attribute is used to assign innerHTML. * * @example * * const n = div("", { unsafeHTML: UNSAFE_HTML("<span></span>") }); */ unsafeHTML?: AttributeDirective<string>; /** * Provides a way to direct a user to a specific field when element is instantiated. This can provide both direction * and convenience for a user, reducing the need to click or tab to a field. * * @example * * const n = input("", { autofocus: AUTOFOCUS(true) }); */ autofocus?: AttributeDirective<boolean>; [key: string]: string | number | boolean | AttributeDirective<any> | CSSStyleProps | undefined; } export declare interface HTMLElementAttrs extends ElementAttrs { /** * The accesskey global attribute provides a hint for generating a keyboard shortcut for the current element. The * attribute value must consist of a single printable character (which includes accented and other characters that * can be generated by the keyboard). * * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/accesskey} */ accesskey?: string; /** * The autocapitalize global attribute is an enumerated attribute that controls whether and how text input is * automatically capitalized as it is entered/edited by the user. The attribute must take one of the following values: * - "off" or "none": No autocapitalization is applied (all letters default to lowercase) * - "on" or "sentences": The first letter of each sentence defaults to a capital letter; all other letters default to * lowercase * - "words": The first letter of each word defaults to a capital letter; all other letters default to lowercase * - "characters": All letters should default to uppercase * * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autocapitalize} */ autocapitalize?: string; /** * The contenteditable global attribute is an enumerated attribute indicating if the element should be editable by * the user. If so, the browser modifies its widget to allow editing. The attribute must take one of the following * values: * * - "true" * - "false" * - "plaintext-only" * - "events" * - "caret" * - "typing" * - "inherit" * * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable} */ contenteditable?: string; /** * The dir global attribute is an enumerated attribute indicates the directionality of the element's text. It can * have the following values: * * - "ltr" * - "rtl" * - "auto" * * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir} */ dir?: string; /** * The draggable global attribute is an enumerated attribute that indicates whether the element can be dragged, using * the HTML Drag and Drop API. It can have the following values: * * - "true" * - "false" * * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/draggable} */ draggable?: string; /** * The hidden global attribute is a Boolean attribute indicating that the element is not yet, or is no longer, * relevant. For example, it can be used to hide elements of the page that can't be used until the login process has * been completed. Browsers won't render elements with the hidden attribute set. * * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden} */ hidden?: boolean; /** * The lang global attribute helps define the language of an element: the language that non-editable elements are * written in, or the language that the editable elements should be written in by the user. * * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang} */ lang?: string; /** * The spellcheck global attribute is an enumerated attribute defines whether the element may be checked for spelling * errors. It may have the following values: * * - "true" * - "false" * * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/spellcheck} */ spellcheck?: boolean; /** * The tabindex global attribute indicates if its element can be focused, and if/where it participates in sequential * keyboard navigation (usually with the Tab key, hence the name). * * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex} */ tabIndex?: string | number; /** * The title global attribute contains text representing advisory information, related to the element it belongs to. * * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/title} */ title?: string; } export declare interface HTMLAnchorElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the character set used to encode the object. */ charset?: string; /** * Sets or retrieves the coordinates of the object. */ coords?: string; download?: string; /** * Sets or retrieves a destination URL or an anchor point. */ href?: string; /** * Sets or retrieves the language code of the object. */ hreflang?: string; /** * Sets or retrieves the shape of the object. */ name?: string; /** * Sets or retrieves the relationship between the object and the destination of the link. */ rel?: string; /** * Sets or retrieves the relationship between the object and the destination of the link. */ rev?: string; /** * Sets or retrieves the shape of the object. */ shape?: string; /** * Sets or retrieves the window or frame at which to target content. */ target?: string; /** * Retrieves or sets the text of the object as a string. */ text?: string; type?: string; urn?: string; } export declare interface HTMLAreaElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves a text alternative to the graphic. */ alt?: string; /** * Sets or retrieves the coordinates of the object. */ coords?: string; download?: string; /** * Sets or retrieves a destination URL or an anchor point. */ href?: string; /** * Sets or gets whether clicks in this region cause action. */ noHref?: boolean; rel?: string; /** * Sets or retrieves the shape of the object. */ shape?: string; /** * Sets or retrieves the window or frame at which to target content. */ target?: string; } export declare interface HTMLMediaElementAttrs extends HTMLElementAttrs { /** * Gets or sets a value that indicates whether to start playing the media automatically. */ autoplay?: boolean; /** * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the * developer does not include controls for the player). */ controls?: boolean; crossOrigin?: string; /** * Gets or sets the current playback position, in seconds. */ currentTime?: number; defaultMuted?: boolean; /** * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio * resource. */ defaultPlaybackRate?: number; /** * Gets or sets a flag to specify whether playback should restart after it completes. */ loop?: boolean; /** * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. */ muted?: boolean; /** * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple * of the normal speed of the media resource. */ playbackRate?: number; /** * Gets or sets the current playback position, in seconds. */ preload?: string; readyState?: number; /** * The address or URL of the a media resource that is to be considered. */ src?: string; /** * Gets or sets the volume level for audio portions of the media element. */ volume?: number; } export declare interface HTMLAudioElementAttrs extends HTMLMediaElementAttrs { } export declare interface HTMLBaseElementAttrs extends HTMLElementAttrs { /** * Gets or sets the baseline URL on which relative links are based. */ href?: string; /** * Sets or retrieves the window or frame at which to target content. */ target?: string; } export declare interface HTMLQuoteElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves reference information about the object. */ cite?: string; } export declare interface HTMLBodyElementAttrs extends HTMLElementAttrs { } export declare interface HTMLBRElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is * inserted into the document. */ clear?: string; } export declare interface HTMLButtonElementAttrs extends HTMLElementAttrs { disabled?: boolean; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ formaction?: string; /** * Used to override the encoding (formEnctype attribute) specified on the form element. */ formenctype?: string; /** * Overrides the submit method attribute previously specified on a form element. */ formmethod?: string; /** * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without * validation. This can be used to create a "save draft"-type submit option. */ formnovalidate?: string; /** * Overrides the target attribute on a form element. */ formtarget?: string; /** * Sets or retrieves the name of the object. */ name?: string; /** * Gets the classification and default behavior of the button. */ type?: string; /** * Sets or retrieves the default or selected value of the control. */ value?: string; } export declare interface HTMLCanvasElementAttrs extends HTMLElementAttrs { /** * Gets or sets the height of a canvas element on a document. */ height?: number; /** * Gets or sets the width of a canvas element on a document. */ width?: number; } export declare interface HTMLTableCaptionElementAttrs extends HTMLElementAttrs { } export declare interface HTMLTableColElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the number of columns in the group. */ span?: number; } export declare interface HTMLModElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves reference information about the object. */ cite?: string; /** * Sets or retrieves the date and time of a modification to the object. */ dateTime?: string; } export declare interface HTMLDivElementAttrs extends HTMLElementAttrs { } export declare interface HTMLDListElementAttrs extends HTMLElementAttrs { } export declare interface HTMLFieldSetElementAttrs extends HTMLElementAttrs { disabled?: boolean; } export declare interface HTMLFormElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing * the form. */ "accept-charset"?: string; /** * Sets or retrieves the URL to which the form content is sent for processing. */ action?: string; /** * Specifies whether autocomplete is applied to an editable text field. */ autocomplete?: string; /** * Sets or retrieves the encoding type for the form. */ enctype?: string; /** * Sets or retrieves how to send the form data to the server. */ method?: string; /** * Sets or retrieves the name of the object. */ name?: string; /** * Designates a form that is not validated when submitted. */ novalidate?: boolean; /** * Sets or retrieves the window or frame at which to target content. */ target?: string; } export declare interface HTMLHeadingElementAttrs extends HTMLElementAttrs { } export declare interface HTMLHeadElementAttrs extends HTMLElementAttrs { profile?: string; } export declare interface HTMLHRElementAttrs extends HTMLElementAttrs { } export declare interface HTMLHtmlElementAttrs extends HTMLElementAttrs { } export declare interface HTMLIFrameElementAttrs extends HTMLElementAttrs { /** * This attribute can be set to true if the frame is allowed to be placed into full screen mode by calling its * `requestFullscreen()` method. If this isn't set, the element can't be placed into full screen mode. */ allowfullscreen?: boolean; /** * This attribute can be set to true if the contents of a cross-origin <iframe> should be allowed to invoke the * Payment Request API. */ allowpaymentrequest?: boolean; /** * Sets or retrieves the height of the object. */ height?: string; /** * Sets or retrieves the frame name. */ name?: string; /** * Sets or retrieves whether the user can resize the frame. */ noresize?: boolean; /** * A string indicating which referrer to use when fetching the resource. */ referrerpolicy?: string; /** * If specified as an empty string, this attribute enables extra restrictions on the content that can appear in the * inline frame. The value of the attribute can either be an empty string (all the restrictions are applied), or a * space-separated list of tokens that lift particular restrictions. */ sandbox?: string; /** * Sets or retrieves whether the frame can be scrolled. */ scrolling?: string; /** * Sets or retrieves a URL to be loaded by the object. */ src?: string; /** * The content of the page that the embedded context is to contain. This attribute is expected to generally be used * together with the sandbox attribute. If a browser supports the srcdoc attribute, it will override the content * specified in the src attribute (if present). If a browser does not support the srcdoc attribute, it will show the * file specified in the src attribute instead (if present). Note that if the content of the attribute contains a * script tag then a closing script tag is required for the script to run, even if nothing else comes after the * script. */ srcdoc?: string; /** * Sets or retrieves the width of the object. */ width?: string; } export declare interface HTMLImageElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves a text alternative to the graphic. */ alt?: string; /** * This enumerated attribute indicates if the fetching of the related image must be done using CORS or not. * CORS-enabled images can be reused in the <canvas> element without being "tainted." */ crossorigin?: string; /** * Sets or retrieves the height of the object. */ height?: number; /** * Sets or retrieves whether the image is a server-side image map. */ ismap?: boolean; /** * Sets or retrieves the name of the object. */ name?: string; /** * A list of one or more strings separated by commas indicating a set of source sizes. */ sizes?: string; /** * The address or URL of the a media resource that is to be considered. */ src?: string; /** * A list of one or more strings separated by commas indicating a set of possible image sources for the user agent to * use. */ srcset?: string; /** * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. */ usemap?: string; /** * Sets or retrieves the width of the object. */ width?: number; } export declare interface HTMLInputElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves a comma-separated list of content types. */ accept?: string; /** * Sets or retrieves a text alternative to the graphic. */ alt?: string; /** * Specifies whether autocomplete is applied to an editable text field. */ autocomplete?: string; /** * Sets or retrieves the state of the check box or radio button. */ defaultChecked?: boolean; /** * Sets or retrieves the initial contents of the object. */ defaultValue?: string; /** * This Boolean attribute indicates that the form control is not available for interaction. In particular, the click * event will not be dispatched on disabled controls. Also, a disabled control's value isn't submitted with the form. */ disabled?: boolean; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ formaction?: string; /** * Used to override the encoding (formEnctype attribute) specified on the form element. */ formenctype?: string; /** * Overrides the submit method attribute previously specified on a form element. */ formmethod?: string; /** * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without * validation. This can be used to create a "save draft"-type submit option. */ formnovalidate?: string; /** * Overrides the target attribute on a form element. */ formtarget?: string; /** * Sets or retrieves the height of the object. */ height?: string; /** * A hint to the browser for which virtual keyboard to display. This attribute applies when the value of the type * attribute is text, password, email, or url. */ inputmode?: string; /** * Defines the maximum acceptable value for an input element with type="number".When used with the min and step * attributes, lets you control the range and increment (such as only even numbers) that the user can enter into * an input field. */ max?: string; /** * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ maxlength?: number; /** * Defines the minimum acceptable value for an input element with type="number". When used with the max and step * attributes, lets you control the range and increment (such as even numbers only) that the user can enter into * an input field. */ min?: string; /** * Sets or retrieves the minimum number of characters that the user can enter in a text control. */ minlength?: number; /** * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. */ multiple?: boolean; /** * Sets or retrieves the name of the object. */ name?: string; /** * Gets or sets a string containing a regular expression that the user's input must match. */ pattern?: string; /** * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or * type of information they need to enter.The text appears in an input field until the user puts focus on the * field. */ placeholder?: string; /** * This attribute indicates that the user cannot modify the value of the control. The value of the attribute is * irrelevant. If you need read-write access to the input value, do not add the "readonly" attribute. */ readonly?: string; /** * When present, marks an element that can't be submitted without a value. */ required?: boolean; /** * The direction in which selection occurred. This is "forward" if the selection was made from left-to-right in an * LTR locale or right-to-left in an RTL locale, or "backward" if the selection was made in the opposite direction. */ selectionDirection?: string; /** * Gets or sets the end position or offset of a text selection. */ selectionEnd?: number; /** * Gets or sets the starting position or offset of a text selection. */ selectionStart?: number; /** * The initial size of the control. This value is in pixels unless the value of the type attribute is text or * password, in which case it is an integer number of characters. Starting in HTML5, this attribute applies only when * the type attribute is set to text, search, tel, url, email, or password, otherwise it is ignored. */ size?: number; /** * The address or URL of the a media resource that is to be considered. */ src?: string; /** * Defines an increment or jump between values that you want to allow the user to enter. When used with the max * and min attributes, lets you control the range and increment (for example, allow only even numbers) that the * user can enter into an input field. */ step?: string; /** * Returns the content type of the object. */ type?: string; /** * Sets or retrieves the width of the object. */ width?: string; /** * Input checked value. * * @example * * const n = input("", { type: "checked", checked: CHECKED(true) }); */ checked?: AttributeDirective<boolean>; /** * Input value. * * @example * * const n = input("", { value: VALUE("abc") }); */ value?: AttributeDirective<string>; } export declare interface HTMLUnknownElementAttrs extends HTMLElementAttrs { } export declare interface HTMLLabelElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the object to which the given label object is assigned. */ for?: string; } export declare interface HTMLLegendElementAttrs extends HTMLElementAttrs { } export declare interface HTMLLIElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the value of a list item. */ value?: number; } export declare interface HTMLLinkElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the character set used to encode the object. */ charset?: string; disabled?: boolean; /** * Sets or retrieves a destination URL or an anchor point. */ href?: string; /** * Sets or retrieves the language code of the object. */ hreflang?: string; /** * Sets or retrieves the media type. */ media?: string; /** * Sets or retrieves the relationship between the object and the destination of the link. */ rel?: string; /** * Sets or retrieves the relationship between the object and the destination of the link. */ rev?: string; /** * Sets or retrieves the window or frame at which to target content. */ target?: string; /** * Sets or retrieves the MIME type of the object. */ type?: string; integrity?: string; } export declare interface HTMLMapElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the name of the object. */ name?: string; } export declare interface HTMLMediaElementAttrs extends HTMLElementAttrs { /** * Gets or sets a value that indicates whether to start playing the media automatically. */ autoplay?: boolean; /** * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the * developer does not include controls for the player). */ controls?: boolean; crossOrigin?: string; /** * Gets or sets the current playback position, in seconds. */ currentTime?: number; defaultMuted?: boolean; /** * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio * resource. */ defaultPlaybackRate?: number; /** * Gets or sets a flag to specify whether playback should restart after it completes. */ loop?: boolean; /** * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. */ muted?: boolean; /** * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of * the normal speed of the media resource. */ playbackRate?: number; /** * Gets or sets the current playback position, in seconds. */ preload?: string; readyState?: number; /** * The address or URL of the a media resource that is to be considered. */ src?: string; /** * Gets or sets the volume level for audio portions of the media element. */ volume?: number; } export declare interface HTMLMenuElementAttrs extends HTMLElementAttrs { } export declare interface HTMLMetaElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the character set used to encode the object. */ charset?: string; /** * Gets or sets meta-information to associate with httpEquiv or name. */ content?: string; /** * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response * header. */ httpEquiv?: string; /** * Sets or retrieves the value specified in the content attribute of the meta object. */ name?: string; /** * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. */ scheme?: string; /** * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url?: string; } export declare interface HTMLMeterElementAttrs extends HTMLElementAttrs { high?: number; low?: number; max?: number; min?: number; optimum?: number; value?: number; } export declare interface HTMLModElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves reference information about the object. */ cite?: string; /** * Sets or retrieves the date and time of a modification to the object. */ dateTime?: string; } export declare interface HTMLOListElementAttrs extends HTMLElementAttrs { /** * The starting number. */ start?: number; } export declare interface HTMLOptGroupElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the status of an option. */ defaultSelected?: boolean; disabled?: boolean; /** * Sets or retrieves a value that you can use to implement your own label functionality for the object. */ label?: string; /** * Sets or retrieves whether the option in the list box is the default item. */ selected?: boolean; /** * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value?: string; } export declare interface HTMLOptionElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the status of an option. */ defaultSelected?: boolean; disabled?: boolean; /** * Sets or retrieves a value that you can use to implement your own label functionality for the object. */ label?: string; /** * Sets or retrieves whether the option in the list box is the default item. */ selected?: boolean; /** * Sets or retrieves the text string specified by the option tag. */ text?: string; /** * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value?: string; } export declare interface HTMLParagraphElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves how the object is aligned with adjacent text. */ align?: string; clear?: string; } export declare interface HTMLPictureElementAttrs extends HTMLElementAttrs { } export declare interface HTMLPreElementAttrs extends HTMLElementAttrs { /** * Sets or gets a value that you can use to implement your own width functionality for the object. */ width?: number; } export declare interface HTMLProgressElementAttrs extends HTMLElementAttrs { /** * Defines the maximum, or "done" value for a progress element. */ max?: number; /** * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the * max value. */ value?: number; } export declare interface HTMLQuoteElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves reference information about the object. */ cite?: string; } export declare interface HTMLScriptElementAttrs extends HTMLElementAttrs { async?: boolean; /** * Sets or retrieves the character set used to encode the object. */ charset?: string; /** * Sets or retrieves the status of the script. */ defer?: boolean; /** * Sets or retrieves the event for which the script is written. */ event?: string; /** * Sets or retrieves the object that is bound to the event script. */ for?: string; /** * Retrieves the URL to an external file that contains the source code or data. */ src?: string; /** * Retrieves or sets the text of the object as a string. */ text?: string; /** * Sets or retrieves the MIME type for the associated scripting engine. */ type?: string; integrity?: string; } export declare interface HTMLSelectElementAttrs extends HTMLElementAttrs { disabled?: boolean; /** * Sets or retrieves the number of objects in a collection. */ length?: number; /** * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. */ multiple?: boolean; /** * Sets or retrieves the name of the object. */ name?: string; /** * When present, marks an element that can't be submitted without a value. */ required?: boolean; /** * Sets or retrieves the index of the selected option in a select object. */ selectedIndex?: number; /** * Sets or retrieves the number of rows in the list box. */ size?: number; /** * Sets or retrieves the value which is returned to the server when the form control is submitted. */ value?: string; } export declare interface HTMLSourceElementAttrs extends HTMLElementAttrs { /** * Gets or sets the intended media type of the media source. */ media?: string; sizes?: string; /** * The address or URL of the a media resource that is to be considered. */ src?: string; srcset?: string; /** * Gets or sets the MIME type of a media resource. */ type?: string; } export declare interface HTMLSpanElementAttrs extends HTMLElementAttrs { } export declare interface HTMLStyleElementAttrs extends HTMLElementAttrs { disabled?: boolean; /** * Sets or retrieves the media type. */ media?: string; /** * Retrieves the CSS language in which the style sheet is written. */ type?: string; } export declare interface HTMLTableCaptionElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the alignment of the caption or legend. */ align?: string; /** * Sets or retrieves whether the caption appears at the top or bottom of the table. */ vAlign?: string; } export declare interface HTMLTableCellElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the number columns in the table that the object should span. */ colspan?: number; /** * Sets or retrieves a list of header cells that provide information for the object. */ headers?: string; /** * Sets or retrieves the height of the object. */ height?: any; /** * Sets or retrieves how many rows in a table the cell should span. */ rowSpan?: number; /** * Sets or retrieves the width of the object. */ width?: string; } export declare interface HTMLTableColElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the number of columns in the group. */ span?: number; /** * Sets or retrieves the width of the object. */ width?: any; } export declare interface HTMLTableDataCellElementAttrs extends HTMLTableCellElementAttrs { } export declare interface HTMLTableElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the height of the object. */ height?: any; /** * Sets or retrieves the width of the object. */ width?: string; } export declare interface HTMLTableHeaderCellElementAttrs extends HTMLTableCellElementAttrs { } export declare interface HTMLTableRowElementAttrs extends HTMLElementAttrs { } export declare interface HTMLTableSectionElementAttrs extends HTMLElementAttrs { } export declare interface HTMLTemplateElementAttrs extends HTMLElementAttrs { } export declare interface HTMLTextAreaElementAttrs extends HTMLElementAttrs { /** * Sets or retrieves the width of the object. */ cols?: number; /** * Sets or retrieves the initial contents of the object. */ defaultValue?: string; disabled?: boolean; /** * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ maxLength?: number; /** * Sets or retrieves the minimum number of characters that the user can enter in a text control. */ minlength?: number; /** * Sets or retrieves the name of the object. */ name?: string; /** * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or * type of information they need to enter.The text appears in an input field until the user puts focus on the * field. */ placeholder?: string; /** * Sets or retrieves the value indicated whether the content of the object is read-only. */ readonly?: string; /** * When present, marks an element that can't be submitted without a value. */ required?: boolean; /** * Sets or retrieves the number of horizontal rows contained in the object. */ rows?: number; /** * Gets or sets the end position or offset of a text selection. */ selectionEnd?: number; /** * Gets or sets the starting position or offset of a text selection. */ selectionStart?: number; /** * Sets or retrieves the value indicating whether the control is selected. */ status?: any; /** * Sets or retrieves how to handle wordwrapping in the object. */ wrap?: string; /** * Text area value is disable, content attribute is used to assign text area value. * * @example * * const n = textarea("", { content: CONTENT("abc") }); */ value?: never; /** * Text area value. * * @example * * const n = textarea("", { content: CONTENT("abc") }); */ content?: AttributeDirective<string>; } export declare interface HTMLTitleElementAttrs extends HTMLElementAttrs { /** * Retrieves or sets the text of the object as a string. */ text?: string; } export declare interface HTMLTrackElementAttrs extends HTMLElementAttrs { default?: boolean; kind?: string; label?: string; src?: string; srclang?: string; } export declare interface HTMLUListElementAttrs extends HTMLElementAttrs { } export declare interface HTMLVideoElementAttrs extends HTMLMediaElementAttrs { /** * Gets or sets the height of the video element. */ height?: number; /** * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the * video, or another image if no video data is available. */ poster?: string; /** * Gets or sets the width of the video element. */ width?: number; } /* tslint:disable:max-line-length no-empty-interface */
the_stack
import _ from 'lodash' import IstioFunctions from "./istioFunctions"; import { K8sClient } from "./k8sClient"; import K8sFunctions from "./k8sFunctions"; import { ServiceDetails } from "./k8sObjectTypes"; import {isGlobalFqdn, isNamespaceFqdn, isServiceFqdn, normalizeServiceFqdn, FqdnMatcher} from '../util/matchUtil' import yaml from 'yaml' import { inherits } from "util"; export enum ServiceMtlsMode { DISABLE = "DISABLE", STRICT = "STRICT", PERMISSIVE = "PERMISSIVE" } export enum ClientMtlsMode { NONE = "NONE", DISABLE = "DISABLE", ISTIO_MUTUAL = "ISTIO_MUTUAL" } export interface GlobalMtlsStatus { isGlobalMtlsEnabled: boolean isGlobalMtlsPermissive: boolean globalMtlsMode: ServiceMtlsMode } export interface MtlsPolicyInfo { namespace: string, serviceName: string, policyName: string, ports: any[], peers: any[], mode: string, policy: any } export class MtlsUtil { static getGlobalMtlsStatus = async (k8sClient: K8sClient) => { let globalMtlsMode = ServiceMtlsMode.DISABLE const defaultMeshPolicy = (await IstioFunctions.listAllMeshPolicies(k8sClient)) .filter(policy => policy.name === 'default')[0] if(defaultMeshPolicy) { const meshPolicyMtls = defaultMeshPolicy.peers.filter(p => p.mtls).map(p => p.mtls)[0] meshPolicyMtls && (globalMtlsMode = meshPolicyMtls.mode ? meshPolicyMtls.mode.toUpperCase() : ServiceMtlsMode.STRICT) } return { isGlobalMtlsEnabled: globalMtlsMode !== ServiceMtlsMode.DISABLE, isGlobalMtlsPermissive: globalMtlsMode === ServiceMtlsMode.PERMISSIVE, globalMtlsMode, } as GlobalMtlsStatus } static getMtlsPolicies = async (k8sClient: K8sClient) => { const namespacesWithDefaultMtls = {} const namespaceDefaultMtlsPolicies = {} const servicesWithMtlsPolicies: any[] = [] const policies = await IstioFunctions.listAllPolicies(k8sClient, false) if(policies && policies.length) { policies .filter(policy => policy.name === 'default' && !policy.targets && policy.peers && (policy.peers.length === 0 || policy.peers.filter(peer => peer.mtls).length > 0)) .forEach(policy => { namespaceDefaultMtlsPolicies[policy.namespace] = policy const peerMtls = policy.peers.filter(peer => peer.mtls).map(peer => peer.mtls)[0] namespacesWithDefaultMtls[policy.namespace] = peerMtls && peerMtls.mode ? peerMtls.mode.toUpperCase() : ServiceMtlsMode.DISABLE }) policies.filter(policy => policy.name !== 'default' && policy.peers && policy.peers.filter(peer => peer.mtls).length > 0 && policy.targets && policy.targets.length > 0) .forEach(policy => policy.targets.forEach(target => { const peerMtls = policy.peers.filter(peer => peer.mtls).map(peer => peer.mtls)[0] servicesWithMtlsPolicies.push({ serviceName: target.name, ports: target.ports, policyName: policy.name, namespace: policy.namespace, peers: policy.peers, mode: peerMtls && peerMtls.mode ? peerMtls.mode.toUpperCase() : ServiceMtlsMode.DISABLE, policy }) })) } return { namespacesWithDefaultMtls, namespaceDefaultMtlsPolicies, servicesWithMtlsPolicies } } private static filterMtlsDestinationRules(drules: any[]) { return drules.filter(dr => dr.host && dr.trafficPolicy) .filter(dr => { if(dr.trafficPolicy.tls && dr.trafficPolicy.tls.mode || dr.trafficPolicy.portLevelSettings && dr.trafficPolicy.portLevelSettings.filter(p => p.tls).length > 0) { return true } else { dr.trafficPolicy = (dr.trafficPolicy || {}) dr.trafficPolicy.tls = (dr.trafficPolicy.tls || {}) dr.trafficPolicy.tls.mode = 'DISABLE' dr.trafficPolicy.tls.note = "** DR missing TLS mode, defaults to DISABLE **" return true } }) } private static async filterGlobalMtlsDestinationRules(drules: any[], configNamespace: string) { return drules.filter(dr => dr.namespace === configNamespace && (!dr.exportTo || dr.exportTo.includes("*"))) } private static async filterNonGlobalMtlsDestinationRules(drules: any[], configNamespace: string) { return drules.filter(dr => dr.namespace !== configNamespace && (!dr.exportTo || dr.exportTo.includes("*"))) } static getMtlsDestinationRules = async (k8sClient: K8sClient) => { const mtlsDestinationRules = MtlsUtil.filterMtlsDestinationRules( IstioFunctions.extractDestinationRules(await k8sClient.istio.destinationrules.get())) mtlsDestinationRules.forEach(dr => { dr.data = {} dr.data.isTargetGlobal = isGlobalFqdn(dr.host) dr.data.isTargetNamespace = isNamespaceFqdn(dr.host) dr.data.isTargetService = isServiceFqdn(dr.host) dr.data.targetService = dr.data.isTargetService ? normalizeServiceFqdn(dr.host) : undefined dr.data.targetNamespace = (dr.data.isTargetNamespace || dr.data.targetService) && dr.host.split(".")[1] dr.data.sourceNamespace = dr.namespace dr.data.targetSelf = dr.namespace === dr.data.targetNamespace }) const istioConfigMap = await K8sFunctions.getNamespaceConfigMap("istio", "istio-system", k8sClient) const configNamespace = istioConfigMap ? yaml.parse(istioConfigMap.data.mesh).rootNamespace : "istio-system" const allGlobalRules = await MtlsUtil.filterGlobalMtlsDestinationRules(mtlsDestinationRules, configNamespace) const allNonGlobalRules = await MtlsUtil.filterNonGlobalMtlsDestinationRules(mtlsDestinationRules, configNamespace) const globalRules : any[] = [] const allToNSRules = {} const allToServiceRules = {} const nsToAllRules = {} const nsToNSRules = {} const nsToServiceRules = {} //Global rules have lowest priority allGlobalRules.forEach(dr => { if(dr.data.isTargetGlobal) { globalRules.push(dr) } else if(dr.data.isTargetNamespace) { allToNSRules[dr.data.targetNamespace] = allToNSRules[dr.data.targetNamespace] || [] allToNSRules[dr.data.targetNamespace].push(dr) } else if(dr.data.isTargetService) { allToServiceRules[dr.data.targetService] = allToServiceRules[dr.data.targetService] || [] allToServiceRules[dr.data.targetService].push(dr) } delete dr.data }) //Service namespace rules have medium priority allNonGlobalRules.forEach(dr => { const sourceNS = dr.data.sourceNamespace const targetNS = dr.data.targetNamespace if(dr.data.isTargetGlobal) { nsToAllRules[sourceNS] = nsToAllRules[sourceNS] || [] nsToAllRules[sourceNS].push(dr) //An NSToAll rule is also an AllToNS rule allToNSRules[sourceNS] = allToNSRules[sourceNS] || [] allToNSRules[sourceNS].push(dr) } else if(dr.data.isTargetNamespace) { nsToNSRules[sourceNS] = nsToNSRules[sourceNS] || {} nsToNSRules[sourceNS][targetNS] = nsToNSRules[sourceNS][targetNS] || [] nsToNSRules[sourceNS][targetNS].push(dr) if(sourceNS === targetNS) { allToNSRules[targetNS] = allToNSRules[targetNS] || [] allToNSRules[targetNS].push(dr) } } else if(dr.data.isTargetService) { nsToServiceRules[sourceNS] = nsToServiceRules[sourceNS] || {} nsToServiceRules[sourceNS][dr.data.targetService] = nsToServiceRules[sourceNS][dr.data.targetService] || [] nsToServiceRules[sourceNS][dr.data.targetService].push(dr) if(sourceNS === targetNS) { allToServiceRules[dr.data.targetService] = allToServiceRules[dr.data.targetService] || [] allToServiceRules[dr.data.targetService].push(dr) } } delete dr.data }) return { globalRules, allToNSRules, allToServiceRules, nsToAllRules, nsToNSRules, nsToServiceRules } } static TlsModeExtractor = { currentLevelPortTlsModes: {}, //used to reset a port's tls config if seen at a higher priority level map: {}, init(map: any) { this.currentLevelPortTlsModes = {} this.map = map }, extractDestinationRuleTlsModes(dr) { if(dr.trafficPolicy) { if(dr.trafficPolicy.tls && dr.trafficPolicy.tls.mode) { Object.keys(this.map).forEach(key => { if(this.currentLevelPortTlsModes[key]) { this.map[key].push({mode: dr.trafficPolicy.tls.mode, dr}) } else { this.currentLevelPortTlsModes[key]=true this.map[key] = [{mode: dr.trafficPolicy.tls.mode, dr}] } }) if(this.currentLevelPortTlsModes[""]) { this.map[""].push({mode: dr.trafficPolicy.tls.mode, dr}) } else { this.currentLevelPortTlsModes[""]=true this.map[""] = [{mode: dr.trafficPolicy.tls.mode, dr}] } } dr.trafficPolicy.portLevelSettings && dr.trafficPolicy.portLevelSettings.forEach(p => { if(p.port && p.tls && p.tls.mode) { const portId = p.port.number || p.port.name if(this.currentLevelPortTlsModes[portId]) { this.map[portId].push({mode: p.tls.mode, dr}) } else { this.currentLevelPortTlsModes[portId]=true this.map[portId] = [{mode: p.tls.mode, dr}] } } }) } } } static getMtlsModes = (mtlsDestinationRules: any) => { const {globalRules, allToNSRules, allToServiceRules, nsToAllRules, nsToNSRules, nsToServiceRules} = mtlsDestinationRules //maps from NS/Service to ports to array of tls modes const allToAllMtlsModes = {} const allToNSMtlsModes = {} const nsToAllMtlsModes = {} const nsToNSMtlsModes = {} const allToServiceMtlsModes = {} const nsToServiceMtlsModes = {"": {}} MtlsUtil.TlsModeExtractor.init(allToAllMtlsModes) globalRules.filter(dr => dr.host === "*") .forEach(dr => MtlsUtil.TlsModeExtractor.extractDestinationRuleTlsModes(dr)) MtlsUtil.TlsModeExtractor.init(allToAllMtlsModes) globalRules.filter(dr => dr.host === "*.local") .forEach(dr => MtlsUtil.TlsModeExtractor.extractDestinationRuleTlsModes(dr)) MtlsUtil.TlsModeExtractor.init(allToAllMtlsModes) globalRules.filter(dr => dr.host === "*.cluster.local") .forEach(dr => MtlsUtil.TlsModeExtractor.extractDestinationRuleTlsModes(dr)) MtlsUtil.TlsModeExtractor.init(allToAllMtlsModes) globalRules.filter(dr => dr.host === "*.svc.cluster.local") .forEach(dr => MtlsUtil.TlsModeExtractor.extractDestinationRuleTlsModes(dr)) Object.keys(allToNSRules).forEach(targetNS => { if(!allToNSMtlsModes[targetNS]) { allToNSMtlsModes[targetNS] = {} } MtlsUtil.TlsModeExtractor.init(allToNSMtlsModes[targetNS]) allToNSRules[targetNS].forEach(dr => MtlsUtil.TlsModeExtractor.extractDestinationRuleTlsModes(dr)) }) Object.keys(allToServiceRules).forEach(targetService => { if(!allToServiceMtlsModes[targetService]) { allToServiceMtlsModes[targetService] = {} } MtlsUtil.TlsModeExtractor.init(allToServiceMtlsModes[targetService]) allToServiceRules[targetService].forEach(dr => MtlsUtil.TlsModeExtractor.extractDestinationRuleTlsModes(dr)) }) Object.keys(nsToAllRules).forEach(sourceNS => { if(!nsToAllMtlsModes[sourceNS]) { nsToAllMtlsModes[sourceNS] = {} } MtlsUtil.TlsModeExtractor.init(nsToAllMtlsModes[sourceNS]) nsToAllRules[sourceNS].forEach(dr => MtlsUtil.TlsModeExtractor.extractDestinationRuleTlsModes(dr)) }) Object.keys(nsToNSRules).forEach(sourceNS => { if(!nsToNSMtlsModes[sourceNS]) { nsToNSMtlsModes[sourceNS] = {} } Object.keys(nsToNSRules[sourceNS]).forEach(targetNS => { if(!nsToNSMtlsModes[sourceNS][targetNS]) { nsToNSMtlsModes[sourceNS][targetNS] = {} } MtlsUtil.TlsModeExtractor.init(nsToNSMtlsModes[sourceNS][targetNS]) nsToNSRules[sourceNS][targetNS].forEach(dr => MtlsUtil.TlsModeExtractor.extractDestinationRuleTlsModes(dr)) }) }) Object.keys(nsToServiceRules).forEach(sourceNS => { if(!nsToServiceMtlsModes[sourceNS]) { nsToServiceMtlsModes[sourceNS] = {} } Object.keys(nsToServiceRules[sourceNS]).forEach(targetService => { if(!nsToServiceMtlsModes[sourceNS][targetService]) { nsToServiceMtlsModes[sourceNS][targetService] = {} } MtlsUtil.TlsModeExtractor.init(nsToServiceMtlsModes[sourceNS][targetService]) nsToServiceRules[sourceNS][targetService].forEach(dr => MtlsUtil.TlsModeExtractor.extractDestinationRuleTlsModes(dr)) }) }) return { allToAllMtlsModes, allToNSMtlsModes, allToServiceMtlsModes, nsToAllMtlsModes, nsToNSMtlsModes, nsToServiceMtlsModes } } static getServiceMtlsStatus = async (k8sClient: K8sClient, namespace: string, service?: ServiceDetails) => { return (await MtlsUtil.getNamespaceServiceMtlsStatuses(k8sClient, [namespace], service && [service]))[namespace] } static getServiceMtlsStatuses = async (k8sClient: K8sClient, services: ServiceDetails[]) => { const namespaces = services.map(s => s.namespace) return MtlsUtil.getNamespaceServiceMtlsStatuses(k8sClient, namespaces, services) } static getNamespaceServiceMtlsStatuses = async (k8sClient: K8sClient, namespaces: string[], services?: ServiceDetails[]) => { const globalMtlsStatus = await MtlsUtil.getGlobalMtlsStatus(k8sClient) const {namespacesWithDefaultMtls, servicesWithMtlsPolicies} = await MtlsUtil.getMtlsPolicies(k8sClient) const mtlsDestinationRules = await MtlsUtil.getMtlsDestinationRules(k8sClient) const mtlsModes = MtlsUtil.getMtlsModes(mtlsDestinationRules) let serviceMtlsStatus = {} for(const namespace of namespaces) { serviceMtlsStatus[namespace] = {} const namespaceDefaultMtlsMode = namespacesWithDefaultMtls[namespace] if(namespaceDefaultMtlsMode) { serviceMtlsStatus[namespace]["namespaceDefaultMtlsMode"] = namespaceDefaultMtlsMode } const nsServices = services ? services.filter(s => s.namespace === namespace) : (await K8sFunctions.getServicesWithDetails(namespace, k8sClient)) as ServiceDetails[] for(const service of nsServices) { const servicePoliciesMtlsStatus = MtlsUtil.getServicePoliciesMtlsStatus( service, servicesWithMtlsPolicies, namespaceDefaultMtlsMode, globalMtlsStatus) const effectiveServicePortClientMtlsModes = MtlsUtil.getClientMtlsModeForServicePorts(service, mtlsModes) const servicePortClientNamespaceMtlsConflicts = MtlsUtil.getClientMtlsConflicsForServicePorts(effectiveServicePortClientMtlsModes) const servicePortDefaultMtlsDestinationRuleStatus = MtlsUtil.getDefaultDestinationRulesMtlsStatusForServicePorts(effectiveServicePortClientMtlsModes) const applicableDestinationRules = MtlsUtil.getApplicableDestinationRules(service, mtlsDestinationRules) const podsAndContainers = await K8sFunctions.getPodsAndContainersForService(service, k8sClient) const containers = podsAndContainers.containers ? podsAndContainers.containers as any[] : [] const hasSidecar = containers.filter(c => c === "istio-proxy").length > 0 const servicePortAccess = {} service.ports.forEach(p => { const servicePortMtlsModeHasConflict = servicePoliciesMtlsStatus.effectiveServicePortMtlsModes[p.port] && servicePoliciesMtlsStatus.effectiveServicePortMtlsModes[p.port].length > 1 const servicePortMtlsEnabled = hasSidecar && servicePoliciesMtlsStatus.effectiveServicePortMtlsModes[p.port] && (servicePoliciesMtlsStatus.effectiveServicePortMtlsModes[p.port].length > 0 && servicePoliciesMtlsStatus.effectiveServicePortMtlsModes[p.port][0].length > 0 && servicePoliciesMtlsStatus.effectiveServicePortMtlsModes[p.port][0] !== ServiceMtlsMode.DISABLE) const servicePortMtlsMode = servicePortMtlsEnabled && !servicePortMtlsModeHasConflict && servicePoliciesMtlsStatus.effectiveServicePortMtlsModes[p.port][0] const servicePortMtlsPermissive = servicePortMtlsEnabled && servicePortMtlsMode === ServiceMtlsMode.PERMISSIVE const clientNamespacesWithMtlsConflicts = servicePortClientNamespaceMtlsConflicts[p.port] const effectiveClientModes = effectiveServicePortClientMtlsModes[p.port] const noDestinationRules = Object.keys(effectiveClientModes).length === 0 const mtlsAccessOnly = servicePortMtlsEnabled && !servicePortMtlsPermissive const sidecarAccessNamespaces: any[] = [] const clientNamespacesInConflictWithMtlsPolicy = {} Object.keys(effectiveClientModes).forEach(sourceNS => { if(effectiveClientModes[sourceNS].length === 1) { const sourceNSMtlsMode = effectiveClientModes[sourceNS][0].mode const sourceDR = effectiveClientModes[sourceNS][0].dr if((sourceNSMtlsMode === ClientMtlsMode.DISABLE && mtlsAccessOnly) || (sourceNSMtlsMode === ClientMtlsMode.ISTIO_MUTUAL && !servicePortMtlsEnabled)) { if(!clientNamespacesInConflictWithMtlsPolicy[sourceNS]) { clientNamespacesInConflictWithMtlsPolicy[sourceNS] = [] } clientNamespacesInConflictWithMtlsPolicy[sourceNS].push(sourceDR) } else if(sourceNSMtlsMode === ClientMtlsMode.ISTIO_MUTUAL) { sidecarAccessNamespaces.push({namespace: sourceNS, dr: sourceDR}) } } else if(effectiveClientModes[sourceNS].length === 0) { if(!servicePortMtlsEnabled || servicePortMtlsPermissive) { sidecarAccessNamespaces.push({namespace: sourceNS}) } } }) const clientHasConflicts = clientNamespacesWithMtlsConflicts.length > 0 || Object.keys(clientNamespacesInConflictWithMtlsPolicy).length > 0 const allAccess = !servicePortMtlsEnabled || servicePortMtlsPermissive const noAccess = mtlsAccessOnly && noDestinationRules const portDefaultMtlsDestinationRuleStatus = servicePortDefaultMtlsDestinationRuleStatus[p.port] const nonSidecarOnly = !servicePortMtlsEnabled && portDefaultMtlsDestinationRuleStatus && portDefaultMtlsDestinationRuleStatus.onlyDefaultMtlsDestinationRuleDefined && portDefaultMtlsDestinationRuleStatus.defaultDestinationRuleMtlsMode === ClientMtlsMode.ISTIO_MUTUAL servicePortAccess[p.port] = { service: { conflict: servicePortMtlsModeHasConflict, mtls: servicePortMtlsEnabled, permissive: servicePortMtlsPermissive, servicePortMtlsMode, }, client: { conflict: clientHasConflicts, sidecarAccessNamespaces, clientNamespacesWithMtlsConflicts, clientNamespacesInConflictWithMtlsPolicy, noDestinationRules, noAccess, allAccess, sidecarOnly: mtlsAccessOnly, nonSidecarOnly, } } }) serviceMtlsStatus[namespace][service.name] = { hasSidecar, mtlsPolicies: servicePoliciesMtlsStatus.mtlsPolicies, effectiveServicePortMtlsModes: servicePoliciesMtlsStatus.effectiveServicePortMtlsModes, mtlsDestinationRules: applicableDestinationRules, effectiveServicePortClientMtlsModes, servicePortDefaultMtlsDestinationRuleStatus, servicePortClientNamespaceMtlsConflicts, servicePortAccess } } } return serviceMtlsStatus } static getServicePoliciesMtlsStatus(service, servicesWithMtlsPolicies, namespaceDefaultMtlsMode, globalMtlsStatus) { let applicablePolicies: any[] = [] const servicePortPolicies: any[] = [] servicesWithMtlsPolicies .filter(sp => sp.serviceName === service.name && sp.namespace === service.namespace && sp.ports) .forEach(sp => { applicablePolicies.push(sp.policy) sp.ports.forEach(port => { servicePortPolicies.push({ serviceName: sp.serviceName, port: port.number || port.name, policyName: sp.policyName, namespace: sp.namespace, mode: sp.mode, }) }) }) const servicePolicies = servicesWithMtlsPolicies .filter(sp => sp.serviceName === service.name && sp.namespace === service.namespace && !sp.ports) servicePolicies.forEach(sp => applicablePolicies.push(sp.policy)) const servicePortMtlsModes = {} servicePortPolicies.forEach(sp => { if(!servicePortMtlsModes[sp.port]) { servicePortMtlsModes[sp.port] = [] } if(!servicePortMtlsModes[sp.port].includes(sp.mode)) { servicePortMtlsModes[sp.port].push(sp.mode) } }) const serviceMtlsModes: any[] = [] servicePolicies.forEach(sp => { if(!serviceMtlsModes.includes(sp.mode)) { serviceMtlsModes.push(sp.mode) } }) const effectiveServicePortMtlsModes = {} const defaultServiceMtlsMode = serviceMtlsModes.length > 0 ? serviceMtlsModes : [namespaceDefaultMtlsMode || globalMtlsStatus.globalMtlsMode] service.ports.forEach(p => { effectiveServicePortMtlsModes[p.port] = [] if(servicePortMtlsModes[p.port] && servicePortMtlsModes[p.port].length > 0) { effectiveServicePortMtlsModes[p.port] = effectiveServicePortMtlsModes[p.port].concat(servicePortMtlsModes[p.port]) } if(servicePortMtlsModes[p.name] && servicePortMtlsModes[p.name].length > 0) { effectiveServicePortMtlsModes[p.port] = effectiveServicePortMtlsModes[p.port].concat(servicePortMtlsModes[p.name]) } if(effectiveServicePortMtlsModes[p.port].length === 0) { effectiveServicePortMtlsModes[p.port] = defaultServiceMtlsMode } }) let servicePoliciesHaveConflict = serviceMtlsModes.length > 1 Object.keys(effectiveServicePortMtlsModes).forEach(port => { servicePoliciesHaveConflict = servicePoliciesHaveConflict || effectiveServicePortMtlsModes[port].length > 1 if(serviceMtlsModes.length === 1 && effectiveServicePortMtlsModes[port].length === 1) { servicePoliciesHaveConflict = servicePoliciesHaveConflict || serviceMtlsModes[0] !== effectiveServicePortMtlsModes[port][0] } }) return { servicePoliciesHaveConflict, effectiveServicePortMtlsModes, mtlsPolicies: applicablePolicies } } static getApplicableDestinationRules(service, mtlsDestinationRules) { const serviceNS = service.namespace const serviceFqdn = service.name+"."+serviceNS+".svc.cluster.local" FqdnMatcher.initWithService(service.name, serviceNS) let applicableDestinationRules : any[] = [] applicableDestinationRules = applicableDestinationRules.concat(mtlsDestinationRules.globalRules) if(mtlsDestinationRules.allToNSRules[serviceNS]) { applicableDestinationRules = applicableDestinationRules.concat( mtlsDestinationRules.allToNSRules[serviceNS]) } if(mtlsDestinationRules.allToServiceRules[serviceFqdn]) { applicableDestinationRules = applicableDestinationRules.concat( mtlsDestinationRules.allToServiceRules[serviceFqdn]) } Object.keys(mtlsDestinationRules.nsToAllRules).forEach(sourceNS => { applicableDestinationRules = applicableDestinationRules.concat( mtlsDestinationRules.nsToAllRules[sourceNS]) }) if(mtlsDestinationRules.nsToNSRules[serviceNS]) { Object.keys(mtlsDestinationRules.nsToNSRules[serviceNS]).forEach(targetNS => { applicableDestinationRules = applicableDestinationRules.concat( mtlsDestinationRules.nsToNSRules[serviceNS][targetNS]) }) } Object.keys(mtlsDestinationRules.nsToNSRules).forEach(sourceNS => { if(mtlsDestinationRules.nsToNSRules[sourceNS][serviceNS]) { applicableDestinationRules = applicableDestinationRules.concat( mtlsDestinationRules.nsToNSRules[sourceNS][serviceNS]) } }) if(mtlsDestinationRules.nsToServiceRules[serviceNS]) { Object.keys(mtlsDestinationRules.nsToServiceRules[serviceNS]).forEach(targetService => { applicableDestinationRules = applicableDestinationRules.concat( mtlsDestinationRules.nsToServiceRules[serviceNS][targetService]) }) } Object.keys(mtlsDestinationRules.nsToServiceRules).forEach(sourceNS => { if(mtlsDestinationRules.nsToServiceRules[sourceNS][serviceFqdn]) { applicableDestinationRules = applicableDestinationRules.concat( mtlsDestinationRules.nsToServiceRules[sourceNS][serviceFqdn]) } }) applicableDestinationRules = _.uniqBy(applicableDestinationRules, dr => dr.name+"."+dr.namespace) return applicableDestinationRules } static getClientMtlsModeForServicePorts(service, mtlsModes) { const serviceNS = service.namespace FqdnMatcher.initWithService(service.name, serviceNS) const effectiveServicePortClientMtlsModes = {} service.ports.forEach(p => { effectiveServicePortClientMtlsModes[p.port] = {} const sourcePortModes = new Set mtlsModes.allToAllMtlsModes[p.port] && mtlsModes.allToAllMtlsModes[p.port].forEach(data => sourcePortModes.add(data)) mtlsModes.allToAllMtlsModes[p.name] && mtlsModes.allToAllMtlsModes[p.name].forEach(data => sourcePortModes.add(data)) if(sourcePortModes.size === 0) { //specific port data not found, use default port data mtlsModes.allToAllMtlsModes[""] && mtlsModes.allToAllMtlsModes[""].forEach(data => sourcePortModes.add(data)) } if(sourcePortModes.size > 0) { effectiveServicePortClientMtlsModes[p.port][""] = Array.from(sourcePortModes.values()) } Object.keys(mtlsModes.allToNSMtlsModes).forEach(targetNS => { if(targetNS === serviceNS) { const sourcePortModes = new Set mtlsModes.allToNSMtlsModes[targetNS][p.port] && mtlsModes.allToNSMtlsModes[targetNS][p.port].forEach(data => sourcePortModes.add(data)) mtlsModes.allToNSMtlsModes[targetNS][p.name] && mtlsModes.allToNSMtlsModes[targetNS][p.name].forEach(data => sourcePortModes.add(data)) if(sourcePortModes.size === 0) { mtlsModes.allToNSMtlsModes[targetNS][""] && mtlsModes.allToNSMtlsModes[targetNS][""].forEach(data => sourcePortModes.add(data)) } if(sourcePortModes.size > 0) { effectiveServicePortClientMtlsModes[p.port][""] = Array.from(sourcePortModes.values()) } } }) Object.keys(mtlsModes.allToServiceMtlsModes).forEach(targetService => { if(FqdnMatcher.matchService(targetService)) { const sourcePortModes = new Set mtlsModes.allToServiceMtlsModes[targetService][p.port] && mtlsModes.allToServiceMtlsModes[targetService][p.port].forEach(data => sourcePortModes.add(data)) mtlsModes.allToServiceMtlsModes[targetService][p.name] && mtlsModes.allToServiceMtlsModes[targetService][p.name].forEach(data => sourcePortModes.add(data)) if(sourcePortModes.size === 0) { mtlsModes.allToServiceMtlsModes[targetService][""] && mtlsModes.allToServiceMtlsModes[targetService][""].forEach(data => sourcePortModes.add(data)) } if(sourcePortModes.size > 0) { effectiveServicePortClientMtlsModes[p.port][""] = Array.from(sourcePortModes.values()) } } }) Object.keys(mtlsModes.nsToAllMtlsModes).forEach(sourceNS => { const sourcePortModes = new Set mtlsModes.nsToAllMtlsModes[sourceNS][p.port] && mtlsModes.nsToAllMtlsModes[sourceNS][p.port].forEach(data => sourcePortModes.add(data)) mtlsModes.nsToAllMtlsModes[sourceNS][p.name] && mtlsModes.nsToAllMtlsModes[sourceNS][p.name].forEach(data => sourcePortModes.add(data)) if(sourcePortModes.size === 0) { mtlsModes.nsToAllMtlsModes[sourceNS][""] && mtlsModes.nsToAllMtlsModes[sourceNS][""].forEach(data => sourcePortModes.add(data)) } if(sourcePortModes.size > 0) { effectiveServicePortClientMtlsModes[p.port][sourceNS] = Array.from(sourcePortModes.values()) } }) Object.keys(mtlsModes.nsToNSMtlsModes).forEach(sourceNS => { Object.keys(mtlsModes.nsToNSMtlsModes[sourceNS]).forEach(targetNS => { if(targetNS === serviceNS) { const sourcePortModes = new Set mtlsModes.nsToNSMtlsModes[sourceNS][targetNS][p.port] && mtlsModes.nsToNSMtlsModes[sourceNS][targetNS][p.port].forEach(data => sourcePortModes.add(data)) mtlsModes.nsToNSMtlsModes[sourceNS][targetNS][p.name] && mtlsModes.nsToNSMtlsModes[sourceNS][targetNS][p.name].forEach(data => sourcePortModes.add(data)) if(sourcePortModes.size === 0) { mtlsModes.nsToNSMtlsModes[sourceNS][targetNS][""] && mtlsModes.nsToNSMtlsModes[sourceNS][targetNS][""].forEach(data => sourcePortModes.add(data)) } if(sourcePortModes.size > 0) { effectiveServicePortClientMtlsModes[p.port][sourceNS] = Array.from(sourcePortModes.values()) } } }) }) Object.keys(mtlsModes.nsToServiceMtlsModes).forEach(sourceNS => { Object.keys(mtlsModes.nsToServiceMtlsModes[sourceNS]).forEach(targetService => { if(FqdnMatcher.matchService(targetService)) { const sourcePortModes = new Set mtlsModes.nsToServiceMtlsModes[sourceNS][targetService][p.port] && mtlsModes.nsToServiceMtlsModes[sourceNS][targetService][p.port].forEach(data => sourcePortModes.add(data)) mtlsModes.nsToServiceMtlsModes[sourceNS][targetService][p.name] && mtlsModes.nsToServiceMtlsModes[sourceNS][targetService][p.name].forEach(data => sourcePortModes.add(data)) if(sourcePortModes.size === 0) { mtlsModes.nsToServiceMtlsModes[sourceNS][targetService][""] && mtlsModes.nsToServiceMtlsModes[sourceNS][targetService][""].forEach(data => sourcePortModes.add(data)) } if(sourcePortModes.size > 0) { effectiveServicePortClientMtlsModes[p.port][sourceNS] = Array.from(sourcePortModes.values()) } } }) }) }) return effectiveServicePortClientMtlsModes } static getClientMtlsConflicsForServicePorts(effectiveServicePortClientMtlsModes) { const servicePortClientNamespaceMtlsConflicts = {} Object.keys(effectiveServicePortClientMtlsModes).forEach(port => { servicePortClientNamespaceMtlsConflicts[port] = [] const portSourceNamespaces = Object.keys(effectiveServicePortClientMtlsModes[port]) portSourceNamespaces.forEach(sourceNS => { effectiveServicePortClientMtlsModes[port][sourceNS].length > 1 && servicePortClientNamespaceMtlsConflicts[port].push(sourceNS) }) }) return servicePortClientNamespaceMtlsConflicts } static getDefaultDestinationRulesMtlsStatusForServicePorts(effectiveServicePortClientMtlsModes) { const servicePortDefaultMtlsDestinationRuleStatus = {} Object.keys(effectiveServicePortClientMtlsModes).forEach(port => { const portSourceNamespaces = Object.keys(effectiveServicePortClientMtlsModes[port]) servicePortDefaultMtlsDestinationRuleStatus[port] = {} servicePortDefaultMtlsDestinationRuleStatus[port].defaultMtlsDestinationRuleDefined = effectiveServicePortClientMtlsModes[port][""] && effectiveServicePortClientMtlsModes[port][""].length > 0 servicePortDefaultMtlsDestinationRuleStatus[port].defaultDestinationRuleMtlsMode = effectiveServicePortClientMtlsModes[port][""] && effectiveServicePortClientMtlsModes[port][""].length === 1 ? effectiveServicePortClientMtlsModes[port][""][0] : undefined servicePortDefaultMtlsDestinationRuleStatus[port].onlyDefaultMtlsDestinationRuleDefined = servicePortDefaultMtlsDestinationRuleStatus[port].defaultMtlsDestinationRuleDefined && portSourceNamespaces.length === 1 }) return servicePortDefaultMtlsDestinationRuleStatus } }
the_stack
import type { DataItem } from "../../../core/render/Component"; import type { AxisRenderer } from "./AxisRenderer"; import { Axis, IAxisSettings, IAxisPrivate, IAxisDataItem, IAxisEvents } from "./Axis"; import type { IXYSeriesDataItem, XYSeries } from "../series/XYSeries"; import * as $array from "../../../core/util/Array"; import * as $type from "../../../core/util/Type"; import * as $math from "../../../core/util/Math"; import * as $utils from "../../../core/util/Utils"; import { populateString } from "../../../core/util/PopulateString"; import type { Tooltip } from "../../../core/render/Tooltip"; export interface ICategoryAxisSettings<R extends AxisRenderer> extends IAxisSettings<R> { /** * A function that can be used to specify how to configure axis fills. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/axes/#Axis_fills} for more info */ fillRule?: (dataItem: DataItem<ICategoryAxisDataItem>, index?: number) => void; /** * A field in data which holds categories. */ categoryField: string; /** * Relative location of where axis cell starts: 0 - beginning, 1 - end. * * @default 0 */ startLocation?: number; /** * Relative location of where axis cell ends: 0 - beginning, 1 - end. * * @default 1 */ endLocation?: number; } export interface ICategoryAxisDataItem extends IAxisDataItem { /** * Named category. */ category?: string; /** * Named end category (for axis items that span multiple categories, like * axis ranges). */ endCategory?: string; /** * Index of the data item. */ index?: number; /** * Relative location of the category within cell: 0 - start, 1 - end. */ categoryLocation?: number; /** * Relative location of the end category within cell: 0 - start, 1 - end. */ endCategoryLocation?: number; /** * A distance to shift data item relative to its original position. * * The value is 0 to 1, where 1 is full witdth of the axis. * * Can be used to sort data items without modifying order of the actual data. */ deltaPosition?: number; } export interface ICategoryAxisPrivate extends IAxisPrivate { /** * Start index of the current zoom scope. */ startIndex?: number; /** * End index of the current zoom scope. */ endIndex?: number; } export interface ICategoryAxisEvents extends IAxisEvents { } /** * Creates a category axis. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/axes/category-axis/} for more info * @important */ export class CategoryAxis<R extends AxisRenderer> extends Axis<R> { public static className: string = "CategoryAxis"; public static classNames: Array<string> = Axis.classNames.concat([CategoryAxis.className]); declare public _settings: ICategoryAxisSettings<R>; declare public _privateSettings: ICategoryAxisPrivate; declare public _dataItemSettings: ICategoryAxisDataItem; declare public _events: ICategoryAxisEvents; protected _frequency: number = 1; protected _itemMap: { [index: string]: DataItem<ICategoryAxisDataItem> } = {}; protected _afterNew() { this._settings.themeTags = $utils.mergeTags(this._settings.themeTags, ["axis"]); this.fields.push("category"); this.setPrivateRaw("name", "category"); this.addTag("category"); super._afterNew(); } public _prepareChildren() { super._prepareChildren(); const len = this.dataItems.length; let i = 0; if (this._valuesDirty) { $array.each(this.dataItems, (dataItem) => { dataItem.setRaw("index", i); this._itemMap[dataItem.get("category") as string] = dataItem; i++; }) this.setPrivateRaw("maxZoomFactor", len); } this.setPrivateRaw("startIndex", Math.max(Math.round(this.get("start", 0) * len), 0)); this.setPrivateRaw("endIndex", Math.min(Math.round(this.get("end", 1) * len), len)); if (this._sizeDirty || this._valuesDirty || (this.isDirty("start") || this.isDirty("end") || this.isPrivateDirty("endIndex") || this.isPrivateDirty("startIndex") || this.isPrivateDirty("width") || this.isPrivateDirty("height"))) { if (this.dataItems.length > 0) { this._handleRangeChange(); this._prepareAxisItems(); this._updateAxisRanges(); } } } protected _handleRangeChange() { $array.each(this.series, (series) => { let startCategory = this.dataItems[this.startIndex()].get("category"); let endCategory = this.dataItems[this.endIndex() - 1].get("category"); let baseAxis = series.get("baseAxis"); let xAxis = series.get("xAxis"); let yAxis = series.get("yAxis"); if (xAxis instanceof CategoryAxis && yAxis instanceof CategoryAxis) { series._markDirtyAxes(); } else if (baseAxis === this) { let key: string | undefined; let openKey: string | undefined; let otherAxis = yAxis; if (xAxis === baseAxis) { if (series.get("categoryXField")) { key = "categoryX"; } if (series.get("openCategoryXField")) { openKey = "openCategoryX"; } } else if (yAxis === baseAxis) { if (series.get("categoryYField")) { key = "categoryY"; } if (series.get("openCategoryYField")) { openKey = "openCategoryY"; } otherAxis = xAxis; } if (otherAxis.className == "ValueAxis") { if (key || openKey) { let startDataItem: DataItem<IXYSeriesDataItem> | undefined; let endDataItem: DataItem<IXYSeriesDataItem> | undefined; for (let i = 0, len = series.dataItems.length; i < len; i++) { let dataItem = series.dataItems[i]; if (key) { if (dataItem.get(key as any) === startCategory) { startDataItem = dataItem; break; } } if (openKey) { if (dataItem.get(openKey as any) === startCategory) { startDataItem = dataItem; break; } } } for (let i = series.dataItems.length - 1; i >= 0; i--) { let dataItem = series.dataItems[i]; if (key) { if (dataItem.get(key as any) === endCategory) { endDataItem = dataItem; break; } } if (openKey) { if (dataItem.get(openKey as any) === endCategory) { endDataItem = dataItem; break; } } } if (startDataItem) { series.setPrivate("startIndex", series.dataItems.indexOf(startDataItem)); } if (endDataItem) { series.setPrivate("endIndex", series.dataItems.indexOf(endDataItem) + 1); } } } series._markDirtyAxes(); // must be outside } }) } protected _prepareAxisItems() { const renderer = this.get("renderer"); const len = this.dataItems.length; let startIndex = this.startIndex(); if (startIndex > 0) { startIndex--; } let endIndex = this.endIndex(); if (endIndex < len) { endIndex++; } let maxCount = renderer.axisLength() / Math.max(renderer.get("minGridDistance")!, 1 / Number.MAX_SAFE_INTEGER); let frequency = Math.max(1, Math.min(len, Math.ceil((endIndex - startIndex) / maxCount))); startIndex = Math.floor(startIndex / frequency) * frequency; this._frequency = frequency; for (let j = 0; j < len; j++) { this.dataItems[j].hide(); } let f = this.dataItems[startIndex].get("index", 0); for (let i = startIndex; i < endIndex; i = i + frequency) { let dataItem = this.dataItems[i]; this._createAssets(dataItem, []); if (dataItem.isHidden()) { dataItem.show(); } this._prepareDataItem(dataItem, f, frequency); f++; } this._updateGhost(); } public _prepareDataItem(dataItem: DataItem<this["_dataItemSettings"]>, fillIndex?: number, count?: number) { let renderer = this.get("renderer"); let categoryLocation = dataItem.get("categoryLocation", 0); let endCategoryLocation = dataItem.get("endCategoryLocation", 1); let index: number | undefined = dataItem.get("index"); if (!$type.isNumber(index)) { index = this.categoryToIndex(dataItem.get("category")!); } let position = this.indexToPosition(index, categoryLocation); let endCategory = dataItem.get("endCategory")!; let endIndex: number; if (endCategory) { endIndex = this.categoryToIndex(endCategory); if (!$type.isNumber(endIndex)) { endIndex = index; } } else { endIndex = index; } let endPosition = this.indexToPosition(endIndex, endCategoryLocation); let fillEndIndex: number; let fillEndPosition: number; if (dataItem.get("isRange")) { fillEndIndex = endIndex; } else { fillEndIndex = index + this._frequency - 1; } fillEndPosition = this.indexToPosition(fillEndIndex, endCategoryLocation); renderer.updateLabel(dataItem.get("label"), position, endPosition, count); renderer.updateGrid(dataItem.get("grid"), position, endPosition); renderer.updateTick(dataItem.get("tick"), position, endPosition, count); renderer.updateFill(dataItem.get("axisFill"), position, fillEndPosition); this._processBullet(dataItem); renderer.updateBullet(dataItem.get("bullet"), position, endPosition); const fillRule = this.get("fillRule"); if (fillRule) { fillRule(dataItem, fillIndex) } } public startIndex() { let len = this.dataItems.length; return Math.min(Math.max(this.getPrivate("startIndex", 0), 0), len - 1); } public endIndex() { let len = this.dataItems.length; return Math.max(1, Math.min(this.getPrivate("endIndex", len), len)); } /** * @ignore */ public baseValue(): any { } /** * @ignore */ public basePosition() { return 0; } /** * Returns X coordinate in pixels corresponding to specific category index. * * @param value Index * @return X coordinate */ public getX(value: string): number { let axisDataItem = this._itemMap[value]; if (axisDataItem) { return this._settings.renderer.positionToCoordinate(this.indexToPosition(axisDataItem.get("index", 0))); } return NaN; } /** * Returns Y coordinate in pixels corresponding to specific category index. * * @param value Index * @return Y coordinate */ public getY(value: string): number { let axisDataItem = this._itemMap[value]; if (axisDataItem) { return this._settings.renderer.positionToCoordinate(this.indexToPosition(axisDataItem.get("index", 0))); } return NaN; } /** * @ignore */ public getDataItemPositionX(dataItem: DataItem<IXYSeriesDataItem>, field: string, cellLocation: number, _axisLocation?: number): number { const category = dataItem.get(field as any); const axisDataItem = this._itemMap[category]; if (axisDataItem) { return this.indexToPosition(axisDataItem.get("index", 0), cellLocation); } return NaN; } /** * @ignore */ public getDataItemCoordinateX(dataItem: DataItem<IXYSeriesDataItem>, field: string, cellLocation: number, _axisLocation?: number): number { return this._settings.renderer.positionToCoordinate(this.getDataItemPositionX(dataItem, field, cellLocation, _axisLocation)); } /** * @ignore */ public getDataItemPositionY(dataItem: DataItem<IXYSeriesDataItem>, field: string, cellLocation: number, _axisLocation?: number): number { const category = dataItem.get(field as any); const axisDataItem = this._itemMap[category]; if (axisDataItem) { return this.indexToPosition(axisDataItem.get("index", 0), cellLocation); } return NaN; } /** * @ignore */ public getDataItemCoordinateY(dataItem: DataItem<IXYSeriesDataItem>, field: string, cellLocation: number, _axisLocation?: number): number { return this._settings.renderer.positionToCoordinate(this.getDataItemPositionY(dataItem, field, cellLocation, _axisLocation)); } /** * Converts category index to a relative position. * * `location` indicates relative position within category: 0 - start, 1 - end. * * If not set, will use middle (0.5) of the category. * * @param index Index * @param location Location * @return Index */ public indexToPosition(index: number, location?: number): number { if (!$type.isNumber(location)) { location = 0.5; } let len = this.dataItems.length; let startLocation = this.get("startLocation", 0); let endLocation = this.get("endLocation", 1); len -= startLocation; len -= (1 - endLocation); let position = (index + location - startLocation) / len; let dataItem = this.dataItems[index]; if (dataItem) { position += dataItem.get("deltaPosition", 0); } return position; } /** * Returns an index of a category. * * @param category Category to look up * @return Index */ public categoryToIndex(category: string): number { let dataItem = this._itemMap[category]; if (dataItem) { return dataItem.get("index")!; } return NaN; } /** * @ignore */ public dataItemToPosition(dataItem: DataItem<this["_dataItemSettings"]>): number { return this.indexToPosition(dataItem.get("index")!); } /** * @ignore */ public roundAxisPosition(position: number, location: number): number { return this.indexToPosition(this.axisPositionToIndex(position), location); } /** * Returns an index of the category that corresponds to specific pixel * position within axis. * * @param position Position (px) * @return Category index */ public axisPositionToIndex(position: number): number { let len = this.dataItems.length; return $math.fitToRange(Math.floor(position * len), 0, len - 1);//$math.fitToRange(Math.floor((end - start) * len * position + len * start), 0, len - 1); } /** * Returns text to be used in an axis tooltip for specific relative position. * * @param position Position * @return Tooltip text */ public getTooltipText(position: number): string | undefined { //@todo number formatter + tag const dataItem = this.dataItems[this.axisPositionToIndex(position)]; if (dataItem) { const label = dataItem.get("label") if(label){ return populateString(label, this.get("tooltipText", "")); } } } protected _updateTooltipText(tooltip: Tooltip, position: number) { tooltip._setDataItem(this.dataItems[this.axisPositionToIndex(position)]); tooltip.label.text.markDirtyText(); } /** * Returns a data item from series that is closest to the `position`. * * @param series Series * @param position Relative position * @return Data item */ public getSeriesItem(series: XYSeries, position: number): DataItem<IXYSeriesDataItem> | undefined { if (this.dataItems.length > 0) { let fieldName = <any>(this.getPrivate("name")! + this.get("renderer").getPrivate("letter")!); let index = this.axisPositionToIndex(position); // try simple first let seriesDataItem = series.dataItems[index]; let axisDataItem = this.dataItems[index]; let category = axisDataItem.get("category"); if (seriesDataItem && axisDataItem) { if (seriesDataItem.get(fieldName) === category) { return seriesDataItem; } } // if not found, try looking for (let i = 0, len = series.dataItems.length; i < len; i++) { let dataItem = series.dataItems[i]; if (dataItem.get(fieldName) === category) { return dataItem; } } } } /** * Zooms the axis to specific `start` and `end` indexes. * * Optional `duration` specifies duration of zoom animation in milliseconds. * * @param start Start index * @param end End index * @param duration Duration in milliseconds */ public zoomToIndexes(start: number, end: number, duration?: number) { let len = this.dataItems.length; this.zoom(start / len, end / len, duration); } public zoomToCategories(startCategory: string, endCategory: string, duration?: number) { this.zoomToIndexes(this.categoryToIndex(startCategory), this.categoryToIndex(endCategory) + 1, duration); } }
the_stack
import { assert } from 'chai' import path from 'path' import { spawn } from 'child_process' import del from 'del' import fs from 'fs-extra' import { MOCHAPACK_NAME } from '../../../src/util/constants' const fixtureDir = path.join(process.cwd(), '.tmp/fixture') const deleteTest = fileName => del(path.join(fixtureDir, fileName)) const createTest = (fileName, testName, passing) => { const content = ` var assert = require('assert'); describe('${fileName} - ${testName}', function () { it('runs test', function () { assert.ok(${passing}); }); }); ` fs.outputFileSync(path.join(fixtureDir, fileName), content) } function createSyntaxErrorTest(fileName, testName) { const content = ` var assert = require('assert'); describe('${fileName} - ${testName}', function () { it('runs test', function () { assert.ok(false); }); ` fs.outputFileSync(path.join(fixtureDir, fileName), content) } function createUncaughtErrorTest(fileName, testName) { const content = ` describe('${fileName} - ${testName}', function () { it('runs test', function () { setTimeout(function () { done(); // done is undefined -> uncaught error }, 1000); }); }); ` fs.outputFileSync(path.join(fixtureDir, fileName), content) } function createErrorFile(fileName, testName) { const content = ` throw new Error('Error ${fileName} ${testName}'); ` fs.outputFileSync(path.join(fixtureDir, fileName), content) } const createLongRunningTest = (fileName, testName) => { const content = ` var assert = require('assert'); describe('${fileName} - ${testName} - 1', function () { it('runs test 1' , function (done) { this.timeout(3000); console.log('starting ${testName} - 1'); setTimeout(function() { console.log('finished ${testName} - 1'); done(); }, 2000); }); }); describe('${fileName} - ${testName}', function () { it('runs test 2' , function (done) { this.timeout(3000); console.log('starting ${testName} - 2'); setTimeout(function() { console.log('finished ${testName} - 2'); done(); }, 2000); }); }); ` fs.outputFileSync(path.join(fixtureDir, fileName), content) } const createNeverEndingTest = (fileName, testName) => { const content = ` var assert = require('assert'); describe('${fileName} - ${testName} - 1', function () { it('runs test 1' , function (done) { console.log('starting ${testName}'); }); }); ` fs.outputFileSync(path.join(fixtureDir, fileName), content) } const waitFor = (condition, timeoutInMs) => new Promise((resolve, reject) => { const startTime = Date.now() const endTime = startTime + timeoutInMs const remainingTime = () => Math.max(endTime - Date.now(), 0) const timeoutDelay = () => Math.min(remainingTime(), 500) const run = () => { let result = false let error = null try { result = condition() } catch (e) { error = e result = false } if (result !== false && error === null) { resolve() } else if (remainingTime() > 0) { setTimeout(run, timeoutDelay()) } else if (error != null) { reject(error) } else { reject( new Error(`Condition not met within time: ${condition.toString()}`) ) } } setTimeout(run, timeoutDelay()) }) const spawnMochapack = (...args) => { let data = '' const binPath = path.relative(process.cwd(), path.join('bin', MOCHAPACK_NAME)) const child = spawn('node', [binPath, '--mode', 'development', ...args]) const receiveData = d => { data += d.toString() } child.stdout.on('data', receiveData) child.stderr.on('data', receiveData) return { get log() { return data }, clearLog() { data = '' }, kill() { child.stdout.removeListener('data', receiveData) child.stderr.removeListener('data', receiveData) child.kill() } } } // eslint-disable-next-line // FIXME These tests have proven unreliable in the past and are thus disabled xdescribe('cli --watch', function() { // Retry all tests in this suite up to 4 times this.retries(4) beforeEach(function() { this.testGlob = path.join(fixtureDir, '*.js') this.entryGlob = path.relative(process.cwd(), this.testGlob) }) it('should log syntax error and wait until that is fixed before running tests', function() { this.timeout(10000) const testFile = 'test1.js' const testId = Date.now() createSyntaxErrorTest(testFile, testId) const mw = spawnMochapack('--watch', this.entryGlob) return Promise.resolve() // wait until the output matches our condition .then(() => waitFor(() => assert.include(mw.log, 'Unexpected token'), 5000) ) // output matched our condition .then(() => { assert.notInclude(mw.log, testId) assert.notInclude(mw.log, 'failing') assert.notInclude(mw.log, 'passing') // clear log to receive only changes mw.clearLog() // fix test const updatedTestId = testId + 100 createTest(testFile, updatedTestId, true) return updatedTestId }) // wait until the output matches our condition .then(updatedTestId => waitFor( () => assert.include(mw.log, updatedTestId) && assert.include(mw.log, '1 passing'), 5000 ) ) // output matched our condition .then(() => { // check if test was updated assert.notInclude(mw.log, testId) }) .catch(e => e) .then(e => { // finally, kill watch process mw.kill() // maybe rethrow error assert.ifError(e) }) }) it('should catch other errors outside of tests', function() { this.timeout(10000) const testFile = 'test1.js' const testId = Date.now() createErrorFile(testFile, testId) const mw = spawnMochapack('--watch', this.entryGlob) return Promise.resolve() // wait until the output matches our condition .then(() => waitFor(() => assert.include(mw.log, `Error ${testFile}`), 5000) ) // output matched our condition .then(() => { assert.include(mw.log, 'Exception occurred while loading your tests') assert.include(mw.log, testId) // clear log to receive only changes mw.clearLog() // fix test const updatedTestId = testId + 100 createTest(testFile, updatedTestId, true) return updatedTestId }) // wait until the output matches our condition .then(updatedTestId => waitFor( () => assert.include(mw.log, updatedTestId) && assert.include(mw.log, '1 passing'), 5000 ) ) // output matched our condition .then(() => { // check if test was updated assert.notInclude(mw.log, testId) }) .catch(e => e) .then(e => { // finally, kill watch process mw.kill() // maybe rethrow error assert.ifError(e) }) }) it('should catch uncaught errors that occur after tests are done', function() { this.timeout(10000) const testFile = 'test1.js' const testId = Date.now() createUncaughtErrorTest(testFile, testId) const mw = spawnMochapack('--watch', this.entryGlob) return Promise.resolve() // wait until the output matches our condition .then(() => waitFor(() => assert.include(mw.log, 'UNCAUGHT EXCEPTION'), 5000) ) // output matched our condition .then(() => { assert.include(mw.log, 'Exception occurred after running tests') assert.include(mw.log, '1 passing') assert.include(mw.log, testFile) assert.include(mw.log, testId) // clear log to receive only changes mw.clearLog() // fix test const updatedTestId = testId + 100 createTest(testFile, updatedTestId, true) return updatedTestId }) // wait until the output matches our condition .then(updatedTestId => waitFor( () => assert.include(mw.log, updatedTestId) && assert.include(mw.log, '1 passing'), 5000 ) ) // output matched our condition .then(() => { // check if test was updated assert.notInclude(mw.log, testId) }) .catch(e => e) .then(e => { // finally, kill watch process mw.kill() // maybe rethrow error assert.ifError(e) }) }) it('should run a test', function() { this.timeout(5000) const testFile = 'test1.js' const testId = Date.now() createTest(testFile, testId, true) const mw = spawnMochapack('--watch', this.entryGlob) return Promise.resolve() // wait until the output matches our condition .then(() => waitFor( () => assert.include(mw.log, testId) && assert.include(mw.log, '1 passing'), 5000 ) ) .catch(e => e) .then(e => { // finally, kill watch process mw.kill() // maybe rethrow error assert.ifError(e) }) }) it('should run a test again when it changes', function() { this.timeout(15000) const testFile = 'test1.js' const testId = Date.now() createTest(testFile, testId, true) const mw = spawnMochapack('--watch', this.entryGlob) return Promise.resolve() // wait until the output matches our condition .then(() => waitFor( () => assert.include(mw.log, testId) && assert.include(mw.log, '1 passing'), 5000 ) ) // output matched our condition .then(() => { // clear log to receive only changes mw.clearLog() // update test const updatedTestId = testId + 100 createTest(testFile, updatedTestId, true) return updatedTestId }) // wait until the output matches our condition .then(updatedTestId => waitFor( () => assert.include(mw.log, updatedTestId) && assert.include(mw.log, '1 passing'), 5000 ) ) // output matched our condition .then(() => { // check if test was updated assert.notInclude(mw.log, testId) }) .catch(e => e) .then(e => { // finally, kill watch process mw.kill() // maybe rethrow error assert.ifError(e) }) }) it('should run only the changed test again when it changes', function() { this.timeout(15000) const testFile1 = 'test1.js' const testFile2 = 'test2.js' const testId1 = Date.now() + 1 const testId2 = testId1 + 2 createTest(testFile1, testId1, true) createTest(testFile2, testId2, true) const mw = spawnMochapack('--watch', this.entryGlob) return Promise.resolve() // wait until the output matches our condition .then(() => waitFor(() => assert.include(mw.log, '2 passing'), 5000)) // output matched our condition .then(() => { // check if both tests were tested assert.include(mw.log, testId1) assert.include(mw.log, testFile1) assert.include(mw.log, testId2) assert.include(mw.log, testFile2) // clear log to receive only changes mw.clearLog() // update test const updatedTestId = testId2 + 100 createTest(testFile2, updatedTestId, true) return updatedTestId }) // wait until the output matches our condition .then(updatedTestId => waitFor( () => assert.include(mw.log, updatedTestId) && assert.include(mw.log, '1 passing'), 5000 ) ) // output matched our condition .then(() => { // check if just updated test was tested again assert.notInclude(mw.log, testFile1) assert.notInclude(mw.log, testId1) }) .catch(e => e) .then(e => { // finally, kill watch process mw.kill() // maybe rethrow error assert.ifError(e) }) }) it('should abort test suite when a file changes while running tests and then test again', function() { this.timeout(15000) const testFile = 'test1.js' const testId = Date.now() const updatedTestId = testId + 100 createLongRunningTest(testFile, testId) const mw = spawnMochapack('--watch', this.entryGlob) return Promise.resolve() // wait until the first async test start .then(() => waitFor(() => assert.include(mw.log, `starting ${testId} - 1`), 5000) ) .then(() => { // check if tests were not ready yet assert.notInclude(mw.log, `starting ${testId} - 2`) assert.notInclude(mw.log, `finished ${testId} - 2`) // clear log to receive only changes mw.clearLog() // update test createTest(testFile, updatedTestId, true) }) // wait until tests were aborted .then(() => waitFor(() => assert.include(mw.log, '0 passing'), 5000)) .then(() => { // check if tests were aborted assert.notInclude(mw.log, `finished ${testId} - 2`) }) // wait until tests were tested again .then(() => waitFor( () => assert.include(mw.log, updatedTestId) && assert.include(mw.log, '1 passing'), 5000 ) ) .catch(e => e) .then(e => { // finally, kill watch process mw.kill() // maybe rethrow error assert.ifError(e) }) }) it('should also abort tests that will never finish (e.g. by mistake) when timeouts are disabled and run tests again', function() { this.timeout(15000) const testFile = 'test1.js' const testId = Date.now() const updatedTestId = testId + 100 createNeverEndingTest(testFile, testId) const mw = spawnMochapack('--timeout', 0, '--watch', this.entryGlob) return Promise.resolve() // wait until the first async test start .then(() => waitFor(() => assert.include(mw.log, `starting ${testId}`), 5000) ) .then(() => { // clear log to receive only changes mw.clearLog() // update test createTest(testFile, updatedTestId, true) }) // wait until tests were aborted .then(() => waitFor(() => assert.include(mw.log, 'Tests aborted'), 5000)) .then(() => { // check if tests were aborted assert.notInclude(mw.log, `finished ${testId} - 2`) }) // wait until tests were tested again .then(() => waitFor( () => assert.include(mw.log, updatedTestId) && assert.include(mw.log, '1 passing'), 5000 ) ) .catch(e => e) .then(e => { // finally, kill watch process mw.kill() // maybe rethrow error assert.ifError(e) }) }) it('should recognize new test entries that match the pattern', function() { this.timeout(10000) const testFile1 = 'test1.js' const testId1 = Date.now() + 1 const testFile2 = 'test2.js' const testId2 = testId1 + 2 createTest(testFile1, testId1, true) const mw = spawnMochapack('--watch', this.entryGlob) return Promise.resolve() // wait until the output matches our condition .then(() => waitFor( () => assert.include(mw.log, testId1) && assert.include(mw.log, '1 passing'), 5000 ) ) // output matched our condition .then(() => { // clear log to receive only changes mw.clearLog() // create new test createTest(testFile2, testId2, true) }) // wait until the output matches our condition .then(() => waitFor( () => assert.include(mw.log, testId2) && assert.include(mw.log, '1 passing'), 5000 ) ) .then(() => { assert.notInclude(mw.log, testId1) assert.notInclude(mw.log, testFile1) }) // output matched our condition .catch(e => e) .then(e => { // finally, kill watch process mw.kill() // maybe rethrow error assert.ifError(e) }) }) it('should recognize multiple new test entries that match the pattern', function() { this.timeout(10000) const testFile1 = 'test1.js' const testId1 = Date.now() + 1 const testFile2 = 'test2.js' const testId2 = testId1 + 2 const testFile3 = 'test3.js' const testId3 = testId2 + 3 createTest(testFile1, testId1, true) const mw = spawnMochapack('--watch', this.entryGlob) return Promise.resolve() // wait until the output matches our condition .then(() => waitFor(() => assert.include(mw.log, '1 passing'), 5000)) // output matched our condition .then(() => { assert.include(mw.log, testId1) assert.include(mw.log, testFile1) // clear log to receive only changes mw.clearLog() // create new tests createTest(testFile2, testId2, true) createTest(testFile3, testId3, true) }) // wait until the output matches our condition .then(() => waitFor( () => assert.include(mw.log, testId2) && assert.include(mw.log, testId3) && assert.include(mw.log, '2 passing'), 5000 ) ) .then(() => { assert.notInclude(mw.log, testId1) assert.notInclude(mw.log, testFile1) }) // output matched our condition .catch(e => e) .then(e => { // finally, kill watch process mw.kill() // maybe rethrow error assert.ifError(e) }) }) it('should recognize deleted test entries that match the pattern', function() { this.timeout(10000) const testFile1 = 'test1.js' const testFile2 = 'test2.js' const testId1 = Date.now() + 1 const testId2 = Date.now() + 2 createTest(testFile1, testId1, true) createTest(testFile2, testId2, true) const mw = spawnMochapack('--watch', this.entryGlob) return Promise.resolve() // wait until the output matches our condition .then(() => waitFor(() => assert.include(mw.log, '2 passing'), 5000)) // output matched our condition .then(() => { assert.include(mw.log, testId1) assert.include(mw.log, testFile1) assert.include(mw.log, testId2) assert.include(mw.log, testFile2) // clear log to receive only changes mw.clearLog() // delete test deleteTest(testFile2) }) // wait until the output matches our condition .then(() => waitFor(() => assert.include(mw.log, 'passing'), 5000)) .then(() => { assert.notInclude(mw.log, testId2) }) .catch(e => e) .then(e => { // finally, kill watch process mw.kill() // maybe rethrow error assert.ifError(e) }) }) afterEach(function() { return del(this.testGlob) }) })
the_stack
// The MIT License (MIT) // // vs-deploy (https://github.com/mkloubert/vs-deploy) // Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER const CoffeeScript = require('coffeescript'); import * as deploy_contracts from './contracts'; import * as deploy_globals from './globals'; import * as deploy_helpers from './helpers'; import * as deploy_workspace from './workspace'; import * as FS from 'fs'; const Glob = require('glob'); import * as HtmlMinifier from 'html-minifier'; import * as i18 from './i18'; const LESS = require('less'); import * as Path from 'path'; const Pug = require('pug'); const TypeScript = require('typescript'); import * as UglifyJS from 'uglify-js'; import * as vscode from 'vscode'; import * as Workflows from 'node-workflows'; /** * A CoffeeScript compiler error entry. */ export interface CoffeeScriptCompilerError extends CompilerError { } /** * CoffeeScript compiler options. */ export interface CoffeeScriptCompilerOptions extends TextCompilerOptions { /** * The custom file extension for the output files to use. */ extension?: string; /** * Generate source map files or not. */ sourceMap?: boolean; } /** * A CoffeeScript compiler result. */ export interface CoffeeScriptCompilerResult extends CompilerResult { /** @inheritdoc */ errors: CoffeeScriptCompilerError[]; } /** * List of known compilers. */ export enum Compiler { /** * Less */ Less = 0, /** * TypeScript */ TypeScript = 1, /** * Script based compiler */ Script = 2, /** * UglifyJS */ UglifyJS = 3, /** * Pug */ Pug = 4, /** * Html Minifier */ HtmlMinifier = 5, /** * CoffeeScript */ CoffeeScript = 6, } /** * A compiler error entry. */ export interface CompilerError { /** * The error. */ error: any; /** * The file. */ file: string; } /** * Compiler options. */ export interface CompilerOptions { /** * Files to exclude. */ exclude?: string | string[]; /** * Files to compile. */ files?: string | string[]; } /** * A compiler result. */ export interface CompilerResult { /** * The list of errors. */ errors: CompilerError[]; /** * The files for the compilation. */ files: string[]; } /** * A Html Minifier compiler error entry. */ export interface HtmlMinifierCompilerError extends CompilerError { } /** * Html Minifier compiler options. */ export interface HtmlMinifierCompilerOptions extends TextCompilerOptions { /** * Delete the source file(s) on success or not. */ deleteSources?: boolean; /** * The extension to use for the output files. */ extension?: string; } /** * A Html Minifier compiler result. */ export interface HtmlMinifierCompilerResult extends CompilerResult { /** @inheritdoc */ errors: HtmlMinifierCompilerError[]; } /** * A LESS compiler error entry. */ export interface LessCompilerError extends CompilerError { } /** * LESS compiler options. */ export interface LessCompilerOptions extends TextCompilerOptions { /** * Compress output or not. */ compress?: boolean; /** * The custom file extension for the output files to use. */ extension?: string; /** * Search paths for @import directives. */ paths?: string | string[]; } /** * A LESS compiler result. */ export interface LessCompilerResult extends CompilerResult { /** @inheritdoc */ errors: LessCompilerError[]; } /** * A Pug compiler error entry. */ export interface PugCompilerError extends CompilerError { } /** * Pug compiler options. */ export interface PugCompilerOptions extends TextCompilerOptions { /** * When (false) no debug instrumentation is compiled. */ compileDebug?: boolean; /** * The extension to use for the output files. */ extension?: string; /** * Add pretty-indentation whitespace to output. */ pretty?: boolean; } /** * A Pug compiler result. */ export interface PugCompilerResult extends CompilerResult { } /** * A compiler. * * @param {ScriptCompilerArguments} args Arguments for the compilation. * * @returns {ScriptCompilerResult|Promise<ScriptCompilerResult>} The result. */ export type ScriptCompiler = (args: ScriptCompilerArguments) => void | ScriptCompilerResult | Promise<ScriptCompilerResult>; /** * Arguments for the compilation. */ export interface ScriptCompilerArguments extends deploy_contracts.ScriptArguments, deploy_contracts.FileDeployer { /** * The list of files to compile. */ files: string[]; /** * The compiler options. */ options: ScriptCompilerOptions; /** * A preconfigured result object. */ result: ScriptCompilerResult; } /** * A script compiler error entry. */ export interface ScriptCompilerError extends CompilerError { } /** * A module to compile files. */ export interface ScriptCompilerModule { /** * Compiles files. */ compile: ScriptCompiler; } /** * Script compiler options. */ export interface ScriptCompilerOptions extends TextCompilerOptions { /** * Additional data for the compilation. */ data?: any; /** * Path to the script. */ script?: string; } /** * A script compiler result. */ export interface ScriptCompilerResult extends CompilerResult { /** @inheritdoc */ errors: ScriptCompilerError[]; } /** * Options for text file based compilers. */ export interface TextCompilerOptions extends CompilerOptions { /** * The encoding to use. */ encoding?: string; } /** * A TypeScript compiler error entry. */ export interface TypeScriptCompilerError extends CompilerError { /** * The underlying Diagnostic object from the compiler result. */ diagnostic: any; } /** * TypeScript compiler options. */ export interface TypeScriptCompilerOptions extends TextCompilerOptions { } /** * A TypeScript compiler result. */ export interface TypeScriptCompilerResult extends CompilerResult { /** @inheritdoc */ errors: TypeScriptCompilerError[]; } /** * A UglifyJS compiler error entry. */ export interface UglifyJSCompilerError extends CompilerError { } /** * UglifyJS compiler options. */ export interface UglifyJSCompilerOptions extends TextCompilerOptions { /** * Delete the source file(s) on success or not. */ deleteSources?: boolean; /** * The extension to use for the output files. */ extension?: string; } /** * A UglifyJS compiler result. */ export interface UglifyJSCompilerResult extends CompilerResult { /** @inheritdoc */ errors: UglifyJSCompilerError[]; } /** * Collects files to compile. * * @param {CompilerOptions} defaultOpts The default options. * @param {CompilerOptions} [opts] The options. * * @returns Promise<string[]> The promise. */ export function collectCompilerFiles(defaultOpts: CompilerOptions, opts?: CompilerOptions): Promise<string[]> { if (!defaultOpts) { defaultOpts = { files: '**', }; } if (!opts) { opts = {}; } let cleanupStringList = (list: string | string[]): string[] => { list = deploy_helpers.asArray(list) .map(x => deploy_helpers.toStringSafe(x)) .filter(x => !deploy_helpers.isEmptyString(x)); return deploy_helpers.distinctArray(list); }; let filters = cleanupStringList(opts.files); if (filters.length < 1) { // use defaults filters = cleanupStringList(defaultOpts.files); } let filesToExclude = cleanupStringList(opts.exclude); if (filesToExclude.length < 1) { // use defaults filesToExclude = cleanupStringList(defaultOpts.exclude); } return new Promise<string[]>((resolve, reject) => { let completed = deploy_helpers.createSimplePromiseCompletedAction<string[]>(resolve, reject); try { let filesToCompile: string[] = []; let nextFilter: () => void; nextFilter = () => { if (filters.length < 1) { filesToCompile = filesToCompile.filter(x => !deploy_helpers.isEmptyString(x)) .map(x => Path.resolve(x)); filesToCompile = deploy_helpers.asArray(filesToCompile); completed(null, filesToCompile); return; } let f = filters.shift(); try { Glob(f, { absolute: true, cwd: deploy_workspace.getRootPath(), dot: true, ignore: filesToExclude, nodir: true, root: deploy_workspace.getRootPath(), }, (err, files) => { if (err) { completed(err); } else { filesToCompile = filesToCompile.concat(files); nextFilter(); } }); } catch (e) { completed(e); } }; nextFilter(); } catch (e) { completed(e); } }); } /** * Compiles (files). * * @param {Compiler} compiler The compiler to use. * @param {any[]} [args] One or more arguments for the compilation. * * @returns {Promise<CompilerResult>} The promise. */ export function compile(compiler: Compiler, args?: any[]): Promise<CompilerResult> { let me = this; if (!args) { args = []; } return new Promise<CompilerResult>((resolve, reject) => { let func: Function; switch (compiler) { case Compiler.CoffeeScript: // CoffeeScript func = compileCoffeeScript; break; case Compiler.HtmlMinifier: // Html Minifier func = compileHtmlMinifier; break; case Compiler.Less: // LESS func = compileLess; break; case Compiler.Pug: // Pug func = compliePug; break; case Compiler.Script: // script based compiler func = compileScript; break; case Compiler.TypeScript: // TypeScript func = compileTypeScript; break; case Compiler.UglifyJS: // UglifyJS func = compileUglifyJS; break; } if (func) { try { func.apply(me, args).then((result) => { resolve(result); }).catch((err) => { reject(err); }); } catch (e) { reject(e); } } else { reject(new Error(`Compiler '${compiler}' is not supported!`)); } }); } /** * Compiles CoffeeScript files. * * @param {CoffeeScriptCompilerOptions} [opts] The options. * * @returns Promise<CoffeeScriptCompilerResult> The promise. */ export function compileCoffeeScript(opts?: CoffeeScriptCompilerOptions): Promise<CoffeeScriptCompilerResult> { if (!opts) { opts = {}; } let enc = deploy_helpers.normalizeString(opts.encoding); if ('' === enc) { enc = 'utf8'; } let outExt = deploy_helpers.toStringSafe(opts.extension); if (deploy_helpers.isEmptyString(outExt)) { outExt = 'js'; } return new Promise<CoffeeScriptCompilerResult>((resolve, reject) => { let completed = (err: any, result?: CoffeeScriptCompilerResult) => { if (err) { reject(err); } else { resolve(result); } }; try { collectCompilerFiles({ files: "/**/*.coffee", }, opts).then((filesToCompile) => { let result: CoffeeScriptCompilerResult = { errors: [], files: filesToCompile.map(x => x), // create copy }; let coffeeOpts = deploy_helpers.cloneObject(opts); delete coffeeOpts['files']; delete coffeeOpts['exclude']; delete coffeeOpts['encoding']; delete coffeeOpts['extension']; coffeeOpts['inlineMap'] = deploy_helpers.toBooleanSafe(coffeeOpts['sourceMap']); coffeeOpts['sourceMap'] = false; let wf = Workflows.create(); filesToCompile.forEach(f => { return new Promise<any>((res, rej) => { let addError = (err: any) => { result.errors.push({ error: err, file: f, }); res(); }; FS.readFile(f, (err, data) => { try { if (err) { addError(err); return; } let coffeeCode = data.toString(enc); let jsCode = CoffeeScript.compile(coffeeCode, opts); let outDir = Path.dirname(f); let ext = Path.extname(f); let fileName = Path.basename(f, ext); let outputFile = Path.join(outDir, fileName + '.' + outExt); FS.writeFile(outputFile, new Buffer(jsCode, 'utf8'), (err) => { if (err) { addError(err); } else { res(); } }); } catch (e) { addError(e); } }); }); }); wf.start().then(() => { completed(null, result); }).catch((err) => { completed(err); }); }); } catch (e) { completed(e); } }); } /** * Compiles JavaScript files with UglifyJS. * * @param {HtmlMinifierCompilerOptions} [opts] The options. * * @returns Promise<HtmlMinifierCompilerResult> The promise. */ export function compileHtmlMinifier(opts?: HtmlMinifierCompilerOptions): Promise<HtmlMinifierCompilerResult> { if (!opts) { opts = {}; } let enc = deploy_helpers.normalizeString(opts.encoding); if ('' === enc) { enc = 'utf8'; } let outExt = deploy_helpers.toStringSafe(opts.extension); if (deploy_helpers.isEmptyString(opts.extension)) { outExt = 'min.html'; } let deleteOnSuccess = deploy_helpers.toBooleanSafe(opts.deleteSources); return new Promise<HtmlMinifierCompilerResult>((resolve, reject) => { let completed = deploy_helpers.createSimplePromiseCompletedAction<HtmlMinifierCompilerResult>(resolve, reject); try { collectCompilerFiles({ files: "/**/*.html", }, opts).then((filesToCompile) => { try { let result: HtmlMinifierCompilerResult = { errors: [], files: filesToCompile.map(x => x), // create copy }; let htmlMiniOpts = <any>deploy_helpers.cloneObject(opts); delete htmlMiniOpts['deleteSources']; delete htmlMiniOpts['files']; delete htmlMiniOpts['exclude']; delete htmlMiniOpts['encoding']; delete htmlMiniOpts['extension']; let nextFile: () => void; let addError = (err: any, file: string) => { result.errors.push({ error: err, file: file, }); nextFile(); }; nextFile = () => { if (filesToCompile.length < 1) { completed(null, result); return; } let f = filesToCompile.shift(); try { let outDir = Path.dirname(f); let ext = Path.extname(f); let fileName = Path.basename(f, ext); let outputFile = Path.join(outDir, fileName + '.' + outExt); let deleteSourceFile = () => { if (deleteOnSuccess) { FS.unlink(f, (err) => { if (err) { addError(err, f); } else { nextFile(); } }); } else { nextFile(); } }; FS.readFile(f, (err, data) => { if (err) { addError(err, f); } else { try { let code = data.toString(enc); let ugliCode = HtmlMinifier.minify(code, htmlMiniOpts); FS.writeFile(outputFile, new Buffer(ugliCode, enc), (err) => { if (err) { addError(err, f); } else { deleteSourceFile(); } }); } catch (e) { addError(err, f); } } }); } catch (e) { addError(e, f); } }; nextFile(); } catch (e) { completed(e); } }).catch((err) => { completed(err); }); } catch (e) { completed(e); } }); } /** * Compiles LESS files. * * @param {LessCompilerOptions} [opts] The options. * * @returns Promise<LessCompilerResult> The promise. */ export function compileLess(opts?: LessCompilerOptions): Promise<LessCompilerResult> { if (!opts) { opts = {}; } let compressOutput = deploy_helpers.toBooleanSafe(opts.compress); let enc = deploy_helpers.normalizeString(opts.encoding); if ('' === enc) { enc = 'utf8'; } let searchPaths = deploy_helpers.asArray(opts.paths) .map(x => deploy_helpers.toStringSafe(x)) .filter(x => !deploy_helpers.isEmptyString(x)); searchPaths = deploy_helpers.distinctArray(searchPaths); let outExt = deploy_helpers.toStringSafe(opts.extension); if (deploy_helpers.isEmptyString(outExt)) { outExt = 'css'; } return new Promise<LessCompilerResult>((resolve, reject) => { let completed = deploy_helpers.createSimplePromiseCompletedAction<LessCompilerResult>(resolve, reject); try { collectCompilerFiles({ files: "/**/*.less", }, opts).then((filesToCompile) => { let result: LessCompilerResult = { errors: [], files: filesToCompile.map(x => x), // create copy }; let compileNext: () => void; let compileCompleted = (file: string, err?: any) => { if (err) { result.errors.push({ error: err, file: file, }); } compileNext(); }; compileNext = () => { if (filesToCompile.length < 1) { completed(null, result); return; } let f = filesToCompile.shift(); FS.readFile(f, (err, data) => { if (err) { compileCompleted(f, err); return; } try { let lessCode = data.toString(enc); let dir = Path.dirname(f); let fileExt = Path.extname(f); let fileName = Path.basename(f, fileExt); let outputFile = Path.join(dir, fileName + '.' + outExt); let compilerPaths: string[]; if (searchPaths.length > 0) { compilerPaths = searchPaths.map(x => { if (!Path.isAbsolute(x)) { x = Path.join(dir, x); } return x; }); } if (compilerPaths) { compilerPaths = compilerPaths.filter(x => !deploy_helpers.isEmptyString(x)) .map(x => Path.resolve(x)); compilerPaths = deploy_helpers.distinctArray(compilerPaths); } // compile... LESS.render(lessCode, { compress: compressOutput, paths: compilerPaths, }, (err, output) => { try { if (err) { compileCompleted(f, err); // compile error } else { let outData = new Buffer(deploy_helpers.toStringSafe(output.css), enc); let writeToFile = () => { FS.writeFile(outputFile, outData, (err) => { outData = null; compileCompleted(f, err); }); }; // check if output file exists FS.exists(outputFile, (fileExists) => { if (fileExists) { // yes, no check if really a file FS.lstat(outputFile, (err, stats) => { if (err) { compileCompleted(f, err); } else { if (stats.isFile()) { // now delete existing file... FS.unlink(outputFile, (err) => { if (err) { compileCompleted(f, err); } else { writeToFile(); // write to file } }); } else { // no compileCompleted(f, new Error(i18.t('isNo.file', outputFile))); } } }); } else { writeToFile(); // no, write to file } }); } } catch (e) { compileCompleted(f, e); } }); } catch (e) { compileCompleted(e); // read file error } }); }; compileNext(); // start compiling }).catch((err) => { completed(err); }); } catch (e) { completed(e); } }); } /** * Compiles Pug files. * * @param {PugCompilerOptions} [opts] The options. * * @returns Promise<PugCompilerResult> The promise. */ export function compliePug(opts?: PugCompilerOptions): Promise<PugCompilerResult> { if (!opts) { opts = {}; } let enc = deploy_helpers.normalizeString(opts.encoding); if ('' === enc) { enc = 'utf8'; } let outExt = deploy_helpers.toStringSafe(opts.extension); if (deploy_helpers.isEmptyString(opts.extension)) { outExt = 'html'; } return new Promise<PugCompilerResult>((resolve, reject) => { let completed = deploy_helpers.createSimplePromiseCompletedAction<PugCompilerResult>(resolve, reject); try { collectCompilerFiles({ files: "/**/*.pug", }, opts).then((filesToCompile) => { try { let result: PugCompilerResult = { errors: [], files: filesToCompile.map(x => x), }; let pugOpts = deploy_helpers.cloneObject(opts); delete pugOpts['files']; delete pugOpts['exclude']; delete pugOpts['encoding']; delete pugOpts['extension']; let nextFile: () => void; let addError = (err: any, file: string) => { result.errors.push({ error: err, file: file, }); nextFile(); }; nextFile = () => { if (filesToCompile.length < 1) { completed(null, result); return; } let f = filesToCompile.shift(); let dir = Path.dirname(f); let ext = Path.extname(f); let fn = Path.basename(f, ext); let outFile = Path.join(dir, fn + '.' + outExt); FS.readFile(f, (err, data) => { if (err) { addError(err, f); } else { try { pugOpts['filename'] = f; let pugSrc = data.toString(enc); let html = Pug.render(pugSrc, pugOpts); FS.writeFile(outFile, new Buffer(html, enc), (err) => { if (err) { addError(err, f); } else { nextFile(); } }); } catch (e) { addError(e, f); } } }); }; nextFile(); } catch (e) { completed(e); } }); } catch (e) { completed(e); } }); } /** * Compiles files via a script. * * @param {ScriptCompilerOptions} [opts] The options. * * @returns Promise<TypeScriptCompilerResult> The promise. */ export function compileScript(cfg: deploy_contracts.DeployConfiguration, opts?: ScriptCompilerOptions): Promise<ScriptCompilerResult> { if (!opts) { opts = { script: './compile.js', }; } return new Promise<ScriptCompilerResult>((resolve, reject) => { let completed = deploy_helpers.createSimplePromiseCompletedAction<ScriptCompilerResult>(resolve, reject); try { let compilerModule = deploy_helpers.loadModule<ScriptCompilerModule>(opts.script); if (compilerModule) { if (compilerModule.compile) { collectCompilerFiles({ files: '**', }, opts).then((filesToCompile) => { let sym = Symbol("deploy.compilers.compileScript"); let args: ScriptCompilerArguments = { deployFiles: (files, targets) => { return deploy_helpers.deployFiles(files, targets, sym); }, emitGlobal: function() { return deploy_globals.EVENTS .emit .apply(deploy_globals.EVENTS, arguments); }, files: filesToCompile, globals: deploy_helpers.cloneObject(cfg.globals), options: opts, require: function(id) { return require(id); }, result: { errors: [], files: filesToCompile.map(x => x), }, }; Promise.resolve(<any>compilerModule.compile(args)).then((result: ScriptCompilerResult) => { completed(null, result || args.result); }).catch((err) => { completed(err); }); }).catch((err) => { completed(err); }); } else { completed(new Error('No compile() function found!')); } } else { completed(new Error('No compiler module found!')); } } catch (e) { completed(e); } }); } /** * Compiles TypeScript files. * * @param {TypeScriptCompilerOptions} [opts] The options. * * @returns Promise<TypeScriptCompilerResult> The promise. */ export function compileTypeScript(opts?: TypeScriptCompilerOptions): Promise<TypeScriptCompilerResult> { if (!opts) { opts = {}; } return new Promise<TypeScriptCompilerResult>((resolve, reject) => { let completed = deploy_helpers.createSimplePromiseCompletedAction<TypeScriptCompilerResult>(resolve, reject); try { collectCompilerFiles({ files: "/**/*.ts", }, opts).then((filesToCompile) => { try { // create compiler let program = TypeScript.createProgram(filesToCompile, opts); // execute let result = program.emit(); result.errors = []; result.files = filesToCompile; // collect errors let allDiagnostics = TypeScript.getPreEmitDiagnostics(program).concat(result.diagnostics); allDiagnostics.forEach(x => { if (x.category != TypeScript.DiagnosticCategory.Error) { return; } result.errors .push({ diagnostic: x, error: new Error(`[TS${x.code}] Offset ${x.start} :: ${x.messageText}`), file: x.file.fileName, }); }); completed(null, result); } catch (e) { completed(e); } }); } catch (e) { completed(e); } }); }; /** * Compiles JavaScript files with UglifyJS. * * @param {UglifyJSCompilerOptions} [opts] The options. * * @returns Promise<UglifyJSCompilerResult> The promise. */ export function compileUglifyJS(opts?: UglifyJSCompilerOptions): Promise<UglifyJSCompilerResult> { if (!opts) { opts = {}; } let enc = deploy_helpers.normalizeString(opts.encoding); if ('' === enc) { enc = 'utf8'; } let outExt = deploy_helpers.toStringSafe(opts.extension); if (deploy_helpers.isEmptyString(opts.extension)) { outExt = 'min.js'; } let deleteOnSuccess = deploy_helpers.toBooleanSafe(opts.deleteSources); return new Promise<UglifyJSCompilerResult>((resolve, reject) => { let completed = deploy_helpers.createSimplePromiseCompletedAction<UglifyJSCompilerResult>(resolve, reject); try { collectCompilerFiles({ files: "/**/*.js", }, opts).then((filesToCompile) => { try { let result: UglifyJSCompilerResult = { errors: [], files: filesToCompile.map(x => x), // create copy }; let uglifyOpts = <any>deploy_helpers.cloneObject(opts); delete uglifyOpts['deleteSources']; delete uglifyOpts['files']; delete uglifyOpts['exclude']; delete uglifyOpts['encoding']; delete uglifyOpts['extension']; let nextFile: () => void; let addError = (err: any, file: string) => { result.errors.push({ error: err, file: file, }); nextFile(); }; nextFile = () => { if (filesToCompile.length < 1) { completed(null, result); return; } let f = filesToCompile.shift(); try { let outDir = Path.dirname(f); let ext = Path.extname(f); let fileName = Path.basename(f, ext); let outputFile = Path.join(outDir, fileName + '.' + outExt); let ur = UglifyJS.minify([ f ], uglifyOpts); let ugliCode = deploy_helpers.toStringSafe(ur.code); let deleteSourceFile = () => { if (deleteOnSuccess) { FS.unlink(f, (err) => { if (err) { addError(err, f); } else { nextFile(); } }); } else { nextFile(); } }; FS.writeFile(outputFile, new Buffer(ugliCode, enc), (err) => { if (err) { addError(err, f); } else { deleteSourceFile(); } }); } catch (e) { addError(e, f); } }; nextFile(); } catch (e) { completed(e); } }).catch((err) => { completed(err); }); } catch (e) { completed(e); } }); }
the_stack
import { GaxiosPromise } from 'gaxios'; import { Compute, JWT, OAuth2Client, UserRefreshClient } from 'google-auth-library'; import { APIRequestContext, BodyResponseCallback, GlobalOptions, GoogleConfigurable, MethodOptions } from 'googleapis-common'; export declare namespace plus_v1 { interface Options extends GlobalOptions { version: 'v1'; } interface StandardParameters { /** * Data format for the response. */ alt?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API * access, quota, and reports. Required unless you provide an OAuth 2.0 * token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * An opaque string that represents a user for quota purposes. Must not * exceed 40 characters. */ quotaUser?: string; /** * Deprecated. Please use quotaUser instead. */ userIp?: string; } /** * Google+ API * * Builds on top of the Google+ platform. * * @example * const {google} = require('googleapis'); * const plus = google.plus('v1'); * * @namespace plus * @type {Function} * @version v1 * @variation v1 * @param {object=} options Options for Plus */ class Plus { context: APIRequestContext; activities: Resource$Activities; comments: Resource$Comments; people: Resource$People; constructor(options: GlobalOptions, google?: GoogleConfigurable); } interface Schema$Acl { /** * Description of the access granted, suitable for display. */ description?: string; /** * The list of access entries. */ items?: Schema$PlusAclentryResource[]; /** * Identifies this resource as a collection of access controls. Value: * &quot;plus#acl&quot;. */ kind?: string; } interface Schema$Activity { /** * Identifies who has access to see this activity. */ access?: Schema$Acl; /** * The person who performed this activity. */ actor?: { clientSpecificActorInfo?: { youtubeActorInfo?: { channelId?: string; }; }; displayName?: string; id?: string; image?: { url?: string; }; name?: { familyName?: string; givenName?: string; }; url?: string; verification?: { adHocVerified?: string; }; }; /** * Street address where this activity occurred. */ address?: string; /** * Additional content added by the person who shared this activity, * applicable only when resharing an activity. */ annotation?: string; /** * If this activity is a crosspost from another system, this property * specifies the ID of the original activity. */ crosspostSource?: string; /** * ETag of this response for caching purposes. */ etag?: string; /** * Latitude and longitude where this activity occurred. Format is latitude * followed by longitude, space separated. */ geocode?: string; /** * The ID of this activity. */ id?: string; /** * Identifies this resource as an activity. Value: * &quot;plus#activity&quot;. */ kind?: string; /** * The location where this activity occurred. */ location?: Schema$Place; /** * The object of this activity. */ object?: { actor?: { clientSpecificActorInfo?: { youtubeActorInfo?: { channelId?: string; }; }; displayName?: string; id?: string; image?: { url?: string; }; url?: string; verification?: { adHocVerified?: string; }; }; attachments?: Array<{ content?: string; displayName?: string; embed?: { type?: string; url?: string; }; fullImage?: { height?: number; type?: string; url?: string; width?: number; }; id?: string; image?: { height?: number; type?: string; url?: string; width?: number; }; objectType?: string; thumbnails?: Array<{ description?: string; image?: { height?: number; type?: string; url?: string; width?: number; }; url?: string; }>; url?: string; }>; content?: string; id?: string; objectType?: string; originalContent?: string; plusoners?: { selfLink?: string; totalItems?: number; }; replies?: { selfLink?: string; totalItems?: number; }; resharers?: { selfLink?: string; totalItems?: number; }; url?: string; }; /** * ID of the place where this activity occurred. */ placeId?: string; /** * Name of the place where this activity occurred. */ placeName?: string; /** * The service provider that initially published this activity. */ provider?: { title?: string; }; /** * The time at which this activity was initially published. Formatted as an * RFC 3339 timestamp. */ published?: string; /** * Radius, in meters, of the region where this activity occurred, centered * at the latitude and longitude identified in geocode. */ radius?: string; /** * Title of this activity. */ title?: string; /** * The time at which this activity was last updated. Formatted as an RFC * 3339 timestamp. */ updated?: string; /** * The link to this activity. */ url?: string; /** * This activity&#39;s verb, which indicates the action that was performed. * Possible values include, but are not limited to, the following values: - * &quot;post&quot; - Publish content to the stream. - &quot;share&quot; - * Reshare an activity. */ verb?: string; } interface Schema$ActivityFeed { /** * ETag of this response for caching purposes. */ etag?: string; /** * The ID of this collection of activities. Deprecated. */ id?: string; /** * The activities in this page of results. */ items?: Schema$Activity[]; /** * Identifies this resource as a collection of activities. Value: * &quot;plus#activityFeed&quot;. */ kind?: string; /** * Link to the next page of activities. */ nextLink?: string; /** * The continuation token, which is used to page through large result sets. * Provide this value in a subsequent request to return the next page of * results. */ nextPageToken?: string; /** * Link to this activity resource. */ selfLink?: string; /** * The title of this collection of activities, which is a truncated portion * of the content. */ title?: string; /** * The time at which this collection of activities was last updated. * Formatted as an RFC 3339 timestamp. */ updated?: string; } interface Schema$Comment { /** * The person who posted this comment. */ actor?: { clientSpecificActorInfo?: { youtubeActorInfo?: { channelId?: string; }; }; displayName?: string; id?: string; image?: { url?: string; }; url?: string; verification?: { adHocVerified?: string; }; }; /** * ETag of this response for caching purposes. */ etag?: string; /** * The ID of this comment. */ id?: string; /** * The activity this comment replied to. */ inReplyTo?: Array<{ id?: string; url?: string; }>; /** * Identifies this resource as a comment. Value: &quot;plus#comment&quot;. */ kind?: string; /** * The object of this comment. */ object?: { content?: string; objectType?: string; originalContent?: string; }; /** * People who +1&#39;d this comment. */ plusoners?: { totalItems?: number; }; /** * The time at which this comment was initially published. Formatted as an * RFC 3339 timestamp. */ published?: string; /** * Link to this comment resource. */ selfLink?: string; /** * The time at which this comment was last updated. Formatted as an RFC 3339 * timestamp. */ updated?: string; /** * This comment&#39;s verb, indicating what action was performed. Possible * values are: - &quot;post&quot; - Publish content to the stream. */ verb?: string; } interface Schema$CommentFeed { /** * ETag of this response for caching purposes. */ etag?: string; /** * The ID of this collection of comments. */ id?: string; /** * The comments in this page of results. */ items?: Schema$Comment[]; /** * Identifies this resource as a collection of comments. Value: * &quot;plus#commentFeed&quot;. */ kind?: string; /** * Link to the next page of activities. */ nextLink?: string; /** * The continuation token, which is used to page through large result sets. * Provide this value in a subsequent request to return the next page of * results. */ nextPageToken?: string; /** * The title of this collection of comments. */ title?: string; /** * The time at which this collection of comments was last updated. Formatted * as an RFC 3339 timestamp. */ updated?: string; } interface Schema$PeopleFeed { /** * ETag of this response for caching purposes. */ etag?: string; /** * The people in this page of results. Each item includes the id, * displayName, image, and url for the person. To retrieve additional * profile data, see the people.get method. */ items?: Schema$Person[]; /** * Identifies this resource as a collection of people. Value: * &quot;plus#peopleFeed&quot;. */ kind?: string; /** * The continuation token, which is used to page through large result sets. * Provide this value in a subsequent request to return the next page of * results. */ nextPageToken?: string; /** * Link to this resource. */ selfLink?: string; /** * The title of this collection of people. */ title?: string; /** * The total number of people available in this list. The number of people * in a response might be smaller due to paging. This might not be set for * all collections. */ totalItems?: number; } interface Schema$Person { /** * A short biography for this person. */ aboutMe?: string; /** * The age range of the person. Valid ranges are 17 or younger, 18 to 20, * and 21 or older. Age is determined from the user&#39;s birthday using * Western age reckoning. */ ageRange?: { max?: number; min?: number; }; /** * The person&#39;s date of birth, represented as YYYY-MM-DD. */ birthday?: string; /** * The &quot;bragging rights&quot; line of this person. */ braggingRights?: string; /** * For followers who are visible, the number of people who have added this * person or page to a circle. */ circledByCount?: number; /** * The cover photo content. */ cover?: { coverInfo?: { leftImageOffset?: number; topImageOffset?: number; }; coverPhoto?: { height?: number; url?: string; width?: number; }; layout?: string; }; /** * (this field is not currently used) */ currentLocation?: string; /** * The name of this person, which is suitable for display. */ displayName?: string; /** * The hosted domain name for the user&#39;s Google Apps account. For * instance, example.com. The plus.profile.emails.read or email scope is * needed to get this domain name. */ domain?: string; /** * A list of email addresses that this person has, including their Google * account email address, and the public verified email addresses on their * Google+ profile. The plus.profile.emails.read scope is needed to retrieve * these email addresses, or the email scope can be used to retrieve just * the Google account email address. */ emails?: Array<{ type?: string; value?: string; }>; /** * ETag of this response for caching purposes. */ etag?: string; /** * The person&#39;s gender. Possible values include, but are not limited to, * the following values: - &quot;male&quot; - Male gender. - * &quot;female&quot; - Female gender. - &quot;other&quot; - Other. */ gender?: string; /** * The ID of this person. */ id?: string; /** * The representation of the person&#39;s profile photo. */ image?: { isDefault?: boolean; url?: string; }; /** * Whether this user has signed up for Google+. */ isPlusUser?: boolean; /** * Identifies this resource as a person. Value: &quot;plus#person&quot;. */ kind?: string; /** * The user&#39;s preferred language for rendering. */ language?: string; /** * An object representation of the individual components of a person&#39;s * name. */ name?: { familyName?: string; formatted?: string; givenName?: string; honorificPrefix?: string; honorificSuffix?: string; middleName?: string; }; /** * The nickname of this person. */ nickname?: string; /** * Type of person within Google+. Possible values include, but are not * limited to, the following values: - &quot;person&quot; - represents an * actual person. - &quot;page&quot; - represents a page. */ objectType?: string; /** * The occupation of this person. */ occupation?: string; /** * A list of current or past organizations with which this person is * associated. */ organizations?: Array<{ department?: string; description?: string; endDate?: string; location?: string; name?: string; primary?: boolean; startDate?: string; title?: string; type?: string; }>; /** * A list of places where this person has lived. */ placesLived?: Array<{ primary?: boolean; value?: string; }>; /** * If a Google+ Page, the number of people who have +1&#39;d this page. */ plusOneCount?: number; /** * The person&#39;s relationship status. Possible values include, but are * not limited to, the following values: - &quot;single&quot; - Person is * single. - &quot;in_a_relationship&quot; - Person is in a relationship. * - &quot;engaged&quot; - Person is engaged. - &quot;married&quot; - * Person is married. - &quot;its_complicated&quot; - The relationship is * complicated. - &quot;open_relationship&quot; - Person is in an open * relationship. - &quot;widowed&quot; - Person is widowed. - * &quot;in_domestic_partnership&quot; - Person is in a domestic * partnership. - &quot;in_civil_union&quot; - Person is in a civil union. */ relationshipStatus?: string; /** * The person&#39;s skills. */ skills?: string; /** * The brief description (tagline) of this person. */ tagline?: string; /** * The URL of this person&#39;s profile. */ url?: string; /** * A list of URLs for this person. */ urls?: Array<{ label?: string; type?: string; value?: string; }>; /** * Whether the person or Google+ Page has been verified. */ verified?: boolean; } interface Schema$Place { /** * The physical address of the place. */ address?: { formatted?: string; }; /** * The display name of the place. */ displayName?: string; /** * The id of the place. */ id?: string; /** * Identifies this resource as a place. Value: &quot;plus#place&quot;. */ kind?: string; /** * The position of the place. */ position?: { latitude?: number; longitude?: number; }; } interface Schema$PlusAclentryResource { /** * A descriptive name for this entry. Suitable for display. */ displayName?: string; /** * The ID of the entry. For entries of type &quot;person&quot; or * &quot;circle&quot;, this is the ID of the resource. For other types, this * property is not set. */ id?: string; /** * The type of entry describing to whom access is granted. Possible values * are: - &quot;person&quot; - Access to an individual. - * &quot;circle&quot; - Access to members of a circle. - * &quot;myCircles&quot; - Access to members of all the person&#39;s * circles. - &quot;extendedCircles&quot; - Access to members of all the * person&#39;s circles, plus all of the people in their circles. - * &quot;domain&quot; - Access to members of the person&#39;s Google Apps * domain. - &quot;public&quot; - Access to anyone on the web. */ type?: string; } class Resource$Activities { context: APIRequestContext; constructor(context: APIRequestContext); /** * plus.activities.get * @desc Shut down. See https://developers.google.com/+/api-shutdown for * more details. * @alias plus.activities.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.activityId The ID of the activity to get. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Activities$Get, options?: MethodOptions): GaxiosPromise<Schema$Activity>; get(params: Params$Resource$Activities$Get, options: MethodOptions | BodyResponseCallback<Schema$Activity>, callback: BodyResponseCallback<Schema$Activity>): void; get(params: Params$Resource$Activities$Get, callback: BodyResponseCallback<Schema$Activity>): void; get(callback: BodyResponseCallback<Schema$Activity>): void; /** * plus.activities.list * @desc Shut down. See https://developers.google.com/+/api-shutdown for * more details. * @alias plus.activities.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.collection The collection of activities to list. * @param {integer=} params.maxResults The maximum number of activities to include in the response, which is used for paging. For any response, the actual number returned might be less than the specified maxResults. * @param {string=} params.pageToken The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response. * @param {string} params.userId The ID of the user to get activities for. The special value "me" can be used to indicate the authenticated user. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Activities$List, options?: MethodOptions): GaxiosPromise<Schema$ActivityFeed>; list(params: Params$Resource$Activities$List, options: MethodOptions | BodyResponseCallback<Schema$ActivityFeed>, callback: BodyResponseCallback<Schema$ActivityFeed>): void; list(params: Params$Resource$Activities$List, callback: BodyResponseCallback<Schema$ActivityFeed>): void; list(callback: BodyResponseCallback<Schema$ActivityFeed>): void; /** * plus.activities.search * @desc Shut down. See https://developers.google.com/+/api-shutdown for * more details. * @alias plus.activities.search * @memberOf! () * * @param {object} params Parameters for request * @param {string=} params.language Specify the preferred language to search with. See search language codes for available values. * @param {integer=} params.maxResults The maximum number of activities to include in the response, which is used for paging. For any response, the actual number returned might be less than the specified maxResults. * @param {string=} params.orderBy Specifies how to order search results. * @param {string=} params.pageToken The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response. This token can be of any length. * @param {string} params.query Full-text search query string. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ search(params?: Params$Resource$Activities$Search, options?: MethodOptions): GaxiosPromise<Schema$ActivityFeed>; search(params: Params$Resource$Activities$Search, options: MethodOptions | BodyResponseCallback<Schema$ActivityFeed>, callback: BodyResponseCallback<Schema$ActivityFeed>): void; search(params: Params$Resource$Activities$Search, callback: BodyResponseCallback<Schema$ActivityFeed>): void; search(callback: BodyResponseCallback<Schema$ActivityFeed>): void; } interface Params$Resource$Activities$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The ID of the activity to get. */ activityId?: string; } interface Params$Resource$Activities$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The collection of activities to list. */ collection?: string; /** * The maximum number of activities to include in the response, which is * used for paging. For any response, the actual number returned might be * less than the specified maxResults. */ maxResults?: number; /** * The continuation token, which is used to page through large result sets. * To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ pageToken?: string; /** * The ID of the user to get activities for. The special value "me" can be * used to indicate the authenticated user. */ userId?: string; } interface Params$Resource$Activities$Search extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Specify the preferred language to search with. See search language codes * for available values. */ language?: string; /** * The maximum number of activities to include in the response, which is * used for paging. For any response, the actual number returned might be * less than the specified maxResults. */ maxResults?: number; /** * Specifies how to order search results. */ orderBy?: string; /** * The continuation token, which is used to page through large result sets. * To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. This token can be of any * length. */ pageToken?: string; /** * Full-text search query string. */ query?: string; } class Resource$Comments { context: APIRequestContext; constructor(context: APIRequestContext); /** * plus.comments.get * @desc Shut down. See https://developers.google.com/+/api-shutdown for * more details. * @alias plus.comments.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.commentId The ID of the comment to get. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Comments$Get, options?: MethodOptions): GaxiosPromise<Schema$Comment>; get(params: Params$Resource$Comments$Get, options: MethodOptions | BodyResponseCallback<Schema$Comment>, callback: BodyResponseCallback<Schema$Comment>): void; get(params: Params$Resource$Comments$Get, callback: BodyResponseCallback<Schema$Comment>): void; get(callback: BodyResponseCallback<Schema$Comment>): void; /** * plus.comments.list * @desc Shut down. See https://developers.google.com/+/api-shutdown for * more details. * @alias plus.comments.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.activityId The ID of the activity to get comments for. * @param {integer=} params.maxResults The maximum number of comments to include in the response, which is used for paging. For any response, the actual number returned might be less than the specified maxResults. * @param {string=} params.pageToken The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response. * @param {string=} params.sortOrder The order in which to sort the list of comments. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Comments$List, options?: MethodOptions): GaxiosPromise<Schema$CommentFeed>; list(params: Params$Resource$Comments$List, options: MethodOptions | BodyResponseCallback<Schema$CommentFeed>, callback: BodyResponseCallback<Schema$CommentFeed>): void; list(params: Params$Resource$Comments$List, callback: BodyResponseCallback<Schema$CommentFeed>): void; list(callback: BodyResponseCallback<Schema$CommentFeed>): void; } interface Params$Resource$Comments$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The ID of the comment to get. */ commentId?: string; } interface Params$Resource$Comments$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The ID of the activity to get comments for. */ activityId?: string; /** * The maximum number of comments to include in the response, which is used * for paging. For any response, the actual number returned might be less * than the specified maxResults. */ maxResults?: number; /** * The continuation token, which is used to page through large result sets. * To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ pageToken?: string; /** * The order in which to sort the list of comments. */ sortOrder?: string; } class Resource$People { context: APIRequestContext; constructor(context: APIRequestContext); /** * plus.people.get * @desc Get a person's profile. If your app uses scope * https://www.googleapis.com/auth/plus.login, this method is guaranteed to * return ageRange and language. * @alias plus.people.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userId The ID of the person to get the profile for. The special value "me" can be used to indicate the authenticated user. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$People$Get, options?: MethodOptions): GaxiosPromise<Schema$Person>; get(params: Params$Resource$People$Get, options: MethodOptions | BodyResponseCallback<Schema$Person>, callback: BodyResponseCallback<Schema$Person>): void; get(params: Params$Resource$People$Get, callback: BodyResponseCallback<Schema$Person>): void; get(callback: BodyResponseCallback<Schema$Person>): void; /** * plus.people.list * @desc List all of the people in the specified collection. * @alias plus.people.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.collection The collection of people to list. * @param {integer=} params.maxResults The maximum number of people to include in the response, which is used for paging. For any response, the actual number returned might be less than the specified maxResults. * @param {string=} params.orderBy The order to return people in. * @param {string=} params.pageToken The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response. * @param {string} params.userId Get the collection of people for the person identified. Use "me" to indicate the authenticated user. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$People$List, options?: MethodOptions): GaxiosPromise<Schema$PeopleFeed>; list(params: Params$Resource$People$List, options: MethodOptions | BodyResponseCallback<Schema$PeopleFeed>, callback: BodyResponseCallback<Schema$PeopleFeed>): void; list(params: Params$Resource$People$List, callback: BodyResponseCallback<Schema$PeopleFeed>): void; list(callback: BodyResponseCallback<Schema$PeopleFeed>): void; /** * plus.people.listByActivity * @desc Shut down. See https://developers.google.com/+/api-shutdown for * more details. * @alias plus.people.listByActivity * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.activityId The ID of the activity to get the list of people for. * @param {string} params.collection The collection of people to list. * @param {integer=} params.maxResults The maximum number of people to include in the response, which is used for paging. For any response, the actual number returned might be less than the specified maxResults. * @param {string=} params.pageToken The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ listByActivity(params?: Params$Resource$People$Listbyactivity, options?: MethodOptions): GaxiosPromise<Schema$PeopleFeed>; listByActivity(params: Params$Resource$People$Listbyactivity, options: MethodOptions | BodyResponseCallback<Schema$PeopleFeed>, callback: BodyResponseCallback<Schema$PeopleFeed>): void; listByActivity(params: Params$Resource$People$Listbyactivity, callback: BodyResponseCallback<Schema$PeopleFeed>): void; listByActivity(callback: BodyResponseCallback<Schema$PeopleFeed>): void; /** * plus.people.search * @desc Shut down. See https://developers.google.com/+/api-shutdown for * more details. * @alias plus.people.search * @memberOf! () * * @param {object} params Parameters for request * @param {string=} params.language Specify the preferred language to search with. See search language codes for available values. * @param {integer=} params.maxResults The maximum number of people to include in the response, which is used for paging. For any response, the actual number returned might be less than the specified maxResults. * @param {string=} params.pageToken The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response. This token can be of any length. * @param {string} params.query Specify a query string for full text search of public text in all profiles. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ search(params?: Params$Resource$People$Search, options?: MethodOptions): GaxiosPromise<Schema$PeopleFeed>; search(params: Params$Resource$People$Search, options: MethodOptions | BodyResponseCallback<Schema$PeopleFeed>, callback: BodyResponseCallback<Schema$PeopleFeed>): void; search(params: Params$Resource$People$Search, callback: BodyResponseCallback<Schema$PeopleFeed>): void; search(callback: BodyResponseCallback<Schema$PeopleFeed>): void; } interface Params$Resource$People$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The ID of the person to get the profile for. The special value "me" can * be used to indicate the authenticated user. */ userId?: string; } interface Params$Resource$People$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The collection of people to list. */ collection?: string; /** * The maximum number of people to include in the response, which is used * for paging. For any response, the actual number returned might be less * than the specified maxResults. */ maxResults?: number; /** * The order to return people in. */ orderBy?: string; /** * The continuation token, which is used to page through large result sets. * To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ pageToken?: string; /** * Get the collection of people for the person identified. Use "me" to * indicate the authenticated user. */ userId?: string; } interface Params$Resource$People$Listbyactivity extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The ID of the activity to get the list of people for. */ activityId?: string; /** * The collection of people to list. */ collection?: string; /** * The maximum number of people to include in the response, which is used * for paging. For any response, the actual number returned might be less * than the specified maxResults. */ maxResults?: number; /** * The continuation token, which is used to page through large result sets. * To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ pageToken?: string; } interface Params$Resource$People$Search extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Specify the preferred language to search with. See search language codes * for available values. */ language?: string; /** * The maximum number of people to include in the response, which is used * for paging. For any response, the actual number returned might be less * than the specified maxResults. */ maxResults?: number; /** * The continuation token, which is used to page through large result sets. * To get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. This token can be of any * length. */ pageToken?: string; /** * Specify a query string for full text search of public text in all * profiles. */ query?: string; } }
the_stack
import { sample, guard, createEvent, createStore, createEffect, is, } from 'effector' import {argumentHistory} from 'effector/fixtures' test('sid support', () => { const source = createStore(null) const sampled = sample({source, sid: 'foo'}) expect(sampled.sid).toBe('foo') }) describe('temporal consistency', () => { test('in combination with guard, pass immediately', () => { const fn = jest.fn() const trigger = createEvent<number>() const target = createEvent() sample({ source: trigger, clock: guard(trigger, { filter: x => x > 0, }), target, }) target.watch(fn) trigger(1) expect(argumentHistory(fn)).toEqual([1]) }) test('in combination with guard, pass on second call', () => { const fn = jest.fn() const trigger = createEvent<number>() const target = createEvent() sample({ source: trigger, clock: guard(trigger, { filter: x => x > 0, }), target, }) target.watch(fn) trigger(0) trigger(1) expect(argumentHistory(fn)).toEqual([1]) }) test('in combination with .filter, pass immediately', () => { const fn = jest.fn() const trigger = createEvent<number>() const target = createEvent() sample({ source: trigger, clock: trigger.filter({ fn: x => x > 0, }), target, }) target.watch(fn) trigger(1) expect(argumentHistory(fn)).toEqual([1]) }) test('in combination with .filter, pass on second call', () => { const fn = jest.fn() const trigger = createEvent<number>() const target = createEvent() sample({ source: trigger, clock: trigger.filter({ fn: x => x > 0, }), target, }) target.watch(fn) trigger(0) trigger(1) expect(argumentHistory(fn)).toEqual([1]) }) test('source & clock is a same event', () => { const fn = jest.fn() const trigger = createEvent<number>() const target = createEvent() sample({ source: trigger, clock: trigger, target, }) target.watch(fn) trigger(0) trigger(1) expect(argumentHistory(fn)).toEqual([0, 1]) }) test('clock triggers earlier than source during same pure phase', () => { const fn = jest.fn() const trigger = createEvent<number>() const source = trigger.map(x => x) const target = createEvent() sample({ source, clock: trigger, target, }) target.watch(fn) trigger(0) trigger(1) //note that during first trigger call, source is not called yet //in general, users should avoid such a backward-clocking expect(argumentHistory(fn)).toEqual([1]) }) }) it('should not accept undefined clocks', () => { expect(() => { sample({ //@ts-expect-error source: createStore(null), clock: undefined, }) }).toThrowErrorMatchingInlineSnapshot(`"sample: clock should be defined"`) }) describe('sample type', () => { test.each` source | clock | kind ${createStore(0)} | ${createStore(0)} | ${'store'} ${createStore(0)} | ${createEvent()} | ${'event'} ${createEvent()} | ${createStore(0)} | ${'event'} ${createEvent()} | ${createEvent()} | ${'event'} `(`$kind <- $source.kind by $clock.kind`, ({source, clock, kind}) => { //@ts-expect-error expect(sample(source, clock).kind).toBe(kind) }) test.each` source | clock | kind ${createStore(0)} | ${createStore(0)} | ${'store'} ${createStore(0)} | ${createEvent()} | ${'event'} ${createEvent()} | ${createStore(0)} | ${'event'} ${createEvent()} | ${createEvent()} | ${'event'} `( `$kind <- $source.kind by $clock.kind with handler`, ({source, clock, kind}) => { expect( //@ts-expect-error sample(source, clock, (source, clock) => ({source, clock})).kind, ).toBe(kind) }, ) }) describe('sample', () => { it('works with config', () => { const foo = createStore('') const bar = createStore('') sample({clock: foo, source: foo, target: bar}) }) it('handles object combination', () => { const foo = createStore('') //@ts-expect-error sample({foo}) }) it('works with single source', () => { const foo = createStore('') sample(foo) }) describe('sample with event as source', () => { describe.each` greedy | resultDirect | resultBacktracking ${false} | ${[{x: 1}, {x: 2}, {x: 3}]} | ${[{x: 2}, {x: 3}]} ${true} | ${[{x: 1}, {x: 2}, {x: 3}]} | ${[{x: 1}, {x: 2}]} `( 'depended on order of execution (greedy = $greedy)', ({greedy, resultDirect, resultBacktracking}) => { test('direct order', () => { const fn = jest.fn() const A = createEvent<number>() const B = A.map(x => ({x})) sample({ source: A, clock: B, fn: (A, B) => B, greedy, }).watch(e => fn(e)) A(1) A(2) A(3) expect(argumentHistory(fn)).toEqual(resultDirect) }) test('backtracking', () => { const fn = jest.fn() const A = createEvent<number>() const B = A.map(x => ({x})) sample({ source: B, clock: A, fn: B => B, greedy, }).watch(e => fn(e)) A(1) A(2) A(3) expect(argumentHistory(fn)).toEqual(resultBacktracking) }) }, ) it('works with sibling events', () => { const fn1 = jest.fn() const fn2 = jest.fn() const A = createEvent<number>() const B = A.map(b => ({b})) const C = A.filterMap(x => { if (x > 5) return `${x} > 5` }) sample(B, C, ({b}, c) => ({b, c})).watch(e => fn1(e)) sample(C, B, (c, {b}) => ({b, c})).watch(e => fn2(e)) A(2) A(6) A(3) A(4) A(10) expect(argumentHistory(fn1)).toEqual([ {b: 6, c: `6 > 5`}, {b: 10, c: `10 > 5`}, ]) expect(argumentHistory(fn2)).toEqual([ {b: 3, c: `6 > 5`}, {b: 4, c: `6 > 5`}, {b: 10, c: `10 > 5`}, ]) }) test('event', () => { const fn = jest.fn() const data = createEvent<any>() const stop = createEvent() const lastData = sample(data, stop) lastData.watch(value => fn(value)) data({foo: 'bar'}) data(true) data(false) data({x: 'baz'}) stop() expect(argumentHistory(fn)).toEqual([{x: 'baz'}]) expect(fn).toHaveBeenCalledTimes(1) }) test('no updates until first source update', () => { const fn = jest.fn() const data = createEvent<any>() const stop = createEvent() const lastData = sample(data, stop) lastData.watch(value => fn(value)) stop() stop() expect(fn).not.toHaveBeenCalled() data({x: 'baz'}) expect(fn).not.toHaveBeenCalled() stop() expect(argumentHistory(fn)).toEqual([{x: 'baz'}]) expect(fn).toHaveBeenCalledTimes(1) }) test( 'edge case: no updates until first source update ' + 'even when clock is store', () => { const fn = jest.fn() const data = createEvent<any>() const add = createEvent<number>() const stop = createStore(0).on(add, (x, n) => x + n) const lastData = sample(data, stop) lastData.watch(value => fn(value)) add(1) add(2) expect(fn).not.toHaveBeenCalled() data({x: 'baz'}) add(0) //edge case: store will not be updated expect(fn).not.toHaveBeenCalled() add(3) expect(argumentHistory(fn)).toEqual([{x: 'baz'}]) expect(fn).toHaveBeenCalledTimes(1) add(4) expect(argumentHistory(fn)).toEqual([{x: 'baz'}, {x: 'baz'}]) expect(fn).toHaveBeenCalledTimes(2) }, ) test('handler works', () => { const fn = jest.fn() const release = createEvent<number>() const emit = createEvent<number>() const received = sample(emit, release, (last, payload) => [last, payload]) received.watch(value => fn(value)) release(0) emit(1) emit(2) release(3) release(4) emit(5) expect(argumentHistory(fn)).toEqual([ [2, 3], [2, 4], ]) }) test('store as clock', () => { const fn = jest.fn() const source = createEvent<string>() const clock = createStore(0) const result = sample(source, clock) result.watch(value => fn(value)) //@ts-expect-error clock.setState(1) expect(fn).not.toHaveBeenCalled() source('run') expect(fn).not.toHaveBeenCalled() //@ts-expect-error clock.setState(2) expect(argumentHistory(fn)).toEqual(['run']) }) test('store as clock with handler', () => { const fn = jest.fn() const handler = jest.fn(x => x) const source = createEvent<string>() const clock = createStore(0) const result = sample(source, clock, (source, clock) => handler({ source, clock, }), ) result.watch(value => fn(value)) //@ts-expect-error clock.setState(1) expect(fn).not.toHaveBeenCalled() expect(handler).not.toHaveBeenCalled() source('run') expect(fn).not.toHaveBeenCalled() expect(handler).not.toHaveBeenCalled() //@ts-expect-error clock.setState(2) expect(argumentHistory(fn)).toEqual([{source: 'run', clock: 2}]) expect(argumentHistory(handler)).toEqual([{source: 'run', clock: 2}]) }) test('event source with store as target', () => {}) test('event source with effect as target', () => {}) }) describe('sample with effect as source', () => { test('effect', () => { const fn = jest.fn() const data = createEffect({ handler(_: any) { return 'resolved' }, }) const stop = createEvent() const lastData = sample(data, stop) lastData.watch(value => fn(value)) data({foo: 'bar'}) data(true) data(false) data({x: 'baz'}) stop() expect(argumentHistory(fn)).toEqual([{x: 'baz'}]) expect(fn).toHaveBeenCalledTimes(1) }) it('support watchers as usual', async () => { const fn1 = jest.fn() const fn2 = jest.fn() const hello = createEffect({ handler(_: any) { return Promise.resolve(200) }, }) const run = createEvent() sample(hello, run).watch(e => fn1(e)) sample(hello.done, run).watch(e => fn2(e)) await hello('test') run() expect(fn1).toHaveBeenCalledTimes(1) expect(fn2).toHaveBeenCalledTimes(1) }) describe('event call will not break watchers', () => { it.each` greedy ${false} ${true} `( 'event call will not break watchers (greedy = $greedy)', async ({greedy}) => { const fn1 = jest.fn() const hello = createEvent<string>() const run = createEvent<string>() sample({ source: hello, clock: run, fn: (a, b) => ({a, b}), greedy, }).watch(() => {}) sample({ source: hello, clock: run, fn: (a, b) => ({a, b}), greedy, }).watch(e => fn1(e)) run('R') hello('hello') run('RR') expect(fn1).toHaveBeenCalledTimes(1) }, ) }) test('effect source with store as target', () => {}) test('effect source with effect as target', () => {}) }) describe('sample with store as source', () => { test('store', () => { const fn = jest.fn() const inc = createEvent() const dec = createEvent() const stop = createEvent() const s1 = createStore(0) const s2 = sample(s1, stop) s2.watch(value => fn(value)) s1.on(inc, n => n + 1).on(dec, n => n - 1) inc() dec() inc() inc() stop() expect(argumentHistory(fn)).toEqual([2]) }) test('store has the same state as source', () => { const fn = jest.fn() const stop = createEvent() const s1 = createStore(0) //@ts-expect-error s1.setState(1) const s2 = sample(s1, stop) s2.watch(e => fn(e)) stop() expect(argumentHistory(fn)).toEqual([1]) }) test('store has its own defaultState', () => { const stop = createStore(0) const s1 = createStore(0) //@ts-expect-error s1.setState(1) const s2 = sample(s1, stop) expect(s2.defaultState).toEqual(1) }) test('store source with event as target plain', () => { const foo = createStore([1, 2, 3]) const bar = createStore([4, 5, 6]) const stop = createEvent<string[]>() const baz = sample(bar, stop) foo.on(baz, (store1, store2) => [...store1, ...store2]) stop(['stop']) expect(foo.getState()).toEqual([1, 2, 3, 4, 5, 6]) }) test('store source with effect as target', () => {}) }) test('store with handler', () => { const fn = jest.fn() const stop = createEvent<string>() const s1 = createStore(0) //@ts-expect-error s1.setState(1) const s2 = sample(s1, stop, (s1, stop) => ({s1, stop})) s2.watch(value => fn(value)) expect(fn).toHaveBeenCalledTimes(0) //@ts-expect-error s1.setState(2) stop('x') expect(argumentHistory(fn)).toEqual([{s1: 2, stop: 'x'}]) expect(fn).toHaveBeenCalledTimes(1) }) test('store x store x handler', () => { const fn = jest.fn() const stop = createStore(false) const s1 = createStore(0) //@ts-expect-error s1.setState(1) const s2 = sample(s1, stop, (s1, stop) => ({s1, stop})) s2.watch(value => fn(value)) expect(argumentHistory(fn)).toEqual([{s1: 1, stop: false}]) //@ts-expect-error s1.setState(2) //@ts-expect-error s1.setState(0) //@ts-expect-error stop.setState(true) expect(argumentHistory(fn)).toEqual([ {s1: 1, stop: false}, {s1: 0, stop: true}, ]) expect(fn).toHaveBeenCalledTimes(2) }) }) test('array target', () => { const fn1 = jest.fn() const fn2 = jest.fn() const store = createStore(0) const trigger = createEvent() const t1 = createEvent() const t2 = createEvent() t1.watch(fn1) t2.watch(fn2) sample({ source: store, clock: trigger, target: [t1, t2], }) trigger() expect(argumentHistory(fn1)).toEqual([0]) expect(argumentHistory(fn2)).toEqual([0]) }) test('validate shape', () => { expect(() => { const clock = createEvent() //@ts-expect-error sample(0, clock) }).toThrowErrorMatchingInlineSnapshot(`"expect first argument be an object"`) }) test('source shape support', () => { const sampled = sample({ source: { source: createStore(0), }, clock: createEvent(), }) expect(is.event(sampled)).toBe(true) }) describe('it works without source', () => { test('it works with clock unit', () => { const fn = jest.fn() const clockA = createEvent<number>() const target = createEvent<number>() target.watch(fn) const result = sample({ clock: clockA, target, }) clockA(1) expect(result === target).toBe(true) expect(argumentHistory(fn)).toMatchInlineSnapshot(` Array [ 1, ] `) }) test('it works with clock array', () => { const fn = jest.fn() const clockA = createEvent<number>() const clockB = createEvent<number>() const target = createEvent<number>() target.watch(fn) const result = sample({ clock: [clockA, clockB], target, }) clockA(1) clockB(4) expect(result === target).toBe(true) expect(argumentHistory(fn)).toMatchInlineSnapshot(` Array [ 1, 4, ] `) }) }) describe('validation', () => { test('valid case without clock', () => { const source = createEvent<any>() const target = createEffect((_: any) => {}) expect(() => { sample({source, target}) }).not.toThrow() }) test('valid case without source', () => { const clock = createEvent<any>() const target = createEffect((_: any) => {}) expect(() => { sample({clock, target}) }).not.toThrow() }) test('source validation', () => { const target = createEffect((_: any) => {}) expect(() => { //@ts-expect-error sample({source: undefined, target}) }).toThrowErrorMatchingInlineSnapshot(`"sample: source should be defined"`) }) test('clock validation', () => { const target = createEffect((_: any) => {}) expect(() => { //@ts-expect-error sample({clock: undefined, target}) }).toThrowErrorMatchingInlineSnapshot(`"sample: clock should be defined"`) }) test('no source no clock', () => { const target = createEffect((_: any) => {}) expect(() => { //@ts-expect-error sample({target}) }).toThrowErrorMatchingInlineSnapshot( `"sample: either source or clock should be defined"`, ) }) }) describe('event/effect sampling behavior (issue #633)', () => { test('event behavior', () => { const fn = jest.fn() const triggerEvent = createEvent() const targetFx = createEffect(() => {}) const initEvent = createEvent() sample({ clock: triggerEvent, target: [initEvent.prepend(() => 1), initEvent.prepend(() => 2)], }) sample({ clock: initEvent, filter: targetFx.pending.map(val => !val), target: targetFx, }) targetFx.watch(params => fn(params)) triggerEvent() /* [effect] targetFx 2 [effect] targetFx.done {params: 2, result: undefined} */ expect(argumentHistory(fn)).toEqual([2]) }) test('effect behavior', () => { const fn = jest.fn() const triggerEffect = createEvent() const targetFx = createEffect(() => {}) const initFx = createEffect(() => {}) sample({ clock: triggerEffect, target: [initFx.prepend(() => 1), initFx.prepend(() => 2)], }) sample({ clock: initFx, filter: targetFx.pending.map(val => !val), target: targetFx, }) targetFx.watch(params => fn(params)) triggerEffect() /* [effect] targetFx 1 [effect] targetFx 2 [effect] targetFx.done {params: 1, result: undefined} [effect] targetFx.done {params: 2, result: undefined} */ expect(argumentHistory(fn)).toEqual([1, 2]) }) })
the_stack
import { Component, OnInit } from '@angular/core'; import { IdprestapiService } from '../idprestapi.service'; import { IdpService } from '../idp-service.service'; import { IdpdataService } from '../idpdata.service'; @Component({ selector: 'app-approve-release', templateUrl: './approve-release.component.html', styleUrls: ['./approve-release.component.css'] }) export class ApproveReleaseComponent implements OnInit { constructor(public idpdataService: IdpdataService, private idpService: IdpService, private idprestapiService: IdprestapiService) { if (this.data === undefined) { this.data = { "applicationName": this.idpdataService.appName, "approvedArtifact": [], "environmentName": "", "importedArtifact": [], "pipelineName": this.idpdataService.pipelineName, "releaseNumber": "" }; this.outputData = { "applicationName": this.idpdataService.appName, "approvedArtifact": [], "environmentName": "", "importedArtifact": [], "pipelineName": this.idpdataService.pipelineName, "releaseNumber": "" }; } this.getReleaseAndEnvironment(); } ngOnInit() { } data: any; update: boolean; approve = ""; envList = []; release = []; releaseList = []; approvedList = []; importedList = []; disapproveList = ['Bangalore', 'Chennai']; extraMultiselectSettings = { enableSearchFilter: true, selectAllText: 'Select All', unSelectAllText: 'UnSelect All' }; arraylist = []; importedarrayList = []; approvearrayList = []; importedSelected: any = []; approveSelected: any = []; outputDisapproveRemark: any; outputApproveRemark: any; displayimportedSelected: any = []; displayapproveSelected: any = []; outputData: any getReleaseAndEnvironment() { this.idpdataService.loading = true; this.idprestapiService.getReleasesApprovePortal().then(response => { let resp = response.json(); //alert(resp); console.log(resp); let errorMsg = resp.errorMessage; // console.log("required"+JSON.stringify(resp)); this.release = JSON.parse(resp.resource).releasePipeline[0].release; this.envList = JSON.parse(resp.resource).accessEnvironmentList; for (var i = 0; i < this.release.length; i++) { //push into release list to show in dropdown this.releaseList.push(this.release[i].releaseNumber) } console.log(this.release); this.idpdataService.loading = false; }) } getReleaseNamesApprovePortal() { } getArtifactsApprovePortal() { console.log("In artifacts!!"); if (this.data.environmentName !== "") { this.idpdataService.loading = true; this.data.importedArtifact = []; this.data.approvedArtifact = []; this.idprestapiService.getArtifactsApprovePortal(this.data).then(response => { let resp = response.json(); //alert(resp); console.log(resp); let errorMsg = resp.errorMessage; // console.log("required"+JSON.stringify(resp)); console.log(resp.resource); this.importedarrayList = JSON.parse(resp.resource).importedArtifact; this.approvearrayList = JSON.parse(resp.resource).approvedArtifact; var temp = JSON.parse(resp.resource).approvedArtifact; this.approvedList = []; //multiselect box dosent take simple array of strings as input, hence convert it to array of objects for (var i = 0; i < temp.length; i++) { this.approvedList.push({ "id": i, "itemName": temp[i].artifactName }); } temp = JSON.parse(resp.resource).importedArtifact; this.importedList = []; for (var i = 0; i < temp.length; i++) { this.importedList.push({ "id": i, "itemName": temp[i].artifactName }); } console.log(this.importedList); console.log(this.release); this.idpdataService.loading = false; }) } } updateArtifacts() { console.log(this.outputData.importedArtifact); console.log(this.outputData.approvedArtifact); if ((this.outputData.importedArtifact.length !== 0 && this.outputData.importedArtifact !== undefined) || (this.outputData.approvedArtifact.length !== 0 && this.outputData.approvedArtifact !== undefined)) { // this.data.applicationName=this.IdpdataService.appName; // this.data.pipelineName=this.IdpdataService.pipelineName; // var temp = this.data.importedArtifact; // this.data.importedArtifact = []; // this.update=false; // if(temp!== undefined){ // for(var i = 0; i < temp.length; i++){ // this.data.importedArtifact.push(temp[i].itemName); // } // } // temp = this.data.approvedArtifact; // this.data.approvedArtifact = []; // if(temp!== undefined){ // for(var i = 0; i < temp.length; i++){ // this.data.approvedArtifact.push(temp[i].itemName); // } // } this.outputData.environmentName = this.data.environmentName; this.outputData.releaseNumber = this.data.releaseNumber; this.idpdataService.loading = true; this.idprestapiService.updateArtifacts(this.outputData).then(response => { let resp = response.json(); //alert(resp); console.log(resp); let errorMsg = resp.errorMessage; // console.log("required"+JSON.stringify(resp)); if (resp.resource === "Updated Successfully!!!") { this.update = true; } else { alert("Update unsuccessful!! Please update again."); } console.log(this.release); this.idpdataService.loading = false; }) } else { alert("Please Select artifacts!!"); } this.displayapproveSelected = this.approveSelected; this.displayimportedSelected = this.importedSelected; this.importedSelected = []; this.outputData.importedArtifact = []; // this.outputApproveRemark; this.approveSelected = []; this.outputData.approvedArtifact = []; // this.outputDisapproveRemark; } updateArtifactRemark() { this.outputData.environmentName = this.data.environmentName; this.outputData.releaseNumber = this.data.releaseNumber; console.log(this.outputData); } updateFalse() { this.update = false; this.data = { "applicationName": this.idpdataService.appName, "approvedArtifact": [], "environmentName": "", "importedArtifact": [], "pipelineName": this.idpdataService.pipelineName, "releaseNumber": "" }; this.approve = ""; } clearData() { this.data.approvedArtifact = []; this.data.importedArtifact = []; this.data.environmentName = ""; this.approve = ""; this.importedList = []; this.approvedList = []; } onItemSelect(item: any) { console.log(item); var temp = this.importedarrayList; for (var i = 0; i < temp.length; i++) { if (temp[i].artifactName == item.itemName) this.importedSelected.push(temp[i]); } let artifactJson = { "artifactName": '', "artifactDetails": [{ "status": '', "remark": '' }] } artifactJson.artifactName = item.itemName; artifactJson.artifactDetails[0].status = 'approved' this.outputData.importedArtifact.push(artifactJson); //this.outputApproveRemark.push(''); //this.importedSelected.push(item.itemName); //this.buildInfo.postBuildScript.dependentPipelineList.push(item.itemName); //console.log(this.selectedItems2); } OnItemDeSelect(item: any) { console.log(item); var temp = this.importedSelected; for (var i = 0; i < temp.length; i++) { if (temp[i].artifactName == item.itemName) { this.importedSelected.splice(i, 1); break; } } for (var i = 0; i < this.outputData.importedArtifact.length; i++) { if (this.outputData.importedArtifact[i].artifactName === item.itemName) { //console.log("Deteleted artifact: " + this.outputData.approvedArtifact[i].artifactName); this.outputData.importedArtifact.splice(i, 1); //this.outputApproveRemark.splice(i,1); break; } } /* var i = this.buildInfo.postBuildScript.dependentPipelineList.indexOf(item.itemName); if (i !== -1) { this.buildInfo.postBuildScript.dependentPipelineList.splice(i, 1); console.log("Item Found"); } */ } onSelectAll(items: any) { console.log(items); this.importedSelected = []; this.outputData.importedArtifact = []; //this.outputApproveRemark = []; var temp = this.importedarrayList; for (var i = 0; i < temp.length; i++) { this.importedSelected.push(temp[i]); } for (var item of items) { let artifactJson = { "artifactName": '', "artifactDetails": [{ "status": '', "remark": '' }] } artifactJson.artifactName = item.itemName; artifactJson.artifactDetails[0].status = 'approved' this.outputData.importedArtifact.push(artifactJson); //this.outputApproveRemark.push(''); } /* for (var item of items) { this.buildInfo.postBuildScript.dependentPipelineList.push(item.itemName); } */ } onDeSelectAll(items: any) { console.log(items); this.importedSelected = []; this.outputData.importedArtifact = []; //this.outputApproveRemark = []; //this.buildInfo.postBuildScript.dependentPipelineList = []; } onItemSelectDisapprove(item: any) { console.log(item); var temp = this.approvearrayList; for (var i = 0; i < temp.length; i++) { if (temp[i].artifactName == item.itemName) this.approveSelected.push(temp[i]); } let artifactJson = { "artifactName": '', "artifactDetails": [{ "status": '', "remark": '' }] } artifactJson.artifactName = item.itemName; artifactJson.artifactDetails[0].status = 'disapproved' this.outputData.approvedArtifact.push(artifactJson); //this.outputDisapproveRemark.push(''); //console.log(artifactJson); //this.importedSelected.push(item.itemName); //this.buildInfo.postBuildScript.dependentPipelineList.push(item.itemName); //console.log(this.selectedItems2); } OnItemDeSelectDisapprove(item: any) { console.log(item); var temp = this.approveSelected; for (var i = 0; i < temp.length; i++) { if (temp[i].artifactName == item.itemName) { this.approveSelected.splice(i, 1); break; } } //console.log("Before deleting: " + this.outputData.approvedArtifact.length ); for (var i = 0; i < this.outputData.approvedArtifact.length; i++) { if (this.outputData.approvedArtifact[i].artifactName === item.itemName) { //console.log("Deteleted artifact: " + this.outputData.approvedArtifact[i].artifactName); this.outputData.approvedArtifact.splice(i, 1); //this.outputDisapproveRemark.splice(i,1); break; } } //console.log("After deleting: " + this.outputData.approvedArtifact.length ); /* var i = this.buildInfo.postBuildScript.dependentPipelineList.indexOf(item.itemName); if (i !== -1) { this.buildInfo.postBuildScript.dependentPipelineList.splice(i, 1); console.log("Item Found"); } */ } onSelectAllDisapprove(items: any) { console.log(items); this.approveSelected = []; this.outputData.approvedArtifact = []; //this.outputDisapproveRemark = []; var temp = this.approvearrayList; for (var i = 0; i < temp.length; i++) { this.approveSelected.push(temp[i]); } for (var item of items) { let artifactJson = { "artifactName": '', "artifactDetails": [{ "status": '', "remark": '' }] } artifactJson.artifactName = item.itemName; artifactJson.artifactDetails[0].status = 'disapproved' this.outputData.approvedArtifact.push(artifactJson); //this.outputDisapproveRemark.push(''); } /* for (var item of items) { this.buildInfo.postBuildScript.dependentPipelineList.push(item.itemName); } */ } onDeSelectAllDisapprove(items: any) { console.log(items); this.approveSelected = []; this.outputData.approvedArtifact = []; //this.outputDisapproveRemark = []; //this.buildInfo.postBuildScript.dependentPipelineList = []; } insertDisapproveRemark(remark: any) { for (var count = 0; count < this.outputData.approvedArtifact.length; count++) { this.outputData.approvedArtifact[count].artifactDetails[0].remark = remark; console.log(this.outputData); } } insertApproveRemark(remark: any) { for (var count = 0; count < this.outputData.importedArtifact.length; count++) { this.outputData.importedArtifact[count].artifactDetails[0].remark = remark; console.log(this.outputData); } } clearArtifact(){ this.approveSelected = []; this.outputData.approvedArtifact = []; this.importedSelected = []; this.outputData.importedArtifact = []; this.data.importedArtifact=[]; this.data.approvedArtifact=[]; } }
the_stack
import React, { ComponentType, HTMLAttributes, ReactNode, useCallback, useMemo, useState } from 'react'; import Popover from 'src/components/Popover'; import ConfigContext from 'src/components/ConfigProvider/ConfigContext'; import useLocale from 'src/components/LocaleProvider/useLocale'; import { Override, Size } from 'src/type'; import { ChildrenMap, groupChildrenAsDataSource, Key, SubGroupMap } from 'src/hooks/group'; import { getPopoverConfigFromContext } from 'src/hooks/usePopoverConfig'; import useUncontrolled from 'src/hooks/useUncontrolled'; import useInitial from 'src/hooks/useInitial'; import noop from 'src/utils/noop'; import deprecatedLog from 'src/utils/deprecatedLog'; import { onceWarning } from 'src/utils/warning'; import isObject from 'src/utils/isObject'; import isEmpty from 'src/utils/isEmpty'; import { PureOption } from './Option'; import Group from './Group'; import Extra from './Extra'; import { SelectWrap, SelectSearchInput, SSelector, Arrow, BlockMenu, MenuWrap, EmptyContentWrapper, selectorContentCls, FooterWrap } from './style'; import SelectContext from './SelectContext'; import LOCALE from './locale/zh_CN'; export const deprecatedLogForPopover = deprecatedLog('Select popover', 'popoverProps'); const warnLogForVirtualList = onceWarning('Select virtualList only valid when use options'); const warnLogForCustomHeight = onceWarning( 'CustomStyle.optionListMaxHeight is invalid when use virtualList, please use virtualList.height' ); const warnLogForSearchProps = onceWarning(`Don't use item.props in custom search, just use item as props.`); const groupOptions = { itemTag: 'isMenuItem', subGroupTag: 'isMenuSubMenu', itemKeyName: 'value', subGroupKeyName: 'groupKey', displayName: 'label', subGroupName: 'children', ItemComponent: PureOption, SubGroupComponent: Group }; type PopoverProps = any; export interface SelectProps { /** 当前值,controlled */ value?: Key; /** 默认值,uncontrolled */ defaultValue?: Key; /** 无选项时显示内容 */ placeholder?: ReactNode; /** 修改时的回调 */ onChange?: (value: Key | Key[]) => void; /** 快速设置选项 */ options?: { /** 选项展示 */ label?: ReactNode; /** 选项 value,不可重复 */ value: Key; }[]; /** 在尾部增加附加内容,会脱离选项流容器,超高度时不会一起滚动,如需在选项中嵌入附加内容,可使用 Select.Extra */ extra?: { content: ReactNode } | ReactNode | ((hidePopup: () => void) => ReactNode); /** 是否多选 */ multiple?: boolean; /** 是否显示全选 */ showSelectAll?: boolean; /** 是否禁用 */ disabled?: boolean; /** * 如何渲染选中项的展示 * @param value - 当前 select 的值 * @param valueChild - 当前值对应的展示内容(为性能考虑,只提供前 20 个选项,如果需要获取所有,请自行拿 value 获取) */ renderContent?: (value?: Key | Key[], valueChild?: ReactNode[]) => ReactNode; /** * 自定义渲染选择器 * @param {node} content - 渲染的内容 * @param {bool} visible - 当前的select下拉是否展示 */ renderSelector?: (content: ReactNode, visible: boolean) => ReactNode; /** * 自定义渲染弹出内容 * @param {Object} options - 配置 * @param {function} options.handleVisible - 处理弹出层的显示隐藏 * @param {function} options.onChange - value 变化回调 * @param options.value - select 的当前值 */ renderPopup?: ( options: { handleVisible: (visible: boolean) => void; onChange: (v: Key | Key[]) => void; value?: Key | Key[]; /** @ignore */ children?: ReactNode; } & Pick<SelectProps, 'multiple' | 'extra' | 'search' | 'options'> ) => ReactNode; /** * - 是否展示搜索框,可以为 true 或者 Object * - 为 Object 时可传入 handleSearch 对搜索筛选进行自定义 */ search?: | true | { /** * 自定义搜索 * @argument searchValue - 搜索的值 * @argument value - option的值 */ handleSearch?: (searchValue: string, value: Key, s: any) => boolean; /** 搜索值 受控 */ searchValue?: string; /** 默认搜索值 非受控 */ defaultSearchValue?: string; /** 搜索值变化回调 */ onSearchValueChange?: (searchValue: string) => void; }; /** 尺寸 */ size?: Size; /** * 弹出层的popover props * @deprecated 请使用popoverProps替换 */ popover?: PopoverProps; /** 弹出层的popover props */ popoverProps?: PopoverProps; /** * @deprecated 请勿使用 * @ignore */ onVisibleChange?: (visible?: boolean) => void; /** @ignore */ locale?: typeof LOCALE; /** * 自定义样式 */ customStyle?: { /** 列表最大高度 */ optionListMaxHeight?: number | string; /** 弹出菜单的最大宽度 */ popupMaxWidth?: string; /** 弹出菜单的宽度 */ popupWidth?: string; }; /** * 可选性为空时展示内容 */ emptyContent?: ReactNode; /** * 启用虚拟列表,仅使用 options 时生效 */ virtualList?: | boolean | { simple?: true; height?: number; }; } const Selector = ({ size, disabled, multiple, placeholder, renderContent, renderSelector, renderPopup, value, visible, locale, dataSource, ...rest }: Pick< SelectProps, 'size' | 'disabled' | 'multiple' | 'placeholder' | 'renderContent' | 'renderSelector' | 'renderPopup' | 'value' > & { visible: boolean; locale: typeof LOCALE; dataSource: ReturnType<typeof groupChildrenAsDataSource>; }) => { placeholder = useMemo(() => placeholder || locale.placeholder, [locale.placeholder, placeholder]); const defaultRenderContent = useCallback( (value, valueChild) => { if (!multiple) { if (value === undefined) { return placeholder; } else { return valueChild; } } else { if (value && value.length) { return `${locale.selected}${value.length}${locale.items}`; } else { return placeholder; } } }, [locale.items, locale.selected, multiple, placeholder] ); const getContent = useCallback(() => { const [, , , , childrenMap = new Map()] = dataSource; let valueChild; const getValueChild = (v?: Key) => { return childrenMap.has(v) ? childrenMap.get(v) : v; }; if (!multiple) { valueChild = getValueChild(value); } else { const _value = ((value as unknown) as Key[]) ? [...((value as unknown) as Key[])] : []; // only get the top twenty item child for better performance if (_value.length > 20) { _value.length = 20; } valueChild = _value.map(getValueChild); } if (renderContent) { return renderContent(value, valueChild); } else { return defaultRenderContent(value, valueChild); } }, [dataSource, defaultRenderContent, multiple, renderContent, value]); let content = useMemo(getContent, [getContent]); // 自定义渲染弹层时,开发者可能不传入 options 和 children,导致 content memo deps 不触发变更,故强制更新 if (renderPopup) content = getContent(); if (renderSelector) { const selector = renderSelector(content, visible) || <></>; return React.isValidElement(selector) ? React.cloneElement(selector, rest) : null; } const title = typeof content === 'string' ? content : undefined; return ( <SSelector styleType="border" size={size} disabled={disabled} title={title} {...rest}> <div className={selectorContentCls} key="content"> {content} </div> <Arrow key="icon" type={visible ? 'arrow-up' : 'arrow-down'} /> </SSelector> ); }; const Popup = ({ extra, customStyle = {}, search, multiple, emptyContent, showSelectAll, value, renderPopup, options, children, onChange, locale, handleVisibleChange, hidePopup, dataSource, searchValue, setSearchValue, virtualList }: Pick< SelectProps, | 'extra' | 'customStyle' | 'search' | 'multiple' | 'emptyContent' | 'showSelectAll' | 'value' | 'renderPopup' | 'options' | 'virtualList' > & Required<Pick<SelectProps, 'onChange'>> & { children?: ReactNode; locale: typeof LOCALE; handleVisibleChange: (visible: boolean) => void; hidePopup: () => void; dataSource: ReturnType<typeof groupChildrenAsDataSource>; searchValue: string; setSearchValue: (searchValue: string) => void; }) => { const handleChange = useCallback( (value: Key[]) => { if (!multiple) { handleVisibleChange(false); onChange(value[0]); } else { onChange(value); } }, [multiple, onChange, handleVisibleChange] ); const handleSearchInput = useCallback( e => { setSearchValue(e.target.value); }, [setSearchValue] ); const finalExtra = useMemo(() => { if (typeof extra === 'function') { return <Extra>{extra(hidePopup)}</Extra>; } else if (!isEmpty(extra)) { if (React.isValidElement(extra)) { return <Extra>{extra}</Extra>; } else if (isObject(extra)) { const { content, ...rest } = extra as { content: ReactNode }; return <Extra {...rest}>{content}</Extra>; } } }, [extra, hidePopup]); if (renderPopup) { return ( <> {renderPopup({ handleVisible: handleVisibleChange, onChange, value, multiple, extra, search, children, options })} </> ); } const maxWidth = customStyle.popupMaxWidth ? customStyle.popupMaxWidth : 'none'; const newCustomStyle = { ...customStyle }; if (virtualList) { newCustomStyle.optionListMaxHeight = 'none'; if ('optionListMaxHeight' in newCustomStyle) warnLogForCustomHeight(); } const renderEmptyContent = () => { return emptyContent || <EmptyContentWrapper>{locale.emptyTip}</EmptyContentWrapper>; }; return ( <MenuWrap> {search && <SelectSearchInput onChange={handleSearchInput} value={searchValue} status="default" />} {children || options?.length ? ( <BlockMenu onChange={handleChange} customStyle={newCustomStyle} menuCustomStyle={{ maxWidth }} dataSource={dataSource} multiple={multiple} showSelectAll={showSelectAll} selectedKeys={multiple ? value : [value]} virtualList={options ? virtualList : false} /> ) : ( <BlockMenu>{renderEmptyContent()}</BlockMenu> )} {finalExtra ? <FooterWrap>{finalExtra}</FooterWrap> : null} </MenuWrap> ); }; const groupOptionsAsDataSource = < T extends { disabled?: boolean; key?: Key; [key: string]: Key | ReactNode | unknown; } >( options: T[], globalDisabled = false, { subGroupName, displayName, itemKeyName, subGroupKeyName, ItemComponent, SubGroupComponent }: { subGroupName: string; displayName: string; itemKeyName: string; subGroupKeyName: string; ItemComponent: ComponentType<any>; SubGroupComponent: ComponentType<any>; } = { subGroupName: 'children', displayName: 'label', itemKeyName: 'itemKey', subGroupKeyName: 'subGroupKey', ItemComponent: () => null, SubGroupComponent: () => null }, searchValue: string, handleSearch: (value: Key, props: any) => boolean ): [Key[], Key[], ReactNode[], SubGroupMap, ChildrenMap] => { const subGroupMap: SubGroupMap = new Map(); const childrenMap: ChildrenMap = new Map(); const isValidKey = (v: any) => { return typeof v === 'string' || typeof v === 'number'; }; const group = (options: T[], disabled = false, prefixKey: Key): [Key[], Key[], ReactNode[]] => { const validKeys: Key[] = []; const disabledKeys: Key[] = []; const renderChildren: ReactNode[] = []; options.forEach((child, i) => { const subChildren = child[subGroupName] as T[]; if (subChildren) { const key = (child[subGroupKeyName] as Key) || child.key || `${prefixKey}-${i}`; const reactKey = child.key || isValidKey(child[subGroupKeyName]) ? child[subGroupKeyName] : `${prefixKey}-${i}`; const isDisabled = disabled || child.disabled; const [subValidKeys, subDisabledKeys, subRenderChildren] = group(subChildren, isDisabled, key); subGroupMap.set(key, { validKeys: subValidKeys, disabledKeys: subDisabledKeys }); validKeys.push(...subValidKeys); disabledKeys.push(...subDisabledKeys); const visible = searchValue ? !!subRenderChildren.length : true; if (visible) { renderChildren.push( <SubGroupComponent key={reactKey} {...child} {...{ disabled: globalDisabled || isDisabled, [subGroupKeyName]: key }} > {subRenderChildren} </SubGroupComponent> ); } } else { const key = (child[itemKeyName] === undefined ? child.key : child[itemKeyName]) as Key; const reactKey = child.key || isValidKey(child[itemKeyName]) ? child[itemKeyName] : `${prefixKey}-${i}`; const isDisabled = disabled || child.disabled; if (isDisabled) { disabledKeys.push(key); } else { validKeys.push(key); } const display = (child[displayName] as ReactNode) ?? key; const visible = searchValue ? handleSearch(key, child) : true; if (visible) { renderChildren.push( <ItemComponent key={reactKey} {...child} {...{ disabled: globalDisabled || isDisabled, [itemKeyName]: key }} > {display} </ItemComponent> ); } childrenMap.set(key, display); } }); return [validKeys, disabledKeys, renderChildren]; }; return [...group(options, false, 'group-root'), subGroupMap, childrenMap]; }; const Select = ({ size = 'md', value: _value, defaultValue, onChange: _onChange, onVisibleChange = noop, disabled, search, multiple, renderContent, renderSelector, placeholder, locale: _locale, options, children, emptyContent, showSelectAll, extra, customStyle, popover, popoverProps, renderPopup, virtualList, ...rest }: SelectProps & Override<HTMLAttributes<HTMLDivElement>, SelectProps>) => { const [value, onChange] = useUncontrolled(_value, defaultValue, _onChange); const [visible, setVisible] = useState(false); const locale = useLocale(LOCALE, 'Select', _locale); if (search === true) search = {}; const [searchValue, setSearchValue] = useUncontrolled( search?.searchValue, search?.defaultSearchValue || '', search?.onSearchValueChange ); useInitial(() => { if (popover) deprecatedLogForPopover(); if (virtualList && !options) warnLogForVirtualList(); }); const handleSearch = useCallback( (value: Key, props: any) => { if (!search || !searchValue) { return true; } if (typeof search === 'object' && search.handleSearch) { // assign props for forward compatible const beforeProps = { ...props }; if (options) beforeProps.children = beforeProps.label ?? beforeProps.value; const itemInfo = { ...props }; if (!('props' in itemInfo)) { Object.defineProperty(itemInfo, 'props', { get: () => { warnLogForSearchProps(); return beforeProps; } }); } return search.handleSearch(searchValue, value, itemInfo); } else { // use label for options case const children = options ? props.label : props.children; return ( (value + '').indexOf(searchValue) >= 0 || (children && typeof children === 'string' && children.indexOf(searchValue) >= 0) ); } }, [options, search, searchValue] ); const childrenDataSource = useMemo( () => (options ? [] : groupChildrenAsDataSource(children, disabled, groupOptions)), [children, disabled, options] ); const optionsDataSource = useMemo( () => (options ? groupOptionsAsDataSource(options, disabled, groupOptions, searchValue, handleSearch) : []), [disabled, handleSearch, options, searchValue] ); virtualList = useMemo(() => (options ? virtualList : false), [options, virtualList]); const dataSource = useMemo( () => (options ? optionsDataSource : childrenDataSource) as | ReturnType<typeof groupOptionsAsDataSource> | ReturnType<typeof groupChildrenAsDataSource>, [options, childrenDataSource, optionsDataSource] ); const handleVisibleChange = useCallback( (open: boolean) => { setVisible(open); onVisibleChange(open); }, [onVisibleChange] ); const hidePopup = useCallback(() => handleVisibleChange(false), [handleVisibleChange]); return ( <ConfigContext.Consumer> {configContext => { const popupConfigProps = getPopoverConfigFromContext(configContext); return ( <SelectContext.Provider value={{ hidePopup, handleSearch, searchValue }} > <SelectWrap {...rest}> <Popover onVisibleChange={handleVisibleChange} placement="bottomLeft" trigger={['click']} {...popupConfigProps} visible={visible} {...popover} {...popoverProps} popup={ <Popup {...{ extra, customStyle, search, multiple, emptyContent, showSelectAll, value, renderPopup, options, children, onChange, locale, handleVisibleChange, hidePopup, dataSource, searchValue, setSearchValue, virtualList }} /> } forceRender={false} > <Selector {...{ size, disabled, multiple, placeholder, renderContent, renderSelector, renderPopup, value, visible, locale, dataSource }} /> </Popover> </SelectWrap> </SelectContext.Provider> ); }} </ConfigContext.Consumer> ); }; export default Select;
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PublicIPAddresses } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { NetworkManagementClient } from "../networkManagementClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { PublicIPAddress, PublicIPAddressesListAllNextOptionalParams, PublicIPAddressesListAllOptionalParams, PublicIPAddressesListNextOptionalParams, PublicIPAddressesListOptionalParams, PublicIPAddressesListVirtualMachineScaleSetPublicIPAddressesNextOptionalParams, PublicIPAddressesListVirtualMachineScaleSetPublicIPAddressesOptionalParams, PublicIPAddressesListVirtualMachineScaleSetVMPublicIPAddressesNextOptionalParams, PublicIPAddressesListVirtualMachineScaleSetVMPublicIPAddressesOptionalParams, PublicIPAddressesDeleteOptionalParams, PublicIPAddressesGetOptionalParams, PublicIPAddressesGetResponse, PublicIPAddressesCreateOrUpdateOptionalParams, PublicIPAddressesCreateOrUpdateResponse, TagsObject, PublicIPAddressesUpdateTagsOptionalParams, PublicIPAddressesUpdateTagsResponse, PublicIPAddressesListAllResponse, PublicIPAddressesListResponse, PublicIPAddressesListVirtualMachineScaleSetPublicIPAddressesResponse, PublicIPAddressesListVirtualMachineScaleSetVMPublicIPAddressesResponse, PublicIPAddressesGetVirtualMachineScaleSetPublicIPAddressOptionalParams, PublicIPAddressesGetVirtualMachineScaleSetPublicIPAddressResponse, PublicIPAddressesListAllNextResponse, PublicIPAddressesListNextResponse, PublicIPAddressesListVirtualMachineScaleSetPublicIPAddressesNextResponse, PublicIPAddressesListVirtualMachineScaleSetVMPublicIPAddressesNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing PublicIPAddresses operations. */ export class PublicIPAddressesImpl implements PublicIPAddresses { private readonly client: NetworkManagementClient; /** * Initialize a new instance of the class PublicIPAddresses class. * @param client Reference to the service client */ constructor(client: NetworkManagementClient) { this.client = client; } /** * Gets all the public IP addresses in a subscription. * @param options The options parameters. */ public listAll( options?: PublicIPAddressesListAllOptionalParams ): PagedAsyncIterableIterator<PublicIPAddress> { const iter = this.listAllPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAllPagingPage(options); } }; } private async *listAllPagingPage( options?: PublicIPAddressesListAllOptionalParams ): AsyncIterableIterator<PublicIPAddress[]> { let result = await this._listAll(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAllNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listAllPagingAll( options?: PublicIPAddressesListAllOptionalParams ): AsyncIterableIterator<PublicIPAddress> { for await (const page of this.listAllPagingPage(options)) { yield* page; } } /** * Gets all public IP addresses in a resource group. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ public list( resourceGroupName: string, options?: PublicIPAddressesListOptionalParams ): PagedAsyncIterableIterator<PublicIPAddress> { const iter = this.listPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceGroupName, options); } }; } private async *listPagingPage( resourceGroupName: string, options?: PublicIPAddressesListOptionalParams ): AsyncIterableIterator<PublicIPAddress[]> { let result = await this._list(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, options?: PublicIPAddressesListOptionalParams ): AsyncIterableIterator<PublicIPAddress> { for await (const page of this.listPagingPage(resourceGroupName, options)) { yield* page; } } /** * Gets information about all public IP addresses on a virtual machine scale set level. * @param resourceGroupName The name of the resource group. * @param virtualMachineScaleSetName The name of the virtual machine scale set. * @param options The options parameters. */ public listVirtualMachineScaleSetPublicIPAddresses( resourceGroupName: string, virtualMachineScaleSetName: string, options?: PublicIPAddressesListVirtualMachineScaleSetPublicIPAddressesOptionalParams ): PagedAsyncIterableIterator<PublicIPAddress> { const iter = this.listVirtualMachineScaleSetPublicIPAddressesPagingAll( resourceGroupName, virtualMachineScaleSetName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listVirtualMachineScaleSetPublicIPAddressesPagingPage( resourceGroupName, virtualMachineScaleSetName, options ); } }; } private async *listVirtualMachineScaleSetPublicIPAddressesPagingPage( resourceGroupName: string, virtualMachineScaleSetName: string, options?: PublicIPAddressesListVirtualMachineScaleSetPublicIPAddressesOptionalParams ): AsyncIterableIterator<PublicIPAddress[]> { let result = await this._listVirtualMachineScaleSetPublicIPAddresses( resourceGroupName, virtualMachineScaleSetName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listVirtualMachineScaleSetPublicIPAddressesNext( resourceGroupName, virtualMachineScaleSetName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listVirtualMachineScaleSetPublicIPAddressesPagingAll( resourceGroupName: string, virtualMachineScaleSetName: string, options?: PublicIPAddressesListVirtualMachineScaleSetPublicIPAddressesOptionalParams ): AsyncIterableIterator<PublicIPAddress> { for await (const page of this.listVirtualMachineScaleSetPublicIPAddressesPagingPage( resourceGroupName, virtualMachineScaleSetName, options )) { yield* page; } } /** * Gets information about all public IP addresses in a virtual machine IP configuration in a virtual * machine scale set. * @param resourceGroupName The name of the resource group. * @param virtualMachineScaleSetName The name of the virtual machine scale set. * @param virtualmachineIndex The virtual machine index. * @param networkInterfaceName The network interface name. * @param ipConfigurationName The IP configuration name. * @param options The options parameters. */ public listVirtualMachineScaleSetVMPublicIPAddresses( resourceGroupName: string, virtualMachineScaleSetName: string, virtualmachineIndex: string, networkInterfaceName: string, ipConfigurationName: string, options?: PublicIPAddressesListVirtualMachineScaleSetVMPublicIPAddressesOptionalParams ): PagedAsyncIterableIterator<PublicIPAddress> { const iter = this.listVirtualMachineScaleSetVMPublicIPAddressesPagingAll( resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listVirtualMachineScaleSetVMPublicIPAddressesPagingPage( resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, options ); } }; } private async *listVirtualMachineScaleSetVMPublicIPAddressesPagingPage( resourceGroupName: string, virtualMachineScaleSetName: string, virtualmachineIndex: string, networkInterfaceName: string, ipConfigurationName: string, options?: PublicIPAddressesListVirtualMachineScaleSetVMPublicIPAddressesOptionalParams ): AsyncIterableIterator<PublicIPAddress[]> { let result = await this._listVirtualMachineScaleSetVMPublicIPAddresses( resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listVirtualMachineScaleSetVMPublicIPAddressesNext( resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listVirtualMachineScaleSetVMPublicIPAddressesPagingAll( resourceGroupName: string, virtualMachineScaleSetName: string, virtualmachineIndex: string, networkInterfaceName: string, ipConfigurationName: string, options?: PublicIPAddressesListVirtualMachineScaleSetVMPublicIPAddressesOptionalParams ): AsyncIterableIterator<PublicIPAddress> { for await (const page of this.listVirtualMachineScaleSetVMPublicIPAddressesPagingPage( resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, options )) { yield* page; } } /** * Deletes the specified public IP address. * @param resourceGroupName The name of the resource group. * @param publicIpAddressName The name of the subnet. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, publicIpAddressName: string, options?: PublicIPAddressesDeleteOptionalParams ): 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, publicIpAddressName, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Deletes the specified public IP address. * @param resourceGroupName The name of the resource group. * @param publicIpAddressName The name of the subnet. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, publicIpAddressName: string, options?: PublicIPAddressesDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, publicIpAddressName, options ); return poller.pollUntilDone(); } /** * Gets the specified public IP address in a specified resource group. * @param resourceGroupName The name of the resource group. * @param publicIpAddressName The name of the subnet. * @param options The options parameters. */ get( resourceGroupName: string, publicIpAddressName: string, options?: PublicIPAddressesGetOptionalParams ): Promise<PublicIPAddressesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, publicIpAddressName, options }, getOperationSpec ); } /** * Creates or updates a static or dynamic public IP address. * @param resourceGroupName The name of the resource group. * @param publicIpAddressName The name of the public IP address. * @param parameters Parameters supplied to the create or update public IP address operation. * @param options The options parameters. */ async beginCreateOrUpdate( resourceGroupName: string, publicIpAddressName: string, parameters: PublicIPAddress, options?: PublicIPAddressesCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<PublicIPAddressesCreateOrUpdateResponse>, PublicIPAddressesCreateOrUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<PublicIPAddressesCreateOrUpdateResponse> => { 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, publicIpAddressName, parameters, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "azure-async-operation" }); } /** * Creates or updates a static or dynamic public IP address. * @param resourceGroupName The name of the resource group. * @param publicIpAddressName The name of the public IP address. * @param parameters Parameters supplied to the create or update public IP address operation. * @param options The options parameters. */ async beginCreateOrUpdateAndWait( resourceGroupName: string, publicIpAddressName: string, parameters: PublicIPAddress, options?: PublicIPAddressesCreateOrUpdateOptionalParams ): Promise<PublicIPAddressesCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( resourceGroupName, publicIpAddressName, parameters, options ); return poller.pollUntilDone(); } /** * Updates public IP address tags. * @param resourceGroupName The name of the resource group. * @param publicIpAddressName The name of the public IP address. * @param parameters Parameters supplied to update public IP address tags. * @param options The options parameters. */ updateTags( resourceGroupName: string, publicIpAddressName: string, parameters: TagsObject, options?: PublicIPAddressesUpdateTagsOptionalParams ): Promise<PublicIPAddressesUpdateTagsResponse> { return this.client.sendOperationRequest( { resourceGroupName, publicIpAddressName, parameters, options }, updateTagsOperationSpec ); } /** * Gets all the public IP addresses in a subscription. * @param options The options parameters. */ private _listAll( options?: PublicIPAddressesListAllOptionalParams ): Promise<PublicIPAddressesListAllResponse> { return this.client.sendOperationRequest({ options }, listAllOperationSpec); } /** * Gets all public IP addresses in a resource group. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ private _list( resourceGroupName: string, options?: PublicIPAddressesListOptionalParams ): Promise<PublicIPAddressesListResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listOperationSpec ); } /** * Gets information about all public IP addresses on a virtual machine scale set level. * @param resourceGroupName The name of the resource group. * @param virtualMachineScaleSetName The name of the virtual machine scale set. * @param options The options parameters. */ private _listVirtualMachineScaleSetPublicIPAddresses( resourceGroupName: string, virtualMachineScaleSetName: string, options?: PublicIPAddressesListVirtualMachineScaleSetPublicIPAddressesOptionalParams ): Promise< PublicIPAddressesListVirtualMachineScaleSetPublicIPAddressesResponse > { return this.client.sendOperationRequest( { resourceGroupName, virtualMachineScaleSetName, options }, listVirtualMachineScaleSetPublicIPAddressesOperationSpec ); } /** * Gets information about all public IP addresses in a virtual machine IP configuration in a virtual * machine scale set. * @param resourceGroupName The name of the resource group. * @param virtualMachineScaleSetName The name of the virtual machine scale set. * @param virtualmachineIndex The virtual machine index. * @param networkInterfaceName The network interface name. * @param ipConfigurationName The IP configuration name. * @param options The options parameters. */ private _listVirtualMachineScaleSetVMPublicIPAddresses( resourceGroupName: string, virtualMachineScaleSetName: string, virtualmachineIndex: string, networkInterfaceName: string, ipConfigurationName: string, options?: PublicIPAddressesListVirtualMachineScaleSetVMPublicIPAddressesOptionalParams ): Promise< PublicIPAddressesListVirtualMachineScaleSetVMPublicIPAddressesResponse > { return this.client.sendOperationRequest( { resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, options }, listVirtualMachineScaleSetVMPublicIPAddressesOperationSpec ); } /** * Get the specified public IP address in a virtual machine scale set. * @param resourceGroupName The name of the resource group. * @param virtualMachineScaleSetName The name of the virtual machine scale set. * @param virtualmachineIndex The virtual machine index. * @param networkInterfaceName The name of the network interface. * @param ipConfigurationName The name of the IP configuration. * @param publicIpAddressName The name of the public IP Address. * @param options The options parameters. */ getVirtualMachineScaleSetPublicIPAddress( resourceGroupName: string, virtualMachineScaleSetName: string, virtualmachineIndex: string, networkInterfaceName: string, ipConfigurationName: string, publicIpAddressName: string, options?: PublicIPAddressesGetVirtualMachineScaleSetPublicIPAddressOptionalParams ): Promise< PublicIPAddressesGetVirtualMachineScaleSetPublicIPAddressResponse > { return this.client.sendOperationRequest( { resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, publicIpAddressName, options }, getVirtualMachineScaleSetPublicIPAddressOperationSpec ); } /** * ListAllNext * @param nextLink The nextLink from the previous successful call to the ListAll method. * @param options The options parameters. */ private _listAllNext( nextLink: string, options?: PublicIPAddressesListAllNextOptionalParams ): Promise<PublicIPAddressesListAllNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listAllNextOperationSpec ); } /** * ListNext * @param resourceGroupName The name of the resource group. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, nextLink: string, options?: PublicIPAddressesListNextOptionalParams ): Promise<PublicIPAddressesListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listNextOperationSpec ); } /** * ListVirtualMachineScaleSetPublicIPAddressesNext * @param resourceGroupName The name of the resource group. * @param virtualMachineScaleSetName The name of the virtual machine scale set. * @param nextLink The nextLink from the previous successful call to the * ListVirtualMachineScaleSetPublicIPAddresses method. * @param options The options parameters. */ private _listVirtualMachineScaleSetPublicIPAddressesNext( resourceGroupName: string, virtualMachineScaleSetName: string, nextLink: string, options?: PublicIPAddressesListVirtualMachineScaleSetPublicIPAddressesNextOptionalParams ): Promise< PublicIPAddressesListVirtualMachineScaleSetPublicIPAddressesNextResponse > { return this.client.sendOperationRequest( { resourceGroupName, virtualMachineScaleSetName, nextLink, options }, listVirtualMachineScaleSetPublicIPAddressesNextOperationSpec ); } /** * ListVirtualMachineScaleSetVMPublicIPAddressesNext * @param resourceGroupName The name of the resource group. * @param virtualMachineScaleSetName The name of the virtual machine scale set. * @param virtualmachineIndex The virtual machine index. * @param networkInterfaceName The network interface name. * @param ipConfigurationName The IP configuration name. * @param nextLink The nextLink from the previous successful call to the * ListVirtualMachineScaleSetVMPublicIPAddresses method. * @param options The options parameters. */ private _listVirtualMachineScaleSetVMPublicIPAddressesNext( resourceGroupName: string, virtualMachineScaleSetName: string, virtualmachineIndex: string, networkInterfaceName: string, ipConfigurationName: string, nextLink: string, options?: PublicIPAddressesListVirtualMachineScaleSetVMPublicIPAddressesNextOptionalParams ): Promise< PublicIPAddressesListVirtualMachineScaleSetVMPublicIPAddressesNextResponse > { return this.client.sendOperationRequest( { resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName, nextLink, options }, listVirtualMachineScaleSetVMPublicIPAddressesNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.publicIpAddressName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PublicIPAddress }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.expand], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.publicIpAddressName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.PublicIPAddress }, 201: { bodyMapper: Mappers.PublicIPAddress }, 202: { bodyMapper: Mappers.PublicIPAddress }, 204: { bodyMapper: Mappers.PublicIPAddress }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters42, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.publicIpAddressName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const updateTagsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.PublicIPAddress }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.publicIpAddressName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listAllOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PublicIPAddressListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PublicIPAddressListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listVirtualMachineScaleSetPublicIPAddressesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/publicipaddresses", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PublicIPAddressListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.virtualMachineScaleSetName ], headerParameters: [Parameters.accept], serializer }; const listVirtualMachineScaleSetVMPublicIPAddressesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PublicIPAddressListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkInterfaceName, Parameters.virtualMachineScaleSetName, Parameters.virtualmachineIndex, Parameters.ipConfigurationName ], headerParameters: [Parameters.accept], serializer }; const getVirtualMachineScaleSetPublicIPAddressOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses/{publicIpAddressName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PublicIPAddress }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.expand, Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkInterfaceName, Parameters.virtualMachineScaleSetName, Parameters.virtualmachineIndex, Parameters.ipConfigurationName, Parameters.publicIpAddressName ], headerParameters: [Parameters.accept], serializer }; const listAllNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PublicIPAddressListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PublicIPAddressListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listVirtualMachineScaleSetPublicIPAddressesNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PublicIPAddressListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.nextLink, Parameters.virtualMachineScaleSetName ], headerParameters: [Parameters.accept], serializer }; const listVirtualMachineScaleSetVMPublicIPAddressesNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PublicIPAddressListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.nextLink, Parameters.networkInterfaceName, Parameters.virtualMachineScaleSetName, Parameters.virtualmachineIndex, Parameters.ipConfigurationName ], headerParameters: [Parameters.accept], serializer };
the_stack
import { Component } from '../component'; import { DOMUtils } from '../../services'; import { Tools } from '../../tools'; import * as Configuration from '../../configuration'; import { Events, ColorClassNameTypes, RenderTypes } from '../../interfaces'; // D3 imports import { select } from 'd3-selection'; import { sankey as d3Sankey, sankeyLinkHorizontal } from 'd3-sankey'; export class Alluvial extends Component { type = 'alluvial'; renderType = RenderTypes.SVG; private graph: any; gradient_id = 'gradient-id-' + Math.floor(Math.random() * 99999999999); render(animate = true) { // svg and container widths const svg = this.getComponentContainer({ withinChartClip: true }); svg.html(''); const { width, height } = DOMUtils.getSVGElementSize(svg, { useAttrs: true, }); // Because of a Firefox bug with regards to sizing & d3 packs, // rather than checking if height or width aren't 0, // we have to make sure they're not smaller than 1 if (width < 1 || height < 1) { return; } const options = this.model.getOptions(); const data = this.model.getDisplayData(); // Is gradient enabled or not const isGradientAllowed = Tools.getProperty( this.getOptions(), 'color', 'gradient', 'enabled' ); // Set the custom node padding if provided let nodePadding = Configuration.alluvial.minNodePadding; if ( options.alluvial.nodePadding > Configuration.alluvial.minNodePadding ) { nodePadding = options.alluvial.nodePadding; } const sankey = d3Sankey() .nodeId((d) => d.name) .nodeWidth(Configuration.alluvial.nodeWidth) // Distance nodes are apart from each other .nodePadding(nodePadding) // Size of the chart and its padding // Chart starts at 2 and ends at width - 2 so the outer nodes can expand from center // Chart starts from 30 so node categories can be displayed .extent([ [2, 30], [width - 2, height], ]); // Construct a graph with the provided user data // Data must be deep cloned to ensure user passed data isn't deleted when themes change this.graph = sankey({ nodes: options.alluvial.nodes.map((d) => Object.assign({}, d)), links: data.map((d) => Object.assign({}, d)), }); // Filter out unused nodes so they are not rendered this.graph.nodes = this.graph.nodes.filter((node) => node.value !== 0); // Determine the category name placement x position const nodeCoordinates = {}; this.graph.nodes.forEach((element) => { const point = element.x0; // Only 1 category per x-value if (element.category) { nodeCoordinates[point] = element?.category; } }); // Add node category text const alluvialCategory = svg .append('g') .classed('header-arrows', true) .selectAll('g') .data(Object.keys(nodeCoordinates)) .join('g') .attr('transform', (d) => { return `translate(${d}, 0)`; }); // Add the category text alluvialCategory .append('text') .attr('id', (d, i) => this.services.domUtils.generateElementIDString( `alluvial-category-${i}` ) ) .style('font-size', '14px') .text((d) => { if (nodeCoordinates[d]) { return nodeCoordinates[d]; } return ''; }) .attr('y', 20) .attr('x', (d, i) => { const elementID = this.services.domUtils.generateElementIDString( `alluvial-category-${i}` ); const { width } = DOMUtils.getSVGElementSize( select(`text#${elementID}`), { useBBox: true } ); // Make the text on the left on node group (except first column) let x = 0; if (d + x >= width) { x = -width + 4; } return x; }); // Draws the links (Waves) const links = svg .append('g') .attr('fill', 'none') .selectAll('g') .data(this.graph.links); // Exit so we can have multiple appends in group links.exit().remove(); // Add gradient if requsted if (isGradientAllowed) { const scale = Tools.getProperty( this.getOptions(), 'color', 'scale' ); if (scale) { links .enter() .append('linearGradient') .attr('id', (d) => `${this.gradient_id}-link-${d.index}`) .attr('gradientUnits', 'userSpaceOnUse') .call((gradient) => gradient .append('stop') .attr('offset', '0%') .attr('stop-color', (d) => { return scale[d.source.name]; }) ) .call((gradient) => gradient .append('stop') .attr('offset', '100%') .attr('stop-color', (d) => { return scale[d.target.name]; }) ); } // Exit so path can be appended to the group links.exit().remove(); } links .enter() .append('path') .classed('link', true) .attr('d', sankeyLinkHorizontal()) .attr('id', (d) => this.services.domUtils.generateElementIDString( `alluvial-line-${d.index}` ) ) .attr('class', (d) => { // Use a single color for the lines if (options.alluvial.monochrome) { return this.model.getColorClassName({ classNameTypes: [ColorClassNameTypes.STROKE], dataGroupName: 0, originalClassName: 'link', }); } return this.model.getColorClassName({ classNameTypes: [ColorClassNameTypes.STROKE], dataGroupName: d.source.index, originalClassName: 'link', }); }) .style('stroke', (d) => { if (isGradientAllowed) { return `url(#${this.gradient_id}-link-${d.index})`; } return this.model.getFillColor(d.source.name); }) .attr('stroke-width', (d) => Math.max(1, d.width)) .style('stroke-opacity', Configuration.alluvial.opacity.default) .attr( 'aria-label', (d) => `${d.source.name} → ${d.target.name} (${d.value}${ options.alluvial.units ? ' ' + options.alluvial.units : '' })` ); // Creating the groups const node = svg .append('g') .selectAll('g') .data(this.graph.nodes) .enter() .append('g') .attr('id', (d) => this.services.domUtils.generateElementIDString( `alluvial-node-${d.index}` ) ) .classed('node-group', true) .attr('transform', (d) => `translate(${d.x0}, ${d.y0})`); // Creating the nodes node.append('rect') .classed('node', true) .attr('height', (d) => d.y1 - d.y0) .attr('width', (d) => d.x1 - d.x0) .attr('fill', 'black'); // Group to hold the text & rectangle background const textNode = node .append('g') .attr('id', (d) => this.services.domUtils.generateElementIDString( `alluvial-node-title-${d.index}` ) ); // Node title - text textNode .append('text') .attr('id', (d) => this.services.domUtils.generateElementIDString( `alluvial-node-text-${d.index}` ) ) .attr('class', 'node-text') .style('font-size', '12px') .attr('text-anchor', 'start') .attr('fill', 'white') // Padding to text .attr('x', 4) // shift 13 pixels down to fit background container .attr('dy', 13) .text((d) => { return `${d.name} (${d.value})`; }) .attr('aria-label', (d) => { return `${d.name} (${d.value})`; }); // Text background textNode .append('rect') .classed('node-text-bg', true) .attr('width', (d, i) => { const elementID = this.services.domUtils.generateElementIDString( `alluvial-node-text-${i}` ); // Determine rectangle width based on text width const { width } = DOMUtils.getSVGElementSize( select(`text#${elementID}`), { useBBox: true } ); return width + 8; }) .attr('height', 18) .attr('stroke-width', 2) .lower(); // Position group based on text width textNode.attr('transform', (d, i) => { const elementID = this.services.domUtils.generateElementIDString( `alluvial-node-text-${i}` ); const { width } = DOMUtils.getSVGElementSize( select(`text#${elementID}`), { useBBox: true } ); // Subtracting 9 since text background is 18 to center const y = (d.y1 - d.y0) / 2 - 9; // Node width let x = d.x1 - d.x0; // Display bars on the right instead of left of the node if (d.x1 >= width) { // 16 = node width (4) + text container padding (8) + distance between node and text container (4) x = x - (width + 16); } else { // Add padding to text containers x += 4; } return `translate(${x}, ${y})`; }); this.addLineEventListener(); this.addNodeEventListener(); } addLineEventListener() { const options = this.getOptions(); const self = this; // Set delay to counter flashy behaviour const debouncedLineHighlight = Tools.debounce( (link, event = 'mouseover') => { const allLinks = self.parent .selectAll('path.link') .transition() .call((t) => self.services.transitions.setupTransition({ transition: t, name: 'alluvial-links-mouse-highlight', }) ); if (event === 'mouseout') { select(link).lower(); allLinks.style( 'stroke-opacity', Configuration.alluvial.opacity.default ); } else { allLinks.style('stroke-opacity', function () { // highlight and raise if link is this if (link === this) { select(this).raise(); return Configuration.alluvial.opacity.selected; } return Configuration.alluvial.opacity.unfocus; }); } }, 33 ); this.parent .selectAll('path.link') .on('mouseover', function (event, datum) { const hoveredElement = select(this); debouncedLineHighlight(this, 'mouseover'); hoveredElement.classed('link-hovered', true); const strokeColor = getComputedStyle(this).getPropertyValue( 'stroke' ); // Dispatch mouse over event self.services.events.dispatchEvent( Events.Alluvial.LINE_MOUSEOVER, { event, element: hoveredElement, datum, } ); // Dispatch tooltip show event self.services.events.dispatchEvent(Events.Tooltip.SHOW, { event, hoveredElement, items: [ { label: datum.target.name, value: datum.value + (options.alluvial.units ? ` ${options.alluvial.units}` : ''), color: strokeColor, labelIcon: self.getRightArrowIcon(), }, ], }); }) .on('mousemove', function (event, datum) { // Dispatch mouse move event self.services.events.dispatchEvent( Events.Alluvial.LINE_MOUSEMOVE, { event, element: select(this), datum, } ); // Dispatch tooltip move event self.services.events.dispatchEvent(Events.Tooltip.MOVE, { event, }); }) .on('click', function (event, datum) { // Dispatch mouse click event self.services.events.dispatchEvent(Events.Alluvial.LINE_CLICK, { event, element: select(this), datum, }); }) .on('mouseout', function (event, datum) { const hoveredElement = select(this); debouncedLineHighlight(this, 'mouseout'); hoveredElement.classed('link-hovered', false); // Dispatch mouse out event self.services.events.dispatchEvent( Events.Alluvial.LINE_MOUSEOUT, { event, element: hoveredElement, datum, } ); // Dispatch hide tooltip event self.services.events.dispatchEvent(Events.Tooltip.HIDE, { event, hoveredElement, }); }); } addNodeEventListener() { const self = this; // Set delay to counter flashy behaviour const debouncedLineHighlight = Tools.debounce( (links = [], event = 'mouseover') => { if (event === 'mouseout' || links.length === 0) { // set all links to default opacity & corret link order self.parent .selectAll('path.link') .classed('link-hovered', false) .data(this.graph.links, (d) => d.index) .order() .style( 'stroke-opacity', Configuration.alluvial.opacity.default ); return; } // Highlight all nodes const allLinks = self.parent .selectAll('path.link') .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'alluvial-link-mouse-highlight', }) ); allLinks.style('stroke-opacity', function (d) { // Raise the links & increase stroke-opacity to selected if (links.some((element) => element === d.index)) { select(this).classed('link-hovered', true).raise(); return Configuration.alluvial.opacity.selected; } return Configuration.alluvial.opacity.unfocus; }); }, 66 ); self.parent .selectAll('.node-group') .on('mouseover', function (event, datum) { const hoveredElement = select(this); // Highlight all links that pass through node const paths = []; // Outgoing links self.traverse( { link: 'sourceLinks', node: 'target' }, datum, paths ); //Incoming links self.traverse( { link: 'targetLinks', node: 'source' }, datum, paths ); // Highlight all linked lines in the graph data structure if (paths.length) { // Get transformation value of node const nodeMatrix = Tools.getTranformOffsets( hoveredElement.attr('transform') ); // Move node to the left by 2 to grow node from the center hoveredElement.attr( 'transform', `translate(${nodeMatrix.x - 2}, ${nodeMatrix.y})` ); hoveredElement .classed('node-hovered', true) .selectAll('rect.node') .attr('width', 8); // Translate first column text container to the // right so it doesn't clash with expanding node if (datum.x0 - 2 === 0) { const elementID = self.services.domUtils.generateElementIDString( `alluvial-node-title-${datum.index}` ); const titleContainer = self.parent.select( `g#${elementID}` ); const titleMatrix = Tools.getTranformOffsets( titleContainer.attr('transform') ); titleContainer.attr( 'transform', `translate(${titleMatrix.x + 4},${titleMatrix.y})` ); } const elementID = self.services.domUtils.generateElementIDString( `alluvial-node-text-${datum.index}` ); self.parent .select(`text#${elementID}`) .style('font-weight', 'bold'); debouncedLineHighlight(paths, 'mouseover'); // Dispatch mouse over event self.services.events.dispatchEvent( Events.Alluvial.NODE_MOUSEOVER, { event, element: hoveredElement, datum, } ); } }) .on('mousemove', function (event, datum) { // Dispatch mouse move event self.services.events.dispatchEvent( Events.Alluvial.NODE_MOUSEMOVE, { event, element: select(this), datum, } ); // Dispatch tooltip move event self.services.events.dispatchEvent(Events.Tooltip.MOVE, { event, }); }) .on('click', function (event, datum) { // Dispatch mouse click event self.services.events.dispatchEvent(Events.Alluvial.NODE_CLICK, { event, element: select(this), datum, }); }) .on('mouseout', function (event, datum) { const hoveredElement = select(this); // Set the node position to initial state (unexpanded) const nodeMatrix = Tools.getTranformOffsets( hoveredElement.attr('transform') ); hoveredElement .classed('node-hovered', false) .attr( 'transform', `translate(${nodeMatrix.x + 2}, ${nodeMatrix.y})` ) .select('rect.node') .attr('width', Configuration.alluvial.nodeWidth); // Translate text container back to initial state if (datum.x0 - 2 === 0) { const elementID = self.services.domUtils.generateElementIDString( `alluvial-node-title-${datum.index}` ); const titleContainer = self.parent.select(`g#${elementID}`); const titleMatrix = Tools.getTranformOffsets( titleContainer.attr('transform') ); titleContainer.attr( 'transform', `translate(${titleMatrix.x - 4},${titleMatrix.y})` ); } const elementID = self.services.domUtils.generateElementIDString( `alluvial-node-text-${datum.index}` ); self.parent .select(`text#${elementID}`) .style('font-weight', 'normal'); debouncedLineHighlight([], 'mouseout'); // Dispatch mouse out event self.services.events.dispatchEvent( Events.Alluvial.NODE_MOUSEOUT, { event, element: hoveredElement, datum, } ); // Dispatch hide tooltip event self.services.events.dispatchEvent(Events.Tooltip.HIDE, { hoveredElement, }); }); } // Traverse graph and get all connected links to node private traverse( direction: | { link: 'sourceLinks'; node: 'target' } | { link: 'targetLinks'; node: 'source' }, node, visited = [] ) { const links = node[direction.link].map((element) => { visited.push(element.index); return element[direction.node]; }); // Retrieve the child nodes links.forEach((element) => this.traverse(direction, element, visited)); } getRightArrowIcon() { return ` <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"> <polygon points="18 6 16.57 7.393 24.15 15 4 15 4 17 24.15 17 16.57 24.573 18 26 28 16 18 6"/> <rect data-name="&lt;Transparent Rectangle&gt;" style="fill: none;" width="32" height="32"/> </svg>`; } // Remove event listeners destroy() { this.parent .selectAll('path.line,.node-group') .on('mouseover', null) .on('mousemove', null) .on('click', null) .on('mouseout', null); } }
the_stack
import { MachineConfig, Machine, assign, Action, AssignAction, spawn, Condition, DoneInvokeEvent, StateSchema, StateMachine, State } from 'xstate'; import {filter, map, distinctUntilChanged} from 'rxjs/operators'; import {StateVariables} from '@statechannels/wallet-core'; import {StateChannelsError} from '@statechannels/client-api-schema'; import _ from 'lodash'; import { PlayerStateUpdate, ChannelUpdated, JoinChannelEvent, CreateChannelEvent, PlayerRequestConclude, OpenEvent } from '../event-types'; import {ChannelStoreEntry} from '../store/channel-store-entry'; import {Store, Errors} from '../store'; import {unreachable} from '../utils'; import {logger} from '../logger'; import {CONCLUDE_TIMEOUT} from '../constants'; import {createMockGuard} from '../utils/workflow-utils'; import {MessagingServiceInterface, SupportedFundingStrategy} from '../messaging'; import {serializeChannelEntry} from '../utils/wallet-core-v0.8.0'; import {ConcludeChannel, CreateAndFund, ChallengeChannel, Confirm as CCC} from './'; export interface WorkflowContext { applicationDomain: string; fundingStrategy: SupportedFundingStrategy; channelId?: string; requestObserver?: any; updateObserver?: any; requestId?: number; channelParams?: Omit<CreateChannelEvent, 'type'>; } type CreateInit = WorkflowContext & CreateChannelEvent; type JoinInit = WorkflowContext & {channelId: string; type: 'JOIN_CHANNEL'}; export type Init = CreateInit | JoinInit; type ChannelIdExists = WorkflowContext & {channelId: string}; type RequestIdExists = WorkflowContext & {requestId: number}; type Guards<Keys extends string> = Record<Keys, Condition<WorkflowContext, WorkflowEvent>>; type WorkflowGuards = Guards< | 'channelOpen' | 'channelClosing' | 'channelClosed' | 'channelChallenging' | 'isDirectFunding' | 'isLedgerFunding' | 'isVirtualFunding' | 'amCreator' | 'amJoiner' >; export interface WorkflowActions { sendChallengeChannelResponse: Action<RequestIdExists & ChannelIdExists, any>; sendCreateChannelResponse: Action<RequestIdExists & ChannelIdExists, any>; sendJoinChannelResponse: Action<RequestIdExists & ChannelIdExists, any>; assignChannelId: Action<WorkflowContext, any>; assignRequestId: Action<WorkflowContext, any>; displayUi: Action<WorkflowContext, any>; hideUi: Action<WorkflowContext, any>; sendChannelUpdatedNotification: Action<WorkflowContext, any>; spawnObservers: AssignAction<ChannelIdExists, any>; updateChannel: Action<WorkflowContext, PlayerStateUpdate>; closeChannel: Action<WorkflowContext, PlayerRequestConclude>; } export type WorkflowEvent = | PlayerRequestConclude | PlayerStateUpdate | OpenEvent | ChannelUpdated | JoinChannelEvent | DoneInvokeEvent<keyof WorkflowServices>; export type WorkflowServices = { setapplicationDomain(ctx: ChannelIdExists, e: JoinChannelEvent): Promise<void>; createChannel: (context: WorkflowContext, event: WorkflowEvent) => Promise<string>; signFinalStateIfMyTurn: (context: ChannelIdExists) => Promise<any>; invokeClosingProtocol: ( context: ChannelIdExists ) => StateMachine<ConcludeChannel.Init, any, any, any>; invokeChallengingProtocol: ( context: ChannelIdExists ) => StateMachine<ChallengeChannel.Initial, any, any, any>; invokeCreateChannelAndFundProtocol: StateMachine<any, any, any, any>; invokeCreateChannelConfirmation: CCC.WorkflowMachine; }; interface WorkflowStateSchema extends StateSchema<WorkflowContext> { states: { branchingOnFundingStrategy: {}; confirmingWithUser: {}; creatingChannel: {}; joiningChannel: {}; openChannelAndFundProtocol: {}; running: {}; sendChallenge: {}; closing: {}; done: {}; failure: {}; fundingChannel: {}; }; } export type StateValue = keyof WorkflowStateSchema['states']; export type WorkflowState = State<WorkflowContext, WorkflowEvent, WorkflowStateSchema, any>; const signFinalStateIfMyTurn = (store: Store) => async ({channelId}: ChannelIdExists) => store.updateChannel(channelId, {isFinal: true}); const generateConfig = ( actions: WorkflowActions, guards: WorkflowGuards ): MachineConfig<WorkflowContext, WorkflowStateSchema, WorkflowEvent> => ({ id: 'application-workflow', initial: 'joiningChannel', on: {CHANNEL_UPDATED: {actions: [actions.sendChannelUpdatedNotification]}}, states: { joiningChannel: { initial: 'joining', states: { failure: {}, joining: { on: { JOIN_CHANNEL: { target: 'settingDomain', actions: [actions.assignRequestId, actions.sendJoinChannelResponse] } }, always: [ {target: 'failure', cond: guards.isLedgerFunding}, // TODO: Should we even support ledger funding? {target: 'done', cond: guards.amCreator} ] }, settingDomain: {invoke: {src: 'setapplicationDomain', onDone: 'done'}}, done: {type: 'final'} }, onDone: [ {target: 'confirmingWithUser', cond: guards.isDirectFunding}, {target: 'creatingChannel', cond: guards.isVirtualFunding} ] }, confirmingWithUser: { // FIXME We should keep track of whether the UI was turned on in the context. // That way, at the end, we know whether we have to send hideUI // TODO: implement assignUIState // entry: [actions.displayUi, 'assignUIState'], entry: [actions.displayUi], invoke: {src: 'invokeCreateChannelConfirmation', onDone: 'creatingChannel'} }, creatingChannel: { invoke: { data: (_, event) => event.data, src: 'createChannel', onDone: { target: 'fundingChannel', actions: [actions.assignChannelId, actions.sendCreateChannelResponse] } }, always: {target: 'fundingChannel', cond: guards.amJoiner} }, fundingChannel: { invoke: { src: 'invokeCreateChannelAndFundProtocol', data: (ctx: ChannelIdExists): CreateAndFund.Init => ({ channelId: ctx.channelId, funding: ctx.fundingStrategy }), onDone: {target: 'running', actions: [actions.hideUi]} } }, running: { entry: [actions.spawnObservers], on: { // TODO: It would be nice to get rid of this event, which is used // in testing when starting the workflow in the 'running' state. SPAWN_OBSERVERS: {actions: actions.spawnObservers}, PLAYER_STATE_UPDATE: { target: 'running', actions: [actions.updateChannel] }, CHANNEL_UPDATED: [ {target: 'closing', cond: guards.channelClosing}, {target: 'sendChallenge', cond: guards.channelChallenging} ], PLAYER_REQUEST_CONCLUDE: { target: 'running', actions: [actions.closeChannel], after: {[CONCLUDE_TIMEOUT]: {target: 'sendChallenge', cond: guards.channelClosing}} }, PLAYER_REQUEST_CHALLENGE: {target: 'sendChallenge'} } }, // This could handled by another workflow instead of the application workflow closing: { invoke: { id: 'closing-protocol', src: 'invokeClosingProtocol', data: context => context, autoForward: true, onDone: {target: 'done'} } }, // This could handled by another workflow instead of the application workflow sendChallenge: { entry: actions.displayUi, exit: actions.hideUi, invoke: { id: 'challenge-protocol', src: 'invokeChallengingProtocol', data: context => context, autoForward: true, onDone: {target: 'running', actions: [actions.sendChallengeChannelResponse]} } }, done: {type: 'final'} } as any // TODO: This is to deal with some flickering compilation issues. }); export const workflow = ( store: Store, messagingService: MessagingServiceInterface, context?: Init ) => { const notifyOnChannelRequest = ({channelId}: ChannelIdExists) => messagingService.requestFeed.pipe( filter( r => (r.type === 'PLAYER_STATE_UPDATE' || r.type === 'PLAYER_REQUEST_CONCLUDE' || r.type === 'PLAYER_REQUEST_CHALLENGE') && r.channelId === channelId ) ); const notifyOnUpdate = ({channelId}: ChannelIdExists) => store.channelUpdatedFeed(channelId).pipe( filter(storeEntry => storeEntry.isSupported), distinctUntilChanged((entry1, entry2) => _.isEqual(serializeChannelEntry(entry1), serializeChannelEntry(entry2)) ), map(storeEntry => ({ type: 'CHANNEL_UPDATED', storeEntry })) ); const actions: WorkflowActions = { sendCreateChannelResponse: async (context: RequestIdExists & ChannelIdExists) => { const entry = await store.getEntry(context.channelId); await messagingService.sendResponse(context.requestId, serializeChannelEntry(entry)); }, sendJoinChannelResponse: async (context: RequestIdExists & ChannelIdExists) => { const entry = await store.getEntry(context.channelId); await messagingService.sendResponse(context.requestId, serializeChannelEntry(entry)); }, sendChallengeChannelResponse: async (context: RequestIdExists & ChannelIdExists) => { const entry = await store.getEntry(context.channelId); await messagingService.sendResponse(context.requestId, serializeChannelEntry(entry)); }, spawnObservers: assign<ChannelIdExists>((context: ChannelIdExists) => ({ ...context, updateObserver: context.updateObserver ?? spawn(notifyOnUpdate(context)), requestObserver: context.requestObserver ?? spawn(notifyOnChannelRequest(context)) })), sendChannelUpdatedNotification: async ( context: ChannelIdExists, event: {storeEntry: ChannelStoreEntry} ) => { if (event.storeEntry.channelId === context.channelId) { messagingService.sendChannelNotification( 'ChannelUpdated', serializeChannelEntry(event.storeEntry) ); } }, displayUi: () => { messagingService.sendDisplayMessage('Show'); }, hideUi: () => { messagingService.sendDisplayMessage('Hide'); }, assignChannelId: assign((context, event: AssignChannelEvent) => { if (context.channelId) return context; switch (event.type) { case 'PLAYER_STATE_UPDATE': case 'JOIN_CHANNEL': return {channelId: event.channelId}; case 'done.invoke.createChannel': return {channelId: event.data}; default: return unreachable(event); } }), assignRequestId: assign((context, event: JoinChannelEvent | PlayerRequestConclude) => ({ requestId: event.requestId })), updateChannel: async (context: ChannelIdExists, event: PlayerStateUpdate) => { if (context.channelId === event.channelId) { try { messagingService.sendResponse( event.requestId, serializeChannelEntry(await store.updateChannel(event.channelId, event)) ); } catch (error) { const matches = reason => new RegExp(reason).test(error.message); // TODO: Catch other errors let message: StateChannelsError; if (matches(Errors.channelMissing)) message = {code: 400, message: 'Channel not found'}; else if (matches(Errors.notMyTurn)) message = {code: 403, message: 'Not your turn'}; else { message = {code: 500, message: 'Wallet error'}; logger.error({error}, 'UpdateChannel call failed with error 500'); } messagingService.sendError(event.requestId, message); } } }, closeChannel: async (context: ChannelIdExists, event: PlayerRequestConclude) => { if (context.channelId === event.channelId) { try { messagingService.sendResponse( event.requestId, serializeChannelEntry(await store.updateChannel(event.channelId, {isFinal: true})) ); } catch (error) { const matches = reason => new RegExp(reason).test(error.message); let message: StateChannelsError; if (matches(Errors.notMyTurn)) message = {code: 300, message: 'Not your turn'}; else if (matches(Errors.channelMissing)) message = {code: 301, message: 'Channel not found'}; else { message = {code: 500, message: 'Wallet error'}; logger.error({error}, 'CloseChannel call failed with error 500'); } messagingService.sendError(event.requestId, message); } } } }; const guards: WorkflowGuards = { channelOpen: (_: ChannelIdExists, event: ChannelUpdated): boolean => !event.storeEntry.latestSignedByMe.isFinal, channelClosing: (_: ChannelIdExists, event: ChannelUpdated): boolean => !!event.storeEntry.latest?.isFinal, // TODO: Should use supported channelChallenging: (context: ChannelIdExists, event: ChannelUpdated): boolean => !!event.storeEntry.isChallenging, channelClosed: (_, event: any): boolean => !!event.storeEntry.supported?.isFinal, isDirectFunding: (ctx: Init) => ctx.fundingStrategy === 'Direct', isLedgerFunding: (ctx: Init) => ctx.fundingStrategy === 'Ledger', isVirtualFunding: (ctx: Init) => ctx.fundingStrategy === 'Virtual', amCreator: (ctx: Init) => ctx.type === 'CREATE_CHANNEL', amJoiner: (ctx: Init) => ctx.type === 'JOIN_CHANNEL' }; const services: WorkflowServices = { setapplicationDomain: async (ctx: ChannelIdExists, event: JoinChannelEvent) => await store.setapplicationDomain(ctx.channelId, event.applicationDomain), signFinalStateIfMyTurn: signFinalStateIfMyTurn(store), createChannel: async (context: CreateInit) => { const { participants, challengeDuration, outcome, appData, appDefinition, fundingStrategy, applicationDomain } = context; const stateVars: StateVariables = { outcome, appData, turnNum: 0, isFinal: false }; const {channelId: targetChannelId} = await store.createChannel( participants, challengeDuration, stateVars, appDefinition, applicationDomain ); // Create a open channel objective so we can coordinate with all participants await store.addObjective({ type: 'OpenChannel', data: {targetChannelId, fundingStrategy}, participants: [participants[1]] }); return targetChannelId; }, invokeClosingProtocol: (context: ChannelIdExists) => ConcludeChannel.machine(store, messagingService).withContext({channelId: context.channelId}), invokeChallengingProtocol: ({channelId}: ChannelIdExists) => ChallengeChannel.machine(store, {channelId}), invokeCreateChannelAndFundProtocol: CreateAndFund.machine(store, messagingService), invokeCreateChannelConfirmation: CCC.workflow({}) }; const config = generateConfig(actions, guards); return Machine(config).withConfig({services}, context); }; const mockGuards: WorkflowGuards = { channelOpen: createMockGuard('channelOpen'), channelClosing: createMockGuard('channelClosing'), channelChallenging: createMockGuard('channelChallenging'), channelClosed: createMockGuard('channelClosed'), isDirectFunding: createMockGuard('isDirectFunding'), isLedgerFunding: createMockGuard('isLedgerFunding'), isVirtualFunding: createMockGuard('isVirtualFunding'), amCreator: createMockGuard('amCreator'), amJoiner: createMockGuard('amJoiner') }; const mockActions: Record<keyof WorkflowActions, string> = { assignChannelId: 'assignChannelId', sendChannelUpdatedNotification: 'sendChannelUpdatedNotification', sendChallengeChannelResponse: 'sendChallengeChannelResponse', sendCreateChannelResponse: 'sendCreateChannelResponse', sendJoinChannelResponse: 'sendJoinChannelResponse', hideUi: 'hideUi', displayUi: 'displayUi', spawnObservers: 'spawnObservers', updateChannel: 'updateChannel', closeChannel: 'closeChannel', assignRequestId: 'assignRequestId' }; export const config = generateConfig(mockActions as any, mockGuards); export const mockOptions = {guards: mockGuards}; type AssignChannelEvent = | PlayerStateUpdate | JoinChannelEvent | (DoneInvokeEvent<string> & {type: 'done.invoke.createChannel'});
the_stack
| Copyright (c) 2014-2017, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ import { ArrayExt, StringExt } from '@lumino/algorithm'; import { JSONExt, ReadonlyJSONObject } from '@lumino/coreutils'; import { CommandRegistry } from '@lumino/commands'; import { ElementExt } from '@lumino/domutils'; import { Message } from '@lumino/messaging'; import { ElementDataset, VirtualDOM, VirtualElement, h } from '@lumino/virtualdom'; import { Widget } from './widget'; /** * A widget which displays command items as a searchable palette. */ export class CommandPalette extends Widget { /** * Construct a new command palette. * * @param options - The options for initializing the palette. */ constructor(options: CommandPalette.IOptions) { super({ node: Private.createNode() }); this.addClass('lm-CommandPalette'); /* <DEPRECATED> */ this.addClass('p-CommandPalette'); /* </DEPRECATED> */ this.setFlag(Widget.Flag.DisallowLayout); this.commands = options.commands; this.renderer = options.renderer || CommandPalette.defaultRenderer; this.commands.commandChanged.connect(this._onGenericChange, this); this.commands.keyBindingChanged.connect(this._onGenericChange, this); } /** * Dispose of the resources held by the widget. */ dispose(): void { this._items.length = 0; this._results = null; super.dispose(); } /** * The command registry used by the command palette. */ readonly commands: CommandRegistry; /** * The renderer used by the command palette. */ readonly renderer: CommandPalette.IRenderer; /** * The command palette search node. * * #### Notes * This is the node which contains the search-related elements. */ get searchNode(): HTMLDivElement { return this.node.getElementsByClassName('lm-CommandPalette-search')[0] as HTMLDivElement; } /** * The command palette input node. * * #### Notes * This is the actual input node for the search area. */ get inputNode(): HTMLInputElement { return this.node.getElementsByClassName('lm-CommandPalette-input')[0] as HTMLInputElement; } /** * The command palette content node. * * #### Notes * This is the node which holds the command item nodes. * * Modifying this node directly can lead to undefined behavior. */ get contentNode(): HTMLUListElement { return this.node.getElementsByClassName('lm-CommandPalette-content')[0] as HTMLUListElement; } /** * A read-only array of the command items in the palette. */ get items(): ReadonlyArray<CommandPalette.IItem> { return this._items; } /** * Add a command item to the command palette. * * @param options - The options for creating the command item. * * @returns The command item added to the palette. */ addItem(options: CommandPalette.IItemOptions): CommandPalette.IItem { // Create a new command item for the options. let item = Private.createItem(this.commands, options); // Add the item to the array. this._items.push(item); // Refresh the search results. this.refresh(); // Return the item added to the palette. return item; } /** * Adds command items to the command palette. * * @param items - An array of options for creating each command item. * * @returns The command items added to the palette. */ addItems(items: CommandPalette.IItemOptions[]): CommandPalette.IItem[] { const newItems = items.map(item => Private.createItem(this.commands, item)); newItems.forEach(item => this._items.push(item)); this.refresh(); return newItems; } /** * Remove an item from the command palette. * * @param item - The item to remove from the palette. * * #### Notes * This is a no-op if the item is not in the palette. */ removeItem(item: CommandPalette.IItem): void { this.removeItemAt(this._items.indexOf(item)); } /** * Remove the item at a given index from the command palette. * * @param index - The index of the item to remove. * * #### Notes * This is a no-op if the index is out of range. */ removeItemAt(index: number): void { // Remove the item from the array. let item = ArrayExt.removeAt(this._items, index); // Bail if the index is out of range. if (!item) { return; } // Refresh the search results. this.refresh(); } /** * Remove all items from the command palette. */ clearItems(): void { // Bail if there is nothing to remove. if (this._items.length === 0) { return; } // Clear the array of items. this._items.length = 0; // Refresh the search results. this.refresh(); } /** * Clear the search results and schedule an update. * * #### Notes * This should be called whenever the search results of the palette * should be updated. * * This is typically called automatically by the palette as needed, * but can be called manually if the input text is programatically * changed. * * The rendered results are updated asynchronously. */ refresh(): void { this._results = null; if(this.inputNode.value !== '') { let clear = this.node.getElementsByClassName('lm-close-icon')[0] as HTMLInputElement; clear.style.display = 'inherit' } else { let clear = this.node.getElementsByClassName('lm-close-icon')[0] as HTMLInputElement; clear.style.display = 'none' } this.update(); } /** * Handle the DOM events for the command palette. * * @param event - The DOM event sent to the command palette. * * #### Notes * This method implements the DOM `EventListener` interface and is * called in response to events on the command palette's DOM node. * It should not be called directly by user code. */ handleEvent(event: Event): void { switch (event.type) { case 'click': this._evtClick(event as MouseEvent); break; case 'keydown': this._evtKeyDown(event as KeyboardEvent); break; case 'input': this.refresh(); break; case 'focus': case 'blur': this._toggleFocused(); break; } } /** * A message handler invoked on a `'before-attach'` message. */ protected onBeforeAttach(msg: Message): void { this.node.addEventListener('click', this); this.node.addEventListener('keydown', this); this.node.addEventListener('input', this); this.node.addEventListener('focus', this, true); this.node.addEventListener('blur', this, true); } /** * A message handler invoked on an `'after-detach'` message. */ protected onAfterDetach(msg: Message): void { this.node.removeEventListener('click', this); this.node.removeEventListener('keydown', this); this.node.removeEventListener('input', this); this.node.removeEventListener('focus', this, true); this.node.removeEventListener('blur', this, true); } /** * A message handler invoked on an `'activate-request'` message. */ protected onActivateRequest(msg: Message): void { if (this.isAttached) { let input = this.inputNode; input.focus(); input.select(); } } /** * A message handler invoked on an `'update-request'` message. */ protected onUpdateRequest(msg: Message): void { // Fetch the current query text and content node. let query = this.inputNode.value; let contentNode = this.contentNode; // Ensure the search results are generated. let results = this._results; if (!results) { // Generate and store the new search results. results = this._results = Private.search(this._items, query); // Reset the active index. this._activeIndex = ( query ? ArrayExt.findFirstIndex(results, Private.canActivate) : -1 ); } // If there is no query and no results, clear the content. if (!query && results.length === 0) { VirtualDOM.render(null, contentNode); return; } // If the is a query but no results, render the empty message. if (query && results.length === 0) { let content = this.renderer.renderEmptyMessage({ query }); VirtualDOM.render(content, contentNode); return; } // Create the render content for the search results. let renderer = this.renderer; let activeIndex = this._activeIndex; let content = new Array<VirtualElement>(results.length); for (let i = 0, n = results.length; i < n; ++i) { let result = results[i]; if (result.type === 'header') { let indices = result.indices; let category = result.category; content[i] = renderer.renderHeader({ category, indices }); } else { let item = result.item; let indices = result.indices; let active = i === activeIndex; content[i] = renderer.renderItem({ item, indices, active }); } } // Render the search result content. VirtualDOM.render(content, contentNode); // Adjust the scroll position as needed. if (activeIndex < 0 || activeIndex >= results.length) { contentNode.scrollTop = 0; } else { let element = contentNode.children[activeIndex]; ElementExt.scrollIntoViewIfNeeded(contentNode, element); } } /** * Handle the `'click'` event for the command palette. */ private _evtClick(event: MouseEvent): void { // Bail if the click is not the left button. if (event.button !== 0) { return; } // Clear input if the target is clear button if((event.target as HTMLElement).classList.contains("lm-close-icon")) { this.inputNode.value = ''; this.refresh(); return; } // Find the index of the item which was clicked. let index = ArrayExt.findFirstIndex(this.contentNode.children, node => { return node.contains(event.target as HTMLElement); }); // Bail if the click was not on an item. if (index === -1) { return; } // Kill the event when a content item is clicked. event.preventDefault(); event.stopPropagation(); // Execute the item if possible. this._execute(index); } /** * Handle the `'keydown'` event for the command palette. */ private _evtKeyDown(event: KeyboardEvent): void { if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { return; } switch (event.keyCode) { case 13: // Enter event.preventDefault(); event.stopPropagation(); this._execute(this._activeIndex); break; case 38: // Up Arrow event.preventDefault(); event.stopPropagation(); this._activatePreviousItem(); break; case 40: // Down Arrow event.preventDefault(); event.stopPropagation(); this._activateNextItem(); break; } } /** * Activate the next enabled command item. */ private _activateNextItem(): void { // Bail if there are no search results. if (!this._results || this._results.length === 0) { return; } // Find the next enabled item index. let ai = this._activeIndex; let n = this._results.length; let start = ai < n - 1 ? ai + 1 : 0; let stop = start === 0 ? n - 1 : start - 1; this._activeIndex = ArrayExt.findFirstIndex( this._results, Private.canActivate, start, stop ); // Schedule an update of the items. this.update(); } /** * Activate the previous enabled command item. */ private _activatePreviousItem(): void { // Bail if there are no search results. if (!this._results || this._results.length === 0) { return; } // Find the previous enabled item index. let ai = this._activeIndex; let n = this._results.length; let start = ai <= 0 ? n - 1 : ai - 1; let stop = start === n - 1 ? 0 : start + 1; this._activeIndex = ArrayExt.findLastIndex( this._results, Private.canActivate, start, stop ); // Schedule an update of the items. this.update(); } /** * Execute the command item at the given index, if possible. */ private _execute(index: number): void { // Bail if there are no search results. if (!this._results) { return; } // Bail if the index is out of range. let part = this._results[index]; if (!part) { return; } // Update the search text if the item is a header. if (part.type === 'header') { let input = this.inputNode; input.value = `${part.category.toLowerCase()} `; input.focus(); this.refresh(); return; } // Bail if item is not enabled. if (!part.item.isEnabled) { return; } // Execute the item. this.commands.execute(part.item.command, part.item.args); // Clear the query text. this.inputNode.value = ''; // Refresh the search results. this.refresh(); } /** * Toggle the focused modifier based on the input node focus state. */ private _toggleFocused(): void { let focused = document.activeElement === this.inputNode; this.toggleClass('lm-mod-focused', focused); /* <DEPRECATED> */ this.toggleClass('p-mod-focused', focused); /* </DEPRECATED> */ } /** * A signal handler for generic command changes. */ private _onGenericChange(): void { this.refresh(); } private _activeIndex = -1; private _items: CommandPalette.IItem[] = []; private _results: Private.SearchResult[] | null = null; } /** * The namespace for the `CommandPalette` class statics. */ export namespace CommandPalette { /** * An options object for creating a command palette. */ export interface IOptions { /** * The command registry for use with the command palette. */ commands: CommandRegistry; /** * A custom renderer for use with the command palette. * * The default is a shared renderer instance. */ renderer?: IRenderer; } /** * An options object for creating a command item. */ export interface IItemOptions { /** * The category for the item. */ category: string; /** * The command to execute when the item is triggered. */ command: string; /** * The arguments for the command. * * The default value is an empty object. */ args?: ReadonlyJSONObject; /** * The rank for the command item. * * The rank is used as a tie-breaker when ordering command items * for display. Items are sorted in the following order: * 1. Text match (lower is better) * 2. Category (locale order) * 3. Rank (lower is better) * 4. Label (locale order) * * The default rank is `Infinity`. */ rank?: number; } /** * An object which represents an item in a command palette. * * #### Notes * Item objects are created automatically by a command palette. */ export interface IItem { /** * The command to execute when the item is triggered. */ readonly command: string; /** * The arguments for the command. */ readonly args: ReadonlyJSONObject; /** * The category for the command item. */ readonly category: string; /** * The rank for the command item. */ readonly rank: number; /** * The display label for the command item. */ readonly label: string; /** * The display caption for the command item. */ readonly caption: string; /** * The icon renderer for the command item. */ readonly icon: VirtualElement.IRenderer | undefined /* <DEPRECATED> */ | string /* </DEPRECATED> */; /** * The icon class for the command item. */ readonly iconClass: string; /** * The icon label for the command item. */ readonly iconLabel: string; /** * The extra class name for the command item. */ readonly className: string; /** * The dataset for the command item. */ readonly dataset: CommandRegistry.Dataset; /** * Whether the command item is enabled. */ readonly isEnabled: boolean; /** * Whether the command item is toggled. */ readonly isToggled: boolean; /** * Whether the command item is toggleable. */ readonly isToggleable: boolean; /** * Whether the command item is visible. */ readonly isVisible: boolean; /** * The key binding for the command item. */ readonly keyBinding: CommandRegistry.IKeyBinding | null; } /** * The render data for a command palette header. */ export interface IHeaderRenderData { /** * The category of the header. */ readonly category: string; /** * The indices of the matched characters in the category. */ readonly indices: ReadonlyArray<number> | null; } /** * The render data for a command palette item. */ export interface IItemRenderData { /** * The command palette item to render. */ readonly item: IItem; /** * The indices of the matched characters in the label. */ readonly indices: ReadonlyArray<number> | null; /** * Whether the item is the active item. */ readonly active: boolean; } /** * The render data for a command palette empty message. */ export interface IEmptyMessageRenderData { /** * The query which failed to match any commands. */ query: string; } /** * A renderer for use with a command palette. */ export interface IRenderer { /** * Render the virtual element for a command palette header. * * @param data - The data to use for rendering the header. * * @returns A virtual element representing the header. */ renderHeader(data: IHeaderRenderData): VirtualElement; /** * Render the virtual element for a command palette item. * * @param data - The data to use for rendering the item. * * @returns A virtual element representing the item. * * #### Notes * The command palette will not render invisible items. */ renderItem(data: IItemRenderData): VirtualElement; /** * Render the empty results message for a command palette. * * @param data - The data to use for rendering the message. * * @returns A virtual element representing the message. */ renderEmptyMessage(data: IEmptyMessageRenderData): VirtualElement; } /** * The default implementation of `IRenderer`. */ export class Renderer implements IRenderer { /** * Render the virtual element for a command palette header. * * @param data - The data to use for rendering the header. * * @returns A virtual element representing the header. */ renderHeader(data: IHeaderRenderData): VirtualElement { let content = this.formatHeader(data); return h.li({ className: 'lm-CommandPalette-header' /* <DEPRECATED> */ + ' p-CommandPalette-header' /* </DEPRECATED> */ }, content); } /** * Render the virtual element for a command palette item. * * @param data - The data to use for rendering the item. * * @returns A virtual element representing the item. */ renderItem(data: IItemRenderData): VirtualElement { let className = this.createItemClass(data); let dataset = this.createItemDataset(data); if (data.item.isToggleable) { return ( h.li({ className, dataset, role: 'checkbox', 'aria-checked': `${data.item.isToggled}` }, this.renderItemIcon(data), this.renderItemContent(data), this.renderItemShortcut(data)) ) } return ( h.li({ className, dataset }, this.renderItemIcon(data), this.renderItemContent(data), this.renderItemShortcut(data), ) ); } /** * Render the empty results message for a command palette. * * @param data - The data to use for rendering the message. * * @returns A virtual element representing the message. */ renderEmptyMessage(data: IEmptyMessageRenderData): VirtualElement { let content = this.formatEmptyMessage(data); return h.li({ className: 'lm-CommandPalette-emptyMessage' /* <DEPRECATED> */ + ' p-CommandPalette-emptyMessage' /* </DEPRECATED> */ }, content); } /** * Render the icon for a command palette item. * * @param data - The data to use for rendering the icon. * * @returns A virtual element representing the icon. */ renderItemIcon(data: IItemRenderData): VirtualElement { let className = this.createIconClass(data); /* <DEPRECATED> */ if (typeof data.item.icon === 'string') { return h.div({className}, data.item.iconLabel); } /* </DEPRECATED> */ // if data.item.icon is undefined, it will be ignored return h.div({className}, data.item.icon!, data.item.iconLabel); } /** * Render the content for a command palette item. * * @param data - The data to use for rendering the content. * * @returns A virtual element representing the content. */ renderItemContent(data: IItemRenderData): VirtualElement { return ( h.div({ className: 'lm-CommandPalette-itemContent' /* <DEPRECATED> */ + ' p-CommandPalette-itemContent' /* </DEPRECATED> */ }, this.renderItemLabel(data), this.renderItemCaption(data) ) ); } /** * Render the label for a command palette item. * * @param data - The data to use for rendering the label. * * @returns A virtual element representing the label. */ renderItemLabel(data: IItemRenderData): VirtualElement { let content = this.formatItemLabel(data); return h.div({ className: 'lm-CommandPalette-itemLabel' /* <DEPRECATED> */ + ' p-CommandPalette-itemLabel' /* </DEPRECATED> */ }, content); } /** * Render the caption for a command palette item. * * @param data - The data to use for rendering the caption. * * @returns A virtual element representing the caption. */ renderItemCaption(data: IItemRenderData): VirtualElement { let content = this.formatItemCaption(data); return h.div({ className: 'lm-CommandPalette-itemCaption' /* <DEPRECATED> */ + ' p-CommandPalette-itemCaption' /* </DEPRECATED> */ }, content); } /** * Render the shortcut for a command palette item. * * @param data - The data to use for rendering the shortcut. * * @returns A virtual element representing the shortcut. */ renderItemShortcut(data: IItemRenderData): VirtualElement { let content = this.formatItemShortcut(data); return h.div({ className: 'lm-CommandPalette-itemShortcut' /* <DEPRECATED> */ + ' p-CommandPalette-itemShortcut' /* </DEPRECATED> */ }, content); } /** * Create the class name for the command palette item. * * @param data - The data to use for the class name. * * @returns The full class name for the command palette item. */ createItemClass(data: IItemRenderData): string { // Set up the initial class name. let name = 'lm-CommandPalette-item'; /* <DEPRECATED> */ name += ' p-CommandPalette-item'; /* </DEPRECATED> */ // Add the boolean state classes. if (!data.item.isEnabled) { name += ' lm-mod-disabled'; /* <DEPRECATED> */ name += ' p-mod-disabled'; /* </DEPRECATED> */ } if (data.item.isToggled) { name += ' lm-mod-toggled'; /* <DEPRECATED> */ name += ' p-mod-toggled'; /* </DEPRECATED> */ } if (data.active) { name += ' lm-mod-active'; /* <DEPRECATED> */ name += ' p-mod-active'; /* </DEPRECATED> */ } // Add the extra class. let extra = data.item.className; if (extra) { name += ` ${extra}`; } // Return the complete class name. return name; } /** * Create the dataset for the command palette item. * * @param data - The data to use for creating the dataset. * * @returns The dataset for the command palette item. */ createItemDataset(data: IItemRenderData): ElementDataset { return { ...data.item.dataset, command: data.item.command }; } /** * Create the class name for the command item icon. * * @param data - The data to use for the class name. * * @returns The full class name for the item icon. */ createIconClass(data: IItemRenderData): string { let name = 'lm-CommandPalette-itemIcon'; /* <DEPRECATED> */ name += ' p-CommandPalette-itemIcon'; /* </DEPRECATED> */ let extra = data.item.iconClass; return extra ? `${name} ${extra}` : name; } /** * Create the render content for the header node. * * @param data - The data to use for the header content. * * @returns The content to add to the header node. */ formatHeader(data: IHeaderRenderData): h.Child { if (!data.indices || data.indices.length === 0) { return data.category; } return StringExt.highlight(data.category, data.indices, h.mark); } /** * Create the render content for the empty message node. * * @param data - The data to use for the empty message content. * * @returns The content to add to the empty message node. */ formatEmptyMessage(data: IEmptyMessageRenderData): h.Child { return `No commands found that match '${data.query}'`; } /** * Create the render content for the item shortcut node. * * @param data - The data to use for the shortcut content. * * @returns The content to add to the shortcut node. */ formatItemShortcut(data: IItemRenderData): h.Child { let kb = data.item.keyBinding; return kb ? kb.keys.map(CommandRegistry.formatKeystroke).join(', ') : null; } /** * Create the render content for the item label node. * * @param data - The data to use for the label content. * * @returns The content to add to the label node. */ formatItemLabel(data: IItemRenderData): h.Child { if (!data.indices || data.indices.length === 0) { return data.item.label; } return StringExt.highlight(data.item.label, data.indices, h.mark); } /** * Create the render content for the item caption node. * * @param data - The data to use for the caption content. * * @returns The content to add to the caption node. */ formatItemCaption(data: IItemRenderData): h.Child { return data.item.caption; } } /** * The default `Renderer` instance. */ export const defaultRenderer = new Renderer(); } /** * The namespace for the module implementation details. */ namespace Private { /** * Create the DOM node for a command palette. */ export function createNode(): HTMLDivElement { let node = document.createElement('div'); let search = document.createElement('div'); let wrapper = document.createElement('div'); let input = document.createElement('input'); let content = document.createElement('ul'); let clear = document.createElement('button'); search.className = 'lm-CommandPalette-search'; wrapper.className = 'lm-CommandPalette-wrapper'; input.className = 'lm-CommandPalette-input'; clear.className = 'lm-close-icon'; content.className = 'lm-CommandPalette-content'; /* <DEPRECATED> */ search.classList.add('p-CommandPalette-search'); wrapper.classList.add('p-CommandPalette-wrapper'); input.classList.add('p-CommandPalette-input'); content.classList.add('p-CommandPalette-content'); /* </DEPRECATED> */ input.spellcheck = false; wrapper.appendChild(input); wrapper.appendChild(clear); search.appendChild(wrapper); node.appendChild(search); node.appendChild(content); return node; } /** * Create a new command item from a command registry and options. */ export function createItem(commands: CommandRegistry, options: CommandPalette.IItemOptions): CommandPalette.IItem { return new CommandItem(commands, options); } /** * A search result object for a header label. */ export interface IHeaderResult { /** * The discriminated type of the object. */ readonly type: 'header'; /** * The category for the header. */ readonly category: string; /** * The indices of the matched category characters. */ readonly indices: ReadonlyArray<number> | null; } /** * A search result object for a command item. */ export interface IItemResult { /** * The discriminated type of the object. */ readonly type: 'item'; /** * The command item which was matched. */ readonly item: CommandPalette.IItem; /** * The indices of the matched label characters. */ readonly indices: ReadonlyArray<number> | null; } /** * A type alias for a search result item. */ export type SearchResult = IHeaderResult | IItemResult; /** * Search an array of command items for fuzzy matches. */ export function search(items: CommandPalette.IItem[], query: string): SearchResult[] { // Fuzzy match the items for the query. let scores = matchItems(items, query); // Sort the items based on their score. scores.sort(scoreCmp); // Create the results for the search. return createResults(scores); } /** * Test whether a result item can be activated. */ export function canActivate(result: SearchResult): boolean { return result.type === 'item' && result.item.isEnabled; } /** * Normalize a category for a command item. */ function normalizeCategory(category: string): string { return category.trim().replace(/\s+/g, ' '); } /** * Normalize the query text for a fuzzy search. */ function normalizeQuery(text: string): string { return text.replace(/\s+/g, '').toLowerCase(); } /** * An enum of the supported match types. */ const enum MatchType { Label, Category, Split, Default } /** * A text match score with associated command item. */ interface IScore { /** * The numerical type for the text match. */ matchType: MatchType; /** * The numerical score for the text match. */ score: number; /** * The indices of the matched category characters. */ categoryIndices: number[] | null; /** * The indices of the matched label characters. */ labelIndices: number[] | null; /** * The command item associated with the match. */ item: CommandPalette.IItem; } /** * Perform a fuzzy match on an array of command items. */ function matchItems(items: CommandPalette.IItem[], query: string): IScore[] { // Normalize the query text to lower case with no whitespace. query = normalizeQuery(query); // Create the array to hold the scores. let scores: IScore[] = []; // Iterate over the items and match against the query. for (let i = 0, n = items.length; i < n; ++i) { // Ignore items which are not visible. let item = items[i]; if (!item.isVisible) { continue; } // If the query is empty, all items are matched by default. if (!query) { scores.push({ matchType: MatchType.Default, categoryIndices: null, labelIndices: null, score: 0, item }); continue; } // Run the fuzzy search for the item and query. let score = fuzzySearch(item, query); // Ignore the item if it is not a match. if (!score) { continue; } // Penalize disabled items. // TODO - push disabled items all the way down in sort cmp? if (!item.isEnabled) { score.score += 1000; } // Add the score to the results. scores.push(score); } // Return the final array of scores. return scores; } /** * Perform a fuzzy search on a single command item. */ function fuzzySearch(item: CommandPalette.IItem, query: string): IScore | null { // Create the source text to be searched. let category = item.category.toLowerCase(); let label = item.label.toLowerCase(); let source = `${category} ${label}`; // Set up the match score and indices array. let score = Infinity; let indices: number[] | null = null; // The regex for search word boundaries let rgx = /\b\w/g; // Search the source by word boundary. while (true) { // Find the next word boundary in the source. let rgxMatch = rgx.exec(source); // Break if there is no more source context. if (!rgxMatch) { break; } // Run the string match on the relevant substring. let match = StringExt.matchSumOfDeltas(source, query, rgxMatch.index); // Break if there is no match. if (!match) { break; } // Update the match if the score is better. if (match && match.score <= score) { score = match.score; indices = match.indices; } } // Bail if there was no match. if (!indices || score === Infinity) { return null; } // Compute the pivot index between category and label text. let pivot = category.length + 1; // Find the slice index to separate matched indices. let j = ArrayExt.lowerBound(indices, pivot, (a, b) => a - b); // Extract the matched category and label indices. let categoryIndices = indices.slice(0, j); let labelIndices = indices.slice(j); // Adjust the label indices for the pivot offset. for (let i = 0, n = labelIndices.length; i < n; ++i) { labelIndices[i] -= pivot; } // Handle a pure label match. if (categoryIndices.length === 0) { return { matchType: MatchType.Label, categoryIndices: null, labelIndices, score, item }; } // Handle a pure category match. if (labelIndices.length === 0) { return { matchType: MatchType.Category, categoryIndices, labelIndices: null, score, item }; } // Handle a split match. return { matchType: MatchType.Split, categoryIndices, labelIndices, score, item }; } /** * A sort comparison function for a match score. */ function scoreCmp(a: IScore, b: IScore): number { // First compare based on the match type let m1 = a.matchType - b.matchType; if (m1 !== 0) { return m1; } // Otherwise, compare based on the match score. let d1 = a.score - b.score; if (d1 !== 0) { return d1; } // Find the match index based on the match type. let i1 = 0; let i2 = 0; switch (a.matchType) { case MatchType.Label: i1 = a.labelIndices![0]; i2 = b.labelIndices![0]; break; case MatchType.Category: case MatchType.Split: i1 = a.categoryIndices![0]; i2 = b.categoryIndices![0]; break; } // Compare based on the match index. if (i1 !== i2) { return i1 - i2; } // Otherwise, compare by category. let d2 = a.item.category.localeCompare(b.item.category); if (d2 !== 0) { return d2; } // Otherwise, compare by rank. let r1 = a.item.rank; let r2 = b.item.rank; if (r1 !== r2) { return r1 < r2 ? -1 : 1; // Infinity safe } // Finally, compare by label. return a.item.label.localeCompare(b.item.label); } /** * Create the results from an array of sorted scores. */ function createResults(scores: IScore[]): SearchResult[] { // Set up an array to track which scores have been visited. let visited = new Array(scores.length); ArrayExt.fill(visited, false); // Set up the search results array. let results: SearchResult[] = []; // Iterate over each score in the array. for (let i = 0, n = scores.length; i < n; ++i) { // Ignore a score which has already been processed. if (visited[i]) { continue; } // Extract the current item and indices. let { item, categoryIndices } = scores[i]; // Extract the category for the current item. let category = item.category; // Add the header result for the category. results.push({ type: 'header', category, indices: categoryIndices }); // Find the rest of the scores with the same category. for (let j = i; j < n; ++j) { // Ignore a score which has already been processed. if (visited[j]) { continue; } // Extract the data for the current score. let { item, labelIndices } = scores[j]; // Ignore an item with a different category. if (item.category !== category) { continue; } // Create the item result for the score. results.push({ type: 'item', item, indices: labelIndices }); // Mark the score as processed. visited[j] = true; } } // Return the final results. return results; } /** * A concrete implementation of `CommandPalette.IItem`. */ class CommandItem implements CommandPalette.IItem { /** * Construct a new command item. */ constructor(commands: CommandRegistry, options: CommandPalette.IItemOptions) { this._commands = commands; this.category = normalizeCategory(options.category); this.command = options.command; this.args = options.args || JSONExt.emptyObject; this.rank = options.rank !== undefined ? options.rank : Infinity; } /** * The category for the command item. */ readonly category: string; /** * The command to execute when the item is triggered. */ readonly command: string; /** * The arguments for the command. */ readonly args: ReadonlyJSONObject; /** * The rank for the command item. */ readonly rank: number; /** * The display label for the command item. */ get label(): string { return this._commands.label(this.command, this.args); } /** * The icon renderer for the command item. */ get icon(): VirtualElement.IRenderer | undefined /* <DEPRECATED> */ | string /* </DEPRECATED> */ { return this._commands.icon(this.command, this.args); } /** * The icon class for the command item. */ get iconClass(): string { return this._commands.iconClass(this.command, this.args); } /** * The icon label for the command item. */ get iconLabel(): string { return this._commands.iconLabel(this.command, this.args); } /** * The display caption for the command item. */ get caption(): string { return this._commands.caption(this.command, this.args); } /** * The extra class name for the command item. */ get className(): string { return this._commands.className(this.command, this.args); } /** * The dataset for the command item. */ get dataset(): CommandRegistry.Dataset { return this._commands.dataset(this.command, this.args); } /** * Whether the command item is enabled. */ get isEnabled(): boolean { return this._commands.isEnabled(this.command, this.args); } /** * Whether the command item is toggled. */ get isToggled(): boolean { return this._commands.isToggled(this.command, this.args); } /** * Whether the command item is toggleable. */ get isToggleable(): boolean { return this._commands.isToggleable(this.command, this.args); } /** * Whether the command item is visible. */ get isVisible(): boolean { return this._commands.isVisible(this.command, this.args); } /** * The key binding for the command item. */ get keyBinding(): CommandRegistry.IKeyBinding | null { let { command, args } = this; return ArrayExt.findLastValue(this._commands.keyBindings, kb => { return kb.command === command && JSONExt.deepEqual(kb.args, args); }) || null; } private _commands: CommandRegistry; } }
the_stack
import { ERC20Wrapper } from '@0x/contracts-asset-proxy'; import { blockchainTests, describe } from '@0x/contracts-test-utils'; import * as _ from 'lodash'; import { deployAndConfigureContractsAsync, StakingApiWrapper } from './utils/api_wrapper'; import { CumulativeRewardTrackingSimulation, TestAction } from './utils/cumulative_reward_tracking_simulation'; // tslint:disable:no-unnecessary-type-assertion // tslint:disable:max-file-line-count blockchainTests.resets('Cumulative Reward Tracking', env => { // tokens & addresses let accounts: string[]; let owner: string; // wrappers let stakingApiWrapper: StakingApiWrapper; let simulation: CumulativeRewardTrackingSimulation; // let testWrapper: TestRewardBalancesContract; let erc20Wrapper: ERC20Wrapper; // tests before(async () => { // create accounts accounts = await env.getAccountAddressesAsync(); owner = accounts[0]; const actors = accounts.slice(1); // set up ERC20Wrapper erc20Wrapper = new ERC20Wrapper(env.provider, accounts, owner); // deploy staking contracts stakingApiWrapper = await deployAndConfigureContractsAsync(env, owner, erc20Wrapper); simulation = new CumulativeRewardTrackingSimulation(stakingApiWrapper, actors); await simulation.deployAndConfigureTestContractsAsync(env); }); describe('Tracking Cumulative Rewards (CR)', () => { it('pool created at epoch 1', async () => { await simulation.runTestAsync([], [TestAction.CreatePool], []); }); it('pool created in epoch >1', async () => { await simulation.runTestAsync([TestAction.Finalize], [TestAction.CreatePool], []); }); it('delegating in the same epoch pool is created', async () => { await simulation.runTestAsync( [ // Creates CR for epoch 1 TestAction.CreatePool, ], [ // Updates CR for epoch 1 // Creates CR for epoch 2 TestAction.Delegate, ], [{ event: 'SetCumulativeReward', epoch: 1 }], ); }); it('re-delegating in the same epoch', async () => { await simulation.runTestAsync( [ // Creates CR for epoch 1 TestAction.CreatePool, ], [ // Updates CR for epoch 1 TestAction.Delegate, // Updates CR for epoch 1 TestAction.Delegate, ], [{ event: 'SetCumulativeReward', epoch: 1 }], ); }); it('delegating in new epoch', async () => { // since there was no delegation in epoch 1 there is no longer a dependency on the CR for epoch 1 await simulation.runTestAsync( [ // Creates CR for epoch 1 TestAction.CreatePool, // Moves to epoch 2 TestAction.Finalize, ], [ // Creates a CR for epoch 2 // Sets MRCR to epoch 2 // Unsets the CR for epoch 1 TestAction.Delegate, ], [{ event: 'SetCumulativeReward', epoch: 2 }], ); }); it('re-delegating in a new epoch', async () => { await simulation.runTestAsync( [ // Creates CR in epoch 1 TestAction.CreatePool, // Updates CR for epoch 1 // Creates CR for epoch 2 TestAction.Delegate, // Moves to epoch 2 TestAction.Finalize, ], [ // Updates CR for epoch 2 // Sets MRCR to epoch 2 TestAction.Delegate, ], [{ event: 'SetCumulativeReward', epoch: 2 }], ); }); it('delegating in epoch 2 then again in epoch 3', async () => { await simulation.runTestAsync( [ // Creates CR for epoch 1 TestAction.CreatePool, // Moves to epoch 2 TestAction.Finalize, // Creates CR for epoch 2 // Sets MRCR to epoch 2 TestAction.Delegate, // Move to epoch 3 TestAction.Finalize, ], [ // Updates CR for epoch 3 // Sets MRCR to epoch 3 // Creates CR for epoch 4 // Clears CR for epoch 2 TestAction.Delegate, ], [{ event: 'SetCumulativeReward', epoch: 3 }], ); }); it('delegate in epoch 2 then undelegate in epoch 3', async () => { await simulation.runTestAsync( [ // Creates CR for epoch 1 TestAction.CreatePool, // Moves to epoch 2 TestAction.Finalize, // Creates CR for epoch 2 // Sets MRCR to epoch 1 // Clears CR for epoch 1 // Creates CR for epoch 3 TestAction.Delegate, // Moves to epoch 3 TestAction.Finalize, ], [ // Update CR for epoch 3 // Set MRCR to epoch 3 // Clear CR for epoch 2 TestAction.Undelegate, ], [{ event: 'SetCumulativeReward', epoch: 3 }], ); }); it('delegate in epoch 1 and epoch 2, then undelegate half in epoch 3', async () => { await simulation.runTestAsync( [ // Create CR for epoch 1 TestAction.CreatePool, // Updates CR for epoch 1 // Sets MRCR to epoch 1 // Creates CR for epoch 2 TestAction.Delegate, // Moves to epoch 2 TestAction.Finalize, // Updates CR for epoch 2 // Sets MRCR to epoch 2 // Creates CR for epoch 3 // Clears CR for epoch 1 TestAction.Delegate, // Moves to epoch 3 TestAction.Finalize, ], [ // Updates CR for epoch 3 // Sets MRCR to epoch 3 // Creates CR for epoch 4 (because there will still be stake) // Clears CR for epoch 2 TestAction.Undelegate, ], [{ event: 'SetCumulativeReward', epoch: 3 }], ); }); it('delegate in epoch 2 and 3 then again in 3', async () => { await simulation.runTestAsync( [ // Creates CR for epoch 1 TestAction.CreatePool, // Updates CR for epoch 1 // Sets MRCR to epoch 1 // Creates CR for epoch 2 TestAction.Delegate, // Moves to epoch 2 TestAction.Finalize, // Updates CR for epoch 2 // Sets MRCR to epoch 2 // Creates CR for epoch 3 // Clears CR for epoch 1 TestAction.Delegate, // Moves to epoch 3 TestAction.Finalize, ], [ // Updates CR for epoch 3 // Sets MRCR to epoch 3 // Creates CR for epoch 4 // Clears CR for epoch 2 TestAction.Delegate, ], [{ event: 'SetCumulativeReward', epoch: 3 }], ); }); it('delegate in epoch 1, earn reward in epoch 2', async () => { await simulation.runTestAsync( [ // Create CR for epoch 1 TestAction.CreatePool, // Updates CR for epoch 1 // Sets MRCR to epoch 1 // Creates CR for epoch 2 TestAction.Delegate, // Moves to epoch 2 TestAction.Finalize, // Credits pool with rewards TestAction.PayProtocolFee, ], [ // Moves to epoch 3 // Creates CR for epoch 3 // Sets MRCR to epoch 3 TestAction.Finalize, ], [{ event: 'SetCumulativeReward', epoch: 3 }], ); }); it('delegate in epoch 1, epoch 3, earn reward in epoch 4, then delegate', async () => { await simulation.runTestAsync( [ // Create CR for epoch 1 TestAction.CreatePool, // Updates CR for epoch 1 // Sets MRCR to epoch 1 // Creates CR for epoch 2 TestAction.Delegate, // Moves to epoch 2 TestAction.Finalize, // Updates CR for epoch 2 // Sets MRCR to epoch 2 // Creates CR for epoch 3 // Clears CR for epoch 1 TestAction.Delegate, // Moves to epoch 3 TestAction.Finalize, // Credits pool with rewards TestAction.PayProtocolFee, // Moves to epoch 4 // Creates CR for epoch 4 // Sets MRCR to epoch 4 TestAction.Finalize, ], [ // Updates CR for epoch 4 // Creates CR for epoch 5 // Clears CR for epoch 2 // Clears CR for epoch 3 TestAction.Delegate, ], [], ); }); it('delegate in epoch 1 and 2, earn reward in epoch 4, then undelegate half', async () => { await simulation.runTestAsync( [ // Create CR for epoch 1 TestAction.CreatePool, // Updates CR for epoch 1 // Sets MRCR to epoch 1 // Creates CR for epoch 2 TestAction.Delegate, // Moves to epoch 2 TestAction.Finalize, // Updates CR for epoch 2 // Sets MRCR to epoch 2 // Creates CR for epoch 3 // Clears CR for epoch 1 TestAction.Delegate, // Moves to epoch 3 TestAction.Finalize, // Credits pool with rewards TestAction.PayProtocolFee, // Moves to epoch 4 // Creates CR for epoch 4 // Sets MRCR to epoch 4 TestAction.Finalize, ], [ // Updates CR for epoch 4 // Creates CR for epoch 5 (because there is still stake remaming) // Clears CR for epoch 2 // Clears CR for epoch 3 TestAction.Undelegate, ], [], ); }); it('delegate in epoch 2, 3, earn rewards in epoch 4, skip to epoch 5, then delegate', async () => { await simulation.runTestAsync( [ // Create CR for epoch 1 TestAction.CreatePool, // Updates CR for epoch 1 // Sets MRCR to epoch 1 // Creates CR for epoch 2 TestAction.Delegate, // Moves to epoch 2 TestAction.Finalize, // Updates CR for epoch 2 // Sets MRCR to epoch 2 // Creates CR for epoch 3 // Clears CR for epoch 1 TestAction.Delegate, // Moves to epoch 3 TestAction.Finalize, // Credits pool with rewards TestAction.PayProtocolFee, // Moves to epoch 4 // Creates CR for epoch 4 // Sets MRCR to epoch 4 TestAction.Finalize, // Moves to epoch 5 TestAction.Finalize, ], [ // Creates CR for epoch 5 // Sets MRCR to epoch 5 // Clears CR for epoch 4 // Creates CR for epoch 6 // Clears CR for epoch 2 TestAction.Delegate, ], [{ event: 'SetCumulativeReward', epoch: 5 }], ); }); it('earn reward in epoch 2 with no stake, then delegate', async () => { await simulation.runTestAsync( [ // Creates CR for epoch 1 TestAction.CreatePool, // Credit pool with rewards TestAction.PayProtocolFee, // Moves to epoch 2 // That's it, because there's no active pools. TestAction.Finalize, ], [ // Updates CR to epoch 2 // Sets MRCR to epoch 2 // Clears CR for epoch 1 // Creates CR for epoch 3 TestAction.Delegate, ], [{ event: 'SetCumulativeReward', epoch: 2 }], ); }); it('delegate in epoch 2, 4, then delegate in epoch 5', async () => { await simulation.runTestAsync( [ // Creates CR for epoch 1 TestAction.CreatePool, // Moves to epoch 2 TestAction.Finalize, // Creates CR for epoch 2 // Sets MRCR to epoch 1 // Clears CR for epoch 1 // Creates CR for epoch 3 TestAction.Delegate, // Moves to epoch 3 TestAction.Finalize, // Moves to epoch 4 TestAction.Finalize, // Creates CR for epoch 4 // Sets MRCR to epoch 4 // Clears CR for epoch 2 // Creates CR for epoch 5 // Clears CR for epoch 3 TestAction.Delegate, // Moves to epoch 5 TestAction.Finalize, ], [ // Updates CR for epoch 5 // Sets MRCR to epoch 5 // Clears CR for epoch 4 // Creates CR for epoch 6 TestAction.Delegate, ], [{ event: 'SetCumulativeReward', epoch: 5 }], ); }); it('delegate in epoch 2, then epoch 4', async () => { await simulation.runTestAsync( [ // Creates CR for epoch 1 TestAction.CreatePool, // Moves to epoch 2 TestAction.Finalize, // Creates CR for epoch 2 // Sets MRCR to epoch 1 // Clears CR for epoch 1 // Creates CR for epoch 3 TestAction.Delegate, // Moves to epoch 3 TestAction.Finalize, // Moves to epoch 4 TestAction.Finalize, ], [ // Creates CR for epoch 4 // Sets MRCR to epoch 4 // Clears CR for epoch 2 // Creates CR for epoch 5 // Clears CR for epoch 3 TestAction.Delegate, ], [{ event: 'SetCumulativeReward', epoch: 4 }], ); }); }); }); // tslint:enable:no-unnecessary-type-assertion
the_stack
import type { TSESTree } from "@typescript-eslint/experimental-utils"; import { AST_NODE_TYPES } from "@typescript-eslint/experimental-utils"; // TS import - only use this for types, will be stripped out by rollup. import type { Type, UnionType } from "typescript"; // TS import - conditionally imported only when typescript is available. import ts from "~/conditional-imports/typescript"; // Any JSDoc for these functions would be tedious. // eslint-disable-next-line eslint-comments/disable-enable-pair /* eslint-disable jsdoc/require-jsdoc */ /* * TS Types. */ export type ArrayType = Type & { readonly symbol: { readonly name: "Array"; }; }; export type ArrayConstructorType = Type & { readonly symbol: { readonly name: "ArrayConstructor"; }; }; export type ObjectConstructorType = Type & { readonly symbol: { readonly name: "ObjectConstructor"; }; }; /* * Basic type guards. */ export function isReadonlyArray( value: unknown ): value is ReadonlyArray<unknown> { return Array.isArray(value); } /* * Node type guards. */ export function isArrayExpression( node: TSESTree.Node ): node is TSESTree.ArrayExpression { return node.type === AST_NODE_TYPES.ArrayExpression; } export function isAssignmentExpression( node: TSESTree.Node ): node is TSESTree.AssignmentExpression { return node.type === AST_NODE_TYPES.AssignmentExpression; } export function isAssignmentPattern( node: TSESTree.Node ): node is TSESTree.AssignmentPattern { return node.type === AST_NODE_TYPES.AssignmentPattern; } export function isBlockStatement( node: TSESTree.Node ): node is TSESTree.BlockStatement { return node.type === AST_NODE_TYPES.BlockStatement; } export function isBreakStatement( node: TSESTree.Node ): node is TSESTree.BreakStatement { return node.type === AST_NODE_TYPES.BreakStatement; } export function isCallExpression( node: TSESTree.Node ): node is TSESTree.CallExpression { return node.type === AST_NODE_TYPES.CallExpression; } export function isPropertyDefinition( node: TSESTree.Node ): node is TSESTree.PropertyDefinition { return node.type === AST_NODE_TYPES.PropertyDefinition; } /** * Is the given node a class node? * * It doesn't matter what type of class. */ export function isClassLike( node: TSESTree.Node ): node is TSESTree.ClassDeclaration | TSESTree.ClassExpression { return ( node.type === AST_NODE_TYPES.ClassDeclaration || node.type === AST_NODE_TYPES.ClassExpression ); } export function isContinueStatement( node: TSESTree.Node ): node is TSESTree.ContinueStatement { return node.type === AST_NODE_TYPES.ContinueStatement; } export function isExpressionStatement( node: TSESTree.Node ): node is TSESTree.ExpressionStatement { return node.type === AST_NODE_TYPES.ExpressionStatement; } export function isFunctionDeclaration( node: TSESTree.Node ): node is TSESTree.FunctionDeclaration { return node.type === AST_NODE_TYPES.FunctionDeclaration; } /** * Is the given node a function expression node? * * It doesn't matter what type of function expression. */ export function isFunctionExpressionLike( node: TSESTree.Node ): node is TSESTree.ArrowFunctionExpression | TSESTree.FunctionExpression { return ( node.type === AST_NODE_TYPES.FunctionExpression || node.type === AST_NODE_TYPES.ArrowFunctionExpression ); } /** * Is the given node a function node? * * It doesn't matter what type of function. */ export function isFunctionLike( node: TSESTree.Node ): node is | TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression { return isFunctionDeclaration(node) || isFunctionExpressionLike(node); } export function isIdentifier(node: TSESTree.Node): node is TSESTree.Identifier { return node.type === AST_NODE_TYPES.Identifier; } export function isIfStatement( node: TSESTree.Node ): node is TSESTree.IfStatement { return node.type === AST_NODE_TYPES.IfStatement; } export function isMemberExpression( node: TSESTree.Node ): node is TSESTree.MemberExpression { return node.type === AST_NODE_TYPES.MemberExpression; } export function isMethodDefinition( node: TSESTree.Node ): node is TSESTree.MethodDefinition { return node.type === AST_NODE_TYPES.MethodDefinition; } export function isNewExpression( node: TSESTree.Node ): node is TSESTree.NewExpression { return node.type === AST_NODE_TYPES.NewExpression; } export function isProperty(node: TSESTree.Node): node is TSESTree.Property { return node.type === AST_NODE_TYPES.Property; } export function isRestElement( node: TSESTree.Node ): node is TSESTree.RestElement { return node.type === AST_NODE_TYPES.RestElement; } export function isReturnStatement( node: TSESTree.Node ): node is TSESTree.ReturnStatement { return node.type === AST_NODE_TYPES.ReturnStatement; } export function isSwitchStatement( node: TSESTree.Node ): node is TSESTree.SwitchStatement { return node.type === AST_NODE_TYPES.SwitchStatement; } export function isThisExpression( node: TSESTree.Node ): node is TSESTree.ThisExpression { return node.type === AST_NODE_TYPES.ThisExpression; } export function isThrowStatement( node: TSESTree.Node ): node is TSESTree.ThrowStatement { return node.type === AST_NODE_TYPES.ThrowStatement; } export function isTSArrayType( node: TSESTree.Node ): node is TSESTree.TSArrayType { return node.type === AST_NODE_TYPES.TSArrayType; } export function isTSFunctionType( node: TSESTree.Node ): node is TSESTree.TSFunctionType { return node.type === AST_NODE_TYPES.TSFunctionType; } export function isTSIndexSignature( node: TSESTree.Node ): node is TSESTree.TSIndexSignature { return node.type === AST_NODE_TYPES.TSIndexSignature; } export function isTSInterfaceBody( node: TSESTree.Node ): node is TSESTree.TSInterfaceBody { return node.type === AST_NODE_TYPES.TSInterfaceBody; } export function isTSInterfaceHeritage( node: TSESTree.Node ): node is TSESTree.TSInterfaceHeritage { return node.type === AST_NODE_TYPES.TSInterfaceHeritage; } export function isTSNullKeyword( node: TSESTree.Node ): node is TSESTree.TSNullKeyword { return node.type === AST_NODE_TYPES.TSNullKeyword; } export function isTSParameterProperty( node: TSESTree.Node ): node is TSESTree.TSParameterProperty { return node.type === AST_NODE_TYPES.TSParameterProperty; } export function isTSPropertySignature( node: TSESTree.Node ): node is TSESTree.TSPropertySignature { return node.type === AST_NODE_TYPES.TSPropertySignature; } export function isTSTupleType( node: TSESTree.Node ): node is TSESTree.TSTupleType { return node.type === AST_NODE_TYPES.TSTupleType; } export function isTSTypeAnnotation( node: TSESTree.Node ): node is TSESTree.TSTypeAnnotation { return node.type === AST_NODE_TYPES.TSTypeAnnotation; } export function isTSTypeLiteral( node: TSESTree.Node ): node is TSESTree.TSTypeLiteral { return node.type === AST_NODE_TYPES.TSTypeLiteral; } export function isTSTypeOperator( node: TSESTree.Node ): node is TSESTree.TSTypeOperator { return node.type === AST_NODE_TYPES.TSTypeOperator; } export function isTSTypeReference( node: TSESTree.Node ): node is TSESTree.TSTypeReference { return node.type === AST_NODE_TYPES.TSTypeReference; } export function isTSUndefinedKeyword( node: TSESTree.Node ): node is TSESTree.TSUndefinedKeyword { return node.type === AST_NODE_TYPES.TSUndefinedKeyword; } export function isTSVoidKeyword( node: TSESTree.Node ): node is TSESTree.TSVoidKeyword { return node.type === AST_NODE_TYPES.TSVoidKeyword; } export function isUnaryExpression( node: TSESTree.Node ): node is TSESTree.UnaryExpression { return node.type === AST_NODE_TYPES.UnaryExpression; } export function isVariableDeclaration( node: TSESTree.Node ): node is TSESTree.VariableDeclaration { return node.type === AST_NODE_TYPES.VariableDeclaration; } export function isVariableDeclarator( node: TSESTree.Node ): node is TSESTree.VariableDeclarator { return node.type === AST_NODE_TYPES.VariableDeclarator; } export function hasID( node: TSESTree.Node ): node is TSESTree.Node & { readonly id: unknown } { return Object.prototype.hasOwnProperty.call(node, "id"); } export function hasKey( node: TSESTree.Node ): node is TSESTree.Node & { readonly key: unknown } { return Object.prototype.hasOwnProperty.call(node, "key"); } /* * TS types type guards. */ export function isUnionType(type: Type): type is UnionType { return ts !== undefined && type.flags === ts.TypeFlags.Union; } export function isArrayType(type: Type | null): type is ArrayType; export function isArrayType( type: Type, assumeType: false, node: null ): type is ArrayType; export function isArrayType( type: Type | null, assumeType: boolean, node: TSESTree.Node | null ): type is ArrayType; export function isArrayType( type: null, assumeType: true, node: TSESTree.Node ): boolean; export function isArrayType( type: Type | null, assumeType = false, node: TSESTree.Node | null = null ): boolean { return assumeType === true && type === null ? node !== null : type !== null && ((type.symbol !== undefined && type.symbol.name === "Array") || (isUnionType(type) && type.types.some((t) => isArrayType(t, false, null)))); } export function isArrayConstructorType( type: Type | null ): type is ArrayConstructorType; export function isArrayConstructorType( type: Type, assumeType: false, node: null ): type is ArrayConstructorType; export function isArrayConstructorType( type: Type | null, assumeType: boolean, node: TSESTree.Node | null ): type is ArrayConstructorType; export function isArrayConstructorType( type: null, assumeType: true, node: TSESTree.Node ): boolean; export function isArrayConstructorType( type: Type | null, assumeType = false, node: TSESTree.Node | null = null ): boolean { return assumeType === true && type === null ? node !== null && isIdentifier(node) && node.name === "Array" : type !== null && ((type.symbol !== undefined && type.symbol.name === "ArrayConstructor") || (isUnionType(type) && type.types.some((t) => isArrayConstructorType(t, false, null)))); } export function isObjectConstructorType( type: Type | null ): type is ObjectConstructorType; export function isObjectConstructorType( type: Type, assumeType: false, node: null ): type is ObjectConstructorType; export function isObjectConstructorType( type: Type | null, assumeType: boolean, node: TSESTree.Node | null ): type is ObjectConstructorType; export function isObjectConstructorType( type: null, assumeType: true, node: TSESTree.Node ): boolean; export function isObjectConstructorType( type: Type | null, assumeType = false, node: TSESTree.Node | null = null ): boolean { return assumeType === true && type === null ? node !== null && isIdentifier(node) && node.name === "Object" : type !== null && ((type.symbol !== undefined && type.symbol.name === "ObjectConstructor") || (isUnionType(type) && type.types.some((t) => isObjectConstructorType(t, false, null)))); } export function isNeverType(type: Type): boolean { return ts !== undefined && type.flags === ts.TypeFlags.Never; } export function isVoidType(type: Type): boolean { return ts !== undefined && type.flags === ts.TypeFlags.Void; } export function isNullType(type: Type): boolean { return ts !== undefined && type.flags === ts.TypeFlags.Null; } export function isUndefinedType(type: Type): boolean { return ts !== undefined && type.flags === ts.TypeFlags.Undefined; }
the_stack
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { createSelector, select, Store } from '@ngrx/store'; import { Operation } from 'fast-json-patch'; import { Observable } from 'rxjs'; import { find, map, take } from 'rxjs/operators'; import { EPeopleRegistryCancelEPersonAction, EPeopleRegistryEditEPersonAction } from '../../access-control/epeople-registry/epeople-registry.actions'; import { EPeopleRegistryState } from '../../access-control/epeople-registry/epeople-registry.reducers'; import { AppState } from '../../app.reducer'; import { hasValue, hasNoValue } from '../../shared/empty.util'; import { NotificationsService } from '../../shared/notifications/notifications.service'; import { FollowLinkConfig } from '../../shared/utils/follow-link-config.model'; import { dataService } from '../cache/builders/build-decorators'; import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; import { RequestParam } from '../cache/models/request-param.model'; import { ObjectCacheService } from '../cache/object-cache.service'; import { DataService } from '../data/data.service'; import { DSOChangeAnalyzer } from '../data/dso-change-analyzer.service'; import { PaginatedList, buildPaginatedList } from '../data/paginated-list.model'; import { RemoteData } from '../data/remote-data'; import { FindListOptions, PatchRequest, PostRequest, } from '../data/request.models'; import { RequestService } from '../data/request.service'; import { HALEndpointService } from '../shared/hal-endpoint.service'; import { getRemoteDataPayload, getFirstSucceededRemoteData, } from '../shared/operators'; import { EPerson } from './models/eperson.model'; import { EPERSON } from './models/eperson.resource-type'; import { NoContent } from '../shared/NoContent.model'; import { PageInfo } from '../shared/page-info.model'; const ePeopleRegistryStateSelector = (state: AppState) => state.epeopleRegistry; const editEPersonSelector = createSelector(ePeopleRegistryStateSelector, (ePeopleRegistryState: EPeopleRegistryState) => ePeopleRegistryState.editEPerson); /** * A service to retrieve {@link EPerson}s from the REST API & EPerson related CRUD actions */ @Injectable() @dataService(EPERSON) export class EPersonDataService extends DataService<EPerson> { protected linkPath = 'epersons'; protected searchByEmailPath = 'byEmail'; protected searchByMetadataPath = 'byMetadata'; constructor( protected requestService: RequestService, protected rdbService: RemoteDataBuildService, protected store: Store<any>, protected objectCache: ObjectCacheService, protected halService: HALEndpointService, protected notificationsService: NotificationsService, protected http: HttpClient, protected comparator: DSOChangeAnalyzer<EPerson> ) { super(); } /** * Search the EPeople with a given scope and query * @param scope Scope of the EPeople search, default byMetadata * @param query Query of search * @param options Options of search request */ public searchByScope(scope: string, query: string, options: FindListOptions = {}, useCachedVersionIfAvailable?: boolean): Observable<RemoteData<PaginatedList<EPerson>>> { switch (scope) { case 'metadata': return this.getEpeopleByMetadata(query.trim(), options, useCachedVersionIfAvailable); case 'email': return this.getEPersonByEmail(query.trim()).pipe( map((rd: RemoteData<EPerson | NoContent>) => { if (rd.hasSucceeded) { // Turn the single EPerson or NoContent in to a PaginatedList<EPerson> let page; if (rd.statusCode === 204 || hasNoValue(rd.payload)) { page = []; } else { page = [rd.payload]; } return new RemoteData<PaginatedList<EPerson>>( rd.timeCompleted, rd.msToLive, rd.lastUpdated, rd.state, rd.errorMessage, buildPaginatedList(new PageInfo({ elementsPerPage: options.elementsPerPage, totalElements: page.length, totalPages: page.length, currentPage: 1 }), page), rd.statusCode ); } else { // If it hasn't succeeded, there can be no payload, so we can re-cast the existing // RemoteData object return rd as RemoteData<PaginatedList<EPerson>>; } }) ); default: return this.getEpeopleByMetadata(query.trim(), options, useCachedVersionIfAvailable); } } /** * Returns a single EPerson, by email query (/eperson/epersons/search/{@link searchByEmailPath}?email=<>). If it can be found * NoContent otherwise * * @param query email query * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved */ public getEPersonByEmail(query: string, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<EPerson>[]): Observable<RemoteData<EPerson | NoContent>> { const findListOptions = new FindListOptions(); findListOptions.searchParams = [new RequestParam('email', encodeURIComponent(query))]; const href$ = this.getSearchByHref(this.searchByEmailPath, findListOptions, ...linksToFollow); return this.findByHref(href$, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } /** * Returns a search result list of EPeople, by metadata query (/eperson/epersons/search/{@link searchByMetadataPath}?query=<>) * @param query metadata query * @param options * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved */ private getEpeopleByMetadata(query: string, options?: FindListOptions, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<EPerson>[]): Observable<RemoteData<PaginatedList<EPerson>>> { const searchParams = [new RequestParam('query', encodeURIComponent(query))]; return this.getEPeopleBy(searchParams, this.searchByMetadataPath, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } /** * Returns a search result list of EPeople in a given searchMethod, with given searchParams * @param searchParams query parameters in the search * @param searchMethod searchBy path * @param options * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved */ private getEPeopleBy(searchParams: RequestParam[], searchMethod: string, options?: FindListOptions, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<EPerson>[]): Observable<RemoteData<PaginatedList<EPerson>>> { let findListOptions = new FindListOptions(); if (options) { findListOptions = Object.assign(new FindListOptions(), options); } if (findListOptions.searchParams) { findListOptions.searchParams = [...findListOptions.searchParams, ...searchParams]; } else { findListOptions.searchParams = searchParams; } return this.searchBy(searchMethod, findListOptions, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } /** * Add a new patch to the object cache * The patch is derived from the differences between the given object and its version in the object cache * @param {DSpaceObject} ePerson The given object */ public updateEPerson(ePerson: EPerson): Observable<RemoteData<EPerson>> { const requestId = this.requestService.generateRequestId(); const oldVersion$ = this.findByHref(ePerson._links.self.href, true, false); oldVersion$.pipe( getFirstSucceededRemoteData(), getRemoteDataPayload(), take(1) ).subscribe((oldEPerson: EPerson) => { const operations = this.generateOperations(oldEPerson, ePerson); const patchRequest = new PatchRequest(requestId, ePerson._links.self.href, operations); return this.requestService.send(patchRequest); }); return this.rdbService.buildFromRequestUUID(requestId); } /** * Metadata operations are generated by the difference between old and new EPerson * Custom replace operations for the other EPerson values * @param oldEPerson * @param newEPerson */ private generateOperations(oldEPerson: EPerson, newEPerson: EPerson): Operation[] { let operations = this.comparator.diff(oldEPerson, newEPerson).filter((operation: Operation) => operation.op === 'replace'); if (hasValue(oldEPerson.email) && oldEPerson.email !== newEPerson.email) { operations = [...operations, { op: 'replace', path: '/email', value: newEPerson.email }]; } if (hasValue(oldEPerson.requireCertificate) && oldEPerson.requireCertificate !== newEPerson.requireCertificate) { operations = [...operations, { op: 'replace', path: '/certificate', value: newEPerson.requireCertificate }]; } if (hasValue(oldEPerson.canLogIn) && oldEPerson.canLogIn !== newEPerson.canLogIn) { operations = [...operations, { op: 'replace', path: '/canLogIn', value: newEPerson.canLogIn }]; } return operations; } /** * Method that clears a cached EPerson request */ public clearEPersonRequests(): void { this.getBrowseEndpoint().pipe(take(1)).subscribe((link: string) => { this.requestService.removeByHrefSubstring(link); }); } /** * Method that clears a link's requests in cache */ public clearLinkRequests(href: string): void { this.requestService.setStaleByHrefSubstring(href); } /** * Method to retrieve the eperson that is currently being edited */ public getActiveEPerson(): Observable<EPerson> { return this.store.pipe(select(editEPersonSelector)); } /** * Method to cancel editing an EPerson, dispatches a cancel EPerson action */ public cancelEditEPerson() { this.store.dispatch(new EPeopleRegistryCancelEPersonAction()); } /** * Method to set the EPerson being edited, dispatches an edit EPerson action * @param ePerson The EPerson to edit */ public editEPerson(ePerson: EPerson) { this.store.dispatch(new EPeopleRegistryEditEPersonAction(ePerson)); } /** * Method to delete an EPerson * @param ePerson The EPerson to delete */ public deleteEPerson(ePerson: EPerson): Observable<RemoteData<NoContent>> { return this.delete(ePerson.id); } /** * Change which ePerson is being edited and return the link for EPeople edit page * @param ePerson New EPerson to edit */ public startEditingNewEPerson(ePerson: EPerson): string { this.getActiveEPerson().pipe(take(1)).subscribe((activeEPerson: EPerson) => { if (ePerson === activeEPerson) { this.cancelEditEPerson(); } else { this.editEPerson(ePerson); } }); return '/access-control/epeople'; } /** * Get EPeople admin page * @param ePerson New EPerson to edit */ public getEPeoplePageRouterLink(): string { return '/access-control/epeople'; } /** * Create a new EPerson using a token * @param eperson * @param token */ public createEPersonForToken(eperson: EPerson, token: string): Observable<RemoteData<EPerson>> { const requestId = this.requestService.generateRequestId(); const hrefObs = this.getBrowseEndpoint().pipe( map((href: string) => `${href}?token=${token}`)); hrefObs.pipe( find((href: string) => hasValue(href)), ).subscribe((href: string) => { const request = new PostRequest(requestId, href, eperson); this.requestService.send(request); }); return this.rdbService.buildFromRequestUUID(requestId); } /** * Sends a patch request to update an epersons password based on a forgot password token * @param uuid Uuid of the eperson * @param token The forgot password token * @param password The new password value */ patchPasswordWithToken(uuid: string, token: string, password: string): Observable<RemoteData<EPerson>> { const requestId = this.requestService.generateRequestId(); const operation = Object.assign({ op: 'add', path: '/password', value: password }); const hrefObs = this.halService.getEndpoint(this.linkPath).pipe( map((endpoint: string) => this.getIDHref(endpoint, uuid)), map((href: string) => `${href}?token=${token}`)); hrefObs.pipe( find((href: string) => hasValue(href)), ).subscribe((href: string) => { const request = new PatchRequest(requestId, href, [operation]); this.requestService.send(request); }); return this.rdbService.buildFromRequestUUID(requestId); } }
the_stack
import { fAccounts, fAdvancedERC20TxSendFormikFields, fAdvancedETHTxSendFormikFields, fAssets, fERC20NonWeb3TxConfig, fERC20TxSendFormikFields, fETHNonWeb3TxConfig, fETHTxSendFormikFields, fETHTxSendFormikFieldsEIP1559, fNetwork } from '@fixtures'; import { translateRaw } from '@translations'; import { ILegacyTxObject, TAddress, TTicker, TxQueryTypes } from '@types'; import { generateGenericErc20, isERC20Asset, parseQueryParams, parseTransactionQueryParams, processFormDataToTx, processFormForEstimateGas } from './helpers'; const validETHSpeedUpQuery = { queryType: TxQueryTypes.SPEEDUP, gasLimit: '0x5208', chainId: '3', nonce: '0x6', gasPrice: '0x12a05f200', from: '0xB2BB2b958aFA2e96dAb3F3Ce7162B87dAea39017', to: '0xB2BB2b958aFA2e96dAb3F3Ce7162B87dAea39017', value: '0x2386f26fc10000', data: '0x' }; const validETHSpeedUpQueryEIP1559 = { queryType: TxQueryTypes.SPEEDUP, gasLimit: '0x5208', chainId: '3', nonce: '0x6', maxFeePerGas: '0x4a817c800', maxPriorityFeePerGas: '0x3b9aca00', from: '0xB2BB2b958aFA2e96dAb3F3Ce7162B87dAea39017', to: '0xB2BB2b958aFA2e96dAb3F3Ce7162B87dAea39017', value: '0x2386f26fc10000', data: '0x' }; const validERC20SpeedUpQuery = { queryType: TxQueryTypes.SPEEDUP, gasLimit: '0x7d3c', chainId: '3', nonce: '0x7', gasPrice: '0x12a05f200', from: '0xB2BB2b958aFA2e96dAb3F3Ce7162B87dAea39017', to: '0xad6d458402f60fd3bd25163575031acdce07538d', // DAI contract address value: '0x0', data: '0xa9059cbb000000000000000000000000b2bb2b958AFa2e96dab3f3Ce7162b87daEa39017000000000000000000000000000000000000000000000000002386f26fc10000' // Transfer method call }; const invalidSpeedUpQuery = { queryType: TxQueryTypes.SPEEDUP, gasLimit: '0x5208', chainId: '3', nonce: '0x60' }; const validETHCancelQuery = { queryType: TxQueryTypes.CANCEL, gasLimit: '0x5208', chainId: '3', nonce: '0x6', gasPrice: '0x12a05f200', from: '0xB2BB2b958aFA2e96dAb3F3Ce7162B87dAea39017', to: '0xB2BB2b958aFA2e96dAb3F3Ce7162B87dAea39017', value: '0x2386f26fc10000', data: '0x' }; const validERC20CancelQuery = { queryType: TxQueryTypes.CANCEL, gasLimit: '0x7d3c', chainId: '3', nonce: '0x7', gasPrice: '0x12a05f200', from: '0xB2BB2b958aFA2e96dAb3F3Ce7162B87dAea39017', to: '0xad6d458402f60fd3bd25163575031acdce07538d', // DAI contract address value: '0x0', data: '0xa9059cbb000000000000000000000000b2bb2b958AFa2e96dab3f3Ce7162b87daEa39017000000000000000000000000000000000000000000000000002386f26fc10000' // Transfer method call }; const invalidCancelQuery = { queryType: TxQueryTypes.CANCEL, gasLimit: '0x5208', chainId: '3', nonce: '0x60' }; describe('Query string parsing', () => { it('parses valid erc20 tx query parameters correctly - speed up', () => { const parsedQueryParams = parseQueryParams(validERC20SpeedUpQuery)( [fNetwork], fAssets, fAccounts ); expect(parsedQueryParams).toStrictEqual({ queryType: TxQueryTypes.SPEEDUP, txConfig: fERC20NonWeb3TxConfig }); }); it('parses valid eth tx query parameters correctly - speed up', () => { const parsedQueryParams = parseQueryParams(validETHSpeedUpQuery)( [fNetwork], fAssets, fAccounts ); expect(parsedQueryParams).toStrictEqual({ queryType: TxQueryTypes.SPEEDUP, txConfig: fETHNonWeb3TxConfig }); }); it('parses valid eth tx query parameters correctly - speed up EIP 1559', () => { const parsedQueryParams = parseQueryParams(validETHSpeedUpQueryEIP1559)( [fNetwork], fAssets, fAccounts ); const { gasPrice, ...rawTransaction } = fETHNonWeb3TxConfig.rawTransaction as ILegacyTxObject; expect(parsedQueryParams).toStrictEqual({ queryType: TxQueryTypes.SPEEDUP, txConfig: { ...fETHNonWeb3TxConfig, rawTransaction: { ...rawTransaction, maxFeePerGas: '0x4a817c800', maxPriorityFeePerGas: '0x3b9aca00', type: 2 } } }); }); it('parses valid erc20 tx query parameters correctly - cancel', () => { const parsedQueryParams = parseQueryParams(validERC20CancelQuery)( [fNetwork], fAssets, fAccounts ); expect(parsedQueryParams).toStrictEqual({ queryType: TxQueryTypes.CANCEL, txConfig: fERC20NonWeb3TxConfig }); }); it('parses valid eth tx query parameters correctly - cancel', () => { const parsedQueryParams = parseQueryParams(validETHCancelQuery)([fNetwork], fAssets, fAccounts); expect(parsedQueryParams).toStrictEqual({ queryType: TxQueryTypes.CANCEL, txConfig: fETHNonWeb3TxConfig }); }); it('fails to derive txConfig when invalid eth tx query parameters are included - cancel', () => { const parsedQueryParams = parseQueryParams(invalidCancelQuery)([fNetwork], fAssets, fAccounts); expect(parsedQueryParams).toStrictEqual({ queryType: TxQueryTypes.CANCEL, txConfig: undefined }); }); it('fails to derive txConfig when there is no network config for specified chainID - cancel', () => { const parsedQueryParams = parseQueryParams(validETHCancelQuery)([], fAssets, fAccounts); expect(parsedQueryParams).toStrictEqual({ queryType: TxQueryTypes.CANCEL, txConfig: undefined }); }); it('fails to derive txConfig when there is no added account with from address - cancel', () => { const parsedQueryParams = parseQueryParams(validETHCancelQuery)([fNetwork], fAssets, []); expect(parsedQueryParams).toStrictEqual({ queryType: TxQueryTypes.CANCEL, txConfig: undefined }); }); it('fails to derive txConfig when invalid eth tx query parameters are included - speed up', () => { const parsedQueryParams = parseQueryParams(invalidSpeedUpQuery)([fNetwork], fAssets, fAccounts); expect(parsedQueryParams).toStrictEqual({ queryType: TxQueryTypes.SPEEDUP, txConfig: undefined }); }); it('fails to derive txConfig when there is no network config for specified chainID - speed up', () => { const parsedQueryParams = parseQueryParams(validETHSpeedUpQuery)([], fAssets, fAccounts); expect(parsedQueryParams).toStrictEqual({ queryType: TxQueryTypes.SPEEDUP, txConfig: undefined }); }); it('fails to derive txConfig when there is no added account with from address - speed up', () => { const parsedQueryParams = parseQueryParams(validETHSpeedUpQuery)([fNetwork], fAssets, []); expect(parsedQueryParams).toStrictEqual({ queryType: TxQueryTypes.SPEEDUP, txConfig: undefined }); }); it('fails on invalid input', () => { const parsedQueryParams = parseQueryParams({ queryType: undefined })([fNetwork], fAssets, []); expect(parsedQueryParams).toStrictEqual({ queryType: TxQueryTypes.DEFAULT }); }); }); describe('parseTransactionQueryParams', () => { it('correctly parses valid erc20 speedup query params', () => { const parsedSpeedUpParams = parseTransactionQueryParams(validERC20SpeedUpQuery)( [fNetwork], fAssets, fAccounts ); expect(parsedSpeedUpParams).toEqual(fERC20NonWeb3TxConfig); }); it('correctly parses valid eth speedup query params', () => { const parsedSpeedUpParams = parseTransactionQueryParams(validETHSpeedUpQuery)( [fNetwork], fAssets, fAccounts ); expect(parsedSpeedUpParams).toEqual(fETHNonWeb3TxConfig); }); it('correctly handles invalid speedup query params', () => { const parsedSpeedUpParams = parseTransactionQueryParams(invalidSpeedUpQuery)( [fNetwork], fAssets, fAccounts ); expect(parsedSpeedUpParams).toBeUndefined(); }); }); describe('generateGenericErc20', () => { it('creates a generic erc20 token from contract address and chainID', () => { const testGenericERC20 = { uuid: 'e1f698bf-cb85-5405-b563-14774af14bf1', name: translateRaw('GENERIC_ERC20_NAME'), ticker: 'Unknown ERC20' as TTicker, type: 'erc20', networkId: 'Ethereum' }; const genericERC20 = generateGenericErc20( '0x6B175474E89094C44Da98b954EedeAC495271d0F' as TAddress, '1', 'Ethereum' ); expect(genericERC20).toStrictEqual(testGenericERC20); }); }); describe('isERC20Asset', () => { it('correctly determines base asset', () => { expect(isERC20Asset(fAssets[0])).toBe(false); }); it('correctly determines erc20 asset', () => { // Expects ropsten dai to be the last asset in fAssets expect(isERC20Asset(fAssets[fAssets.length - 1])).toBe(true); }); }); describe('processFormDataToTx', () => { it('correctly process eth form data to eth tx', () => { expect(processFormDataToTx(fETHTxSendFormikFields)).toMatchSnapshot(); }); it('correctly process eth form data to eth tx for EIP 1559', () => { expect(processFormDataToTx(fETHTxSendFormikFieldsEIP1559)).toMatchSnapshot(); }); it('correctly process advanced eth form data to eth tx', () => { expect(processFormDataToTx(fAdvancedETHTxSendFormikFields)).toMatchSnapshot(); }); it('correctly process erc20 form data to erc20 tx', () => { expect(processFormDataToTx(fERC20TxSendFormikFields)).toMatchSnapshot(); }); it('correctly process advanced erc20 form data to erc20 tx', () => { expect(processFormDataToTx(fAdvancedERC20TxSendFormikFields)).toMatchSnapshot(); }); }); describe('processFormForEstimateGas', () => { it('correctly process eth form data for gas limit estimate', () => { expect(processFormForEstimateGas(fETHTxSendFormikFields)).toMatchSnapshot(); }); it('correctly process erc20 form data for gas limit estimate', () => { expect(processFormForEstimateGas(fERC20TxSendFormikFields)).toMatchSnapshot(); }); it('correctly process advanced eth form data for gas limit estimate', () => { expect(processFormForEstimateGas(fAdvancedETHTxSendFormikFields)).toMatchSnapshot(); }); it('correctly process advanced erc20 form data for gas limit estimate', () => { expect(processFormForEstimateGas(fAdvancedERC20TxSendFormikFields)).toMatchSnapshot(); }); });
the_stack
import { IAppInsightsDeprecated } from "../../../src/ApplicationInsightsDeprecated"; import { ApplicationInsightsContainer } from "../../../src/ApplicationInsightsContainer"; import { IApplicationInsights, Snippet } from "../../../src/Initialization"; import { Sender } from "@microsoft/applicationinsights-channel-js"; import { createLegacySnippet } from "./testLegacySnippet"; import { SinonSpy } from "sinon"; import { AITestClass, Assert, PollingAssert } from "@microsoft/ai-test-framework"; import { hasOwnProperty, isNotNullOrUndefined } from "@microsoft/applicationinsights-core-js"; function getBasicLegacySnippetConfig() { return { instrumentationKey: 'b7170927-2d1c-44f1-acec-59f4e1751c11', disableAjaxTracking: false, disableFetchTracking: false, maxBatchInterval: 500 }; } const _expectedProperties = [ "config", "core", "context", "cookie", "appInsights", "appInsightsNew", "version" ]; const _expectedTrackMethods = [ "startTrackEvent", "stopTrackEvent", "startTrackPage", "stopTrackPage", "trackException", "trackEvent", "trackMetric", "trackPageView", "trackTrace", "setAuthenticatedUserContext", "clearAuthenticatedUserContext", "flush" ]; const _expectedMethodsAfterInitialization = [ "getCookieMgr" ]; export class SnippetLegacyInitializationTests extends AITestClass { // Sinon private errorSpy: SinonSpy; private successSpy: SinonSpy; private loggingSpy: SinonSpy; constructor(emulateEs3: boolean) { super("SnippetLegacyInitializationTests", emulateEs3); } public testInitialize() { this._disableDynProtoBaseFuncs(); // We need to disable the useBaseInst performance setting as the sinon spy fools the internal logic and the spy is bypassed this.useFakeServer = true; this.fakeServerAutoRespond = true; } public testCleanup() { } public registerTests() { this.testCase({ name: "Check support for 1.0 apis", test: () => { let theSnippet = this._initializeSnippet(createLegacySnippet(getBasicLegacySnippetConfig())); Assert.ok(theSnippet, 'ApplicationInsights SDK exists'); Assert.ok(theSnippet.downloadAndSetup, "The [Legacy] snippet should have the downloadAndSetup"); // has legacy method } }); this.testCaseAsync({ name: "Public Members exist", stepDelay: 1, steps: [() => { let theSnippet = this._initializeSnippet(createLegacySnippet(getBasicLegacySnippetConfig())) as any; _expectedTrackMethods.forEach(method => { Assert.ok(hasOwnProperty(theSnippet, method), `${method} exists`); Assert.ok(theSnippet[method], `${method} exists`); Assert.equal('function', typeof theSnippet[method], `${method} is a function`); let funcSpyNew; let funcSpy; if (method === "setAuthenticatedUserContext" || method === "clearAuthenticatedUserContext") { //funcSpy = this.sandbox.spy(theSnippet.context.user, method); funcSpyNew = this.sandbox.spy(theSnippet.appInsightsNew.context.user, method); } else if (method === "flush") { funcSpyNew = this.sandbox.spy(theSnippet.appInsightsNew, method); } else { funcSpy = this.sandbox.spy(theSnippet.appInsights, method); funcSpyNew = this.sandbox.spy(theSnippet.appInsightsNew, method); } try { theSnippet[method](); } catch(e) { // Do nothing } Assert.ok(funcSpyNew.called, "Function [" + method + "] of the new implementation should have been called") if (funcSpy) { Assert.ok(funcSpy.called, "Function [" + method + "] of the appInsights should have been called") } }); _expectedMethodsAfterInitialization.forEach(method => { Assert.ok(hasOwnProperty(theSnippet, method), `${method} exists`); Assert.ok(theSnippet[method], `${method} exists`); Assert.equal('function', typeof theSnippet[method], `${method} is a function`); let funcSpy = this.sandbox.spy(theSnippet.appInsights, method); let funcSpyNew = this.sandbox.spy(theSnippet.appInsightsNew, method); try { theSnippet[method](); } catch(e) { // Do nothing } Assert.ok(funcSpyNew.called, "Function [" + method + "] of the new implementation should have been called") if (funcSpy) { Assert.ok(funcSpy.called, "Function [" + method + "] of the appInsights should have been called") } }); }, PollingAssert.createPollingAssert(() => { try { Assert.ok(true, "* waiting for scheduled actions to send events " + new Date().toISOString()); if(this.successSpy.called) { let currentCount: number = 0; this.successSpy.args.forEach(call => { call[0].forEach(message => { // Ignore the internal SendBrowserInfoOnUserInit message (Only occurs when running tests in a browser) if (!message || message.indexOf("AI (Internal): 72 ") == -1) { currentCount ++; } }); }); return currentCount > 0; } return false; } catch (e) { Assert.ok(false, "Exception:" + e); } }, "waiting for sender success", 30, 1000) as any] }); this.testCase({ name: "Check properties exist", test: () => { let theSnippet = this._initializeSnippet(createLegacySnippet(getBasicLegacySnippetConfig())) as any; _expectedProperties.forEach(property => { Assert.ok(hasOwnProperty(theSnippet, property), `${property} has own property`) Assert.notEqual(undefined, theSnippet[property], `${property} exists`); Assert.notEqual('function', typeof theSnippet[property], `${property} is not a function`); }); Assert.ok(isNotNullOrUndefined(theSnippet.core), "Make sure the core is set"); Assert.ok(isNotNullOrUndefined(theSnippet.appInsightsNew.core), "Make sure the appInsights core is set"); Assert.equal(theSnippet.core, theSnippet.appInsightsNew.core, "Make sure the core instances are actually the same"); } }); this.testCase({ name: "Check cookie manager access", test: () => { let theSnippet = this._initializeSnippet(createLegacySnippet(getBasicLegacySnippetConfig())) as any; let coreCookieMgr = theSnippet.core.getCookieMgr(); Assert.ok(isNotNullOrUndefined(coreCookieMgr), "Make sure the cookie manager is returned"); Assert.equal(true, coreCookieMgr.isEnabled(), "Cookies should be enabled") Assert.equal(coreCookieMgr, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned"); let appInsightsCookieMgr = theSnippet.appInsightsNew.core.getCookieMgr(); Assert.ok(isNotNullOrUndefined(appInsightsCookieMgr), "Make sure the cookie manager is returned"); Assert.equal(true, appInsightsCookieMgr.isEnabled(), "Cookies should be enabled") Assert.equal(appInsightsCookieMgr, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned"); Assert.equal(coreCookieMgr, appInsightsCookieMgr, "Make sure the cookie managers are the same"); Assert.equal(true, theSnippet.getCookieMgr().isEnabled(), "Cookies should be enabled") let appInsightsCookieMgr2 = theSnippet.appInsightsNew.appInsights.core.getCookieMgr(); Assert.ok(isNotNullOrUndefined(appInsightsCookieMgr2), "Make sure the cookie manager is returned"); Assert.equal(true, appInsightsCookieMgr2.isEnabled(), "Cookies should be enabled") Assert.equal(appInsightsCookieMgr2, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned"); Assert.equal(coreCookieMgr, appInsightsCookieMgr2, "Make sure the cookie managers are the same"); } }); this.testCase({ name: "Check cookie manager access as disabled", test: () => { let theConfig = getBasicLegacySnippetConfig() as any; theConfig.disableCookiesUsage = true; let theSnippet = this._initializeSnippet(createLegacySnippet(theConfig)) as any; let coreCookieMgr = theSnippet.core.getCookieMgr(); Assert.ok(isNotNullOrUndefined(coreCookieMgr), "Make sure the cookie manager is returned"); Assert.equal(false, coreCookieMgr.isEnabled(), "Cookies should be disabled") Assert.equal(coreCookieMgr, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned"); let appInsightsCookieMgr = theSnippet.appInsightsNew.core.getCookieMgr(); Assert.ok(isNotNullOrUndefined(appInsightsCookieMgr), "Make sure the cookie manager is returned"); Assert.equal(false, appInsightsCookieMgr.isEnabled(), "Cookies should be disabled") Assert.equal(appInsightsCookieMgr, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned"); Assert.equal(coreCookieMgr, appInsightsCookieMgr, "Make sure the cookie managers are the same"); Assert.equal(false, theSnippet.getCookieMgr().isEnabled(), "Cookies should be disabled") let appInsightsCookieMgr2 = theSnippet.appInsightsNew.appInsights.core.getCookieMgr(); Assert.ok(isNotNullOrUndefined(appInsightsCookieMgr2), "Make sure the cookie manager is returned"); Assert.equal(false, appInsightsCookieMgr2.isEnabled(), "Cookies should be disabled") Assert.equal(appInsightsCookieMgr2, theSnippet.getCookieMgr(), "Make sure the cookie manager is returned"); Assert.equal(coreCookieMgr, appInsightsCookieMgr2, "Make sure the cookie managers are the same"); } }); this.addLegacyApiTests(createLegacySnippet); } public addLegacyApiTests(snippetCreator: (config:any) => Snippet): void { this.testCaseAsync({ name: "[Legacy] trackEvent sends to backend", stepDelay: 1, steps: [() => { let theSnippet = this._initializeSnippet(snippetCreator(getBasicLegacySnippetConfig())) as IAppInsightsDeprecated; theSnippet.trackEvent("event"); }].concat(this.asserts(1)) }); this.testCaseAsync({ name: "[Legacy] trackTrace sends to backend", stepDelay: 1, steps: [() => { let theSnippet = this._initializeSnippet(snippetCreator(getBasicLegacySnippetConfig())) as IAppInsightsDeprecated; theSnippet.trackTrace("trace"); }].concat(this.asserts(1)) }); this.testCaseAsync({ name: "[Legacy] trackException sends to backend", stepDelay: 1, steps: [() => { let exception: Error = null; let theSnippet = this._initializeSnippet(snippetCreator(getBasicLegacySnippetConfig())) as IAppInsightsDeprecated; try { window['a']['b'](); Assert.ok(false, 'trackException test not run'); } catch (e) { exception = e; theSnippet.trackException(exception); } Assert.ok(exception); }].concat(this.asserts(1)) }); this.testCaseAsync({ name: "[Legacy] track metric", stepDelay: 1, steps: [ () => { let theSnippet = this._initializeSnippet(snippetCreator(getBasicLegacySnippetConfig())) as IAppInsightsDeprecated; console.log("* calling trackMetric " + new Date().toISOString()); for (let i = 0; i < 100; i++) { theSnippet.trackMetric("test" + i,Math.round(100 * Math.random())); } console.log("* done calling trackMetric " + new Date().toISOString()); } ].concat(this.asserts(100)) }); this.testCaseAsync({ name: "[Legacy] track page view", stepDelay: 1, steps: [ () => { let theSnippet = this._initializeSnippet(snippetCreator(getBasicLegacySnippetConfig())) as IAppInsightsDeprecated; theSnippet.trackPageView(); // sends 2 } ].concat(this.asserts(2)) }); } private _initializeSnippet(snippet: Snippet): IAppInsightsDeprecated { try { // Call the initialization ((ApplicationInsightsContainer.getAppInsights(snippet, snippet.version)) as IAppInsightsDeprecated); const appInsights = (snippet as any).appInsights; this.onDone(() => { if (snippet["unload"]) { snippet["unload"](false); } else if (snippet["appInsightsNew"]) { snippet["appInsightsNew"].unload(false); } }); Assert.ok(appInsights, "The App insights instance should be populated"); Assert.ok(appInsights.core, "The Core exists"); Assert.equal(appInsights.core, (snippet as any).core, "The core instances should match"); Assert.equal(true, appInsights.isInitialized(), 'App Analytics is initialized'); Assert.equal(true, appInsights.core.isInitialized(), 'Core is initialized'); const appInsightsNew = (snippet as any).appInsightsNew; Assert.ok(appInsightsNew, "The App insights new instance should be populated"); Assert.ok(appInsightsNew.core, "The Core exists"); Assert.equal(appInsightsNew.core, (snippet as any).core, "The core instances should match"); Assert.equal(true, appInsightsNew.appInsights.isInitialized(), 'App Analytics is initialized'); Assert.equal(true, appInsightsNew.core.isInitialized(), 'Core is initialized'); // Setup Sinon stuff const sender: Sender = appInsightsNew.core.getTransmissionControls()[0][0] as Sender; this.errorSpy = this.sandbox.spy(sender, '_onError'); this.successSpy = this.sandbox.spy(sender, '_onSuccess'); this.loggingSpy = this.sandbox.stub(appInsights.core.logger, 'throwInternal'); } catch (e) { console.error('Failed to initialize'); Assert.ok(false, e); } // Note: Explicitly returning the original snippet as this should have been updated! return snippet as IAppInsightsDeprecated; } private boilerPlateAsserts = () => { Assert.ok(this.successSpy.called, "success"); Assert.ok(!this.errorSpy.called, "no error sending"); const isValidCallCount = this.loggingSpy.callCount === 0; Assert.ok(isValidCallCount, "logging spy was called 0 time(s)"); if (!isValidCallCount) { while (this.loggingSpy.args.length) { Assert.ok(false, "[warning thrown]: " + this.loggingSpy.args.pop()); } } } private asserts: any = (expectedCount: number) => [() => { const message = "polling: " + new Date().toISOString(); Assert.ok(true, message); console.log(message); if (this.successSpy.called) { this.boilerPlateAsserts(); this.testCleanup(); } else if (this.errorSpy.called || this.loggingSpy.called) { this.boilerPlateAsserts(); } }, (PollingAssert.createPollingAssert(() => { try { Assert.ok(true, "* checking success spy " + new Date().toISOString()); if(this.successSpy.called) { let currentCount: number = 0; this.successSpy.args.forEach(call => { call[0].forEach(message => { // Ignore the internal SendBrowserInfoOnUserInit message (Only occurs when running tests in a browser) if (!message || message.indexOf("AI (Internal): 72 ") == -1) { currentCount ++; } }); }); console.log('curr: ' + currentCount + ' exp: ' + expectedCount); return currentCount === expectedCount; } return false; } catch (e) { Assert.ok(false, "Exception:" + e); } }, "sender succeeded", 30, 1000))]; }
the_stack
* @packageDocumentation * @module std */ //================================================================ import { IForwardIterator } from "../iterator/IForwardIterator"; import { IPointer } from "../functional/IPointer"; import { Pair } from "../utility/Pair"; import { BinaryPredicator } from "../internal/functional/BinaryPredicator"; import { UnaryPredicator } from "../internal/functional/UnaryPredicator"; import { equal_to, less } from "../functional/comparators"; import { advance, distance } from "../iterator/global"; /* ========================================================= ITERATIONS (NON-MODIFYING SEQUENCE) - FOR_EACH - AGGREGATE CONDITIONS - FINDERS - COUNTERS ============================================================ FOR_EACH --------------------------------------------------------- */ /** * Apply a function to elements in range. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param fn The function to apply. * * @return The function *fn* itself. */ export function for_each< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, Func extends (val: IPointer.ValueType<InputIterator>) => any> (first: InputIterator, last: InputIterator, fn: Func): Func { for (let it = first; !it.equals(last); it = it.next()) fn(it.value); return fn; } /** * Apply a function to elements in steps. * * @param first Input iteartor of the starting position. * @param n Steps to maximum advance. * @param fn The function to apply. * * @return Iterator advanced from *first* for *n* steps. */ export function for_each_n< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, Func extends (val: IPointer.ValueType<InputIterator>) => any> (first: InputIterator, n: number, fn: Func): InputIterator { for (let i: number = 0; i < n; ++i) { fn(first.value); first = first.next(); } return first; } /* --------------------------------------------------------- AGGREGATE CONDITIONS --------------------------------------------------------- */ /** * Test whether all elements meet a specific condition. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param pred A function predicates the specific condition. * * @return Whether the *pred* returns always `true` for all elements. */ export function all_of<InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, pred: UnaryPredicator<IPointer.ValueType<InputIterator>> ): boolean { for (let it = first; !it.equals(last); it = it.next()) if (pred(it.value) === false) return false; return true; } /** * Test whether any element meets a specific condition. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param pred A function predicates the specific condition. * * @return Whether the *pred* returns at least a `true` for all elements. */ export function any_of<InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, pred: UnaryPredicator<IPointer.ValueType<InputIterator>> ): boolean { for (let it = first; !it.equals(last); it = it.next()) if (pred(it.value) === true) return true; return false; } /** * Test whether any element doesn't meet a specific condition. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param pred A function predicates the specific condition. * * @return Whether the *pred* doesn't return `true` for all elements. */ export function none_of<InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, pred: UnaryPredicator<IPointer.ValueType<InputIterator>> ): boolean { return !any_of(first, last, pred); } /** * Test whether two ranges are equal. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param pred A binary function predicates two arguments are equal. * * @return Whether two ranges are equal. */ export function equal< InputIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator1>>, InputIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator2>>> ( first1: InputIterator1, last1: InputIterator1, first2: InputIterator2 ): boolean; /** * Test whether two ranges are equal. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param pred A binary function predicates two arguments are equal. * * @return Whether two ranges are equal. */ export function equal< InputIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator1>>, InputIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator2>, InputIterator2>>> ( first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, pred: BinaryPredicator<IPointer.ValueType<InputIterator1>, IPointer.ValueType<InputIterator2>> ): boolean; export function equal< InputIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator1>>, InputIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator2>, InputIterator2>>> ( first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, pred: BinaryPredicator<IPointer.ValueType<InputIterator1>, IPointer.ValueType<InputIterator2>> = equal_to as any ): boolean { while (!first1.equals(last1)) if (!pred(first1.value, first2.value)) return false; else { first1 = first1.next(); first2 = first2.next(); } return true; } /** * Compare lexicographically. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param last2 Input iterator of the last position of the 2nd range. * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. * * @return Whether the 1st range precedes the 2nd. */ export function lexicographical_compare< Iterator1 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator1>>, Iterator2 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator2>>> ( first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, comp: BinaryPredicator<IPointer.ValueType<Iterator1>> = less ): boolean { while (!first1.equals(last1)) if (first2.equals(last2) || comp(first2.value, first1.value)) return false; else if (comp(first1.value, first2.value)) return true; else { first1 = first1.next(); first2 = first2.next(); } return !first2.equals(last2); } /* --------------------------------------------------------- FINDERS --------------------------------------------------------- */ /** * Find a value in range. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param val The value to find. * * @return Iterator to the first element {@link equal to equal_to} the value. */ export function find<InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, val: IPointer.ValueType<InputIterator> ): InputIterator { return find_if(first, last, elem => equal_to(elem, val)); } /** * Find a matched condition in range. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param pred A function predicates the specific condition. * * @return Iterator to the first element *pred* returns `true`. */ export function find_if<InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, pred: UnaryPredicator<IPointer.ValueType<InputIterator>> ): InputIterator { for (let it = first; !it.equals(last); it = it.next()) if (pred(it.value)) return it; return last; } /** * Find a mismatched condition in range. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param pred A function predicates the specific condition. * * @return Iterator to the first element *pred* returns `false`. */ export function find_if_not<InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, pred: UnaryPredicator<IPointer.ValueType<InputIterator>> ): InputIterator { return find_if(first, last, elem => !pred(elem)); } /** * Find the last sub range. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param last2 Input iterator of the last position of the 2nd range. * * @return Iterator to the first element of the last sub range. */ export function find_end< Iterator1 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator1>>, Iterator2 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator2>>> ( first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2 ): Iterator1; /** * Find the last sub range. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param last2 Input iterator of the last position of the 2nd range. * @param pred A binary function predicates two arguments are equal. * * @return Iterator to the first element of the last sub range. */ export function find_end< Iterator1 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator1>>, Iterator2 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator2>, Iterator2>>> ( first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: BinaryPredicator<IPointer.ValueType<Iterator1>, IPointer.ValueType<Iterator2>> ): Iterator1; export function find_end< Iterator1 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator1>>, Iterator2 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator2>, Iterator2>>> ( first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: BinaryPredicator<IPointer.ValueType<Iterator1>, IPointer.ValueType<Iterator2>> = <any>equal_to ): Iterator1 { if (first2.equals(last2)) return last1; let ret: Iterator1 = last1; for (; !first1.equals(last1); first1 = first1.next()) { let it1: Iterator1 = first1; let it2: Iterator2 = first2; while (pred(it1.value, it2.value)) { it1 = it1.next(); it2 = it2.next(); if (it2.equals(last2)) { ret = first1; break; } else if (it1.equals(last1)) return ret; } } return ret; } /** * Find the first sub range. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param last2 Input iterator of the last position of the 2nd range. * * @return Iterator to the first element of the first sub range. */ export function find_first_of< Iterator1 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator1>>, Iterator2 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator2>>> ( first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2 ): Iterator1; /** * Find the first sub range. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param last2 Input iterator of the last position of the 2nd range. * @param pred A binary function predicates two arguments are equal. * * @return Iterator to the first element of the first sub range. */ export function find_first_of< Iterator1 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator1>>, Iterator2 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator2>, Iterator2>>> ( first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: BinaryPredicator<IPointer.ValueType<Iterator1>, IPointer.ValueType<Iterator2>> ): Iterator1; export function find_first_of< Iterator1 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator1>>, Iterator2 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator2>, Iterator2>>> ( first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: BinaryPredicator<IPointer.ValueType<Iterator1>, IPointer.ValueType<Iterator2>> = <any>equal_to ): Iterator1 { for (; !first1.equals(last1); first1 = first1.next()) for (let it = first2; !it.equals(last2); it = it.next()) if (pred(first1.value, it.value)) return first1; return last1; } /** * Find the first adjacent element. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param pred A binary function predicates two arguments are equal. Default is {@link equal_to}. * * @return Iterator to the first element of adjacent find. */ export function adjacent_find<InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, pred: BinaryPredicator<IPointer.ValueType<InputIterator>> = equal_to ): InputIterator { if (!first.equals(last)) { let next: InputIterator = first.next(); while (!next.equals(last)) { if (pred(first.value, next.value)) return first; first = first.next(); next = next.next(); } } return last; } /** * Search sub range. * * @param first1 Forward iteartor of the first position of the 1st range. * @param last1 Forward iterator of the last position of the 1st range. * @param first2 Forward iterator of the first position of the 2nd range. * @param last2 Forward iterator of the last position of the 2nd range. * * @return Iterator to the first element of the sub range. */ export function search< ForwardIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<ForwardIterator1>, ForwardIterator1>>, ForwardIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<ForwardIterator1>, ForwardIterator2>>> ( first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2 ): ForwardIterator1; /** * Search sub range. * * @param first1 Forward iteartor of the first position of the 1st range. * @param last1 Forward iterator of the last position of the 1st range. * @param first2 Forward iterator of the first position of the 2nd range. * @param last2 Forward iterator of the last position of the 2nd range. * @param pred A binary function predicates two arguments are equal. * * @return Iterator to the first element of the sub range. */ export function search< ForwardIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<ForwardIterator1>, ForwardIterator1>>, ForwardIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<ForwardIterator2>, ForwardIterator2>>> ( first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2, pred: BinaryPredicator<IPointer.ValueType<ForwardIterator1>, IPointer.ValueType<ForwardIterator2>> ): ForwardIterator1; export function search< ForwardIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<ForwardIterator1>, ForwardIterator1>>, ForwardIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<ForwardIterator2>, ForwardIterator2>>> ( first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2, pred: BinaryPredicator<IPointer.ValueType<ForwardIterator1>, IPointer.ValueType<ForwardIterator2>> = <any>equal_to ): ForwardIterator1 { if (first2.equals(last2)) return first1; for (; !first1.equals(last1); first1 = first1.next()) { let it1: ForwardIterator1 = first1; let it2: ForwardIterator2 = first2; while (pred(it1.value, it2.value)) { if (it2.equals(last2)) return first1; else if (it1.equals(last1)) return last1; it1 = it1.next(); it2 = it2.next(); } } return last1; } /** * Search specific and repeated elements. * * @param first Forward iteartor of the first position. * @param last Forward iterator of the last position. * @param count Count to be repeated. * @param val Value to search. * @param pred A binary function predicates two arguments are equal. Default is {@link equal_to}. * * @return Iterator to the first element of the repetition. */ export function search_n<ForwardIterator extends Readonly<IForwardIterator<IPointer.ValueType<ForwardIterator>, ForwardIterator>>> ( first: ForwardIterator, last: ForwardIterator, count: number, val: IPointer.ValueType<ForwardIterator>, pred: BinaryPredicator<IPointer.ValueType<ForwardIterator>> = equal_to ): ForwardIterator { const limit: ForwardIterator = advance(first, distance(first, last) - count); for (; !first.equals(limit); first = first.next()) { let it: ForwardIterator = first; let i: number = 0; while (pred(it.value, val)) { it = it.next(); if (++i === count) return first; } } return last; } /** * Find the first mistmached position between two ranges. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * * @return A {@link Pair} of mismatched positions. */ export function mismatch< Iterator1 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator1>>, Iterator2 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator2>>> ( first1: Iterator1, last1: Iterator1, first2: Iterator2 ): Pair<Iterator1, Iterator2>; /** * Find the first mistmached position between two ranges. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param pred A binary function predicates two arguments are equal. * * @return A {@link Pair} of mismatched positions. */ export function mismatch< Iterator1 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator1>>, Iterator2 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator2>, Iterator2>>> ( first1: Iterator1, last1: Iterator1, first2: Iterator2, pred: BinaryPredicator<IPointer.ValueType<Iterator1>, IPointer.ValueType<Iterator2>> ): Pair<Iterator1, Iterator2>; export function mismatch< Iterator1 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator1>, Iterator1>>, Iterator2 extends Readonly<IForwardIterator<IPointer.ValueType<Iterator2>, Iterator2>>> ( first1: Iterator1, last1: Iterator1, first2: Iterator2, pred: BinaryPredicator<IPointer.ValueType<Iterator1>, IPointer.ValueType<Iterator2>> = <any>equal_to ): Pair<Iterator1, Iterator2> { while (!first1.equals(last1) && pred(first1.value, first2.value)) { first1 = first1.next(); first2 = first2.next(); } return new Pair(first1, first2); } /* --------------------------------------------------------- COUNTERS --------------------------------------------------------- */ /** * Count matched value in range. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param val The value to count. * * @return The matched count. */ export function count<InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, val: IPointer.ValueType<InputIterator> ): number { return count_if(first, last, elem => equal_to(elem, val)); } /** * Count matched condition in range. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param pred A function predicates the specific condition. * * @return The matched count. */ export function count_if<InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, pred: UnaryPredicator<IPointer.ValueType<InputIterator>> ): number { let ret: number = 0; for (let it = first; !it.equals(last); it = it.next()) if (pred(it.value)) ++ret; return ret; }
the_stack
import { BuilderContext, createBuilder, targetFromTargetString } from '@angular-devkit/architect'; import { DevServerBuildOutput, WebpackLoggingCallback, runWebpackDevServer, } from '@angular-devkit/build-webpack'; import { json, tags } from '@angular-devkit/core'; import * as path from 'path'; import { Observable, from } from 'rxjs'; import { concatMap, switchMap } from 'rxjs/operators'; import * as url from 'url'; import webpack from 'webpack'; import webpackDevServer from 'webpack-dev-server'; import { ExecutionTransformer } from '../../transforms'; import { normalizeOptimization } from '../../utils'; import { checkPort } from '../../utils/check-port'; import { colors } from '../../utils/color'; import { I18nOptions, loadTranslations } from '../../utils/i18n-options'; import { IndexHtmlTransform } from '../../utils/index-file/index-html-generator'; import { createTranslationLoader } from '../../utils/load-translations'; import { NormalizedCachedOptions, normalizeCacheOptions } from '../../utils/normalize-cache'; import { generateEntryPoints } from '../../utils/package-chunk-sort'; import { assertCompatibleAngularVersion } from '../../utils/version'; import { generateI18nBrowserWebpackConfigFromContext, getIndexInputFile, getIndexOutputFile, } from '../../utils/webpack-browser-config'; import { addError, addWarning } from '../../utils/webpack-diagnostics'; import { getAnalyticsConfig, getCommonConfig, getDevServerConfig, getStylesConfig, } from '../../webpack/configs'; import { IndexHtmlWebpackPlugin } from '../../webpack/plugins/index-html-webpack-plugin'; import { createWebpackLoggingCallback } from '../../webpack/utils/stats'; import { Schema as BrowserBuilderSchema, OutputHashing } from '../browser/schema'; import { Schema } from './schema'; export type DevServerBuilderOptions = Schema & json.JsonObject; /** * @experimental Direct usage of this type is considered experimental. */ export type DevServerBuilderOutput = DevServerBuildOutput & { baseUrl: string; }; /** * Reusable implementation of the Angular Webpack development server builder. * @param options Dev Server options. * @param context The build context. * @param transforms A map of transforms that can be used to hook into some logic (such as * transforming webpack configuration before passing it to webpack). * * @experimental Direct usage of this function is considered experimental. */ // eslint-disable-next-line max-lines-per-function export function serveWebpackBrowser( options: DevServerBuilderOptions, context: BuilderContext, transforms: { webpackConfiguration?: ExecutionTransformer<webpack.Configuration>; logging?: WebpackLoggingCallback; indexHtml?: IndexHtmlTransform; } = {}, ): Observable<DevServerBuilderOutput> { // Check Angular version. const { logger, workspaceRoot } = context; assertCompatibleAngularVersion(workspaceRoot); const browserTarget = targetFromTargetString(options.browserTarget); async function setup(): Promise<{ browserOptions: json.JsonObject & BrowserBuilderSchema; webpackConfig: webpack.Configuration; projectRoot: string; }> { const projectName = context.target?.project; if (!projectName) { throw new Error('The builder requires a target.'); } options.port = await checkPort(options.port ?? 4200, options.host || 'localhost'); if (options.hmr) { logger.warn(tags.stripIndents`NOTICE: Hot Module Replacement (HMR) is enabled for the dev server. See https://webpack.js.org/guides/hot-module-replacement for information on working with HMR for Webpack.`); } if ( !options.disableHostCheck && options.host && !/^127\.\d+\.\d+\.\d+/g.test(options.host) && options.host !== 'localhost' ) { logger.warn(tags.stripIndent` Warning: This is a simple server for use in testing or debugging Angular applications locally. It hasn't been reviewed for security issues. Binding this server to an open connection can result in compromising your application or computer. Using a different host than the one passed to the "--host" flag might result in websocket connection issues. You might need to use "--disable-host-check" if that's the case. `); } if (options.disableHostCheck) { logger.warn(tags.oneLine` Warning: Running a server with --disable-host-check is a security risk. See https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a for more information. `); } // Get the browser configuration from the target name. const rawBrowserOptions = (await context.getTargetOptions(browserTarget)) as json.JsonObject & BrowserBuilderSchema; if (rawBrowserOptions.outputHashing && rawBrowserOptions.outputHashing !== OutputHashing.None) { // Disable output hashing for dev build as this can cause memory leaks // See: https://github.com/webpack/webpack-dev-server/issues/377#issuecomment-241258405 rawBrowserOptions.outputHashing = OutputHashing.None; logger.warn(`Warning: 'outputHashing' option is disabled when using the dev-server.`); } const metadata = await context.getProjectMetadata(projectName); const cacheOptions = normalizeCacheOptions(metadata, context.workspaceRoot); const browserName = await context.getBuilderNameForTarget(browserTarget); const browserOptions = (await context.validateOptions( { ...rawBrowserOptions, watch: options.watch, verbose: options.verbose, // In dev server we should not have budgets because of extra libs such as socks-js budgets: undefined, } as json.JsonObject & BrowserBuilderSchema, browserName, )) as json.JsonObject & BrowserBuilderSchema; const { styles, scripts } = normalizeOptimization(browserOptions.optimization); if (scripts || styles.minify) { logger.error(tags.stripIndents` **************************************************************************************** This is a simple server for use in testing or debugging Angular applications locally. It hasn't been reviewed for security issues. DON'T USE IT FOR PRODUCTION! **************************************************************************************** `); } const { config, projectRoot, i18n } = await generateI18nBrowserWebpackConfigFromContext( browserOptions, context, (wco) => [ getDevServerConfig(wco), getCommonConfig(wco), getStylesConfig(wco), getAnalyticsConfig(wco, context), ], options, ); if (!config.devServer) { throw new Error('Webpack Dev Server configuration was not set.'); } let locale: string | undefined; if (i18n.shouldInline) { // Dev-server only supports one locale locale = [...i18n.inlineLocales][0]; } else if (i18n.hasDefinedSourceLocale) { // use source locale if not localizing locale = i18n.sourceLocale; } let webpackConfig = config; // If a locale is defined, setup localization if (locale) { if (i18n.inlineLocales.size > 1) { throw new Error( 'The development server only supports localizing a single locale per build.', ); } await setupLocalize(locale, i18n, browserOptions, webpackConfig, cacheOptions, context); } if (transforms.webpackConfiguration) { webpackConfig = await transforms.webpackConfiguration(webpackConfig); } if (browserOptions.index) { const { scripts = [], styles = [], baseHref } = browserOptions; const entrypoints = generateEntryPoints({ scripts, styles, // The below is needed as otherwise HMR for CSS will break. // styles.js and runtime.js needs to be loaded as a non-module scripts as otherwise `document.currentScript` will be null. // https://github.com/webpack-contrib/mini-css-extract-plugin/blob/90445dd1d81da0c10b9b0e8a17b417d0651816b8/src/hmr/hotModuleReplacement.js#L39 isHMREnabled: !!webpackConfig.devServer?.hot, }); webpackConfig.plugins ??= []; webpackConfig.plugins.push( new IndexHtmlWebpackPlugin({ indexPath: path.resolve(workspaceRoot, getIndexInputFile(browserOptions.index)), outputPath: getIndexOutputFile(browserOptions.index), baseHref, entrypoints, deployUrl: browserOptions.deployUrl, sri: browserOptions.subresourceIntegrity, cache: cacheOptions, postTransform: transforms.indexHtml, optimization: normalizeOptimization(browserOptions.optimization), crossOrigin: browserOptions.crossOrigin, lang: locale, }), ); } return { browserOptions, webpackConfig, projectRoot, }; } return from(setup()).pipe( switchMap(({ browserOptions, webpackConfig }) => { return runWebpackDevServer(webpackConfig, context, { logging: transforms.logging || createWebpackLoggingCallback(browserOptions, logger), webpackFactory: require('webpack') as typeof webpack, webpackDevServerFactory: require('webpack-dev-server') as typeof webpackDevServer, }).pipe( concatMap(async (buildEvent, index) => { // Resolve serve address. const serverAddress = url.format({ protocol: options.ssl ? 'https' : 'http', hostname: options.host === '0.0.0.0' ? 'localhost' : options.host, port: buildEvent.port, pathname: webpackConfig.devServer?.devMiddleware?.publicPath, }); if (index === 0) { logger.info( '\n' + tags.oneLine` ** Angular Live Development Server is listening on ${options.host}:${buildEvent.port}, open your browser on ${serverAddress} ** ` + '\n', ); if (options.open) { const open = (await import('open')).default; await open(serverAddress); } } if (buildEvent.success) { logger.info(`\n${colors.greenBright(colors.symbols.check)} Compiled successfully.`); } else { logger.info(`\n${colors.redBright(colors.symbols.cross)} Failed to compile.`); } return { ...buildEvent, baseUrl: serverAddress } as DevServerBuilderOutput; }), ); }), ); } async function setupLocalize( locale: string, i18n: I18nOptions, browserOptions: BrowserBuilderSchema, webpackConfig: webpack.Configuration, cacheOptions: NormalizedCachedOptions, context: BuilderContext, ) { const localeDescription = i18n.locales[locale]; // Modify main entrypoint to include locale data if ( localeDescription?.dataPath && typeof webpackConfig.entry === 'object' && !Array.isArray(webpackConfig.entry) && webpackConfig.entry['main'] ) { if (Array.isArray(webpackConfig.entry['main'])) { webpackConfig.entry['main'].unshift(localeDescription.dataPath); } else { webpackConfig.entry['main'] = [ localeDescription.dataPath, webpackConfig.entry['main'] as string, ]; } } let missingTranslationBehavior = browserOptions.i18nMissingTranslation || 'ignore'; let translation = localeDescription?.translation || {}; if (locale === i18n.sourceLocale) { missingTranslationBehavior = 'ignore'; translation = {}; } const i18nLoaderOptions = { locale, missingTranslationBehavior, translation: i18n.shouldInline ? translation : undefined, translationFiles: localeDescription?.files.map((file) => path.resolve(context.workspaceRoot, file.path), ), }; const i18nRule: webpack.RuleSetRule = { test: /\.[cm]?[tj]sx?$/, enforce: 'post', use: [ { loader: require.resolve('../../babel/webpack-loader'), options: { cacheDirectory: (cacheOptions.enabled && path.join(cacheOptions.path, 'babel-dev-server-i18n')) || false, cacheIdentifier: JSON.stringify({ locale, translationIntegrity: localeDescription?.files.map((file) => file.integrity), }), i18n: i18nLoaderOptions, }, }, ], }; // Get the rules and ensure the Webpack configuration is setup properly const rules = webpackConfig.module?.rules || []; if (!webpackConfig.module) { webpackConfig.module = { rules }; } else if (!webpackConfig.module.rules) { webpackConfig.module.rules = rules; } rules.push(i18nRule); // Add a plugin to reload translation files on rebuilds const loader = await createTranslationLoader(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion webpackConfig.plugins!.push({ apply: (compiler: webpack.Compiler) => { compiler.hooks.thisCompilation.tap('build-angular', (compilation) => { if (i18n.shouldInline && i18nLoaderOptions.translation === undefined) { // Reload translations loadTranslations(locale, localeDescription, context.workspaceRoot, loader, { warn(message) { addWarning(compilation, message); }, error(message) { addError(compilation, message); }, }); i18nLoaderOptions.translation = localeDescription.translation; } compilation.hooks.finishModules.tap('build-angular', () => { // After loaders are finished, clear out the now unneeded translations i18nLoaderOptions.translation = undefined; }); }); }, }); } export default createBuilder<DevServerBuilderOptions, DevServerBuilderOutput>(serveWebpackBrowser);
the_stack
import * as cdk from '@aws-cdk/core'; import * as cfn_parse from '@aws-cdk/core/lib/cfn-parse'; /** * Properties for defining a `AWS::CodePipeline::CustomActionType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html * @external */ export interface CfnCustomActionTypeProps { /** * `AWS::CodePipeline::CustomActionType.Category`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-category * @external */ readonly category: string; /** * `AWS::CodePipeline::CustomActionType.InputArtifactDetails`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-inputartifactdetails * @external */ readonly inputArtifactDetails: CfnCustomActionType.ArtifactDetailsProperty | cdk.IResolvable; /** * `AWS::CodePipeline::CustomActionType.OutputArtifactDetails`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-outputartifactdetails * @external */ readonly outputArtifactDetails: CfnCustomActionType.ArtifactDetailsProperty | cdk.IResolvable; /** * `AWS::CodePipeline::CustomActionType.Provider`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-provider * @external */ readonly provider: string; /** * `AWS::CodePipeline::CustomActionType.Version`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-version * @external */ readonly version: string; /** * `AWS::CodePipeline::CustomActionType.ConfigurationProperties`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-configurationproperties * @external */ readonly configurationProperties?: Array<CfnCustomActionType.ConfigurationPropertiesProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::CodePipeline::CustomActionType.Settings`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-settings * @external */ readonly settings?: CfnCustomActionType.SettingsProperty | cdk.IResolvable; /** * `AWS::CodePipeline::CustomActionType.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::CodePipeline::CustomActionType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html * @external * @cloudformationResource AWS::CodePipeline::CustomActionType */ export declare class CfnCustomActionType extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::CodePipeline::CustomActionType"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnCustomActionType; /** * `AWS::CodePipeline::CustomActionType.Category`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-category * @external */ category: string; /** * `AWS::CodePipeline::CustomActionType.InputArtifactDetails`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-inputartifactdetails * @external */ inputArtifactDetails: CfnCustomActionType.ArtifactDetailsProperty | cdk.IResolvable; /** * `AWS::CodePipeline::CustomActionType.OutputArtifactDetails`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-outputartifactdetails * @external */ outputArtifactDetails: CfnCustomActionType.ArtifactDetailsProperty | cdk.IResolvable; /** * `AWS::CodePipeline::CustomActionType.Provider`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-provider * @external */ provider: string; /** * `AWS::CodePipeline::CustomActionType.Version`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-version * @external */ version: string; /** * `AWS::CodePipeline::CustomActionType.ConfigurationProperties`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-configurationproperties * @external */ configurationProperties: Array<CfnCustomActionType.ConfigurationPropertiesProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::CodePipeline::CustomActionType.Settings`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-settings * @external */ settings: CfnCustomActionType.SettingsProperty | cdk.IResolvable | undefined; /** * `AWS::CodePipeline::CustomActionType.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::CodePipeline::CustomActionType`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnCustomActionTypeProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::CodePipeline::CustomActionType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html * @external * @cloudformationResource AWS::CodePipeline::CustomActionType */ export declare namespace CfnCustomActionType { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-artifactdetails.html * @external */ interface ArtifactDetailsProperty { /** * `CfnCustomActionType.ArtifactDetailsProperty.MaximumCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-artifactdetails.html#cfn-codepipeline-customactiontype-artifactdetails-maximumcount * @external */ readonly maximumCount: number; /** * `CfnCustomActionType.ArtifactDetailsProperty.MinimumCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-artifactdetails.html#cfn-codepipeline-customactiontype-artifactdetails-minimumcount * @external */ readonly minimumCount: number; } } /** * A CloudFormation `AWS::CodePipeline::CustomActionType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html * @external * @cloudformationResource AWS::CodePipeline::CustomActionType */ export declare namespace CfnCustomActionType { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html * @external */ interface ConfigurationPropertiesProperty { /** * `CfnCustomActionType.ConfigurationPropertiesProperty.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-description * @external */ readonly description?: string; /** * `CfnCustomActionType.ConfigurationPropertiesProperty.Key`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-key * @external */ readonly key: boolean | cdk.IResolvable; /** * `CfnCustomActionType.ConfigurationPropertiesProperty.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-name * @external */ readonly name: string; /** * `CfnCustomActionType.ConfigurationPropertiesProperty.Queryable`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-queryable * @external */ readonly queryable?: boolean | cdk.IResolvable; /** * `CfnCustomActionType.ConfigurationPropertiesProperty.Required`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-required * @external */ readonly required: boolean | cdk.IResolvable; /** * `CfnCustomActionType.ConfigurationPropertiesProperty.Secret`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-secret * @external */ readonly secret: boolean | cdk.IResolvable; /** * `CfnCustomActionType.ConfigurationPropertiesProperty.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-type * @external */ readonly type?: string; } } /** * A CloudFormation `AWS::CodePipeline::CustomActionType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html * @external * @cloudformationResource AWS::CodePipeline::CustomActionType */ export declare namespace CfnCustomActionType { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-settings.html * @external */ interface SettingsProperty { /** * `CfnCustomActionType.SettingsProperty.EntityUrlTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-settings.html#cfn-codepipeline-customactiontype-settings-entityurltemplate * @external */ readonly entityUrlTemplate?: string; /** * `CfnCustomActionType.SettingsProperty.ExecutionUrlTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-settings.html#cfn-codepipeline-customactiontype-settings-executionurltemplate * @external */ readonly executionUrlTemplate?: string; /** * `CfnCustomActionType.SettingsProperty.RevisionUrlTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-settings.html#cfn-codepipeline-customactiontype-settings-revisionurltemplate * @external */ readonly revisionUrlTemplate?: string; /** * `CfnCustomActionType.SettingsProperty.ThirdPartyConfigurationUrl`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-settings.html#cfn-codepipeline-customactiontype-settings-thirdpartyconfigurationurl * @external */ readonly thirdPartyConfigurationUrl?: string; } } /** * Properties for defining a `AWS::CodePipeline::Pipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html * @external */ export interface CfnPipelineProps { /** * `AWS::CodePipeline::Pipeline.RoleArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-rolearn * @external */ readonly roleArn: string; /** * `AWS::CodePipeline::Pipeline.Stages`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-stages * @external */ readonly stages: Array<CfnPipeline.StageDeclarationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::CodePipeline::Pipeline.ArtifactStore`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-artifactstore * @external */ readonly artifactStore?: CfnPipeline.ArtifactStoreProperty | cdk.IResolvable; /** * `AWS::CodePipeline::Pipeline.ArtifactStores`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-artifactstores * @external */ readonly artifactStores?: Array<CfnPipeline.ArtifactStoreMapProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::CodePipeline::Pipeline.DisableInboundStageTransitions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-disableinboundstagetransitions * @external */ readonly disableInboundStageTransitions?: Array<CfnPipeline.StageTransitionProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::CodePipeline::Pipeline.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-name * @external */ readonly name?: string; /** * `AWS::CodePipeline::Pipeline.RestartExecutionOnUpdate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-restartexecutiononupdate * @external */ readonly restartExecutionOnUpdate?: boolean | cdk.IResolvable; /** * `AWS::CodePipeline::Pipeline.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-tags * @external */ readonly tags?: cdk.CfnTag[]; } /** * A CloudFormation `AWS::CodePipeline::Pipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html * @external * @cloudformationResource AWS::CodePipeline::Pipeline */ export declare class CfnPipeline extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::CodePipeline::Pipeline"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnPipeline; /** * @external * @cloudformationAttribute Version */ readonly attrVersion: string; /** * `AWS::CodePipeline::Pipeline.RoleArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-rolearn * @external */ roleArn: string; /** * `AWS::CodePipeline::Pipeline.Stages`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-stages * @external */ stages: Array<CfnPipeline.StageDeclarationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::CodePipeline::Pipeline.ArtifactStore`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-artifactstore * @external */ artifactStore: CfnPipeline.ArtifactStoreProperty | cdk.IResolvable | undefined; /** * `AWS::CodePipeline::Pipeline.ArtifactStores`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-artifactstores * @external */ artifactStores: Array<CfnPipeline.ArtifactStoreMapProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::CodePipeline::Pipeline.DisableInboundStageTransitions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-disableinboundstagetransitions * @external */ disableInboundStageTransitions: Array<CfnPipeline.StageTransitionProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * `AWS::CodePipeline::Pipeline.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-name * @external */ name: string | undefined; /** * `AWS::CodePipeline::Pipeline.RestartExecutionOnUpdate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-restartexecutiononupdate * @external */ restartExecutionOnUpdate: boolean | cdk.IResolvable | undefined; /** * `AWS::CodePipeline::Pipeline.Tags`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-tags * @external */ readonly tags: cdk.TagManager; /** * Create a new `AWS::CodePipeline::Pipeline`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnPipelineProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::CodePipeline::Pipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html * @external * @cloudformationResource AWS::CodePipeline::Pipeline */ export declare namespace CfnPipeline { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html * @external */ interface ActionDeclarationProperty { /** * `CfnPipeline.ActionDeclarationProperty.ActionTypeId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid * @external */ readonly actionTypeId: CfnPipeline.ActionTypeIdProperty | cdk.IResolvable; /** * `CfnPipeline.ActionDeclarationProperty.Configuration`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-configuration * @external */ readonly configuration?: any | cdk.IResolvable; /** * `CfnPipeline.ActionDeclarationProperty.InputArtifacts`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-inputartifacts * @external */ readonly inputArtifacts?: Array<CfnPipeline.InputArtifactProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnPipeline.ActionDeclarationProperty.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-name * @external */ readonly name: string; /** * `CfnPipeline.ActionDeclarationProperty.Namespace`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-actiondeclaration-namespace * @external */ readonly namespace?: string; /** * `CfnPipeline.ActionDeclarationProperty.OutputArtifacts`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-outputartifacts * @external */ readonly outputArtifacts?: Array<CfnPipeline.OutputArtifactProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnPipeline.ActionDeclarationProperty.Region`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-region * @external */ readonly region?: string; /** * `CfnPipeline.ActionDeclarationProperty.RoleArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-rolearn * @external */ readonly roleArn?: string; /** * `CfnPipeline.ActionDeclarationProperty.RunOrder`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-runorder * @external */ readonly runOrder?: number; } } /** * A CloudFormation `AWS::CodePipeline::Pipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html * @external * @cloudformationResource AWS::CodePipeline::Pipeline */ export declare namespace CfnPipeline { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html * @external */ interface ActionTypeIdProperty { /** * `CfnPipeline.ActionTypeIdProperty.Category`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid-category * @external */ readonly category: string; /** * `CfnPipeline.ActionTypeIdProperty.Owner`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid-owner * @external */ readonly owner: string; /** * `CfnPipeline.ActionTypeIdProperty.Provider`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid-provider * @external */ readonly provider: string; /** * `CfnPipeline.ActionTypeIdProperty.Version`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid-version * @external */ readonly version: string; } } /** * A CloudFormation `AWS::CodePipeline::Pipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html * @external * @cloudformationResource AWS::CodePipeline::Pipeline */ export declare namespace CfnPipeline { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore.html * @external */ interface ArtifactStoreProperty { /** * `CfnPipeline.ArtifactStoreProperty.EncryptionKey`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore.html#cfn-codepipeline-pipeline-artifactstore-encryptionkey * @external */ readonly encryptionKey?: CfnPipeline.EncryptionKeyProperty | cdk.IResolvable; /** * `CfnPipeline.ArtifactStoreProperty.Location`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore.html#cfn-codepipeline-pipeline-artifactstore-location * @external */ readonly location: string; /** * `CfnPipeline.ArtifactStoreProperty.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore.html#cfn-codepipeline-pipeline-artifactstore-type * @external */ readonly type: string; } } /** * A CloudFormation `AWS::CodePipeline::Pipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html * @external * @cloudformationResource AWS::CodePipeline::Pipeline */ export declare namespace CfnPipeline { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstoremap.html * @external */ interface ArtifactStoreMapProperty { /** * `CfnPipeline.ArtifactStoreMapProperty.ArtifactStore`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstoremap.html#cfn-codepipeline-pipeline-artifactstoremap-artifactstore * @external */ readonly artifactStore: CfnPipeline.ArtifactStoreProperty | cdk.IResolvable; /** * `CfnPipeline.ArtifactStoreMapProperty.Region`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstoremap.html#cfn-codepipeline-pipeline-artifactstoremap-region * @external */ readonly region: string; } } /** * A CloudFormation `AWS::CodePipeline::Pipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html * @external * @cloudformationResource AWS::CodePipeline::Pipeline */ export declare namespace CfnPipeline { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-blockers.html * @external */ interface BlockerDeclarationProperty { /** * `CfnPipeline.BlockerDeclarationProperty.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-blockers.html#cfn-codepipeline-pipeline-stages-blockers-name * @external */ readonly name: string; /** * `CfnPipeline.BlockerDeclarationProperty.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-blockers.html#cfn-codepipeline-pipeline-stages-blockers-type * @external */ readonly type: string; } } /** * A CloudFormation `AWS::CodePipeline::Pipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html * @external * @cloudformationResource AWS::CodePipeline::Pipeline */ export declare namespace CfnPipeline { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore-encryptionkey.html * @external */ interface EncryptionKeyProperty { /** * `CfnPipeline.EncryptionKeyProperty.Id`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore-encryptionkey.html#cfn-codepipeline-pipeline-artifactstore-encryptionkey-id * @external */ readonly id: string; /** * `CfnPipeline.EncryptionKeyProperty.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore-encryptionkey.html#cfn-codepipeline-pipeline-artifactstore-encryptionkey-type * @external */ readonly type: string; } } /** * A CloudFormation `AWS::CodePipeline::Pipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html * @external * @cloudformationResource AWS::CodePipeline::Pipeline */ export declare namespace CfnPipeline { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-inputartifacts.html * @external */ interface InputArtifactProperty { /** * `CfnPipeline.InputArtifactProperty.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-inputartifacts.html#cfn-codepipeline-pipeline-stages-actions-inputartifacts-name * @external */ readonly name: string; } } /** * A CloudFormation `AWS::CodePipeline::Pipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html * @external * @cloudformationResource AWS::CodePipeline::Pipeline */ export declare namespace CfnPipeline { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-outputartifacts.html * @external */ interface OutputArtifactProperty { /** * `CfnPipeline.OutputArtifactProperty.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-outputartifacts.html#cfn-codepipeline-pipeline-stages-actions-outputartifacts-name * @external */ readonly name: string; } } /** * A CloudFormation `AWS::CodePipeline::Pipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html * @external * @cloudformationResource AWS::CodePipeline::Pipeline */ export declare namespace CfnPipeline { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages.html * @external */ interface StageDeclarationProperty { /** * `CfnPipeline.StageDeclarationProperty.Actions`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages.html#cfn-codepipeline-pipeline-stages-actions * @external */ readonly actions: Array<CfnPipeline.ActionDeclarationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnPipeline.StageDeclarationProperty.Blockers`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages.html#cfn-codepipeline-pipeline-stages-blockers * @external */ readonly blockers?: Array<CfnPipeline.BlockerDeclarationProperty | cdk.IResolvable> | cdk.IResolvable; /** * `CfnPipeline.StageDeclarationProperty.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages.html#cfn-codepipeline-pipeline-stages-name * @external */ readonly name: string; } } /** * A CloudFormation `AWS::CodePipeline::Pipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html * @external * @cloudformationResource AWS::CodePipeline::Pipeline */ export declare namespace CfnPipeline { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-disableinboundstagetransitions.html * @external */ interface StageTransitionProperty { /** * `CfnPipeline.StageTransitionProperty.Reason`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-disableinboundstagetransitions.html#cfn-codepipeline-pipeline-disableinboundstagetransitions-reason * @external */ readonly reason: string; /** * `CfnPipeline.StageTransitionProperty.StageName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-disableinboundstagetransitions.html#cfn-codepipeline-pipeline-disableinboundstagetransitions-stagename * @external */ readonly stageName: string; } } /** * Properties for defining a `AWS::CodePipeline::Webhook`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html * @external */ export interface CfnWebhookProps { /** * `AWS::CodePipeline::Webhook.Authentication`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-authentication * @external */ readonly authentication: string; /** * `AWS::CodePipeline::Webhook.AuthenticationConfiguration`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-authenticationconfiguration * @external */ readonly authenticationConfiguration: CfnWebhook.WebhookAuthConfigurationProperty | cdk.IResolvable; /** * `AWS::CodePipeline::Webhook.Filters`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-filters * @external */ readonly filters: Array<CfnWebhook.WebhookFilterRuleProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::CodePipeline::Webhook.TargetAction`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-targetaction * @external */ readonly targetAction: string; /** * `AWS::CodePipeline::Webhook.TargetPipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-targetpipeline * @external */ readonly targetPipeline: string; /** * `AWS::CodePipeline::Webhook.TargetPipelineVersion`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-targetpipelineversion * @external */ readonly targetPipelineVersion: number; /** * `AWS::CodePipeline::Webhook.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-name * @external */ readonly name?: string; /** * `AWS::CodePipeline::Webhook.RegisterWithThirdParty`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-registerwiththirdparty * @external */ readonly registerWithThirdParty?: boolean | cdk.IResolvable; } /** * A CloudFormation `AWS::CodePipeline::Webhook`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html * @external * @cloudformationResource AWS::CodePipeline::Webhook */ export declare class CfnWebhook extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::CodePipeline::Webhook"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnWebhook; /** * @external * @cloudformationAttribute Url */ readonly attrUrl: string; /** * `AWS::CodePipeline::Webhook.Authentication`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-authentication * @external */ authentication: string; /** * `AWS::CodePipeline::Webhook.AuthenticationConfiguration`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-authenticationconfiguration * @external */ authenticationConfiguration: CfnWebhook.WebhookAuthConfigurationProperty | cdk.IResolvable; /** * `AWS::CodePipeline::Webhook.Filters`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-filters * @external */ filters: Array<CfnWebhook.WebhookFilterRuleProperty | cdk.IResolvable> | cdk.IResolvable; /** * `AWS::CodePipeline::Webhook.TargetAction`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-targetaction * @external */ targetAction: string; /** * `AWS::CodePipeline::Webhook.TargetPipeline`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-targetpipeline * @external */ targetPipeline: string; /** * `AWS::CodePipeline::Webhook.TargetPipelineVersion`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-targetpipelineversion * @external */ targetPipelineVersion: number; /** * `AWS::CodePipeline::Webhook.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-name * @external */ name: string | undefined; /** * `AWS::CodePipeline::Webhook.RegisterWithThirdParty`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html#cfn-codepipeline-webhook-registerwiththirdparty * @external */ registerWithThirdParty: boolean | cdk.IResolvable | undefined; /** * Create a new `AWS::CodePipeline::Webhook`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnWebhookProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::CodePipeline::Webhook`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html * @external * @cloudformationResource AWS::CodePipeline::Webhook */ export declare namespace CfnWebhook { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-webhook-webhookauthconfiguration.html * @external */ interface WebhookAuthConfigurationProperty { /** * `CfnWebhook.WebhookAuthConfigurationProperty.AllowedIPRange`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-webhook-webhookauthconfiguration.html#cfn-codepipeline-webhook-webhookauthconfiguration-allowediprange * @external */ readonly allowedIpRange?: string; /** * `CfnWebhook.WebhookAuthConfigurationProperty.SecretToken`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-webhook-webhookauthconfiguration.html#cfn-codepipeline-webhook-webhookauthconfiguration-secrettoken * @external */ readonly secretToken?: string; } } /** * A CloudFormation `AWS::CodePipeline::Webhook`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html * @external * @cloudformationResource AWS::CodePipeline::Webhook */ export declare namespace CfnWebhook { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-webhook-webhookfilterrule.html * @external */ interface WebhookFilterRuleProperty { /** * `CfnWebhook.WebhookFilterRuleProperty.JsonPath`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-webhook-webhookfilterrule.html#cfn-codepipeline-webhook-webhookfilterrule-jsonpath * @external */ readonly jsonPath: string; /** * `CfnWebhook.WebhookFilterRuleProperty.MatchEquals`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-webhook-webhookfilterrule.html#cfn-codepipeline-webhook-webhookfilterrule-matchequals * @external */ readonly matchEquals?: string; } }
the_stack
import * as React from 'react'; import { cleanup, render, fireEvent } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { DefaultButton } from './DefaultButton/DefaultButton'; import { IconButton } from './IconButton/IconButton'; import { ActionButton } from './ActionButton/ActionButton'; import { CommandBarButton } from './CommandBarButton/CommandBarButton'; import { CompoundButton } from './CompoundButton/CompoundButton'; import { KeyCodes, resetIds } from '../../Utilities'; import type { IContextualMenuProps } from '../../ContextualMenu'; const alertClicked = (): void => { /*noop*/ }; describe('Button', () => { beforeEach(() => { resetIds(); cleanup(); document.body.innerHTML = ''; }); it('renders DefaultButton correctly', () => { const { container } = render(<DefaultButton text="Button" />); expect(container).toMatchSnapshot(); }); it('renders ActionButton correctly', () => { const { container } = render(<ActionButton>Button</ActionButton>); expect(container).toMatchSnapshot(); }); it('renders a DefaultButton with a keytip correctly', () => { const keytipProps = { content: 'A', keySequences: ['a'], }; const { container } = render(<DefaultButton text="Button" keytipProps={keytipProps} />); expect(container).toMatchSnapshot(); }); it('renders CommandBarButton correctly', () => { const { container } = render( <CommandBarButton iconProps={{ iconName: 'Add' }} text="Create account" menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); expect(container).toMatchSnapshot(); }); it('renders CompoundButton correctly', () => { const { container } = render( <CompoundButton secondaryText="You can create a new account here.">Create account</CompoundButton>, ); expect(container).toMatchSnapshot(); }); it('renders IconButton correctly', () => { const { container } = render(<IconButton iconProps={{ iconName: 'Emoji2' }} title="Emoji" ariaLabel="Emoji" />); expect(container).toMatchSnapshot(); }); describe('DefaultButton', () => { it('can render without an onClick.', () => { const { container } = render(<DefaultButton>Hello</DefaultButton>); expect(container.firstElementChild!.tagName).toEqual('BUTTON'); }); it('can render with an onClick.', () => { const onClick: () => null = () => null; const { container } = render(<DefaultButton onClick={onClick}>Hello</DefaultButton>); expect(container.firstElementChild!.tagName).toEqual('BUTTON'); }); it('can render with an href', () => { const { container } = render( <DefaultButton href="http://www.microsoft.com" target="_blank"> Hello </DefaultButton>, ); expect(container.firstElementChild!.tagName).toEqual('A'); }); it('can handle elementRef', () => { const ref = React.createRef<HTMLElement>(); render(<DefaultButton elementRef={ref}>Content</DefaultButton>); expect(ref.current).toBeTruthy(); }); describe('aria attributes', () => { it('does not apply aria attributes that are not passed in', () => { const { getByRole } = render( <DefaultButton href="http://www.microsoft.com" target="_blank"> Hello </DefaultButton>, ); const button = getByRole('link'); expect(button.getAttribute('aria-label')).toBeNull(); expect(button.getAttribute('aria-labelledby')).toBeNull(); expect(button.getAttribute('aria-describedby')).toBeNull(); expect(button.getAttribute('aria-pressed')).toBeNull(); }); it('overrides native aria-label with Button ariaLabel', () => { const { getByRole } = render( <DefaultButton href="http://www.microsoft.com" target="_blank" aria-label="NativeLabel" ariaLabel="ButtonLabel" > Hello </DefaultButton>, ); const button = getByRole('link'); expect(button.getAttribute('aria-label')).toEqual('ButtonLabel'); expect(button.getAttribute('aria-labelledby')).toBeNull(); expect(button.getAttribute('aria-describedby')).toBeNull(); }); it('applies aria-label', () => { const { getByRole } = render( <DefaultButton href="http://www.microsoft.com" target="_blank" aria-label="MyLabel"> Hello </DefaultButton>, ); const button = getByRole('link'); expect(button.getAttribute('aria-label')).toEqual('MyLabel'); expect(button.getAttribute('aria-labelledby')).toBeNull(); expect(button.getAttribute('aria-describedby')).toBeNull(); }); it('applies aria-labelledby', () => { const { getByRole } = render( <DefaultButton href="http://www.microsoft.com" target="_blank" aria-labelledby="someid"> Hello </DefaultButton>, ); const button = getByRole('link'); expect(button.getAttribute('aria-labelledby')).toEqual('someid'); expect(button.getAttribute('aria-describedby')).toBeNull(); }); it('does not apply aria-labelledby to a button with no text', () => { const { getByRole } = render( <DefaultButton href="http://www.microsoft.com" target="_blank" aria-describedby="someid" />, ); const button = getByRole('link'); expect(button.getAttribute('aria-labelledby')).toBeNull(); expect(button.getAttribute('aria-describedby')).toEqual('someid'); }); it('applies aria-labelledby and aria-describedby', () => { const { getByRole } = render( <DefaultButton href="http://www.microsoft.com" target="_blank" ariaDescription="This description is not visible" styles={{ screenReaderText: 'some-screenreader-class' }} > Hello </DefaultButton>, ); const button = getByRole('link'); expect(button.getAttribute('aria-label')).toBeNull(); expect(button.getAttribute('aria-labelledby')).toEqual(button.querySelector(`.ms-Button-label`)!.id); expect(button.getAttribute('aria-describedby')).toEqual(button.querySelector('.some-screenreader-class')!.id); }); it('applies aria-describedby to an IconButton', () => { const { getByRole } = render( <IconButton iconProps={{ iconName: 'Emoji2' }} ariaDescription="Description on icon button" styles={{ screenReaderText: 'some-screenreader-class' }} />, ); const button = getByRole('button'); expect(button.getAttribute('aria-label')).toBeNull(); expect(button.getAttribute('aria-labelledby')).toBeNull(); expect(button.getAttribute('aria-describedby')).toEqual(button.querySelector('.some-screenreader-class')!.id); }); it('applies aria-labelledby and aria-describedby to a CompoundButton with ariaDescription', () => { const { getByRole } = render( <CompoundButton secondaryText="Some awesome description" ariaDescription="Description on icon button" styles={{ screenReaderText: 'some-screenreader-class' }} > And this is the label </CompoundButton>, ); const button = getByRole('button'); expect(button.getAttribute('aria-label')).toBeNull(); expect(button.getAttribute('aria-labelledby')).toEqual(button.querySelector('.ms-Button-label')!.id); expect(button.getAttribute('aria-describedby')).toEqual(button.querySelector('.some-screenreader-class')!.id); }); it( 'applies aria-labelledby and aria-describedby to a CompoundButton with secondaryText ' + 'and no ariaDescription', () => { const { getByRole } = render( <CompoundButton secondaryText="Some awesome description">And this is the label</CompoundButton>, ); const button = getByRole('button'); expect(button.getAttribute('aria-label')).toBeNull(); expect(button.getAttribute('aria-labelledby')).toEqual(button.querySelector('.ms-Button-label')!.id); expect(button.getAttribute('aria-describedby')).toEqual(button.querySelector('.ms-Button-description')!.id); }, ); it('does not apply aria-pressed to an unchecked button', () => { const { getByRole } = render(<DefaultButton toggle={true}>Hello</DefaultButton>); expect(getByRole('button').getAttribute('aria-pressed')).toEqual('false'); }); it('applies aria-pressed to a checked button', () => { const { getByRole } = render( <DefaultButton toggle={true} checked={true}> Hello </DefaultButton>, ); expect(getByRole('button').getAttribute('aria-pressed')).toEqual('true'); }); it('does not apply aria-pressed to an unchecked split button', () => { const { getAllByRole } = render( <DefaultButton toggle={true} split={true} onClick={alertClicked} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, ], }} > Hello </DefaultButton>, ); expect(getAllByRole('button')[0].getAttribute('aria-pressed')).toEqual('false'); }); it('applies aria-checked to a role=menuitemcheckbox checked button', () => { const { getByRole } = render( <DefaultButton role="menuitemcheckbox" toggle={true} checked={true}> Hello </DefaultButton>, ); expect(getByRole('menuitemcheckbox').getAttribute('aria-checked')).toEqual('true'); }); it('applies aria-checked to a role=checkbox checked button', () => { const { getByRole } = render( <DefaultButton role="checkbox" toggle={true} checked={true}> Hello </DefaultButton>, ); expect(getByRole('checkbox').getAttribute('aria-checked')).toEqual('true'); }); it('applies aria-checked=false to a role=checkbox button even if toggle is not passed', () => { const { getByRole } = render(<DefaultButton role="checkbox">Hello</DefaultButton>); expect(getByRole('checkbox').getAttribute('aria-checked')).toEqual('false'); }); it('does not mutate menuprops hidden property', () => { const menuProps: IContextualMenuProps = { hidden: false, items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, ], }; const { getAllByRole } = render( <DefaultButton toggle={true} split={true} onClick={alertClicked} persistMenu={true} menuProps={menuProps}> Hello </DefaultButton>, ); expect(getAllByRole('button')[0]).toBeTruthy(); expect(menuProps.hidden).toEqual(false); }); it('uses menuprops id in aria-controls when passed', () => { const menuProps: IContextualMenuProps = { id: 'custom-id', items: [ { key: 'menuItem', text: 'Menu Item', }, ], }; const { getByRole } = render(<DefaultButton menuProps={menuProps}>Hello</DefaultButton>); const button = getByRole('button'); userEvent.click(button); expect(button.getAttribute('aria-controls')).toBe('custom-id'); }); it('applies aria-pressed to a checked split button', () => { const { getAllByRole } = render( <DefaultButton toggle={true} checked={true} split={true} onClick={alertClicked} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, ], }} > Hello </DefaultButton>, ); expect(getAllByRole('button')[0].getAttribute('aria-pressed')).toEqual('true'); }); }); describe('with menuProps', () => { it('contains aria-haspopup=true', () => { const { getAllByRole } = render( <DefaultButton menuProps={{ items: [{ key: 'item', text: 'Item' }] }}>Hello</DefaultButton>, ); expect(getAllByRole('button')[0].getAttribute('aria-haspopup')).toEqual('true'); }); }); describe('without menuProps', () => { it('does not contain aria-haspopup', () => { const { getByRole } = render(<DefaultButton>Hello</DefaultButton>); expect(getByRole('button').getAttribute('aria-haspopup')).toEqual(null); }); }); describe('with menuIconProps', () => { it('Contains the expected icon via menuIconProps', () => { const { getAllByRole } = render(<DefaultButton menuIconProps={{ iconName: 'fontColor' }}>Hello</DefaultButton>); expect(getAllByRole('button')[0].querySelectorAll('[data-icon-name="fontColor"]').length).toEqual(1); }); }); it('Providing onClick and menuProps does not render a SplitButton', () => { const { getAllByRole } = render( <DefaultButton text="Create account" onClick={alertClicked} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); expect(getAllByRole('button')[0].tagName).not.toEqual('DIV'); }); it('Providing onKeyDown and menuProps still fires provided onKeyDown', () => { const keyDownSpy = jest.fn(); render( <DefaultButton text="Create account" onKeyDown={keyDownSpy} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); userEvent.tab(); userEvent.keyboard('{enter}'); expect(keyDownSpy).toHaveBeenCalled(); }); it('Providing onKeyDown, menuProps and splitButton=true fires provided onKeyDown on both buttons', () => { const keyDownSpy = jest.fn(); render( <DefaultButton text="Create account" onKeyDown={keyDownSpy} split={true} onClick={alertClicked} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); userEvent.tab(); userEvent.keyboard('{arrowdown}'); expect(keyDownSpy).toHaveBeenCalled(); }); it('Space keydown in a splitButton will fire onClick', () => { const onClickSpy = jest.fn(); render( <DefaultButton data-automation-id="test" text="Create account" split={true} onClick={onClickSpy} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); userEvent.tab(); userEvent.keyboard('{space}'); expect(onClickSpy).toHaveBeenCalled(); }); it('Providing onClick, menuProps and setting splitButton to true renders a SplitButton', () => { const { getAllByRole } = render( <DefaultButton text="Create account" split={true} onClick={alertClicked} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); expect(getAllByRole('button')[0].tagName).toEqual('DIV'); }); it('Tapping menu button of SplitButton expands menu', () => { const { getAllByRole } = render( <DefaultButton text="Create account" split={true} onClick={alertClicked} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); const menuButton = getAllByRole('button')[2]; userEvent.click(menuButton); expect(getAllByRole('button')[0].getAttribute('aria-expanded')).toEqual('true'); }); it('Touch Start on primary button of SplitButton expands menu', () => { const { getAllByRole } = render( <DefaultButton text="Create account" split={true} onClick={alertClicked} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); const primaryButton = getAllByRole('button')[1]; // in a normal scenario, when we do a touchstart we would also cause a // click event to fire. This doesn't happen in the simulator so we're // manually adding this in. fireEvent.touchStart(primaryButton); userEvent.click(primaryButton); expect(getAllByRole('button')[0].getAttribute('aria-expanded')).toEqual('true'); }); it('If menu trigger is disabled, pressing down does not trigger menu', () => { const { getAllByRole } = render( <DefaultButton text="Create account" menuTriggerKeyCode={null} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); userEvent.tab(); userEvent.keyboard('{arrowdown}'); expect(getAllByRole('button')[0].getAttribute('aria-expanded')).toEqual('false'); }); it('If menu trigger is specified, default key is overridden', () => { const { getAllByRole } = render( <DefaultButton text="Create account" menuTriggerKeyCode={KeyCodes.right} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); const button = getAllByRole('button')[0]; userEvent.tab(); userEvent.keyboard('{arrowdown}'); expect(button.getAttribute('aria-expanded')).toEqual('false'); userEvent.keyboard('{arrowright}'); expect(button.getAttribute('aria-expanded')).toEqual('true'); }); describe('Response to click event', () => { let didClick = false; const setTrue = (): void => { didClick = true; }; beforeEach(() => { didClick = false; }); function buildRenderButtonWithMenu(callbackMock?: jest.Mock<unknown>, persistMenu?: boolean): HTMLElement { const { getAllByRole } = render( <DefaultButton text="Create account" split={true} onClick={setTrue} onAfterMenuDismiss={callbackMock} persistMenu={persistMenu} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); return getAllByRole('button')[0]; } it('Clicking SplitButton button triggers action', () => { const button: HTMLElement = buildRenderButtonWithMenu(); const menuButtonDOM: HTMLButtonElement = button.querySelectorAll('button')[0]; userEvent.click(menuButtonDOM); expect(didClick).toEqual(true); }); it('Pressing alt + down on SplitButton triggers menu', () => { const button: HTMLElement = buildRenderButtonWithMenu(); userEvent.tab(); userEvent.keyboard('{alt}{arrowdown}'); expect(button.getAttribute('aria-expanded')).toEqual('true'); }); it('Click on button opens the menu, a second click closes the menu and calls onAfterMenuDismiss', () => { const callbackMock = jest.fn(); const button: HTMLElement = buildRenderButtonWithMenu(callbackMock); const menuButtonElement = button.querySelectorAll('button')[1]; userEvent.click(menuButtonElement); expect(button.getAttribute('aria-expanded')).toEqual('true'); userEvent.click(menuButtonElement); expect(button.getAttribute('aria-expanded')).toEqual('false'); expect(callbackMock.mock.calls.length).toBe(1); }); it('[PersistedMenu] Opens on first click, closes on second click and calls onAfterMenuDismiss', () => { const callbackMock = jest.fn(); const button: HTMLElement = buildRenderButtonWithMenu(callbackMock, true); const menuButtonElement = button.querySelectorAll('button')[1]; userEvent.click(menuButtonElement); expect(button.getAttribute('aria-expanded')).toEqual('true'); userEvent.click(menuButtonElement); expect(button.getAttribute('aria-expanded')).toEqual('false'); expect(callbackMock.mock.calls.length).toBe(1); }); it('A disabled SplitButton does not respond to input events', () => { const { getAllByRole } = render( <DefaultButton disabled={true} text="Create account" split={true} onClick={setTrue} onKeyPress={setTrue} onKeyUp={setTrue} onKeyDown={setTrue} onMouseDown={setTrue} onMouseUp={setTrue} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); const button = getAllByRole('button')[0]; userEvent.click(button); userEvent.keyboard('{alt}{arrowdown}'); expect(didClick).toEqual(false); }); it('A disabled Button does not respond to input events', () => { const { getAllByRole } = render( <DefaultButton disabled={true} text="Create account" split={false} onClick={setTrue} onKeyPress={setTrue} onKeyUp={setTrue} onKeyDown={setTrue} onMouseDown={setTrue} onMouseUp={setTrue} />, ); const button = getAllByRole('button')[0]; userEvent.click(button); userEvent.keyboard('{alt}{arrowdown}'); expect(didClick).toEqual(false); }); it('A focusable disabled button does not respond to input events', () => { const { getAllByRole } = render( <DefaultButton disabled={true} allowDisabledFocus={true} text="Create account" split={false} onClick={setTrue} onKeyPress={setTrue} onKeyUp={setTrue} onKeyDown={setTrue} onMouseDown={setTrue} onMouseUp={setTrue} />, ); const button = getAllByRole('button')[0]; userEvent.click(button); userEvent.keyboard('{alt}{arrowdown}'); expect(didClick).toEqual(false); }); it('A focusable disabled menu button does not respond to input events', () => { const { getAllByRole } = render( <DefaultButton disabled={true} allowDisabledFocus={true} text="Create account" split={false} onClick={setTrue} onKeyPress={setTrue} onKeyUp={setTrue} onKeyDown={setTrue} onMouseDown={setTrue} onMouseUp={setTrue} menuProps={{ items: [ { key: 'emailMessage', text: 'Email message', iconProps: { iconName: 'Mail' }, }, { key: 'calendarEvent', text: 'Calendar event', iconProps: { iconName: 'Calendar' }, }, ], }} />, ); const button = getAllByRole('button')[0]; userEvent.click(button); userEvent.keyboard('{alt}{arrowdown}'); expect(didClick).toEqual(false); }); }); describe('with contextual menu', () => { function buildRenderAndClickButtonAndReturnContextualMenuDOMElement( menuPropsPatch?: any, text?: string, textAsChildElement: boolean = false, ): HTMLElement { const menuProps = { items: [{ key: 'item', name: 'Item' }], ...menuPropsPatch }; const element: React.ReactElement<any> = ( <DefaultButton iconProps={{ iconName: 'Add' }} text={!textAsChildElement && text ? text : undefined} menuProps={menuProps} > {textAsChildElement && text ? text : null} </DefaultButton> ); const { getAllByRole } = render(element); const button = getAllByRole('button')[0]; userEvent.click(button); // get the menu id from the button's aria attribute const menuId = button.getAttribute('aria-controls'); expect(menuId).toBeTruthy(); const menuDOM = button.ownerDocument!.getElementById(menuId as string); expect(menuDOM).toBeTruthy(); return menuDOM as HTMLElement; } it('If button has text, contextual menu has aria-labelledBy attribute set', () => { const contextualMenuElement = buildRenderAndClickButtonAndReturnContextualMenuDOMElement(null, 'Button Text'); expect(contextualMenuElement).not.toBeNull(); expect(contextualMenuElement?.getAttribute('aria-label')).toBeNull(); expect(contextualMenuElement?.getAttribute('aria-labelledBy')).toBeTruthy(); }); it('If button has a text child, contextual menu has aria-labelledBy attribute set', () => { const contextualMenuElement = buildRenderAndClickButtonAndReturnContextualMenuDOMElement( null, 'Button Text', true, ); expect(contextualMenuElement).not.toBeNull(); expect(contextualMenuElement?.getAttribute('aria-label')).toBeNull(); expect(contextualMenuElement?.getAttribute('aria-labelledBy')).not.toBeNull(); }); it('If button has no text, contextual menu has no aria-label or aria-labelledBy attributes', () => { const contextualMenuElement = buildRenderAndClickButtonAndReturnContextualMenuDOMElement(); expect(contextualMenuElement).not.toBeNull(); expect(contextualMenuElement?.getAttribute('aria-label')).toBeNull(); expect(contextualMenuElement?.getAttribute('aria-labelledBy')).toBeNull(); }); it('If button has text but ariaLabel provided in menuProps, contextual menu has aria-label set', () => { const explicitLabel = 'ExplicitLabel'; const contextualMenuElement = buildRenderAndClickButtonAndReturnContextualMenuDOMElement( { ariaLabel: explicitLabel }, 'Button Text', ); expect(contextualMenuElement).not.toBeNull(); expect(contextualMenuElement?.getAttribute('aria-label')).toEqual(explicitLabel); expect(contextualMenuElement?.getAttribute('aria-labelledBy')).toBeNull(); }); it('Click on button opens the menu, escape press dismisses menu', () => { const callbackMock = jest.fn(); const menuProps = { items: [{ key: 'item', name: 'Item' }], onDismiss: callbackMock }; const { getAllByRole } = render( <DefaultButton iconProps={{ iconName: 'Add' }} menuProps={menuProps}> {'Button Text'} </DefaultButton>, ); const button = getAllByRole('button')[0]; userEvent.click(button); // get the menu id from the button's aria attribute const menuId = button.getAttribute('aria-controls'); expect(menuId).toBeTruthy(); const contextualMenuElement = button.ownerDocument!.getElementById(menuId as string); expect(contextualMenuElement).not.toBeNull(); userEvent.tab(); userEvent.keyboard('{esc}'); expect(callbackMock.mock.calls.length).toBe(1); // Expect that the menu doesn't exist any more since it's been dismissed const dismissed = button.ownerDocument!.getElementById(menuId as string); expect(dismissed).toBeNull(); }); it(`If button has text but labelElementId provided in menuProps, contextual menu has aria-labelledBy reflecting labelElementId`, () => { const explicitLabelElementId = 'id_ExplicitLabel'; const contextualMenuElement = buildRenderAndClickButtonAndReturnContextualMenuDOMElement( { labelElementId: explicitLabelElementId }, 'Button Text', ); expect(contextualMenuElement).not.toBeNull(); expect(contextualMenuElement?.getAttribute('aria-label')).toBeNull(); expect(contextualMenuElement?.getAttribute('aria-labelledBy')).toEqual(explicitLabelElementId); }); }); }); });
the_stack
import { IExecuteFunctions, } from 'n8n-core'; import { IDataObject, ILoadOptionsFunctions, INodeExecutionData, INodePropertyOptions, INodeType, INodeTypeDescription, } from 'n8n-workflow'; import { discourseApiRequest, } from './GenericFunctions'; import { postFields, postOperations, } from './PostDescription'; import { categoryFields, categoryOperations, } from './CategoryDescription'; import { groupFields, groupOperations, } from './GroupDescription'; // import { // searchFields, // searchOperations, // } from './SearchDescription'; import { userFields, userOperations, } from './UserDescription'; import { userGroupFields, userGroupOperations, } from './UserGroupDescription'; //import * as moment from 'moment'; export class Discourse implements INodeType { description: INodeTypeDescription = { displayName: 'Discourse', name: 'discourse', icon: 'file:discourse.svg', group: ['input'], version: 1, subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', description: 'Consume Discourse API', defaults: { name: 'Discourse', }, inputs: ['main'], outputs: ['main'], credentials: [ { name: 'discourseApi', required: true, }, ], properties: [ { displayName: 'Resource', name: 'resource', type: 'options', options: [ { name: 'Category', value: 'category', }, { name: 'Group', value: 'group', }, { name: 'Post', value: 'post', }, // { // name: 'Search', // value: 'search', // }, { name: 'User', value: 'user', }, { name: 'User Group', value: 'userGroup', }, ], default: 'post', description: 'The resource to operate on.', }, ...categoryOperations, ...categoryFields, ...groupOperations, ...groupFields, ...postOperations, ...postFields, // ...searchOperations, // ...searchFields, ...userOperations, ...userFields, ...userGroupOperations, ...userGroupFields, ], }; methods = { loadOptions: { // Get all the calendars to display them to user so that he can // select them easily async getCategories( this: ILoadOptionsFunctions, ): Promise<INodePropertyOptions[]> { const returnData: INodePropertyOptions[] = []; const { category_list } = await discourseApiRequest.call( this, 'GET', `/categories.json`, ); for (const category of category_list.categories) { returnData.push({ name: category.name, value: category.id, }); } return returnData; }, }, }; async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> { const items = this.getInputData(); const returnData: IDataObject[] = []; const length = (items.length as unknown) as number; const qs: IDataObject = {}; let responseData; const resource = this.getNodeParameter('resource', 0) as string; const operation = this.getNodeParameter('operation', 0) as string; for (let i = 0; i < length; i++) { try { if (resource === 'category') { //https://docs.discourse.org/#tag/Categories/paths/~1categories.json/post if (operation === 'create') { const name = this.getNodeParameter('name', i) as string; const color = this.getNodeParameter('color', i) as string; const textColor = this.getNodeParameter('textColor', i) as string; const body: IDataObject = { name, color, text_color: textColor, }; responseData = await discourseApiRequest.call( this, 'POST', `/categories.json`, body, ); responseData = responseData.category; } //https://docs.discourse.org/#tag/Categories/paths/~1categories.json/get if (operation === 'getAll') { const returnAll = this.getNodeParameter('returnAll', i) as boolean; responseData = await discourseApiRequest.call( this, 'GET', `/categories.json`, {}, qs, ); responseData = responseData.category_list.categories; if (returnAll === false) { const limit = this.getNodeParameter('limit', i) as number; responseData = responseData.splice(0, limit); } } //https://docs.discourse.org/#tag/Categories/paths/~1categories~1{id}/put if (operation === 'update') { const categoryId = this.getNodeParameter('categoryId', i) as string; const name = this.getNodeParameter('name', i) as string; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; const body: IDataObject = { name, }; Object.assign(body, updateFields); responseData = await discourseApiRequest.call( this, 'PUT', `/categories/${categoryId}.json`, body, ); responseData = responseData.category; } } if (resource === 'group') { //https://docs.discourse.org/#tag/Posts/paths/~1posts.json/post if (operation === 'create') { const name = this.getNodeParameter('name', i) as string; const body: IDataObject = { name, }; responseData = await discourseApiRequest.call( this, 'POST', `/admin/groups.json`, { group: body }, ); responseData = responseData.basic_group; } //https://docs.discourse.org/#tag/Groups/paths/~1groups~1{name}.json/get if (operation === 'get') { const name = this.getNodeParameter('name', i) as string; responseData = await discourseApiRequest.call( this, 'GET', `/groups/${name}`, {}, qs, ); responseData = responseData.group; } //https://docs.discourse.org/#tag/Groups/paths/~1groups.json/get if (operation === 'getAll') { const returnAll = this.getNodeParameter('returnAll', i) as boolean; responseData = await discourseApiRequest.call( this, 'GET', `/groups.json`, {}, qs, ); responseData = responseData.groups; if (returnAll === false) { const limit = this.getNodeParameter('limit', i) as number; responseData = responseData.splice(0, limit); } } //https://docs.discourse.org/#tag/Posts/paths/~1posts~1{id}.json/put if (operation === 'update') { const groupId = this.getNodeParameter('groupId', i) as string; const name = this.getNodeParameter('name', i) as string; const body: IDataObject = { name, }; responseData = await discourseApiRequest.call( this, 'PUT', `/groups/${groupId}.json`, { group: body }, ); } } if (resource === 'post') { //https://docs.discourse.org/#tag/Posts/paths/~1posts.json/post if (operation === 'create') { const content = this.getNodeParameter('content', i) as string; const title = this.getNodeParameter('title', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; const body: IDataObject = { title, raw: content, }; Object.assign(body, additionalFields); responseData = await discourseApiRequest.call( this, 'POST', `/posts.json`, body, ); } //https://docs.discourse.org/#tag/Posts/paths/~1posts~1{id}.json/get if (operation === 'get') { const postId = this.getNodeParameter('postId', i) as string; responseData = await discourseApiRequest.call( this, 'GET', `/posts/${postId}`, {}, qs, ); } //https://docs.discourse.org/#tag/Posts/paths/~1posts.json/get if (operation === 'getAll') { const returnAll = this.getNodeParameter('returnAll', i) as boolean; responseData = await discourseApiRequest.call( this, 'GET', `/posts.json`, {}, qs, ); responseData = responseData.latest_posts; if (returnAll === false) { const limit = this.getNodeParameter('limit', i) as number; responseData = responseData.splice(0, limit); } } //https://docs.discourse.org/#tag/Posts/paths/~1posts~1{id}.json/put if (operation === 'update') { const postId = this.getNodeParameter('postId', i) as string; const content = this.getNodeParameter('content', i) as string; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; const body: IDataObject = { raw: content, }; Object.assign(body, updateFields); responseData = await discourseApiRequest.call( this, 'PUT', `/posts/${postId}.json`, body, ); responseData = responseData.post; } } // TODO figure how to paginate the results // if (resource === 'search') { // //https://docs.discourse.org/#tag/Search/paths/~1search~1query/get // if (operation === 'query') { // qs.term = this.getNodeParameter('term', i) as string; // const simple = this.getNodeParameter('simple', i) as boolean; // const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; // Object.assign(qs, updateFields); // qs.page = 1; // responseData = await discourseApiRequest.call( // this, // 'GET', // `/search/query`, // {}, // qs, // ); // if (simple === true) { // const response = []; // for (const key of Object.keys(responseData)) { // for (const data of responseData[key]) { // response.push(Object.assign(data, { __type: key })); // } // } // responseData = response; // } // } // } if (resource === 'user') { //https://docs.discourse.org/#tag/Users/paths/~1users/post if (operation === 'create') { const name = this.getNodeParameter('name', i) as string; const email = this.getNodeParameter('email', i) as string; const password = this.getNodeParameter('password', i) as string; const username = this.getNodeParameter('username', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; const body: IDataObject = { name, password, email, username, }; Object.assign(body, additionalFields); responseData = await discourseApiRequest.call( this, 'POST', `/users.json`, body, ); } //https://docs.discourse.org/#tag/Users/paths/~1users~1{username}.json/get if (operation === 'get') { const by = this.getNodeParameter('by', i) as string; let endpoint = ''; if (by === 'username') { const username = this.getNodeParameter('username', i) as string; endpoint = `/users/${username}`; } else if (by === 'externalId') { const externalId = this.getNodeParameter('externalId', i) as string; endpoint = `/u/by-external/${externalId}.json`; } responseData = await discourseApiRequest.call( this, 'GET', endpoint, ); } //https://docs.discourse.org/#tag/Users/paths/~1admin~1users~1{id}.json/delete if (operation === 'getAll') { const returnAll = this.getNodeParameter('returnAll', i) as boolean; const flag = this.getNodeParameter('flag', i) as boolean; responseData = await discourseApiRequest.call( this, 'GET', `/admin/users/list/${flag}.json`, {}, qs, ); if (returnAll === false) { const limit = this.getNodeParameter('limit', i) as number; responseData = responseData.splice(0, limit); } } } if (resource === 'userGroup') { //https://docs.discourse.org/#tag/Groups/paths/~1groups~1{group_id}~1members.json/put if (operation === 'add') { const usernames = this.getNodeParameter('usernames', i) as string; const groupId = this.getNodeParameter('groupId', i) as string; const body: IDataObject = { usernames, }; responseData = await discourseApiRequest.call( this, 'PUT', `/groups/${groupId}/members.json`, body, ); } //https://docs.discourse.org/#tag/Groups/paths/~1groups~1{group_id}~1members.json/delete if (operation === 'remove') { const usernames = this.getNodeParameter('usernames', i) as string; const groupId = this.getNodeParameter('groupId', i) as string; const body: IDataObject = { usernames, }; responseData = await discourseApiRequest.call( this, 'DELETE', `/groups/${groupId}/members.json`, body, ); } } if (Array.isArray(responseData)) { returnData.push.apply(returnData, responseData as IDataObject[]); } else if (responseData !== undefined) { returnData.push(responseData as IDataObject); } } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } return [this.helpers.returnJsonArray(returnData)]; } }
the_stack
import {Fraction} from "../../Common/DataObjects/Fraction"; import {Repetition} from "../MusicSource/Repetition"; import {DynamicsContainer} from "../VoiceData/HelperObjects/DynamicsContainer"; import {MappingSourceMusicPart} from "../MusicSource/MappingSourceMusicPart"; import {SourceMeasure} from "../VoiceData/SourceMeasure"; import {VoiceEntry} from "../VoiceData/VoiceEntry"; import {Instrument} from "../Instrument"; import {VerticalSourceStaffEntryContainer} from "../VoiceData/VerticalSourceStaffEntryContainer"; import {RhythmInstruction} from "../VoiceData/Instructions/RhythmInstruction"; import {AbstractNotationInstruction} from "../VoiceData/Instructions/AbstractNotationInstruction"; import {RepetitionInstruction} from "../VoiceData/Instructions/RepetitionInstruction"; import {ContinuousDynamicExpression} from "../VoiceData/Expressions/ContinuousExpressions/ContinuousDynamicExpression"; import {InstantaneousDynamicExpression} from "../VoiceData/Expressions/InstantaneousDynamicExpression"; import {MultiTempoExpression} from "../VoiceData/Expressions/MultiTempoExpression"; import {AbstractExpression} from "../VoiceData/Expressions/AbstractExpression"; import log from "loglevel"; import { MusicSheet } from "../MusicSheet"; export class MusicPartManagerIterator { constructor(musicSheet: MusicSheet, startTimestamp?: Fraction, endTimestamp?: Fraction) { try { this.frontReached = true; this.musicSheet = musicSheet; this.currentVoiceEntries = undefined; this.frontReached = false; for (const rep of this.musicSheet.Repetitions) { this.setRepetitionIterationCount(rep, 1); } this.activeDynamicExpressions = new Array(this.musicSheet.getCompleteNumberOfStaves()); this.currentMeasure = this.musicSheet.SourceMeasures[0]; if (!startTimestamp) { return; } do { this.moveToNext(); } while ((!this.currentVoiceEntries || this.currentTimeStamp.lt(startTimestamp)) && !this.endReached); for (let staffIndex: number = 0; staffIndex < this.activeDynamicExpressions.length; staffIndex++) { if (this.activeDynamicExpressions[staffIndex]) { if (this.activeDynamicExpressions[staffIndex] instanceof ContinuousDynamicExpression) { const continuousDynamic: ContinuousDynamicExpression = <ContinuousDynamicExpression>this.activeDynamicExpressions[staffIndex]; this.currentDynamicChangingExpressions.push(new DynamicsContainer(continuousDynamic, staffIndex)); } else { const instantaneousDynamic: InstantaneousDynamicExpression = <InstantaneousDynamicExpression>this.activeDynamicExpressions[staffIndex]; this.currentDynamicChangingExpressions.push(new DynamicsContainer(instantaneousDynamic, staffIndex)); } } } this.currentTempoChangingExpression = this.activeTempoExpression; } catch (err) { log.info("MusicPartManagerIterator: " + err); } } public backJumpOccurred: boolean; public forwardJumpOccurred: boolean; private musicSheet: MusicSheet; private currentMappingPart: MappingSourceMusicPart; private currentMeasure: SourceMeasure; private currentMeasureIndex: number = 0; private currentPartIndex: number = 0; private currentVoiceEntryIndex: number = -1; private currentDynamicEntryIndex: number = 0; private currentTempoEntryIndex: number = 0; private currentVoiceEntries: VoiceEntry[]; private currentDynamicChangingExpressions: DynamicsContainer[] = []; private currentTempoChangingExpression: MultiTempoExpression; // FIXME: replace these two with a real Dictionary! private repetitionIterationCountDictKeys: Repetition[]; private repetitionIterationCountDictValues: number[]; private currentRepetition: Repetition = undefined; private endReached: boolean = false; private frontReached: boolean = false; public currentTimeStamp: Fraction = new Fraction(0, 1); private currentEnrolledMeasureTimestamp: Fraction = new Fraction(0, 1); private currentRelativeInMeasureTimestamp: Fraction = new Fraction(0, 1); private currentVerticalContainerInMeasureTimestamp: Fraction = new Fraction(0, 1); private jumpResponsibleRepetition: Repetition = undefined; private currentBpm: number; private activeDynamicExpressions: AbstractExpression[] = []; private activeTempoExpression: MultiTempoExpression; public get EndReached(): boolean { return this.endReached; } public get FrontReached(): boolean { return this.frontReached; } public get CurrentMeasure(): SourceMeasure { return this.currentMeasure; } public get CurrentRepetition(): Repetition { return this.currentRepetition; } public get CurrentRepetitionIteration(): number { if (this.CurrentRepetition) { return this.getRepetitionIterationCount(this.CurrentRepetition); } return 0; } public get CurrentJumpResponsibleRepetitionIterationBeforeJump(): number { if (this.jumpResponsibleRepetition) { return this.getRepetitionIterationCount(this.jumpResponsibleRepetition) - 1; } return 0; } public get CurrentBpm(): number { return this.currentBpm; } public get CurrentVoiceEntries(): VoiceEntry[] { return this.currentVoiceEntries; } public get CurrentMeasureIndex(): number { return this.currentMeasureIndex; } public get CurrentEnrolledTimestamp(): Fraction { return Fraction.plus(this.currentEnrolledMeasureTimestamp, this.currentVerticalContainerInMeasureTimestamp); } public get CurrentSourceTimestamp(): Fraction { return this.currentTimeStamp; } public get CurrentRelativeInMeasureTimestamp(): Fraction { return this.currentRelativeInMeasureTimestamp; } public get JumpOccurred(): boolean { return this.backJumpOccurred || this.forwardJumpOccurred; } public get ActiveTempoExpression(): MultiTempoExpression { return this.activeTempoExpression; } public get ActiveDynamicExpressions(): AbstractExpression[] { return this.activeDynamicExpressions; } public get CurrentTempoChangingExpression(): MultiTempoExpression { return this.currentTempoChangingExpression; } public get JumpResponsibleRepetition(): Repetition { return this.jumpResponsibleRepetition; } /** * Creates a clone of this iterator which has the same actual position. */ public clone(startTimeStamp: Fraction = undefined, endTimeStamp: Fraction = undefined): MusicPartManagerIterator { const ret: MusicPartManagerIterator = new MusicPartManagerIterator(this.musicSheet, startTimeStamp ?? this.currentTimeStamp, endTimeStamp); ret.currentVoiceEntryIndex = this.currentVoiceEntryIndex; ret.currentMappingPart = this.currentMappingPart; ret.currentPartIndex = this.currentPartIndex; ret.currentVoiceEntries = this.currentVoiceEntries; ret.endReached = this.endReached; ret.frontReached = this.frontReached; // alternative method to set currentTimeStamp? may not fully affect current iterator position // ret.currentTimeStamp = this.currentTimeStamp; return ret; } /** * Returns the visible voice entries for the provided instrument of the current iterator position. * @param instrument * Returns: A List of voiceEntries. If there are no entries the List has a Count of 0 (it does not return null). */ public CurrentVisibleVoiceEntries(instrument?: Instrument): VoiceEntry[] { const voiceEntries: VoiceEntry[] = []; if (!this.currentVoiceEntries) { return voiceEntries; } if (instrument) { for (const entry of this.currentVoiceEntries) { if (entry.ParentVoice.Parent.IdString === instrument.IdString) { this.getVisibleEntries(entry, voiceEntries); return voiceEntries; } } } else { for (const entry of this.currentVoiceEntries) { this.getVisibleEntries(entry, voiceEntries); } } return voiceEntries; } /** * Returns the visible voice entries for the provided instrument of the current iterator position. * @param instrument * Returns: A List of voiceEntries. If there are no entries the List has a Count of 0 (it does not return null). */ public CurrentAudibleVoiceEntries(instrument?: Instrument): VoiceEntry[] { const voiceEntries: VoiceEntry[] = []; if (!this.currentVoiceEntries) { return voiceEntries; } if (instrument) { for (const entry of this.currentVoiceEntries) { if (entry.ParentVoice.Parent.IdString === instrument.IdString) { this.getAudibleEntries(entry, voiceEntries); return voiceEntries; } } } else { for (const entry of this.currentVoiceEntries) { this.getAudibleEntries(entry, voiceEntries); } } return voiceEntries; } /** * Returns the audible dynamics of the current iterator position. * Returns: A List of Dynamics. If there are no entries the List has a Count of 0 (it does not return null). */ public getCurrentDynamicChangingExpressions(): DynamicsContainer[] { return this.currentDynamicChangingExpressions; } /** * Returns the score following voice entries for the provided instrument of the current iterator position. * @param instrument * Returns: A List of voiceEntries. If there are no entries the List has a Count of 0 * (it does not return null). */ public CurrentScoreFollowingVoiceEntries(instrument?: Instrument): VoiceEntry[] { const voiceEntries: VoiceEntry[] = []; if (!this.currentVoiceEntries) { return voiceEntries; } if (instrument) { for (const entry of this.currentVoiceEntries) { if (entry.ParentVoice.Parent.IdString === instrument.IdString) { this.getScoreFollowingEntries(entry, voiceEntries); return voiceEntries; } } } else { for (const entry of this.currentVoiceEntries) { this.getScoreFollowingEntries(entry, voiceEntries); } } return voiceEntries; } //public currentPlaybackSettings(): PlaybackSettings { // return this.manager.MusicSheet.SheetPlaybackSetting; //} public moveToNext(): void { this.forwardJumpOccurred = this.backJumpOccurred = false; if (this.endReached) { return; } if (this.currentVoiceEntries) { this.currentVoiceEntries = []; } this.recursiveMove(); if (!this.currentMeasure) { this.currentTimeStamp = new Fraction(99999, 1); } } public moveToNextVisibleVoiceEntry(notesOnly: boolean): void { while (!this.endReached) { this.moveToNext(); if (this.checkEntries(notesOnly)) { return; } } } private resetRepetitionIterationCount(repetition: Repetition): number { this.setRepetitionIterationCount(repetition, 1); return 1; } private incrementRepetitionIterationCount(repetition: Repetition): number { if (this.repetitionIterationCountDictKeys.indexOf(repetition) === -1) { return this.setRepetitionIterationCount(repetition, 1); } else { return this.setRepetitionIterationCount(repetition, this.getRepetitionIterationCount(repetition) + 1); } } private setRepetitionIterationCount(repetition: Repetition, iterationCount: number): number { const i: number = this.repetitionIterationCountDictKeys.indexOf(repetition); if (i === -1) { this.repetitionIterationCountDictKeys.push(repetition); this.repetitionIterationCountDictValues.push(iterationCount); } else { this.repetitionIterationCountDictValues[i] = iterationCount; } return iterationCount; } private getRepetitionIterationCount(rep: Repetition): number { const i: number = this.repetitionIterationCountDictKeys.indexOf(rep); if (i !== -1) { return this.repetitionIterationCountDictValues[i]; } } /* private moveTempoIndexToTimestamp(measureNumber: number): void { for (let index: number = 0; index < this.manager.MusicSheet.TimestampSortedTempoExpressionsList.length; index++) { if (this.manager.MusicSheet.TimestampSortedTempoExpressionsList[index].SourceMeasureParent.MeasureNumber >= measureNumber) { this.currentTempoEntryIndex = Math.Max(-1, index - 1); return } } } private getNextTempoEntryTimestamp(): Fraction { if (this.currentTempoEntryIndex >= this.manager.MusicSheet.TimestampSortedTempoExpressionsList.length - 1) { return new Fraction(99999, 1); } return this.manager.MusicSheet.TimestampSortedTempoExpressionsList[this.currentTempoEntryIndex + 1].SourceMeasureParent.AbsoluteTimestamp + this.manager.MusicSheet.TimestampSortedTempoExpressionsList[this.currentTempoEntryIndex + 1].Timestamp; } private moveToNextDynamic(): void { this.currentDynamicEntryIndex++; this.currentDynamicChangingExpressions.Clear(); let curDynamicEntry: DynamicsContainer = this.manager.MusicSheet.TimestampSortedDynamicExpressionsList[this.currentDynamicEntryIndex]; this.currentDynamicChangingExpressions.push(curDynamicEntry); let tsNow: Fraction = curDynamicEntry.parMultiExpression().AbsoluteTimestamp; for (let i: number = this.currentDynamicEntryIndex + 1; i < this.manager.MusicSheet.TimestampSortedDynamicExpressionsList.length; i++) { curDynamicEntry = this.manager.MusicSheet.TimestampSortedDynamicExpressionsList[i]; if ((curDynamicEntry.parMultiExpression().AbsoluteTimestamp !== tsNow)) { break; } this.currentDynamicEntryIndex = i; this.currentDynamicChangingExpressions.push(curDynamicEntry); } } private moveDynamicIndexToTimestamp(absoluteTimestamp: Fraction): void { let dynamics: DynamicsContainer[] = this.manager.MusicSheet.TimestampSortedDynamicExpressionsList; for (let index: number = 0; index < dynamics.length; index++) { if (dynamics[index].parMultiExpression().AbsoluteTimestamp.gte(absoluteTimestamp)) { this.currentDynamicEntryIndex = Math.Max(0, index - 1); return } } } private getNextDynamicsEntryTimestamp(): Fraction { if (this.currentDynamicEntryIndex >= this.manager.MusicSheet.TimestampSortedDynamicExpressionsList.length - 1) { return new Fraction(99999, 1); } return this.manager.MusicSheet.TimestampSortedDynamicExpressionsList[this.currentDynamicEntryIndex + 1].parMultiExpression().AbsoluteTimestamp; } */ private handleRepetitionsAtMeasureBegin(): void { for (let idx: number = 0, len: number = this.currentMeasure.FirstRepetitionInstructions.length; idx < len; ++idx) { const repetitionInstruction: RepetitionInstruction = this.currentMeasure.FirstRepetitionInstructions[idx]; if (!repetitionInstruction.parentRepetition) { continue; } const currentRepetition: Repetition = repetitionInstruction.parentRepetition; this.currentRepetition = currentRepetition; if (currentRepetition.StartIndex === this.currentMeasureIndex) { if ( this.JumpResponsibleRepetition !== undefined && currentRepetition !== this.JumpResponsibleRepetition && currentRepetition.StartIndex >= this.JumpResponsibleRepetition.StartIndex && currentRepetition.EndIndex <= this.JumpResponsibleRepetition.EndIndex ) { this.resetRepetitionIterationCount(currentRepetition); } } } } private handleRepetitionsAtMeasureEnd(): void { for (let idx: number = 0, len: number = this.currentMeasure.LastRepetitionInstructions.length; idx < len; ++idx) { const repetitionInstruction: RepetitionInstruction = this.currentMeasure.LastRepetitionInstructions[idx]; const currentRepetition: Repetition = repetitionInstruction.parentRepetition; if (!currentRepetition) { continue; } if (currentRepetition.BackwardJumpInstructions.indexOf(repetitionInstruction) > -1) { if (this.getRepetitionIterationCount(currentRepetition) < currentRepetition.UserNumberOfRepetitions) { this.doBackJump(currentRepetition); this.backJumpOccurred = true; return; } } if (repetitionInstruction === currentRepetition.forwardJumpInstruction) { if ( this.JumpResponsibleRepetition !== undefined && currentRepetition !== this.JumpResponsibleRepetition && currentRepetition.StartIndex >= this.JumpResponsibleRepetition.StartIndex && currentRepetition.EndIndex <= this.JumpResponsibleRepetition.EndIndex ) { this.resetRepetitionIterationCount(currentRepetition); } const forwardJumpTargetMeasureIndex: number = currentRepetition.getForwardJumpTargetForIteration( this.getRepetitionIterationCount(currentRepetition) ); if (forwardJumpTargetMeasureIndex >= 0) { this.currentMeasureIndex = forwardJumpTargetMeasureIndex; this.currentMeasure = this.musicSheet.SourceMeasures[this.currentMeasureIndex]; this.currentVoiceEntryIndex = -1; this.jumpResponsibleRepetition = currentRepetition; this.forwardJumpOccurred = true; return; } if (forwardJumpTargetMeasureIndex === -2) { this.endReached = true; } } } this.currentMeasureIndex++; if (this.JumpResponsibleRepetition !== undefined && this.currentMeasureIndex > this.JumpResponsibleRepetition.EndIndex) { this.jumpResponsibleRepetition = undefined; } } private doBackJump(currentRepetition: Repetition): void { this.currentMeasureIndex = currentRepetition.getBackwardJumpTarget(); this.currentMeasure = this.musicSheet.SourceMeasures[this.currentMeasureIndex]; this.currentVoiceEntryIndex = -1; this.incrementRepetitionIterationCount(currentRepetition); this.jumpResponsibleRepetition = currentRepetition; } private activateCurrentRhythmInstructions(): void { if ( this.currentMeasure !== undefined && this.currentMeasure.FirstInstructionsStaffEntries.length > 0 && this.currentMeasure.FirstInstructionsStaffEntries[0] !== undefined ) { const instructions: AbstractNotationInstruction[] = this.currentMeasure.FirstInstructionsStaffEntries[0].Instructions; for (let idx: number = 0, len: number = instructions.length; idx < len; ++idx) { const abstractNotationInstruction: AbstractNotationInstruction = instructions[idx]; if (abstractNotationInstruction instanceof RhythmInstruction) { this.musicSheet.SheetPlaybackSetting.rhythm = (<RhythmInstruction>abstractNotationInstruction).Rhythm; } } } } private activateCurrentDynamicOrTempoInstructions(): void { const timeSortedDynamics: DynamicsContainer[] = this.musicSheet.TimestampSortedDynamicExpressionsList; while ( this.currentDynamicEntryIndex > 0 && ( this.currentDynamicEntryIndex >= timeSortedDynamics.length || this.CurrentSourceTimestamp.lte(timeSortedDynamics[this.currentDynamicEntryIndex].parMultiExpression().AbsoluteTimestamp) ) ) { this.currentDynamicEntryIndex--; } while ( this.currentDynamicEntryIndex < timeSortedDynamics.length && timeSortedDynamics[this.currentDynamicEntryIndex].parMultiExpression().AbsoluteTimestamp.lt(this.CurrentSourceTimestamp) ) { this.currentDynamicEntryIndex++; } while ( this.currentDynamicEntryIndex < timeSortedDynamics.length && timeSortedDynamics[this.currentDynamicEntryIndex].parMultiExpression().AbsoluteTimestamp.Equals(this.CurrentSourceTimestamp) ) { const dynamicsContainer: DynamicsContainer = timeSortedDynamics[this.currentDynamicEntryIndex]; const staffIndex: number = dynamicsContainer.staffNumber; if (this.CurrentSourceTimestamp.Equals(dynamicsContainer.parMultiExpression().AbsoluteTimestamp)) { if (dynamicsContainer.continuousDynamicExpression) { this.activeDynamicExpressions[staffIndex] = dynamicsContainer.continuousDynamicExpression; } else if (dynamicsContainer.instantaneousDynamicExpression) { this.activeDynamicExpressions[staffIndex] = dynamicsContainer.instantaneousDynamicExpression; } } this.currentDynamicEntryIndex++; } this.currentDynamicChangingExpressions = []; for (let staffIndex: number = 0; staffIndex < this.activeDynamicExpressions.length; staffIndex++) { if (this.activeDynamicExpressions[staffIndex]) { let startTime: Fraction; let endTime: Fraction; if (this.activeDynamicExpressions[staffIndex] instanceof ContinuousDynamicExpression) { const continuousDynamic: ContinuousDynamicExpression = <ContinuousDynamicExpression>this.activeDynamicExpressions[staffIndex]; startTime = continuousDynamic.StartMultiExpression.AbsoluteTimestamp; endTime = continuousDynamic.EndMultiExpression.AbsoluteTimestamp; if (startTime.lte(this.CurrentSourceTimestamp) && this.CurrentSourceTimestamp.lte(endTime)) { this.currentDynamicChangingExpressions.push(new DynamicsContainer(continuousDynamic, staffIndex)); } } else { const instantaneousDynamic: InstantaneousDynamicExpression = <InstantaneousDynamicExpression>this.activeDynamicExpressions[staffIndex]; if (this.CurrentSourceTimestamp.Equals(instantaneousDynamic.ParentMultiExpression.AbsoluteTimestamp)) { this.currentDynamicChangingExpressions.push(new DynamicsContainer(instantaneousDynamic, staffIndex)); } } } } const timeSortedTempoExpressions: MultiTempoExpression[] = this.musicSheet.TimestampSortedTempoExpressionsList; while (this.currentTempoEntryIndex > 0 && ( this.currentTempoEntryIndex >= timeSortedTempoExpressions.length || this.CurrentSourceTimestamp.lte(timeSortedTempoExpressions[this.currentTempoEntryIndex].AbsoluteTimestamp) )) { this.currentTempoEntryIndex--; } while ( this.currentTempoEntryIndex < timeSortedTempoExpressions.length && timeSortedTempoExpressions[this.currentTempoEntryIndex].AbsoluteTimestamp.lt(this.CurrentSourceTimestamp) ) { this.currentTempoEntryIndex++; } while ( this.currentTempoEntryIndex < timeSortedTempoExpressions.length && timeSortedTempoExpressions[this.currentTempoEntryIndex].AbsoluteTimestamp.Equals(this.CurrentSourceTimestamp) ) { this.activeTempoExpression = timeSortedTempoExpressions[this.currentTempoEntryIndex]; this.currentTempoEntryIndex++; } this.currentTempoChangingExpression = undefined; if (this.activeTempoExpression) { let endTime: Fraction = this.activeTempoExpression.AbsoluteTimestamp; if (this.activeTempoExpression.ContinuousTempo) { endTime = this.activeTempoExpression.ContinuousTempo.AbsoluteEndTimestamp; } if ( this.activeTempoExpression.AbsoluteTimestamp.lte(this.CurrentSourceTimestamp) || this.CurrentSourceTimestamp.lte(endTime) ) { this.currentTempoChangingExpression = this.activeTempoExpression; } } } private recursiveMove(): void { this.currentVoiceEntryIndex++; // TODO handle hidden part: skip hidden voice if requested by parameter if (this.currentVoiceEntryIndex === 0) { this.handleRepetitionsAtMeasureBegin(); this.activateCurrentRhythmInstructions(); } // everything fine, no complications if (this.currentVoiceEntryIndex >= 0 && this.currentVoiceEntryIndex < this.currentMeasure.VerticalSourceStaffEntryContainers.length) { const currentContainer: VerticalSourceStaffEntryContainer = this.currentMeasure.VerticalSourceStaffEntryContainers[this.currentVoiceEntryIndex]; this.currentVoiceEntries = this.getVoiceEntries(currentContainer); this.currentVerticalContainerInMeasureTimestamp = currentContainer.Timestamp; this.currentTimeStamp = Fraction.plus(this.currentMeasure.AbsoluteTimestamp, this.currentVerticalContainerInMeasureTimestamp); const selectionEnd: Fraction = this.musicSheet.SelectionEnd; // TODO handle selectionEnd undefined, can happen in Beethoven Ferne Geliebte if (selectionEnd && this.currentTimeStamp.gte(selectionEnd)) { this.endReached = true; } this.activateCurrentDynamicOrTempoInstructions(); return; } this.currentEnrolledMeasureTimestamp.Add(this.currentMeasure.Duration); this.handleRepetitionsAtMeasureEnd(); if (this.currentMeasureIndex >= 0 && this.currentMeasureIndex < this.musicSheet.SourceMeasures.length) { this.currentMeasure = this.musicSheet.SourceMeasures[this.currentMeasureIndex]; this.currentTimeStamp = Fraction.plus(this.currentMeasure.AbsoluteTimestamp, this.currentVerticalContainerInMeasureTimestamp); this.currentVoiceEntryIndex = -1; this.recursiveMove(); return; } // we reached the end this.currentVerticalContainerInMeasureTimestamp = new Fraction(); this.currentMeasure = undefined; this.currentVoiceEntries = undefined; this.endReached = true; } /** * helper function for moveToNextVisibleVoiceEntry and moveToPreviousVisibleVoiceEntry * Get all entries and check if there is at least one valid entry in the list * @param notesOnly */ private checkEntries(notesOnly: boolean): boolean { const tlist: VoiceEntry[] = this.CurrentVisibleVoiceEntries(); if (tlist.length > 0) { if (!notesOnly) { return true; } for (let idx: number = 0, len: number = tlist.length; idx < len; ++idx) { const entry: VoiceEntry = tlist[idx]; if (entry.Notes[0].Pitch) { return true; } } } return false; } private getVisibleEntries(entry: VoiceEntry, visibleEntries: VoiceEntry[]): void { if (entry.ParentVoice.Visible) { visibleEntries.push(entry); } } private getAudibleEntries(entry: VoiceEntry, audibleEntries: VoiceEntry[]): void { if (entry.ParentVoice.Audible) { audibleEntries.push(entry); } } private getScoreFollowingEntries(entry: VoiceEntry, followingEntries: VoiceEntry[]): void { if (entry.ParentVoice.Following && entry.ParentVoice.Parent.Following) { followingEntries.push(entry); } } private getVoiceEntries(container: VerticalSourceStaffEntryContainer): VoiceEntry[] { const entries: VoiceEntry[] = []; for (const sourceStaffEntry of container.StaffEntries) { if (!sourceStaffEntry) { continue; } for (const voiceEntry of sourceStaffEntry.VoiceEntries) { entries.push(voiceEntry); } } return entries; } }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type ArtworkInfoSectionTestsQueryVariables = {}; export type ArtworkInfoSectionTestsQueryResponse = { readonly commerceOrder: { readonly internalID: string; readonly " $fragmentRefs": FragmentRefs<"ArtworkInfoSection_artwork">; } | null; }; export type ArtworkInfoSectionTestsQuery = { readonly response: ArtworkInfoSectionTestsQueryResponse; readonly variables: ArtworkInfoSectionTestsQueryVariables; }; /* query ArtworkInfoSectionTestsQuery { commerceOrder(id: "some-id") { __typename internalID ...ArtworkInfoSection_artwork id } } fragment ArtworkInfoSection_artwork on CommerceOrder { __isCommerceOrder: __typename lineItems(first: 1) { edges { node { artwork { medium editionOf dimensions { in cm } date image { url(version: "square60") } title artistNames id } id } } } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "some-id" } ], v1 = { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v3 = { "enumValues": null, "nullable": false, "plural": false, "type": "String" }, v4 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }, v5 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "ArtworkInfoSectionTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "commerceOrder", "plural": false, "selections": [ (v1/*: any*/), { "args": null, "kind": "FragmentSpread", "name": "ArtworkInfoSection_artwork" } ], "storageKey": "commerceOrder(id:\"some-id\")" } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "ArtworkInfoSectionTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "commerceOrder", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, (v1/*: any*/), { "kind": "TypeDiscriminator", "abstractKey": "__isCommerceOrder" }, { "alias": null, "args": [ { "kind": "Literal", "name": "first", "value": 1 } ], "concreteType": "CommerceLineItemConnection", "kind": "LinkedField", "name": "lineItems", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItemEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItem", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "medium", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "editionOf", "storageKey": null }, { "alias": null, "args": null, "concreteType": "dimensions", "kind": "LinkedField", "name": "dimensions", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "in", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "cm", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "date", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "square60" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"square60\")" } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, (v2/*: any*/) ], "storageKey": null }, (v2/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": "lineItems(first:1)" }, (v2/*: any*/) ], "storageKey": "commerceOrder(id:\"some-id\")" } ] }, "params": { "id": "f9d791b0cf5a271c14bd41ef6c571e88", "metadata": { "relayTestingSelectionTypeInfo": { "commerceOrder": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceOrder" }, "commerceOrder.__isCommerceOrder": (v3/*: any*/), "commerceOrder.__typename": (v3/*: any*/), "commerceOrder.id": (v4/*: any*/), "commerceOrder.internalID": (v4/*: any*/), "commerceOrder.lineItems": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceLineItemConnection" }, "commerceOrder.lineItems.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "CommerceLineItemEdge" }, "commerceOrder.lineItems.edges.node": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceLineItem" }, "commerceOrder.lineItems.edges.node.artwork": { "enumValues": null, "nullable": true, "plural": false, "type": "Artwork" }, "commerceOrder.lineItems.edges.node.artwork.artistNames": (v5/*: any*/), "commerceOrder.lineItems.edges.node.artwork.date": (v5/*: any*/), "commerceOrder.lineItems.edges.node.artwork.dimensions": { "enumValues": null, "nullable": true, "plural": false, "type": "dimensions" }, "commerceOrder.lineItems.edges.node.artwork.dimensions.cm": (v5/*: any*/), "commerceOrder.lineItems.edges.node.artwork.dimensions.in": (v5/*: any*/), "commerceOrder.lineItems.edges.node.artwork.editionOf": (v5/*: any*/), "commerceOrder.lineItems.edges.node.artwork.id": (v4/*: any*/), "commerceOrder.lineItems.edges.node.artwork.image": { "enumValues": null, "nullable": true, "plural": false, "type": "Image" }, "commerceOrder.lineItems.edges.node.artwork.image.url": (v5/*: any*/), "commerceOrder.lineItems.edges.node.artwork.medium": (v5/*: any*/), "commerceOrder.lineItems.edges.node.artwork.title": (v5/*: any*/), "commerceOrder.lineItems.edges.node.id": (v4/*: any*/) } }, "name": "ArtworkInfoSectionTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '5d2179e9e1db79f20da2095123598bf9'; export default node;
the_stack
import { writeFileSync } from "node:fs"; import { mockAccountId, mockApiToken } from "./helpers/mock-account-id"; import { setMockResponse, unsetAllMocks } from "./helpers/mock-cfetch"; import { mockConsoleMethods } from "./helpers/mock-console"; import { runInTempDir } from "./helpers/run-in-tmp"; import { runWrangler } from "./helpers/run-wrangler"; import type { Project, Deployment } from "../pages"; import type { File, FormData } from "undici"; describe("pages", () => { runInTempDir(); const std = mockConsoleMethods(); function endEventLoop() { return new Promise((resolve) => setImmediate(resolve)); } it("should should display a list of available subcommands, for pages with no subcommand", async () => { await runWrangler("pages"); await endEventLoop(); expect(std.out).toMatchInlineSnapshot(` "wrangler pages ⚡️ Configure Cloudflare Pages Commands: wrangler pages dev [directory] [-- command] 🧑‍💻 Develop your full-stack Pages application locally wrangler pages project ⚡️ Interact with your Pages projects wrangler pages deployment 🚀 Interact with the deployments of a project wrangler pages publish [directory] 🆙 Publish a directory of static assets as a Pages deployment Flags: -c, --config Path to .toml configuration file [string] -h, --help Show help [boolean] -v, --version Show version number [boolean] 🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose" `); }); describe("beta message for subcommands", () => { it("should display for pages:dev", async () => { await expect( runWrangler("pages dev") ).rejects.toThrowErrorMatchingInlineSnapshot( `"Must specify a directory of static assets to serve or a command to run."` ); expect(std.out).toMatchInlineSnapshot(` "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new." `); }); it("should display for pages:functions:build", async () => { await expect(runWrangler("pages functions build")).rejects.toThrowError(); expect(std.out).toMatchInlineSnapshot(` "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new." `); }); }); describe("project list", () => { mockAccountId(); mockApiToken(); afterEach(() => { unsetAllMocks(); }); function mockListRequest(projects: unknown[]) { const requests = { count: 0 }; setMockResponse( "/accounts/:accountId/pages/projects", ([_url, accountId], init, query) => { requests.count++; expect(accountId).toEqual("some-account-id"); expect(query.get("per_page")).toEqual("10"); expect(query.get("page")).toEqual(`${requests.count}`); expect(init).toEqual({}); const pageSize = Number(query.get("per_page")); const page = Number(query.get("page")); return projects.slice((page - 1) * pageSize, page * pageSize); } ); return requests; } it("should make request to list projects", async () => { const projects: Project[] = [ { name: "dogs", subdomain: "docs.pages.dev", domains: ["dogs.pages.dev"], source: { type: "github", }, latest_deployment: { modified_on: "2021-11-17T14:52:26.133835Z", }, created_on: "2021-11-17T14:52:26.133835Z", production_branch: "main", }, { name: "cats", subdomain: "cats.pages.dev", domains: ["cats.pages.dev", "kitten.com"], latest_deployment: { modified_on: "2021-11-17T14:52:26.133835Z", }, created_on: "2021-11-17T14:52:26.133835Z", production_branch: "main", }, ]; const requests = mockListRequest(projects); await runWrangler("pages project list"); expect(requests.count).toBe(1); }); it("should make multiple requests for paginated results", async () => { const projects: Project[] = []; for (let i = 0; i < 15; i++) { projects.push({ name: "dogs" + i, subdomain: i + "dogs.pages.dev", domains: [i + "dogs.pages.dev"], source: { type: "github", }, latest_deployment: { modified_on: "2021-11-17T14:52:26.133835Z", }, created_on: "2021-11-17T14:52:26.133835Z", production_branch: "main", }); } const requests = mockListRequest(projects); await runWrangler("pages project list"); expect(requests.count).toEqual(2); }); }); describe("project create", () => { mockAccountId(); mockApiToken(); afterEach(() => { unsetAllMocks(); }); it("should create a project with a production branch", async () => { setMockResponse( "/accounts/:accountId/pages/projects", ([_url, accountId], init) => { expect(accountId).toEqual("some-account-id"); expect(init.method).toEqual("POST"); const body = JSON.parse(init.body as string); expect(body).toEqual({ name: "a-new-project", production_branch: "main", }); return { name: "a-new-project", subdomain: "a-new-project.pages.dev", production_branch: "main", }; } ); await runWrangler( "pages project create a-new-project --production-branch=main" ); expect(std.out).toMatchInlineSnapshot(` "✨ Successfully created the 'a-new-project' project. It will be available at https://a-new-project.pages.dev/ once you create your first deployment. To deploy a folder of assets, run 'wrangler pages publish [directory]'." `); }); }); describe("deployment list", () => { mockAccountId(); mockApiToken(); afterEach(() => { unsetAllMocks(); }); function mockListRequest(deployments: unknown[]) { const requests = { count: 0 }; setMockResponse( "/accounts/:accountId/pages/projects/:project/deployments", ([_url, accountId, project]) => { requests.count++; expect(project).toEqual("images"); expect(accountId).toEqual("some-account-id"); return deployments; } ); return requests; } it("should make request to list deployments", async () => { const deployments: Deployment[] = [ { id: "87bbc8fe-16be-45cd-81e0-63d722e82cdf", url: "https://87bbc8fe.images.pages.dev", environment: "preview", latest_stage: { ended_on: "2021-11-17T14:52:26.133835Z", status: "success", }, deployment_trigger: { metadata: { branch: "main", commit_hash: "c7649364c4cb32ad4f65b530b9424e8be5bec9d6", }, }, project_name: "images", }, ]; const requests = mockListRequest(deployments); await runWrangler("pages deployment list --project-name=images"); expect(requests.count).toBe(1); }); }); describe("deployment create", () => { let actualProcessEnvCI: string | undefined; mockAccountId(); mockApiToken(); runInTempDir(); beforeEach(() => { actualProcessEnvCI = process.env.CI; process.env.CI = "true"; }); afterEach(() => { unsetAllMocks(); process.env.CI = actualProcessEnvCI; }); it("should be aliased with 'wrangler pages publish'", async () => { await runWrangler("pages publish --help"); await endEventLoop(); expect(std.out).toMatchInlineSnapshot(` "wrangler pages publish [directory] 🆙 Publish a directory of static assets as a Pages deployment Positionals: directory The directory of static files to upload [string] Flags: -c, --config Path to .toml configuration file [string] -h, --help Show help [boolean] -v, --version Show version number [boolean] Options: --project-name The name of the project you want to deploy to [string] --branch The name of the branch you want to deploy to [string] --commit-hash The SHA to attach to this deployment [string] --commit-message The commit message to attach to this deployment [string] --commit-dirty Whether or not the workspace should be considered dirty for this deployment [boolean] 🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose" `); }); it("should upload a directory of files", async () => { writeFileSync("logo.png", "foobar"); setMockResponse( "/accounts/:accountId/pages/projects/foo/file", async ([_url, accountId], init) => { expect(accountId).toEqual("some-account-id"); expect(init.method).toEqual("POST"); const body = init.body as FormData; const logoPNGFile = body.get("file") as File; expect(await logoPNGFile.text()).toEqual("foobar"); expect(logoPNGFile.name).toEqual("logo.png"); return { id: "2082190357cfd3617ccfe04f340c6247", }; } ); setMockResponse( "/accounts/:accountId/pages/projects/foo/deployments", async ([_url, accountId], init) => { expect(accountId).toEqual("some-account-id"); expect(init.method).toEqual("POST"); const body = init.body as FormData; const manifest = JSON.parse(body.get("manifest") as string); expect(manifest).toMatchInlineSnapshot(` Object { "/logo.png": "2082190357cfd3617ccfe04f340c6247", } `); return { url: "https://abcxyz.foo.pages.dev/", }; } ); await runWrangler("pages publish . --project-name=foo"); // TODO: Unmounting somehow loses this output // expect(std.out).toMatchInlineSnapshot(` // "✨ Success! Uploaded 1 files (TIMINGS) // ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/" // `); }); }); });
the_stack
import { isLaunchInsideApp, setTransparentBackground, showActionSheet, showModal, showNotification, showPreviewOptions, useStorage, request, } from '@app/lib/help' import {FC} from 'react' /**榜单信息*/ interface TopInfo { /**榜单名字*/ title: string /**榜单链接*/ href: string } /**文章信息*/ interface ArticleInfo { /**文章标题*/ title: string /**原文地址*/ href: string /**文章热度*/ hot: string } /**页面信息*/ interface PageInfo { /**页面标题*/ title: string /**该榜单的 logo */ logo: string /**文章列表*/ articleList: ArticleInfo[] /**cookie*/ cookie: string | null /**js执行的错误信息*/ err: Error } /**内置榜单别名,可在桌面小部件编辑传入别名*/ const topList: TopInfo[] = [ { title: '知乎', href: 'https://tophub.today/n/mproPpoq6O', }, { title: '微博', href: 'https://tophub.today/n/KqndgxeLl9', }, { title: '微信', href: 'https://tophub.today/n/WnBe01o371', }, { title: '澎湃', href: 'https://tophub.today/n/wWmoO5Rd4E', }, { title: '百度', href: 'https://tophub.today/n/Jb0vmloB1G', }, { title: '知乎日报', href: 'https://tophub.today/n/KMZd7VOvrO', }, { title: '历史上的今天', href: 'https://tophub.today/n/KMZd7X3erO', }, { title: '神马搜索', href: 'https://tophub.today/n/n6YoVqDeZa', }, { title: '搜狗', href: 'https://tophub.today/n/NaEdZndrOM', }, { title: '今日头条', href: 'https://tophub.today/n/x9ozB4KoXb', }, { title: '360搜索', href: 'https://tophub.today/n/KMZd7x6erO', }, { title: '36氪', href: 'https://tophub.today/n/Q1Vd5Ko85R', }, { title: '好奇心日报', href: 'https://tophub.today/n/Y3QeLGAd7k', }, { title: '少数派', href: 'https://tophub.today/n/Y2KeDGQdNP', }, { title: '果壳', href: 'https://tophub.today/n/20MdK2vw1q', }, { title: '虎嗅网', href: 'https://tophub.today/n/5VaobgvAj1', }, { title: 'IT之家', href: 'https://tophub.today/n/74Kvx59dkx', }, { title: '爱范儿', href: 'https://tophub.today/n/74KvxK7okx', }, { title: 'GitHub', href: 'https://tophub.today/n/rYqoXQ8vOD', }, { title: '威锋网', href: 'https://tophub.today/n/n4qv90roaK', }, { title: 'CSDN', href: 'https://tophub.today/n/n3moBVoN5O', }, { title: '掘金', href: 'https://tophub.today/n/QaqeEaVe9R', }, { title: '哔哩哔哩', href: 'https://tophub.today/n/74KvxwokxM', }, { title: '抖音', href: 'https://tophub.today/n/DpQvNABoNE', }, { title: '吾爱破解', href: 'https://tophub.today/n/NKGoRAzel6', }, { title: '百度贴吧', href: 'https://tophub.today/n/Om4ejxvxEN', }, { title: '天涯', href: 'https://tophub.today/n/Jb0vmmlvB1', }, { title: 'V2EX', href: 'https://tophub.today/n/wWmoORe4EO', }, { title: '虎扑社区', href: 'https://tophub.today/n/G47o8weMmN', }, { title: '汽车之家', href: 'https://tophub.today/n/YqoXQGXvOD', }, ] const {setStorage, getStorage} = useStorage('newsTop-xiaoming') /**默认背景颜色*/ const defaultBgColor = Color.dynamic(new Color('#ffffff', 1), new Color('#000000', 1)) /**文字颜色*/ const textColor = getStorage<string>('textColor') || Color.dynamic(new Color('#000000', 1), new Color('#dddddd', 1)) /**透明背景*/ const transparentBg: Image | Color = getStorage<Image>('transparentBg') || defaultBgColor /**背景颜色或背景图链接*/ const boxBg = getStorage<string>('boxBg') || defaultBgColor /** * 文章组件 * @param param.article 文章 * @param param.sort 文章序号 */ const Article: FC<{article: ArticleInfo; sort: number}> = ({article, sort}) => { return ( <wstack flexDirection="column" href={article.href}> {sort > 1 && <wspacer></wspacer>} <wstack verticalAlign="center"> <wtext font={Font.heavySystemFont(14)} textColor={textColor} opacity={0.7}> {sort} </wtext> <wspacer length={8}></wspacer> <wtext maxLine={1} font={Font.lightSystemFont(14)} textColor={textColor}> {article.title} </wtext> <wspacer></wspacer> <wtext maxLine={1} font={Font.lightSystemFont(12)} opacity={0.6} textColor={textColor}> {article.hot} </wtext> </wstack> </wstack> ) } class NewsTop { async init() { if (isLaunchInsideApp()) { return await this.showMenu() } const widget = (await this.render()) as ListWidget Script.setWidget(widget) Script.complete() } //渲染组件 async render(): Promise<unknown> { if (isLaunchInsideApp()) { await showNotification({title: '稍等片刻', body: '小部件渲染中...', sound: 'alert'}) } // 获取榜单url const topUrl = this.getTopUrl() // 获取榜单数据 const {title, logo, articleList} = await this.getNewsTop(topUrl) // 多久(毫秒)更新一次小部件(默认1小时) const updateInterval = 1 * 60 * 60 * 1000 // 渲染尺寸 const size = config.widgetFamily const widgetBoxProps = size === 'small' ? {href: articleList[0] && articleList[0].href} : {} return ( <wbox padding={[0, 0, 0, 0]} updateDate={new Date(Date.now() + updateInterval)} background={typeof boxBg === 'string' && boxBg.match('透明背景') ? transparentBg : boxBg} {...widgetBoxProps} > <wstack flexDirection="column" padding={[0, 16, 0, 16]}> <wspacer></wspacer> <wspacer></wspacer> {/* 标题和logo */} <wstack verticalAlign="center"> <wimage src={logo} width={20} height={20} borderRadius={4}></wimage> <wspacer length={8}></wspacer> <wtext opacity={0.7} font={Font.boldSystemFont(16)} textColor={textColor}> {title}排行榜 </wtext> </wstack> <wspacer></wspacer> <wspacer></wspacer> {/* 内容 */} {size === 'small' && this.renderSmall(articleList)} {size === 'medium' && this.renderMedium(articleList)} {size === 'large' && this.renderLarge(articleList)} </wstack> </wbox> ) } // 渲染小尺寸 renderSmall(articleList: ArticleInfo[]) { const article = articleList[0] return ( <wstack flexDirection="column"> <wtext font={Font.lightSystemFont(14)} textColor={textColor}> {article.title} </wtext> <wspacer></wspacer> <wstack> <wspacer></wspacer> <wtext maxLine={1} font={Font.lightSystemFont(12)} opacity={0.6} textColor={textColor}> {article.hot} </wtext> </wstack> <wspacer></wspacer> </wstack> ) } // 渲染中尺寸 renderMedium(articleList: ArticleInfo[]) { const _articleList = articleList.slice(0, 4) return ( <> <wstack flexDirection="column"> {_articleList.map((article, index) => ( <Article article={article} sort={index + 1}></Article> ))} </wstack> <wspacer></wspacer> <wspacer></wspacer> </> ) } // 渲染大尺寸 renderLarge(articleList: ArticleInfo[]) { const _articleList = articleList.slice(0, 10) return ( <> <wstack flexDirection="column"> {_articleList.map((article, index) => ( <Article article={article} sort={index + 1}></Article> ))} </wstack> <wspacer></wspacer> <wspacer></wspacer> </> ) } // 显示菜单 async showMenu() { const selectIndex = await showActionSheet({ title: '菜单', itemList: ['使用其他排行榜', '设置颜色', '设置透明背景', '预览组件', '优化体验'], }) switch (selectIndex) { case 0: await showModal({ title: '使用其他排行榜方法', content: `把小部件添加到桌面后,长按编辑小部件,在 Parameter 栏输入以下任一关键词即可:\n\n${topList .map(top => top.title) .join('、')}`, }) break case 1: const {texts, cancel} = await showModal({ title: '设置全局背景和颜色', content: '如果为空,则还原默认', inputItems: [ { text: getStorage<string>('boxBg') || '', placeholder: '全局背景:可以是颜色、图链接', }, { text: getStorage<string>('textColor') || '', placeholder: '这里填文字颜色', }, ], }) if (cancel) return setStorage('boxBg', texts[0]) setStorage('textColor', texts[1]) await showNotification({title: '设置完成', sound: 'default'}) break case 2: const img: Image | null = (await setTransparentBackground()) || null if (img) { setStorage('transparentBg', img) setStorage('boxBg', '透明背景') await showNotification({title: '设置透明背景成功', sound: 'default'}) } break case 3: await showPreviewOptions(this.render.bind(this)) break case 4: const {cancel: cancelLogin} = await showModal({ title: '优化体验建议', content: '本组件数据来源于 tophub.today 这个网站,未登录状态获取的文章链接不是最终链接,有二次跳转,如果想获取真实链接,建议在此登录该网站。\n\n登录完成后,自行关闭网页', confirmText: '去登录', }) if (cancelLogin) return const loginUrl = 'https://tophub.today/login' const html = await new Request(loginUrl).loadString() await WebView.loadHTML(html, loginUrl, undefined, true) break } } // 获取热榜数据 async getNewsTop(url: string): Promise<PageInfo> { const cookieHeader: Record<string, string> = isLaunchInsideApp() ? {} : {cookie: getStorage<string>('cookie') || ''} const html = ( await request<string>({ url, dataType: 'text', header: { 'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1', ...cookieHeader, }, }) ).data || '' const webview = new WebView() await webview.loadHTML(html, url) await webview.waitForLoad() const {title = '今日热榜', logo = 'flame.fill', articleList = [], cookie, err} = (await webview.evaluateJavaScript( ` let title = '' let logo = '' let articleList = [] let cookie = document.cookie let err = '' try { title = document.title.split(' ')[0] logo = document.querySelector('.custom-info-content > img').src articleList = Array.from(document.querySelector('.divider > .weui-panel > .weui-panel__bd').querySelectorAll('a')).map(a => { return { title: a.querySelector('h4').innerText.replace(/\\d+?[、]\\s*/, ''), href: a.href, hot: a.querySelector('h4+p').innerText } }) } catch(err) { err = err } Object.assign({}, {title, logo, articleList, cookie, err}) `, )) as PageInfo err && console.warn(`热榜获取出错: ${err}`) if (isLaunchInsideApp() && cookie) setStorage('cookie', cookie) return {title, logo, articleList, cookie, err} } // 获取要显示的榜单 url getTopUrl(): string { // 默认为知乎榜单 const defaultUrl = 'https://tophub.today/n/mproPpoq6O' // 从小部件编辑处获取关键词或链接 const keyword = (args.widgetParameter as string) || defaultUrl if (this.isUrl(keyword)) return keyword const topInfo = topList.find(item => item.title.toLowerCase() === keyword.toLowerCase()) if (topInfo) return topInfo.href return defaultUrl } /** * 判断一个值是否为网络连接 * @param value 值 */ isUrl(value: string): boolean { const reg = /^(http|https)\:\/\/[\w\W]+/ return reg.test(value) } } EndAwait(() => new NewsTop().init())
the_stack
/// <reference types="jquery"/> /// <reference types="jqueryui"/> declare namespace JQueryUI { interface UI { dynatree: DynatreeNamespace } } interface JQuery { dynatree(options?: DynatreeOptions): DynaTree; dynatree(option?: string, ...rest: any[]): any; } interface DynaTree { activateKey(key: string): DynaTreeNode; count(): number; enable(): void; disable(): void; enableUpdate(enable: boolean): void; getActiveNode(): DynaTreeNode; getNodeByKey(key: string): DynaTreeNode; getPersistData(): any; getRoot(): DynaTreeNode; getSelectedNodes(stopOnParents: boolean): DynaTreeNode[]; initialize(): void; isInitializing(): boolean; isReloading(): boolean; isUserEvent(): boolean; loadKeyPath(keyPath: string, callback: (node: DynaTreeNode, status: string) =>void ): void; reactivate(setFocus: boolean): void; redraw(): void; reload(): void; renderInvisibleNodes(): void; selectKey(key: string, flag: string): DynaTreeNode; serializeArray(stopOnParents: boolean): any[]; toDict(includeRoot?: boolean): any; visit(fn: (node: DynaTreeNode) =>boolean, includeRoot?: boolean): void; } interface DynaTreeNode { data: DynaTreeDataModel; activate(): void; activateSilently(): void; addChild(nodeData: DynaTreeDataModel, beforeNode?: DynaTreeNode): void; addChild(nodeData: DynaTreeDataModel[], beforeNode?: DynaTreeNode): void; appendAjax(ajaxOptions: JQueryAjaxSettings): void; countChildren(): number; deactivate(): void; expand(flag: boolean): void; focus(): void; getChildren(): DynaTreeNode[]; getEventTargetType(event: Event): string; getLevel(): number; getNextSibling(): DynaTreeNode; getParent(): DynaTreeNode; getPrevSibling(): DynaTreeNode; hasChildren(): boolean; isActive(): boolean; isChildOf(otherNode: DynaTreeNode): boolean; isDescendantOf(otherNode: DynaTreeNode): boolean; isExpanded(): boolean; isFirstSibling(): boolean; isFocused(): boolean; isLastSibling(): boolean; isLazy(): boolean; isLoading(): boolean; isSelected(): boolean; isStatusNode(): boolean; isVisible(): boolean; makeVisible(): boolean; move(targetNode: DynaTreeNode, mode: string): boolean; reload(force: boolean): void; reloadChildren(callback?: (node: DynaTreeNode, isOk: boolean) => any): void; remove(): void; removeChildren(): void; render(useEffects: boolean, includeInvisible: boolean): void; resetLazy(): void; scheduleAction(mode: string, ms: number): void; select(flag: boolean): void; setLazyNodeStatus(status: number): void; setTitle(title: string): void; sortChildren(cmp?: (a: DynaTreeNode, b: DynaTreeNode) =>number, deep?: boolean): void; toDict(recursive: boolean, callback?: (node: any) =>any): any; toggleExpand(): void; toggleSelect(): void; visit(fn: (node: DynaTreeNode) =>boolean, includeSelf: boolean): void; visitParents(fn: (node: DynaTreeNode) =>boolean, includeSelf: boolean): void; } interface DynatreeOptions { title?: string | undefined; // Tree's name (only used for debug outpu) minExpandLevel?: number | undefined; // 1: root node is not collapsible imagePath?: string | undefined; // Path to a folder containing icons. Defaults to 'skin/' subdirectory. children?: DynaTreeDataModel[] | undefined; // Init tree structure from this object array. initId?: string | undefined; // Init tree structure from a <ul> element with this ID. initAjax?: JQueryAjaxSettings | undefined; // Ajax options used to initialize the tree strucuture. autoFocus?: boolean | undefined; // Set focus to first child, when expanding or lazy-loading. keyboard?: boolean | undefined; // Support keyboard navigation. persist?: boolean | undefined; // Persist expand-status to a cookie autoCollapse?: boolean | undefined; // Automatically collapse all siblings, when a node is expanded. clickFolderMode?: number | undefined; // 1:activate, 2:expand, 3:activate and expand activeVisible?: boolean | undefined; // Make sure, active nodes are visible (expanded). checkbox?: boolean | undefined; // Show checkboxes. selectMode?: number | undefined; // 1:single, 2:multi, 3:multi-hier fx?: any; // Animations, e.g. null or { height: "toggle", duration: 200 } noLink?: boolean | undefined; // Use <span> instead of <a> tags for all nodes debugLevel?: number | undefined; // 0:quiet, 1:normal, 2:debug generateIds?: boolean | undefined; // Generate id attributes like <span id='dynatree-id-KEY'> idPrefix?: string | undefined; // Used to generate node id's like <span id="dynatree-id-<key>">. keyPathSeparator?: string | undefined; // Used by node.getKeyPath() and tree.loadKeyPath(). cookieId?: string | undefined; // Choose a more unique name, to allow multiple trees. dnd?: DynaTreeDNDOptions | undefined; // Drag'n'drop support ajaxDefaults?: DynaTreeAjaxOptions | undefined;// Used by initAjax option strings?: DynaTreeStringsOptions | undefined; cookie?: DynaTreeCookieOptions | undefined; // Class names used, when rendering the HTML markup. // Note: if only single entries are passed for options.classNames, all other // values are still set to default. classNames?: DynatreeClassNamesOptions | undefined; // Low level event handlers: onEvent(dtnode, event): return false, to stop default processing onClick?: ((dtnode: DynaTreeNode, event: Event) =>boolean) | undefined; // null: generate focus, expand, activate, select events. onDblClick?: ((dtnode: DynaTreeNode, event: Event) =>boolean) | undefined; // (No default actions.) onKeydown?: ((dtnode: DynaTreeNode, event: Event) =>boolean) | undefined; // null: generate keyboard navigation (focus, expand, activate). onKeypress?: ((dtnode: DynaTreeNode, event: Event) =>boolean) | undefined; // (No default actions.) onFocus?: ((dtnode: DynaTreeNode, event: Event) =>boolean) | undefined; // null: set focus to node. onBlur?: ((dtnode: DynaTreeNode, event: Event) =>boolean) | undefined; // null: remove focus from node. // Pre-event handlers onQueryEvent(flag, dtnode): return false, to stop processing onQueryActivate?: ((flag: string, dtnode: DynaTreeNode) =>void) | undefined; // Callback(flag, dtnode) before a node is (de)activated. onQuerySelect?: ((flag: string, dtnode: DynaTreeNode) =>void) | undefined;// Callback(flag, dtnode) before a node is (de)selected. onQueryExpand?: ((flag: string, dtnode: DynaTreeNode) =>void) | undefined;// Callback(flag, dtnode) before a node is expanded/collpsed. // High level event handlers onPostInit?: ((isReloading: boolean, isError: boolean) =>void) | undefined;// Callback(isReloading, isError) when tree was (re)loaded. onActivate?: ((dtnode: DynaTreeNode) =>void) | undefined; // Callback(dtnode) when a node is activated. onDeactivate?: ((dtnode: DynaTreeNode) =>void) | undefined; // Callback(dtnode) when a node is deactivated. onSelect?: ((flag: string, dtnode: DynaTreeNode) =>void) | undefined; // Callback(flag, dtnode) when a node is (de)selected. onExpand?: ((flag: string, dtnode: DynaTreeNode) =>void) | undefined; // Callback(flag, dtnode) when a node is expanded/collapsed. onLazyRead?: ((dtnode: DynaTreeNode) =>void) | undefined; // Callback(dtnode) when a lazy node is expanded for the first time. onCustomRender?: ((dtnode: DynaTreeNode) =>void) | undefined; // Callback(dtnode) before a node is rendered. Return a HTML string to override. onCreate?: ((dtnode: DynaTreeNode, nodeSpan: any) =>void) | undefined; // Callback(dtnode, nodeSpan) after a node was rendered for the first time. onRender?: ((dtnode: DynaTreeNode, nodeSpan: any) =>void) | undefined; // Callback(dtnode, nodeSpan) after a node was rendered. postProcess?: ((data: any, dataType: any) =>void) | undefined; // Callback(data, dataType) before an Ajax result is passed to dynatree. } interface DynaTreeDataModel { title: string; // (required) Displayed name of the node (html is allowed here) key?: string | undefined; // May be used with activate(), select(), find(), ... isFolder?: boolean | undefined; // Use a folder icon. Also the node is expandable but not selectable. isLazy?: boolean | undefined; // Call onLazyRead(), when the node is expanded for the first time to allow for delayed creation of children. tooltip?: string | undefined; // Show this popup text. href?: string | undefined; // Added to the generated <a> tag. icon?: string | undefined; // Use a custom image (filename relative to tree.options.imagePath). 'null' for default icon, 'false' for no icon. addClass?: string | undefined; // Class name added to the node's span tag. noLink?: boolean | undefined; // Use <span> instead of <a> tag for this node activate?: boolean | undefined; // Initial active status. focus?: boolean | undefined; // Initial focused status. expand?: boolean | undefined; // Initial expanded status. select?: boolean | undefined; // Initial selected status. hideCheckbox?: boolean | undefined; // Suppress checkbox display for this node. unselectable?: boolean | undefined; // Prevent selection. // The following attributes are only valid if passed to some functions: children?: DynaTreeDataModel[] | undefined; // Array of child nodes. // NOTE: we can also add custom attributes here. // This may then also be used in the onActivate(), onSelect() or onLazyTree() callbacks. } interface DynaTreeDNDOptions { autoExpandMS?: number | undefined; // Expand nodes after n milliseconds of hovering. preventVoidMoves?: boolean | undefined; // Prevent dropping nodes 'before self', etc. revert: boolean; // true: slide helper back to source if drop is rejected // Make tree nodes draggable: onDragStart?: ((sourceNode: any) =>void) | undefined; // Callback(sourceNode), return true, to enable dnd onDragStop?: ((sourceNode: any) =>void) | undefined; // Callback(sourceNode) // Make tree nodes accept draggables onDragEnter?: ((targetNode: any, sourceNode: any) =>void) | undefined; // Callback(targetNode, sourceNode) onDragOver?: ((targetNode: any, sourceNode: any, hitMode: string) =>void) | undefined; // Callback(targetNode, sourceNode, hitMode) onDrop?: ((targetNode: any, sourceNode: any, hitMode: string) =>void) | undefined; // Callback(targetNode, sourceNode, hitMode) onDragLeave?: ((targetNode: any, sourceNode: any) =>void) | undefined; // Callback(targetNode, sourceNode) } interface DynaTreeCookieOptions { expires: any; } interface DynaTreeStringsOptions { loading?: string | undefined; loadError?: string | undefined; } interface DynaTreeAjaxOptions { cache?: boolean | undefined; // false: Append random '_' argument to the request url to prevent caching. timeout?: number | undefined; // >0: Make sure we get an ajax error for invalid URLs dataType?: string | undefined; // Expect json format and pass json object to callbacks. } interface DynatreeClassNamesOptions { container?: string | undefined; node?: string | undefined; folder?: string | undefined; empty?: string | undefined; vline?: string | undefined; expander?: string | undefined; connector?: string | undefined; checkbox?: string | undefined; nodeIcon?: string | undefined; title?: string | undefined; noConnector?: string | undefined; nodeError?: string | undefined; nodeWait?: string | undefined; hidden?: string | undefined; combinedExpanderPrefix?: string | undefined; combinedIconPrefix?: string | undefined; hasChildren?: string | undefined; active?: string | undefined; selected?: string | undefined; expanded?: string | undefined; lazy?: string | undefined; focused?: string | undefined; partsel?: string | undefined; lastsib?: string | undefined; } interface DynatreeNamespace { getNode(element: HTMLElement): DynaTreeNode; getPersistData(cookieId: string, cookieOpts: DynaTreeCookieOptions): any; version: number; }
the_stack
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'; import {AutoComplete, Input, Modal, Tag} from 'antd'; import {ExclamationCircleOutlined} from '@ant-design/icons'; import styled from 'styled-components'; import {ResourceFilterType} from '@models/appstate'; import {useAppDispatch, useAppSelector} from '@redux/hooks'; import {resetResourceFilter, selectK8sResource, updateResourceFilter} from '@redux/reducers/main'; import {closeQuickSearchActionsPopup} from '@redux/reducers/ui'; import {AppDispatch} from '@redux/store'; import {useNamespaces} from '@hooks/useNamespaces'; import {isResourcePassingFilter} from '@utils/resources'; import Colors from '@styles/Colors'; import {ResourceKindHandlers} from '@src/kindhandlers'; import LabelMapper from './LabelMapper'; const StyledModal = styled(Modal)` & .ant-input { height: 34px; } & .ant-input:focus { box-shadow: none !important; } & .ant-input:hover + .ant-input-group-addon { border: 1px solid #165996 !important; } & .ant-input-search-button { border: 0px !important; } & .ant-input-group-addon { border: 1px solid rgb(67, 67, 67) !important; } & .ant-select-focused .ant-input-group-addon { border: 1px solid #165996 !important; } `; const KnownResourceKinds = ResourceKindHandlers.map(kindHandler => kindHandler.kind); const applyFilterWithConfirm = ( option: string, type: 'namespace' | 'kind', resourceFilter: ResourceFilterType, dispatch: AppDispatch ) => { let title = `Are you sure you want apply ${option} ${type} filter? It will replace the currently applied ${resourceFilter[type]} ${type} filter.`; Modal.confirm({ title, icon: <ExclamationCircleOutlined />, onOk() { return new Promise(resolve => { dispatch(updateResourceFilter({...resourceFilter, [type]: option})); dispatch(closeQuickSearchActionsPopup()); resolve({}); }); }, onCancel() { document.getElementById('quick_search_input')?.focus(); }, }); }; const selectK8sResourceWithConfirm = (resourceId: string, resourceName: string, dispatch: AppDispatch) => { let title = `Are you sure you want to select ${resourceName}? It will reset the currently applied filters.`; Modal.confirm({ title, icon: <ExclamationCircleOutlined />, onOk() { return new Promise(resolve => { dispatch(resetResourceFilter()); dispatch(selectK8sResource({resourceId})); dispatch(closeQuickSearchActionsPopup()); resolve({}); }); }, onCancel() { document.getElementById('quick_search_input')?.focus(); }, }); }; const QuickSearchActionsV3: React.FC = () => { const dispatch = useAppDispatch(); const isOpen = useAppSelector(state => state.ui.quickSearchActionsPopup.isOpen); const resourceFilter = useAppSelector(state => state.main.resourceFilter); const resourceMap = useAppSelector(state => state.main.resourceMap); const selectedResourceId = useAppSelector(state => state.main.selectedResourceId); const [namespaces] = useNamespaces({extra: ['default']}); const [searchingValue, setSearchingValue] = useState<string>(''); const allResourceKinds = useMemo(() => { return [ ...new Set([ ...KnownResourceKinds, ...Object.values(resourceMap) .filter(r => !KnownResourceKinds.includes(r.kind)) .map(r => r.kind), ]), ].sort(); }, [resourceMap]); const filteredResources = useMemo( () => Object.fromEntries( Object.entries(resourceMap).filter(([, resource]) => isResourcePassingFilter(resource, resourceFilter)) ), [resourceFilter, resourceMap] ); const applyOption = useCallback( (type: string, option: string) => { if (type === 'namespace' || type === 'kind') { if (resourceFilter[type]) { if (resourceFilter[type] !== option) { applyFilterWithConfirm(option, type, resourceFilter, dispatch); } } else { dispatch(updateResourceFilter({...resourceFilter, [type]: option})); dispatch(closeQuickSearchActionsPopup()); } } else if (type === 'resource') { if (!filteredResources[option]) { selectK8sResourceWithConfirm(option, resourceMap[option].name, dispatch); } else if (selectedResourceId !== option) { dispatch(selectK8sResource({resourceId: option})); dispatch(closeQuickSearchActionsPopup()); } } }, [dispatch, filteredResources, resourceFilter, resourceMap, selectedResourceId] ); const matchingCharactersLabel = useCallback( (label: string, type: string) => { const inputValue = searchingValue.replaceAll('\\', '\\\\'); const regex = new RegExp(`(${inputValue})`, 'gi'); const parts = label.split(regex); return parts.map((part, index) => { const key = `${type}-${label}-${index}`; if (part) { if (part.toLowerCase() === searchingValue) { return ( <span key={key} style={{color: Colors.cyan7}}> {part} </span> ); } return part; } return ''; }); }, [searchingValue] ); const options = useMemo(() => { const namespaceOptions = namespaces .sort((a, b) => a.localeCompare(b)) .reduce((filteredOpt, ns) => { if (ns.toLowerCase().includes(searchingValue.toLowerCase())) { const optionLabel = <span>{matchingCharactersLabel(ns, 'namespace')}</span>; filteredOpt.push({value: `namespace:${ns}`, label: optionLabel}); } return filteredOpt; }, [] as {value: string; label: JSX.Element}[]); const kindOptions = allResourceKinds.reduce((filteredOpt, kind) => { if (kind.toLowerCase().includes(searchingValue.toLowerCase())) { const optionLabel = <span>{matchingCharactersLabel(kind, 'kind')}</span>; filteredOpt.push({value: `kind:${kind}`, label: optionLabel}); } return filteredOpt; }, [] as {value: string; label: JSX.Element}[]); const resourceOptions = Object.entries(resourceMap) .sort((a, b) => { const resA = a[1]; const resB = b[1]; if (resA.kind !== resB.kind) { return resA.kind.localeCompare(resB.kind); } if (resA.namespace && !resB.namespace) { return -1; } if (!resA.namespace && resB.namespace) { return 1; } if (resA.namespace && resB.namespace && resA.namespace !== resB.namespace) { return resA.namespace.localeCompare(resB.namespace); } return resA.name.localeCompare(resB.name); }) .reduce((filteredOpt, resourceEntry) => { const resourceName = resourceEntry[1].name; if (!resourceName.startsWith('Patch:') && resourceName.toLowerCase().includes(searchingValue.toLowerCase())) { const optionLabel = ( <div> {resourceEntry[1].namespace && <Tag>{resourceEntry[1].namespace}</Tag>} <span>{matchingCharactersLabel(resourceName, 'resource')}</span> {resourceEntry[1].kind && ( <span style={{fontStyle: 'italic', marginLeft: '8px', color: Colors.grey7}}> {resourceEntry[1].kind} </span> )} </div> ); filteredOpt.push({value: `resource:${resourceEntry[0]}`, label: optionLabel}); } return filteredOpt; }, [] as {value: string; label: JSX.Element}[]); return [ {label: LabelMapper['kind'], options: kindOptions}, {label: LabelMapper['namespace'], options: namespaceOptions}, {label: LabelMapper['resource'], options: resourceOptions}, ]; }, [allResourceKinds, matchingCharactersLabel, namespaces, resourceMap, searchingValue]); const previousInputListFirstChild = useRef<any>(null); useEffect(() => { if (isOpen) { setSearchingValue(''); } }, [isOpen]); return ( <StyledModal bodyStyle={{padding: '0px'}} closable={false} destroyOnClose footer={null} visible={isOpen} onCancel={() => dispatch(closeQuickSearchActionsPopup())} > <AutoComplete id="quick_search_input" autoFocus defaultActiveFirstOption listHeight={500} notFoundContent="Kind, namespace or resource not found." onDropdownVisibleChange={open => { if (open) { setImmediate(() => { previousInputListFirstChild.current = document.getElementById('quick_search_input_list_0'); }); } }} options={options} showAction={['focus']} style={{width: '100%'}} value={searchingValue} onPopupScroll={e => { const currentFirstInputListNode = document.getElementById('quick_search_input_list_0'); // check if the previous first element from the dropdown list is equal to the current first element // if not, scroll to the top in order to show the label if ( currentFirstInputListNode && !currentFirstInputListNode.isEqualNode(previousInputListFirstChild.current) ) { setTimeout(() => (e.target as HTMLDivElement).scrollTo({top: 0, left: 0}), 20); } previousInputListFirstChild.current = currentFirstInputListNode; }} onKeyDown={e => { if (e.code === 'Escape') { e.preventDefault(); dispatch(closeQuickSearchActionsPopup()); } }} onSearch={value => setSearchingValue(value)} onSelect={(value: string) => { // options are of type : `type:value` applyOption(value.split(':')[0], value.split(':')[1]); }} filterOption={(inputValue, opt) => { if (opt?.options?.length) { return true; } return false; }} > <Input.Search placeholder="Search by namespace, kind and resource" /> </AutoComplete> </StyledModal> ); }; export default QuickSearchActionsV3;
the_stack
import assert = require("assert"); import { existsSync, readFileSync } from "fs"; import { pathExists, remove } from "fs-extra"; import os = require("os"); import * as fold from "travis-fold"; import * as yargs from "yargs"; import { FS, getDefinitelyTyped } from "../get-definitely-typed"; import { Options, TesterOptions } from "../lib/common"; import { parseVersionFromDirectoryName } from "../lib/definition-parser"; import { NpmInfo, UncachedNpmInfoClient } from "../lib/npm-client"; import { AllPackages, DependencyVersion, formatDependencyVersion, NotNeededPackage, PackageId, TypingsData } from "../lib/packages"; import { sourceBranch, typesDirectoryName } from "../lib/settings"; import { Semver } from "../lib/versions"; import { npmInstallFlags } from "../util/io"; import { consoleLogger, Logger, LoggerWithErrors, loggerWithErrors } from "../util/logging"; import { assertDefined, CrashRecoveryState, exec, execAndThrowErrors, flatMap, joinPaths, logUncaughtErrors, mapIter, numberOfOsProcesses, runWithListeningChildProcesses, } from "../util/util"; import { allDependencies, getAffectedPackages } from "./get-affected-packages"; const perfDir = joinPaths(os.homedir(), ".dts", "perf"); const suggestionsDir = joinPaths(os.homedir(), ".dts", "suggestions"); if (!module.parent) { if (yargs.argv.affected) { logUncaughtErrors(testAffectedOnly(Options.defaults)); } else { const selection = yargs.argv.all ? "all" : yargs.argv._[0] ? new RegExp(yargs.argv._[0]) : "affected"; const options = testerOptions(!!yargs.argv.runFromDefinitelyTyped); logUncaughtErrors( getDefinitelyTyped(options, loggerWithErrors()[0]).then(dt => runTests(dt, options.definitelyTypedPath, parseNProcesses(), selection))); } } export interface GitDiff { status: "A" | "D" | "M"; file: string; } async function testAffectedOnly(options: TesterOptions): Promise<void> { const changes = getAffectedPackages( await AllPackages.read(await getDefinitelyTyped(options, loggerWithErrors()[0])), gitChanges(await gitDiff(consoleLogger.info, options.definitelyTypedPath))); console.log({ changedPackages: changes.changedPackages.map(t => t.desc), dependersLength: changes.dependentPackages.map(t => t.desc).length }); } export function parseNProcesses(): number { const str = yargs.argv.nProcesses as string | undefined; if (!str) { return numberOfOsProcesses; } const nProcesses = Number.parseInt(str, 10); if (Number.isNaN(nProcesses)) { throw new Error("Expected nProcesses to be a number."); } return nProcesses; } export function testerOptions(runFromDefinitelyTyped: boolean): TesterOptions { return runFromDefinitelyTyped ? { definitelyTypedPath: process.cwd(), progress: false, parseInParallel: true } : Options.defaults; } export default async function runTests( dt: FS, definitelyTypedPath: string, nProcesses: number, selection: "all" | "affected" | RegExp, ): Promise<void> { const { changedPackages, dependentPackages, allPackages } = await getAffectedPackagesFromDiff(dt, definitelyTypedPath, selection); console.log(`Running with ${nProcesses} processes.`); const typesPath = `${definitelyTypedPath}/types`; await doInstalls(allPackages, [...changedPackages, ...dependentPackages], typesPath); console.log("Testing..."); await doRunTests([...changedPackages, ...dependentPackages], new Set(changedPackages), typesPath, nProcesses); } export async function getAffectedPackagesFromDiff(dt: FS, definitelyTypedPath: string, selection: "all" | "affected" | RegExp) { const allPackages = await AllPackages.read(dt); const diffs = await gitDiff(consoleLogger.info, definitelyTypedPath); if (diffs.find(d => d.file === "notNeededPackages.json")) { const uncached = new UncachedNpmInfoClient(); for (const deleted of getNotNeededPackages(allPackages, diffs)) { const source = await uncached.fetchNpmInfo(deleted.libraryName); // eg @babel/parser const typings = await uncached.fetchNpmInfo(deleted.fullNpmName); // eg @types/babel__parser checkNotNeededPackage(deleted, source, typings); } } const affected = selection === "all" ? { changedPackages: allPackages.allTypings(), dependentPackages: [], allPackages } : selection === "affected" ? getAffectedPackages(allPackages, gitChanges(diffs)) : { changedPackages: allPackages.allTypings().filter(t => selection.test(t.name)), dependentPackages: [], allPackages }; console.log(`Testing ${affected.changedPackages.length} changed packages: ${affected.changedPackages.map(t => t.desc).toString()}`); console.log(`Testing ${affected.dependentPackages.length} dependent packages: ${affected.dependentPackages.map(t => t.desc).toString()}`); return affected; } /** * 1. find all the deleted files and group by toplevel * 2. Make sure that there are no packages left with deleted entries * 3. make sure that each toplevel deleted has a matching entry in notNeededPackages */ export function getNotNeededPackages(allPackages: AllPackages, diffs: GitDiff[]): Iterable<NotNeededPackage> { const deletedPackages = new Set(diffs.filter(d => d.status === "D").map(d => assertDefined(getDependencyFromFile(d.file), `Unexpected file deleted: ${d.file} When removing packages, you should only delete files that are a part of removed packages.`) .name)); return mapIter(deletedPackages, p => { if (allPackages.hasTypingFor({ name: p, version: "*" })) { throw new Error(`Please delete all files in ${p} when adding it to notNeededPackages.json.`); } return assertDefined(allPackages.getNotNeededPackage(p), `Deleted package ${p} is not in notNeededPackages.json.`); }); } /** * 1. libraryName must exist on npm (SKIPPED and preferably/optionally have been the libraryName in just-deleted header) * (SKIPPED 2.) sourceRepoURL must exist and be the npm homepage * 3. asOfVersion must be newer than `@types/name@latest` on npm * 4. `name@asOfVersion` must exist on npm * * I skipped (2) because the cached npm info doesn't include it. I might add it later. */ export function checkNotNeededPackage(unneeded: NotNeededPackage, source: NpmInfo | undefined, typings: NpmInfo | undefined) { source = assertDefined(source, `The entry for ${unneeded.fullNpmName} in notNeededPackages.json has "libraryName": "${unneeded.libraryName}", but there is no npm package with this name. Unneeded packages have to be replaced with a package on npm.`); typings = assertDefined(typings, `Unexpected error: @types package not found for ${unneeded.fullNpmName}`); const latestTypings = Semver.parse( assertDefined(typings.distTags.get("latest"), `Unexpected error: ${unneeded.fullNpmName} is missing the "latest" tag.`), ); assert( unneeded.version.greaterThan(latestTypings), `The specified version ${unneeded.version.versionString} of ${unneeded.libraryName} must be newer than the version it is supposed to replace, ${latestTypings.versionString} of ${unneeded.fullNpmName}.`, ); assert( source.versions.has(unneeded.version.versionString), `The specified version ${unneeded.version.versionString} of ${unneeded.libraryName} is not on npm.`, ); } async function doInstalls(allPackages: AllPackages, packages: Iterable<TypingsData>, typesPath: string): Promise<void> { console.log("Installing NPM dependencies..."); // We need to run `npm install` for all dependencies, too, so that we have dependencies' dependencies installed. for (const pkg of allDependencies(allPackages, packages)) { const cwd = directoryPath(typesPath, pkg); if (!await pathExists(joinPaths(cwd, "package.json"))) { continue; } // Scripts may try to compile native code. // This doesn't work reliably on travis, and we're just installing for the types, so ignore. const cmd = `npm install ${npmInstallFlags}`; console.log(` ${cwd}: ${cmd}`); const stdout = await execAndThrowErrors(cmd, cwd); if (stdout) { // Must specify what this is for since these run in parallel. console.log(` from ${cwd}: ${stdout}`); } } await runCommand(console, undefined, require.resolve("dtslint"), ["--installAll"]); } function directoryPath(typesPath: string, pkg: TypingsData): string { return joinPaths(typesPath, pkg.subDirectoryPath); } async function doRunTests( packages: ReadonlyArray<TypingsData>, changed: ReadonlySet<TypingsData>, typesPath: string, nProcesses: number, ): Promise<void> { await remove(suggestionsDir); const allFailures: Array<[string, string]> = []; if (fold.isTravis()) { console.log(fold.start("tests")); } await runWithListeningChildProcesses({ inputs: packages.map(p => ({ path: p.subDirectoryPath, onlyTestTsNext: !changed.has(p), expectOnly: !changed.has(p) })), commandLineArgs: ["--listen"], workerFile: require.resolve("dtslint"), nProcesses, crashRecovery: true, crashRecoveryMaxOldSpaceSize: 0, // disable retry with more memory cwd: typesPath, handleStart(input, processIndex): void { const prefix = processIndex === undefined ? "" : `${processIndex}> `; console.log(`${prefix}${input.path} START`); }, handleOutput(output, processIndex): void { const prefix = processIndex === undefined ? "" : `${processIndex}> `; const { path, status } = output as { path: string, status: string }; if (status === "OK") { console.log(`${prefix}${path} OK`); } else { console.error(`${prefix}${path} failing:`); console.error(prefix ? status.split(/\r?\n/).map(line => `${prefix}${line}`).join("\n") : status); allFailures.push([path, status]); } }, handleCrash(input, state, processIndex) { const prefix = processIndex === undefined ? "" : `${processIndex}> `; switch (state) { case CrashRecoveryState.Retry: console.warn(`${prefix}${input.path} Out of memory: retrying`); break; case CrashRecoveryState.RetryWithMoreMemory: console.warn(`${prefix}${input.path} Out of memory: retrying with increased memory (4096M)`); break; case CrashRecoveryState.Crashed: console.error(`${prefix}${input.path} Out of memory: failed`); allFailures.push([input.path, "Out of memory"]); break; default: } }, }); if (fold.isTravis()) { console.log(fold.end("tests")); } console.log("\n\n=== SUGGESTIONS ===\n"); const suggestionLines: string[] = []; for (const change of changed) { const pkgPath = change.versionDirectoryName ? change.name + change.versionDirectoryName : change.name; const path = joinPaths(suggestionsDir, pkgPath + ".txt"); if (existsSync(path)) { const suggestions = readFileSync(path, "utf8").split("\n"); suggestionLines.push(`"${change.subDirectoryPath}": [${suggestions.join(",")}]`); } } console.log(`{${suggestionLines.join(",")}}`); console.log("\n\n=== PERFORMANCE ===\n"); console.log("{"); for (const change of changed) { const path = joinPaths(perfDir, change.name + ".json"); if (existsSync(path)) { const perf = JSON.parse(readFileSync(path, "utf8")) as { [name: string]: { typeCount: number } }; console.log(` "${change.name}": ${perf[change.name].typeCount},`); } } console.log("}"); if (allFailures.length === 0) { return; } console.error("\n\n=== ERRORS ===\n"); for (const [path, error] of allFailures) { console.error(`\n\nError in ${path}`); console.error(error); } throw new Error(`The following packages had errors: ${allFailures.map(e => e[0]).join(", ")}`); } interface TesterError { message: string; } async function runCommand(log: LoggerWithErrors, cwd: string | undefined, cmd: string, args: string[]): Promise<TesterError | undefined> { const nodeCmd = `node ${cmd} ${args.join(" ")}`; log.info(`Running: ${nodeCmd}`); try { const { error, stdout, stderr } = await exec(nodeCmd, cwd); if (stdout) { log.info(stdout); } if (stderr) { log.error(stderr); } return error && { message: `${error.message}\n${stdout}\n${stderr}` }; } catch (e) { return e as TesterError; } } /** Returns all immediate subdirectories of the root directory that have changed. */ export function gitChanges(diffs: GitDiff[]): PackageId[] { const changedPackages = new Map<string, Map<string, DependencyVersion>>(); for (const diff of diffs) { const dep = getDependencyFromFile(diff.file); if (dep) { const versions = changedPackages.get(dep.name); if (!versions) { changedPackages.set(dep.name, new Map([[formatDependencyVersion(dep.version), dep.version]])); } else { versions.set(formatDependencyVersion(dep.version), dep.version); } } } return Array.from(flatMap(changedPackages, ([name, versions]) => mapIter(versions, ([_, version]) => ({ name, version })))); } /* We have to be careful about how we get the diff because travis uses a shallow clone. Travis runs: git clone --depth=50 https://github.com/DefinitelyTyped/DefinitelyTyped.git DefinitelyTyped cd DefinitelyTyped git fetch origin +refs/pull/123/merge git checkout -qf FETCH_HEAD If editing this code, be sure to test on both full and shallow clones. */ export async function gitDiff(log: Logger, definitelyTypedPath: string): Promise<GitDiff[]> { try { await run(`git rev-parse --verify ${sourceBranch}`); // If this succeeds, we got the full clone. } catch (_) { // This is a shallow clone. await run(`git fetch origin ${sourceBranch}`); await run(`git branch ${sourceBranch} FETCH_HEAD`); } let diff = (await run(`git diff ${sourceBranch} --name-status`)).trim(); if (diff === "") { // We are probably already on master, so compare to the last commit. diff = (await run(`git diff ${sourceBranch}~1 --name-status`)).trim(); } return diff.split("\n").map(line => { const [status, file] = line.split(/\s+/, 2); return { status: status.trim(), file: file.trim() } as GitDiff; }); async function run(cmd: string): Promise<string> { log(`Running: ${cmd}`); const stdout = await execAndThrowErrors(cmd, definitelyTypedPath); log(stdout); return stdout; } } /** * For "types/a/b/c", returns { name: "a", version: "*" }. * For "types/a/v3/c", returns { name: "a", version: 3 }. * For "x", returns undefined. */ function getDependencyFromFile(file: string): PackageId | undefined { const parts = file.split("/"); if (parts.length <= 2) { // It's not in a typings directory at all. return undefined; } const [typesDirName, name, subDirName] = parts; // Ignore any other parts if (typesDirName !== typesDirectoryName) { return undefined; } if (subDirName) { const version = parseVersionFromDirectoryName(subDirName); if (version !== undefined) { return { name, version }; } } return { name, version: "*" }; }
the_stack
const fetch = require('node-fetch'); const crypto = require('crypto'); var url = require('url'); // import bodyParser from "body-parser"; var bodyParser = require('body-parser') import * as botbuilder from "botbuilder"; const VERIFY_TOKENS = [ '00000000000000000000000000000000', 'ffffffffffffffffffffffffffffffff' ] export class ImageMap implements botbuilder.IIsAttachment { static ONE_IMAGE = 11; static TWO_IMAGE_VERTICAL = 21; static TWO_IMAGE_HORIZONTAL = 22; static THREE_IMAGE_VERTICAL = 31; static THREE_IMAGE_HORIZONTAL = 32; static FOUR_IMAGE = 40; static SIX_IMAGE = 60; // session: botbuilder.Session; // address: botbuilder.IAddress text: string; baseUrl: string; baseSize: { width: number, height: number } actions: Array<{ type: string, linkUri?: string, label?: string, text?: string, area: { x: number, y: number, width: number, height: number } }> constructor(text: string, baseUrl: string, baseSize: { width: number, height: number }, actions: Array<{ type: string, linkUri?: string, label?: string, text?: string, area: { x: number, y: number, width: number, height: number } }>) { // this.address = address; this.text = text; this.baseUrl = baseUrl; this.baseSize = baseSize; this.actions = actions; } toAttachment(): botbuilder.IAttachment { return { contentType: "imagemap", content: { baseUrl: this.baseUrl, baseSize: this.baseSize, actions: this.actions, text: this.text } } } static getImageMapActions: any = (type: number, width: number, height: number, open_urls: Array<string>) => { let IMAGE_WIDTH = width; let IMAGE_HEIGHT = height; // console.log(open_urls) /* 1: one image 2: two image 3. three image with 水平 4. three image with 垂直 */ switch (type) { case ImageMap.ONE_IMAGE: return [ { "type": "uri", "linkUri": open_urls[0], "area": { "x": 0, "y": 0, "width": IMAGE_WIDTH, "height": IMAGE_HEIGHT } } ] case ImageMap.TWO_IMAGE_VERTICAL: return [ { "type": "uri", "linkUri": open_urls[0], "area": { "x": 0, "y": 0, "width": IMAGE_WIDTH, "height": IMAGE_HEIGHT / 2 } }, { "type": "uri", "linkUri": open_urls[1], "area": { "x": 0, "y": IMAGE_HEIGHT / 2, "width": IMAGE_WIDTH, "height": IMAGE_HEIGHT / 2 } } ] case ImageMap.TWO_IMAGE_HORIZONTAL: return [ { "type": "uri", "linkUri": open_urls[0], "area": { "x": 0, "y": 0, "width": IMAGE_WIDTH / 2, "height": IMAGE_HEIGHT } }, { "type": "uri", "linkUri": open_urls[1], "area": { "x": IMAGE_WIDTH / 2, "y": 0, "width": IMAGE_WIDTH / 2, "height": IMAGE_HEIGHT } } ] case ImageMap.THREE_IMAGE_VERTICAL: return [ { "type": "uri", "linkUri": open_urls[0], "area": { "x": 0, "y": 0, "width": IMAGE_WIDTH, "height": IMAGE_HEIGHT / 3 } }, { "type": "uri", "linkUri": open_urls[1], "area": { "x": 0, "y": IMAGE_HEIGHT / 3, "width": IMAGE_WIDTH, "height": IMAGE_HEIGHT / 3 } }, { "type": "uri", "linkUri": open_urls[2], "area": { "x": 0, "y": (IMAGE_HEIGHT / 3) * 2, "width": IMAGE_WIDTH, "height": IMAGE_HEIGHT / 3 } } ] case ImageMap.THREE_IMAGE_HORIZONTAL: return [ { "type": "uri", "linkUri": open_urls[0], "area": { "x": 0, "y": 0, "width": IMAGE_WIDTH / 3, "height": IMAGE_HEIGHT } }, { "type": "uri", "linkUri": open_urls[1], "area": { "x": IMAGE_WIDTH / 3, "y": 0, "width": IMAGE_WIDTH / 3, "height": IMAGE_HEIGHT } }, { "type": "uri", "linkUri": open_urls[2], "area": { "x": (IMAGE_WIDTH / 3) * 2, "y": 0, "width": IMAGE_WIDTH / 3, "height": IMAGE_HEIGHT } } ] case ImageMap.FOUR_IMAGE: return [ { "type": "uri", "linkUri": open_urls[0], "area": { "x": 0, "y": 0, "width": IMAGE_WIDTH / 2, "height": IMAGE_HEIGHT / 2 } }, { "type": "uri", "linkUri": open_urls[1], "area": { "x": IMAGE_WIDTH / 2, "y": 0, "width": IMAGE_WIDTH / 2, "height": IMAGE_HEIGHT / 2 } }, { "type": "uri", "linkUri": open_urls[2], "area": { "x": 0, "y": IMAGE_HEIGHT / 2, "width": IMAGE_WIDTH / 2, "height": IMAGE_HEIGHT / 2 } }, { "type": "uri", "linkUri": open_urls[3], "area": { "x": IMAGE_WIDTH / 2, "y": IMAGE_HEIGHT / 2, "width": IMAGE_WIDTH / 2, "height": IMAGE_HEIGHT / 2 } }, ] case ImageMap.SIX_IMAGE: return [ { "type": "uri", "linkUri": open_urls[0], "area": { "x": 0, "y": 0, "width": IMAGE_WIDTH / 3, "height": IMAGE_HEIGHT / 2 } }, { "type": "uri", "linkUri": open_urls[1], "area": { "x": IMAGE_WIDTH / 3, "y": 0, "width": IMAGE_WIDTH / 3, "height": IMAGE_HEIGHT / 2 } }, { "type": "uri", "linkUri": open_urls[2], "area": { "x": (IMAGE_WIDTH / 3) * 2, "y": 0, "width": IMAGE_WIDTH / 3, "height": IMAGE_HEIGHT / 2 } }, { "type": "uri", "linkUri": open_urls[3], "area": { "x": 0, "y": IMAGE_HEIGHT / 2, "width": IMAGE_WIDTH / 3, "height": IMAGE_HEIGHT / 2 } }, { "type": "uri", "linkUri": open_urls[4], "area": { "x": IMAGE_WIDTH / 3, "y": IMAGE_HEIGHT / 2, "width": IMAGE_WIDTH / 3, "height": IMAGE_HEIGHT / 2 } }, { "type": "uri", "linkUri": open_urls[5], "area": { "x": (IMAGE_WIDTH / 3) * 2, "y": IMAGE_HEIGHT / 2, "width": IMAGE_WIDTH / 3, "height": IMAGE_HEIGHT / 2 } } ] } } } export class Sticker implements botbuilder.IIsAttachment { // address: botbuilder.IAddress packageId: string; stickerId: string; // session: botbuilder.Session; constructor(packageId: number, stickerId: number) { this.packageId = packageId.toString(); this.stickerId = stickerId.toString(); // this.address = address; } toAttachment(): botbuilder.IAttachment { // throw new Error("Method not implemented."); // console.log(this.session.message) // let address: any = this.session.message.address; // if (this.session.message && // ((this.session.message.source && this.session.message.source === "line") || // (address.channel.source && address.channel.source === "line")) // ) { // if (this.session.message && this.session.message.source && this.session.message.source === "line") { return { contentType: "sticker", content: { packageId: this.packageId, stickerId: this.stickerId } } // } else { // // throw new Error("Method not implemented."); // return new botbuilder.MediaCard().text("this is a sticker!!").toAttachment() // } } } export class Location implements botbuilder.IIsAttachment { // session: botbuilder.Session; // address: botbuilder.IAddress title: string; location_address: string; latitude: number; longitude: number; constructor(title: string, address_or_desc: string, latitude: number, longitude: number) { // this.address = address; this.title = title; this.location_address = address_or_desc; this.latitude = latitude; this.longitude = longitude; } toAttachment(): botbuilder.IAttachment { // let address: any = this.session.message.address; // if (this.session.message && // ((this.session.message.source && this.session.message.source === "line") || // (address.channel.source && address.channel.source === "line")) // ) { // if (this.session.message && this.session.message.source && this.session.message.source === "line") { return { contentType: "location", content: { title: this.title, address: this.location_address, latitude: this.latitude, longitude: this.longitude } // } // } else { // // throw new Error("Method not implemented."); // return new botbuilder.MediaCard().text(`this is a location!! ${this.location_address}`).toAttachment() // } } } } export class LineConnector implements botbuilder.IConnector { //const headers: any; endpoint: string; botId: string; hasPushApi = false; autoGetUserProfile = false //from dispatch replyToken: any; options: any; conversationId: any; conversationType: any; event_cache = []; //form botframework handler: any; timer: any; constructor(options: any) { this.options = options || {}; this.options.channelId = options.channelId || ''; this.options.channelSecret = options.channelSecret || ''; this.options.channelAccessToken = options.channelAccessToken || ''; if (this.options.verify === undefined) { this.options.verify = true; } if (this.options.hasPushApi !== undefined) { this.hasPushApi = this.options.hasPushApi; } if (this.autoGetUserProfile !== undefined) { this.autoGetUserProfile = this.options.autoGetUserProfile; } this.headers = { Accept: 'application/json', 'Content-Type': 'application/json', Authorization: 'Bearer ' + this.options.channelAccessToken }; this.endpoint = 'https://api.line.me/v2/bot'; this.botId = options.channelId; } private verify(rawBody: any, signature: any) { const hash = crypto.createHmac('sha256', this.options.channelSecret) .update(rawBody, 'utf8') .digest('base64'); return hash === signature; } listen() { console.log("listen") const parser = bodyParser.json({ verify: function (req: any, res: any, buf: any, encoding: any) { req.rawBody = buf.toString(encoding); } }); return (req: any, res: any) => { parser(req, res, () => { // if (this.options.verify && !this.verify(req.rawBody, req.get('X-Line-Signature'))) { // return res.sendStatus(400); // } this.dispatch(req.body, res); return res.json({}); }); }; } async serverlessWebhock(event: any) { this.dispatch(JSON.parse(event.body), null); } private addReplyToken(replyToken: any) { const _this = this; _this.replyToken = replyToken; // console.log("addReplyToken1", _this.replyToken, _this.event_cache) clearTimeout(this.timer) this.timer = setTimeout(() => { // console.log("addReplyToken2", _this.replyToken) if (_this.replyToken && _this.event_cache.length > 0) { let r = (' ' + _this.replyToken).slice(1); _this.replyToken = null; _this.reply(r, _this.event_cache); } else if (_this.replyToken !== null) { console.log("wait for 2 seconds let will make replyToken no use, clean the replytoken") } _this.replyToken = null; _this.event_cache = []; }, 10000) } private dispatch(body: any, res: any) { console.log("dispatch") const _this = this; if (!body || !body.events) { console.log("dispatch return") return; } body.events.forEach(async (event: any) => { console.log("event", event) if (VERIFY_TOKENS.indexOf(event.replyToken) !== -1) { return; } _this.addReplyToken(event.replyToken) let m: any = { timestamp: new Date(parseInt(event.timestamp)).toISOString(), source: "line", address: { conversation: {}, channel: {}, user: {} } } switch (event.source.type) { case 'user': m.address.conversation.name = "user"; m.address.conversation.id = event.source.userId; m.address.channel.id = event.source.userId; m.address.channelId = event.source.userId; m.address.channel.source = "line"; m.address.user.name = "user"; m.address.user.id = event.source.userId; _this.conversationId = event.source.userId; break; case 'group': m.address.conversation.name = "group"; m.address.conversation.id = event.source.groupId; m.address.conversation.isGroup = true; m.address.channel.id = event.source.groupId; m.address.channelId = event.source.groupId; m.address.user.name = "group"; m.address.user.id = event.source.groupId; _this.conversationId = event.source.groupId; _this.conversationType = "group"; break; case 'room': m.address.conversation.name = "room"; m.address.conversation.id = event.source.roomId; m.address.conversation.isGroup = true; m.address.channel.id = event.source.roomId; m.address.channelId = event.source.roomId; m.address.user.name = "room"; m.address.user.id = event.source.roomId; _this.conversationId = event.source.roomId; _this.conversationType = "room"; break; } m.from = { id: event.source.userId } if (event.source.userId && _this.autoGetUserProfile) { try { let r = await _this.getUserProfile(event.source.userId); m.from = { id: event.source.userId, name: r.displayName, pictureUrl: r.pictureUrl, statusMessage: r.statusMessage } } catch (e) { console.log(e) } } switch (event.type) { case 'message': m.id = event.message.id; m.type = 'message' const message = event.message; switch (message.type) { case 'text': m.text = event.message.text break; case 'image': m.attachments = [{ contentType: "image", contentUrl: "", name: "" }]; break; case 'video': m.attachments = [{ contentType: "video", contentUrl: "", name: "" }]; break; case 'audio': m.attachments = [{ contentType: "audio", contentUrl: "", name: "" }]; break; case 'location': m.attachments = [{ "type": "location", "id": event.message.id, "latitude": event.message.latitude, "longitude": event.message.longitude }]; break; case 'sticker': m.attachments = [{ contentType: "sticker", contentUrl: "", name: "" }]; break; default: throw new Error(`Unknown message: ${JSON.stringify(message)}`); break; } break; case 'follow': m.id = event.source.userId; m.type = 'conversationUpdate' m.text = "follow" break; case 'unfollow': m.id = event.source.userId; m.type = 'conversationUpdate' m.text = "unfollow" break; case 'join': m.membersAdded = [{}] m.type = 'conversationUpdate' m.text = "join" break; case 'leave': m.membersRemoved = true m.type = 'conversationUpdate' m.text = "leave" break; case 'postback': m.type = 'message' let data = event.postback.data; if (data === 'DATE' || data === 'TIME' || data === 'DATETIME') { data = `${event.postback.params.datetime}`; } m.text = data break; case 'beacon': break; default: throw new Error(`Unknown event: ${JSON.stringify(event)}`); break; } // console.log("m", m) _this.handler([m]); }) } onEvent(handler: any) { this.handler = handler; }; private static createMessages(message: any) { // console.log(message) if (typeof message === 'string') { return [{ type: 'text', text: message }]; } if (Array.isArray(message)) { return message.map(function (m) { if (typeof m === 'string') { return { type: 'text', text: m }; } return m; }); } return [message]; } private post(path: any, body: any) { console.log("post", path, body) // console.log(path, body) // let r; // try { // r = fetch(this.endpoint + path, { method: 'POST', headers: this.headers, body: JSON.stringify(body) }); // } catch (er) { // console.log("er",er) // } return fetch(this.endpoint + path, { method: 'POST', headers: this.headers, body: JSON.stringify(body) }); } private get(path: any) { // console.log("get", path); return fetch(this.endpoint + path, { method: 'GET', headers: this.headers }); } private async reply(replyToken: any, message: any) { console.log("reply") let m = LineConnector.createMessages(message); const body = { replyToken: replyToken, messages: m }; let r = await this.post('/message/reply', body).then(); if (r.status === 400) { r.json().then((json: any) => { console.log(json); throw new Error(json.toString()) }); } return r; } private async push(toId: any, message: any) { let m = LineConnector.createMessages(message); const body = { to: toId, messages: m }; // console.log("body", body) // let res = await this.post('/message/push', body).then(); let r = await this.post('/message/push', body).then(); // let r = await res.json().then(); if (r.status === 400) { r.json().then((json: any) => { console.log(json); throw new Error(json.toString()) }); } return r; } async getUserProfile(userId: string) { let url = '/profile/' + userId; // return url let res = await this.get(url).then() let r = await res.json().then(); if (r.message) { throw new Error(r.message) } return r; } private async getMemberIDs() { if (this.conversationType === undefined) { throw new Error("not room or group") return; } let url = `/${this.conversationType === "group" ? "group" : this.conversationType === "room" ? "room" : ""}/${this.conversationId}/members/ids` // return url let res = await this.get(url).then() // console.log(res) let r = await res.json().then(); if (r.message) { throw new Error(r.message) } return r; } private async getMemberRrofile(userId: string) { if (this.conversationType === undefined) { throw new Error("not room or group") return; } let url = `/${this.conversationType === "group" ? "group" : this.conversationType === "room" ? "room" : ""}/${this.conversationId}/member/${userId}` // return url let res = await this.get(url).then() let r = await res.json().then(); if (r.message) { throw new Error(r.message) } return r; } async leave() { if (this.conversationType === undefined) { throw new Error("not room or group") return; } let url = `/${this.conversationType === "group" ? "group" : this.conversationType === "room" ? "room" : ""}/${this.conversationId}/leave` const body = { replyToken: this.replyToken, }; let r = await this.post(url, body).then(); // let r = await res.json().then(); if (r.status === 400) { r.json().then((json: any) => { console.log(json); throw new Error(json.toString()) }); } return r; } private getRenderTemplate(event: any) { var _this = this; // console.log("getRenderTemplate", event) //20170825 should be there let getButtonTemp = (b: any) => { if (b.type === 'postBack') { return { "type": "postback", "label": b.title, "data": b.value, // "text": "OK" } } else if (b.type === 'openUrl') { return { "type": "uri", "label": b.title ? b.title : "open url", "uri": b.value } } else if (b.type === 'datatimepicker') { // console.log("datatimepicker", b) let p = { "type": "datetimepicker", "label": b.title, "data": "DATETIME", "mode": "datetime", "initial": new Date(new Date().getTime() - (1000 * 60 * new Date().getTimezoneOffset())).toISOString().substring(0, new Date().toISOString().length - 8), "max": new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 30 * 12)).toISOString().substring(0, new Date().toISOString().length - 8), "min": new Date(new Date().getTime() - (1000 * 60 * 60 * 24 * 30 * 12)).toISOString().substring(0, new Date().toISOString().length - 8), } if (b.value) { let d = JSON.parse(b.value) p.initial = d.initial ? d.initial : p.initial; p.max = d.max ? d.max : p.max; p.min = d.min ? d.min : p.min; } return p } else { return { "type": "message", "label": b.title, "text": b.value } } } let getAltText = (s: string) => { return s.substring(0, 400) } // console.log("event", event) switch (event.type) { case 'message': if (event.text) { if (event.suggestedActions && event.suggestedActions.actions && event.suggestedActions.actions.length > 0) { let l = event.suggestedActions.actions.length; switch (l) { // case 2: // //confirm // return { // type: "template", // altText: getAltText(event.text), // template: { // type: "confirm", // // title: event.text || "", // text: `${event.text || ""}`, // actions: event.suggestedActions.actions.map(b => // getButtonTemp(b) // ) // } // } default: return { type: "template", altText: getAltText(event.text), template: { type: "buttons", // title: event.text || "", text: `${event.text || ""}`, actions: event.suggestedActions.actions.map((b: any) => getButtonTemp(b) ) } } } } return { type: 'text', text: event.text } } else if (event.attachments) { if (event.attachmentLayout === 'carousel') { //for carousel //for image carousel // let be_same = event.attachments.reduce((c, n) => { // return c.contentType === n.contentType // }) var be_same = event.attachments.reduce(function (c: any, n: any) { if (c.contentType === n.contentType) { return c; } else { return false } }); if (!be_same) { throw new Error("must be same attachment") } if (event.attachments[0].contentType === "application/vnd.microsoft.card.hero") { // let be_image_carousel = event.attachments.reduce((c, n) => { // return c.content.images.length === 1 && n.content.images.length === 1 && c.content.buttons.length === 1 && n.content.buttons.length === 1 // }) var be_image_carousel = event.attachments.reduce(function (c: any, n: any) { if (c === false) { return false; } if (c.content.images && c.content.images.length === 1 && n.content.images.length === 1 && c.content.buttons.length === 1 && n.content.buttons.length === 1) { return c; } else { return false } }); if (be_image_carousel) { return { "type": "template", "altText": getAltText(event.attachments[0].content.text), "template": { "type": "image_carousel", "columns": event.attachments.map((a: any) => { return { imageUrl: a.content.images[0].url, action: getButtonTemp(a.content.buttons[0]) } }) } } } else { let t: any = { type: "template", altText: getAltText(event.attachments[0].content.text), template: { type: "carousel", imageAspectRatio: "rectangle", imageSize: "cover", columns: event.attachments.map((a: any) => { let c: any = { title: a.content.title || "", text: getAltText(event.attachments[0].content.text), actions: a.content.buttons.map((b: any) => getButtonTemp(b) ) } if (a.content.images) { c.thumbnailImageUrl = a.content.images[0].url; c.imageBackgroundColor = "#FFFFFF"; } return c; }) } } return t; } } else { throw new Error("do not suppoert this card,only support HeroCard ") } } return event.attachments.map((a: any) => { // console.log("a", a) switch (a.contentType) { case 'sticker': return { type: 'sticker', packageId: a.content.packageId, stickerId: a.content.stickerId } case `imagemap`: let t: any; t = { type: "imagemap", baseUrl: a.content.baseUrl, baseSize: a.content.baseSize, altText: getAltText(a.content.text), actions: a.content.actions }; return t; return { "type": "imagemap", "baseUrl": "https://www.profolio.com/sites/default/files/styles/1920x1040/public/field/image/Bikini_Girls_adx.jpg?itok=uciEvomy", "altText": "This is an imagemap", "baseSize": { "width": 1040, "height": 104 }, // "video": { // "originalContentUrl": "https://example.com/video.mp4", // "previewImageUrl": "https://www.profolio.com/sites/default/files/styles/1920x1040/public/field/image/Bikini_Girls_adx.jpg?itok=uciEvomy", // "area": { // "x": 0, // "y": 0, // "width": 1040, // "height": 585 // }, // "externalLink": { // "linkUri": "https://example.com/see_more.html", // "label": "See More" // } // }, "actions": [ { "type": "uri", "linkUri": "https://google.com/", "area": { "x": 0, "y": 0, "width": 1040, "height": 104 } }, // { // "type": "message", // "text": "Hello", // "area": { // "x": 520, // "y": 586, // "width": 520, // "height": 454 // } // } ] } case 'location': return { type: 'location', title: a.content.title, address: a.content.location_address, latitude: a.content.latitude, longitude: a.content.longitude } case 'application/vnd.microsoft.card.video': if (a.content.image && a.content.media && a.content.media[0].url.indexOf("https") > -1 && a.content.image.url.indexOf("https") > -1) { return { "type": "video", "originalContentUrl": a.content.media[0].url, "previewImageUrl": a.content.image.url } } else { return new Error("need image and media") } case 'application/vnd.microsoft.card.audio': if (a.content.media && a.content.media[0].url.indexOf("https") > -1) { return { "type": "audio", "originalContentUrl": a.content.media[0].url, "duration": a.content.media[0].duration || 240000 } } else { return new Error("need image and media") } case 'application/vnd.microsoft.keyboard': if (a.content.image && a.content.image.url.indexOf("https") > -1) { return { "type": "image", "originalContentUrl": a.content.image.url, "previewImageUrl": a.content.image.url } } case 'application/vnd.microsoft.card.hero': if (!a.content.buttons) { return new Error("need buttons data") } if (a.content.images === undefined && a.content.buttons.length === 2) { //confirm return { type: "template", altText: getAltText(a.content.text), template: { type: "confirm", title: a.content.title || "", text: `${a.content.title || ""}${a.content.subtitle || ""}`, actions: a.content.buttons.map((b: any) => getButtonTemp(b) ) } } } else { let t: any = { type: "template", altText: a.content.text, template: { type: "buttons", title: a.content.title || "", text: `${a.content.title || ""}${a.content.subtitle || ""}`, actions: a.content.buttons.map((b: any) => getButtonTemp(b) ) } } if (a.content.images) { t.template.thumbnailImageUrl = a.content.images[0].url; t.template.imageAspectRatio = "rectangle"; t.template.imageSize = "cover"; t.template.imageBackgroundColor = "#FFFFFF"; } return t; } } }) } } } send(messages: botbuilder.IMessage[], done: any) { // let ts = []; const _this = this; messages.map((e: botbuilder.IMessage, i) => { // console.log("e", e) const address = e.address; if (e.type === 'endOfConversation') { return address; } if (_this.hasPushApi) { _this.conversationId = e.address.channelId; _this.push(_this.conversationId, _this.getRenderTemplate(e)) } else if (_this.replyToken) { let t: Array<any> = _this.getRenderTemplate(e) // console.log(t) if (Array.isArray(t)) { _this.event_cache = _this.event_cache.concat(<any>t) } else { _this.event_cache.push(t) } if ((_this.event_cache.length === messages.length) || _this.event_cache.length === 5) { let r = (' ' + _this.replyToken).slice(1); _this.replyToken = null; _this.reply(r, _this.event_cache); _this.event_cache = []; } } else { throw new Error(`no way to send message: ` + e); } }) } startConversation(address: any, callback: any) { console.log(address); console.log(callback); } }
the_stack
import { inject, injectable, multiInject } from 'inversify'; import { homedir } from 'os'; import { basename, join } from 'path'; import * as vscode from 'vscode'; import * as nls from 'vscode-nls'; import { ProfilerFactory } from '../../adapter/profiling'; import { Commands } from '../../common/contributionUtils'; import { DisposableList, IDisposable } from '../../common/disposable'; import { moveFile } from '../../common/fsUtils'; import { AnyLaunchConfiguration } from '../../configuration'; import Dap from '../../dap/api'; import { FS, FsPromises, SessionSubStates } from '../../ioc-extras'; import { DebugSessionTracker } from '../debugSessionTracker'; import { ManualTerminationCondition } from './manualTerminationCondition'; import { ITerminationCondition, ITerminationConditionFactory } from './terminationCondition'; import { UiProfileSession } from './uiProfileSession'; const localize = nls.loadMessageBundle(); const isProfileCandidate = (session: vscode.DebugSession) => '__pendingTargetId' in session.configuration; /** * Arguments provided in the `startProfile` command. */ export interface IStartProfileArguments { /** * Session ID to capture. If not provided, the user may be asked to pick * an available session. */ sessionId?: string; /** * Type of profile to take. One of the "IProfiler.type" types. Currently, * only 'cpu' is available. If not provided, the user will be asked to pick. */ type?: string; /** * Termination condition. If not provided, the user will be asked to pick. * Optionally pass arguments: * - `manual` takes no arguments * - `duration` takes a [number] of seconds * - `breakpoint` takes a `[Array<number>]` of DAP breakpoint IDs. These can * be found by calling the custom `getBreakpoints` method on a debug session. */ termination?: string | { type: string; args?: ReadonlyArray<unknown> }; /** * Command to run when the profile has completed. If not provided, the * profile will be opened in a new untitled editor. The command will receive * an `IProfileCallbackArguments` object. */ onCompleteCommand?: string; } /** * Arguments given to the `onCompleteCommand`. */ export interface IProfileCallbackArguments { /** * String contents of the profile. */ contents: string; /** * Suggested file name of the profile. */ basename: string; } @injectable() export class UiProfileManager implements IDisposable { private statusBarItem?: vscode.StatusBarItem; private lastChosenType: string | undefined; private lastChosenTermination: string | undefined; private readonly activeSessions = new Map<string /* debug session id */, UiProfileSession>(); private readonly disposables = new DisposableList(); constructor( @inject(DebugSessionTracker) private readonly tracker: DebugSessionTracker, @inject(FS) private readonly fs: FsPromises, @inject(SessionSubStates) private readonly sessionStates: SessionSubStates, @multiInject(ITerminationConditionFactory) private readonly terminationConditions: ReadonlyArray<ITerminationConditionFactory>, ) { this.disposables.push( vscode.debug.onDidReceiveDebugSessionCustomEvent(event => { if (event.event !== 'profileStarted') { return; } const args = event.body as Dap.ProfileStartedEventParams; let session = this.activeSessions.get(event.session.id); if (!session) { session = new UiProfileSession( event.session, ProfilerFactory.ctors.find(t => t.type === args.type) || ProfilerFactory.ctors[0], new ManualTerminationCondition(), ); this.registerSession(session); } session.setFile(args.file); }), ); } /** * Starts a profiling session. */ public async start(args: IStartProfileArguments) { let maybeSession: vscode.DebugSession | undefined; const candidates = [...this.tracker.getConcreteSessions()].filter(isProfileCandidate); if (args.sessionId) { maybeSession = candidates.find(s => s.id === args.sessionId); } else { maybeSession = await this.pickSession(candidates); } if (!maybeSession) { return; // cancelled or invalid } const session = maybeSession; const existing = this.activeSessions.get(session.id); if (existing) { if (!(await this.alreadyRunningSession(existing))) { return; } } const impl = await this.pickType(session, args.type); if (!impl) { return; } let termination: ITerminationCondition | undefined; if (!impl.instant) { termination = await this.pickTermination(session, args.termination); if (!termination) { return; } } const uiSession = new UiProfileSession(session, impl, termination); if (!uiSession) { return; } this.registerSession(uiSession, args.onCompleteCommand); await uiSession.start(); if (impl.instant) { await uiSession.stop(); } } /** * Stops the profiling session if it exists. */ public async stop(sessionId?: string) { let uiSession: UiProfileSession | undefined; if (sessionId) { uiSession = this.activeSessions.get(sessionId); } else { const session = await this.pickSession([...this.activeSessions.values()].map(s => s.session)); uiSession = session && this.activeSessions.get(session.id); } if (!uiSession) { return; } this.sessionStates.remove(uiSession.session.id); await uiSession.stop(); } /** * @inheritdoc */ public dispose() { for (const session of this.activeSessions.values()) { session.dispose(); } this.activeSessions.clear(); this.disposables.dispose(); } /** * Starts tracking a UI profile session in the manager. */ private registerSession(uiSession: UiProfileSession, onCompleteCommand?: string) { this.activeSessions.set(uiSession.session.id, uiSession); this.sessionStates.add(uiSession.session.id, localize('profile.sessionState', 'Profiling')); uiSession.onStatusChange(() => this.updateStatusBar()); uiSession.onStop(file => { if (file) { this.openProfileFile(uiSession, onCompleteCommand, uiSession.session, file); } this.activeSessions.delete(uiSession.session.id); uiSession.dispose(); this.updateStatusBar(); }); this.updateStatusBar(); } /** * Opens the profile file within the UI, called * when a session ends gracefully. */ private async openProfileFile( uiSession: UiProfileSession, onCompleteCommand: string | undefined, session: vscode.DebugSession, sourceFile: string, ) { if (onCompleteCommand) { return Promise.all([ vscode.commands.executeCommand(onCompleteCommand, { contents: await this.fs.readFile(sourceFile, 'utf-8'), basename: basename(sourceFile) + uiSession.impl.extension, } as IProfileCallbackArguments), this.fs.unlink(sourceFile), ]); } const directory = session.workspaceFolder?.uri.fsPath ?? vscode.workspace.workspaceFolders?.[0].uri.fsPath ?? homedir(); const now = new Date(); const filename = [ 'vscode-profile', now.getFullYear(), now.getMonth() + 1, now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds(), ] .map(n => String(n).padStart(2, '0')) .join('-') + uiSession.impl.extension; // todo: open as untitled, see: https://github.com/microsoft/vscode/issues/93441 const fileUri = vscode.Uri.file(join(directory, filename)); await moveFile(this.fs, sourceFile, fileUri.fsPath); await vscode.commands.executeCommand( uiSession.impl.editable ? 'vscode.open' : 'revealInExplorer', fileUri, ); } /** * Updates the status bar based on the state of current debug sessions. */ private updateStatusBar() { if (this.activeSessions.size === 0) { this.statusBarItem?.hide(); vscode.commands.executeCommand('setContext', 'jsDebugIsProfiling', false); return; } if (!this.statusBarItem) { this.statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 500); this.statusBarItem.command = Commands.StopProfile; } vscode.commands.executeCommand('setContext', 'jsDebugIsProfiling', true); if (this.activeSessions.size === 1) { const session: UiProfileSession = this.activeSessions.values().next().value; this.statusBarItem.text = session.status ? localize( 'profile.status.single', '$(loading) Click to Stop Profiling ({0})', session.status, ) : localize('profile.status.default', '$(loading) Click to Stop Profiling'); } else { this.statusBarItem.text = localize( 'profile.status.multiSession', '$(loading) Click to Stop Profiling ({0} sessions)', this.activeSessions.size, ); } this.statusBarItem.show(); } /** * Triggered when we try to profile a session we're already profiling. Asks * if they want to stop and start profiling it again. */ private async alreadyRunningSession(existing: UiProfileSession) { const yes = localize('yes', 'Yes'); const no = localize('no', 'No'); const stopExisting = await vscode.window.showErrorMessage( localize( 'profile.alreadyRunning', 'A profiling session is already running, would you like to stop it and start a new session?', ), yes, no, ); if (stopExisting !== yes) { return false; } await this.stop(existing.session.id); return true; } /** * Quickpick to select any of the given candidate sessions. */ private async pickSession(candidates: ReadonlyArray<vscode.DebugSession>) { if (candidates.length === 0) { return; } if (candidates.length === 1) { return candidates[0]; } const chosen = await vscode.window.showQuickPick( candidates.map(c => ({ label: c.name, id: c.id })), ); return chosen && candidates.find(c => c.id === chosen.id); } /** * Picks the profiler type to run in the session. */ private async pickType(session: vscode.DebugSession, suggestedType?: string) { const params = session.configuration as AnyLaunchConfiguration; if (suggestedType) { return ProfilerFactory.ctors.find(t => t.type === suggestedType && t.canApplyTo(params)); } const chosen = await this.pickWithLastDefault( localize('profile.type.title', 'Type of profile:'), ProfilerFactory.ctors.filter(ctor => ctor.canApplyTo(params)), this.lastChosenType, ); if (chosen) { this.lastChosenType = chosen.label; } return chosen; } /** * Picks the termination condition to use for the session. */ private async pickTermination( session: vscode.DebugSession, suggested: IStartProfileArguments['termination'], ) { if (suggested) { const s = typeof suggested === 'string' ? { type: suggested } : suggested; return this.terminationConditions .find(t => t.id === s.type) ?.onPick(session, ...(s.args ?? [])); } const chosen = await this.pickWithLastDefault( localize('profile.termination.title', 'How long to run the profile:'), this.terminationConditions, this.lastChosenTermination, ); if (chosen) { this.lastChosenTermination = chosen.label; } return chosen?.onPick(session); } private async pickWithLastDefault< T extends { label: string; description?: string; sortOrder?: number }, >(title: string, items: ReadonlyArray<T>, lastLabel?: string): Promise<T | undefined> { if (items.length <= 1) { return items[0]; // first T or undefined } const quickpick = vscode.window.createQuickPick(); quickpick.title = title; quickpick.items = items .slice() .sort((a, b) => { if (a.label === lastLabel || b.label === lastLabel) { return a.label === lastLabel ? -1 : 1; } return (a.sortOrder ?? 0) - (b.sortOrder ?? 0); }) .map(ctor => ({ label: ctor.label, description: ctor.description, alwaysShow: true })); const chosen = await new Promise<string | undefined>(resolve => { quickpick.onDidAccept(() => resolve(quickpick.selectedItems[0]?.label)); quickpick.onDidHide(() => resolve(undefined)); quickpick.show(); }); quickpick.dispose(); if (!chosen) { return; } return items.find(c => c.label === chosen); } }
the_stack
import React, { CSSProperties, useRef, useCallback, useEffect, useState, } from 'react' import { boostHubWebViewUserAgent, boostHubPreloadUrl } from '../lib/boosthub' import { WebviewTag, DidNavigateEvent, IpcMessageEvent, DidNavigateInPageEvent, NewWindowEvent, WillNavigateEvent, } from 'electron' import { useEffectOnce } from 'react-use' import { openNew } from '../lib/platform' import { openContextMenu, openExternal, openNewWindow, signInBroadcast, addIpcListener, removeIpcListener, sendIpcMessage, signOutBroadcast, } from '../lib/electronOnly' import { DidFailLoadEvent, IpcRendererEvent } from 'electron/main' import styled from '../design/lib/styled' import { boostHubBaseUrl } from '../cloud/lib/consts' import Button from '../design/components/atoms/Button' export interface WebviewControl { focus(): void reload(): void goBack(): void goForward(): void openDevTools(): void sendMessage(channel: string, ...args: any[]): void } interface BoostHubWebviewProps { src: string style?: CSSProperties className?: string controlRef?: React.MutableRefObject<WebviewControl | undefined> onDidNavigate?: (event: DidNavigateEvent) => void onDidNavigateInPage?: (event: DidNavigateInPageEvent) => void } const BoostHubWebview = ({ src, style, className, controlRef, onDidNavigate, }: BoostHubWebviewProps) => { const webviewRef = useRef<WebviewTag>(null) const domReadyRef = useRef<boolean>(false) const [connectionErrorOccurred, setConnectionErrorOccurred] = useState(false) const reload = useCallback(() => { webviewRef.current!.reload() }, []) const goBack = useCallback(() => { webviewRef.current!.goBack() }, []) const goForward = useCallback(() => { webviewRef.current!.goForward() }, []) const openDevTools = useCallback(() => { webviewRef.current!.openDevTools() }, []) const sendMessage = useCallback((channel: string, ...args: any[]) => { webviewRef.current!.send(channel, ...args) }, []) const focus = useCallback(() => { webviewRef.current!.focus() }, []) useEffect(() => { if (controlRef == null) { return } controlRef.current = { focus, reload, goBack, goForward, openDevTools, sendMessage, } }, [controlRef, reload, goBack, goForward, openDevTools, sendMessage, focus]) useEffect(() => { const webview = webviewRef.current! const willNavigateEventListener = async (event: WillNavigateEvent) => { if (!new URL(event.url).href.startsWith(boostHubBaseUrl)) { openExternal(event.url) } } const newWindowEventListener = async (event: NewWindowEvent) => { if (!new URL(event.url).href.startsWith(boostHubBaseUrl)) { openExternal(event.url) } } webview.addEventListener('will-navigate', willNavigateEventListener) webview.addEventListener('new-window', newWindowEventListener) return () => { webview.removeEventListener('will-navigate', willNavigateEventListener) webview.removeEventListener('new-window', newWindowEventListener) } }, []) useEffect(() => { const webview = webviewRef.current! if (onDidNavigate == null) { return } webview.addEventListener('did-navigate', onDidNavigate) return () => { webview.removeEventListener('did-navigate', onDidNavigate) } }, [onDidNavigate]) useEffect(() => { const webview = webviewRef.current! const onDidFailLoad = (event: DidFailLoadEvent) => { console.warn('did fail load', event) if (event.errorDescription !== 'ERR_CONNECTION_REFUSED') { return } setConnectionErrorOccurred(true) } webview.addEventListener('did-fail-load', onDidFailLoad) return () => { webview.removeEventListener('did-fail-load', onDidFailLoad) } }, []) useEffectOnce(() => { const webview = webviewRef.current! if (webview == null) { return } const reloadIpcEventHandler = () => { webview.reload() } const forceReloadIpcEventHandler = () => { webview.reloadIgnoringCache() } const toggleDevToolsIpcEventHandler = () => { if (webview.isDevToolsOpened()) { webview.closeDevTools() } else { webview.openDevTools() } } addIpcListener('reload', reloadIpcEventHandler) addIpcListener('force-reload', forceReloadIpcEventHandler) addIpcListener('toggle-dev-tools', toggleDevToolsIpcEventHandler) const newDocIpcEventHandler = () => { webview.send('new-doc') } const searchIpcEventHandler = () => { webview.send('search') } const toggleSettingsIpcEventHandler = () => { webview.send('toggle-settings') } const saveAsIpcEventHandler = () => { webview.send('save-as') } const applyBoldStyleIpcEventHandler = () => { webview.send('apply-bold-style') } const applyItalicStyleIpcEventHandler = () => { webview.send('apply-italic-style') } const focusEditorIpcEventHandler = () => { webview.send('focus-editor') } const focusTitleIpcEventHandler = () => { webview.send('focus-title') } const togglePreviewModeIpcEventHandler = () => { webview.send('toggle-preview-mode') } const toggleSplitEditModeIpcEventHandler = () => { webview.send('toggle-split-edit-mode') } const switchSpaceIpcEventHandler = ( _event: IpcRendererEvent, index: number ) => { webview.send('switch-space', index) } const openBoostNoteUrlIpcEventHandler = ( _event: IpcRendererEvent, index: number ) => { webview.send('open-boostnote-url', index) } addIpcListener('new-doc', newDocIpcEventHandler) addIpcListener('search', searchIpcEventHandler) addIpcListener('toggle-settings', toggleSettingsIpcEventHandler) addIpcListener('save-as', saveAsIpcEventHandler) addIpcListener('apply-bold-style', applyBoldStyleIpcEventHandler) addIpcListener('apply-italic-style', applyItalicStyleIpcEventHandler) addIpcListener('focus-editor', focusEditorIpcEventHandler) addIpcListener('focus-title', focusTitleIpcEventHandler) addIpcListener('toggle-preview-mode', togglePreviewModeIpcEventHandler) addIpcListener('toggle-split-edit-mode', toggleSplitEditModeIpcEventHandler) addIpcListener('switch-space', switchSpaceIpcEventHandler) addIpcListener('open-boostnote-url', openBoostNoteUrlIpcEventHandler) return () => { removeIpcListener('reload', reloadIpcEventHandler) removeIpcListener('force-reload', forceReloadIpcEventHandler) removeIpcListener('toggle-dev-tools', toggleDevToolsIpcEventHandler) removeIpcListener('new-doc', newDocIpcEventHandler) removeIpcListener('search', searchIpcEventHandler) removeIpcListener('toggle-settings', toggleSettingsIpcEventHandler) removeIpcListener('save-as', saveAsIpcEventHandler) removeIpcListener('apply-bold-style', applyBoldStyleIpcEventHandler) removeIpcListener('apply-italic-style', applyItalicStyleIpcEventHandler) removeIpcListener('focus-editor', focusEditorIpcEventHandler) removeIpcListener('focus-title', focusTitleIpcEventHandler) removeIpcListener('toggle-preview-mode', togglePreviewModeIpcEventHandler) removeIpcListener( 'toggle-split-edit-mode', toggleSplitEditModeIpcEventHandler ) removeIpcListener('switch-space', switchSpaceIpcEventHandler) removeIpcListener('open-boostnote-url', openBoostNoteUrlIpcEventHandler) } }) useEffectOnce(() => { const webview = webviewRef.current! const ipcMessageEventHandler = (event: IpcMessageEvent) => { switch (event.channel) { // Discard after v0.23: sign-in-page-load is for smooth migration from <= v0.22 to v0.23 case 'sign-in-page-load': const preferences = localStorage.getItem( 'note.boostio.co:preferences' ) if (preferences == null) { return } const parsedPreferences = JSON.parse(preferences) const accessToken = parsedPreferences['cloud.user']?.accessToken if (accessToken != null) { webview.send('sign-in-via-access-token', accessToken) } localStorage.setItem( 'backup:note.boostio.co:preferences', preferences ) localStorage.removeItem('note.boostio.co:preferences') return case 'new-window': const urlToOpen = event.args[0] if (typeof urlToOpen !== 'string') { console.warn( 'The first argument of new-window event must be a string.' ) return } if (urlToOpen.startsWith(process.env.BOOST_HUB_BASE_URL!)) { openNewWindow(urlToOpen) } else { openExternal(urlToOpen) } break case 'open-external-url': const [url] = event.args openExternal(url) break case 'open-context-menu': openContextMenu({ menuItems: [ { type: 'normal', label: 'Back', click: goBack, }, { type: 'normal', label: 'Forward', click: goForward, }, { type: 'normal', label: 'Reload', click: reload, }, { type: 'separator', }, { type: 'submenu', label: 'Other Actions', submenu: [ { type: 'normal', label: 'Go To Desktop Home Page', click: () => { webview.loadURL(src) }, }, { type: 'normal', label: 'Open Dev Tools', click: openDevTools, }, { type: 'normal', label: 'Hard Reload (Ignore Cache)', click: () => { webview.reloadIgnoringCache() }, }, ], }, { type: 'separator', }, { type: 'normal', label: 'Sign Out', }, ], }) break case 'sign-out-event': signOutBroadcast() break case 'sign-in-event': // broadcast to other windows that sign in event happened signInBroadcast(webview.getWebContentsId()) break case 'register-protocol': sendIpcMessage('register-protocol', []) break default: console.log('Unhandled ipc message event', event.channel, event.args) break } } webview.addEventListener('ipc-message', ipcMessageEventHandler) const newWindowEventHandler = (event: NewWindowEvent) => { event.preventDefault() openNew(event.url) } webview.addEventListener('new-window', newWindowEventHandler) const domReadyHandler = () => { domReadyRef.current = true } webview.addEventListener('dom-ready', domReadyHandler) return () => { webview.removeEventListener('ipc-message', ipcMessageEventHandler) webview.removeEventListener('new-window', newWindowEventHandler) webview.removeEventListener('dom-ready', domReadyHandler) } }) return ( <Container className={className} style={style}> {connectionErrorOccurred && ( <div className='connection-error'> <div className='connection-error__body'> <h1>Connection Refused</h1> <p> Cannot reach the server... Please check your internet connection. </p> <div> <Button onClick={() => { setConnectionErrorOccurred(false) reload() }} > Reload </Button> </div> </div> </div> )} <webview ref={webviewRef} src={src} tabIndex={-1} useragent={boostHubWebViewUserAgent} preload={boostHubPreloadUrl} webpreferences='contextIsolation=no' /> </Container> ) } export default BoostHubWebview const Container = styled.div` position: relative; width: 100%; height: 100%; & > webview { z-index: 0; position: absolute; width: 100%; height: 100%; top: 0; left: 0; right: 0; bottom: 0; } & > .connection-error { z-index: 1; position: absolute; width: 100%; height: 100%; top: 0; left: 0; right: 0; bottom: 0; background-color: #1e2024; color: #fff; font-family: ${({ theme }) => theme.fonts.family}; display: flex; justify-content: center; } .connection-error__body { max-width: 640px; padding: ${({ theme }) => theme.sizes.spaces.df}px; } `
the_stack
import { AbiItem, BurnDetails, ContractCall, getRenNetworkDetails, LockAndMintTransaction, Logger, MintChain, ChainStatic, RenNetwork, RenNetworkDetails, RenNetworkString, EventEmitterTyped, } from "@renproject/interfaces"; import { assertType, fromHex, Ox, payloadToABI, utilsWithChainNetwork, } from "@renproject/utils"; import BigNumber from "bignumber.js"; import * as ethers from "ethers"; import { JsonRpcFetchFunc, Web3Provider, ExternalProvider, } from "@ethersproject/providers"; import { EthereumConfig, renDevnet, renMainnet, renTestnet } from "./networks"; import { EthAddress, EthProvider, EthTransaction } from "./types"; import { addressIsValid, transactionIsValid, extractBurnDetails, findBurnByNonce, findMintBySigHash, getGatewayAddress, getTokenAddress, submitToEthereum, EthereumTransactionConfig, } from "./utils"; export const EthereumConfigMap = { [RenNetwork.Mainnet]: renMainnet, [RenNetwork.Testnet]: renTestnet, [RenNetwork.Devnet]: renDevnet, }; const isEthereumConfig = ( renNetwork: | RenNetwork | RenNetworkString | RenNetworkDetails | EthereumConfig, ): renNetwork is EthereumConfig => { return !!(renNetwork as EthereumConfig).addresses; }; const resolveNetwork = ( renNetwork?: | RenNetwork | RenNetworkString | RenNetworkDetails | EthereumConfig, ): EthereumConfig => { if (!renNetwork) { return EthereumConfigMap[RenNetwork.Mainnet]; } let networkConfig: EthereumConfig | undefined; if (renNetwork && isEthereumConfig(renNetwork)) { networkConfig = renNetwork; } else if (renNetwork) { const networkDetails = getRenNetworkDetails(renNetwork); if (EthereumConfigMap[networkDetails.name]) { networkConfig = EthereumConfigMap[networkDetails.name]; } } if (!networkConfig) { throw new Error( `Unrecognized network ${ typeof renNetwork === "string" ? renNetwork : renNetwork.name }.`, ); } return networkConfig; }; export type NetworkInput = | RenNetwork | RenNetworkString | RenNetworkDetails | EthereumConfig; export class EthereumBaseChain implements MintChain<EthTransaction, EthAddress, EthereumConfig> { public static chain = "Ethereum"; public chain = EthereumBaseChain.chain; public name = EthereumBaseChain.chain; public legacyName: MintChain["legacyName"] = "Eth"; public logRequestLimit: number | undefined = undefined; private logger: Logger | undefined; public static configMap: { [network in RenNetwork]?: EthereumConfig; } = EthereumConfigMap; public configMap: { [network in RenNetwork]?: EthereumConfig; } = EthereumConfigMap; public static utils = { resolveChainNetwork: resolveNetwork, addressIsValid, transactionIsValid, addressExplorerLink: ( address: EthAddress, network?: NetworkInput, ): string => `${ ( EthereumBaseChain.utils.resolveChainNetwork(network) || renMainnet ).etherscan }/address/${address}`, transactionExplorerLink: ( transaction: EthTransaction, network?: NetworkInput, ): string => `${ ( EthereumBaseChain.utils.resolveChainNetwork(network) || renMainnet ).etherscan }/tx/${transaction || ""}`, }; public utils = utilsWithChainNetwork( EthereumBaseChain.utils, () => this.renNetworkDetails, ); public provider: Web3Provider | undefined; public signer: ethers.Signer | undefined; public renNetworkDetails: EthereumConfig | undefined; public readonly getTokenContractAddress = async (asset: string) => { if (!this.provider || !this.renNetworkDetails) { throw new Error( `${this.name} object not initialized - must provide network to constructor.`, ); } return getTokenAddress(this.renNetworkDetails, this.provider, asset); }; public readonly getGatewayContractAddress = async (token: string) => { if (!this.provider || !this.renNetworkDetails) { throw new Error( `${this.name} object not initialized - must provide network to constructor.`, ); } const gatewayAddress = await getGatewayAddress( this.renNetworkDetails, this.provider, token, ); if (gatewayAddress === "0x0000000000000000000000000000000000000000") { throw new Error(`Asset not supported on mint-chain.`); } return gatewayAddress; }; constructor( web3Provider: EthProvider, renNetwork?: | RenNetwork | RenNetworkString | RenNetworkDetails | EthereumConfig, config: { logger?: Logger; } = {}, ) { if (web3Provider) { /* eslint-disable @typescript-eslint/no-explicit-any */ if ( (web3Provider as any).signer && (web3Provider as any).provider ) { this.provider = (web3Provider as any).provider; this.signer = (web3Provider as any).signer; } else { const provider = (web3Provider as any)._isProvider ? (web3Provider as any) : new ethers.providers.Web3Provider( web3Provider as ExternalProvider | JsonRpcFetchFunc, ); this.provider = provider; this.signer = provider.getSigner(); } } if (renNetwork) { this.renNetworkDetails = resolveNetwork(renNetwork); } this.logger = config.logger; } public withProvider = (web3Provider: EthProvider) => { if ((web3Provider as any).signer && (web3Provider as any).provider) { this.provider = (web3Provider as any).provider; this.signer = (web3Provider as any).signer; } else { const provider = (web3Provider as any)._isProvider ? (web3Provider as any) : new ethers.providers.Web3Provider( web3Provider as ExternalProvider | JsonRpcFetchFunc, ); this.provider = provider; this.signer = provider.getSigner(); } return this; }; /** * See [LockChain.initialize]. */ initialize = ( renNetwork: RenNetwork | RenNetworkString | RenNetworkDetails, ) => { this.renNetworkDetails = this.renNetworkDetails || EthereumConfigMap[getRenNetworkDetails(renNetwork).name]; if (!this.renNetworkDetails) { throw new Error( `Unable to set ${this.name} network for RenVM network ${ getRenNetworkDetails(renNetwork).name }. Please provide ${this.name} network details to ${ this.name } constructor.`, ); } return this; }; // Supported assets assetIsNative = (asset: string): boolean => { return asset === "ETH"; }; /** * `assetIsSupported` should return true if the asset is native to the * MintChain. * * ```ts * ethereum.assetIsSupported = asset => asset === "ETH"; * ``` */ assetIsSupported = async (asset: string): Promise<boolean> => { if (this.assetIsNative(asset)) { return true; } if (!this.provider || !this.renNetworkDetails) { throw new Error( `${this.name} object not initialized - must provide network to constructor.`, ); } // Check that there's a gateway contract for the asset. try { return !!(await this.getGatewayContractAddress(asset)); } catch (error) { if ( /(Empty address returned)|(Asset not supported on mint-chain)/.exec( String((error || {}).message), ) ) { // Ignore } else { console.warn(error); } return false; } }; /** * `assetDecimals` should return the number of decimals of the asset. * * If the asset is not supported, an error should be thrown. * */ assetDecimals = async (asset: string): Promise<number> => { if (!this.provider) { throw new Error( `${this.name} object not initialized - must provide network to constructor.`, ); } if (asset === "ETH") { return 18; } const tokenAddress = await this.getTokenContractAddress(asset); const decimalsABI: AbiItem = { constant: true, inputs: [], name: "decimals", outputs: [ { internalType: "uint256", name: "", type: "uint256", }, ], payable: false, stateMutability: "view", type: "function", }; const tokenContract = new ethers.Contract( tokenAddress, [decimalsABI], this.provider, ); const decimalsRaw = await tokenContract.decimals(); return new BigNumber(decimalsRaw.toString()).toNumber(); }; transactionID = (transaction: EthTransaction): string => { return transaction || ""; }; transactionIDFromRPCFormat = (txid: string | Buffer, txindex: string) => this.transactionID(this.transactionFromRPCFormat(txid, txindex)); transactionFromRPCFormat = (txid: string | Buffer, _txindex: string) => Ox(txid); /** * @deprecated Renamed to `transactionFromRPCFormat`. * Will be removed in 3.0.0. */ transactionFromID = this.transactionFromRPCFormat; transactionConfidence = async ( transaction: EthTransaction, ): Promise<{ current: number; target: number }> => { if (!this.provider || !this.renNetworkDetails) { throw new Error( `${this.name} object not initialized - must provide network to constructor.`, ); } if (transaction === null) { throw new Error( `Unable to fetch transaction confidence, transaction hash is 'null'.`, ); } const currentBlock = new BigNumber( (await this.provider.getBlockNumber()).toString(), ); const receipt = await this.provider.getTransactionReceipt(transaction); let current = 0; if (receipt.blockNumber) { const transactionBlock = new BigNumber( receipt.blockNumber.toString(), ); current = currentBlock.minus(transactionBlock).plus(1).toNumber(); } return { current, target: this.renNetworkDetails.isTestnet ? 15 : 30, }; }; submitMint = async ( asset: string, contractCalls: ContractCall[], mintTx: LockAndMintTransaction, eventEmitter: EventEmitterTyped<{ transactionHash: [string]; confirmation: [number, { status: number }]; }>, ): Promise<EthTransaction> => { if (!mintTx.out) { throw new Error(`No signature passed to mint submission.`); } if (mintTx.out.revert !== undefined) { throw new Error(`Unable to submit reverted RenVM transaction.`); } if (!this.provider || !this.signer) { throw new Error( `${this.name} object not initialized - must provide network to constructor.`, ); } const existingTransaction = await this.findMint( asset, mintTx.out.nhash, mintTx.out.sighash, ); if (existingTransaction === "") { return ""; } else if (existingTransaction) { eventEmitter.emit("transactionHash", existingTransaction); eventEmitter.emit("confirmation", 1, { status: 1 }); return existingTransaction; } return await submitToEthereum( this.signer, contractCalls, mintTx, eventEmitter, ); }; findMint = async ( asset: string, nHash: Buffer, sigHash?: Buffer, ): Promise<EthTransaction | undefined> => { if (!this.renNetworkDetails || !this.provider) { throw new Error( `${this.name} object not initialized - must provide network to constructor.`, ); } return findMintBySigHash( this.renNetworkDetails, this.provider, asset, nHash, sigHash, this.logRequestLimit, ); }; resolveTokenGatewayContract = async (asset: string): Promise<string> => { if (!this.renNetworkDetails || !this.provider) { throw new Error( `${this.name} object not initialized - must provide network to constructor.`, ); } return Ox( await getTokenAddress(this.renNetworkDetails, this.provider, asset), ); }; /** * Read a burn reference from an Ethereum transaction - or submit a * transaction first if the transaction details have been provided. */ submitBurn = async ( _asset: string, eventEmitter: EventEmitterTyped<{ transactionHash: [string]; }>, contractCalls: ContractCall[], config: { networkDelay?: number } = {}, ): Promise<BurnDetails<EthTransaction>> => { if (!this.renNetworkDetails || !this.provider) { throw new Error( `${this.name} object not initialized - must provide network to constructor.`, ); } // Make a call to the provided contract and Pass on the // transaction hash. let transaction: EthTransaction | undefined; for (let i = 0; i < contractCalls.length; i++) { const contractCall = contractCalls[i]; const last = i === contractCalls.length - 1; const { contractParams, contractFn, sendTo } = contractCall; const callParams = [ ...(contractParams || []).map((value) => value.value), ]; const ABI = payloadToABI(contractFn, contractParams); const contract = new ethers.Contract(sendTo, ABI, this.signer); let txConfig = typeof contractCall === "object" ? (contractCall.txConfig as EthereumTransactionConfig) : {}; txConfig = { ...txConfig, ...{ value: txConfig && txConfig.value ? txConfig.value.toString() : undefined, gasPrice: txConfig && txConfig.gasPrice ? txConfig.gasPrice.toString() : undefined, }, }; if (this.logger) { this.logger.debug( "Calling Ethereum contract", contractFn, sendTo, ...callParams, txConfig, ); } const tx = await contract[contractFn](...callParams, txConfig); if (last) { eventEmitter.emit("transactionHash", tx.hash); } const receipt = await tx.wait(); transaction = receipt.transactionHash; if (this.logger) { this.logger.debug("Transaction hash", transaction); } } if (!transaction) { throw new Error(`Unable to find burn from provided parameters.`); } return extractBurnDetails( this.provider, transaction, this.logger, config.networkDelay, ); }; /** * Read a burn reference from an Ethereum transaction - or submit a * transaction first if the transaction details have been provided. */ findBurn = async ( asset: string, eventEmitter: EventEmitterTyped<{ transactionHash: [string]; }>, // Once of the following should not be undefined. transaction?: EthTransaction, burnNonce?: Buffer | string | number, config: { networkDelay?: number } = {}, ): Promise<BurnDetails<EthTransaction> | undefined> => { if (!this.renNetworkDetails || !this.provider) { throw new Error( `${this.name} object not initialized - must provide network to constructor.`, ); } if (!transaction && burnNonce) { return findBurnByNonce( this.renNetworkDetails, this.provider, asset, burnNonce.toString(), ); } if (!transaction) { return undefined; } eventEmitter.emit("transactionHash", transaction); return extractBurnDetails( this.provider, transaction, this.logger, config.networkDelay, ); }; getFees = async ( asset: string, ): Promise<{ burn: number; mint: number; }> => { if (!this.provider) { throw new Error( `${this.name} object not initialized - must provide network to constructor.`, ); } const gatewayAddress = await this.getGatewayContractAddress(asset); const mintFeeABI: AbiItem = { constant: true, inputs: [], name: "mintFee", outputs: [ { internalType: "uint16", name: "", type: "uint16", }, ], payable: false, stateMutability: "view", type: "function", }; const burnFeeABI: AbiItem = { constant: true, inputs: [], name: "burnFee", outputs: [ { internalType: "uint16", name: "", type: "uint16", }, ], payable: false, stateMutability: "view", type: "function", }; const gatewayContract = new ethers.Contract( gatewayAddress, [mintFeeABI, burnFeeABI], this.provider, ); const mintFee = await gatewayContract.mintFee(); const burnFee = await gatewayContract.burnFee(); return { mint: new BigNumber(mintFee.toString()).toNumber(), burn: new BigNumber(burnFee.toString()).toNumber(), }; }; public getBalance = async ( asset: string, address?: EthAddress, ): Promise<BigNumber> => { const balanceOfABI: AbiItem = { constant: true, inputs: [ { internalType: "address", name: "account", type: "address", }, ], name: "balanceOf", outputs: [ { internalType: "uint256", name: "", type: "uint256", }, ], payable: false, stateMutability: "view", type: "function", }; if (!this.provider) { throw new Error( `${this.name} object not initialized - must provide network to constructor.`, ); } const tokenAddress = await this.getTokenContractAddress(asset); const tokenContract = new ethers.Contract( tokenAddress, [balanceOfABI], this.provider, ); const balanceRaw = await await tokenContract.balanceOf(address); return new BigNumber(balanceRaw.toString()); }; transactionRPCFormat = (transaction: EthTransaction, _v2?: boolean) => { assertType<string | null>("string | null", { transaction }); if (transaction === null) { throw new Error( `Unable to encode transaction, transaction hash is 'null'.`, ); } return { txid: fromHex(transaction), txindex: "0", }; }; transactionRPCTxidFromID = (transactionID: string): Buffer => fromHex(transactionID); } const _: ChainStatic<EthTransaction, EthAddress, EthereumConfig> = EthereumBaseChain;
the_stack
import * as sinon from "sinon"; import * as assert from "assert"; import * as util from "util"; import { State, Player } from "./Schema"; import { MapSchema, type, Schema, filterChildren, SchemaDefinition, ArraySchema } from "../src"; describe("MapSchema Tests", () => { it("should allow to pre-populate a Map", () => { const state = new State(); state.mapOfPlayers = new MapSchema<Player>({ jake: new Player("Jake"), katarina: new Player("Katarina"), }); const decodedState = new State(); decodedState.decode(state.encode()); assert.deepEqual(Array.from(decodedState.mapOfPlayers.keys()), ['jake', 'katarina']); }); it("forEach()", () => { const map = new MapSchema<number>(); map.set('one', 1); map.set('two', 2); map.set('three', 3); const keys = []; const values = []; map.forEach((value, key) => { keys.push(key); values.push(value); }); assert.deepEqual(keys, ['one', 'two', 'three']); assert.deepEqual(values, [1, 2, 3]); }); it("should allow to clear a Map", () => { const state = new State(); state.mapOfPlayers = new MapSchema(); state.mapOfPlayers.set("one", new Player().assign({ name: "Jake", x: 0, y: 0 })) state.mapOfPlayers.set("two", new Player().assign({ name: "Katarina", x: 1, y: 1 })) const decodedState = new State(); decodedState.decode(state.encode()); assert.strictEqual(2, decodedState.mapOfPlayers.size); state.mapOfPlayers.clear(); decodedState.decode(state.encode()); assert.strictEqual(0, decodedState.mapOfPlayers.size); }); it("should allow to CLEAR and ADD in the same patch", () => { const state = new State(); state.mapOfPlayers = new MapSchema(); state.mapOfPlayers.set("one", new Player().assign({ name: "Jake", x: 0, y: 0 })) state.mapOfPlayers.set("two", new Player().assign({ name: "Katarina", x: 1, y: 1 })) const decodedState = new State(); decodedState.decode(state.encode()); state.mapOfPlayers.clear(); state.mapOfPlayers.set("three", new Player().assign({ name: "Three", x: 10, y: 10 })); decodedState.decode(state.encode()); assert.deepEqual({ mapOfPlayers: { three: { name: "Three", x: 10, y: 10 } } }, state.toJSON()); }); it("should allow to CLEAR and REPLACE in the same patch", () => { const state = new State(); state.mapOfPlayers = new MapSchema(); state.mapOfPlayers.set("one", new Player().assign({ name: "Jake", x: 0, y: 0 })) state.mapOfPlayers.set("two", new Player().assign({ name: "Katarina", x: 1, y: 1 })) const decodedState = new State(); decodedState.decode(state.encode()); state.mapOfPlayers.clear(); state.mapOfPlayers.set("two", new Player().assign({ name: "Jake again", x: 10, y: 10 })); decodedState.decode(state.encode()); assert.deepEqual({ mapOfPlayers: { two: { name: "Jake again", x: 10, y: 10 } } }, state.toJSON()); }); it("should allow to clear a Map while using filters", () => { class Player extends Schema { @type("number") x: number; @type("number") y: number; } class State extends Schema { @filterChildren(function(client, key: string, value: Player, root: State) { return client.sessionId === key; }) @type({ map: Player }) map = new Map<string, Player>(); } const state = new State(); state.map.set("one", new Player().assign({ x: 1, y: 1 })); state.map.set("two", new Player().assign({ x: 2, y: 2 })); state.map.set("three", new Player().assign({ x: 3, y: 3 })); const client1 = { sessionId: "one" }; const client2 = { sessionId: "two" }; const client3 = { sessionId: "three" }; const decoded1 = new State(); const decoded2 = new State(); const decoded3 = new State(); let encoded = state.encode(undefined, undefined, true); let encoded1 = state.applyFilters(client1); let encoded2 = state.applyFilters(client2); let encoded3 = state.applyFilters(client3); decoded1.decode(encoded1); assert.strictEqual(decoded1.map.size, 1); assert.strictEqual(decoded1.map.get("one").x, 1); decoded2.decode(encoded2); assert.strictEqual(decoded2.map.size, 1); assert.strictEqual(decoded2.map.get("two").x, 2); decoded3.decode(encoded3); assert.strictEqual(decoded3.map.size, 1); assert.strictEqual(decoded3.map.get("three").x, 3); // discard previous changes state.discardAllChanges(); // clear map state.map.clear(); encoded = state.encode(undefined, undefined, true); encoded1 = state.applyFilters(client1); encoded2 = state.applyFilters(client2); encoded3 = state.applyFilters(client3); decoded1.decode(encoded1); assert.strictEqual(decoded1.map.size, 0); decoded2.decode(encoded2); assert.strictEqual(decoded2.map.size, 0); decoded3.decode(encoded3); assert.strictEqual(decoded3.map.size, 0); }); it("should not consider changes after removing from the change tree", () => { class Item extends Schema { @type("number") price: number; constructor (price: number) { super(); this.price = price; } } class Inventory extends Schema { @type({ map: Item }) slots = new MapSchema<Item>(); } class Player extends Schema { @type("string") name: string; @type(Inventory) inventory = new Inventory(); @type(Inventory) purchase = new Inventory(); } class State extends Schema { @type({map: Player}) players = new MapSchema<Player>(); } const state = new State(); const playerOne = new Player(); state.players['one'] = playerOne; playerOne.name = "One!"; playerOne.inventory.slots['one'] = new Item(100); playerOne.inventory.slots['two'] = new Item(100); playerOne.inventory.slots['three'] = new Item(100); state.encodeAll(); const playerTwo = new Player(); state.players['two'] = playerTwo playerTwo.name = "Two!"; delete state.players['two']; playerTwo.name = "Hello"; playerTwo.purchase.slots['one'] = new Item(500); playerTwo.purchase.slots['two'] = new Item(500); playerTwo.purchase.slots['three'] = new Item(500); state.encode(); playerTwo.name = "Hello"; playerTwo.purchase.slots['one'] = new Item(500); playerTwo.purchase.slots['two'] = new Item(500); playerTwo.purchase.slots['three'] = new Item(500); state.encode(); const decodedState = new State(); decodedState.decode(state.encodeAll()); }); it("should allow to remove and set an item in the same place", () => { const state = new State(); state.mapOfPlayers = new MapSchema<Player>(); state.mapOfPlayers['one'] = new Player("Jake"); state.mapOfPlayers['two'] = new Player("Katarina"); const decodedState = new State(); let encoded = state.encode(); decodedState.decode(encoded); assert.strictEqual(decodedState.mapOfPlayers['one'].name, "Jake"); assert.strictEqual(decodedState.mapOfPlayers['two'].name, "Katarina"); state.discardAllChanges(); delete state.mapOfPlayers['one']; state.mapOfPlayers['one'] = new Player("Jake 2"); encoded = state.encode(); decodedState.decode(encoded); state.discardAllChanges(); assert.strictEqual(decodedState.mapOfPlayers['one'].name, "Jake 2"); assert.strictEqual(decodedState.mapOfPlayers['two'].name, "Katarina"); delete state.mapOfPlayers['two']; state.mapOfPlayers['two'] = new Player("Katarina 2"); encoded = state.encode(); decodedState.decode(encoded); assert.strictEqual(decodedState.mapOfPlayers['one'].name, "Jake 2"); assert.strictEqual(decodedState.mapOfPlayers['two'].name, "Katarina 2"); }); it("should allow map of primitive types", () => { class Player extends Schema { @type({ map: "number" }) mapOfNumbers = new MapSchema<number>(); } class State extends Schema { @type({ map: Player }) mapOfPlayers = new MapSchema<Player>(); } const state = new State(); state.mapOfPlayers['one'] = new Player(); state.mapOfPlayers['one'].mapOfNumbers['2'] = 2; state.mapOfPlayers['one'].mapOfNumbers['3'] = 3; const decodedState = new State(); decodedState.decode(state.encode()); assert.deepEqual(decodedState.toJSON(), { mapOfPlayers: { one: { mapOfNumbers: { 2: 2, 3: 3 } } } }); }); it("removing items should have as very few bytes", () => { const state = new State(); state.mapOfPlayers = new MapSchema<Player>(); state.mapOfPlayers['one'] = new Player("Jake"); state.mapOfPlayers['two'] = new Player("Katarina"); state.mapOfPlayers['three'] = new Player("Tarquinn"); state.mapOfPlayers['four'] = new Player("Snake"); state.encode(); delete state.mapOfPlayers['one']; delete state.mapOfPlayers['two']; delete state.mapOfPlayers['three']; delete state.mapOfPlayers['four']; const encoded = state.encode(); // TODO: we could get lower than that. assert.ok(encoded.length <= 12); }); it("should not encode item if added and removed at the same patch", () => { const state = new State(); state.mapOfPlayers = new MapSchema<Player>(); state.mapOfPlayers['one'] = new Player("Jake", 10, 10); const decodedState = new State(); decodedState.mapOfPlayers = new MapSchema<Player>(); decodedState.mapOfPlayers.onAdd = function(item, key) {}; decodedState.mapOfPlayers.onRemove = function(item, key) {}; const onRemoveSpy = sinon.spy(decodedState.mapOfPlayers, 'onRemove'); decodedState.decode(state.encode()); state.mapOfPlayers['one'].x++; state.mapOfPlayers['two'] = new Player("Snake", 10, 10); delete state.mapOfPlayers['two']; const patchBytes = state.encode(); // // TODO: improve me! `DELETE` operation should not be encoded here. // this test conflicts with encodeAll() + encode() for other structures, where DELETE operation is necessary. // // assert.deepEqual([ 4, 1, 0, 1, 11, 193 ], patchBytes); // decodedState.decode(patchBytes); sinon.assert.notCalled(onRemoveSpy); state.mapOfPlayers['one'].x++; delete state.mapOfPlayers['one']; decodedState.decode(state.encode()); sinon.assert.calledOnce(onRemoveSpy); }); it("should consider the field of map schema value change.", (done) => { class Player extends Schema { @type("string") id:string @type("string") name: string; @type('uint16') age:number; @type("string") next: string; constructor(id:string){ super() this.id = id; } } class State extends Schema { @type({ map: Player }) players = new MapSchema<Player>(); } const state = new State(); const decodeState = new State() const playerOne = new Player("76355"); state.players[playerOne.id] = playerOne; playerOne.name = "Player One!"; playerOne.age = 100; playerOne.next = playerOne.id;//1->1; decodeState.decode(state.encode()); const playerTwo = new Player("8848"); state.players[playerTwo.id] = playerTwo playerTwo.name = "Player Two!"; playerTwo.age = 200; playerOne.next = playerTwo.id;//1->2; playerTwo.next = playerOne.id;//2->1; decodeState.decode(state.encode()); const playerThree = new Player("8658"); state.players[playerThree.id] = playerThree playerThree.name = "Player Three!"; playerThree.age = 300; playerOne.next = playerTwo.id;//1->2; playerTwo.next = playerThree.id;//2->3 playerThree.next = playerOne.id;//3->1 decodeState.decode(state.encode()); assert.strictEqual(decodeState.players['76355'].next,'8848');//1->2 assert.strictEqual(decodeState.players['8848'].next,'8658');//2->3 assert.strictEqual(decodeState.players['8658'].next,'76355')//3->1 done(); }); it("should iterate though map values", () => { const map = new MapSchema<number>(); map.set("one", 1); map.set("two", 2); map.set("three", 3); map.set("four", 4); map.set("five", 5); const keys: string[] = []; const values: number[] = []; for (const key of map.keys()) { keys.push(key); } for (const num of map.values()) { values.push(num); } assert.deepEqual(['one', 'two', 'three', 'four', 'five'], keys); assert.deepEqual([1, 2, 3, 4, 5], values); }); it("should allow adding and removing same key multiple times", () => { class Action extends Schema { @type("string") type: string; } class Entity extends Schema { @type("number") id: number; @type(Action) action: Action; } class Item extends Entity { @type("number") damage: number; } class Player extends Entity { @type("number") hp: number; } class State extends Schema { @type(["number"]) grid = new ArraySchema<number>(); @type({ map: Entity }) entities = new MapSchema<Entity>(); } const state = new State(); state.grid.push(0, 1, 0, 1, 0, 1, 0, 1, 0); const decodedState = new State(); decodedState.decode(state.encode()); state.entities.set("item1", new Item().assign({ id: 1, damage: 10 })); state.entities.set("item2", new Item().assign({ id: 2, damage: 20 })); state.entities.set("item3", new Item().assign({ id: 3, damage: 20 })); state.entities.set("item4", new Item().assign({ id: 4, damage: 20 })); state.entities.set("item5", new Item().assign({ id: 5, damage: 20 })); state.entities.set("item6", new Item().assign({ id: 6, damage: 20 })); state.entities.set("item7", new Item().assign({ id: 7, damage: 20 })); state.entities.set("item8", new Item().assign({ id: 8, damage: 20 })); state.entities.set("item9", new Item().assign({ id: 9, damage: 20 })); state.entities.set("player1", new Player().assign({ id: 10, hp: 100 })); decodedState.decode(state.encode()); state.entities.delete("item1"); state.entities.delete("player1"); decodedState.decode(state.encode()); const decodedState2 = new State(); state.entities.set("player1", new Player().assign({ id: 3, hp: 100 })); decodedState2.decode(state.encodeAll()); state.entities.delete("item2"); const encodedPatch = state.encode(); decodedState.decode(encodedPatch); decodedState2.decode(encodedPatch); assert.strictEqual(false, decodedState2.entities.has("item1"), "'item1' should've been deleted."); assert.strictEqual(false, decodedState2.entities.has("item2"), "'item2' should've been deleted."); }); it("should allow to move a key from one map to another", () => { class Entity extends Schema { @type("number") id: number; } class Item extends Entity { @type("number") damage: number; } class Player extends Entity { @type("number") hp: number; } class State extends Schema { @type({ map: Entity }) entities = new MapSchema<Entity>(); @type({ map: Entity }) items = new MapSchema<Entity>(); } const state = new State(); const decodedState = new State(); decodedState.decode(state.encodeAll()); state.entities.set("item1", new Item().assign({ id: 1, damage: 10 })); state.entities.set("item2", new Item().assign({ id: 2, damage: 20 })); state.entities.set("player1", new Player().assign({ id: 10, hp: 100 })); state.items.set("weapon", new Item().assign({ id: 3, damage: 999 }));; decodedState.decode(state.encode()); decodedState.entities.onAdd = function (item, key) {}; decodedState.entities.onChange = function (item, key) {} decodedState.entities.onRemove = function (item, key) {} const onEntityAddSpy = sinon.spy(decodedState.entities, 'onAdd'); decodedState.items.onAdd = function (item, key) {} decodedState.items.onChange = function (item, key) {} decodedState.items.onRemove = function (item, key) {} const onItemsChangeSpy = sinon.spy(decodedState.items, 'onChange'); const item1 = state.entities.get("item1"); const previousWeapon = state.items.get("weapon"); state.items.set("weapon", item1.clone()); state.entities.set("item3", previousWeapon); decodedState.decode(state.encode()); assert.deepEqual({ entities: { item1: { id: 1, damage: 10 }, item2: { id: 2, damage: 20 }, player1: { id: 10, hp: 100 }, item3: { id: 3, damage: 999 } }, items: { weapon: { id: 1, damage: 10 } } }, decodedState.toJSON()); sinon.assert.calledOnce(onEntityAddSpy); sinon.assert.calledOnce(onItemsChangeSpy); }); it("replacing MapSchema should trigger onRemove on previous items", () => { class State extends Schema { @type({ map: "number" }) numbers: MapSchema<number>; } const state = new State(); state.numbers = new MapSchema({ one: 1, two: 2, three: 3 }); const decodedState = new State(); decodedState.decode(state.encode()); decodedState.numbers.onRemove = function(num, i) {} const onRemove = sinon.spy(decodedState.numbers, 'onRemove'); state.numbers = new MapSchema({ four: 1, five: 2, six: 3 }); decodedState.decode(state.encode()); sinon.assert.callCount(onRemove, 3); }); it("should throw error trying to set null or undefined", () => { const map = new MapSchema<number>(); assert.throws(() => { map.set("key", undefined); }, /undefined/i); assert.throws(() => { map.set("key", null); }, /null/i); }) });
the_stack
import "mocha"; import chai from "chai"; import chaiAsPromised from "chai-as-promised"; import { createSandbox, match, SinonSandbox } from "sinon"; import dotenv from "dotenv"; import { AadManager } from "../../../../src/plugins/resource/apim/managers/aadManager"; import { v4 } from "uuid"; import { AssertConfigNotEmpty, InvalidAadObjectId, } from "../../../../src/plugins/resource/apim/error"; import { IRequiredResourceAccess } from "../../../../src/plugins/resource/apim/interfaces/IAadResource"; import { AadService } from "../../../../src/plugins/resource/apim/services/aadService"; import { IAadPluginConfig, IApimPluginConfig } from "../../../../src/plugins/resource/apim/config"; import { ApimPluginConfigKeys, TeamsToolkitComponent, } from "../../../../src/plugins/resource/apim/constants"; import { Lazy } from "../../../../src/plugins/resource/apim/utils/commonUtils"; import { aadMatcher, DefaultTestInput, DefaultTestOutput, mockAxios, MockAxiosInput, MockAxiosOutput, } from "./mock"; dotenv.config(); chai.use(chaiAsPromised); describe("AadManager", () => { describe("#provision()", () => { const sandbox = createSandbox(); afterEach(() => { sandbox.restore(); }); it("Create a new AAD", async () => { // Arrange const newAppName = "test-new-app-name"; const apimPluginConfig = buildApimPluginConfig(); const { aadManager, requestStub } = buildAadManager(sandbox); // Act await aadManager.provision(apimPluginConfig, newAppName); // Assert sandbox.assert.calledWithMatch(requestStub, aadMatcher.createAad); sandbox.assert.calledWithMatch(requestStub, aadMatcher.addSecret); sandbox.assert.neverCalledWithMatch(requestStub, aadMatcher.getAad); chai.assert.isNotEmpty(apimPluginConfig.apimClientAADObjectId); chai.assert.isNotEmpty(apimPluginConfig.apimClientAADClientId); chai.assert.isNotEmpty(apimPluginConfig.apimClientAADClientSecret); }); it("Use an existing AAD failed because of error object id", async () => { // Arrange const apimPluginConfig = buildApimPluginConfig(DefaultTestInput.aadObjectId.new); const { aadManager, requestStub } = buildAadManager(sandbox); // Act & Assert await chai .expect(aadManager.provision(apimPluginConfig, DefaultTestInput.aadDisplayName.new)) .to.be.rejectedWith(InvalidAadObjectId.message(DefaultTestInput.aadObjectId.new)); sandbox.assert.calledOnceWithMatch(requestStub, aadMatcher.getAad); }); it("Use an existing AAD, using existing secret", async () => { // Arrange const apimPluginConfig = buildApimPluginConfig( DefaultTestInput.aadObjectId.created, "test-secret" ); const { aadManager, requestStub } = buildAadManager(sandbox); // Act await aadManager.provision(apimPluginConfig, DefaultTestInput.aadDisplayName.new); // Assert sandbox.assert.calledOnceWithMatch(requestStub, aadMatcher.getAad); chai.assert.equal( DefaultTestInput.aadObjectId.created, apimPluginConfig.apimClientAADObjectId ); chai.assert.equal(DefaultTestOutput.createAad.appId, apimPluginConfig.apimClientAADClientId); chai.assert.equal("test-secret", apimPluginConfig.apimClientAADClientSecret); }); it("Use an existing AAD, create new secret", async () => { // Arrange const apimPluginConfig = buildApimPluginConfig(DefaultTestInput.aadObjectId.created); const { aadManager, requestStub } = buildAadManager(sandbox); // Act await aadManager.provision(apimPluginConfig, DefaultTestInput.aadDisplayName.new); // Assert sandbox.assert.calledWithMatch(requestStub, aadMatcher.addSecret); sandbox.assert.calledWithMatch(requestStub, aadMatcher.getAad); sandbox.assert.neverCalledWithMatch(requestStub, aadMatcher.createAad); chai.assert.equal( DefaultTestInput.aadObjectId.created, apimPluginConfig.apimClientAADObjectId ); chai.assert.equal(DefaultTestOutput.getAad.appId, apimPluginConfig.apimClientAADClientId); chai.assert.equal( DefaultTestOutput.addSecret.secretText, apimPluginConfig.apimClientAADClientSecret ); }); }); describe("#postProvision()", () => { const sandbox = createSandbox(); afterEach(() => { sandbox.restore(); }); it("Add a existing scope and add a new redirect url", async () => { // Arrange const apimPluginConfig = buildApimPluginConfig(DefaultTestInput.aadObjectId.created); const aadPluginConfig = buildAadPluginConfig( "test-scope-client-id-created", "test-scope-id-created" ); const redirectUris = [`https://testredirect/${v4()}`]; const { aadManager, requestStub } = buildAadManager(sandbox, DefaultTestInput, { getAad: { id: "test-aad-object-id-created", appId: "test-aad-client-id-created", displayName: "test-aad-display-name-created", requiredResourceAccess: [ { resourceAppId: "test-scope-client-id-created", resourceAccess: [{ id: "test-scope-id-created", type: "Scope" }], }, ], web: { redirectUris: [], implicitGrantSettings: { enableIdTokenIssuance: true }, }, }, }); // Act await aadManager.postProvision(apimPluginConfig, aadPluginConfig, redirectUris); // Assert const updatedAadInfo = { web: { redirectUris: redirectUris, }, }; sandbox.assert.calledWithMatch(requestStub, aadMatcher.getAad); sandbox.assert.calledWithMatch( requestStub, aadMatcher.updateAad.and(aadMatcher.body(updatedAadInfo)) ); }); it("Add a new scope and existing redirect url", async () => { // Arrange const apimPluginConfig = buildApimPluginConfig(DefaultTestInput.aadObjectId.created); const aadPluginConfig = buildAadPluginConfig( "test-scope-client-id-created", "test-scope-id-new" ); const redirectUris = [`https://testredirect/${v4()}`]; const { aadManager, requestStub } = buildAadManager(sandbox, DefaultTestInput, { getAad: { id: "test-aad-object-id-created", appId: "test-aad-client-id-created", displayName: "test-aad-display-name-created", requiredResourceAccess: [ { resourceAppId: "test-scope-client-id-created", resourceAccess: [{ id: "test-scope-id-created", type: "Scope" }], }, ], web: { redirectUris: redirectUris, implicitGrantSettings: { enableIdTokenIssuance: false }, }, }, }); // Act await aadManager.postProvision(apimPluginConfig, aadPluginConfig, redirectUris); // Assert const updatedAadInfo = { requiredResourceAccess: [ { resourceAppId: "test-scope-client-id-created", resourceAccess: [ { id: "test-scope-id-created", type: "Scope" }, { id: "test-scope-id-new", type: "Scope" }, ], }, ], web: { implicitGrantSettings: { enableIdTokenIssuance: true }, }, }; sandbox.assert.calledWithMatch(requestStub, aadMatcher.getAad); sandbox.assert.calledWithMatch( requestStub, aadMatcher.updateAad.and(aadMatcher.body(updatedAadInfo)) ); }); it("Add existing scope and existing redirect url", async () => { // Arrange const apimPluginConfig = buildApimPluginConfig(DefaultTestInput.aadObjectId.created); const aadPluginConfig = buildAadPluginConfig( "test-scope-client-id-created", "test-scope-id-created" ); const redirectUris = [`https://testredirect/${v4()}`]; const { aadManager, requestStub } = buildAadManager(sandbox, DefaultTestInput, { getAad: { id: "test-aad-object-id-created", appId: "test-aad-client-id-created", displayName: "test-aad-display-name-created", requiredResourceAccess: [ { resourceAppId: "test-scope-client-id-created", resourceAccess: [{ id: "test-scope-id-created", type: "Scope" }], }, ], web: { redirectUris: redirectUris, implicitGrantSettings: { enableIdTokenIssuance: true }, }, }, }); // Act await aadManager.postProvision(apimPluginConfig, aadPluginConfig, redirectUris); // Assert sandbox.assert.calledOnceWithMatch(requestStub, aadMatcher.getAad); }); }); describe("#refreshRequiredResourceAccess()", () => { const sandbox = createSandbox(); afterEach(() => { sandbox.restore(); }); const testInput: { message: string; source: IRequiredResourceAccess[] | undefined; expected: IRequiredResourceAccess[] | undefined; }[] = [ { message: "Undefined source", source: undefined, expected: [{ resourceAppId: "0", resourceAccess: [{ id: "0", type: "Scope" }] }], }, { message: "Empty source", source: [], expected: [{ resourceAppId: "0", resourceAccess: [{ id: "0", type: "Scope" }] }], }, { message: "No existing client id", source: [{ resourceAppId: "1" }], expected: [ { resourceAppId: "1" }, { resourceAppId: "0", resourceAccess: [{ id: "0", type: "Scope" }] }, ], }, { message: "Existing client id and undefined resource access", source: [{ resourceAppId: "0" }], expected: [{ resourceAppId: "0", resourceAccess: [{ id: "0", type: "Scope" }] }], }, { message: "Existing client id and empty resource access", source: [{ resourceAppId: "0", resourceAccess: [] }], expected: [{ resourceAppId: "0", resourceAccess: [{ id: "0", type: "Scope" }] }], }, { message: "Existing client id and no scope id", source: [{ resourceAppId: "0", resourceAccess: [{ id: "1", type: "Scope" }] }], expected: [ { resourceAppId: "0", resourceAccess: [ { id: "1", type: "Scope" }, { id: "0", type: "Scope" }, ], }, ], }, { message: "Existing client id and existing scope id", source: [{ resourceAppId: "0", resourceAccess: [{ id: "0", type: "Scope" }] }], expected: undefined, }, ]; testInput.forEach((input) => { it(input.message, async () => { // Arrange const apimPluginConfig = buildApimPluginConfig(DefaultTestInput.aadObjectId.created); const aadPluginConfig = buildAadPluginConfig("0", "0"); const { aadManager, requestStub } = buildAadManager(sandbox, DefaultTestInput, { getAad: { requiredResourceAccess: input.source, }, }); // Act await aadManager.postProvision(apimPluginConfig, aadPluginConfig, []); // Assert sandbox.assert.calledWithMatch(requestStub, aadMatcher.getAad); if (input.expected) { sandbox.assert.calledWithMatch( requestStub, aadMatcher.updateAad.and( aadMatcher.body(match.has("requiredResourceAccess", input.expected)) ) ); } else { sandbox.assert.calledWithMatch(requestStub, aadMatcher.updateAad); sandbox.assert.neverCalledWithMatch( requestStub, aadMatcher.updateAad.and(match.has("requiredResourceAccess")) ); } }); }); }); describe("#refreshRedirectUri()", () => { const sandbox = createSandbox(); afterEach(() => { sandbox.restore(); }); const testInput: { message: string; source: string[] | undefined; added: string[]; expected: string[] | undefined; }[] = [ { message: "Undefined source", source: undefined, added: ["https://added-url"], expected: ["https://added-url"], }, { message: "Empty source", source: [], added: ["https://added-url"], expected: ["https://added-url"], }, { message: "No existing redirect uri", source: ["https://existing-url"], added: ["https://added-url"], expected: ["https://existing-url", "https://added-url"], }, { message: "Existing redirect uri", source: ["https://existing-url", "https://added-url"], added: ["https://added-url"], expected: undefined, }, { message: "Add multiple redirect uris", source: ["https://existing-url", "https://added-url"], added: ["https://added-url", "https://added-url-1"], expected: ["https://existing-url", "https://added-url", "https://added-url-1"], }, { message: "Not add uri", source: ["https://existing-url", "https://added-url"], added: [], expected: undefined, }, ]; testInput.forEach((input) => { it(input.message, async () => { // Arrange const apimPluginConfig = buildApimPluginConfig(DefaultTestInput.aadObjectId.created); const aadPluginConfig = buildAadPluginConfig("", ""); const { aadManager, requestStub } = buildAadManager(sandbox, DefaultTestInput, { getAad: { web: { redirectUris: input.source }, }, }); // Act await aadManager.postProvision(apimPluginConfig, aadPluginConfig, input.added); // Assert sandbox.assert.calledWithMatch(requestStub, aadMatcher.getAad); if (input.expected) { sandbox.assert.calledWithMatch( requestStub, aadMatcher.updateAad.and( aadMatcher.body(match.has("web", match.has("redirectUris", input.expected))) ) ); } else { sandbox.assert.calledWithMatch(requestStub, aadMatcher.updateAad); sandbox.assert.neverCalledWithMatch( requestStub, aadMatcher.updateAad.and(match.has("web", match.has("redirectUris"))) ); } }); }); }); }); function buildAadManager( sandbox: SinonSandbox, mockInput?: MockAxiosInput, mockOutput?: MockAxiosOutput ): { aadManager: AadManager; requestStub: any; } { const res = mockAxios(sandbox, mockInput, mockOutput); const requestStub = res.requestStub; const axiosInstance = res.axiosInstance; const lazyAadService = new Lazy( async () => new AadService(axiosInstance, undefined, undefined, 2) ); const aadManager = new AadManager(lazyAadService); return { aadManager: aadManager, requestStub: requestStub }; } function buildApimPluginConfig(objectId?: string, clientSecret?: string): IApimPluginConfig { return { apimClientAADObjectId: objectId, apimClientAADClientSecret: clientSecret, checkAndGet(key: string): string { let res: string | undefined = undefined; if (key === ApimPluginConfigKeys.apimClientAADObjectId) { res = objectId; } else if (key === ApimPluginConfigKeys.apimClientAADClientSecret) { res = clientSecret; } return AssertConfigNotEmpty(TeamsToolkitComponent.ApimPlugin, key, res, "dev"); }, }; } function buildAadPluginConfig(clientId: string, scopeId: string): IAadPluginConfig { return { objectId: "", clientId: clientId, oauth2PermissionScopeId: scopeId, applicationIdUris: "", }; }
the_stack
import { FormKitNode, FormKitMessage, createMessage } from '@formkit/core' import { FormKitObservedNode, createObserver, applyListeners, diffDeps, removeListeners, FormKitDependencies, isKilled, } from '@formkit/observer' import { has, empty, token, clone, cloneAny, eq } from '@formkit/utils' /** * Special validation properties that affect the way validations are applied. */ interface FormKitValidationHints { /** * If this validation fails, should it block the form from being submitted or * considered "valid"? There are some cases where it is acceptable to allow * an incorrect value to still be allowed to submit. */ blocking: boolean /** * Only run this rule after this many milliseconds of debounce. This is * particularity helpful for more "expensive" async validation rules like * checking if a username is taken from the backend. */ debounce: number /** * Normally the first validation rule to fail blocks other rules from running * if this flag is flipped to true, this rule will be run every time even if * a previous rule in the validation stack failed. */ force: boolean /** * Most validation rules are not run when the input is empty, but this flag * allows that behavior to be changed. */ skipEmpty: boolean /** * The actual name of the validation rule. */ name: string } /** * Defines what fully parsed validation rules look like. * @public */ export type FormKitValidation = { /** * The actual rule function that will be called */ rule: FormKitValidationRule /** * Arguments to be passed to the validation rule */ args: any[] /** * The debounce timer for this input. */ timer: number /** * The state of a validation, can be true, false, or null which means unknown. */ state: boolean | null /** * Determines if the rule should be considered for the next run cycle. This * does not mean the rule will be validated, it just means that it should be * considered. */ queued: boolean /** * Dependencies this validation rule is observing. */ deps: FormKitDependencies } & FormKitValidationHints /** * Defines what validation rules look like when they are parsed, but have not * necessarily had validation rules substituted in yet. * @public */ export type FormKitValidationIntent = [string | FormKitValidationRule, ...any[]] /** * Signature for a generic validation rule. It accepts an input, often a string * but validation rules should be able to accept any input type, and returns a * boolean indicating whether or not it passed validation. * @public */ export type FormKitValidationRule = { (node: FormKitNode, ...args: any[]): boolean | Promise<boolean> ruleName?: string } & Partial<FormKitValidationHints> /** * A validation rule result. * @public */ export interface FormKitValidationRuleResult { result: boolean validation: FormKitValidation } /** * FormKit validation rules are structured as on object of key/function pairs * where the key of the object is the validation rule name. * @public */ export interface FormKitValidationRules { [index: string]: FormKitValidationRule } /** * The interface for the localized validation message registry. * @public */ export interface FormKitValidationMessages { [index: string]: string | ((...args: FormKitValidationI18NArgs) => string) } /** * Determines the validation nonce. * @public */ interface FormKitValidationState { input: string | null rerun: number | null isPassing: boolean } /** * The arguments that are passed to the validation messages in the i18n plugin. * @public */ type FormKitValidationI18NArgs = [ { node: FormKitNode name: string args: any[] message?: string } ] /** * Message that gets set when the node is awaiting validation. */ const validatingMessage = createMessage({ type: 'state', blocking: true, visible: false, value: true, key: 'validating', }) /** * The actual validation plugin function, everything must be bootstrapped here. * @param node - The node to bind validation to. * @public */ export function createValidationPlugin(baseRules: FormKitValidationRules = {}) { return function validationPlugin(node: FormKitNode): void { const availableRules = Object.assign( {}, baseRules, node.props.validationRules as FormKitValidationRules ) // create an observed node let observedNode = createObserver(node) const state = { input: token(), rerun: null, isPassing: true } let validation = cloneAny(node.props.validation) // If the node's validation prop changes, update the rules: node.on('prop:validation', ({ payload: value }) => { if (eq(validation, value)) return validation = cloneAny(value) // Destroy all observers that may re-trigger validation on an old stack removeListeners(observedNode.receipts) // Remove all existing messages before re-validating node.store.filter(() => false, 'validation') node.props.parsedRules = parseRules(value, availableRules) observedNode.kill() observedNode = createObserver(node) validate(observedNode, node.props.parsedRules, state) }) // Validate the field when this plugin is initialized node.props.parsedRules = parseRules(validation, availableRules) validate(observedNode, node.props.parsedRules, state) } } /** * Given parsed validations, a value and a node, run the validations and set * the appropriate store messages on the node. * @param value - The value being validated * @param node - The Node this value belongs to * @param rules - The rules */ function validate( node: FormKitObservedNode, validations: FormKitValidation[], state: FormKitValidationState ) { if (isKilled(node)) return state.input = token() state.isPassing = true node.store.filter((message) => !message.meta.removeImmediately, 'validation') validations.forEach( (validation) => validation.debounce && clearTimeout(validation.timer) ) if (validations.length) { node.store.set(validatingMessage) run(0, validations, node, state, false, () => { node.store.remove(validatingMessage.key) }) } } /** * Runs validation rules recursively while collecting dependencies allowing for * cross-node validation rules that automatically re-trigger when a foreign * value is changed. * @param current - The index of the current validation rule * @param validations - The remaining validation rule stack to run * @param node - An observed node, the owner of this validation stack * @param state - An object of state information about this run * @param removeImmediately - Should messages created during this call be removed immediately when a new commit takes place? * @returns */ function run( current: number, validations: FormKitValidation[], node: FormKitObservedNode, state: FormKitValidationState, removeImmediately: boolean, complete: () => void ): void { const validation = validations[current] if (!validation) return complete() const currentRun = state.input validation.state = null function next(async: boolean, result: boolean | null): void { state.isPassing = state.isPassing && !!result validation.queued = false const newDeps = node.stopObserve() applyListeners(node, diffDeps(validation.deps, newDeps), () => { validation.queued = true if (state.rerun) clearTimeout(state.rerun) state.rerun = setTimeout( validate, 0, node, validations, state ) as unknown as number }) validation.deps = newDeps if (state.input === currentRun) { validation.state = result if (result === false) { createFailedMessage(node, validation, removeImmediately || async) } else { removeMessage(node, validation) } if (validations.length > current + 1) { run( current + 1, validations, node, state, removeImmediately || async, complete ) } else { // The validation has completed complete() } } } if ( (!empty(node.value) || !validation.skipEmpty) && (state.isPassing || validation.force) ) { if (validation.queued) { runRule(validation, node, (result: boolean | Promise<boolean>) => { result instanceof Promise ? result.then((r) => next(true, r)) : next(false, result) }) } else { // In this case our rule is not queued, so literally nothing happened that // would affect it, we just need to move past this rule and make no // modifications to state run(current + 1, validations, node, state, removeImmediately, complete) } } else { // This rule is not being run because either: // 1. The field is empty and this rule should not run when empty // 2. A previous validation rule is failing and this one is not forced // In this case we should call next validation. if (empty(node.value) && validation.skipEmpty && state.isPassing) { // This node has an empty value so its validation was skipped. So we // need to queue it up, we do that by starting an observation and just // touching the value attribute. node.observe() node.value } next(false, null) } } /** * Run a validation rule debounced or not. * @param validation - A validation to debounce */ function runRule( validation: FormKitValidation, node: FormKitObservedNode, after: (result: boolean | Promise<boolean>) => void ) { if (validation.debounce) { validation.timer = setTimeout(() => { node.observe() after(validation.rule(node, ...validation.args)) }, validation.debounce) as unknown as number } else { node.observe() after(validation.rule(node, ...validation.args)) } } /** * The messages given to this function have already been set on the node, but * any other validation messages on the node that are not included in this * stack should be removed because they have been resolved. * @param node - The node to operate on. * @param messages - A new stack of messages */ function removeMessage(node: FormKitNode, validation: FormKitValidation) { const key = `rule_${validation.name}` if (has(node.store, key)) { node.store.remove(key) } } /** * * @param value - The value that is failing * @param validation - The validation object */ function createFailedMessage( node: FormKitNode, validation: FormKitValidation, removeImmediately: boolean ): FormKitMessage { const i18nArgs: FormKitValidationI18NArgs = createI18nArgs(node, validation) const customMessage = createCustomMessage(node, validation, i18nArgs) // Here we short circuit the i18n system to force the output. const message = createMessage({ blocking: validation.blocking, key: `rule_${validation.name}`, meta: { /** * Use this key instead of the message root key to produce i18n validation * messages. */ messageKey: validation.name, /** * For messages that were created *by or after* a debounced or async * validation rule — we make note of it so we can immediately remove them * as soon as the next commit happens. */ removeImmediately, /** * Determines if this message should be passed to localization. */ localize: !customMessage, /** * The arguments that will be passed to the validation rules */ i18nArgs, }, type: 'validation', value: customMessage || 'This field is not valid.', }) node.store.set(message) return message } /** * Returns a custom validation message if applicable. * @param node - FormKit Node * @param validation - The validation rule being processed. */ function createCustomMessage( node: FormKitNode, validation: FormKitValidation, i18nArgs: FormKitValidationI18NArgs ): string | undefined { const customMessage = node.props.validationMessages && has(node.props.validationMessages, validation.name) ? node.props.validationMessages[validation.name] : undefined if (typeof customMessage === 'function') { return customMessage(...i18nArgs) } return customMessage } /** * Creates the arguments passed to the i18n * @param node - The node that performed the validation * @param validation - The validation that failed */ function createI18nArgs( node: FormKitNode, validation: FormKitValidation ): FormKitValidationI18NArgs { // If a custom message has been found, short circuit the i18n system. return [ { node, name: createMessageName(node), args: validation.args, }, ] } /** * The name used in validation messages. * @param node - The node to display * @returns */ function createMessageName(node: FormKitNode): string { if (typeof node.props.validationLabel === 'function') { return node.props.validationLabel(node) } return ( node.props.validationLabel || node.props.label || node.props.name || String(node.name) ) } /** * Describes hints, must also be changed in the debounceExtractor. */ const hintPattern = '(?:[\\*+?()0-9]+)' /** * A pattern to describe rule names. Rules names can only contain letters, * numbers, and underscores and must start with a letter. */ const rulePattern = '[a-zA-Z][a-zA-Z0-9_]+' /** * Regular expression for extracting rule data. */ const ruleExtractor = new RegExp( `^(${hintPattern}?${rulePattern})(?:\\:(.*)+)?$`, 'i' ) /** * Validation hints are special characters preceding a validation rule, like * !phone */ const hintExtractor = new RegExp(`^(${hintPattern})(${rulePattern})$`, 'i') /** * Given a hint string like ^(200)? or ^? or (200)?^ extract the hints to * matches. */ const debounceExtractor = /([\*+?]+)?(\(\d+\))([\*+?]+)?/ /** * Determines if a given string is in the proper debounce format. */ const hasDebounce = /\(\d+\)/ /** * The default values of the available validation hints. */ export const defaultHints: FormKitValidationHints = { blocking: true, debounce: 0, force: false, skipEmpty: true, name: '', } /** * Parse validation intents and strings into validation rule stacks. * @param validation - Either a string a validation rules, or proper array of structured rules. * @internal */ export function parseRules( validation: undefined | string | FormKitValidationIntent[], rules: FormKitValidationRules ): FormKitValidation[] { if (!validation) return [] const intents = typeof validation === 'string' ? extractRules(validation) : clone(validation) return intents.reduce((validations, args) => { let rule = args.shift() as string | FormKitValidationRule const hints = {} if (typeof rule === 'string') { const [ruleName, parsedHints] = parseHints(rule) if (has(rules, ruleName)) { rule = rules[ruleName] Object.assign(hints, parsedHints) } } if (typeof rule === 'function') { validations.push({ rule, args, timer: 0, state: null, queued: true, deps: new Map(), ...defaultHints, ...fnHints(hints, rule), }) } return validations }, [] as FormKitValidation[]) } /** * A string of validation rules written in FormKitRule notation. * @param validation - The string of rules * @internal */ function extractRules(validation: string): FormKitValidationIntent[] { return validation.split('|').reduce((rules, rule) => { const parsedRule = parseRule(rule) if (parsedRule) { rules.push(parsedRule) } return rules }, [] as FormKitValidationIntent[]) } /** * Given a rule like confirm:password_confirm produce a FormKitValidationIntent * @param rule - A string representing a validation rule. * @returns */ function parseRule(rule: string): FormKitValidationIntent | false { const trimmed = rule.trim() if (trimmed) { const matches = trimmed.match(ruleExtractor) if (matches && typeof matches[1] === 'string') { const ruleName = matches[1].trim() const args = matches[2] && typeof matches[2] === 'string' ? matches[2].split(',').map((s) => s.trim()) : [] return [ruleName, ...args] } } return false } /** * Given a rule name, detect if there are any additional hints like ! * @param ruleName - string representing a rule name * @returns */ function parseHints( ruleName: string ): [string, Partial<FormKitValidationHints>] { const matches = ruleName.match(hintExtractor) if (!matches) { return [ruleName, { name: ruleName }] } const map: { [index: string]: Partial<FormKitValidationHints> } = { '*': { force: true }, '+': { skipEmpty: false }, '?': { blocking: false }, } const [, hints, rule] = matches const hintGroups = hasDebounce.test(hints) ? hints.match(debounceExtractor) || [] : [, hints] return [ rule, [hintGroups[1], hintGroups[2], hintGroups[3]].reduce( (hints: Partial<FormKitValidationHints>, group: string | undefined) => { if (!group) return hints if (hasDebounce.test(group)) { hints.debounce = parseInt(group.substr(1, group.length - 1)) } else { group .split('') .forEach( (hint) => has(map, hint) && Object.assign(hints, map[hint]) ) } return hints }, { name: rule } as Partial<FormKitValidationHints> ), ] } /** * Extracts hint properties from the validation rule function itself and applies * them if they are not already in the set of validation hints extracted from * strings. * @param existingHints - An existing set of hints already parsed * @param rule - The actual rule function, which can contain hint properties * @returns */ function fnHints( existingHints: Partial<FormKitValidationHints>, rule: FormKitValidationRule ) { if (!existingHints.name) { existingHints.name = rule.ruleName || rule.name } return ['skipEmpty', 'force', 'debounce', 'blocking'].reduce( (hints: Partial<FormKitValidationHints>, hint: string) => { if (has(rule, hint) && !has(hints, hint)) { Object.assign(hints, { [hint]: rule[hint as keyof FormKitValidationHints], }) } return hints }, existingHints ) }
the_stack
import './hub.css'; // eslint-disable-next-line @typescript-eslint/no-var-requires const taskSvg = require('./task.svg'); import { VSMessage, ViewState} from '../common/vscode-api'; import { debounce } from 'debounce'; import {ResourceData} from '../../tekton-hub-client/api'; import { BaseWidget, Listener, Widget } from '../common/widget'; import { CollapsibleList, CollapsibleListState, ListWidget } from '../common/list-widget'; import { createDiv, createSpan } from '../common/dom-util'; import * as semver from 'semver'; import { HubTask, HubTaskInstallation, InstalledTask, isInstalledTask } from '../../hub/hub-common'; import { Loader } from '../common/loader'; import { dropDownForTags, enterEvent, hideList, initList, keyUpDown, listGroup } from './search_dropdown'; let installingButton; export class SearchInput { private inputListener: Listener<string> | undefined; constructor(private input: HTMLInputElement, private messageSender: VSMessage){ this.input.oninput = debounce(this.inputChange.bind(this)); } private inputChange(): void { if (this.inputListener) { this.inputListener(this.input.value); } } disable(): void { this.input.disabled = true; } get inputElement(): HTMLInputElement { return this.input; } onInputChange(listener: Listener<string>): void { this.inputListener = listener; } get value(): string { return this.input.value; } setValue(value: string): void { this.input.value = value; } } export class TaskItem extends BaseWidget { constructor(private task: HubTask, private messageSender: VSMessage, private loader: Loader, private viewType: string, private tknVersion?: string) { super(); this.element = createDiv('task-list-item'); const iconContainer = createDiv('icon-container'); this.element.appendChild(iconContainer); const image = document.createElement('img'); image.src = taskSvg; image.classList.add('icon'); iconContainer.appendChild(image); this.createDetails(); this.element.onclick = () => { try { this.task.view = this.viewType; this.messageSender.postMessage({type: 'openTaskPage', data: this.task}); } catch (err) { console.error(err); } } } private createDetails(): void { const details = createDiv('details'); this.element.appendChild(details); this.createHeader(details); this.createDescription(details); this.createFooter(details); } private createHeader(details: HTMLDivElement): void { const headerContainer = createDiv('header-container'); details.appendChild(headerContainer); const header = createDiv('header'); const name = createSpan('name'); name.innerText = this.task.latestVersion?.displayName ? this.task.latestVersion.displayName : this.task.name; header.appendChild(name); const version = createSpan('version'); version.innerText = this.task.latestVersion ? this.task.latestVersion.version : (this.task as InstalledTask).installedVersion.version; header.appendChild(version); const ratings = createSpan('ratings'); const star = createSpan('codicon', 'codicon-star-full'); ratings.appendChild(star); const count = createSpan('count'); count.innerText = this.task.rating.toString(); ratings.appendChild(count); header.appendChild(ratings); headerContainer.appendChild(header); } private createDescription(details: HTMLDivElement): void { const description = createDiv('description'); description.classList.add('ellipsis'); description.textContent = this.task.latestVersion ? this.task.latestVersion.description : (this.task as InstalledTask).installedVersion.description; details.appendChild(description); } private createFooter(details: HTMLDivElement): void { const footer = createDiv('footer'); const author = createDiv('author'); author.innerText = this.task.catalog.name; footer.appendChild(author); const actionBar = createDiv('list-action-bar'); const actionContainer = document.createElement('ul'); actionContainer.classList.add('actions-container'); this.addIsClusterTask(actionContainer); if (this.tknVersion){ this.addVersionCheck(actionContainer); } const installEl = document.createElement('li'); installEl.classList.add('action-item'); if (!(this.task as InstalledTask).installedVersion) { const installButton = document.createElement('a'); installButton.classList.add('action-label', 'codicon', 'extension-action', 'install'); installButton.textContent = 'Install'; installButton.onclick = (e) =>{ e.preventDefault(); e.stopPropagation(); if (installButton.textContent !== 'Install'){ return; } this.sendInstall(); installButton.textContent = 'Installing'; installingButton = installButton; }; installEl.appendChild(installButton); } actionContainer.appendChild(installEl); actionBar.appendChild(actionContainer); footer.appendChild(actionBar); details.appendChild(footer); } private sendInstall(): void { this.loader.show(); this.messageSender.postMessage({type: 'installTask', data: { url: this.task.latestVersion.rawURL, name: this.task.name, minPipelinesVersion: this.task.latestVersion.minPipelinesVersion, tknVersion: this.tknVersion, taskVersion: this.task.latestVersion, view: this.viewType } as HubTaskInstallation}); } private addVersionCheck(container: HTMLUListElement): void { if (this.task.latestVersion && this.task.latestVersion.minPipelinesVersion) { if (semver.lt(this.tknVersion, this.task.latestVersion.minPipelinesVersion)){ const versionWarning = document.createElement('li'); versionWarning.classList.add('action-item'); const warning = createSpan('codicon', 'codicon-warning', 'action-warning'); warning.title = `This task requires Tekton Pipelines >= ${this.task.latestVersion.minPipelinesVersion} and is incompatible with the version of Tekton Pipelines installed on your cluster.`; versionWarning.appendChild(warning); container.appendChild(versionWarning); } } } private addIsClusterTask(container: HTMLUListElement): void { if (isInstalledTask(this.task) && this.task.clusterTask) { const clusterTaskContainer = document.createElement('li'); clusterTaskContainer.classList.add('action-item'); const clusterTaskLabel = createSpan('cluster-task-label'); clusterTaskLabel.textContent = 'ClusterTask'; clusterTaskContainer.appendChild(clusterTaskLabel); container.appendChild(clusterTaskContainer); } } } export class TaskList extends ListWidget<HubTask> { tknVersion: string | undefined; constructor(element: HTMLElement, private messageSender: VSMessage, private loader: Loader, private type: string){ super(element); } setErrorMessage(message: string): void { this.element.innerText = message; } createItemWidget(item: HubTask): Widget { return new TaskItem(item, this.messageSender, this.loader, this.type, this.tknVersion); } show(items: HubTask[]): void { if (items.length === 0) { this.showPlaceholder('No tasks found.'); if (this.itemListChangedListener) { this.itemListChangedListener(items); } } else { super.show(items); } } } export class TaskView { private searchInput: SearchInput; private taskList: TaskList; private installedTasks: Map<string, InstalledTask>; private welcomeList: CollapsibleList<HubTask>; private mainContainer: HTMLElement; private loader: Loader; private installedList: TaskList | undefined; private recommendedList: TaskList | undefined; private state: TaskViewState; private searchTasks: ResourceData[]; constructor(private vscodeAPI: VSMessage & ViewState) { this.searchInput = new SearchInput(document.getElementById('taskInput') as HTMLInputElement, vscodeAPI); this.searchInput.inputElement.addEventListener('keypress', (e) => { if (e.code === 'Enter') { enterEvent(e); } hideList(listGroup); initList(); }); this.searchInput.inputElement.addEventListener('click', () => { keyUpDown(); }); this.searchInput.onInputChange((input) => { if (input) { dropDownForTags(input); this.loader.show(); this.vscodeAPI.postMessage({type: 'search', data: input}); } else { hideList(listGroup); this.showWelcomeList(); } }); // Check if we have an old state to restore from this.state = vscodeAPI.getState() as TaskViewState; if (!this.state || !this.state.welcomeList){ this.state = {input: undefined, welcomeList: {}}; } this.loader = new Loader(); const rootElement = document.getElementById('root') rootElement.insertBefore(this.loader.getElement(), rootElement.firstChild); this.loader.show(); const taskListContainer = createDiv(); taskListContainer.id = 'tasksList'; taskListContainer.className = 'contain-style'; this.taskList = new TaskList(taskListContainer, this.vscodeAPI, this.loader, 'searchView'); this.mainContainer = document.getElementById('mainContainer'); const listContainer = createDiv('collapsibleListContainer'); this.mainContainer.appendChild(listContainer); this.welcomeList = new CollapsibleList(listContainer, (state) => { this.state.welcomeList = state; this.vscodeAPI.setState(this.state); }, this.state.welcomeList); document.body.onresize = () => { this.welcomeList.updateLayout(); } } setErrorState(message: string): void { this.loader.hide(); this.searchInput.disable(); this.taskList.setErrorMessage(message); if (!this.mainContainer.contains(this.taskList.getElement())){ this.mainContainer.removeChild(this.welcomeList.getElement()); this.mainContainer.appendChild(this.taskList.getElement()); } } showTasks(tasks: ResourceData[]): void { this.loader.hide(); if (this.searchInput.value){ this.searchTasks = tasks; this.updateSearchList(); this.mainContainer.removeChild(this.welcomeList.getElement()); this.mainContainer.appendChild(this.taskList.getElement()); } else { this.showWelcomeList(); } } private updateSearchList(): void { if (this.installedTasks){ for (const task of this.searchTasks){ if (this.installedTasks.has(task.name)){ (task as InstalledTask).installedVersion = this.installedTasks.get(task.name).installedVersion; (task as InstalledTask).clusterTask = this.installedTasks.get(task.name).clusterTask; } else if ((task as InstalledTask).installedVersion && !this.installedTasks.has(task.name)){ delete (task as InstalledTask).installedVersion; delete (task as InstalledTask).clusterTask; } } } this.taskList.show(this.searchTasks); } private showWelcomeList(): void { this.mainContainer.removeChild(this.taskList.getElement()); this.mainContainer.appendChild(this.welcomeList.getElement()); } setTknVersion(version: string): void { this.taskList.tknVersion = version; } setInstalledTasks(tasks: InstalledTask[]): void { this.loader.hide(); this.installedTasks = new Map(tasks.map(it => [it.name, it])); if (!this.installedList){ const installedElement = createDiv(); this.installedList = new TaskList(installedElement, this.vscodeAPI, this.loader, 'installedView'); this.welcomeList.addSubList('INSTALLED', this.installedList); this.installedList.tknVersion = this.taskList.tknVersion; } this.installedList.show(tasks); if (this.searchInput.value) { this.updateSearchList(); } } setRecommendedTasks(tasks: ResourceData[]): void { if (!this.recommendedList){ const recommendedElement = createDiv(); this.recommendedList = new TaskList(recommendedElement, this.vscodeAPI, this.loader, 'recommendedView'); this.welcomeList.addSubList('RECOMMENDED', this.recommendedList); this.recommendedList.tknVersion = this.taskList.tknVersion; } this.recommendedList.show(tasks); } cancelInstall(): void { if (installingButton){ installingButton.textContent = 'Install'; } } } interface TaskViewState { input: string; welcomeList: CollapsibleListState; }
the_stack
import * as extensions from "../extensions"; import { TypeData, ScalarType, EnumType, FieldsType, FieldsTypeArg } from "gqless"; type Extension<TName extends string> = TName extends keyof typeof extensions ? typeof extensions[TName] : any; /** * @name Boolean * @type SCALAR */ type t_Boolean<T extends boolean = boolean> = ScalarType< T, Extension<"Boolean"> >; /** * @name Boolean_comparison_exp * @type INPUT_OBJECT */ export type Boolean_comparison_exp = { _eq: boolean | null; _gt: boolean | null; _gte: boolean | null; _in: boolean[] | null; _is_null: boolean | null; _lt: boolean | null; _lte: boolean | null; _neq: boolean | null; _nin: boolean[] | null; }; /** * @name CacheControlScope * @type ENUM */ type t_CacheControlScope = EnumType<"PRIVATE" | "PUBLIC">; /** * @name Float * @type SCALAR */ type t_Float<T extends number = number> = ScalarType<T, Extension<"Float">>; /** * @name ID * @type SCALAR */ type t_ID<T extends string = string> = ScalarType<T, Extension<"ID">>; /** * @name Int * @type SCALAR */ type t_Int<T extends number = number> = ScalarType<T, Extension<"Int">>; /** * @name Int_comparison_exp * @type INPUT_OBJECT */ export type Int_comparison_exp = { _eq: number | null; _gt: number | null; _gte: number | null; _in: number[] | null; _is_null: boolean | null; _lt: number | null; _lte: number | null; _neq: number | null; _nin: number[] | null; }; /** * @name Query * @type OBJECT */ type t_Query = FieldsType< { __typename: t_String<"Query">; hello: t_String | null; }, Extension<"Query"> >; /** * @name String * @type SCALAR */ type t_String<T extends string = string> = ScalarType<T, Extension<"String">>; /** * @name String_comparison_exp * @type INPUT_OBJECT */ export type String_comparison_exp = { _eq: string | null; _gt: string | null; _gte: string | null; _ilike: string | null; _in: string[] | null; _is_null: boolean | null; _like: string | null; _lt: string | null; _lte: string | null; _neq: string | null; _nilike: string | null; _nin: string[] | null; _nlike: string | null; _nsimilar: string | null; _similar: string | null; }; /** * @name Upload * @type SCALAR */ type t_Upload<T extends any = any> = ScalarType<T, Extension<"Upload">>; /** * @name __Directive * @type OBJECT */ type t___Directive = FieldsType< { __typename: t_String<"__Directive">; args: t___InputValue[]; description: t_String | null; locations: t___DirectiveLocation[]; name: t_String; }, Extension<"__Directive"> >; /** * @name __DirectiveLocation * @type ENUM */ type t___DirectiveLocation = EnumType< | "ARGUMENT_DEFINITION" | "ENUM" | "ENUM_VALUE" | "FIELD" | "FIELD_DEFINITION" | "FRAGMENT_DEFINITION" | "FRAGMENT_SPREAD" | "INLINE_FRAGMENT" | "INPUT_FIELD_DEFINITION" | "INPUT_OBJECT" | "INTERFACE" | "MUTATION" | "OBJECT" | "QUERY" | "SCALAR" | "SCHEMA" | "SUBSCRIPTION" | "UNION" >; /** * @name __EnumValue * @type OBJECT */ type t___EnumValue = FieldsType< { __typename: t_String<"__EnumValue">; deprecationReason: t_String | null; description: t_String | null; isDeprecated: t_Boolean; name: t_String; }, Extension<"__EnumValue"> >; /** * @name __Field * @type OBJECT */ type t___Field = FieldsType< { __typename: t_String<"__Field">; args: t___InputValue[]; deprecationReason: t_String | null; description: t_String | null; isDeprecated: t_Boolean; name: t_String; type: t___Type; }, Extension<"__Field"> >; /** * @name __InputValue * @type OBJECT */ type t___InputValue = FieldsType< { __typename: t_String<"__InputValue">; defaultValue: t_String | null; description: t_String | null; name: t_String; type: t___Type; }, Extension<"__InputValue"> >; /** * @name __Schema * @type OBJECT */ type t___Schema = FieldsType< { __typename: t_String<"__Schema">; directives: t___Directive[]; mutationType: t___Type | null; queryType: t___Type; subscriptionType: t___Type | null; types: t___Type[]; }, Extension<"__Schema"> >; /** * @name __Type * @type OBJECT */ type t___Type = FieldsType< { __typename: t_String<"__Type">; description: t_String | null; enumValues: FieldsTypeArg< { includeDeprecated?: boolean | null }, t___EnumValue[] | null >; fields: FieldsTypeArg< { includeDeprecated?: boolean | null }, t___Field[] | null >; inputFields: t___InputValue[] | null; interfaces: t___Type[] | null; kind: t___TypeKind; name: t_String | null; ofType: t___Type | null; possibleTypes: t___Type[] | null; }, Extension<"__Type"> >; /** * @name __TypeKind * @type ENUM */ type t___TypeKind = EnumType< | "ENUM" | "INPUT_OBJECT" | "INTERFACE" | "LIST" | "NON_NULL" | "OBJECT" | "SCALAR" | "UNION" >; /** * @name conflict_action * @type ENUM */ type t_conflict_action = EnumType<"ignore" | "update">; /** * @name mutation_root * @type OBJECT */ type t_mutation_root = FieldsType< { __typename: t_String<"mutation_root">; /** * delete data from the table: "todos" */ delete_todos: FieldsTypeArg< { where: todos_bool_exp }, t_todos_mutation_response | null >; /** * delete data from the table: "users" */ delete_users: FieldsTypeArg< { where: users_bool_exp }, t_users_mutation_response | null >; /** * insert data into the table: "todos" */ insert_todos: FieldsTypeArg< { objects: todos_insert_input[]; on_conflict?: todos_on_conflict | null }, t_todos_mutation_response | null >; /** * insert data into the table: "users" */ insert_users: FieldsTypeArg< { objects: users_insert_input[]; on_conflict?: users_on_conflict | null }, t_users_mutation_response | null >; /** * update data of the table: "todos" */ update_todos: FieldsTypeArg< { _inc?: todos_inc_input | null; _set?: todos_set_input | null; where: todos_bool_exp; }, t_todos_mutation_response | null >; /** * update data of the table: "users" */ update_users: FieldsTypeArg< { _inc?: users_inc_input | null; _set?: users_set_input | null; where: users_bool_exp; }, t_users_mutation_response | null >; }, Extension<"mutation_root"> >; /** * @name order_by * @type ENUM */ type t_order_by = EnumType< | "asc" | "asc_nulls_first" | "asc_nulls_last" | "desc" | "desc_nulls_first" | "desc_nulls_last" >; /** * @name query_root * @type OBJECT */ type t_query_root = FieldsType< { __typename: t_String<"query_root">; hello: t_String | null; /** * fetch data from the table: "todos" */ todos: FieldsTypeArg< { distinct_on?: todos_select_column[] | null; limit?: number | null; offset?: number | null; order_by?: todos_order_by[] | null; where?: todos_bool_exp | null; }, t_todos[] >; /** * fetch aggregated fields from the table: "todos" */ todos_aggregate: FieldsTypeArg< { distinct_on?: todos_select_column[] | null; limit?: number | null; offset?: number | null; order_by?: todos_order_by[] | null; where?: todos_bool_exp | null; }, t_todos_aggregate >; /** * fetch data from the table: "todos" using primary key columns */ todos_by_pk: FieldsTypeArg<{ id: number }, t_todos | null>; /** * fetch data from the table: "users" */ users: FieldsTypeArg< { distinct_on?: users_select_column[] | null; limit?: number | null; offset?: number | null; order_by?: users_order_by[] | null; where?: users_bool_exp | null; }, t_users[] >; /** * fetch aggregated fields from the table: "users" */ users_aggregate: FieldsTypeArg< { distinct_on?: users_select_column[] | null; limit?: number | null; offset?: number | null; order_by?: users_order_by[] | null; where?: users_bool_exp | null; }, t_users_aggregate >; /** * fetch data from the table: "users" using primary key columns */ users_by_pk: FieldsTypeArg<{ id: number }, t_users | null>; }, Extension<"query_root"> >; /** * @name subscription_root * @type OBJECT */ type t_subscription_root = FieldsType< { __typename: t_String<"subscription_root">; /** * fetch data from the table: "todos" */ todos: FieldsTypeArg< { distinct_on?: todos_select_column[] | null; limit?: number | null; offset?: number | null; order_by?: todos_order_by[] | null; where?: todos_bool_exp | null; }, t_todos[] >; /** * fetch aggregated fields from the table: "todos" */ todos_aggregate: FieldsTypeArg< { distinct_on?: todos_select_column[] | null; limit?: number | null; offset?: number | null; order_by?: todos_order_by[] | null; where?: todos_bool_exp | null; }, t_todos_aggregate >; /** * fetch data from the table: "todos" using primary key columns */ todos_by_pk: FieldsTypeArg<{ id: number }, t_todos | null>; /** * fetch data from the table: "users" */ users: FieldsTypeArg< { distinct_on?: users_select_column[] | null; limit?: number | null; offset?: number | null; order_by?: users_order_by[] | null; where?: users_bool_exp | null; }, t_users[] >; /** * fetch aggregated fields from the table: "users" */ users_aggregate: FieldsTypeArg< { distinct_on?: users_select_column[] | null; limit?: number | null; offset?: number | null; order_by?: users_order_by[] | null; where?: users_bool_exp | null; }, t_users_aggregate >; /** * fetch data from the table: "users" using primary key columns */ users_by_pk: FieldsTypeArg<{ id: number }, t_users | null>; }, Extension<"subscription_root"> >; /** * @name todos * @type OBJECT */ type t_todos = FieldsType< { __typename: t_String<"todos">; id: t_Int; is_completed: t_Boolean; text: t_String; /** * An object relationship */ user: t_users; user_authID: t_String; }, Extension<"todos"> >; /** * @name todos_aggregate * @type OBJECT */ type t_todos_aggregate = FieldsType< { __typename: t_String<"todos_aggregate">; aggregate: t_todos_aggregate_fields | null; nodes: t_todos[]; }, Extension<"todos_aggregate"> >; /** * @name todos_aggregate_fields * @type OBJECT */ type t_todos_aggregate_fields = FieldsType< { __typename: t_String<"todos_aggregate_fields">; avg: t_todos_avg_fields | null; count: FieldsTypeArg< { columns?: todos_select_column[] | null; distinct?: boolean | null }, t_Int | null >; max: t_todos_max_fields | null; min: t_todos_min_fields | null; stddev: t_todos_stddev_fields | null; stddev_pop: t_todos_stddev_pop_fields | null; stddev_samp: t_todos_stddev_samp_fields | null; sum: t_todos_sum_fields | null; var_pop: t_todos_var_pop_fields | null; var_samp: t_todos_var_samp_fields | null; variance: t_todos_variance_fields | null; }, Extension<"todos_aggregate_fields"> >; /** * @name todos_aggregate_order_by * @type INPUT_OBJECT */ export type todos_aggregate_order_by = { avg: todos_avg_order_by | null; count: order_by | null; max: todos_max_order_by | null; min: todos_min_order_by | null; stddev: todos_stddev_order_by | null; stddev_pop: todos_stddev_pop_order_by | null; stddev_samp: todos_stddev_samp_order_by | null; sum: todos_sum_order_by | null; var_pop: todos_var_pop_order_by | null; var_samp: todos_var_samp_order_by | null; variance: todos_variance_order_by | null; }; /** * @name todos_arr_rel_insert_input * @type INPUT_OBJECT */ export type todos_arr_rel_insert_input = { data: todos_insert_input[]; on_conflict: todos_on_conflict | null; }; /** * @name todos_avg_fields * @type OBJECT */ type t_todos_avg_fields = FieldsType< { __typename: t_String<"todos_avg_fields">; id: t_Float | null; }, Extension<"todos_avg_fields"> >; /** * @name todos_avg_order_by * @type INPUT_OBJECT */ export type todos_avg_order_by = { id: order_by | null }; /** * @name todos_bool_exp * @type INPUT_OBJECT */ export type todos_bool_exp = { _and: (todos_bool_exp | null)[] | null; _not: todos_bool_exp | null; _or: (todos_bool_exp | null)[] | null; id: Int_comparison_exp | null; is_completed: Boolean_comparison_exp | null; text: String_comparison_exp | null; user: users_bool_exp | null; user_authID: String_comparison_exp | null; }; /** * @name todos_constraint * @type ENUM */ type t_todos_constraint = EnumType<"todos_pkey">; /** * @name todos_inc_input * @type INPUT_OBJECT */ export type todos_inc_input = { id: number | null }; /** * @name todos_insert_input * @type INPUT_OBJECT */ export type todos_insert_input = { id: number | null; is_completed: boolean | null; text: string | null; user: users_obj_rel_insert_input | null; user_authID: string | null; }; /** * @name todos_max_fields * @type OBJECT */ type t_todos_max_fields = FieldsType< { __typename: t_String<"todos_max_fields">; id: t_Int | null; text: t_String | null; user_authID: t_String | null; }, Extension<"todos_max_fields"> >; /** * @name todos_max_order_by * @type INPUT_OBJECT */ export type todos_max_order_by = { id: order_by | null; text: order_by | null; user_authID: order_by | null; }; /** * @name todos_min_fields * @type OBJECT */ type t_todos_min_fields = FieldsType< { __typename: t_String<"todos_min_fields">; id: t_Int | null; text: t_String | null; user_authID: t_String | null; }, Extension<"todos_min_fields"> >; /** * @name todos_min_order_by * @type INPUT_OBJECT */ export type todos_min_order_by = { id: order_by | null; text: order_by | null; user_authID: order_by | null; }; /** * @name todos_mutation_response * @type OBJECT */ type t_todos_mutation_response = FieldsType< { __typename: t_String<"todos_mutation_response">; /** * number of affected rows by the mutation */ affected_rows: t_Int; /** * data of the affected rows by the mutation */ returning: t_todos[]; }, Extension<"todos_mutation_response"> >; /** * @name todos_obj_rel_insert_input * @type INPUT_OBJECT */ export type todos_obj_rel_insert_input = { data: todos_insert_input; on_conflict: todos_on_conflict | null; }; /** * @name todos_on_conflict * @type INPUT_OBJECT */ export type todos_on_conflict = { constraint: todos_constraint; update_columns: todos_update_column[]; }; /** * @name todos_order_by * @type INPUT_OBJECT */ export type todos_order_by = { id: order_by | null; is_completed: order_by | null; text: order_by | null; user: users_order_by | null; user_authID: order_by | null; }; /** * @name todos_select_column * @type ENUM */ type t_todos_select_column = EnumType< "id" | "is_completed" | "text" | "user_authID" >; /** * @name todos_set_input * @type INPUT_OBJECT */ export type todos_set_input = { id: number | null; is_completed: boolean | null; text: string | null; user_authID: string | null; }; /** * @name todos_stddev_fields * @type OBJECT */ type t_todos_stddev_fields = FieldsType< { __typename: t_String<"todos_stddev_fields">; id: t_Float | null; }, Extension<"todos_stddev_fields"> >; /** * @name todos_stddev_order_by * @type INPUT_OBJECT */ export type todos_stddev_order_by = { id: order_by | null }; /** * @name todos_stddev_pop_fields * @type OBJECT */ type t_todos_stddev_pop_fields = FieldsType< { __typename: t_String<"todos_stddev_pop_fields">; id: t_Float | null; }, Extension<"todos_stddev_pop_fields"> >; /** * @name todos_stddev_pop_order_by * @type INPUT_OBJECT */ export type todos_stddev_pop_order_by = { id: order_by | null }; /** * @name todos_stddev_samp_fields * @type OBJECT */ type t_todos_stddev_samp_fields = FieldsType< { __typename: t_String<"todos_stddev_samp_fields">; id: t_Float | null; }, Extension<"todos_stddev_samp_fields"> >; /** * @name todos_stddev_samp_order_by * @type INPUT_OBJECT */ export type todos_stddev_samp_order_by = { id: order_by | null }; /** * @name todos_sum_fields * @type OBJECT */ type t_todos_sum_fields = FieldsType< { __typename: t_String<"todos_sum_fields">; id: t_Int | null; }, Extension<"todos_sum_fields"> >; /** * @name todos_sum_order_by * @type INPUT_OBJECT */ export type todos_sum_order_by = { id: order_by | null }; /** * @name todos_update_column * @type ENUM */ type t_todos_update_column = EnumType< "id" | "is_completed" | "text" | "user_authID" >; /** * @name todos_var_pop_fields * @type OBJECT */ type t_todos_var_pop_fields = FieldsType< { __typename: t_String<"todos_var_pop_fields">; id: t_Float | null; }, Extension<"todos_var_pop_fields"> >; /** * @name todos_var_pop_order_by * @type INPUT_OBJECT */ export type todos_var_pop_order_by = { id: order_by | null }; /** * @name todos_var_samp_fields * @type OBJECT */ type t_todos_var_samp_fields = FieldsType< { __typename: t_String<"todos_var_samp_fields">; id: t_Float | null; }, Extension<"todos_var_samp_fields"> >; /** * @name todos_var_samp_order_by * @type INPUT_OBJECT */ export type todos_var_samp_order_by = { id: order_by | null }; /** * @name todos_variance_fields * @type OBJECT */ type t_todos_variance_fields = FieldsType< { __typename: t_String<"todos_variance_fields">; id: t_Float | null; }, Extension<"todos_variance_fields"> >; /** * @name todos_variance_order_by * @type INPUT_OBJECT */ export type todos_variance_order_by = { id: order_by | null }; /** * @name users * @type OBJECT */ type t_users = FieldsType< { __typename: t_String<"users">; authID: t_String; id: t_Int; name: t_String; /** * An array relationship */ todos: FieldsTypeArg< { distinct_on?: todos_select_column[] | null; limit?: number | null; offset?: number | null; order_by?: todos_order_by[] | null; where?: todos_bool_exp | null; }, t_todos[] >; /** * An aggregated array relationship */ todos_aggregate: FieldsTypeArg< { distinct_on?: todos_select_column[] | null; limit?: number | null; offset?: number | null; order_by?: todos_order_by[] | null; where?: todos_bool_exp | null; }, t_todos_aggregate >; }, Extension<"users"> >; /** * @name users_aggregate * @type OBJECT */ type t_users_aggregate = FieldsType< { __typename: t_String<"users_aggregate">; aggregate: t_users_aggregate_fields | null; nodes: t_users[]; }, Extension<"users_aggregate"> >; /** * @name users_aggregate_fields * @type OBJECT */ type t_users_aggregate_fields = FieldsType< { __typename: t_String<"users_aggregate_fields">; avg: t_users_avg_fields | null; count: FieldsTypeArg< { columns?: users_select_column[] | null; distinct?: boolean | null }, t_Int | null >; max: t_users_max_fields | null; min: t_users_min_fields | null; stddev: t_users_stddev_fields | null; stddev_pop: t_users_stddev_pop_fields | null; stddev_samp: t_users_stddev_samp_fields | null; sum: t_users_sum_fields | null; var_pop: t_users_var_pop_fields | null; var_samp: t_users_var_samp_fields | null; variance: t_users_variance_fields | null; }, Extension<"users_aggregate_fields"> >; /** * @name users_aggregate_order_by * @type INPUT_OBJECT */ export type users_aggregate_order_by = { avg: users_avg_order_by | null; count: order_by | null; max: users_max_order_by | null; min: users_min_order_by | null; stddev: users_stddev_order_by | null; stddev_pop: users_stddev_pop_order_by | null; stddev_samp: users_stddev_samp_order_by | null; sum: users_sum_order_by | null; var_pop: users_var_pop_order_by | null; var_samp: users_var_samp_order_by | null; variance: users_variance_order_by | null; }; /** * @name users_arr_rel_insert_input * @type INPUT_OBJECT */ export type users_arr_rel_insert_input = { data: users_insert_input[]; on_conflict: users_on_conflict | null; }; /** * @name users_avg_fields * @type OBJECT */ type t_users_avg_fields = FieldsType< { __typename: t_String<"users_avg_fields">; id: t_Float | null; }, Extension<"users_avg_fields"> >; /** * @name users_avg_order_by * @type INPUT_OBJECT */ export type users_avg_order_by = { id: order_by | null }; /** * @name users_bool_exp * @type INPUT_OBJECT */ export type users_bool_exp = { _and: (users_bool_exp | null)[] | null; _not: users_bool_exp | null; _or: (users_bool_exp | null)[] | null; authID: String_comparison_exp | null; id: Int_comparison_exp | null; name: String_comparison_exp | null; todos: todos_bool_exp | null; }; /** * @name users_constraint * @type ENUM */ type t_users_constraint = EnumType<"users_authID_key" | "users_pkey">; /** * @name users_inc_input * @type INPUT_OBJECT */ export type users_inc_input = { id: number | null }; /** * @name users_insert_input * @type INPUT_OBJECT */ export type users_insert_input = { authID: string | null; id: number | null; name: string | null; todos: todos_arr_rel_insert_input | null; }; /** * @name users_max_fields * @type OBJECT */ type t_users_max_fields = FieldsType< { __typename: t_String<"users_max_fields">; authID: t_String | null; id: t_Int | null; name: t_String | null; }, Extension<"users_max_fields"> >; /** * @name users_max_order_by * @type INPUT_OBJECT */ export type users_max_order_by = { authID: order_by | null; id: order_by | null; name: order_by | null; }; /** * @name users_min_fields * @type OBJECT */ type t_users_min_fields = FieldsType< { __typename: t_String<"users_min_fields">; authID: t_String | null; id: t_Int | null; name: t_String | null; }, Extension<"users_min_fields"> >; /** * @name users_min_order_by * @type INPUT_OBJECT */ export type users_min_order_by = { authID: order_by | null; id: order_by | null; name: order_by | null; }; /** * @name users_mutation_response * @type OBJECT */ type t_users_mutation_response = FieldsType< { __typename: t_String<"users_mutation_response">; /** * number of affected rows by the mutation */ affected_rows: t_Int; /** * data of the affected rows by the mutation */ returning: t_users[]; }, Extension<"users_mutation_response"> >; /** * @name users_obj_rel_insert_input * @type INPUT_OBJECT */ export type users_obj_rel_insert_input = { data: users_insert_input; on_conflict: users_on_conflict | null; }; /** * @name users_on_conflict * @type INPUT_OBJECT */ export type users_on_conflict = { constraint: users_constraint; update_columns: users_update_column[]; }; /** * @name users_order_by * @type INPUT_OBJECT */ export type users_order_by = { authID: order_by | null; id: order_by | null; name: order_by | null; todos_aggregate: todos_aggregate_order_by | null; }; /** * @name users_select_column * @type ENUM */ type t_users_select_column = EnumType<"authID" | "id" | "name">; /** * @name users_set_input * @type INPUT_OBJECT */ export type users_set_input = { authID: string | null; id: number | null; name: string | null; }; /** * @name users_stddev_fields * @type OBJECT */ type t_users_stddev_fields = FieldsType< { __typename: t_String<"users_stddev_fields">; id: t_Float | null; }, Extension<"users_stddev_fields"> >; /** * @name users_stddev_order_by * @type INPUT_OBJECT */ export type users_stddev_order_by = { id: order_by | null }; /** * @name users_stddev_pop_fields * @type OBJECT */ type t_users_stddev_pop_fields = FieldsType< { __typename: t_String<"users_stddev_pop_fields">; id: t_Float | null; }, Extension<"users_stddev_pop_fields"> >; /** * @name users_stddev_pop_order_by * @type INPUT_OBJECT */ export type users_stddev_pop_order_by = { id: order_by | null }; /** * @name users_stddev_samp_fields * @type OBJECT */ type t_users_stddev_samp_fields = FieldsType< { __typename: t_String<"users_stddev_samp_fields">; id: t_Float | null; }, Extension<"users_stddev_samp_fields"> >; /** * @name users_stddev_samp_order_by * @type INPUT_OBJECT */ export type users_stddev_samp_order_by = { id: order_by | null }; /** * @name users_sum_fields * @type OBJECT */ type t_users_sum_fields = FieldsType< { __typename: t_String<"users_sum_fields">; id: t_Int | null; }, Extension<"users_sum_fields"> >; /** * @name users_sum_order_by * @type INPUT_OBJECT */ export type users_sum_order_by = { id: order_by | null }; /** * @name users_update_column * @type ENUM */ type t_users_update_column = EnumType<"authID" | "id" | "name">; /** * @name users_var_pop_fields * @type OBJECT */ type t_users_var_pop_fields = FieldsType< { __typename: t_String<"users_var_pop_fields">; id: t_Float | null; }, Extension<"users_var_pop_fields"> >; /** * @name users_var_pop_order_by * @type INPUT_OBJECT */ export type users_var_pop_order_by = { id: order_by | null }; /** * @name users_var_samp_fields * @type OBJECT */ type t_users_var_samp_fields = FieldsType< { __typename: t_String<"users_var_samp_fields">; id: t_Float | null; }, Extension<"users_var_samp_fields"> >; /** * @name users_var_samp_order_by * @type INPUT_OBJECT */ export type users_var_samp_order_by = { id: order_by | null }; /** * @name users_variance_fields * @type OBJECT */ type t_users_variance_fields = FieldsType< { __typename: t_String<"users_variance_fields">; id: t_Float | null; }, Extension<"users_variance_fields"> >; /** * @name users_variance_order_by * @type INPUT_OBJECT */ export type users_variance_order_by = { id: order_by | null }; /** * @name Boolean * @type SCALAR */ export type Boolean = TypeData<t_Boolean>; /** * @name CacheControlScope * @type ENUM */ export type CacheControlScope = TypeData<t_CacheControlScope>; /** * @name Float * @type SCALAR */ export type Float = TypeData<t_Float>; /** * @name ID * @type SCALAR */ export type ID = TypeData<t_ID>; /** * @name Int * @type SCALAR */ export type Int = TypeData<t_Int>; /** * @name Query * @type OBJECT */ export type Query = TypeData<t_Query>; /** * @name String * @type SCALAR */ export type String = TypeData<t_String>; /** * @name Upload * @type SCALAR */ export type Upload = TypeData<t_Upload>; /** * @name __Directive * @type OBJECT */ export type __Directive = TypeData<t___Directive>; /** * @name __DirectiveLocation * @type ENUM */ export type __DirectiveLocation = TypeData<t___DirectiveLocation>; /** * @name __EnumValue * @type OBJECT */ export type __EnumValue = TypeData<t___EnumValue>; /** * @name __Field * @type OBJECT */ export type __Field = TypeData<t___Field>; /** * @name __InputValue * @type OBJECT */ export type __InputValue = TypeData<t___InputValue>; /** * @name __Schema * @type OBJECT */ export type __Schema = TypeData<t___Schema>; /** * @name __Type * @type OBJECT */ export type __Type = TypeData<t___Type>; /** * @name __TypeKind * @type ENUM */ export type __TypeKind = TypeData<t___TypeKind>; /** * @name conflict_action * @type ENUM */ export type conflict_action = TypeData<t_conflict_action>; /** * @name mutation_root * @type OBJECT */ export type mutation_root = TypeData<t_mutation_root>; /** * @name order_by * @type ENUM */ export type order_by = TypeData<t_order_by>; /** * @name query_root * @type OBJECT */ export type query_root = TypeData<t_query_root>; /** * @name subscription_root * @type OBJECT */ export type subscription_root = TypeData<t_subscription_root>; /** * @name todos * @type OBJECT */ export type todos = TypeData<t_todos>; /** * @name todos_aggregate * @type OBJECT */ export type todos_aggregate = TypeData<t_todos_aggregate>; /** * @name todos_aggregate_fields * @type OBJECT */ export type todos_aggregate_fields = TypeData<t_todos_aggregate_fields>; /** * @name todos_avg_fields * @type OBJECT */ export type todos_avg_fields = TypeData<t_todos_avg_fields>; /** * @name todos_constraint * @type ENUM */ export type todos_constraint = TypeData<t_todos_constraint>; /** * @name todos_max_fields * @type OBJECT */ export type todos_max_fields = TypeData<t_todos_max_fields>; /** * @name todos_min_fields * @type OBJECT */ export type todos_min_fields = TypeData<t_todos_min_fields>; /** * @name todos_mutation_response * @type OBJECT */ export type todos_mutation_response = TypeData<t_todos_mutation_response>; /** * @name todos_select_column * @type ENUM */ export type todos_select_column = TypeData<t_todos_select_column>; /** * @name todos_stddev_fields * @type OBJECT */ export type todos_stddev_fields = TypeData<t_todos_stddev_fields>; /** * @name todos_stddev_pop_fields * @type OBJECT */ export type todos_stddev_pop_fields = TypeData<t_todos_stddev_pop_fields>; /** * @name todos_stddev_samp_fields * @type OBJECT */ export type todos_stddev_samp_fields = TypeData<t_todos_stddev_samp_fields>; /** * @name todos_sum_fields * @type OBJECT */ export type todos_sum_fields = TypeData<t_todos_sum_fields>; /** * @name todos_update_column * @type ENUM */ export type todos_update_column = TypeData<t_todos_update_column>; /** * @name todos_var_pop_fields * @type OBJECT */ export type todos_var_pop_fields = TypeData<t_todos_var_pop_fields>; /** * @name todos_var_samp_fields * @type OBJECT */ export type todos_var_samp_fields = TypeData<t_todos_var_samp_fields>; /** * @name todos_variance_fields * @type OBJECT */ export type todos_variance_fields = TypeData<t_todos_variance_fields>; /** * @name users * @type OBJECT */ export type users = TypeData<t_users>; /** * @name users_aggregate * @type OBJECT */ export type users_aggregate = TypeData<t_users_aggregate>; /** * @name users_aggregate_fields * @type OBJECT */ export type users_aggregate_fields = TypeData<t_users_aggregate_fields>; /** * @name users_avg_fields * @type OBJECT */ export type users_avg_fields = TypeData<t_users_avg_fields>; /** * @name users_constraint * @type ENUM */ export type users_constraint = TypeData<t_users_constraint>; /** * @name users_max_fields * @type OBJECT */ export type users_max_fields = TypeData<t_users_max_fields>; /** * @name users_min_fields * @type OBJECT */ export type users_min_fields = TypeData<t_users_min_fields>; /** * @name users_mutation_response * @type OBJECT */ export type users_mutation_response = TypeData<t_users_mutation_response>; /** * @name users_select_column * @type ENUM */ export type users_select_column = TypeData<t_users_select_column>; /** * @name users_stddev_fields * @type OBJECT */ export type users_stddev_fields = TypeData<t_users_stddev_fields>; /** * @name users_stddev_pop_fields * @type OBJECT */ export type users_stddev_pop_fields = TypeData<t_users_stddev_pop_fields>; /** * @name users_stddev_samp_fields * @type OBJECT */ export type users_stddev_samp_fields = TypeData<t_users_stddev_samp_fields>; /** * @name users_sum_fields * @type OBJECT */ export type users_sum_fields = TypeData<t_users_sum_fields>; /** * @name users_update_column * @type ENUM */ export type users_update_column = TypeData<t_users_update_column>; /** * @name users_var_pop_fields * @type OBJECT */ export type users_var_pop_fields = TypeData<t_users_var_pop_fields>; /** * @name users_var_samp_fields * @type OBJECT */ export type users_var_samp_fields = TypeData<t_users_var_samp_fields>; /** * @name users_variance_fields * @type OBJECT */ export type users_variance_fields = TypeData<t_users_variance_fields>;
the_stack
import type { SubjectMessage } from '../../../../../../tests/transport/SubjectInboundTransport' import { Subject } from 'rxjs' import { SubjectInboundTransport } from '../../../../../../tests/transport/SubjectInboundTransport' import { SubjectOutboundTransport } from '../../../../../../tests/transport/SubjectOutboundTransport' import { getBaseConfig, waitForBasicMessage } from '../../../../tests/helpers' import { Agent } from '../../../agent/Agent' import { ConnectionRecord } from '../../connections' import { MediationState } from '../models/MediationState' const recipientConfig = getBaseConfig('Mediation: Recipient') const mediatorConfig = getBaseConfig('Mediation: Mediator', { autoAcceptMediationRequests: true, endpoints: ['rxjs:mediator'], }) const senderConfig = getBaseConfig('Mediation: Sender', { endpoints: ['rxjs:sender'], }) describe('mediator establishment', () => { let recipientAgent: Agent let mediatorAgent: Agent let senderAgent: Agent afterEach(async () => { await recipientAgent.shutdown() await recipientAgent.wallet.delete() await mediatorAgent.shutdown() await mediatorAgent.wallet.delete() await senderAgent.shutdown() await senderAgent.wallet.delete() }) test(`Mediation end-to-end flow 1. Start mediator agent and create invitation 2. Start recipient agent with mediatorConnectionsInvite from mediator 3. Assert mediator and recipient are connected and mediation state is Granted 4. Start sender agent and create connection with recipient 5. Assert endpoint in recipient invitation for sender is mediator endpoint 6. Send basic message from sender to recipient and assert it is received on the recipient side `, async () => { const mediatorMessages = new Subject<SubjectMessage>() const recipientMessages = new Subject<SubjectMessage>() const senderMessages = new Subject<SubjectMessage>() const subjectMap = { 'rxjs:mediator': mediatorMessages, 'rxjs:sender': senderMessages, } // Initialize mediatorReceived message mediatorAgent = new Agent(mediatorConfig.config, recipientConfig.agentDependencies) mediatorAgent.registerOutboundTransport(new SubjectOutboundTransport(mediatorMessages, subjectMap)) mediatorAgent.registerInboundTransport(new SubjectInboundTransport(mediatorMessages)) await mediatorAgent.initialize() // Create connection to use for recipient const { invitation: mediatorInvitation, connectionRecord: { id: mediatorRecipientConnectionId }, } = await mediatorAgent.connections.createConnection({ autoAcceptConnection: true, }) // Initialize recipient with mediation connections invitation recipientAgent = new Agent( { ...recipientConfig.config, mediatorConnectionsInvite: mediatorInvitation.toUrl({ domain: 'https://example.com/ssi', }), }, recipientConfig.agentDependencies ) recipientAgent.registerOutboundTransport(new SubjectOutboundTransport(recipientMessages, subjectMap)) recipientAgent.registerInboundTransport(new SubjectInboundTransport(recipientMessages)) await recipientAgent.initialize() const recipientMediator = await recipientAgent.mediationRecipient.findDefaultMediator() // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain, @typescript-eslint/no-non-null-assertion const recipientMediatorConnection = await recipientAgent.connections.getById(recipientMediator?.connectionId!) expect(recipientMediatorConnection).toBeInstanceOf(ConnectionRecord) expect(recipientMediatorConnection?.isReady).toBe(true) const mediatorRecipientConnection = await mediatorAgent.connections.getById(mediatorRecipientConnectionId) expect(mediatorRecipientConnection.isReady).toBe(true) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion expect(mediatorRecipientConnection).toBeConnectedWith(recipientMediatorConnection!) expect(recipientMediatorConnection).toBeConnectedWith(mediatorRecipientConnection) expect(recipientMediator?.state).toBe(MediationState.Granted) // Initialize sender agent senderAgent = new Agent(senderConfig.config, senderConfig.agentDependencies) senderAgent.registerOutboundTransport(new SubjectOutboundTransport(senderMessages, subjectMap)) senderAgent.registerInboundTransport(new SubjectInboundTransport(senderMessages)) await senderAgent.initialize() const { invitation: recipientInvitation, connectionRecord: { id: recipientSenderConnectionId }, } = await recipientAgent.connections.createConnection({ autoAcceptConnection: true, }) const endpoints = mediatorConfig.config.endpoints ?? [] expect(recipientInvitation.serviceEndpoint).toBe(endpoints[0]) let senderRecipientConnection = await senderAgent.connections.receiveInvitationFromUrl( recipientInvitation.toUrl({ domain: 'https://example.com/ssi', }), { autoAcceptConnection: true, } ) const recipientSenderConnection = await recipientAgent.connections.returnWhenIsConnected( recipientSenderConnectionId ) senderRecipientConnection = await senderAgent.connections.getById(senderRecipientConnection.id) expect(recipientSenderConnection).toBeConnectedWith(senderRecipientConnection) expect(senderRecipientConnection).toBeConnectedWith(recipientSenderConnection) expect(recipientSenderConnection.isReady).toBe(true) expect(senderRecipientConnection.isReady).toBe(true) const message = 'hello, world' await senderAgent.basicMessages.sendMessage(senderRecipientConnection.id, message) const basicMessage = await waitForBasicMessage(recipientAgent, { content: message, }) expect(basicMessage.content).toBe(message) }) test('restart recipient agent and create connection through mediator after recipient agent is restarted', async () => { const mediatorMessages = new Subject<SubjectMessage>() const recipientMessages = new Subject<SubjectMessage>() const senderMessages = new Subject<SubjectMessage>() const subjectMap = { 'rxjs:mediator': mediatorMessages, 'rxjs:sender': senderMessages, } // Initialize mediator mediatorAgent = new Agent(mediatorConfig.config, recipientConfig.agentDependencies) mediatorAgent.registerOutboundTransport(new SubjectOutboundTransport(mediatorMessages, subjectMap)) mediatorAgent.registerInboundTransport(new SubjectInboundTransport(mediatorMessages)) await mediatorAgent.initialize() // Create connection to use for recipient const { invitation: mediatorInvitation, connectionRecord: { id: mediatorRecipientConnectionId }, } = await mediatorAgent.connections.createConnection({ autoAcceptConnection: true, }) // Initialize recipient with mediation connections invitation recipientAgent = new Agent( { ...recipientConfig.config, mediatorConnectionsInvite: mediatorInvitation.toUrl({ domain: 'https://example.com/ssi' }), }, recipientConfig.agentDependencies ) recipientAgent.registerOutboundTransport(new SubjectOutboundTransport(recipientMessages, subjectMap)) recipientAgent.registerInboundTransport(new SubjectInboundTransport(recipientMessages)) await recipientAgent.initialize() const recipientMediator = await recipientAgent.mediationRecipient.findDefaultMediator() // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain, @typescript-eslint/no-non-null-assertion const recipientMediatorConnection = await recipientAgent.connections.getById(recipientMediator?.connectionId!) expect(recipientMediatorConnection).toBeInstanceOf(ConnectionRecord) expect(recipientMediatorConnection?.isReady).toBe(true) const mediatorRecipientConnection = await mediatorAgent.connections.getById(mediatorRecipientConnectionId) expect(mediatorRecipientConnection.isReady).toBe(true) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion expect(mediatorRecipientConnection).toBeConnectedWith(recipientMediatorConnection!) expect(recipientMediatorConnection).toBeConnectedWith(mediatorRecipientConnection) expect(recipientMediator?.state).toBe(MediationState.Granted) // Restart recipient agent await recipientAgent.shutdown() recipientAgent = new Agent( { ...recipientConfig.config, mediatorConnectionsInvite: mediatorInvitation.toUrl({ domain: 'https://example.com/ssi', }), }, recipientConfig.agentDependencies ) recipientAgent.registerOutboundTransport(new SubjectOutboundTransport(recipientMessages, subjectMap)) recipientAgent.registerInboundTransport(new SubjectInboundTransport(recipientMessages)) await recipientAgent.initialize() // Initialize sender agent senderAgent = new Agent(senderConfig.config, senderConfig.agentDependencies) senderAgent.registerOutboundTransport(new SubjectOutboundTransport(senderMessages, subjectMap)) senderAgent.registerInboundTransport(new SubjectInboundTransport(senderMessages)) await senderAgent.initialize() const { invitation: recipientInvitation, connectionRecord: { id: recipientSenderConnectionId }, } = await recipientAgent.connections.createConnection({ autoAcceptConnection: true, }) const endpoints = mediatorConfig.config.endpoints ?? [] expect(recipientInvitation.serviceEndpoint).toBe(endpoints[0]) let senderRecipientConnection = await senderAgent.connections.receiveInvitationFromUrl( recipientInvitation.toUrl({ domain: 'https://example.com/ssi', }), { autoAcceptConnection: true, } ) const recipientSenderConnection = await recipientAgent.connections.returnWhenIsConnected( recipientSenderConnectionId ) senderRecipientConnection = await senderAgent.connections.getById(senderRecipientConnection.id) expect(recipientSenderConnection).toBeConnectedWith(senderRecipientConnection) expect(senderRecipientConnection).toBeConnectedWith(recipientSenderConnection) expect(recipientSenderConnection.isReady).toBe(true) expect(senderRecipientConnection.isReady).toBe(true) const message = 'hello, world' await senderAgent.basicMessages.sendMessage(senderRecipientConnection.id, message) const basicMessage = await waitForBasicMessage(recipientAgent, { content: message, }) expect(basicMessage.content).toBe(message) }) })
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview Code that deals with the audio features of the site. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.audioEnabled = VRS.globalOptions.audioEnabled !== undefined ? VRS.globalOptions.audioEnabled : true; // True if the audio features are enabled (can still be disabled on server). False if they are to be suppressed. VRS.globalOptions.audioAnnounceSelected = VRS.globalOptions.audioAnnounceSelected !== undefined ? VRS.globalOptions.audioAnnounceSelected : false; // True if details of selected aircraft should be announced. VRS.globalOptions.audioAnnounceOnlyAutoSelected = VRS.globalOptions.audioAnnounceOnlyAutoSelected !== undefined ? VRS.globalOptions.audioAnnounceOnlyAutoSelected : false; // True if only auto-selected aircraft should have their details announced. VRS.globalOptions.audioDefaultVolume = VRS.globalOptions.audioDefaultVolume !== undefined ? VRS.globalOptions.audioDefaultVolume : 1.0; // The default volume for the audio control. Range is 0.0 to 1.0. VRS.globalOptions.audioTimeout = VRS.globalOptions.audioTimeout || 60000; // The number of milliseconds that must elapse before audio is timed-out. /** * Describes URLs that the audio class will automatically play. */ export interface Audio_AutoPlay { src: string; } /** * The settings that are persisted between sessions by the Audio object. */ export interface AudioWrapper_SaveState { announceSelected: boolean; announceOnlyAutoSelected: boolean; volume: number; } /** * Handles the audio callouts for the site. */ export class AudioWrapper implements ISelfPersist<AudioWrapper_SaveState> { private _PausePhrase = ' '; private _BrowserSupportsAudio: boolean; // True if the browser supports audio, false if it does not. Undefined if it has not yet been tested. private _AutoplayQueue: Audio_AutoPlay[] = []; // A queue of objects that describe URLs to automatically play. private _Playing: JQuery = null; // A jQuery object wrapping an HTML5 Audio object that is currently playing. private _PlayingTimeout = 0; // The timeout handle for the timer that, when it expires, will stop the current audio object as a failsafe against audio objects that are pointing to an invalid / slow source. private _AnnounceSelectedAircraftList: AircraftList = null; // The aircraft list that we're reading out details for. private _SelectedAircraftChangedHookResult: IEventHandle = null; // The hook result for the selected aircraft changed event on an aircraft list. private _ListUpdatedHookResult : IEventHandle = null; // The hook result for the list updated event on an aircraft list. private _AnnouncedAircraft: Aircraft = null; // The aircraft whose details are currently being read out. private _AnnouncedAircraftIsUserSelected; // True if the aircraft that's been announced was selected by the user, false if it was auto-selected. private _PreviouslyAnnouncedAircraftIds: number[] = []; // A collection of aircraft IDs whose details were previously read out. We record this to guard against a ping-pong effect where the auto-selector rapidly switches between the same bunch of aircraft. private _Name: string; private _AnnounceSelected: boolean = VRS.globalOptions.audioAnnounceSelected; private _AnnounceOnlyAutoSelected: boolean = VRS.globalOptions.audioAnnounceOnlyAutoSelected; private _Volume: number = VRS.globalOptions.audioDefaultVolume; private _Muted = false; constructor(name?: string) { this._Name = name || 'default'; } getName = () : string => { return this._Name; } getAnnounceSelected = () => { return this._AnnounceSelected; } setAnnounceSelected = (value: boolean) => { if(this._AnnounceSelected !== value) { this._AnnounceSelected = value; if(!this._AnnounceSelected) { this._AutoplayQueue = []; this.stopPlaying(); } } } getAnnounceOnlyAutoSelected = () => { return this._AnnounceOnlyAutoSelected; } setAnnounceOnlyAutoSelected = (value: boolean) => { if(this._AnnounceOnlyAutoSelected !== value) { this._AnnounceOnlyAutoSelected = value; if(this._AnnounceSelected && this._AnnounceOnlyAutoSelected && this._AnnouncedAircraftIsUserSelected) { this._AutoplayQueue = []; this.stopPlaying(); } } } getVolume = () => { return this._Volume; } setVolume = (value: number) => { if(this._Volume !== value) { this._Volume = value; if(this._Playing) { (<HTMLAudioElement>(this._Playing[0])).volume = this._Volume; } } } getMuted = () => { return this._Muted; } setMuted = (value: boolean) => { if(this._Muted !== value) { this._Muted = value; if(this._Playing) { (<HTMLAudioElement>(this._Playing[0])).muted = this._Muted; } } } /** * Releases all resources held by the object. */ dispose = () => { if(this._SelectedAircraftChangedHookResult) { this._AnnounceSelectedAircraftList.unhook(this._SelectedAircraftChangedHookResult); this._SelectedAircraftChangedHookResult = null; } if(this._ListUpdatedHookResult) { this._AnnounceSelectedAircraftList.unhook(this._ListUpdatedHookResult); this._ListUpdatedHookResult = null; } this._AnnounceSelectedAircraftList = null; this._AutoplayQueue = []; this.stopPlaying(); } /** * Saves the current state of the object. */ saveState = () => { VRS.configStorage.save(this.persistenceKey(), this.createSettings()); } /** * Loads the previously saved state of the object or the current state if it's never been saved. */ loadState = () : AudioWrapper_SaveState => { var savedSettings = VRS.configStorage.load(this.persistenceKey(), {}); return $.extend(this.createSettings(), savedSettings); } /** * Applies a previously saved state to the object. */ applyState = (settings: AudioWrapper_SaveState) => { this.setAnnounceOnlyAutoSelected(settings.announceOnlyAutoSelected); this.setAnnounceSelected(settings.announceSelected); this.setVolume(settings.volume); } /** * Loads and then applies a previousy saved state to the object. */ loadAndApplyState = () => { this.applyState(this.loadState()); } /** * Returns the key under which the state will be saved. */ private persistenceKey() : string { return 'vrsAudio-' + this.getName(); } /** * Creates the saved state object. */ private createSettings() : AudioWrapper_SaveState { return { announceSelected: this.getAnnounceSelected(), announceOnlyAutoSelected: this.getAnnounceOnlyAutoSelected(), volume: this.getVolume() }; } /** * Creates the description of the options pane for the object. */ createOptionPane = (displayOrder: number) : OptionPane => { var pane = new VRS.OptionPane({ name: 'vrsAudioPane', titleKey: 'PaneAudio', displayOrder: displayOrder }); if(this.canPlayAudio(true)) { pane.addField(new VRS.OptionFieldCheckBox({ name: 'announceSelected', labelKey: 'AnnounceSelected', getValue: this.getAnnounceSelected, setValue: this.setAnnounceSelected, saveState: this.saveState })); pane.addField(new VRS.OptionFieldCheckBox({ name: 'announceOnlyAutoSelected', labelKey: 'OnlyAutoSelected', getValue: this.getAnnounceOnlyAutoSelected, setValue: this.setAnnounceOnlyAutoSelected, saveState: this.saveState })); } return pane; } /** * Returns true if the browser supports audio and the codecs we want to use, false if it does not. */ isSupported = () : boolean => { return Modernizr.audio && Modernizr.wavaudio; } /** * Returns true if the browser probably supports auto-play, false if it probably does not. */ isAutoplaySupported = () : boolean => { return Modernizr.autoplayaudio; } /** * Returns true if the browser allows audio and if all of the settings together allow audio. This checks everything - * that the global options allow it, that the browser supports it, optionally that the browser can auto-play and * that the server configuration allows it. */ canPlayAudio = (mustAllowAutoPlay: boolean = true) : boolean => { var result = VRS.globalOptions.audioEnabled; if(result) result = this.isSupported(); if(result && mustAllowAutoPlay) result = this.isAutoplaySupported(); if(result) result = VRS.serverConfig ? VRS.serverConfig.audioEnabled() : true; return result; } private playNextEntry = () => { if(!this._Playing && this._AutoplayQueue.length) { var details = this._AutoplayQueue[0]; this._AutoplayQueue.splice(0, 1); this.playSource(details.src); } } /** * Plays any URL as an audio source. */ private playSource = (source: string) => { if(this.canPlayAudio(false)) { this._Playing = $('<audio/>'); this._Playing.on('ended', this.audioEnded); this.stopAudioTimeout(); this._PlayingTimeout = setTimeout(this.audioTimedOut, VRS.globalOptions.audioTimeout); var audioElement = (<HTMLAudioElement>(this._Playing[0])); audioElement.src = source; audioElement.volume = this.getVolume(); audioElement.muted = this.getMuted(); audioElement.play(); } } /** * Stops the currently playing audio object and releases it. */ private stopPlaying = () => { this._AnnouncedAircraft = null; this._AnnouncedAircraftIsUserSelected = undefined; this.stopAudioTimeout(); if(this._Playing) { var audio = this._Playing; this._Playing = null; (<HTMLAudioElement>(audio[0])).pause(); // <-- this may trigger audioEnded() audio.attr('src', ''); audio.off(); } } /** * Stops the timer that's running against the currently-playing audio object. */ private stopAudioTimeout = () => { if(this._PlayingTimeout) { clearTimeout(this._PlayingTimeout); this._PlayingTimeout = 0; } } /** * Calls out the details of the aircraft passed across if the settings allow it. */ private announceAircraft = (aircraft: Aircraft, userSelected: boolean) => { if(!aircraft) throw 'aircraft is null or undefined'; var newAircraft = this._AnnouncedAircraft === null || this._AnnouncedAircraft !== aircraft; var ignore = !this.canPlayAudio(true); if(!ignore) ignore = !this._AnnounceSelected || (userSelected && this._AnnounceOnlyAutoSelected); if(!ignore) ignore = newAircraft && !userSelected && this.isPreviouslyAnnouncedAutoSelected(aircraft); if(!ignore) { if(newAircraft && !userSelected) { this.recordPreviouslyAnnouncedAutoSelected(aircraft); } var sayText = ''; var appendRoute = false; var formatCallsign = () => { appendRoute = true; return VRS.stringUtility.format(VRS.$$.SayCallsign, this.formatAcronymForSpeech(aircraft.formatCallsign(false))) + ' '; }; var formatIcao = () => VRS.stringUtility.format(VRS.$$.SayIcao, this.formatAcronymForSpeech(aircraft.formatIcao())); var formatModelIcao = () => VRS.stringUtility.format(VRS.$$.SayModelIcao, this.formatUpperCaseWordsForSpeech(aircraft.formatModelIcao())) + ' '; var formatOperator = () => VRS.stringUtility.format(VRS.$$.SayOperator, this.formatUpperCaseWordsForSpeech(aircraft.formatOperator())) + ' '; var formatRegistration = () => VRS.stringUtility.format(VRS.$$.SayRegistration, this.formatAcronymForSpeech(aircraft.formatRegistration())) + ' '; if(aircraft === this._AnnouncedAircraft) { if(aircraft.registration.val && aircraft.registration.chg) sayText += formatRegistration(); if(aircraft.callsign.val && aircraft.callsign.chg) sayText += formatCallsign(); } else if(newAircraft) { if(aircraft.registration.val) sayText += formatRegistration(); else sayText += formatIcao(); if(aircraft.modelIcao.val) sayText += formatModelIcao(); if(aircraft.operator.val) sayText += formatOperator(); if(aircraft.callsign.val) sayText += formatCallsign(); } if(appendRoute) { if(!aircraft.hasRoute()) { sayText += VRS.$$.SayRouteNotKnown + ' '; } else { var from = this.formatUpperCaseWordsForSpeech(aircraft.from.val); var to = this.formatUpperCaseWordsForSpeech(aircraft.to.val); var convertedVias = []; var viaLength = aircraft.via.arr.length; for(var i = 0;i < viaLength;++i) { convertedVias.push(this.formatUpperCaseWordsForSpeech(aircraft.via.arr[i].val)); } var via = convertedVias.length === 0 ? null : VRS.$$.sayStopovers(convertedVias); if(!via) sayText += VRS.stringUtility.format(VRS.$$.SayFromTo, from, to); else sayText += VRS.stringUtility.format(VRS.$$.SayFromToVia, from, via, to); } } this._AnnouncedAircraft = aircraft; this._AnnouncedAircraftIsUserSelected = userSelected; if(newAircraft) { this._AutoplayQueue = []; this.stopPlaying(); } if(sayText) { this.say(sayText); } } } /** * Returns true if the aircraft has been read out previously. */ private isPreviouslyAnnouncedAutoSelected = (aircraft: Aircraft) : boolean => { var result = false; var length = this._PreviouslyAnnouncedAircraftIds.length; for(var i = 0;i < length;++i) { if(aircraft.id === this._PreviouslyAnnouncedAircraftIds[i]) { result = true; break; } } return result; } /** * Records the auto-selected aircraft's details. */ private recordPreviouslyAnnouncedAutoSelected = (aircraft: Aircraft) => { if(this._PreviouslyAnnouncedAircraftIds.length === 5) { this._PreviouslyAnnouncedAircraftIds.splice(0, 1); } this._PreviouslyAnnouncedAircraftIds.push(aircraft.id); } /** * Queues up a text-to-speech playback of the text passed across. Note that the text is played 'as-is' - there * is no attempt to convert upper-case to the phonetic alphabet or anything like that. */ say = (text: string) => { if(text && this.canPlayAudio(true)) { var details = { src: 'Audio?cmd=say&line=' + encodeURIComponent(text) }; this._AutoplayQueue.push(details); this.playNextEntry(); } } /** * Takes an acronym (e.g. 'LHR') and returns the text that should cause the acronym to be spoken using the * phonetic alphabet. */ formatAcronymForSpeech = (acronym: string) : string => { var result = ''; if(!acronym) acronym = ''; var length = acronym.length; for(var c = 0;c < length;c++) { var ch = acronym[c]; switch(acronym[c]) { case 'A': ch = VRS.$$.SayAlpha; break; case 'B': ch = VRS.$$.SayBravo; break; case 'C': ch = VRS.$$.SayCharlie; break; case 'D': ch = VRS.$$.SayDelta; break; case 'E': ch = VRS.$$.SayEcho; break; case 'F': ch = VRS.$$.SayFoxtrot; break; case 'G': ch = VRS.$$.SayGolf; break; case 'H': ch = VRS.$$.SayHotel; break; case 'I': ch = VRS.$$.SayIndia; break; case 'J': ch = VRS.$$.SayJuliet; break; case 'K': ch = VRS.$$.SayKilo; break; case 'L': ch = VRS.$$.SayLima; break; case 'M': ch = VRS.$$.SayMike; break; case 'N': ch = VRS.$$.SayNovember; break; case 'O': ch = VRS.$$.SayOscar; break; case 'P': ch = VRS.$$.SayPapa; break; case 'Q': ch = VRS.$$.SayQuebec; break; case 'R': ch = VRS.$$.SayRomeo; break; case 'S': ch = VRS.$$.SaySierra; break; case 'T': ch = VRS.$$.SayTango; break; case 'U': ch = VRS.$$.SayUniform; break; case 'V': ch = VRS.$$.SayVictor; break; case 'W': ch = VRS.$$.SayWhiskey; break; case 'X': ch = VRS.$$.SayXRay; break; case 'Y': ch = VRS.$$.SayYankee; break; case 'Z': ch = VRS.$$.SayZulu; break; case '-': ch = VRS.$$.SayHyphen; break; } if(ch !== ' ') result += ch + this._PausePhrase; } return result; } /** * Returns the text passed in with any upper-case words (e.g. 'LHR' in 'LHR London Heathrow') transformed so * that text-to-speech synthesis will say each individual letter in the word rather than trying to pronounce * the letters as a single word (e.g. LAX would be pronounced as ELL-AY-EX rather than LAX). */ formatUpperCaseWordsForSpeech = (text: string) : string => { var result = ''; text = text ? text : ''; var chunks = text.split(' '); var length = chunks.length; for(var c = 0;c < length;c++) { if(c > 0) result += ' '; var chunk = chunks[c]; result += VRS.stringUtility.isUpperCase(chunk) ? this.formatPunctuationForSpeech(chunk) : chunk; } return result; } /** * Returns a string that will cause the text-to-speech synthesis to spell out each character in the text * rather than pronouncing the text as a word. E.G. if passed 'HI' it will say 'aitch-eye' rather than 'hi'. */ formatPunctuationForSpeech = (text: string) : string => { var result = ''; text = text ? text : ''; var length = text.length; for(var c = 0;c < length;c++) { var ch = text[c]; switch(ch) { case '-': ch = VRS.$$.SayHyphen; break; case 'A': ch = VRS.$$.SayAy; break; case 'Z': ch = VRS.$$.SayZed; break; } if(ch !== ' ') { result += ch + this._PausePhrase; } } return result; } /** * Attaches event handlers to the aircraft list such that when a new aircraft is selected it will read out * details about the aircraft, if the configuration options at the time allow it. */ annouceSelectedAircraftOnList = (aircraftList: AircraftList) => { if(this._SelectedAircraftChangedHookResult) { this._AnnounceSelectedAircraftList.unhook(this._SelectedAircraftChangedHookResult); } if(this._ListUpdatedHookResult) { this._AnnounceSelectedAircraftList.unhook(this._ListUpdatedHookResult); } this._AnnounceSelectedAircraftList = aircraftList; this._SelectedAircraftChangedHookResult = aircraftList.hookSelectedAircraftChanged(this.selectedAircraftChanged, this); this._ListUpdatedHookResult = aircraftList.hookUpdated(this.listUpdated, this); } /** * Called when the currently-playing audio object has finished playing its audio. */ private audioEnded = () => { this.stopAudioTimeout(); this._Playing.off(); this._Playing = null; this.playNextEntry(); } /** * Called after the audio object has existed for a few seconds. It's assumed that if this gets called then the * audio object is pointing at a bad source and should be stopped. If one source is bad then all are considered * bad and the queue is cleared down. */ private audioTimedOut = () => { this._AutoplayQueue = []; this.stopPlaying(); } /** * Called when an aircraft list changes the selected aircraft. */ private selectedAircraftChanged = () => { if(this._AnnounceSelectedAircraftList) { var selectedAircraft = this._AnnounceSelectedAircraftList.getSelectedAircraft(); if(selectedAircraft) { this.announceAircraft(this._AnnounceSelectedAircraftList.getSelectedAircraft(), this._AnnounceSelectedAircraftList.getWasAircraftSelectedByUser()); } else { this._AutoplayQueue = []; this.stopPlaying(); } } } /** * Called when the aircraft list is updated. */ private listUpdated = () => { // Re-announce the aircraft, which should call out any new details. if(this._AnnouncedAircraft) { this.announceAircraft(this._AnnouncedAircraft, this._AnnouncedAircraftIsUserSelected); } } } }
the_stack
import createLogger from "debug"; import uuid from "uuid/v4"; import {WebIOCommand, WebIOCommandType, WebIOMessage, WebIORequest, WebIORequestType, WebIOResponse} from "./message"; import {WebIODomElement, WebIONodeSchema} from "./Node"; import WebIOScope from "./Scope"; import createNode, {NODE_CLASSES} from "./createNode"; import {ObservableGlobalSpecifier} from "./utils"; import WebIOObservable from "./Observable"; import {importResource, importBlock} from "./imports"; import {evalWithWebIOContext} from "./events"; import Future from "./Future"; const debug = createLogger("WebIO"); export type WebIOSendCallback = (message: WebIOMessage) => void; // TODO: void? class WebIO { /** * A promise that is resolved when WebIO is connected to the Julia backend. */ readonly connected: Promise<void>; // We use ! to tell TypeScript that these will be set (see constructor for details). private resolveConnected!: () => void; private rejectConnected!: () => void; /** * A map from `scopeId` to the corresponding {@link WebIOScope} instance. */ private scopes: {[scopeId: string]: WebIOScope | undefined} = {}; /** * A map from `observableId` to an array of corresponding * {@link WebIOObservable} instances. We have an array of these instances * since an observable may appear within several different scopes. Also note * that we identify observables by id here, rather than by name, since the * name may be different in different scopes; the ids are usually of the form * `obs_123`. */ private observables: {[observableId: string]: WebIOObservable[] | undefined} = {}; /** * The function that WebIO uses to send data to the Julia backend. */ private sendCallback?: WebIOSendCallback; /** * A map of in-flight requests. * * Keys are `requestId`s and the values are {@link Future}s that (should be) * ultimately resolved with the corresponding {@link WebIOResponse}. */ private requestFutures: Map<string, Future<WebIOResponse>> = new Map(); private dispatchListeners: Array<WebIO["dispatch"]> = []; /** * A reference to {@link NODE_CLASSES} to allow for extension. */ static readonly NODE_CLASSES = NODE_CLASSES; constructor() { // We have to use the !-postfix on {resolve,reject}Connected because TypeScript // thinks that the body of the promise below isn't immediately executed (it is). this.connected = new Promise<void>((resolve, reject) => { this.resolveConnected = resolve; this.rejectConnected = reject; }) } /** * Dispatch a message into the WebIO JavaScript machinery. * * The message usually comes from the comm (e.g. WebSocket) that WebIO is * using to communicate. * * @param message - The message to dispatch. */ dispatch(message: WebIOMessage) { this.dispatchListeners.forEach((handler) => { try { handler(message) } catch (e) { console.error(e); console.error(`Unhandled error in dispatchListener: ${e}.`); } }); switch (message.type) { case "request": return this.dispatchRequest(message); case "command": return this.dispatchCommand(message); case "response": return this.dispatchResponse(message); } throw new Error(`Unknown message type: ${(message as any).type}.`); } private dispatchCommand(message: WebIOCommand) { debug(`Dispatching command (command: ${message.command}).`, message); switch (message.command) { case WebIOCommandType.UPDATE_OBSERVABLE: { const scope = this.scopes[message.scope]; if (!scope) { debug(`WebIO has no such scope: (id ${message.scope}).`); return; } scope.setObservableValue(message.name, message.value, false); return; } default: { // TODO: see notes in interface definition of WebIOMessage throw new Error(`Unknown command: ${message.command}`); // const {scope: scopeId, command} = message; // const scope = this.scopes[scopeId]; // if (!scope) { // throw new Error(`WebIO has no such scope (id: ${scopeId}).`); // } } } } private async dispatchRequest(message: WebIORequest) { debug(`dispatchRequest: ${message.request}`); switch (message.request) { case WebIORequestType.EVAL: { const scope = this.getScope(message.scope); let result = evalWithWebIOContext(scope, message.expression, {webIO: this, scope}); if (result instanceof Promise) { debug(`Eval expression returned a promise, awaiting promise.`); result = await result; } return await this.send({ type: "response", request: message.request, requestId: message.requestId, result, }); } } throw new Error(`Unknown request type: ${message.request}.`); } private dispatchResponse(message: WebIOResponse) { const {request, requestId} = message; debug(`dispatchResponse: ${request}`); const future = this.requestFutures.get(requestId); if (!future) { debug(`Received response for unknown requestId: ${requestId}.`); return; } this.requestFutures.delete(requestId); future.resolve(message); } /** * Set the send callback that WebIO will use. * * This method, when called for the first time, will also resolve the WebIO * connected promise and send any messages that are waiting. */ setSendCallback(sendCallback: WebIOSendCallback) { debug(`Setting WebIO sendCallback.`); this.sendCallback = sendCallback; this.resolveConnected(); } /** * A method called by scopes to register themselves so that messages * can be routed appropriately. * * @todo This should probably be changed so that this method is used to * create a new `WebIOScope` and have it registered then instead of * asking the scope to register itself. * tl;dr; change * `scope = new WebIOScope(...); webIO.registerScope(scope)` * to `scope = webio.createScope(...);`. * * @param scope */ registerScope(scope: WebIOScope) { debug(`Registering WebIO scope (id: ${scope.id}).`); this.scopes[scope.id] = scope; } /** * A method called by observables to register themselves. This is used to * ensure that observables are in a consistent state within the browser. * @param observable */ registerObservable(observable: WebIOObservable) { const {id} = observable; debug(`Registering WebIO observable (id: ${observable.id}).`); if (!this.observables[id]) { this.observables[id] = []; } this.observables[observable.id]!.push(observable); } /** * Ensure that all observable instances have the value off the * `sourceObservable`. * * @param sourceObservable - The observable whose values are synchronized with * all other registered observables of the same id. */ reconcileObservables(sourceObservable: WebIOObservable) { const {id, name, value} = sourceObservable; const observables = this.observables[id] || []; debug(`Reconciling ${observables.length} observables (id: ${id}).`); if (observables.length < 1) { console.warn( `Tried to reconcile observables (id: ${id}, name: ${name}) but we don't know` + `about any observables with that id.` ); return; } for (const observable of observables) { // Don't re-set the value of the observable that triggered the // reconciliation. if (observable === sourceObservable) continue; debug(`Reconciling observable "${observable.name}" in scope "${observable.scope.id}".`); observable.setValue(value, false); } }; /** * Send a message to the WebIO Julia machinery. */ async send(message: WebIOMessage) { await this.connected; debug(`Sending WebIO message:`, message); debug(`sendCallback:`, this.sendCallback); return this.sendCallback!(message); } async sendRequest<T extends WebIORequestType>(message: WebIORequest<T>): Promise<WebIOResponse<T>> { message.type = message.type || "request"; message.requestId = message.requestId || uuid(); const {type, request, requestId} = message; if (type !== "request" || !request) { throw new Error("Malformed request."); } if (this.requestFutures.has(requestId)) { throw new Error(`Duplicate request id: ${requestId}.`); } const future = new Future<WebIOResponse<T>>(); this.requestFutures.set(requestId, future as any); await this.send(message); return await future; } async RPC(rpcId: string, args: any[]): Promise<unknown> { const result = await this.sendRequest<WebIORequestType.RPC>({ type: "request", request: WebIORequestType.RPC, requestId: uuid(), rpcId, arguments: args, }); if ("exception" in result) { throw new Error(result.exception); } return result.result; } /** * Curried RPC function. * * @example * const rpc = WebIO.getRPC("myRpc"); * await rpc(1, 2, 3); * await rpc(4, 5, 6); */ getRPC = (rpcId: string) => (...args: any[]) => this.RPC(rpcId, args); /** * Mount a WebIO node into the specified element. * * This method overwrites the content of the element. * * @param element - The element to be replaced with the WebIO node. * @param nodeSchema - The data associated with the WebIO node. */ mount(element: WebIODomElement, nodeSchema: WebIONodeSchema) { if (!element) { console.error("WebIO cannot mount node into element.", {element, nodeData: nodeSchema}); throw new Error(`WebIO cannot mount node into element.`); } debug("Mounting WebIO node.", {nodeData: nodeSchema, element}); const node = createNode(nodeSchema, {webIO: this}); // Reset the contents of the node we're mounting into. element.innerHTML = ""; element.classList.add("webio-mountpoint"); element.appendChild(node.element); } getScope(scopeId: string): WebIOScope { const scope = this.scopes[scopeId]; if (!scope) { throw new Error(`WebIO has no scope (id: ${scopeId}).`); } return scope; } /** * Get an {@link WebIOObservable} object. * * @throws Will throw an error if the scope does not exist or there is no * such observable within the scope. */ getObservable({scope, name}: ObservableGlobalSpecifier) { return this.getScope(scope).getLocalObservable(name); } /** * Get the value of some observable. * * @deprecated This method is a shim for old WebIO functionally which relied * on a global WebIO instance. * * @throws Will throw an error if the scope does not exist or there is no * such observable within the scope. */ getval({scope, name}: ObservableGlobalSpecifier) { return this.getScope(scope).getObservableValue(name); } /** * Set the value of some observable. * * @deprecated This method is a shim for old WebIO functionally which relied * on a global WebIO instance. * * @throws Will throw an error if the scope does not exist or there is no * such observable within the scope. */ setval({scope, name}: ObservableGlobalSpecifier, value: any, sync: boolean = true) { return this.getScope(scope).setObservableValue(name, value, sync); } addDispatchListener(listener: WebIO["dispatch"]) { this.dispatchListeners.push(listener); } removeDispatchListener(listener: WebIO["dispatch"]) { const index = this.dispatchListeners.indexOf(listener); if (index === -1) { return; } this.dispatchListeners = this.dispatchListeners.splice(index, 1); } // Re-export from imports.ts importResource = importResource; importBlock = importBlock; } export default WebIO;
the_stack
// Imported from: fs-extra-promise typings (minus Bluebird) /// <reference types="node"/> import stream = require("stream"); import fs = require("fs"); export type Stats = fs.Stats; export interface FSWatcher { close(): void; } export class ReadStream extends stream.Readable { } export class WriteStream extends stream.Writable { } // extended methods export function copy(src: string, dest: string, callback?: (err: Error) => void): void; export function copy(src: string, dest: string, filter: (src: string) => boolean, callback?: (err: Error) => void): void; export function copySync(src: string, dest: string, filter?: (src: string) => boolean): void; export function createFile(file: string, callback?: (err: Error) => void): void; export function createFileSync(file: string): void; export function mkdirs(dir: string, callback?: (err: Error) => void): void; export function mkdirp(dir: string, callback?: (err: Error) => void): void; export function mkdirsSync(dir: string): void; export function mkdirpSync(dir: string): void; export function outputFile(file: string, data: any, callback?: (err: Error) => void): void; export function outputFileSync(file: string, data: any): void; export function outputJson(file: string, data: any, callback?: (err: Error) => void): void; export function outputJSON(file: string, data: any, callback?: (err: Error) => void): void; export function outputJsonSync(file: string, data: any): void; export function outputJSONSync(file: string, data: any): void; export function readJson(file: string, callback?: (err: Error) => void): void; export function readJson(file: string, options?: OpenOptions, callback?: (err: Error) => void): void; export function readJSON(file: string, callback?: (err: Error) => void): void; export function readJSON(file: string, options?: OpenOptions, callback?: (err: Error) => void): void; export function readJsonSync(file: string, options?: OpenOptions): void; export function readJSONSync(file: string, options?: OpenOptions): void; export function remove(dir: string, callback?: (err: Error) => void): void; export function removeSync(dir: string): void; // export function delete(dir: string, callback?: (err: Error) => void): void; // export function deleteSync(dir: string): void; export function writeJson(file: string, object: any, callback?: (err: Error) => void): void; export function writeJson(file: string, object: any, options?: OpenOptions, callback?: (err: Error) => void): void; export function writeJSON(file: string, object: any, callback?: (err: Error) => void): void; export function writeJSON(file: string, object: any, options?: OpenOptions, callback?: (err: Error) => void): void; export function writeJsonSync(file: string, object: any, options?: OpenOptions): void; export function writeJSONSync(file: string, object: any, options?: OpenOptions): void; export function rename(oldPath: string, newPath: string, callback?: (err: Error) => void): void; export function renameSync(oldPath: string, newPath: string): void; export function truncate(fd: number, len: number, callback?: (err: Error) => void): void; export function truncateSync(fd: number, len: number): void; export function chown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void; export function chownSync(path: string, uid: number, gid: number): void; export function fchown(fd: number, uid: number, gid: number, callback?: (err: Error) => void): void; export function fchownSync(fd: number, uid: number, gid: number): void; export function lchown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void; export function lchownSync(path: string, uid: number, gid: number): void; export function chmod(path: string, mode: number | string, callback?: (err: Error) => void): void; export function chmodSync(path: string, mode: number | string): void; export function fchmod(fd: number, mode: number | string, callback?: (err: Error) => void): void; export function fchmodSync(fd: number, mode: number | string): void; export function lchmod(path: string, mode: number | string, callback?: (err: Error) => void): void; export function lchmodSync(path: string, mode: number | string): void; export function stat(path: string, callback?: (err: Error, stats: Stats) => void): void; export function lstat(path: string, callback?: (err: Error, stats: Stats) => void): void; export function fstat(fd: number, callback?: (err: Error, stats: Stats) => void): void; export function statSync(path: string): Stats; export function lstatSync(path: string): Stats; export function fstatSync(fd: number): Stats; export function link(srcpath: string, dstpath: string, callback?: (err: Error) => void): void; export function linkSync(srcpath: string, dstpath: string): void; export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err: Error) => void): void; export function symlinkSync(srcpath: string, dstpath: string, type?: fs.symlink.Type): void; export function readlink(path: string, callback?: (err: Error, linkString: string) => void): void; export function realpath(path: string, callback?: (err: Error, resolvedPath: string) => void): void; export function realpath(path: string, cache: string, callback: (err: Error, resolvedPath: string) => void): void; export function realpathSync(path: string, cache?: boolean): string; export function unlink(path: string, callback?: (err: Error) => void): void; export function unlinkSync(path: string): void; export function rmdir(path: string, callback?: (err: Error) => void): void; export function rmdirSync(path: string): void; export function mkdir(path: string, mode?: number | string, callback?: (err: Error) => void): void; export function mkdirSync(path: string, mode?: number | string): void; export function readdir(path: string, callback?: (err: Error, files: string[]) => void): void; export function readdirSync(path: string): string[]; export function close(fd: number, callback?: (err: Error) => void): void; export function closeSync(fd: number): void; export function open(path: string, flags: string, mode?: string, callback?: (err: Error, fs: number) => void): void; export function openSync(path: string, flags: string, mode?: string): number; export function utimes(path: string, atime: number, mtime: number, callback?: (err: Error) => void): void; export function utimesSync(path: string, atime: number, mtime: number): void; export function futimes(fd: number, atime: number, mtime: number, callback?: (err: Error) => void): void; export function futimesSync(fd: number, atime: number, mtime: number): void; export function fsync(fd: number, callback?: (err: Error) => void): void; export function fsyncSync(fd: number): void; export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: Buffer) => void): void; export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: Buffer) => void): void; export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; export function readFile(filename: string, options: OpenOptions | string, callback: (err: Error, data: string) => void): void; export function readFile(filename: string, callback: (err: Error, data: Buffer) => void): void; export function readFileSync(filename: string): Buffer; export function readFileSync(filename: string, options: OpenOptions | string): string; export function writeFile(filename: string, data: any, callback?: (err: Error) => void): void; export function writeFile(filename: string, data: any, options: OpenOptions | string, callback?: (err: Error) => void): void; export function writeFileSync(filename: string, data: any, option?: OpenOptions | string): void; export function appendFile(filename: string, data: any, callback?: (err: Error) => void): void; export function appendFile(filename: string, data: any, option: OpenOptions | string, callback?: (err: Error) => void): void; export function appendFileSync(filename: string, data: any, option?: OpenOptions | string): void; export function watchFile(filename: string, listener: { curr: Stats; prev: Stats; }): void; export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: { curr: Stats; prev: Stats; }): void; export function unwatchFile(filename: string, listener?: Stats): void; export function watch(filename: string, options?: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; export function exists(path: string, callback?: (exists: boolean) => void): void; export function existsSync(path: string): boolean; export function ensureDir(path: string, cb: (err: Error) => void): void; export function ensureDirSync(path: string): void; export interface OpenOptions { encoding?: string; flag?: string; } export function createReadStream(path: string | Buffer, options?: { flags?: string; encoding?: string; fd?: number; mode?: number; autoClose?: boolean; start?: number; end?: number; }): ReadStream; export function createWriteStream(path: string | Buffer, options?: { flags?: string; encoding?: string; fd?: number; mode?: number; }): WriteStream; // promisified versions export function copyAsync(src: string, dest: string, filter?: (src: string) => boolean): Promise<void>; export function createFileAsync(file: string): Promise<void>; export function mkdirsAsync(dir: string): Promise<void>; export function mkdirpAsync(dir: string): Promise<void>; export function outputFileAsync(file: string, data: any): Promise<void>; export function outputJSONAsync(file: string, data: any): Promise<void>; export function readJSONAsync(file: string, options?: OpenOptions): Promise<void>; export function removeAsync(dir: string): Promise<void>; // export function deleteAsync(dir: string):Promise<void>; export function writeJsonAsync(file: string, object: any, options?: OpenOptions): Promise<void>; export function writeJSONAsync(file: string, object: any, options?: OpenOptions): Promise<void>; export function renameAsync(oldPath: string, newPath: string): Promise<void>; export function truncateAsync(fd: number, len: number): Promise<void>; export function chownAsync(path: string, uid: number, gid: number): Promise<void>; export function fchownAsync(fd: number, uid: number, gid: number): Promise<void>; export function lchownAsync(path: string, uid: number, gid: number): Promise<void>; export function chmodAsync(path: string, mode: number | string): Promise<void>; export function fchmodAsync(fd: number, mode: number | string): Promise<void>; export function lchmodAsync(path: string, mode: number | string): Promise<void>; export function statAsync(path: string): Promise<Stats>; export function lstatAsync(path: string): Promise<Stats>; export function fstatAsync(fd: number): Promise<Stats>; export function linkAsync(srcpath: string, dstpath: string): Promise<void>; export function symlinkAsync(srcpath: string, dstpath: string, type?: fs.symlink.Type): Promise<void>; export function readlinkAsync(path: string): Promise<string>; export function realpathAsync(path: string, cache?: string): Promise<string>; export function unlinkAsync(path: string): Promise<void>; export function rmdirAsync(path: string): Promise<void>; export function mkdirAsync(path: string, mode?: number | string): Promise<void>; export function readdirAsync(path: string): Promise<string[]>; export function closeAsync(fd: number): Promise<void>; export function openAsync(path: string, flags: string, mode?: string): Promise<number>; export function utimesAsync(path: string, atime: number, mtime: number): Promise<void>; export function futimesAsync(fd: number, atime: number, mtime: number): Promise<void>; export function fsyncAsync(fd: number): Promise<void>; export function writeAsync(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise<[number, Buffer]>; export function readAsync(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise<[number, Buffer]>; export function readFileAsync(filename: string, options: OpenOptions | string): Promise<string>; export function readFileAsync(filename: string): Promise<Buffer>; export function writeFileAsync(filename: string, data: any, options?: OpenOptions | string): Promise<void>; export function appendFileAsync(filename: string, data: any, option?: OpenOptions | string): Promise<void>; export function existsAsync(path: string): Promise<boolean>; export function ensureDirAsync(path: string): Promise<void>; export function isDirectory(path: string, callback?: (err: Error, isDirectory: boolean) => void): void; export function isDirectorySync(path: string): boolean; export function isDirectoryAsync(path: string): Promise<boolean>;
the_stack
import _ from 'lodash' import { createQueryBuilder, EntityManager, getManager, UpdateQueryBuilder } from 'typeorm' import { TelleryBaseEntity } from '../../entities/base' import BlockEntity from '../../entities/block' import { LinkEntity } from '../../entities/link' import { InvalidArgumentError } from '../../error/error' import { BlockDTO, BlockParentType, BlockType } from '../../types/block' import { EntityType } from '../../types/entity' import { LinkType } from '../../types/link' import { defaultPermissions, PermissionModel } from '../../types/permission' import { Token } from '../../types/token' import { str2Date, strOrDate2number } from '../../utils/date' import { removeByPathAndId, setByPath } from '../../utils/updater' import { Entity } from '../common' import { Link, updateSourceLinkAlive, updateTargetLinkAlive } from '../link' export type BlockConstructor = new ( id: string, parentId: string, parentTable: BlockParentType, storyId: string, content: Record<string, unknown>, alive: boolean, version: number, format?: Record<string, unknown>, children?: string[], createdById?: string, lastEditedById?: string, createdAt?: Date, updatedAt?: Date, ) => Block const constructs: { [k: string]: BlockConstructor } = {} export function register(type: BlockType, c: BlockConstructor): void { constructs[type] = c } /** * get the corresponding init function by BlockType */ export function getBlockConstructor(type: BlockType): BlockConstructor { const c = constructs[type] if (!c) { throw InvalidArgumentError.new(`unknown block type: ${type}`) } return c } export abstract class Block extends Entity { static type: BlockType id: string storyId: string parentId: string parentTable: BlockParentType content: Record<string, unknown> format?: Record<string, unknown> children?: string[] // ------------internal--------------- // exist when generated by fromEntity() permissions?: PermissionModel[] workspaceId?: string constructor( id: string, parentId: string, parentTable: BlockParentType, storyId: string, content: Record<string, unknown>, alive: boolean, version: number, format?: Record<string, unknown>, children?: string[], createdById?: string, lastEditedById?: string, createdAt?: Date, updatedAt?: Date, ) { super(alive, version, createdById, lastEditedById, createdAt, updatedAt) if (!id || !parentId || !parentTable || !storyId) { throw InvalidArgumentError.new('id and parentId and parentTable and storyId cannot be empty') } this.id = id this.parentId = parentId this.parentTable = parentTable this.storyId = storyId this.content = content this.format = format this.children = children } /** * operations executed before saving * 1. set permission * 2. set workspace */ async preSave(manager: EntityManager): Promise<void> { const getParentPermissions = async () => manager .getRepository(BlockEntity) .findOne(this.storyId) .then((model) => model?.permissions) this.permissions = await this.getPermissions(getParentPermissions) } /** * operations executed after saving * @param origin: block entity before modification, being undefined if it were just created */ async postSave(manager: EntityManager, origin?: Block): Promise<void> { // when block content and alive has changed, modify its bidirectional link await this.syncLink(manager, origin) // sync the alive field to its children await this.syncBlocksAlive(manager, origin) } /** * get links from block content */ getLinksFromContent(): Link[] { return [] } getEntityType(): EntityType { return EntityType.BLOCK } toModel(workspaceId: string): BlockEntity { const pt = this.getPlainText() const entity = new BlockEntity() entity.id = this.id entity.workspaceId = workspaceId entity.storyId = this.storyId entity.parentId = this.parentId entity.parentTable = this.parentTable entity.interKey = this.getInterKey() entity.type = this.getType() entity.content = this.content ?? {} entity.format = this.format entity.children = this.children entity.searchableText = pt entity.permissions = this.permissions! entity.alive = this.alive entity.createdById = this.createdById entity.lastEditedById = this.lastEditedById return entity } toDTO(): BlockDTO { return { id: this.id, type: this.getType(), parentId: this.parentId, parentTable: this.getParentType(), storyId: this.storyId, content: this.content, format: this.format, children: this.children, permissions: this.permissions ?? defaultPermissions, createdAt: strOrDate2number(this.createdAt) || 0, updatedAt: strOrDate2number(this.updatedAt) || 0, version: this.version, createdById: this.createdById, lastEditedById: this.lastEditedById, alive: this.alive, } } static fromEntity(block: BlockEntity): Block { const b = new (getBlockConstructor(block.type))( block.id, block.parentId, block.parentTable, block.storyId, block.content as Record<string, unknown>, block.alive, block.version, block.format as Record<string, unknown>, block.children, block.createdById, block.lastEditedById, block.createdAt, block.updatedAt, ) b.permissions = block.permissions b.workspaceId = block.workspaceId return b } /** * In case of loading a unregistered block type */ static fromEntitySafely(block: BlockEntity): Block | undefined { try { return Block.fromEntity(block) } catch (err) { console.debug(err) } } static fromBlock(block: Block, newType?: BlockType): Block { return new (getBlockConstructor(newType || block.getType()))( block.id, block.parentId, block.parentTable, block.storyId, block.content, block.alive, block.version, block.format, block.children, block.createdById, block.lastEditedById, block.createdAt, block.updatedAt, ) } static fromArgs(args: unknown): Block { return new (getBlockConstructor(_.get(args, 'type')))( _.get(args, 'id'), _.get(args, 'parentId'), _.get(args, 'parentTable'), _.get(args, 'storyId'), _.get(args, 'content'), _.get(args, 'alive'), _.get(args, 'version'), _.get(args, 'format'), _.get(args, 'children'), _.get(args, 'createdById'), _.get(args, 'lastEditedById'), str2Date(_.get(args, 'createdAt')), str2Date(_.get(args, 'updatedAt')), ) } abstract getType(): BlockType /** * prevent the occurrence of duplicated blocks * `id` for common block * `hash(title)` for story block */ getInterKey(): string { return this.id } getParentType(): BlockParentType { return BlockParentType.BLOCK } getRecordedKeys(): string[] { return ['content', 'alive'] } /** * inherits from story / thought block for common blocks */ async getPermissions( getParentPermissions: () => Promise<PermissionModel[] | undefined>, ): Promise<PermissionModel[]> { return this.permissions ?? (await getParentPermissions()) ?? defaultPermissions } /** * set the value in the content by path, e.g. path = ["a", "b", "c"] => this.content.set("a.b.c", args) */ setContentByPath(path: string[], args: unknown): void { setByPath(this, path, args, (a) => { const newBlock = Block.fromArgs(a) Object.assign(this, newBlock) }) } /** * delete elements in the content that possessed the same id (by path) * NOTE: this.content.get(path) must be array or map, and its elements must have the field of `id`. */ removeContentByPathAndId(path: string[], id: string): void { removeByPathAndId(this, path, id) } private async syncLink(manager: EntityManager, origin?: Block) { const needRemoves = origin ? getSubbedLinks(origin, this) : [] const needAdds = getSubbedLinks(this, origin) if (!_(needRemoves).isEmpty()) { const deleteQuery = _(needRemoves) .map(({ sourceBlockId, targetBlockId }) => _.omitBy({ sourceBlockId, targetBlockId }, _.isUndefined), ) .value() await manager .getRepository(LinkEntity) .createQueryBuilder() .delete() .where(deleteQuery) .execute() } if (!_(needAdds).isEmpty()) { await manager.getRepository(LinkEntity).insert(needAdds) } } /** * sync the alive field of current block with its children and corresponding links * - if the `alive` field of a block were set to be false, * all `alive` field of downstream blocks (children) should also be set to false, * and the alive status for links where source / target meet those blocks should also be updated * - if the `alive` field of a block were set to be true (from false), * all `alive` field of downstream blocks (children) should also be set to true, * and the alive status for links where source / target meet those blocks should also be updated */ protected async syncBlocksAlive(manager: EntityManager, origin?: Block): Promise<void> { // if `origin.children` does not exists, it is not a nested block if (!origin || !origin.children) { return } if (this.isBeingDeleted(origin)) { await Promise.all([ this.updateChildrenAlive(manager, origin, false), updateSourceLinkAlive(manager, origin.id, false), updateTargetLinkAlive(manager, origin.id, false), ]) } if (this.isBeingReverted(origin)) { await Promise.all([ this.updateChildrenAlive(manager, origin, true), updateSourceLinkAlive(manager, origin.id, true), updateTargetLinkAlive(manager, origin.id, true), ]) } } /** * update the `alive` field of all children of a certain block */ private async updateChildrenAlive( manager: EntityManager, origin: Block, alive: boolean, ): Promise<void> { if (_.isEmpty(origin.children)) { return } const updateClause = createQueryBuilder(BlockEntity, 'blocks').update().set({ alive }) await cascadeUpdateBlocks(manager, origin.id, updateClause) } protected isBeingDeleted(origin: { alive: boolean }): boolean { return origin.alive && !this.alive } protected isBeingReverted(origin: { alive: boolean }): boolean { return !origin.alive && this.alive } protected isBeingCreated(origin?: Block): boolean { return !origin } } /** * returns [a.links - b.links] */ function getSubbedLinks(a: Block, b?: Block): LinkEntity[] { const als = a.getLinksFromContent ? a.getLinksFromContent() : [] const bls = b?.getLinksFromContent ? b.getLinksFromContent() : [] return _(als) .filter((l) => !_(bls).includes(l)) .map((l) => { const entity = new LinkEntity() entity.sourceBlockId = a.id entity.targetBlockId = l.blockId entity.type = l.type return _.omitBy(entity, _.isUndefined) as LinkEntity }) .value() } export function getPlainTextFromTokens(tokens: Token[]): string | undefined { try { return tokens .filter((t) => t[0] !== '‣') .map((t) => t[0]) .join('') // eslint-disable-next-line } catch (err) {} } /** * recursively take all children of the root block corresponding to rootBlockId, then apply update clause on it * Note: there must be a correct alias for updateClause * Note2: only blocks that possesses the same storyId with the rootBlock would be updated (in case of including external blocks) * blockIdField denotes the field name corresponding to the blockId taking out (i.e. the field which joined with blockId) */ export async function cascadeUpdateBlocks<T extends TelleryBaseEntity>( manager: EntityManager, rootBlockId: string, updateClause: UpdateQueryBuilder<T>, blockIdField: keyof T = 'id', ): Promise<void> { const [updateSql, params] = updateClause .where(`${updateClause.alias}."${blockIdField}" in (SELECT id FROM result)`) .getQueryAndParameters() return manager.query( `WITH RECURSIVE result AS ( SELECT id, children, "storyId" FROM blocks WHERE id = $${ params.length + 1 } UNION SELECT origin.id, origin.children, origin."storyId" FROM result JOIN blocks origin ON origin."storyId" = result."storyId" AND origin.id = ANY(result.children) ) ${updateSql}`, [...params, rootBlockId], ) } export async function cascadeLoadBlocksByLink( ids: string[], direction: 'forward' | 'backward', linkType: LinkType, ): Promise<BlockEntity[]> { let primaryBuilder let recursiveBuilder if (direction === 'backward') { primaryBuilder = createQueryBuilder(LinkEntity, 'links') .select('links."sourceBlockId"') .where('type = :linkType AND links."targetBlockId" IN (:...ids) AND "sourceAlive" = true', { ids, linkType, }) recursiveBuilder = createQueryBuilder(LinkEntity, 'origin') .select('origin."sourceBlockId"') .innerJoin( 'refLinks', 'refLinks', 'origin."targetBlockId" = "refLinks"."sourceBlockId" and origin."sourceAlive" = true and type = :linkType', { linkType }, ) } else { primaryBuilder = createQueryBuilder(LinkEntity, 'links') .select('links.targetBlockId') .where('type = :linkType AND links."sourceBlockId" IN (:...ids) AND "targetAlive" = true', { ids, linkType, }) recursiveBuilder = createQueryBuilder(LinkEntity, 'origin') .select('origin.sourceBlockId') .innerJoin( 'refLinks', 'refLinks', 'origin."targetBlockId" = "refLinks"."sourceBlockId" and origin."sourceAlive" = true and type = :linkType', { linkType }, ) } const [primarySql, primaryParams] = primaryBuilder.getQueryAndParameters() const [recursiveSql] = recursiveBuilder.getQueryAndParameters() const manager = getManager() return manager.query( `WITH RECURSIVE "refLinks" AS ( ${primarySql} UNION ${recursiveSql} ) SELECT * from blocks join "refLinks" on blocks.id = "refLinks"."sourceBlockId" `, primaryParams, ) }
the_stack
import React, { Component } from 'react'; /*-- Apply Third-party plugins (import location should be in front of "GLOBAL STYLES") --*/ import '@/components/_plugins/_lib-bootstrap'; import '@/components/_plugins/_lib-icons'; /*-- Apply global scripts and styles --*/ import '@/components/_utils/styles/_all.scss'; import '@/components/_utils/styles/rtl/_all.scss'; import { __ } from '@/components/_utils/_all'; /*-- Apply this component styles --*/ import '@/components/Parallax/styles/_style.scss'; // import { parallax } from '@/components/Parallax/parallax'; type ParallaxProps = { /** Pure parallax scrolling effect without other embedded HTML elements */ parallaxElements: boolean; /** Transition of parallax when `parallaxElements` is true */ parallaxElementsTransition?: string | null; /** Background image URL */ img?: string; /** Class name of default height */ heightClass?: string | null; /** Whether to display all pictures, including the edges */ fullyVisible?: boolean | null; /** Offset top of background */ offsetTop?: number | null; /** Background overlay */ overlay?: boolean | string | null; /** skew of background */ skew?: number | null; /** speed of parallax animation. Recommended value: `-10.00` to `10.00` */ speed?: number | null; /** -- */ id?: string; }; type ParallaxState = false; export default class Parallax extends Component<ParallaxProps, ParallaxState> { private rootRef = React.createRef<HTMLDivElement>(); windowScrollUpdate: () => void; windowResizeUpdate: () => void; uniqueID: string; constructor(props) { super(props); this.uniqueID = 'app-' + __.GUID.create(); // Add a scroll event listener to window this.windowScrollUpdate = () => { }; // Add a resize event listener to window this.windowResizeUpdate = () => { }; this.parallaxInit = this.parallaxInit.bind(this); } parallaxInit(w) { const self = this; const reactDomEl: any = self.rootRef.current; // Pure parallax scrolling effect without other embedded HTML elements //------------------------------------------ if (reactDomEl.classList.contains('poemkit-parallax--el')) { let dataSpeed = reactDomEl.dataset.speed, dataEasing = reactDomEl.dataset.transition; if (dataSpeed === undefined) dataSpeed = 0; if (dataEasing === undefined) dataEasing = 'none 0s ease 0s'; //Scroll Spy self.windowScrollUpdate = parallax(reactDomEl, { speed: dataSpeed, offsetTop: 0, transition: dataEasing, bg: false }) as unknown as () => void; } // Parallax scrolling effect with embedded HTML elements //------------------------------------------ if (!reactDomEl.classList.contains('poemkit-parallax--el')) { const $curImg = reactDomEl.querySelector('.poemkit-parallax__img'), dataImg = $curImg.src; let dataSkew = reactDomEl.dataset.skew, dataSpeed = reactDomEl.dataset.speed, dataEasing = reactDomEl.dataset.transition, dataOverlay = reactDomEl.dataset.overlayBg, dataFullyVisible = reactDomEl.dataset.fullyVisible, dataXPos = reactDomEl.dataset.xpos, dataOffsetTop = parseFloat(reactDomEl.dataset.offsetTop), curImgH: any = null, curImgW: any = null, curSize = 'cover'; if ( dataOverlay === undefined || dataOverlay === 'none' || dataOverlay === 0 || dataOverlay === 'false' ) { dataOverlay = 'rgba(0, 0, 0, 0)'; } // If there is no data-xxx, save current source to it if (dataSpeed === undefined) dataSpeed = 0; if (dataEasing === undefined) dataEasing = 'none 0s ease 0s'; if (dataXPos === undefined) dataXPos = '50%'; if (dataOffsetTop === undefined) dataOffsetTop = 0; if (dataFullyVisible === undefined) dataFullyVisible = false; //Trigger a callback when the selected images are loaded //Check if the picture is loaded on the page const img = new Image(); img.onload = function () { curImgH = $curImg.offsetHeight; //including: padding + borders + v-scrollbars (if rendered) curImgW = $curImg.offsetWidth; //including: padding + borders + v-scrollbars (if rendered) //Custom height for parallax container if ( reactDomEl.classList.contains('poemkit-height--10') || reactDomEl.classList.contains('poemkit-height--20') || reactDomEl.classList.contains('poemkit-height--30') || reactDomEl.classList.contains('poemkit-height--40') || reactDomEl.classList.contains('poemkit-height--50') || reactDomEl.classList.contains('poemkit-height--60') || reactDomEl.classList.contains('poemkit-height--70') || reactDomEl.classList.contains('poemkit-height--80') || reactDomEl.classList.contains('poemkit-height--90') || reactDomEl.classList.contains('poemkit-height--100') ) { const newH = reactDomEl.offsetHeight; reactDomEl.style.height = newH + 'px'; $curImg.style.maxHeight = newH + 'px'; } else { reactDomEl.style.height = reactDomEl.offsetHeight + 'px'; } //If the ".poemkit-v-align--absolute" has more content if (w <= 768) { if (reactDomEl.querySelector('.poemkit-v-align--absolute').offsetHeight >= curImgH) { reactDomEl.querySelector('.poemkit-v-align--absolute').classList.add( 'poemkit-v-align--relative' ); $curImg.style.display = 'none'; } } //Resize the background image to cover the entire container and //Resize the background image to make sure the image is fully visible if (curImgW > w) { curSize = 'contain'; } else { curSize = 'cover'; } //Determine image height and parallax container height //If the height is the same, higher or lower than the height of the container height, //be sure to use the cover attribute //*** Must be placed before the "dataFullyVisible" condition if (curImgH <= reactDomEl.offsetHeight) { curSize = 'cover'; } //Whether to display all pictures, including the edges if (dataFullyVisible) { if (curImgW < w) { curSize = 'cover'; } else { curSize = 'contain'; } } //console.log( 'Height: ' +curImgH + '===' + reactDomEl.offsetHeight + ' | Width: ' + curImgW + '===' + w + ' | ' + curSize ); //Add background image to parallax container if (dataImg !== undefined) { reactDomEl.style.background = `linear-gradient(${dataOverlay}, ${dataOverlay}), url(${dataImg}) ${dataXPos} ${dataOffsetTop}px/${curSize} no-repeat fixed`; } //Apply tilt effect if (dataSkew !== undefined && dataSkew != 0) { //Firefox browser will affect parallax effect due to transform reactDomEl.style.transform = `skew(0deg, ${dataSkew}deg)`; } //Scroll Spy self.windowScrollUpdate = parallax(reactDomEl, { speed: dataSpeed, offsetTop: dataOffsetTop, transition: dataEasing, bg: { enable: true, xPos: dataXPos } }) as unknown as () => void; }; img.src = dataImg; } } componentDidMount() { let windowWidth = window.innerWidth; this.parallaxInit(windowWidth); const windowUpdate = () => { // Check window width has actually changed and it's not just iOS triggering a resize event on scroll if (window.innerWidth != windowWidth) { // Update the window width for next time windowWidth = window.innerWidth; // Do stuff here this.parallaxInit(windowWidth); } } // Add function to the window that should be resized this.windowResizeUpdate = __.debounce(windowUpdate, 50) as unknown as () => void; window.removeEventListener('resize', this.windowResizeUpdate); window.addEventListener('resize', this.windowResizeUpdate); } /** Remove the global list of events, especially as scroll and interval. */ componentWillUnmount() { // Remove scroll events from window window.removeEventListener('scroll', this.windowScrollUpdate); window.removeEventListener('touchmove', this.windowScrollUpdate); // Remove resize events from window window.removeEventListener('resize', this.windowResizeUpdate); } render() { const { parallaxElements, parallaxElementsTransition, img, heightClass, fullyVisible, offsetTop, overlay, skew, speed, id, children } = this.props; const _parallaxElements = typeof parallaxElements === typeof undefined ? false : parallaxElements; return ( <> {!_parallaxElements ? ( <div ref={this.rootRef} id={id || this.uniqueID} className={`poemkit-parallax ${heightClass || ''}`} data-fully-visible={fullyVisible || false} data-offset-top={offsetTop || 0} data-overlay-bg={overlay || false} data-skew={skew || 0} data-speed={speed || 0.1}> <img className="poemkit-parallax__img" src={img} alt="" /> <div className="poemkit-v-align--absolute poemkit-t-c"> {children} </div> </div> ) : ( <div ref={this.rootRef} id={id || this.uniqueID} className={`poemkit-parallax--el ${heightClass || ''}`} data-transition={parallaxElementsTransition || 'all 0.4s cubic-bezier(0, 0, 0.34, 0.96) 0s'} data-speed={speed || 0.1}> {children} </div> )} </> ) } }
the_stack
import {clamp, toFixedNumber} from '@react-stately/utils'; import {ColorAxes, ColorChannel, ColorChannelRange, ColorFormat, Color as IColor} from '@react-types/color'; // @ts-ignore import intlMessages from '../intl/*.json'; import {MessageDictionary} from '@internationalized/message'; import {NumberFormatter} from '@internationalized/number'; const messages = new MessageDictionary(intlMessages); /** Parses a color from a string value. Throws an error if the string could not be parsed. */ export function parseColor(value: string): IColor { let res = RGBColor.parse(value) || HSBColor.parse(value) || HSLColor.parse(value); if (res) { return res; } throw new Error('Invalid color value: ' + value); } export function normalizeColor(v: string | IColor) { if (typeof v === 'string') { return parseColor(v); } else { return v; } } abstract class Color implements IColor { abstract toFormat(format: ColorFormat): IColor; abstract toString(format: ColorFormat | 'css'): string; abstract clone(): IColor; abstract getChannelRange(channel: ColorChannel): ColorChannelRange; abstract formatChannelValue(channel: ColorChannel, locale: string): string; toHexInt(): number { return this.toFormat('rgb').toHexInt(); } getChannelValue(channel: ColorChannel): number { if (channel in this) { return this[channel]; } throw new Error('Unsupported color channel: ' + channel); } withChannelValue(channel: ColorChannel, value: number): IColor { if (channel in this) { let x = this.clone(); x[channel] = value; return x; } throw new Error('Unsupported color channel: ' + channel); } getChannelName(channel: ColorChannel, locale: string) { return messages.getStringForLocale(channel, locale); } abstract getColorSpace(): ColorFormat getColorSpaceAxes(xyChannels: {xChannel?: ColorChannel, yChannel?: ColorChannel}): ColorAxes { let {xChannel, yChannel} = xyChannels; let xCh = xChannel || this.getColorChannels().find(c => c !== yChannel); let yCh = yChannel || this.getColorChannels().find(c => c !== xCh); let zCh = this.getColorChannels().find(c => c !== xCh && c !== yCh); return {xChannel: xCh, yChannel: yCh, zChannel: zCh}; } abstract getColorChannels(): [ColorChannel, ColorChannel, ColorChannel] } const HEX_REGEX = /^#(?:([0-9a-f]{3})|([0-9a-f]{6}))$/i; // X = <negative/positive number with/without decimal places> // before/after a comma, 0 or more whitespaces are allowed // - rgb(X, X, X) // - rgba(X, X, X, X) const RGB_REGEX = /rgb\(([-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?)\)|rgba\(([-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d(.\d+)?)\)/; class RGBColor extends Color { constructor(private red: number, private green: number, private blue: number, private alpha: number) { super(); } static parse(value: string): RGBColor | void { let m; if ((m = value.match(HEX_REGEX))) { if (m[1]) { let r = parseInt(m[1][0] + m[1][0], 16); let g = parseInt(m[1][1] + m[1][1], 16); let b = parseInt(m[1][2] + m[1][2], 16); return new RGBColor(r, g, b, 1); } else if (m[2]) { let r = parseInt(m[2][0] + m[2][1], 16); let g = parseInt(m[2][2] + m[2][3], 16); let b = parseInt(m[2][4] + m[2][5], 16); return new RGBColor(r, g, b, 1); } } if ((m = value.match(RGB_REGEX))) { const [r, g, b, a] = (m[1] ?? m[2]).split(',').map(n => Number(n.trim())); return new RGBColor(clamp(r, 0, 255), clamp(g, 0, 255), clamp(b, 0, 255), clamp(a ?? 1, 0, 1)); } } toString(format: ColorFormat | 'css') { switch (format) { case 'hex': return '#' + (this.red.toString(16).padStart(2, '0') + this.green.toString(16).padStart(2, '0') + this.blue.toString(16).padStart(2, '0')).toUpperCase(); case 'hexa': return '#' + (this.red.toString(16).padStart(2, '0') + this.green.toString(16).padStart(2, '0') + this.blue.toString(16).padStart(2, '0') + Math.round(this.alpha * 255).toString(16).padStart(2, '0')).toUpperCase(); case 'rgb': return `rgb(${this.red}, ${this.green}, ${this.blue})`; case 'css': case 'rgba': return `rgba(${this.red}, ${this.green}, ${this.blue}, ${this.alpha})`; default: return this.toFormat(format).toString(format); } } toFormat(format: ColorFormat): IColor { switch (format) { case 'hex': case 'hexa': case 'rgb': case 'rgba': return this; case 'hsb': case 'hsba': return this.toHSB(); case 'hsl': case 'hsla': return this.toHSL(); default: throw new Error('Unsupported color conversion: rgb -> ' + format); } } toHexInt(): number { return this.red << 16 | this.green << 8 | this.blue; } /** * Converts an RGB color value to HSB. * Conversion formula adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#From_RGB. * @returns An HSBColor object. */ private toHSB(): IColor { const red = this.red / 255; const green = this.green / 255; const blue = this.blue / 255; const min = Math.min(red, green, blue); const brightness = Math.max(red, green, blue); const chroma = brightness - min; const saturation = brightness === 0 ? 0 : chroma / brightness; let hue = 0; // achromatic if (chroma !== 0) { switch (brightness) { case red: hue = (green - blue) / chroma + (green < blue ? 6 : 0); break; case green: hue = (blue - red) / chroma + 2; break; case blue: hue = (red - green) / chroma + 4; break; } hue /= 6; } return new HSBColor( toFixedNumber(hue * 360, 2), toFixedNumber(saturation * 100, 2), toFixedNumber(brightness * 100, 2), this.alpha ); } /** * Converts an RGB color value to HSL. * Conversion formula adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#From_RGB. * @returns An HSLColor object. */ private toHSL(): IColor { const red = this.red / 255; const green = this.green / 255; const blue = this.blue / 255; const min = Math.min(red, green, blue); const max = Math.max(red, green, blue); const lightness = (max + min) / 2; const chroma = max - min; let hue: number; let saturation: number; if (chroma === 0) { hue = saturation = 0; // achromatic } else { saturation = chroma / (lightness < .5 ? max + min : 2 - max - min); switch (max) { case red: hue = (green - blue) / chroma + (green < blue ? 6 : 0); break; case green: hue = (blue - red) / chroma + 2; break; case blue: hue = (red - green) / chroma + 4; break; } hue /= 6; } return new HSLColor( toFixedNumber(hue * 360, 2), toFixedNumber(saturation * 100, 2), toFixedNumber(lightness * 100, 2), this.alpha); } clone(): IColor { return new RGBColor(this.red, this.green, this.blue, this.alpha); } getChannelRange(channel: ColorChannel): ColorChannelRange { switch (channel) { case 'red': case 'green': case 'blue': return {minValue: 0x0, maxValue: 0xFF, step: 0x1, pageSize: 0x11}; case 'alpha': return {minValue: 0, maxValue: 1, step: 0.01, pageSize: 0.1}; default: throw new Error('Unknown color channel: ' + channel); } } formatChannelValue(channel: ColorChannel, locale: string) { let options: Intl.NumberFormatOptions; let value = this.getChannelValue(channel); switch (channel) { case 'red': case 'green': case 'blue': options = {style: 'decimal'}; break; case 'alpha': options = {style: 'percent'}; break; default: throw new Error('Unknown color channel: ' + channel); } return new NumberFormatter(locale, options).format(value); } getColorSpace(): ColorFormat { return 'rgb'; } private static colorChannels: [ColorChannel, ColorChannel, ColorChannel] = ['red', 'green', 'blue']; getColorChannels(): [ColorChannel, ColorChannel, ColorChannel] { return RGBColor.colorChannels; } } // X = <negative/positive number with/without decimal places> // before/after a comma, 0 or more whitespaces are allowed // - hsb(X, X%, X%) // - hsba(X, X%, X%, X) const HSB_REGEX = /hsb\(([-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d+(?:.\d+)?%)\)|hsba\(([-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d(.\d+)?)\)/; class HSBColor extends Color { constructor(private hue: number, private saturation: number, private brightness: number, private alpha: number) { super(); } static parse(value: string): HSBColor | void { let m: RegExpMatchArray | void; if ((m = value.match(HSB_REGEX))) { const [h, s, b, a] = (m[1] ?? m[2]).split(',').map(n => Number(n.trim().replace('%', ''))); return new HSBColor(mod(h, 360), clamp(s, 0, 100), clamp(b, 0, 100), clamp(a ?? 1, 0, 1)); } } toString(format: ColorFormat | 'css') { switch (format) { case 'css': return this.toHSL().toString('css'); case 'hex': return this.toRGB().toString('hex'); case 'hexa': return this.toRGB().toString('hexa'); case 'hsb': return `hsb(${this.hue}, ${toFixedNumber(this.saturation, 2)}%, ${toFixedNumber(this.brightness, 2)}%)`; case 'hsba': return `hsba(${this.hue}, ${toFixedNumber(this.saturation, 2)}%, ${toFixedNumber(this.brightness, 2)}%, ${this.alpha})`; default: return this.toFormat(format).toString(format); } } toFormat(format: ColorFormat): IColor { switch (format) { case 'hsb': case 'hsba': return this; case 'hsl': case 'hsla': return this.toHSL(); case 'rgb': case 'rgba': return this.toRGB(); default: throw new Error('Unsupported color conversion: hsb -> ' + format); } } /** * Converts a HSB color to HSL. * Conversion formula adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_HSL. * @returns An HSLColor object. */ private toHSL(): IColor { let saturation = this.saturation / 100; let brightness = this.brightness / 100; let lightness = brightness * (1 - saturation / 2); saturation = lightness === 0 || lightness === 1 ? 0 : (brightness - lightness) / Math.min(lightness, 1 - lightness); return new HSLColor( toFixedNumber(this.hue, 2), toFixedNumber(saturation * 100, 2), toFixedNumber(lightness * 100, 2), this.alpha ); } /** * Converts a HSV color value to RGB. * Conversion formula adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB_alternative. * @returns An RGBColor object. */ private toRGB(): IColor { let hue = this.hue; let saturation = this.saturation / 100; let brightness = this.brightness / 100; let fn = (n: number, k = (n + hue / 60) % 6) => brightness - saturation * brightness * Math.max(Math.min(k, 4 - k, 1), 0); return new RGBColor( Math.round(fn(5) * 255), Math.round(fn(3) * 255), Math.round(fn(1) * 255), this.alpha ); } clone(): IColor { return new HSBColor(this.hue, this.saturation, this.brightness, this.alpha); } getChannelRange(channel: ColorChannel): ColorChannelRange { switch (channel) { case 'hue': return {minValue: 0, maxValue: 360, step: 1, pageSize: 15}; case 'saturation': case 'brightness': return {minValue: 0, maxValue: 100, step: 1, pageSize: 10}; case 'alpha': return {minValue: 0, maxValue: 1, step: 0.01, pageSize: 0.1}; default: throw new Error('Unknown color channel: ' + channel); } } formatChannelValue(channel: ColorChannel, locale: string) { let options: Intl.NumberFormatOptions; let value = this.getChannelValue(channel); switch (channel) { case 'hue': options = {style: 'unit', unit: 'degree', unitDisplay: 'narrow'}; break; case 'saturation': case 'brightness': options = {style: 'percent'}; value /= 100; break; case 'alpha': options = {style: 'percent'}; break; default: throw new Error('Unknown color channel: ' + channel); } return new NumberFormatter(locale, options).format(value); } getColorSpace(): ColorFormat { return 'hsb'; } private static colorChannels: [ColorChannel, ColorChannel, ColorChannel] = ['hue', 'saturation', 'brightness']; getColorChannels(): [ColorChannel, ColorChannel, ColorChannel] { return HSBColor.colorChannels; } } // X = <negative/positive number with/without decimal places> // before/after a comma, 0 or more whitespaces are allowed // - hsl(X, X%, X%) // - hsla(X, X%, X%, X) const HSL_REGEX = /hsl\(([-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d+(?:.\d+)?%)\)|hsla\(([-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d(.\d+)?)\)/; function mod(n, m) { return ((n % m) + m) % m; } class HSLColor extends Color { constructor(private hue: number, private saturation: number, private lightness: number, private alpha: number) { super(); } static parse(value: string): HSLColor | void { let m: RegExpMatchArray | void; if ((m = value.match(HSL_REGEX))) { const [h, s, l, a] = (m[1] ?? m[2]).split(',').map(n => Number(n.trim().replace('%', ''))); return new HSLColor(mod(h, 360), clamp(s, 0, 100), clamp(l, 0, 100), clamp(a ?? 1, 0, 1)); } } toString(format: ColorFormat | 'css') { switch (format) { case 'hex': return this.toRGB().toString('hex'); case 'hexa': return this.toRGB().toString('hexa'); case 'hsl': return `hsl(${this.hue}, ${toFixedNumber(this.saturation, 2)}%, ${toFixedNumber(this.lightness, 2)}%)`; case 'css': case 'hsla': return `hsla(${this.hue}, ${toFixedNumber(this.saturation, 2)}%, ${toFixedNumber(this.lightness, 2)}%, ${this.alpha})`; default: return this.toFormat(format).toString(format); } } toFormat(format: ColorFormat): IColor { switch (format) { case 'hsl': case 'hsla': return this; case 'hsb': case 'hsba': return this.toHSB(); case 'rgb': case 'rgba': return this.toRGB(); default: throw new Error('Unsupported color conversion: hsl -> ' + format); } } /** * Converts a HSL color to HSB. * Conversion formula adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_HSV. * @returns An HSBColor object. */ private toHSB(): IColor { let saturation = this.saturation / 100; let lightness = this.lightness / 100; let brightness = lightness + saturation * Math.min(lightness, 1 - lightness); saturation = brightness === 0 ? 0 : 2 * (1 - lightness / brightness); return new HSBColor( toFixedNumber(this.hue, 2), toFixedNumber(saturation * 100, 2), toFixedNumber(brightness * 100, 2), this.alpha ); } /** * Converts a HSL color to RGB. * Conversion formula adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB_alternative. * @returns An RGBColor object. */ private toRGB(): IColor { let hue = this.hue; let saturation = this.saturation / 100; let lightness = this.lightness / 100; let a = saturation * Math.min(lightness, 1 - lightness); let fn = (n: number, k = (n + hue / 30) % 12) => lightness - a * Math.max(Math.min(k - 3, 9 - k, 1), -1); return new RGBColor( Math.round(fn(0) * 255), Math.round(fn(8) * 255), Math.round(fn(4) * 255), this.alpha ); } clone(): IColor { return new HSLColor(this.hue, this.saturation, this.lightness, this.alpha); } getChannelRange(channel: ColorChannel): ColorChannelRange { switch (channel) { case 'hue': return {minValue: 0, maxValue: 360, step: 1, pageSize: 15}; case 'saturation': case 'lightness': return {minValue: 0, maxValue: 100, step: 1, pageSize: 10}; case 'alpha': return {minValue: 0, maxValue: 1, step: 0.01, pageSize: 0.1}; default: throw new Error('Unknown color channel: ' + channel); } } formatChannelValue(channel: ColorChannel, locale: string) { let options: Intl.NumberFormatOptions; let value = this.getChannelValue(channel); switch (channel) { case 'hue': options = {style: 'unit', unit: 'degree', unitDisplay: 'narrow'}; break; case 'saturation': case 'lightness': options = {style: 'percent'}; value /= 100; break; case 'alpha': options = {style: 'percent'}; break; default: throw new Error('Unknown color channel: ' + channel); } return new NumberFormatter(locale, options).format(value); } getColorSpace(): ColorFormat { return 'hsl'; } private static colorChannels: [ColorChannel, ColorChannel, ColorChannel] = ['hue', 'saturation', 'lightness']; getColorChannels(): [ColorChannel, ColorChannel, ColorChannel] { return HSLColor.colorChannels; } }
the_stack
import type { DevtoolsPluginApi, Hooks } from "@vue/devtools-api/lib/esm"; import { promisedTimeout } from "../utils"; type OnEvent = { type: Hooks; args: any[] }; type ApiEvent = { type: keyof DevtoolsPluginApi<unknown>; args: any[] }; let apiProxyFactory: ( promiseApi: Promise<DevtoolsPluginApi<unknown>> ) => DevtoolsPluginApi<unknown> = undefined as any; async function pushEventsToApi( api: DevtoolsPluginApi<unknown>, EventQueue: OnEvent[], ApiQueue: ApiEvent[] ) { setTimeout(async () => { const priority: (keyof DevtoolsPluginApi<unknown>)[] = [ "addTimelineLayer", "addInspector", "sendInspectorTree", "sendInspectorState", "addTimelineEvent", ]; for (const k of priority) { for (const it of ApiQueue.filter((x) => x.type === k)) { // @ts-ignore api[k](...it.args); } await promisedTimeout(20); } new Set( ApiQueue.filter((x) => x.type === "notifyComponentUpdate").map( (x) => x.args[0] ) ).forEach((x) => api.notifyComponentUpdate(x)); // @ts-ignore EventQueue.forEach((x) => api.on[x.type](...x.args)); EventQueue.length = 0; ApiQueue.length = 0; }, 100); } if (__VUE_2__) { apiProxyFactory = (promiseApi) => { const EventQueue: OnEvent[] = []; const ApiQueue: ApiEvent[] = []; let api: DevtoolsPluginApi<unknown>; function queueEvent(type: keyof DevtoolsPluginApi<unknown>, args: any) { if (api) { //@ts-ignore api[type](...args); } else { ApiQueue.push({ type, args }); } } promiseApi.then((x) => { api = x; pushEventsToApi(api, EventQueue, ApiQueue); }); const proxyApi: DevtoolsPluginApi<unknown> = { notifyComponentUpdate(): any { queueEvent("notifyComponentUpdate", arguments); }, addTimelineLayer(): any { queueEvent("addTimelineLayer", arguments); }, addTimelineEvent(): any { queueEvent("addTimelineEvent", arguments); }, addInspector(): any { queueEvent("addInspector", arguments); }, sendInspectorTree(): any { queueEvent("sendInspectorTree", arguments); }, sendInspectorState(): any { queueEvent("sendInspectorState", arguments); }, getComponentBounds(): any { queueEvent("getComponentBounds", arguments); }, getComponentName(): any { queueEvent("getComponentName", arguments); }, getComponentInstances(): any { queueEvent("getComponentInstances", arguments); }, highlightElement(): any { queueEvent("highlightElement", arguments); }, unhighlightElement(): any { queueEvent("unhighlightElement", arguments); }, selectInspectorNode(): any { queueEvent("selectInspectorNode", arguments); }, getSettings(): any { queueEvent("getSettings", arguments); }, setSettings(): any { queueEvent("setSettings", arguments); }, on: { transformCall(handler) { if (api) { api.on.transformCall(handler); } else { //@ts-expect-error EventQueue.push({ type: "transformCall", arg: arguments }); } }, getAppRecordName(handler) { if (api) { api.on.getAppRecordName(handler); } else { //@ts-expect-error EventQueue.push({ type: "getAppRecordName", arg: arguments }); } }, getAppRootInstance(handler) { if (api) { api.on.getAppRootInstance(handler); } else { //@ts-expect-error EventQueue.push({ type: "getAppRootInstance", arg: arguments }); } }, registerApplication(handler) { if (api) { api.on.registerApplication(handler); } else { //@ts-expect-error EventQueue.push({ type: "registerApplication", arg: arguments }); } }, walkComponentTree(handler) { if (api) { api.on.walkComponentTree(handler); } else { //@ts-expect-error EventQueue.push({ type: "walkComponentTree", arg: arguments }); } }, visitComponentTree(handler) { if (api) { api.on.visitComponentTree(handler); } else { //@ts-expect-error EventQueue.push({ type: "visitComponentTree", arg: arguments }); } }, walkComponentParents(handler) { if (api) { api.on.walkComponentParents(handler); } else { //@ts-expect-error EventQueue.push({ type: "walkComponentParents", arg: arguments }); } }, inspectComponent(handler) { if (api) { api.on.inspectComponent(handler); } else { //@ts-expect-error EventQueue.push({ type: "inspectComponent", arg: arguments }); } }, getComponentBounds(handler) { if (api) { api.on.getComponentBounds(handler); } else { //@ts-expect-error EventQueue.push({ type: "getComponentBounds", arg: arguments }); } }, getComponentName(handler) { if (api) { api.on.getComponentName(handler); } else { //@ts-expect-error EventQueue.push({ type: "getComponentName", arg: arguments }); } }, getComponentInstances(handler) { if (api) { api.on.getComponentInstances(handler); } else { //@ts-expect-error EventQueue.push({ type: "getComponentInstances", arg: arguments }); } }, getElementComponent(handler) { if (api) { api.on.getElementComponent(handler); } else { //@ts-expect-error EventQueue.push({ type: "getElementComponent", arg: arguments }); } }, getComponentRootElements(handler) { if (api) { api.on.getComponentRootElements(handler); } else { EventQueue.push({ //@ts-expect-error type: "getComponentRootElements", arg: arguments, }); } }, editComponentState(handler) { if (api) { api.on.editComponentState(handler); } else { //@ts-expect-error EventQueue.push({ type: "editComponentState", arg: arguments }); } }, getComponentDevtoolsOptions(handler) { if (api) { api.on.getComponentDevtoolsOptions(handler); } else { EventQueue.push({ //@ts-expect-error type: "getComponentDevtoolsOptions", arg: arguments, }); } }, inspectTimelineEvent(handler) { if (api) { api.on.inspectTimelineEvent(handler); } else { //@ts-expect-error EventQueue.push({ type: "inspectTimelineEvent", arg: arguments }); } }, getInspectorTree(handler) { if (api) { api.on.getInspectorTree(handler); } else { //@ts-expect-error EventQueue.push({ type: "getInspectorTree", arg: arguments }); } }, getInspectorState(handler) { if (api) { api.on.getInspectorState(handler); } else { //@ts-expect-error EventQueue.push({ type: "getInspectorState", arg: arguments }); } }, editInspectorState(handler) { if (api) { api.on.editInspectorState(handler); } else { //@ts-expect-error EventQueue.push({ type: "editInspectorState", arg: arguments }); } }, setPluginSettings(handler) { if (api) { api.on.setPluginSettings(handler); } else { //@ts-expect-error EventQueue.push({ type: "setPluginSettings", arg: arguments }); } }, getComponentRenderCode(handler) { if (api) { api.on.getComponentRenderCode(handler); } else { //@ts-expect-error EventQueue.push({ type: "getComponentRenderCode", arg: arguments }); } }, timelineCleared(handler) { if (api) { api.on.timelineCleared(handler); } else { //@ts-expect-error EventQueue.push({ type: "timelineCleared", arg: arguments }); } }, }, }; return proxyApi; }; } else { apiProxyFactory = (promiseApi) => { let api: DevtoolsPluginApi<unknown>; const EventQueue: OnEvent[] = []; const ApiQueue: ApiEvent[] = []; const onProxy = new Proxy( {}, { get: (target, prop: Hooks) => { if (api) { //@ts-expect-error return api.on[prop]; } else if (prop in target) { // @ts-ignore return target[prop]; } else { //@ts-ignore return (target[prop] = (...args) => { EventQueue.push({ type: prop, args, }); }); } }, } ); const proxy = new Proxy( { on: onProxy, }, { get: (target, prop: keyof DevtoolsPluginApi<unknown>) => { if (prop === "on") { return target.on; } if (api) { return api[prop]; } if (prop in target) { // @ts-ignore return target[prop]; } // @ts-ignore return (target[prop] = (...args) => { ApiQueue.push({ type: prop, args, }); }); }, } ); promiseApi.then((x) => { api = x; pushEventsToApi(api, EventQueue, ApiQueue); }); return proxy as any; }; } export default apiProxyFactory;
the_stack
import * as _ from "lodash"; import { ModelUtils } from "../utils/ModelUtils"; import { ModelRaceEnum, IGenericField, GenericFieldTypeEnum, IGenericFieldSubModel, EnumConfigExtractResult, } from "./defs"; import * as path from "path"; import * as Inflected from "inflected"; // This model can be inquired for asking: // GraphQL Types, Inputs, Model Classes export type ToContentOptions = { enumPrefix?: string; }; const ToContentDefaults = { enumPrefix: "", }; export class GenericModel { // Note: When you add additional fields don't forget to look at .clone() function race: ModelRaceEnum; name: string; fields: IGenericField[] = []; yupValidation: boolean = false; /** * This refers whether the actual model is stored in .base.ts and the model is extended from it * Allowing code-generators to write in base, and you to modify the model */ isBaseExtendMode: boolean = false; /** * This refers to whether we are dealing with inputs and enums, typically you don't want new enums when you're dealign with inputs which reflect an entity. */ reuseEnums: boolean = false; /** * Whether you are dealing with an input */ isInputMode: boolean = false; // Where should it be written targetPath?: string; public _skipModelNameQuestion = false; constructor(name?: string, race?: ModelRaceEnum, fields?: IGenericField[]) { this.name = name; if (race) { this.race = race; } if (fields) { this.fields = fields; } } get localBaseName() { const basenameParts = path.basename(this.targetPath).split("."); basenameParts.pop(); basenameParts.push("base"); return basenameParts.join("."); } // Most likely we clone it because we want to change the race static clone(model: GenericModel) { const newModel = new GenericModel(); [ "race", "name", "yupValidation", "targetPath", "isBaseExtendMode", "reuseEnums", "isInputMode", ].forEach((field) => (newModel[field] = model[field])); newModel.fields = model.fields.map((field) => { return Object.assign({}, field); }); return newModel; } getField(name: string): IGenericField { return this.fields.find((field) => field.name === name); } addField(field: IGenericField, first = false) { // Ensure uniqueness of name if (this.hasField(field.name)) { throw new Error( `You have already added the field with name: ${field.name}` ); } if (first) { this.fields = [field, ...this.fields]; } else { this.fields.push(field); } } removeField(fieldName: string) { this.fields = this.fields.filter((field) => field.name !== fieldName); } hasField(name: string): boolean { return Boolean(this.fields.find((f) => f.name === name)); } ensureIdField(): void { if (!this.hasField("_id")) { this.addField( { name: "_id", type: GenericFieldTypeEnum.ID, isMany: false, isOptional: true, }, true ); } } get modelTypeName() { switch (this.race) { case ModelRaceEnum.GRAPHQL_TYPE: return "graphql type"; case ModelRaceEnum.CLASSLIKE: return "model"; case ModelRaceEnum.GRAPHQL_INPUT: return "input"; } return "model"; } get modelName() { return _.upperFirst(this.name); } get modelClass() { return _.upperFirst(this.name) + this.modelClassSuffix; } get modelClassSuffix(): string { switch (this.race) { case ModelRaceEnum.GRAPHQL_TYPE: return ""; case ModelRaceEnum.CLASSLIKE: return ""; case ModelRaceEnum.GRAPHQL_INPUT: return "Input"; } return ""; } toGraphQL = () => { return this.graphqlContents(this.fields); }; toGraphQLSubmodel = (model: IGenericFieldSubModel) => { return this.graphqlContents(model.fields, { enumPrefix: model.name, }); }; toTypescript = () => { return this.tsContents(this.fields); }; toTypescriptSubmodel = (model: IGenericFieldSubModel) => { return this.tsContents(model.fields, { enumPrefix: model.name, }); }; graphqlContents( fields: IGenericField[], options: ToContentOptions = ToContentDefaults ): string { let result = ""; fields .filter((field) => !field.ignoreGraphQL) .forEach((field) => { if (field.description) { if (field.description) { result += ` """ ${field.description} """ `; } } if (field.type === GenericFieldTypeEnum.ENUM) { result += ModelUtils.getEnumSignatureForGraphQL( field, options.enumPrefix ? options.enumPrefix : this.modelClass, this.reuseEnums ) + "\n"; } else { result += ModelUtils.getFieldSignatureForGraphQL(field) + "\n"; } }); return result; } tsContents( fields: IGenericField[], options: ToContentOptions = ToContentDefaults ): string { let result = ""; fields .filter((field) => !field.ignoreTypeScript) .forEach((field) => { if (this.isFieldPartOfSubmodel(field)) { console.error({ field }); throw new Error("We do not allow fields that contain a dot."); } if (field.description) { result += ` /** * @description ${field.description} */ `; } if (this.yupValidation) { // It can still be undefined it'll be ok, it just doesn't need to be false if (field.yupValidation !== false) { const yupDecorator = ModelUtils.getYupValidatorDecorator( field, options.enumPrefix ? options.enumPrefix : this.modelClass, this.reuseEnums ); if (yupDecorator) { result += yupDecorator + "\n"; } } } if (field.type === GenericFieldTypeEnum.ENUM) { result += ModelUtils.getEnumSignatureForTS( field, options.enumPrefix ? options.enumPrefix : this.modelClass, this.reuseEnums ) + "\n"; } else { result += ModelUtils.getFieldSignatureForTS(field) + "\n"; } if (this.yupValidation) { // A decorator would need more space to be visibly attractive result += "\n"; } }); return result; } get models(): Array<{ bundle?: string; className: string; }> { return this.fields .filter((field) => this.isFieldModel(field)) .map((field) => { return { className: field.type, bundle: field.model?.referenceBundle, }; }); } get remoteModels(): IGenericFieldSubModel[] { const result = this.getFlatFields(this.fields, (field) => { return field.model?.storage === "outside" && field.model?.local === false; }) .map((field) => { return field.model; }) .filter((model) => { return model.name !== this.modelClass; }) // uniqueness .filter((value, index, self) => { return self.map((v) => v.name).indexOf(value.name) === index; }); return result; } get localModels(): IGenericFieldSubModel[] { return this.getFlatFields(this.fields, (field) => { return field.model?.storage === "outside" && field.model?.local === true; }).map((field) => field.model); } /** * TODO: make recursive so it goes deep otherwise it will fail. */ get embeddedModels(): IGenericFieldSubModel[] { const result = this.fields .filter((field) => { return field.model?.storage === "embed"; }) .map((field) => field.model); return result; } sortFields() { this.fields = _.sortBy(this.fields, "name"); } getFlatFields( fields: IGenericField[], filter: (field: IGenericField) => boolean ): IGenericField[] { const result: IGenericField[] = []; for (const field of fields) { if (filter(field)) { result.push(field); } if (field.model && field.model.fields) { result.push(...this.getFlatFields(field.model.fields, filter)); } } return result; } /** * The logic here is that if the field is not inside the GenericFieldTypeEnum it's definitely a model. * @param field */ isFieldModel(field: IGenericField): boolean { return ModelUtils.isFieldModel(field); } private extractAndAddEnumConfigToResult( fields: IGenericField[], result: EnumConfigExtractResult[], parentFieldName: string = "" ) { fields .filter((field) => field.type === GenericFieldTypeEnum.ENUM) .forEach((field) => { const className = ModelUtils.getEnumClassName( field, this.modelClass + parentFieldName, Boolean(parentFieldName) ); result.push({ className, elements: field.enumValues, importFrom: this.reuseEnums ? `../../collections` : `./enums/${className}.enum`, }); }); } get enums(): EnumConfigExtractResult[] { const result = [] as EnumConfigExtractResult[]; // First level enums this.extractAndAddEnumConfigToResult(this.fields, result); // Second level enums this.fields.forEach((field) => { if (field.model && field.model.fields) { this.extractAndAddEnumConfigToResult( field.model.fields, result, _.upperFirst( field.isMany ? Inflected.singularize(field.name) : field.name ) ); } }); return result; } /** * TODO: Make it create fields out of dotted fields. */ get submodels(): Array<{ GenericModel }> { return []; } protected isFieldPartOfSubmodel(field: IGenericField) { return field.name.indexOf(".") >= 0; } }
the_stack
import { Palette, publish, SVGWidget, Utility } from "@hpcc-js/common"; import { compare2 } from "@hpcc-js/util"; import { sankey as d3Sankey, sankeyLinkHorizontal as d3SankeyLinkHorizontal } from "d3-sankey"; import { select as d3Select } from "d3-selection"; import { AnnotationColumn, toJsonObj } from "./dataGraph"; import { IEdge, IVertex } from "./graph"; import "../../src/graph2/sankeyGraph.css"; export class SankeyGraph extends SVGWidget { @publish([], "any", "Vertex Columns", null, { internal: true }) vertexColumns: publish<this, string[]>; @publish([], "any", "Vertices (Nodes)", null, { internal: true }) vertices: publish<this, Array<Array<string | number | boolean>>>; @publish("", "set", "Vertex Category ID column", function (this: SankeyGraph) { return this.vertexColumns(); }, { optional: true }) vertexCategoryColumn: publish<this, string>; @publish("", "set", "Vertex ID column", function (this: SankeyGraph) { return this.vertexColumns(); }, { optional: true }) vertexIDColumn: publish<this, string>; @publish("", "set", "Vertex label column", function (this: SankeyGraph) { return this.vertexColumns(); }, { optional: true }) vertexLabelColumn: publish<this, string>; @publish("", "set", "Vertex centroid column (boolean)", function (this: SankeyGraph) { return this.vertexColumns(); }, { optional: true }) vertexCentroidColumn: publish<this, string>; @publish("?", "string", "Vertex default FAChar") vertexFAChar: publish<this, string>; @publish("", "set", "Vertex FAChar column", function (this: SankeyGraph) { return this.vertexColumns(); }, { optional: true }) vertexFACharColumn: publish<this, string>; @publish("", "set", "Vertex tooltip column", function (this: SankeyGraph) { return this.vertexColumns(); }, { optional: true }) vertexTooltipColumn: publish<this, string>; @publish([], "propertyArray", "Annotations", null, { autoExpand: AnnotationColumn }) vertexAnnotationColumns: publish<this, AnnotationColumn[]>; @publish([], "any", "Edge columns", null, { internal: true }) edgeColumns: publish<this, string[]>; @publish([], "any", "Edges (Edges)", null, { internal: true }) edges: publish<this, Array<Array<string | number | boolean>>>; @publish("", "set", "Edge ID column", function (this: SankeyGraph) { return this.edgeColumns(); }, { optional: true }) edgeIDColumn: publish<this, string>; @publish("", "set", "Edge label column", function (this: SankeyGraph) { return this.edgeColumns(); }, { optional: true }) edgeLabelColumn: publish<this, string>; @publish("", "set", "Edge source ID column", function (this: SankeyGraph) { return this.edgeColumns(); }, { optional: true }) edgeSourceColumn: publish<this, string>; @publish("", "set", "Edge target ID column", function (this: SankeyGraph) { return this.edgeColumns(); }, { optional: true }) edgeTargetColumn: publish<this, string>; @publish("", "set", "Edge target ID column", function (this: SankeyGraph) { return this.edgeColumns(); }, { optional: true }) edgeWeightColumn: publish<this, string>; protected _d3Sankey: any; protected _selection: any; _palette: any; constructor() { super(); Utility.SimpleSelectionMixin.call(this); this._drawStartPos = "origin"; } private _prevVertices: readonly IVertex[] = []; private _masterVertices: IVertex[] = []; private _masterVerticesMap: { [key: string]: IVertex } = {}; mergeVertices() { const columns = this.vertexColumns(); const annotationColumns = this.vertexAnnotationColumns(); const catIdx = this.indexOf(columns, this.vertexCategoryColumn(), "category"); const idIdx = this.indexOf(columns, this.vertexIDColumn(), "id"); const labelIdx = this.indexOf(columns, this.vertexLabelColumn(), "label"); const centroidIdx = this.indexOf(columns, this.vertexCentroidColumn(), "centroid"); const faCharIdx = this.indexOf(columns, this.vertexFACharColumn(), "faChar"); const vertexTooltipIdx = this.indexOf(columns, this.vertexTooltipColumn(), "tooltip"); const annotationIdxs = annotationColumns.map(ac => this.indexOf(columns, ac.columnID(), "")); const vertices: IVertex[] = this.vertices().map((v): IVertex => { return { categoryID: "" + v[catIdx], id: "" + v[idIdx], text: "" + v[labelIdx], tooltip: "" + v[vertexTooltipIdx], origData: toJsonObj(v, columns), centroid: !!v[centroidIdx], icon: { imageChar: "" + (v[faCharIdx] || this.vertexFAChar()) }, annotationIDs: annotationIdxs.map((ai, i) => !!v[ai] ? annotationColumns[i].annotationID() : undefined).filter(a => !!a) }; }); const diff = compare2(this._prevVertices, vertices, d => d.id); diff.exit.forEach(item => { this._masterVertices = this._masterVertices.filter(i => i.id !== item.id); }); diff.enter.forEach(item => { this._masterVertices.push(item); this._masterVerticesMap[item.id] = item; }); this._prevVertices = vertices; } indexOf(columns: readonly string[], column: string, defColumn: string = ""): number { const retVal = columns.indexOf(column); return retVal >= 0 ? retVal : columns.indexOf(defColumn); } protected _prevEdges: readonly IEdge[] = []; protected _masterEdges: IEdge[] = []; mergeEdges() { const columns = this.edgeColumns(); const idIdx = this.indexOf(columns, this.edgeIDColumn(), "id"); const sourceIdx = this.indexOf(columns, this.edgeSourceColumn(), "source"); const targetIdx = this.indexOf(columns, this.edgeTargetColumn(), "target"); const labelIdx = this.indexOf(columns, this.edgeLabelColumn(), "label"); const weightIdx = this.indexOf(columns, this.edgeWeightColumn(), "weight"); const edges: IEdge[] = this.edges().map(e => { const source = this._masterVerticesMap["" + e[sourceIdx]]; if (!source) console.error(`Invalid edge source entity "${e[sourceIdx]}" does not exist.`); const target = this._masterVerticesMap["" + e[targetIdx]]; if (!target) console.error(`Invalid edge target entity "${e[targetIdx]}" does not exist.`); return { type: "edge", id: idIdx >= 0 ? "" + e[idIdx] : "" + e[sourceIdx] + "->" + e[targetIdx], source, target, value: +e[weightIdx] || 0, label: labelIdx >= 0 ? ("" + e[labelIdx]) : "", origData: toJsonObj(e, columns) }; }).filter(e => e.source && e.target); const diff = compare2(this._masterEdges, edges, d => d.id); diff.exit.forEach(item => { this._masterEdges = this._masterEdges.filter(i => i.id !== item.id); }); diff.enter.forEach(item => { this._masterEdges.push(item); }); this._prevEdges = edges; } sankeyData() { this.mergeVertices(); this.mergeEdges(); return { vertices: this._masterVertices, edges: this._masterEdges }; } enter(domNode, element) { super.enter(domNode, element); this._d3Sankey = d3Sankey(); this._selection.widgetElement(element); } update(domNode, element) { super.update(domNode, element); this._palette = this._palette.switch(this.paletteID()); const strokeWidth = this.vertexStrokeWidth(); const sankeyData = this.sankeyData(); this._d3Sankey .nodeId(d => d.id) .extent([ [0, 0], [this.width(), this.height()] ]) // .nodeAlign(sankeyCenter) // .nodeWidth(this.vertexWidth()) // .nodePadding(this.vertexPadding()) ; if (sankeyData.vertices.length > 0) { this._d3Sankey({ nodes: sankeyData.vertices, links: sankeyData.edges }); } const context = this; // Links --- const link = element.selectAll(".link").data(sankeyData.edges); link.enter().append("path") .attr("class", "link") .each(function () { d3Select(this) .append("title") ; }) .merge(link) .attr("d", d3SankeyLinkHorizontal()) .style("stroke-width", (d: any) => Math.max(1, d.width)) // .sort(function (a, b) { return b.width - a.width; }) .select("title") .text(function (d) { return d.source.text + " → " + d.target.text + "\n" + d.value; }) ; link.exit().remove(); // Nodes --- const node = element.selectAll(".node").data(sankeyData.vertices); node.enter().append("g") .attr("class", "node") .call(this._selection.enter.bind(this._selection)) .on("click", function (d) { context.click(d.origData, "", context._selection.selected(this)); }) .on("dblclick", function (d) { context.dblclick(d.origData, "", context._selection.selected(this)); }) .each(function () { const gElement = d3Select(this); gElement.append("rect"); gElement.append("text"); }) /* .call(d3.behavior.drag() .origin(function (d) { return d; }) .on("dragstart", function () { this.parentNode.appendChild(this); }) .on("drag", dragmove) ) */ .merge(node) .attr("transform", function (d) { let _x = 0; let _y = 0; if (d.x0) _x = d.x0; if (d.y0) _y = d.y0; return "translate(" + (_x + strokeWidth) + "," + (_y + strokeWidth) + ")"; }) .each(function () { const n = d3Select(this); n.select("rect") .attr("height", (d: any) => { return d.y1 - d.y0; }) .attr("width", (d: any) => d.x1 - d.x0) .style("fill", function (d: any) { return context._palette(d.categoryID); }) .style("stroke", function (d: any) { return context.vertexStrokeColor(); }) .style("stroke-width", function (d: any) { return strokeWidth; }) .style("cursor", (context.xAxisMovement() || context.yAxisMovement()) ? null : "default") ; n.select("text") .attr("x", -6) .attr("y", function (d: any) { return (d.y1 - d.y0) / 2; }) .attr("dy", ".35em") .attr("text-anchor", "end") .attr("transform", null) .text(function (d: any) { return d.text; }) .filter(function (d: any) { return d.x0 < context.width() / 2; }) .attr("x", 6 + context._d3Sankey.nodeWidth()) .attr("text-anchor", "start") ; }); node.exit().remove(); /* function dragmove(d) { var gElement = d3.select(this); if (context.xAxisMovement()) { d.x = Math.max(0, Math.min(context.width() - d.dx, d3.event.x)); } if (context.yAxisMovement()) { d.y = Math.max(0, Math.min(context.height() - d.dy, d3.event.y)); } gElement.attr("transform", "translate(" + d.x + "," + d.y + ")"); context._d3Sankey.relayout(); link.attr("d", context._d3SankeyPath); gElement.select("text") .attr("x", -6) .attr("y", function (d) { return d.dy / 2; }) .attr("dy", ".35em") .attr("text-anchor", "end") .attr("transform", null) .text(function (d) { return d.name; }) .filter(function (d) { return d.x < context.width() / 2; }) .attr("x", 6 + context._d3Sankey.nodeWidth()) .attr("text-anchor", "start") ; } */ } paletteID: { (): string; (_: string): SankeyGraph; }; vertexStrokeWidth: { (): number; (_: number): SankeyGraph; }; vertexStrokeColor: { (): string; (_: string): SankeyGraph; }; vertexWidth: { (): number; (_: number): SankeyGraph; }; vertexPadding: { (): number; (_: number): SankeyGraph; }; xAxisMovement: { (): boolean; (_: boolean): SankeyGraph; }; yAxisMovement: { (): boolean; (_: boolean): SankeyGraph; }; exit(domNode, element) { super.exit(domNode, element); } // Events --- click(row, column, selected) { console.log("Click: " + JSON.stringify(row) + ", " + column + "," + selected); } dblclick(row, column, selected) { console.log("Double Click: " + JSON.stringify(row) + ", " + column + "," + selected); } } SankeyGraph.prototype._class += " graph_SankeyGraph"; SankeyGraph.prototype.mixin(Utility.SimpleSelectionMixin); SankeyGraph.prototype._palette = Palette.ordinal("category10"); SankeyGraph.prototype.publish("paletteID", "category10", "set", "Color palette for this widget", SankeyGraph.prototype._palette.switch()); SankeyGraph.prototype.publish("vertexStrokeWidth", 1, "number", "Vertex Stroke Width"); SankeyGraph.prototype.publish("vertexStrokeColor", "darkgray", "string", "Vertex Stroke Color"); SankeyGraph.prototype.publish("vertexWidth", 36, "number", "Vertex Width"); SankeyGraph.prototype.publish("vertexPadding", 20, "number", "Vertex Padding"); SankeyGraph.prototype.publish("xAxisMovement", false, "boolean", "Enable x-axis movement"); SankeyGraph.prototype.publish("yAxisMovement", false, "boolean", "Enable y-axis movement");
the_stack
import * as fs from "fs"; import * as path from "path"; import { dialog, Menu, MenuItemConstructorOptions } from "electron"; import { EmulatorPanelState } from "@state/AppState"; import { LinkDescriptor, MachineContextProviderBase } from "./machine-context"; import { mainProcessStore } from "./mainProcessStore"; import { machineCommandAction } from "@state/redux-machine-command-state"; import { CZ88_BATTERY_LOW, CZ88_HARD_RESET, CZ88_PRESS_BOTH_SHIFTS, CZ88_SOFT_RESET, } from "@shared/machines/macine-commands"; import { IAppWindow } from "./IAppWindows"; import { machineIdFromMenuId, menuIdFromMachineId, } from "./utils/electron-utils"; import { emulatorSetClockMultiplierAction, emulatorSetKeyboardAction, emulatorSetMachineContextAction, } from "@state/redux-emulator-state"; import { AppWindow } from "./AppWindow"; // --- Default ROM file const DEFAULT_ROM = "Z88OZ47.rom"; // --- Menu identifier contants const SOFT_RESET = "cz88_soft_reset"; const HARD_RESET = "cz88_hard_reset"; const PRESS_SHIFTS = "cz88_press_shifts"; const BATTERY_LOW = "cz88_battery_low"; const LCD_DIMS = "cz88_lcd_dims"; const ROM_MENU = "cz88_roms"; const SELECT_ROM_FILE = "cz88_select_rom_file"; const USE_DEFAULT_ROM = "cz88_use_default_rom"; const USE_ROM_FILE = "cz88_rom"; const KEYBOARDS = "cz88_keyboards"; const DE_KEYBOARD = "cz88_de_layout"; const DK_KEYBOARD = "cz88_dk_layout"; const FR_KEYBOARD = "cz88_fr_layout"; const ES_KEYBOARD = "cz88_es_layout"; const SE_KEYBOARD = "cz88_se_layout"; const UK_KEYBOARD = "cz88_uk_layout"; const INSERT_CARDS = "cz88_insert_cards"; const INS_SLOT1 = "cz88_insert_slot1"; const INS_SLOT2 = "cz88_insert_slot2"; const INS_SLOT3 = "cz88_insert_slot3"; const REMOVE_CARDS = "cz88_remove_cards"; const REM_SLOT1 = "cz88_remove_slot1"; const REM_SLOT2 = "cz88_remove_slot2"; const REM_SLOT3 = "cz88_remove_slot3"; // --- Machine type (by LCD resolution) constants const Z88_640_64 = "machine_cz88_255_8"; const Z88_640_320 = "machine_cz88_255_40"; const Z88_640_480 = "machine_cz88_255_60"; const Z88_800_320 = "machine_cz88_100_40"; const Z88_800_480 = "machine_cz88_100_60"; // ---------------------------------------------------------------------------- // Z88-specific help menu items const z88Links: LinkDescriptor[] = [ { label: "Cambridge Z88 User Guide", uri: "https://cambridgez88.jira.com/wiki/spaces/UG/", }, { label: "Cambridge Z88 Developers' Notes", uri: "https://cambridgez88.jira.com/wiki/spaces/DN/", }, { label: "BBC BASIC (Z80) Reference Guide for Z88", uri: "https://docs.google.com/document/d/1ZFxKYsfNvbuTyErnH5Xtv2aKXWk1vg5TjrAxZnrLsuI", }, { label: null, }, { label: "Cambridge Z88 ROM && 3rd party application source code", uri: "https://bitbucket.org/cambridge/", }, { label: "Cambridge Z88 on Wikipedia", uri: "https://en.wikipedia.org/wiki/Cambridge_Z88", }, { label: "Cambridge Z88 assembler tools and utilities", uri: "https://gitlab.com/bits4fun", }, ]; // ---------------------------------------------------------------------------- // We use these two variables to identify the current Z88 machine type // The last used LCD specification let recentLcdType = machineIdFromMenuId(Z88_640_64); let lcdLabel = "640x64"; // The name of the recent ROM let recentRomName: string | null = null; // The current ROM size let romSize = 512; // The current RAM size let ramSize = 512; // The current keyboard layout let kbLayout = "uk"; // !!! Temporary implementation let lastSlot1FileName: string | null = null; let lastSlot2FileName: string | null = null; let lastSlot3FileName: string | null = null; // !!! End // ---------------------------------------------------------------------------- // Configuration we use to instantiate the Z88 machine let recentOptions: Cz88ContructionOptions = { scw: 0xff, sch: 8, }; // ---------------------------------------------------------------------------- // UI state of the ROM submenu // The list of recently used ROMs let recentRoms: string[] = []; // Indicates that a recent ROM is selected. If false, we use the default ROM let recentRomSelected = false; /** * Represents the construction options of Z88 */ export interface Cz88ContructionOptions { sch?: number; scw?: number; rom?: Uint8Array; slot1?: Uint8Array; slot2?: Uint8Array; slot3?: Uint8Array; } /** * Context provider for the Cambridge Z88 machine model */ export class Cz88ContextProvider extends MachineContextProviderBase { /** * Instantiates the provider * @param appWindow: AppWindow instance */ constructor(public appWindow: IAppWindow) { super(); } /** * The normal CPU frequency of the machine */ getNormalCpuFrequency(): number { return 3_276_800; } /** * Context description for Z88 */ getMachineContextDescription(): string { return `Screen: ${lcdLabel}, ROM: ${ recentRomName ?? DEFAULT_ROM } (${romSize}KB), RAM: ${ramSize}KB`; } /** * Sets the current machine context */ setContext(): void { mainProcessStore.dispatch( emulatorSetMachineContextAction(this.getMachineContextDescription())() ); } /** * Items to add to the Show menu */ provideViewMenuItems(): MenuItemConstructorOptions[] | null { return null; } /** * Items to add to the machine menu */ provideMachineMenuItems(): MenuItemConstructorOptions[] | null { // --- Create the submenu of recent roms const romsSubmenu: MenuItemConstructorOptions[] = []; romsSubmenu.push({ id: USE_DEFAULT_ROM, label: "Use default ROM", type: "checkbox", checked: !recentRomSelected, click: (mi) => { mi.checked = true; recentRomSelected = false; const lastRomId = `${USE_ROM_FILE}_0`; const item = Menu.getApplicationMenu().getMenuItemById(lastRomId); if (item) { item.checked = false; } if (recentOptions?.rom) { recentRomName = null; recentOptions = { ...recentOptions, rom: undefined }; this.requestMachine(); } this.setContext(); }, }); if (recentRoms.length > 0) { romsSubmenu.push({ type: "separator" }); for (let i = 0; i < recentRoms.length; i++) { romsSubmenu.push({ id: `${USE_ROM_FILE}_${i}`, label: path.basename(recentRoms[i]), type: i === 0 ? "checkbox" : "normal", checked: i === 0 && recentRomSelected, click: () => this.selectRecentRomItem(i), }); } } romsSubmenu.push( { type: "separator" }, { id: SELECT_ROM_FILE, label: "Select ROM file...", click: async () => await this.selectRomFileToUse(), } ); return [ { id: LCD_DIMS, type: "submenu", label: "LCD resolution", submenu: [ { id: Z88_640_64, type: "radio", label: "640 x 64", click: () => this.setLcd(Z88_640_64, "640x64", 0xff, 8), }, { id: Z88_640_320, type: "radio", label: "640 x 320", click: () => this.setLcd(Z88_640_320, "640x320", 0xff, 40), }, { id: Z88_640_480, type: "radio", label: "640 x 480", click: () => this.setLcd(Z88_640_480, "640x480", 0xff, 60), }, { id: Z88_800_320, type: "radio", label: "800 x 320", click: () => this.setLcd(Z88_800_320, "800x320", 100, 40), }, { id: Z88_800_480, type: "radio", label: "800 x 480", click: () => this.setLcd(Z88_800_480, "800x480", 100, 60), }, ], }, { id: KEYBOARDS, label: "Keyboard layout", type: "submenu", submenu: [ { id: UK_KEYBOARD, label: "British && American", type: "radio", click: () => { kbLayout = "uk"; mainProcessStore.dispatch(emulatorSetKeyboardAction(kbLayout)()); }, }, { id: ES_KEYBOARD, label: "Spanish", type: "radio", click: () => { kbLayout = "es"; mainProcessStore.dispatch(emulatorSetKeyboardAction(kbLayout)()); }, }, { id: FR_KEYBOARD, label: "French", type: "radio", click: () => { kbLayout = "fr"; mainProcessStore.dispatch(emulatorSetKeyboardAction(kbLayout)()); }, }, { id: DE_KEYBOARD, label: "German", type: "radio", click: () => { kbLayout = "de"; mainProcessStore.dispatch(emulatorSetKeyboardAction(kbLayout)()); }, }, { id: DK_KEYBOARD, label: "Danish && Norwegian", type: "radio", click: () => { kbLayout = "dk"; mainProcessStore.dispatch(emulatorSetKeyboardAction(kbLayout)()); }, }, { id: SE_KEYBOARD, label: "Swedish && Finish", type: "radio", click: () => { kbLayout = "se"; mainProcessStore.dispatch(emulatorSetKeyboardAction(kbLayout)()); }, }, ], }, { type: "separator" }, { id: SOFT_RESET, label: "Soft reset", accelerator: "F8", click: async () => await this.softReset(), }, { id: HARD_RESET, label: "Hard reset", accelerator: "F9", click: async () => await this.hardReset(), }, { type: "separator" }, { id: PRESS_SHIFTS, label: "Press both SHIFT keys", accelerator: "F6", click: async () => await this.pressBothShifts(), }, { id: BATTERY_LOW, label: "Raise Battery low signal", click: async () => await this.raiseBatteryLow(), }, { type: "separator" }, { id: ROM_MENU, type: "submenu", label: "Select ROM", submenu: romsSubmenu, }, { type: "separator" }, { id: INSERT_CARDS, label: "Insert card in", type: "submenu", submenu: [ { id: INS_SLOT1, label: `Slot 1${lastSlot1FileName ? ` (${path.basename(lastSlot1FileName)})` : ""}`, click: () => { this.selectCardFileToUse(1) }, }, { id: INS_SLOT2, label: `Slot 2${lastSlot2FileName ? ` (${path.basename(lastSlot2FileName)})` : ""}`, click: () => { this.selectCardFileToUse(2) }, }, { id: INS_SLOT3, label: `Slot 3${lastSlot3FileName ? ` (${path.basename(lastSlot3FileName)})` : ""}`, click: () => { this.selectCardFileToUse(3) }, }, ], }, { type: "separator" }, { id: REMOVE_CARDS, label: "Remove card from", type: "submenu", submenu: [ { id: REM_SLOT1, label: "Slot 1", click: () => { this.removeCardFromSlot(1); }, }, { id: REM_SLOT2, label: "Slot 2", click: () => { this.removeCardFromSlot(2); }, }, { id: REM_SLOT3, label: "Slot 3", click: () => { this.removeCardFromSlot(3); }, }, ], }, ]; } /** * Items to add to the Help menu */ provideHelpMenuItems(): MenuItemConstructorOptions[] | null { return this.getHyperlinkItems(z88Links); } /** * When the application state changes, you can update the menus */ updateMenuStatus(state: EmulatorPanelState): void { const menu = Menu.getApplicationMenu(); const softReset = menu.getMenuItemById(SOFT_RESET); if (softReset) { // --- Soft reset is available only if the machine is started, paused, or stopped. softReset.enabled = state.executionState > 0; } // --- Select the current LCD dimension const lcdType = menu.getMenuItemById(menuIdFromMachineId(recentLcdType)); if (lcdType) { lcdType.checked = true; } // --- Select the current keyboard layout const keyboardId = `cz88_${ state?.keyboardLayout ? state.keyboardLayout : "uk" }_layout`; const keyboardItem = menu.getMenuItemById(keyboardId); if (keyboardItem) { keyboardItem.checked = true; } // --- Enable/disable commands requiring a running machine const bothShifts = menu.getMenuItemById(PRESS_SHIFTS); if (bothShifts) { bothShifts.enabled = state.executionState === 1; } const batLow = menu.getMenuItemById(BATTERY_LOW); if (batLow) { batLow.enabled = state.executionState === 1; } } /** * Gets the startup ROMs for the machine */ getStartupRoms(): Uint8Array[] | string { return this.loadRoms([DEFAULT_ROM], [0x2_0000, 0x4_0000, 0x8_0000]); } /** * Override this method to get the machine-specific settings */ getMachineSpecificSettings(): Record<string, any> { const state = mainProcessStore.getState().emulatorPanelState; return { lcd: lcdLabel, kbLayout, romFile: recentRoms.length > 0 ? recentRoms[0] : null, slot1File: lastSlot1FileName, slot2File: lastSlot2FileName, slot3File: lastSlot3FileName, clockMultiplier: state.clockMultiplier, soundLevel: state.soundLevel, }; } /** * Override this method to set the machine-specific settings */ async setMachineSpecificSettings( settings: Record<string, any> ): Promise<void> { if (settings.lcd) { switch (settings.lcd) { case "640x64": this.setLcd(Z88_640_64, "640x64", 0xff, 8); break; case "640x320": this.setLcd(Z88_640_320, "640x320", 0xff, 40); break; case "640x480": this.setLcd(Z88_640_480, "640x480", 0xff, 60); break; case "800x320": this.setLcd(Z88_800_320, "800x320", 100, 40); break; case "800x480": this.setLcd(Z88_800_480, "800x480", 100, 60); break; } } if (settings.kbLayout) { switch (settings.kbLayout) { case "uk": case "fr": case "es": case "de": case "dk": case "se": kbLayout = settings.kbLayout; mainProcessStore.dispatch(emulatorSetKeyboardAction(kbLayout)()); break; } } if (settings.clockMultiplier) { mainProcessStore.dispatch( emulatorSetClockMultiplierAction(settings.clockMultiplier)() ); } if (settings.soundLevel) { AppWindow.instance.setSoundLevel(settings.soundLevel); AppWindow.instance.setSoundLevelMenu(false, settings.soundLevel); } await new Promise((r) => setTimeout(r, 600)); if (settings.romFile) { await this.selectRomFileToUse(settings.romFile); } if (settings.slot1File) { await this.selectCardFileToUse(1, settings.slot1File); } if (settings.slot2File) { await this.selectCardFileToUse(2, settings.slot2File); } if (settings.slot3File) { await this.selectCardFileToUse(3, settings.slot3File); } } /** * Sets the Z88 with the specified LCD type * @param typeId Machine type with LCD size specification */ private requestMachine(): void { const typeId = `${recentLcdType}_${recentRomName ?? ""}_${lastSlot1FileName ?? "$"}_${lastSlot2FileName ?? "$"}_${lastSlot3FileName ?? "$"}`; this.appWindow.requestMachineType(typeId, recentOptions); } /** * Sets the Z88 LCD mode * @param menuId LCD menu id * @param label LCD label * @param scw LCD width * @param sch LCD height */ private setLcd( menuId: string, label: string, scw: number, sch: number ): void { recentLcdType = machineIdFromMenuId(menuId); lcdLabel = label; recentOptions = { ...recentOptions, scw, sch }; this.requestMachine(); this.setContext(); } /** * Select the ROM file to use with Z88 */ private async selectRomFileToUse(filename?: string): Promise<void> { if (!filename) { filename = await this.selectRomFileFromDialog(); if (!filename) { return; } } const contents = await this.checkCz88Rom(filename); if (typeof contents === "string") { await dialog.showMessageBox(this.appWindow.window, { title: "ROM error", message: contents, type: "error", }); return; } // --- Ok, let's use the contents of this file recentOptions = { ...recentOptions, rom: contents }; // --- Use the selected contents const recentFileIdx = recentRoms.indexOf(filename); if (recentFileIdx >= 0) { recentRoms.splice(recentFileIdx, 1); } recentRoms.unshift(filename); recentRoms.splice(4); // --- Now set the ROM name and refresh the menu recentRomName = path.basename(filename); recentRomSelected = true; this.appWindow.setupMenu(); // --- Request the current machine type this.requestMachine(); } /** * Select a ROM file to use with Z88 */ private async selectRomFileFromDialog(): Promise<string | null> { const window = this.appWindow.window; const result = await dialog.showOpenDialog(window, { title: "Open ROM file", filters: [ { name: "ROM files", extensions: ["rom"] }, { name: "BIN files", extensions: ["bin"] }, { name: "All Files", extensions: ["*"] }, ], }); return result ? result.filePaths[0] : null; } /** * Select the card file to use with Z88 */ private async selectCardFileToUse( slot: number, filename?: string ): Promise<void> { if (!filename) { filename = await this.selectCardFileFromDialog(); if (!filename) { return; } } const contents = await this.checkSlotFile(filename); if (typeof contents === "string") { await dialog.showMessageBox(this.appWindow.window, { title: "Card file error", message: contents, type: "error", }); return; } switch (slot) { case 1: lastSlot1FileName = filename; recentOptions = { ...recentOptions, slot1: contents }; break; case 2: lastSlot2FileName = filename; recentOptions = { ...recentOptions, slot2: contents }; break; default: lastSlot3FileName = filename; recentOptions = { ...recentOptions, slot3: contents }; break; } // --- Now refresh the menu this.appWindow.setupMenu(); // --- Request the current machine type this.requestMachine(); } /** * Removes card from the specified slot * @param slot Slot index */ private removeCardFromSlot(slot: number): void { switch (slot) { case 1: lastSlot1FileName = null; recentOptions = { ...recentOptions, slot1: null }; break; case 2: lastSlot2FileName = null; recentOptions = { ...recentOptions, slot2: null }; break; default: lastSlot3FileName = null; recentOptions = { ...recentOptions, slot3: null }; break; } // --- Now refresh the menu this.appWindow.setupMenu(); // --- Request the current machine type this.requestMachine(); } /** * Select a ROM file to use with Z88 */ private async selectCardFileFromDialog(): Promise<string | null> { const window = this.appWindow.window; const result = await dialog.showOpenDialog(window, { title: "Open EPROM file", filters: [ { name: "EPR files", extensions: ["epr"] }, { name: "All Files", extensions: ["*"] }, ], }); return result ? result.filePaths[0] : null; } /** * Checks if the specified file is a valid Z88 ROM * @param filename ROM file name * @returns The contents, if the ROM is valid; otherwise, the error message */ private async checkCz88Rom(filename: string): Promise<string | Uint8Array> { try { const contents = Uint8Array.from(fs.readFileSync(filename)); // --- Check contents length if ( contents.length !== 0x8_0000 && contents.length !== 0x4_0000 && contents.length !== 0x2_0000 ) { return `Invalid ROM file length: ${contents.length}. The ROM file length can be 128K, 256K, or 512K.`; } // --- Check watermark if (!this.isOZRom(contents)) { return "The file does not contain the OZ ROM watermark."; } // --- Done: valid ROM return contents; } catch (err) { // --- This error is intentionally ignored return ( `Error processing ROM file ${filename}. ` + "Please check if you have the appropriate access rights " + "to read the files contents and the file is a valid ROM file." ); } } /** * Checks if the specified file is a valid Z88 ROM * @param filename ROM file name * @returns The contents, if the ROM is valid; otherwise, the error message */ private async checkSlotFile(filename: string): Promise<string | Uint8Array> { try { const contents = Uint8Array.from(fs.readFileSync(filename)); // --- Check contents length if ( contents.length !== 0x10_0000 && contents.length !== 0x08_0000 && contents.length !== 0x04_0000 && contents.length !== 0x02_0000 && contents.length !== 0x00_8000 ) { return `Invalid card file length: ${contents.length}. The card file length can be 32K, 128K, 256K, 512K, or 1M.`; } // --- Check watermark // --- Done: valid ROM return contents; } catch (err) { // --- This error is intentionally ignored return ( `Error processing card file ${filename}. ` + "Please check if you have the appropriate access rights " + "to read the files contents and the file is a valid ROM file." ); } } /** * Selects one of the recent ROM items * @param idx Selected ROM index */ private selectRecentRomItem(idx: number): void { if (idx < 0 || idx >= recentRoms.length) { return; } this.selectRomFileToUse(recentRoms[idx]); } /** * */ private checkTopRecentRom(): void { // --- Clear the default ROM const defaultItem = Menu.getApplicationMenu().getMenuItemById(USE_DEFAULT_ROM); if (defaultItem) { defaultItem.checked = false; } // --- Set the top ROM const lastRomId = `${USE_ROM_FILE}_0`; const item = Menu.getApplicationMenu().getMenuItemById(lastRomId); if (item) { item.checked = true; } } /** * Check if specified slot contains an OZ Operating system * @param contents Binary contents * @returns true if Application Card is available in slot; otherwise false */ private isOZRom(contents: Uint8Array): boolean { const topBankOffset = (contents.length & 0xe_c000) - 0x4000; return ( contents[topBankOffset + 0x3ffb] === 0x81 && contents[topBankOffset + 0x3ffe] === "O".charCodeAt(0) && contents[topBankOffset + 0x3fff] === "Z".charCodeAt(0) ); } /** * Execure soft reset */ private async softReset(): Promise<void> { if (await this.confirmReset("Soft")) { mainProcessStore.dispatch(machineCommandAction(CZ88_SOFT_RESET)()); } } /** * Execute hard reset */ private async hardReset(): Promise<void> { if (await this.confirmReset("Hard")) { mainProcessStore.dispatch(machineCommandAction(CZ88_HARD_RESET)()); } } /** * Press both shift keys */ private async pressBothShifts(): Promise<void> { mainProcessStore.dispatch(machineCommandAction(CZ88_PRESS_BOTH_SHIFTS)()); } /** * Press both shift keys */ private async raiseBatteryLow(): Promise<void> { mainProcessStore.dispatch(machineCommandAction(CZ88_BATTERY_LOW)()); } /** * Display a confirm message for reset */ private async confirmReset(type: string): Promise<boolean> { const result = await dialog.showMessageBox(this.appWindow.window, { title: `Confirm Cambridge Z88 ${type} Reset`, message: "Are you sure you want to reset the machine?", buttons: ["Yes", "No"], defaultId: 0, type: "question", }); return result.response === 0; } }
the_stack
import { jsx } from '@emotion/react' import { Console } from 'console-feed' import { Resizable, ResizeCallback } from 're-resizable' import React from 'react' import { ErrorMessage, ErrorMessageSeverity, messageIsFatalOrError, messageIsWarning, } from '../../core/shared/error-messages' import { ConsoleLog } from '../editor/store/editor-state' import { CursorPosition } from './code-editor-utils' import { clampValue } from '../../core/shared/math-utils' import { WarningIcon } from '../../uuiui/warning-icon' import { VariableSizeList as List } from 'react-window' import { useColorTheme, UtopiaTheme } from '../../uuiui/styles/theme' import { FlexRow } from '../../uuiui/widgets/layout/flex-row' import { NO_OP } from '../../core/shared/utils' import { TabComponent } from '../../uuiui/tab' import { Icons } from '../../uuiui/icons' import { SimpleFlexColumn } from '../../uuiui/widgets/layout/flex-column' import { UIRow } from '../../uuiui' import { groupBy } from '../../core/shared/array-utils' interface ErrorMessageRowProps { errorMessage: ErrorMessage onOpenFile: (path: string, cursorPosition: CursorPosition | null) => void } const ErrorMessageRowHeight = 31 const ErrorMessageRow = (props: ErrorMessageRowProps) => { const colorTheme = useColorTheme() const { onOpenFile } = props const { fileName, startLine, startColumn } = props.errorMessage const onClick = React.useCallback(() => { const cursorPositon = startLine == null || startColumn == null ? null : { line: startLine, column: startColumn, } onOpenFile(fileName, cursorPositon) }, [onOpenFile, fileName, startLine, startColumn]) const isSourceKnown = props.errorMessage.fileName != '' return ( <FlexRow css={{ height: ErrorMessageRowHeight, flexGrow: 1, color: colorTheme.neutralForeground.value, fontSize: 12, paddingTop: 6, paddingBottom: 6, paddingLeft: 20, paddingRight: 8, cursor: isSourceKnown ? 'pointer' : 'default', '&:hover': { background: colorTheme.emphasizedBackground.value, }, }} onClick={isSourceKnown ? onClick : NO_OP} > <WarningIcon color={errorMessageSeverityToColor(props.errorMessage.severity)} /> <span style={{ marginLeft: 4, userSelect: 'text' }}>{props.errorMessage.source}: </span> <span style={{ marginLeft: 4, userSelect: 'text' }}>{props.errorMessage.message}</span> <span style={{ marginLeft: 4, color: colorTheme.subduedForeground.value, }} > {isSourceKnown ? `${props.errorMessage.startLine}:${props.errorMessage.startColumn}, ${props.errorMessage.fileName}` : null} </span> </FlexRow> ) } function errorMessageSeverityToColor(severity: ErrorMessageSeverity) { switch (severity) { case 'warning': return 'warning' case 'error': case 'fatal': return 'error' default: const _exhaustiveCheck: never = severity throw new Error(`Unknown severity ${severity}}`) } } function getTabStyleForErrors( errorMessages: Array<ErrorMessage>, colorTheme: any, ): { backgroundColor: string } { const errorStyle = { backgroundColor: colorTheme.errorBgSolid.value } const warningStyle = { backgroundColor: colorTheme.warningBgSolid.value } const defaultStyle = { backgroundColor: colorTheme.subtleBackground.value } const isFatalOrError = errorMessages.some(messageIsFatalOrError) const isWarning = errorMessages.some(messageIsWarning) if (isFatalOrError) { return errorStyle } else if (isWarning) { return warningStyle } return defaultStyle } function getTabStyleForLogs( canvasConsoleLogs: Array<ConsoleLog>, colorTheme: any, ): { backgroundColor: string } { const errorStyle = { backgroundColor: colorTheme.errorBgSolid.value } const warningStyle = { backgroundColor: colorTheme.warningBgSolid.value } const defaultStyle = { backgroundColor: 'grey' } const isError = canvasConsoleLogs.some((log) => { return log.method === 'error' }) const isWarning = canvasConsoleLogs.some((log) => { return log.method === 'warn' }) if (isError) { return errorStyle } else if (isWarning) { return warningStyle } return defaultStyle } interface CodeEditorTabPaneProps { errorMessages: Array<ErrorMessage> onOpenFile: (path: string, cursorPosition: CursorPosition | null) => void canvasConsoleLogs: Array<ConsoleLog> } const ProblemRowHeight = 29 const ProblemTabBarHeight = 32 type OpenCodeEditorTab = 'problems' | 'console' export const CodeEditorTabPane = React.memo<CodeEditorTabPaneProps>( ({ errorMessages, onOpenFile, canvasConsoleLogs }) => { const colorTheme = useColorTheme() const defaultHeightWhenOpen = ProblemTabBarHeight + ProblemRowHeight * clampValue(Math.max(errorMessages.length, canvasConsoleLogs.length), 3, 10) const [userDefinedHeightWhenOpen, setHeightWhenOpen] = React.useState<number | null>(null) const [isOpen, setIsOpen] = React.useState(false) const resizableRef = React.useRef<Resizable>(null) const heightWhenOpen = userDefinedHeightWhenOpen ?? defaultHeightWhenOpen const toggleIsOpen = React.useCallback(() => { setIsOpen((value) => { const newValue = !value if (resizableRef.current != null) { resizableRef.current.updateSize({ height: newValue ? heightWhenOpen : ProblemTabBarHeight, width: resizableRef.current.size.width, }) } return newValue }) }, [heightWhenOpen]) const onResize: ResizeCallback = React.useCallback((_, __, elementRef) => { if (elementRef.clientHeight > ProblemTabBarHeight) { setHeightWhenOpen(elementRef.clientHeight) setIsOpen(true) } else { setIsOpen(false) } }, []) const [selectedTab, setSelectedTab] = React.useState<OpenCodeEditorTab>('problems') const selectProblemsTab = React.useCallback(() => { if (!isOpen) { toggleIsOpen() } setSelectedTab('problems') }, [setSelectedTab, isOpen, toggleIsOpen]) const selectConsoleTab = React.useCallback(() => { if (!isOpen) { toggleIsOpen() } setSelectedTab('console') }, [setSelectedTab, isOpen, toggleIsOpen]) const problemsTabBackgroundColor = getTabStyleForErrors(errorMessages, colorTheme) .backgroundColor const ProblemsTabLabel = React.useMemo(() => { return ( <span> Problems <span style={{ marginLeft: 8, fontSize: 10, padding: '1px 5px', borderRadius: 2, fontWeight: 500, color: colorTheme.neutralInvertedForeground.value, backgroundColor: problemsTabBackgroundColor, }} > {errorMessages.length} </span> </span> ) }, [colorTheme, problemsTabBackgroundColor, errorMessages.length]) const consoleTabBackgroundColor = getTabStyleForLogs(canvasConsoleLogs, colorTheme) .backgroundColor const ConsoleTabLabel = React.useMemo(() => { return ( <span> Console <span style={{ marginLeft: 8, fontSize: 10, padding: '1px 5px', borderRadius: 2, fontWeight: 500, color: colorTheme.neutralInvertedForeground.value, backgroundColor: consoleTabBackgroundColor, }} > {canvasConsoleLogs.length} </span> </span> ) }, [colorTheme, consoleTabBackgroundColor, canvasConsoleLogs.length]) function getTabContents() { switch (selectedTab) { case 'problems': return ( <ProblemsTab errorMessages={errorMessages} height={heightWhenOpen} onOpenFile={onOpenFile} /> ) case 'console': return ( <div className='label-consolewrapper' // we need increased specificity because of our global settings for user-selection, // and console-feed 2.8x doesn't allow for style injection, despite the docs. css={{ '& *': { userSelect: 'text', WebkitUserSelect: 'text', cursor: 'text', }, }} style={{ backgroundColor: colorTheme.neutralInvertedBackground.value, color: 'white', height: '100%', // There probably is a better fix but I've run out of goats to sacrifice paddingBottom: ProblemTabBarHeight, overflowY: 'scroll', overscrollBehavior: 'contain', scrollSnapType: 'y proximity', }} > <Console logs={canvasConsoleLogs} variant={'dark'} styles={{ BASE_FONT_FAMILY: 'mono', }} /> {/* since we can't know the last console item as logged in console, we attach a cheat anchor here */} <span style={{ width: 0, height: 0, display: 'block', scrollSnapAlign: 'end', scrollMarginBlockEnd: '50px', }} /> </div> ) default: return null } } return ( <Resizable ref={resizableRef} defaultSize={{ height: ProblemTabBarHeight + (isOpen ? heightWhenOpen : 0), width: '100%' }} minHeight={ProblemTabBarHeight} onResize={onResize} enable={{ top: true, }} style={{ backgroundColor: colorTheme.neutralBackground.value, flexGrow: 0, boxShadow: `0px 1px 0px 0px ${colorTheme.subduedBorder.value}`, }} > <UIRow style={{ borderBottom: `1px solid ${colorTheme.subduedBorder.value}`, alignItems: 'stretch', height: 32, }} > <TabComponent onClick={selectProblemsTab} onDoubleClick={toggleIsOpen} selected={selectedTab === 'problems'} showCloseIndicator={false} showModifiedIndicator={false} label={ProblemsTabLabel} /> <TabComponent onClick={selectConsoleTab} onDoubleClick={toggleIsOpen} selected={selectedTab == 'console'} showCloseIndicator={false} showModifiedIndicator={false} label={ConsoleTabLabel} /> </UIRow> {isOpen ? getTabContents() : null} </Resizable> ) }, ) interface ProblemsTabProps { errorMessages: Array<ErrorMessage> height: number onOpenFile: (path: string, cursorPosition: CursorPosition | null) => void } interface ProblemsHeaderRowData { type: 'HEADER' fileName: string } interface ProblemsErrorRowData { type: 'ERROR_MESSAGE' fileName: string errorMessage: ErrorMessage } type ProblemRowData = ProblemsHeaderRowData | ProblemsErrorRowData interface ProblemsHeaderRowProps { fileName: string } interface ProblemsErrorRowProps { errorMessage: ErrorMessage onOpenFile: (path: string, cursorPosition: CursorPosition | null) => void } const ProblemsHeaderRowHeight = 25 const ProblemsHeaderRow = React.memo((props: ProblemsHeaderRowProps) => { const { fileName } = props return ( <FlexRow style={{ height: ProblemsHeaderRowHeight, padding: '4px 8px' }}> <Icons.React /> <span style={{ marginLeft: 4 }}> {fileName}</span> </FlexRow> ) }) const ProblemsErrorRow = React.memo((props: ProblemsErrorRowProps) => { const { errorMessage, onOpenFile } = props return <ErrorMessageRow errorMessage={errorMessage} onOpenFile={onOpenFile} /> }) function getRowHeight(index: number, data: Array<ProblemRowData>): number { const row = data[index] if (row == null) { return 0 } else if (row.type === 'HEADER') { return ProblemsHeaderRowHeight } else { return ErrorMessageRowHeight } } const ProblemsTab = React.memo((props: ProblemsTabProps) => { const { errorMessages, height, onOpenFile } = props const rowData: Array<ProblemRowData> = React.useMemo(() => { const errorsByFile = groupBy((error: ErrorMessage) => error.fileName, errorMessages) let rows: Array<ProblemRowData> = [] Object.keys(errorsByFile).forEach(function (fileName) { if (fileName != '') { rows.push({ type: 'HEADER', fileName: fileName, }) } errorsByFile[fileName].forEach(function (errorMessage) { rows.push({ type: 'ERROR_MESSAGE', fileName: fileName, errorMessage: errorMessage, }) }) }) return rows }, [errorMessages]) const getItemSize = React.useCallback( (index: number) => { const row = rowData[index] if (row == null) { return 0 } else if (row.type === 'HEADER') { return ProblemsHeaderRowHeight } else { return ErrorMessageRowHeight } }, [rowData], ) const Row = React.useCallback( ({ index, style }: any) => { const row = rowData[index] if (row == null) { return null } else if (row.type === 'HEADER') { return ( <div style={style} key={`error-row-${row.fileName}-filename`}> <ProblemsHeaderRow fileName={row.fileName} /> </div> ) } else { return ( <div style={style} key={`error-row-${row.fileName}-${index}-${row.errorMessage.startLine}-${row.errorMessage.startColumn}`} > <ProblemsErrorRow errorMessage={row.errorMessage} onOpenFile={onOpenFile} /> </div> ) } }, [rowData, onOpenFile], ) return ( <SimpleFlexColumn> <List height={height} itemCount={rowData.length} itemSize={getItemSize} width={'100%'}> {Row} </List> </SimpleFlexColumn> ) })
the_stack
import { Accordion, AccordionDetails, AccordionSummary, Slider, Typography, } from "@material-ui/core"; import { styled, Button, TextField, Box, Drawer, Toolbar, } from "@material-ui/core"; import { compileDomain, showError, SynthesizerSetting } from "@penrose/core"; import React from "react"; import { MultiselectDropdown } from "./MultiselectDropdown"; const DEFAULT_MUTATION_COUNT = [1, 4]; interface StmtType { tag: string; values: string[]; } interface PartialEnv { types: StmtType; constructors: StmtType; functions: StmtType; predicates: StmtType; } const defaultEnv: PartialEnv = { types: { tag: "Type", values: [], }, constructors: { tag: "Constructor", values: [], }, functions: { tag: "Function", values: [], }, predicates: { tag: "Predicate", values: [], }, }; export interface SettingsProps { generateCallback: ( setting: SynthesizerSetting, numPrograms: number, dsl: string, sub: string, sty: string ) => void; defaultDomain: string; defaultStyle: string; } interface SettingState { substance: string; setting: SynthesizerSetting | undefined; numPrograms: number; domainEnv: PartialEnv; domain: string; style: string; } const InputContainer = styled(Box)({ padding: "0.5rem", paddingTop: "1rem", width: "25vw", }); const SettingsDrawer = styled(Drawer)(({ theme }) => ({ width: "25vw", flexShrink: 0, overflow: "auto", zIndex: theme.zIndex.appBar - 10, display: "flex", })); const ButtonContainer = styled("div")({ display: "flex", justifyContent: "center", alignItems: "center", padding: "1rem 0 2rem 0", }); const SliderDiv = styled("div")({ padding: "0.5rem", paddingBottom: "0", }); const SliderLabel = styled(Typography)({ color: "gray", fontSize: "1rem", }); const AccordionHeaderStyled = styled(AccordionSummary)(({ theme }) => ({ borderColor: theme.palette.primary.light, borderWidth: "1px", borderStyle: "outset", color: theme.palette.primary.main, borderRadius: "5px", })); const AccordionBodyStyled = styled(AccordionDetails)(({ theme }) => ({ borderColor: theme.palette.primary.light, borderWidth: "1px", borderStyle: "outset", borderRadius: "3px", borderTop: "0px solid black", })); export class Settings extends React.Component<SettingsProps, SettingState> { constructor(props: SettingsProps) { super(props); this.state = { substance: "", setting: undefined, numPrograms: 10, domainEnv: defaultEnv, domain: this.props.defaultDomain, style: this.props.defaultStyle, }; } componentDidMount() { fetch("public/files/sub_example.txt") .then((r) => r.text()) .then((text) => { this.setState({ substance: text, }); }); fetch("public/files/defaultSetting.json") .then((r) => r.json()) .then((text) => { this.setState({ setting: text }); }); } // TODO: current implementation will not update the UI if there is a domain compiler error // at any point in time, instead, we should display a helpful error message. updateDomainEnv = (newDomain: string) => { const result = compileDomain(newDomain); if (result.isOk()) { this.setState({ domainEnv: { types: { tag: "Type", values: [...result.value.types.keys()], }, constructors: { tag: "Constructor", values: [...result.value.constructors.keys()], }, functions: { tag: "Function", values: [...result.value.functions.keys()], }, predicates: { tag: "Predicate", values: [...result.value.predicates.keys()], }, }, }); } else { console.error(showError(result.error)); } }; componentDidUpdate(prev: SettingsProps) { if ( this.props.defaultDomain !== prev.defaultDomain && this.props.defaultDomain.length > 0 ) { this.updateDomainEnv(this.props.defaultDomain); this.setState({ domain: this.props.defaultDomain }); } if ( this.props.defaultStyle !== prev.defaultStyle && this.props.defaultStyle.length > 0 ) { this.setState({ style: this.props.defaultStyle, }); } } onTextAreaChange = (event: any) => { event.preventDefault(); if (event.target.name === "sub") { this.setState({ substance: event.target.value, }); } else if (event.target.name === "dsl") { this.setState({ domain: event.target.value, }); this.updateDomainEnv(event.target.value); } else if (event.target.name === "sty") { this.setState({ style: event.target.value, }); } }; onGenerateClick = () => { if (this.state.setting) this.props.generateCallback( this.state.setting, this.state.numPrograms, this.state.domain, this.state.substance, this.state.style ); }; onMutationCountChange = (event: any, newValue: number | number[]) => { if (this.state.setting) this.setState({ setting: { ...this.state.setting, mutationCount: newValue as [number, number], }, }); console.log(this.state.setting?.mutationCount); }; onProgCountChange = (event: any, newValue: number | number[]) => { this.setState({ numPrograms: newValue as number }); }; onChangeMultiselect = (op: string, stmtType: string) => ( selected: string[] ) => { const typeSelect = (s: string, op: any, arr: any[]) => { if (s === "Type") return { ...op, type: arr }; if (s === "Constructor") return { ...op, constructor: arr }; if (s === "Function") return { ...op, function: arr }; if (s === "Predicate") return { ...op, predicate: arr }; }; let newSetting = this.state.setting; if (newSetting) { switch (op) { case "Add": newSetting = { ...newSetting, add: typeSelect(stmtType, newSetting.add, selected), }; break; case "Delete": newSetting = { ...newSetting, delete: typeSelect(stmtType, newSetting.delete, selected), }; break; case "Edit": newSetting = { ...newSetting, edit: typeSelect(stmtType, newSetting.edit, selected), }; break; default: break; } this.setState({ setting: newSetting }); } }; getDefaults = (mutationType: string, stmtType: string): string[] => { let defaults: string[] = []; if (this.state.setting) { Object.entries(this.state.setting).map(([key, values]: [string, any]) => { if (mutationType.toLowerCase() === key) { Object.entries(values).map(([k, v]: [string, any]) => { if (stmtType.toLowerCase() === k) { defaults = v; } }); } }); } return defaults; }; inputElements = () => { return ["Add", "Edit", "Delete"].map((op) => ( <Accordion key={op} elevation={0}> <AccordionHeaderStyled>{`${op} Statements`}</AccordionHeaderStyled> <AccordionBodyStyled> <InputContainer> {Object.values(this.state.domainEnv).map((stmtType: StmtType) => ( <MultiselectDropdown stmtType={stmtType.tag} mutationType={op} key={`${op}-${stmtType.tag}`} // name={`${op}-${stmtType}`} onChange={this.onChangeMultiselect(op, stmtType.tag)} defaults={this.getDefaults(op, stmtType.tag)} options={stmtType.values} /> ))} </InputContainer> </AccordionBodyStyled> </Accordion> )); }; render() { return ( <SettingsDrawer variant="permanent"> {/* NOTE: Toolbar is used exclusively to space the content underneath the header of the page. The Settings element is floating so it must be included */} <Toolbar /> <InputContainer> <TextField rows={10} name="sub" multiline label="Substance Program:" variant="outlined" fullWidth onChange={this.onTextAreaChange} value={this.state.substance} /> <Accordion key="domain" elevation={0}> <AccordionHeaderStyled>{`Domain Program`}</AccordionHeaderStyled> <AccordionBodyStyled style={{ padding: 0 }}> <TextField rows={20} name="dsl" multiline variant="outlined" fullWidth inputProps={{ style: { fontSize: ".8rem" } }} style={{ padding: 0 }} onChange={this.onTextAreaChange} value={this.state.domain} /> </AccordionBodyStyled> </Accordion> <Accordion key="style" elevation={0}> <AccordionHeaderStyled>Style Program</AccordionHeaderStyled> <AccordionBodyStyled style={{ padding: 0 }}> <TextField rows={20} name="sty" multiline fullWidth variant="outlined" style={{ padding: 0 }} inputProps={{ style: { fontSize: ".8rem", overflow: "scroll" }, }} onChange={this.onTextAreaChange} value={this.state.style} /> </AccordionBodyStyled> </Accordion> <SliderDiv> <SliderLabel>Diagrams to generate:</SliderLabel> <Slider valueLabelDisplay="auto" step={1} marks={[ { value: 1, label: "1" }, { value: 10, label: "10" }, { value: 20, label: "20" }, ]} value={this.state.numPrograms} min={1} max={20} onChange={this.onProgCountChange} /> </SliderDiv> <SliderDiv> <SliderLabel>Mutations/program:</SliderLabel> <Slider valueLabelDisplay="auto" step={1} marks={[ { value: 1, label: "1" }, { value: 5, label: "5" }, ]} value={ this.state.setting ? this.state.setting.mutationCount : DEFAULT_MUTATION_COUNT } min={1} max={5} onChange={this.onMutationCountChange} /> </SliderDiv> </InputContainer> <br /> <InputContainer>{this.inputElements()}</InputContainer> <ButtonContainer> <Button onClick={this.onGenerateClick} color="primary" variant="contained" > Generate Diagrams </Button> </ButtonContainer> </SettingsDrawer> ); } }
the_stack
import { App, FirebaseArrayIndexError } from '../app'; import { AuthClientErrorCode, ErrorInfo, FirebaseAuthError } from '../utils/error'; import { deepCopy } from '../utils/deep-copy'; import * as validator from '../utils/validator'; import { AbstractAuthRequestHandler, useEmulator } from './auth-api-request'; import { FirebaseTokenGenerator, EmulatedSigner, handleCryptoSignerError } from './token-generator'; import { FirebaseTokenVerifier, createSessionCookieVerifier, createIdTokenVerifier, DecodedIdToken, } from './token-verifier'; import { AuthProviderConfig, SAMLAuthProviderConfig, AuthProviderConfigFilter, ListProviderConfigResults, SAMLConfig, OIDCConfig, OIDCConfigServerResponse, SAMLConfigServerResponse, UpdateAuthProviderRequest, OIDCAuthProviderConfig, CreateRequest, UpdateRequest, } from './auth-config'; import { UserRecord } from './user-record'; import { UserIdentifier, isUidIdentifier, isEmailIdentifier, isPhoneIdentifier, isProviderIdentifier, } from './identifier'; import { UserImportOptions, UserImportRecord, UserImportResult } from './user-import-builder'; import { ActionCodeSettings } from './action-code-settings-builder'; import { cryptoSignerFromApp } from '../utils/crypto-signer'; /** Represents the result of the {@link BaseAuth.getUsers} API. */ export interface GetUsersResult { /** * Set of user records, corresponding to the set of users that were * requested. Only users that were found are listed here. The result set is * unordered. */ users: UserRecord[]; /** Set of identifiers that were requested, but not found. */ notFound: UserIdentifier[]; } /** * Interface representing the object returned from a * {@link BaseAuth.listUsers} operation. Contains the list * of users for the current batch and the next page token if available. */ export interface ListUsersResult { /** * The list of {@link UserRecord} objects for the * current downloaded batch. */ users: UserRecord[]; /** * The next page token if available. This is needed for the next batch download. */ pageToken?: string; } /** * Represents the result of the {@link BaseAuth.deleteUsers}. * API. */ export interface DeleteUsersResult { /** * The number of user records that failed to be deleted (possibly zero). */ failureCount: number; /** * The number of users that were deleted successfully (possibly zero). * Users that did not exist prior to calling `deleteUsers()` are * considered to be successfully deleted. */ successCount: number; /** * A list of `FirebaseArrayIndexError` instances describing the errors that * were encountered during the deletion. Length of this list is equal to * the return value of {@link DeleteUsersResult.failureCount}. */ errors: FirebaseArrayIndexError[]; } /** * Interface representing the session cookie options needed for the * {@link BaseAuth.createSessionCookie} method. */ export interface SessionCookieOptions { /** * The session cookie custom expiration in milliseconds. The minimum allowed is * 5 minutes and the maxium allowed is 2 weeks. */ expiresIn: number; } /** * @internal */ export function createFirebaseTokenGenerator(app: App, tenantId?: string): FirebaseTokenGenerator { try { const signer = useEmulator() ? new EmulatedSigner() : cryptoSignerFromApp(app); return new FirebaseTokenGenerator(signer, tenantId); } catch (err) { throw handleCryptoSignerError(err); } } /** * Common parent interface for both `Auth` and `TenantAwareAuth` APIs. */ export abstract class BaseAuth { /** @internal */ protected readonly tokenGenerator: FirebaseTokenGenerator; /** @internal */ protected readonly idTokenVerifier: FirebaseTokenVerifier; /** @internal */ protected readonly sessionCookieVerifier: FirebaseTokenVerifier; /** * The BaseAuth class constructor. * * @param app - The FirebaseApp to associate with this Auth instance. * @param authRequestHandler - The RPC request handler for this instance. * @param tokenGenerator - Optional token generator. If not specified, a * (non-tenant-aware) instance will be created. Use this paramter to * specify a tenant-aware tokenGenerator. * @constructor * @internal */ constructor( app: App, /** @internal */ protected readonly authRequestHandler: AbstractAuthRequestHandler, tokenGenerator?: FirebaseTokenGenerator) { if (tokenGenerator) { this.tokenGenerator = tokenGenerator; } else { this.tokenGenerator = createFirebaseTokenGenerator(app); } this.sessionCookieVerifier = createSessionCookieVerifier(app); this.idTokenVerifier = createIdTokenVerifier(app); } /** * Creates a new Firebase custom token (JWT) that can be sent back to a client * device to use to sign in with the client SDKs' `signInWithCustomToken()` * methods. (Tenant-aware instances will also embed the tenant ID in the * token.) * * See {@link https://firebase.google.com/docs/auth/admin/create-custom-tokens | Create Custom Tokens} * for code samples and detailed documentation. * * @param uid - The `uid` to use as the custom token's subject. * @param developerClaims - Optional additional claims to include * in the custom token's payload. * * @returns A promise fulfilled with a custom token for the * provided `uid` and payload. */ public createCustomToken(uid: string, developerClaims?: object): Promise<string> { return this.tokenGenerator.createCustomToken(uid, developerClaims); } /** * Verifies a Firebase ID token (JWT). If the token is valid, the promise is * fulfilled with the token's decoded claims; otherwise, the promise is * rejected. * * If `checkRevoked` is set to true, first verifies whether the corresponding * user is disabled. If yes, an `auth/user-disabled` error is thrown. If no, * verifies if the session corresponding to the ID token was revoked. If the * corresponding user's session was invalidated, an `auth/id-token-revoked` * error is thrown. If not specified the check is not applied. * * See {@link https://firebase.google.com/docs/auth/admin/verify-id-tokens | Verify ID Tokens} * for code samples and detailed documentation. * * @param idToken - The ID token to verify. * @param checkRevoked - Whether to check if the ID token was revoked. * This requires an extra request to the Firebase Auth backend to check * the `tokensValidAfterTime` time for the corresponding user. * When not specified, this additional check is not applied. * * @returns A promise fulfilled with the * token's decoded claims if the ID token is valid; otherwise, a rejected * promise. */ public verifyIdToken(idToken: string, checkRevoked = false): Promise<DecodedIdToken> { const isEmulator = useEmulator(); return this.idTokenVerifier.verifyJWT(idToken, isEmulator) .then((decodedIdToken: DecodedIdToken) => { // Whether to check if the token was revoked. if (checkRevoked || isEmulator) { return this.verifyDecodedJWTNotRevokedOrDisabled( decodedIdToken, AuthClientErrorCode.ID_TOKEN_REVOKED); } return decodedIdToken; }); } /** * Gets the user data for the user corresponding to a given `uid`. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} * for code samples and detailed documentation. * * @param uid - The `uid` corresponding to the user whose data to fetch. * * @returns A promise fulfilled with the user * data corresponding to the provided `uid`. */ public getUser(uid: string): Promise<UserRecord> { return this.authRequestHandler.getAccountInfoByUid(uid) .then((response: any) => { // Returns the user record populated with server response. return new UserRecord(response.users[0]); }); } /** * Gets the user data for the user corresponding to a given email. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} * for code samples and detailed documentation. * * @param email - The email corresponding to the user whose data to * fetch. * * @returns A promise fulfilled with the user * data corresponding to the provided email. */ public getUserByEmail(email: string): Promise<UserRecord> { return this.authRequestHandler.getAccountInfoByEmail(email) .then((response: any) => { // Returns the user record populated with server response. return new UserRecord(response.users[0]); }); } /** * Gets the user data for the user corresponding to a given phone number. The * phone number has to conform to the E.164 specification. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} * for code samples and detailed documentation. * * @param phoneNumber - The phone number corresponding to the user whose * data to fetch. * * @returns A promise fulfilled with the user * data corresponding to the provided phone number. */ public getUserByPhoneNumber(phoneNumber: string): Promise<UserRecord> { return this.authRequestHandler.getAccountInfoByPhoneNumber(phoneNumber) .then((response: any) => { // Returns the user record populated with server response. return new UserRecord(response.users[0]); }); } /** * Gets the user data for the user corresponding to a given provider id. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data | Retrieve user data} * for code samples and detailed documentation. * * @param providerId - The provider ID, for example, "google.com" for the * Google provider. * @param uid - The user identifier for the given provider. * * @returns A promise fulfilled with the user data corresponding to the * given provider id. */ public getUserByProviderUid(providerId: string, uid: string): Promise<UserRecord> { // Although we don't really advertise it, we want to also handle // non-federated idps with this call. So if we detect one of them, we'll // reroute this request appropriately. if (providerId === 'phone') { return this.getUserByPhoneNumber(uid); } else if (providerId === 'email') { return this.getUserByEmail(uid); } return this.authRequestHandler.getAccountInfoByFederatedUid(providerId, uid) .then((response: any) => { // Returns the user record populated with server response. return new UserRecord(response.users[0]); }); } /** * Gets the user data corresponding to the specified identifiers. * * There are no ordering guarantees; in particular, the nth entry in the result list is not * guaranteed to correspond to the nth entry in the input parameters list. * * Only a maximum of 100 identifiers may be supplied. If more than 100 identifiers are supplied, * this method throws a FirebaseAuthError. * * @param identifiers - The identifiers used to indicate which user records should be returned. * Must not have more than 100 entries. * @returns A promise that resolves to the corresponding user records. * @throws FirebaseAuthError If any of the identifiers are invalid or if more than 100 * identifiers are specified. */ public getUsers(identifiers: UserIdentifier[]): Promise<GetUsersResult> { if (!validator.isArray(identifiers)) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, '`identifiers` parameter must be an array'); } return this.authRequestHandler .getAccountInfoByIdentifiers(identifiers) .then((response: any) => { /** * Checks if the specified identifier is within the list of * UserRecords. */ const isUserFound = ((id: UserIdentifier, userRecords: UserRecord[]): boolean => { return !!userRecords.find((userRecord) => { if (isUidIdentifier(id)) { return id.uid === userRecord.uid; } else if (isEmailIdentifier(id)) { return id.email === userRecord.email; } else if (isPhoneIdentifier(id)) { return id.phoneNumber === userRecord.phoneNumber; } else if (isProviderIdentifier(id)) { const matchingUserInfo = userRecord.providerData.find((userInfo) => { return id.providerId === userInfo.providerId; }); return !!matchingUserInfo && id.providerUid === matchingUserInfo.uid; } else { throw new FirebaseAuthError( AuthClientErrorCode.INTERNAL_ERROR, 'Unhandled identifier type'); } }); }); const users = response.users ? response.users.map((user: any) => new UserRecord(user)) : []; const notFound = identifiers.filter((id) => !isUserFound(id, users)); return { users, notFound }; }); } /** * Retrieves a list of users (single batch only) with a size of `maxResults` * starting from the offset as specified by `pageToken`. This is used to * retrieve all the users of a specified project in batches. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#list_all_users | List all users} * for code samples and detailed documentation. * * @param maxResults - The page size, 1000 if undefined. This is also * the maximum allowed limit. * @param pageToken - The next page token. If not specified, returns * users starting without any offset. * @returns A promise that resolves with * the current batch of downloaded users and the next page token. */ public listUsers(maxResults?: number, pageToken?: string): Promise<ListUsersResult> { return this.authRequestHandler.downloadAccount(maxResults, pageToken) .then((response: any) => { // List of users to return. const users: UserRecord[] = []; // Convert each user response to a UserRecord. response.users.forEach((userResponse: any) => { users.push(new UserRecord(userResponse)); }); // Return list of user records and the next page token if available. const result = { users, pageToken: response.nextPageToken, }; // Delete result.pageToken if undefined. if (typeof result.pageToken === 'undefined') { delete result.pageToken; } return result; }); } /** * Creates a new user. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#create_a_user | Create a user} * for code samples and detailed documentation. * * @param properties - The properties to set on the * new user record to be created. * * @returns A promise fulfilled with the user * data corresponding to the newly created user. */ public createUser(properties: CreateRequest): Promise<UserRecord> { return this.authRequestHandler.createNewAccount(properties) .then((uid) => { // Return the corresponding user record. return this.getUser(uid); }) .catch((error) => { if (error.code === 'auth/user-not-found') { // Something must have happened after creating the user and then retrieving it. throw new FirebaseAuthError( AuthClientErrorCode.INTERNAL_ERROR, 'Unable to create the user record provided.'); } throw error; }); } /** * Deletes an existing user. * * See {@link https://firebase.google.com/docs/auth/admin/manage-users#delete_a_user | Delete a user} * for code samples and detailed documentation. * * @param uid - The `uid` corresponding to the user to delete. * * @returns An empty promise fulfilled once the user has been * deleted. */ public deleteUser(uid: string): Promise<void> { return this.authRequestHandler.deleteAccount(uid) .then(() => { // Return nothing on success. }); } /** * Deletes the users specified by the given uids. * * Deleting a non-existing user won't generate an error (i.e. this method * is idempotent.) Non-existing users are considered to be successfully * deleted, and are therefore counted in the * `DeleteUsersResult.successCount` value. * * Only a maximum of 1000 identifiers may be supplied. If more than 1000 * identifiers are supplied, this method throws a FirebaseAuthError. * * This API is currently rate limited at the server to 1 QPS. If you exceed * this, you may get a quota exceeded error. Therefore, if you want to * delete more than 1000 users, you may need to add a delay to ensure you * don't go over this limit. * * @param uids - The `uids` corresponding to the users to delete. * * @returns A Promise that resolves to the total number of successful/failed * deletions, as well as the array of errors that corresponds to the * failed deletions. */ public deleteUsers(uids: string[]): Promise<DeleteUsersResult> { if (!validator.isArray(uids)) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, '`uids` parameter must be an array'); } return this.authRequestHandler.deleteAccounts(uids, /*force=*/true) .then((batchDeleteAccountsResponse) => { const result: DeleteUsersResult = { failureCount: 0, successCount: uids.length, errors: [], }; if (!validator.isNonEmptyArray(batchDeleteAccountsResponse.errors)) { return result; } result.failureCount = batchDeleteAccountsResponse.errors.length; result.successCount = uids.length - batchDeleteAccountsResponse.errors.length; result.errors = batchDeleteAccountsResponse.errors.map((batchDeleteErrorInfo) => { if (batchDeleteErrorInfo.index === undefined) { throw new FirebaseAuthError( AuthClientErrorCode.INTERNAL_ERROR, 'Corrupt BatchDeleteAccountsResponse detected'); } const errMsgToError = (msg?: string): FirebaseAuthError => { // We unconditionally set force=true, so the 'NOT_DISABLED' error // should not be possible. const code = msg && msg.startsWith('NOT_DISABLED') ? AuthClientErrorCode.USER_NOT_DISABLED : AuthClientErrorCode.INTERNAL_ERROR; return new FirebaseAuthError(code, batchDeleteErrorInfo.message); }; return { index: batchDeleteErrorInfo.index, error: errMsgToError(batchDeleteErrorInfo.message), }; }); return result; }); } /** * Updates an existing user. * * See {@link https://firebsae.google.com/docs/auth/admin/manage-users#update_a_user | Update a user} * for code samples and detailed documentation. * * @param uid - The `uid` corresponding to the user to update. * @param properties - The properties to update on * the provided user. * * @returns A promise fulfilled with the * updated user data. */ public updateUser(uid: string, properties: UpdateRequest): Promise<UserRecord> { // Although we don't really advertise it, we want to also handle linking of // non-federated idps with this call. So if we detect one of them, we'll // adjust the properties parameter appropriately. This *does* imply that a // conflict could arise, e.g. if the user provides a phoneNumber property, // but also provides a providerToLink with a 'phone' provider id. In that // case, we'll throw an error. properties = deepCopy(properties); if (properties?.providerToLink) { if (properties.providerToLink.providerId === 'email') { if (typeof properties.email !== 'undefined') { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, "Both UpdateRequest.email and UpdateRequest.providerToLink.providerId='email' were set. To " + 'link to the email/password provider, only specify the UpdateRequest.email field.'); } properties.email = properties.providerToLink.uid; delete properties.providerToLink; } else if (properties.providerToLink.providerId === 'phone') { if (typeof properties.phoneNumber !== 'undefined') { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, "Both UpdateRequest.phoneNumber and UpdateRequest.providerToLink.providerId='phone' were set. To " + 'link to a phone provider, only specify the UpdateRequest.phoneNumber field.'); } properties.phoneNumber = properties.providerToLink.uid; delete properties.providerToLink; } } if (properties?.providersToUnlink) { if (properties.providersToUnlink.indexOf('phone') !== -1) { // If we've been told to unlink the phone provider both via setting // phoneNumber to null *and* by setting providersToUnlink to include // 'phone', then we'll reject that. Though it might also be reasonable // to relax this restriction and just unlink it. if (properties.phoneNumber === null) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, "Both UpdateRequest.phoneNumber=null and UpdateRequest.providersToUnlink=['phone'] were set. To " + 'unlink from a phone provider, only specify the UpdateRequest.phoneNumber=null field.'); } } } return this.authRequestHandler.updateExistingAccount(uid, properties) .then((existingUid) => { // Return the corresponding user record. return this.getUser(existingUid); }); } /** * Sets additional developer claims on an existing user identified by the * provided `uid`, typically used to define user roles and levels of * access. These claims should propagate to all devices where the user is * already signed in (after token expiration or when token refresh is forced) * and the next time the user signs in. If a reserved OIDC claim name * is used (sub, iat, iss, etc), an error is thrown. They are set on the * authenticated user's ID token JWT. * * See {@link https://firebase.google.com/docs/auth/admin/custom-claims | * Defining user roles and access levels} * for code samples and detailed documentation. * * @param uid - The `uid` of the user to edit. * @param customUserClaims - The developer claims to set. If null is * passed, existing custom claims are deleted. Passing a custom claims payload * larger than 1000 bytes will throw an error. Custom claims are added to the * user's ID token which is transmitted on every authenticated request. * For profile non-access related user attributes, use database or other * separate storage systems. * @returns A promise that resolves when the operation completes * successfully. */ public setCustomUserClaims(uid: string, customUserClaims: object | null): Promise<void> { return this.authRequestHandler.setCustomUserClaims(uid, customUserClaims) .then(() => { // Return nothing on success. }); } /** * Revokes all refresh tokens for an existing user. * * This API will update the user's {@link UserRecord.tokensValidAfterTime} to * the current UTC. It is important that the server on which this is called has * its clock set correctly and synchronized. * * While this will revoke all sessions for a specified user and disable any * new ID tokens for existing sessions from getting minted, existing ID tokens * may remain active until their natural expiration (one hour). To verify that * ID tokens are revoked, use {@link BaseAuth.verifyIdToken} * where `checkRevoked` is set to true. * * @param uid - The `uid` corresponding to the user whose refresh tokens * are to be revoked. * * @returns An empty promise fulfilled once the user's refresh * tokens have been revoked. */ public revokeRefreshTokens(uid: string): Promise<void> { return this.authRequestHandler.revokeRefreshTokens(uid) .then(() => { // Return nothing on success. }); } /** * Imports the provided list of users into Firebase Auth. * A maximum of 1000 users are allowed to be imported one at a time. * When importing users with passwords, * {@link UserImportOptions} are required to be * specified. * This operation is optimized for bulk imports and will ignore checks on `uid`, * `email` and other identifier uniqueness which could result in duplications. * * @param users - The list of user records to import to Firebase Auth. * @param options - The user import options, required when the users provided include * password credentials. * @returns A promise that resolves when * the operation completes with the result of the import. This includes the * number of successful imports, the number of failed imports and their * corresponding errors. */ public importUsers( users: UserImportRecord[], options?: UserImportOptions): Promise<UserImportResult> { return this.authRequestHandler.uploadAccount(users, options); } /** * Creates a new Firebase session cookie with the specified options. The created * JWT string can be set as a server-side session cookie with a custom cookie * policy, and be used for session management. The session cookie JWT will have * the same payload claims as the provided ID token. * * See {@link https://firebase.google.com/docs/auth/admin/manage-cookies | Manage Session Cookies} * for code samples and detailed documentation. * * @param idToken - The Firebase ID token to exchange for a session * cookie. * @param sessionCookieOptions - The session * cookie options which includes custom session duration. * * @returns A promise that resolves on success with the * created session cookie. */ public createSessionCookie( idToken: string, sessionCookieOptions: SessionCookieOptions): Promise<string> { // Return rejected promise if expiresIn is not available. if (!validator.isNonNullObject(sessionCookieOptions) || !validator.isNumber(sessionCookieOptions.expiresIn)) { return Promise.reject(new FirebaseAuthError(AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION)); } return this.authRequestHandler.createSessionCookie( idToken, sessionCookieOptions.expiresIn); } /** * Verifies a Firebase session cookie. Returns a Promise with the cookie claims. * Rejects the promise if the cookie could not be verified. * * If `checkRevoked` is set to true, first verifies whether the corresponding * user is disabled: If yes, an `auth/user-disabled` error is thrown. If no, * verifies if the session corresponding to the session cookie was revoked. * If the corresponding user's session was invalidated, an * `auth/session-cookie-revoked` error is thrown. If not specified the check * is not performed. * * See {@link https://firebase.google.com/docs/auth/admin/manage-cookies#verify_session_cookie_and_check_permissions | * Verify Session Cookies} * for code samples and detailed documentation * * @param sessionCookie - The session cookie to verify. * @param checkForRevocation - Whether to check if the session cookie was * revoked. This requires an extra request to the Firebase Auth backend to * check the `tokensValidAfterTime` time for the corresponding user. * When not specified, this additional check is not performed. * * @returns A promise fulfilled with the * session cookie's decoded claims if the session cookie is valid; otherwise, * a rejected promise. */ public verifySessionCookie( sessionCookie: string, checkRevoked = false): Promise<DecodedIdToken> { const isEmulator = useEmulator(); return this.sessionCookieVerifier.verifyJWT(sessionCookie, isEmulator) .then((decodedIdToken: DecodedIdToken) => { // Whether to check if the token was revoked. if (checkRevoked || isEmulator) { return this.verifyDecodedJWTNotRevokedOrDisabled( decodedIdToken, AuthClientErrorCode.SESSION_COOKIE_REVOKED); } return decodedIdToken; }); } /** * Generates the out of band email action link to reset a user's password. * The link is generated for the user with the specified email address. The * optional {@link ActionCodeSettings} object * defines whether the link is to be handled by a mobile app or browser and the * additional state information to be passed in the deep link, etc. * * @example * ```javascript * var actionCodeSettings = { * url: 'https://www.example.com/?email=user@example.com', * iOS: { * bundleId: 'com.example.ios' * }, * android: { * packageName: 'com.example.android', * installApp: true, * minimumVersion: '12' * }, * handleCodeInApp: true, * dynamicLinkDomain: 'custom.page.link' * }; * admin.auth() * .generatePasswordResetLink('user@example.com', actionCodeSettings) * .then(function(link) { * // The link was successfully generated. * }) * .catch(function(error) { * // Some error occurred, you can inspect the code: error.code * }); * ``` * * @param email - The email address of the user whose password is to be * reset. * @param actionCodeSettings - The action * code settings. If specified, the state/continue URL is set as the * "continueUrl" parameter in the password reset link. The default password * reset landing page will use this to display a link to go back to the app * if it is installed. * If the actionCodeSettings is not specified, no URL is appended to the * action URL. * The state URL provided must belong to a domain that is whitelisted by the * developer in the console. Otherwise an error is thrown. * Mobile app redirects are only applicable if the developer configures * and accepts the Firebase Dynamic Links terms of service. * The Android package name and iOS bundle ID are respected only if they * are configured in the same Firebase Auth project. * @returns A promise that resolves with the generated link. */ public generatePasswordResetLink(email: string, actionCodeSettings?: ActionCodeSettings): Promise<string> { return this.authRequestHandler.getEmailActionLink('PASSWORD_RESET', email, actionCodeSettings); } /** * Generates the out of band email action link to verify the user's ownership * of the specified email. The {@link ActionCodeSettings} object provided * as an argument to this method defines whether the link is to be handled by a * mobile app or browser along with additional state information to be passed in * the deep link, etc. * * @example * ```javascript * var actionCodeSettings = { * url: 'https://www.example.com/cart?email=user@example.com&cartId=123', * iOS: { * bundleId: 'com.example.ios' * }, * android: { * packageName: 'com.example.android', * installApp: true, * minimumVersion: '12' * }, * handleCodeInApp: true, * dynamicLinkDomain: 'custom.page.link' * }; * admin.auth() * .generateEmailVerificationLink('user@example.com', actionCodeSettings) * .then(function(link) { * // The link was successfully generated. * }) * .catch(function(error) { * // Some error occurred, you can inspect the code: error.code * }); * ``` * * @param email - The email account to verify. * @param actionCodeSettings - The action * code settings. If specified, the state/continue URL is set as the * "continueUrl" parameter in the email verification link. The default email * verification landing page will use this to display a link to go back to * the app if it is installed. * If the actionCodeSettings is not specified, no URL is appended to the * action URL. * The state URL provided must belong to a domain that is whitelisted by the * developer in the console. Otherwise an error is thrown. * Mobile app redirects are only applicable if the developer configures * and accepts the Firebase Dynamic Links terms of service. * The Android package name and iOS bundle ID are respected only if they * are configured in the same Firebase Auth project. * @returns A promise that resolves with the generated link. */ public generateEmailVerificationLink(email: string, actionCodeSettings?: ActionCodeSettings): Promise<string> { return this.authRequestHandler.getEmailActionLink('VERIFY_EMAIL', email, actionCodeSettings); } /** * Generates the out of band email action link to verify the user's ownership * of the specified email. The {@link ActionCodeSettings} object provided * as an argument to this method defines whether the link is to be handled by a * mobile app or browser along with additional state information to be passed in * the deep link, etc. * * @example * ```javascript * var actionCodeSettings = { * url: 'https://www.example.com/cart?email=user@example.com&cartId=123', * iOS: { * bundleId: 'com.example.ios' * }, * android: { * packageName: 'com.example.android', * installApp: true, * minimumVersion: '12' * }, * handleCodeInApp: true, * dynamicLinkDomain: 'custom.page.link' * }; * admin.auth() * .generateEmailVerificationLink('user@example.com', actionCodeSettings) * .then(function(link) { * // The link was successfully generated. * }) * .catch(function(error) { * // Some error occurred, you can inspect the code: error.code * }); * ``` * * @param email - The email account to verify. * @param actionCodeSettings - The action * code settings. If specified, the state/continue URL is set as the * "continueUrl" parameter in the email verification link. The default email * verification landing page will use this to display a link to go back to * the app if it is installed. * If the actionCodeSettings is not specified, no URL is appended to the * action URL. * The state URL provided must belong to a domain that is whitelisted by the * developer in the console. Otherwise an error is thrown. * Mobile app redirects are only applicable if the developer configures * and accepts the Firebase Dynamic Links terms of service. * The Android package name and iOS bundle ID are respected only if they * are configured in the same Firebase Auth project. * @returns A promise that resolves with the generated link. */ public generateSignInWithEmailLink(email: string, actionCodeSettings: ActionCodeSettings): Promise<string> { return this.authRequestHandler.getEmailActionLink('EMAIL_SIGNIN', email, actionCodeSettings); } /** * Returns the list of existing provider configurations matching the filter * provided. At most, 100 provider configs can be listed at a time. * * SAML and OIDC provider support requires Google Cloud's Identity Platform * (GCIP). To learn more about GCIP, including pricing and features, * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. * * @param options - The provider config filter to apply. * @returns A promise that resolves with the list of provider configs meeting the * filter requirements. */ public listProviderConfigs(options: AuthProviderConfigFilter): Promise<ListProviderConfigResults> { const processResponse = (response: any, providerConfigs: AuthProviderConfig[]): ListProviderConfigResults => { // Return list of provider configuration and the next page token if available. const result: ListProviderConfigResults = { providerConfigs, }; // Delete result.pageToken if undefined. if (Object.prototype.hasOwnProperty.call(response, 'nextPageToken')) { result.pageToken = response.nextPageToken; } return result; }; if (options && options.type === 'oidc') { return this.authRequestHandler.listOAuthIdpConfigs(options.maxResults, options.pageToken) .then((response: any) => { // List of provider configurations to return. const providerConfigs: OIDCConfig[] = []; // Convert each provider config response to a OIDCConfig. response.oauthIdpConfigs.forEach((configResponse: any) => { providerConfigs.push(new OIDCConfig(configResponse)); }); // Return list of provider configuration and the next page token if available. return processResponse(response, providerConfigs); }); } else if (options && options.type === 'saml') { return this.authRequestHandler.listInboundSamlConfigs(options.maxResults, options.pageToken) .then((response: any) => { // List of provider configurations to return. const providerConfigs: SAMLConfig[] = []; // Convert each provider config response to a SAMLConfig. response.inboundSamlConfigs.forEach((configResponse: any) => { providerConfigs.push(new SAMLConfig(configResponse)); }); // Return list of provider configuration and the next page token if available. return processResponse(response, providerConfigs); }); } return Promise.reject( new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, '"AuthProviderConfigFilter.type" must be either "saml" or "oidc"')); } /** * Looks up an Auth provider configuration by the provided ID. * Returns a promise that resolves with the provider configuration * corresponding to the provider ID specified. If the specified ID does not * exist, an `auth/configuration-not-found` error is thrown. * * SAML and OIDC provider support requires Google Cloud's Identity Platform * (GCIP). To learn more about GCIP, including pricing and features, * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. * * @param providerId - The provider ID corresponding to the provider * config to return. * @returns A promise that resolves * with the configuration corresponding to the provided ID. */ public getProviderConfig(providerId: string): Promise<AuthProviderConfig> { if (OIDCConfig.isProviderId(providerId)) { return this.authRequestHandler.getOAuthIdpConfig(providerId) .then((response: OIDCConfigServerResponse) => { return new OIDCConfig(response); }); } else if (SAMLConfig.isProviderId(providerId)) { return this.authRequestHandler.getInboundSamlConfig(providerId) .then((response: SAMLConfigServerResponse) => { return new SAMLConfig(response); }); } return Promise.reject(new FirebaseAuthError(AuthClientErrorCode.INVALID_PROVIDER_ID)); } /** * Deletes the provider configuration corresponding to the provider ID passed. * If the specified ID does not exist, an `auth/configuration-not-found` error * is thrown. * * SAML and OIDC provider support requires Google Cloud's Identity Platform * (GCIP). To learn more about GCIP, including pricing and features, * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. * * @param providerId - The provider ID corresponding to the provider * config to delete. * @returns A promise that resolves on completion. */ public deleteProviderConfig(providerId: string): Promise<void> { if (OIDCConfig.isProviderId(providerId)) { return this.authRequestHandler.deleteOAuthIdpConfig(providerId); } else if (SAMLConfig.isProviderId(providerId)) { return this.authRequestHandler.deleteInboundSamlConfig(providerId); } return Promise.reject(new FirebaseAuthError(AuthClientErrorCode.INVALID_PROVIDER_ID)); } /** * Returns a promise that resolves with the updated `AuthProviderConfig` * corresponding to the provider ID specified. * If the specified ID does not exist, an `auth/configuration-not-found` error * is thrown. * * SAML and OIDC provider support requires Google Cloud's Identity Platform * (GCIP). To learn more about GCIP, including pricing and features, * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. * * @param providerId - The provider ID corresponding to the provider * config to update. * @param updatedConfig - The updated configuration. * @returns A promise that resolves with the updated provider configuration. */ public updateProviderConfig( providerId: string, updatedConfig: UpdateAuthProviderRequest): Promise<AuthProviderConfig> { if (!validator.isNonNullObject(updatedConfig)) { return Promise.reject(new FirebaseAuthError( AuthClientErrorCode.INVALID_CONFIG, 'Request is missing "UpdateAuthProviderRequest" configuration.', )); } if (OIDCConfig.isProviderId(providerId)) { return this.authRequestHandler.updateOAuthIdpConfig(providerId, updatedConfig) .then((response) => { return new OIDCConfig(response); }); } else if (SAMLConfig.isProviderId(providerId)) { return this.authRequestHandler.updateInboundSamlConfig(providerId, updatedConfig) .then((response) => { return new SAMLConfig(response); }); } return Promise.reject(new FirebaseAuthError(AuthClientErrorCode.INVALID_PROVIDER_ID)); } /** * Returns a promise that resolves with the newly created `AuthProviderConfig` * when the new provider configuration is created. * * SAML and OIDC provider support requires Google Cloud's Identity Platform * (GCIP). To learn more about GCIP, including pricing and features, * see the {@link https://cloud.google.com/identity-platform | GCIP documentation}. * * @param config - The provider configuration to create. * @returns A promise that resolves with the created provider configuration. */ public createProviderConfig(config: AuthProviderConfig): Promise<AuthProviderConfig> { if (!validator.isNonNullObject(config)) { return Promise.reject(new FirebaseAuthError( AuthClientErrorCode.INVALID_CONFIG, 'Request is missing "AuthProviderConfig" configuration.', )); } if (OIDCConfig.isProviderId(config.providerId)) { return this.authRequestHandler.createOAuthIdpConfig(config as OIDCAuthProviderConfig) .then((response) => { return new OIDCConfig(response); }); } else if (SAMLConfig.isProviderId(config.providerId)) { return this.authRequestHandler.createInboundSamlConfig(config as SAMLAuthProviderConfig) .then((response) => { return new SAMLConfig(response); }); } return Promise.reject(new FirebaseAuthError(AuthClientErrorCode.INVALID_PROVIDER_ID)); } /** * Verifies the decoded Firebase issued JWT is not revoked or disabled. Returns a promise that * resolves with the decoded claims on success. Rejects the promise with revocation error if revoked * or user disabled. * * @param decodedIdToken - The JWT's decoded claims. * @param revocationErrorInfo - The revocation error info to throw on revocation * detection. * @returns A promise that will be fulfilled after a successful verification. */ private verifyDecodedJWTNotRevokedOrDisabled( decodedIdToken: DecodedIdToken, revocationErrorInfo: ErrorInfo): Promise<DecodedIdToken> { // Get tokens valid after time for the corresponding user. return this.getUser(decodedIdToken.sub) .then((user: UserRecord) => { if (user.disabled) { throw new FirebaseAuthError( AuthClientErrorCode.USER_DISABLED, 'The user record is disabled.'); } // If no tokens valid after time available, token is not revoked. if (user.tokensValidAfterTime) { // Get the ID token authentication time and convert to milliseconds UTC. const authTimeUtc = decodedIdToken.auth_time * 1000; // Get user tokens valid after time in milliseconds UTC. const validSinceUtc = new Date(user.tokensValidAfterTime).getTime(); // Check if authentication time is older than valid since time. if (authTimeUtc < validSinceUtc) { throw new FirebaseAuthError(revocationErrorInfo); } } // All checks above passed. Return the decoded token. return decodedIdToken; }); } }
the_stack
import { ABSENT, arrayWith, countResources, countResourcesLike, deepObjectLike, expect as expectCDK, haveResource, haveResourceLike, not, objectLike, ResourcePart, SynthUtils, } from '@aws-cdk/assert'; import { CfnLaunchConfiguration, } from '@aws-cdk/aws-autoscaling'; import { Certificate, } from '@aws-cdk/aws-certificatemanager'; import { AmazonLinuxGeneration, AmazonLinuxImage, Instance, InstanceClass, InstanceSize, InstanceType, MachineImage, Port, SecurityGroup, Subnet, SubnetSelection, SubnetType, Vpc, WindowsVersion, } from '@aws-cdk/aws-ec2'; import { ContainerImage, Ec2TaskDefinition, TaskDefinition, } from '@aws-cdk/aws-ecs'; import { ApplicationProtocol, } from '@aws-cdk/aws-elasticloadbalancingv2'; import { AccountRootPrincipal, Role, } from '@aws-cdk/aws-iam'; import { PrivateHostedZone, } from '@aws-cdk/aws-route53'; import { Bucket, } from '@aws-cdk/aws-s3'; import { CfnSecret, Secret, } from '@aws-cdk/aws-secretsmanager'; import { App, CfnElement, CustomResource, Stack, } from '@aws-cdk/core'; import { ImportedAcmCertificate, X509CertificatePem, } from '../..'; import { testConstructTags, } from '../../core/test/tag-helpers'; import { IVersion, RenderQueue, RenderQueueImages, RenderQueueProps, RenderQueueSecurityGroups, Repository, SecretsManagementRegistrationStatus, SecretsManagementRole, Version, VersionQuery, } from '../lib'; import { SecretsManagementIdentityRegistration } from '../lib/secrets-management'; import { RQ_CONNECTION_ASSET, } from './asset-constants'; describe('RenderQueue', () => { let app: App; let dependencyStack: Stack; let stack: Stack; let vpc: Vpc; let rcsImage: ContainerImage; let images: RenderQueueImages; let repository: Repository; let version: IVersion; let renderQueueVersion: IVersion; let renderQueueCommon: RenderQueue; // GIVEN beforeEach(() => { app = new App(); dependencyStack = new Stack(app, 'DepStack'); vpc = new Vpc(dependencyStack, 'Vpc'); version = new VersionQuery(dependencyStack, 'Version'); repository = new Repository(dependencyStack, 'Repo', { version, vpc, }); stack = new Stack(app, 'Stack'); rcsImage = ContainerImage.fromAsset(__dirname); images = { remoteConnectionServer: rcsImage, }; renderQueueVersion = new VersionQuery(stack, 'Version'); renderQueueCommon = new RenderQueue(stack, 'RenderQueueCommon', { images, repository, version: renderQueueVersion, vpc, }); }); afterEach(() => { jest.resetAllMocks(); }); test('creates cluster', () => { // THEN expectCDK(stack).to(haveResource('AWS::ECS::Cluster')); }); test('creates service', () => { // THEN expectCDK(stack).to(haveResource('AWS::ECS::Service')); }); test('creates task definition', () => { // THEN expectCDK(stack).to(haveResource('AWS::ECS::TaskDefinition')); }); test('closed ingress by default', () => { // THEN expectCDK(stack).notTo(haveResource('AWS::EC2::SecurityGroup', { // The openListener=true option would create an ingress rule in the listener's SG. // make sure that we don't have that. SecurityGroupIngress: arrayWith(objectLike({})), })); }); test('creates load balancer with default values', () => { // THEN expectCDK(stack).to(countResourcesLike('AWS::ElasticLoadBalancingV2::LoadBalancer', 1, { LoadBalancerAttributes: [ { Key: 'deletion_protection.enabled', Value: 'true', }, ], Scheme: 'internal', })); }); test('creates a log group with default prefix of "/renderfarm/"', () => { // THEN expectCDK(stack).to(haveResourceLike('Custom::LogRetention', { LogGroupName: '/renderfarm/RenderQueueCommon', RetentionInDays: 3, })); }); test('configure the container log driver', () => { // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ objectLike({ LogConfiguration: { LogDriver: 'awslogs', Options: { 'awslogs-group': { 'Fn::GetAtt': [ 'RenderQueueCommonLogGroupWrapperA0EF7057', 'LogGroupName', ], }, 'awslogs-stream-prefix': 'RCS', 'awslogs-region': { Ref: 'AWS::Region' }, }, }, }), ], })); }); test('child dependencies added', () => { // GIVEN const host = new Instance(stack, 'Host', { vpc, instanceType: InstanceType.of( InstanceClass.R4, InstanceSize.LARGE, ), machineImage: MachineImage.latestAmazonLinux({ generation: AmazonLinuxGeneration.AMAZON_LINUX_2 }), }); // WHEN renderQueueCommon.addChildDependency(host); // THEN expectCDK(stack).to(haveResourceLike('AWS::EC2::Instance', { DependsOn: arrayWith( 'RenderQueueCommonLBPublicListener935F5635', 'RenderQueueCommonRCSTask2A4D5EA5', 'RenderQueueCommonAlbEc2ServicePatternService42BEFF4C', 'RenderQueueCommonWaitForStableServiceDB53E266', ), }, ResourcePart.CompleteDefinition)); }); describe('renderQueueSize.min', () => { describe('defaults to 1', () => { function assertSpecifiesMinSize(stackToAssert: Stack) { expectCDK(stackToAssert).to(haveResourceLike('AWS::AutoScaling::AutoScalingGroup', { MinSize: '1', })); } test('renderQueueSize unspecified', () => { // THEN assertSpecifiesMinSize(stack); }); test('renderQueueSize.min unspecified', () => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); // WHEN new RenderQueue(isolatedStack, 'RenderQueue', { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, renderQueueSize: {}, }); // THEN assertSpecifiesMinSize(isolatedStack); }); }); // Asserts that at least one RCS container and ASG instance must be created. test('throws error when minimum size is 0', () => { // GIVEN const props: RenderQueueProps = { images, repository, version: renderQueueVersion, vpc, renderQueueSize: { min: 0, }, }; // WHEN expect(() => { new RenderQueue(stack, 'RenderQueue', props); }) // THEN .toThrow('renderQueueSize.min capacity must be at least 1: got 0'); }); // Deadline before 10.1.10 requires that successive API requests are serviced by a single RCS. test('validates Deadline pre 10.1.10 has min value of at most 1', () => { // GIVEN const min = 2; const newStack = new Stack(app, 'NewStack'); const versionOld = new VersionQuery(newStack, 'VersionOld', {version: '10.1.9'}); const props: RenderQueueProps = { images, repository, version: versionOld, vpc, renderQueueSize: { min, }, }; // WHEN expect(() => { new RenderQueue(newStack, 'RenderQueue', props); }) // THEN .toThrow(`renderQueueSize.min for Deadline version less than 10.1.10.0 cannot be greater than 1 - got ${min}`); }); // Asserts that when the renderQueueSize.min prop is specified, the underlying ASG's min property is set accordingly. test.each([ [1], [2], [10], ])('configures minimum number of ASG instances to %d', (min: number) => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, renderQueueSize: { min, }, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); // THEN expectCDK(isolatedStack).to(haveResourceLike('AWS::AutoScaling::AutoScalingGroup', { MinSize: min.toString(), })); }); }); describe('renderQueueSize.max', () => { describe('defaults to 1', () => { function assertSpecifiesMaxSize(stackToAssert: Stack) { expectCDK(stackToAssert).to(haveResourceLike('AWS::AutoScaling::AutoScalingGroup', { MaxSize: '1', })); } test('renderQueueSize unspecified', () => { // THEN assertSpecifiesMaxSize(stack); }); test('renderQueueSize.max unspecified', () => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); // WHEN new RenderQueue(isolatedStack, 'RenderQueue', { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, renderQueueSize: {}, }); // THEN assertSpecifiesMaxSize(isolatedStack); }); }); // Deadline before 10.1.10 requires that successive API requests are serviced by a single RCS. test('validates Deadline pre 10.1.10 has max value of at most 1', () => { // GIVEN const max = 2; const newStack = new Stack(app, 'NewStack'); const versionOld = new VersionQuery(newStack, 'VersionOld', {version: '10.1.9'}); const props: RenderQueueProps = { images, repository, version: versionOld, vpc, renderQueueSize: { max, }, }; // WHEN expect(() => { new RenderQueue(newStack, 'RenderQueue', props); }) // THEN .toThrow(`renderQueueSize.max for Deadline version less than 10.1.10.0 cannot be greater than 1 - got ${max}`); }); // Asserts that when the renderQueueSize.max prop is specified, the underlying ASG's max property is set accordingly. test.each([ [1], [2], [10], ])('configures maximum number of ASG instances to %d', (max: number) => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, renderQueueSize: { max, }, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); // THEN expectCDK(isolatedStack).to(haveResourceLike('AWS::AutoScaling::AutoScalingGroup', { MaxSize: max.toString(), })); }); }); describe('renderQueueSize.desired', () => { describe('defaults', () => { test('unset ASG desired', () => { expectCDK(stack).to(haveResourceLike('AWS::AutoScaling::AutoScalingGroup', { DesiredCapacity: ABSENT, })); expectCDK(stack).to(haveResourceLike('AWS::ECS::Service', { DesiredCount: 1, })); }); }); test('validates Deadline pre 10.1.10 has desired value of at most 1', () => { // GIVEN const desired = 2; const newStack = new Stack(app, 'NewStack'); const versionOld = new VersionQuery(newStack, 'VersionOld', {version: '10.1.9'}); const props: RenderQueueProps = { images, repository, version: versionOld, vpc, renderQueueSize: { desired, }, }; // WHEN expect(() => { new RenderQueue(newStack, 'RenderQueue', props); }) // THEN .toThrow(`renderQueueSize.desired for Deadline version less than 10.1.10.0 cannot be greater than 1 - got ${desired}`); }); test.each([ [1], [2], [10], ])('is specified to %d', (desired: number) => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, renderQueueSize: { desired, }, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); // THEN expectCDK(isolatedStack).to(haveResourceLike('AWS::AutoScaling::AutoScalingGroup', { DesiredCapacity: desired.toString(), })); // THEN expectCDK(isolatedStack).to(haveResourceLike('AWS::ECS::Service', { DesiredCount: desired, })); }); }); describe('trafficEncryption', () => { describe('defaults', () => { let isolatedStack: Stack; beforeEach(() => { // GIVEN isolatedStack = new Stack(app, 'IsolatedStack'); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, trafficEncryption: {}, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); }); // THEN test('to HTTPS internally between ALB and RCS', () => { expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::TargetGroup', { Protocol: 'HTTPS', Port: 4433, })); }); test('to HTTPS externally between clients and ALB', () => { expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::Listener', { Protocol: 'HTTPS', Port: 4433, })); }); }); describe('when interalProtocol is HTTPS', () => { let isolatedStack: Stack; let renderQueue: RenderQueue; let caCertPemLogicalId: string; let caCertPkcsLogicalId: string; let caCertPkcsPassphraseLogicalId: string; beforeEach(() => { // GIVEN isolatedStack = new Stack(app, 'IsolatedStack'); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, trafficEncryption: { internalProtocol: ApplicationProtocol.HTTPS, }, }; // WHEN renderQueue = new RenderQueue(isolatedStack, 'RenderQueue', props); caCertPemLogicalId = isolatedStack.getLogicalId( renderQueue.node.findChild('TlsCaCertPem').node.defaultChild as CfnElement, ); const caCertPkcs = renderQueue.node.findChild('TlsRcsCertBundle'); const caCertPkcsPassphrase = caCertPkcs.node.findChild('Passphrase'); caCertPkcsLogicalId = isolatedStack.getLogicalId(caCertPkcs.node.defaultChild as CfnElement); caCertPkcsPassphraseLogicalId = isolatedStack.getLogicalId(caCertPkcsPassphrase.node.defaultChild as CfnElement); }); // THEN test('ALB connects with HTTPS to port 4433', () => { expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::TargetGroup', { Protocol: 'HTTPS', Port: 4433, })); }); test('creates RCS cert', () => { expectCDK(isolatedStack).to(haveResourceLike('Custom::RFDK_X509Generator', { ServiceToken: { 'Fn::GetAtt': arrayWith('Arn'), }, DistinguishedName: { CN: 'renderfarm.local' }, Secret: { NamePrefix: 'IsolatedStack/RenderQueue/TlsCaCertPem', }, })); }); test('grants read access to secrets containing the certs and passphrase', () => { const taskDef = renderQueue.node.findChild('RCSTask') as TaskDefinition; const taskRoleLogicalId = isolatedStack.getLogicalId((taskDef.taskRole as Role).node.defaultChild as CfnElement); expectCDK(isolatedStack).to(haveResourceLike('AWS::IAM::Policy', { PolicyDocument: { Statement: arrayWith( { Action: [ 'secretsmanager:GetSecretValue', 'secretsmanager:DescribeSecret', ], Effect: 'Allow', Resource: { 'Fn::GetAtt': [ caCertPemLogicalId, 'Cert', ], }, }, { Action: [ 'secretsmanager:GetSecretValue', 'secretsmanager:DescribeSecret', ], Effect: 'Allow', Resource: { 'Fn::GetAtt': [ caCertPkcsLogicalId, 'Cert', ], }, }, { Action: [ 'secretsmanager:GetSecretValue', 'secretsmanager:DescribeSecret', ], Effect: 'Allow', Resource: { Ref: caCertPkcsPassphraseLogicalId }, }, ), Version: '2012-10-17', }, Roles: arrayWith({ Ref: taskRoleLogicalId }), })); }); test('configures environment variables for cert secret URIs', () => { expectCDK(isolatedStack).to(haveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: arrayWith(deepObjectLike({ Environment: arrayWith( { Name: 'RCS_TLS_CA_CERT_URI', Value: { 'Fn::GetAtt': [ caCertPemLogicalId, 'Cert', ], }, }, { Name: 'RCS_TLS_CERT_URI', Value: { 'Fn::GetAtt': [ caCertPkcsLogicalId, 'Cert', ], }, }, { Name: 'RCS_TLS_CERT_PASSPHRASE_URI', Value: { Ref: caCertPkcsPassphraseLogicalId }, }, ), })), })); }); }); describe('when internal protocol is HTTP', () => { let isolatedStack: Stack; beforeEach(() => { // GIVEN isolatedStack = new Stack(app, 'IsolatedStack'); const nonSmRepository = new Repository(dependencyStack, 'NonSMRepository', { vpc, version, secretsManagementSettings: { enabled: false }, }); const props: RenderQueueProps = { images, repository: nonSmRepository, version: new VersionQuery(isolatedStack, 'Version'), vpc, trafficEncryption: { internalProtocol: ApplicationProtocol.HTTP, externalTLS: { enabled: false }, }, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); }); // THEN test('no certs are created', () => { expectCDK(isolatedStack).notTo(haveResource('Custom::RFDK_X509Generator')); }); test('ALB connects with HTTP to port 8080', () => { expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::TargetGroup', { Protocol: 'HTTP', Port: 8080, })); }); }); describe('externalProtocol is HTTPS', () => { let isolatedStack: Stack; const CERT_ARN = 'certarn'; const CA_ARN = 'arn:aws:secretsmanager:123456789012:secret:ca/arn'; const ZONE_NAME = 'renderfarm.local'; beforeEach(() => { // GIVEN isolatedStack = new Stack(app, 'IsolatedStack'); const zone = new PrivateHostedZone(isolatedStack, 'RenderQueueZone', { vpc, zoneName: ZONE_NAME, }); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, trafficEncryption: { externalTLS: { acmCertificate: Certificate.fromCertificateArn(stack, 'Certificate', CERT_ARN), acmCertificateChain: Secret.fromSecretPartialArn(stack, 'CA_Cert', CA_ARN), }, }, hostname: { hostname: 'renderqueue', zone, }, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); }); test('sets the listener port to 4433', () => { // THEN expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::Listener', { Port: 4433, })); }); test('sets the listener protocol to HTTPS', () => { // THEN expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::Listener', { Protocol: 'HTTPS', })); }); test('configures the ALB listener to use the specified ACM certificate', () => { expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::Listener', { Protocol: 'HTTPS', Certificates: arrayWith({ CertificateArn: CERT_ARN, }), })); }); test('raises an error when a cert is specified without a hosted zone', () => { // GIVEN const props: RenderQueueProps = { images, repository, version: renderQueueVersion, vpc, trafficEncryption: { externalTLS: { acmCertificate: Certificate.fromCertificateArn(stack, 'Cert', 'certArn'), acmCertificateChain: Secret.fromSecretArn(stack, 'CA_Cert2', CA_ARN), }, }, }; // WHEN expect(() => { new RenderQueue(stack, 'RenderQueue', props); }) // THEN .toThrow(/The hostname for the render queue must be defined if supplying your own certificates./); }); test('raises an error when a cert is specified without a hostname', () => { // GIVEN const zone = new PrivateHostedZone(isolatedStack, 'RenderQueueZoneNoName', { vpc, zoneName: ZONE_NAME, }); const props: RenderQueueProps = { images, repository, version: renderQueueVersion, vpc, trafficEncryption: { externalTLS: { acmCertificate: Certificate.fromCertificateArn(stack, 'Cert', 'certArn'), acmCertificateChain: Secret.fromSecretArn(stack, 'CA_Cert2', CA_ARN), }, }, hostname: { zone }, }; // WHEN expect(() => { new RenderQueue(stack, 'RenderQueue', props); }) // THEN .toThrow(/A hostname must be supplied if a certificate is supplied, with the common name of the certificate matching the hostname \+ domain name/); }); }); describe('externalProtocol is HTTPS importing cert', () => { describe('passing cases', () => { let isolatedStack: Stack; let zone: PrivateHostedZone; const ZONE_NAME = 'renderfarm.local'; const HOSTNAME = 'server'; beforeEach(() => { // GIVEN isolatedStack = new Stack(app, 'IsolatedStack'); zone = new PrivateHostedZone(isolatedStack, 'RenderQueueZone', { vpc, zoneName: ZONE_NAME, }); const caCert = new X509CertificatePem(isolatedStack, 'CaCert', { subject: { cn: `ca.${ZONE_NAME}`, }, }); const serverCert = new X509CertificatePem(isolatedStack, 'ServerCert', { subject: { cn: `${HOSTNAME}.${ZONE_NAME}`, }, signingCertificate: caCert, }); const nonSmRepository = new Repository(dependencyStack, 'NonSMRepository', { vpc, version, secretsManagementSettings: { enabled: false }, }); const props: RenderQueueProps = { images, repository: nonSmRepository, version: new VersionQuery(isolatedStack, 'Version'), vpc, trafficEncryption: { externalTLS: { rfdkCertificate: serverCert, }, internalProtocol: ApplicationProtocol.HTTP, }, hostname: { zone, hostname: HOSTNAME, }, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); }); test('sets the listener port to 4433', () => { // THEN expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::Listener', { Port: 4433, })); }); test('sets the listener protocol to HTTPS', () => { // THEN expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::Listener', { Protocol: 'HTTPS', })); }); test('Imports Cert to ACM', () => { // THEN expectCDK(isolatedStack).to(haveResourceLike('Custom::RFDK_AcmImportedCertificate', { X509CertificatePem: { Cert: { 'Fn::GetAtt': [ 'ServerCert', 'Cert', ], }, Key: { 'Fn::GetAtt': [ 'ServerCert', 'Key', ], }, Passphrase: { Ref: 'ServerCertPassphraseE4C3CB38', }, CertChain: { 'Fn::GetAtt': [ 'ServerCert', 'CertChain', ], }, }, })); }); }); describe('failure cases,', () => { test('Throws when missing cert chain', () => { const ZONE_NAME = 'renderfarm.local'; const HOSTNAME = 'server'; // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); const zone = new PrivateHostedZone(isolatedStack, 'RenderQueueZone', { vpc, zoneName: ZONE_NAME, }); const rootCert = new X509CertificatePem(isolatedStack, 'RootCert', { subject: { cn: `ca.${ZONE_NAME}`, }, }); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, trafficEncryption: { externalTLS: { rfdkCertificate: rootCert, }, internalProtocol: ApplicationProtocol.HTTP, }, hostname: { zone, hostname: HOSTNAME, }, }; // WHEN expect(() => { new RenderQueue(isolatedStack, 'RenderQueue', props); }) // THEN .toThrow(/Provided rfdkCertificate does not contain a certificate chain/); }); }); }); test('Creates default RFDK cert if no cert given', () => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, trafficEncryption: { externalTLS: { }, }, }; const rq = new RenderQueue(isolatedStack, 'RenderQueue', props); const rootCa = rq.node.findChild('RootCA').node.defaultChild as X509CertificatePem; const rootCaGen = rootCa.node.defaultChild as CustomResource; const rfdkCert = rq.node.findChild('RenderQueuePemCert').node.defaultChild as X509CertificatePem; const rfdkCertGen = rfdkCert.node.defaultChild as CustomResource; const acmCert = rq.node.findChild('AcmCert').node.defaultChild as ImportedAcmCertificate; expectCDK(isolatedStack).to(haveResourceLike('Custom::RFDK_X509Generator', { Passphrase: isolatedStack.resolve(rootCa.passphrase), })); expectCDK(isolatedStack).to(haveResourceLike('Custom::RFDK_X509Generator', { Passphrase: isolatedStack.resolve(rfdkCert.passphrase), SigningCertificate: { Cert: isolatedStack.resolve(rootCaGen.getAtt('Cert')), Key: isolatedStack.resolve(rootCaGen.getAtt('Key')), Passphrase: isolatedStack.resolve(rootCa.passphrase), CertChain: '', }, })); expectCDK(isolatedStack).to(countResources('Custom::RFDK_AcmImportedCertificate', 1)); expectCDK(isolatedStack).to(haveResourceLike('Custom::RFDK_AcmImportedCertificate', { X509CertificatePem: { Cert: isolatedStack.resolve(rfdkCertGen.getAtt('Cert')), Key: isolatedStack.resolve(rfdkCertGen.getAtt('Key')), Passphrase: isolatedStack.resolve(rfdkCert.passphrase), CertChain: isolatedStack.resolve(rfdkCertGen.getAtt('CertChain')), }, })); expectCDK(isolatedStack).to(countResources('AWS::ElasticLoadBalancingV2::Listener', 1)); expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::Listener', { Certificates: [ { CertificateArn: isolatedStack.resolve(acmCert.certificateArn), }, ], })); }); test('Throws if given ACM cert and RFDK Cert', () => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); const ZONE_NAME = 'renderfarm.local'; const CERT_ARN = 'certArn'; const CA_ARN = 'arn:aws:secretsmanager:123456789012:secret:ca/arn'; const zone = new PrivateHostedZone(isolatedStack, 'RenderQueueZone', { vpc, zoneName: ZONE_NAME, }); const caCert = new X509CertificatePem(isolatedStack, 'CaCert', { subject: { cn: `ca.${ZONE_NAME}`, }, }); const serverCert = new X509CertificatePem(isolatedStack, 'ServerCert', { subject: { cn: `server.${ZONE_NAME}`, }, signingCertificate: caCert, }); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, trafficEncryption: { externalTLS: { acmCertificate: Certificate.fromCertificateArn(isolatedStack, 'Certificate', CERT_ARN), acmCertificateChain: Secret.fromSecretArn(isolatedStack, 'CA_Cert', CA_ARN), rfdkCertificate: serverCert, }, }, hostname: { zone, }, }; // WHEN expect(() => { new RenderQueue(isolatedStack, 'RenderQueue', props); }) // THEN .toThrow(/Exactly one of externalTLS.acmCertificate and externalTLS.rfdkCertificate must be provided when using externalTLS/); }); test('Throws if ACM Cert is given without a cert chain', () => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); const HOSTNAME = 'renderqueue'; const ZONE_NAME = 'renderfarm.local'; const CERT_ARN = 'certArn'; const zone = new PrivateHostedZone(isolatedStack, 'RenderQueueZone', { vpc, zoneName: ZONE_NAME, }); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, trafficEncryption: { externalTLS: { acmCertificate: Certificate.fromCertificateArn(isolatedStack, 'Certificate', CERT_ARN), }, }, hostname: { hostname: HOSTNAME, zone, }, }; // WHEN expect(() => { new RenderQueue(isolatedStack, 'RenderQueue', props); }) // THEN .toThrow(/externalTLS.acmCertificateChain must be provided when using externalTLS.acmCertificate./); }); }); describe('Client Connection', () => { describe('externalProtocol is http', () => { let isolatedStack: Stack; let zone: PrivateHostedZone; const ZONE_NAME = 'renderfarm.local'; let rq: RenderQueue; beforeEach(() => { // GIVEN isolatedStack = new Stack(app, 'IsolatedStack'); zone = new PrivateHostedZone(isolatedStack, 'RenderQueueZone', { vpc, zoneName: ZONE_NAME, }); const nonSmRepository = new Repository(dependencyStack, 'NonSMRepository', { vpc, version, secretsManagementSettings: { enabled: false }, }); const props: RenderQueueProps = { images, repository: nonSmRepository, version: new VersionQuery(isolatedStack, 'Version'), vpc, hostname: { zone, }, trafficEncryption: { externalTLS: { enabled: false } }, }; // WHEN rq = new RenderQueue(isolatedStack, 'RenderQueue', props); }); test('ECS can connect', () => { // WHEN const hosts = [new Instance(isolatedStack, 'Host', { vpc, instanceType: InstanceType.of( InstanceClass.R4, InstanceSize.LARGE, ), machineImage: MachineImage.latestAmazonLinux({ generation: AmazonLinuxGeneration.AMAZON_LINUX_2 }), })]; const role = new Role(isolatedStack, 'Role', {assumedBy: new AccountRootPrincipal()}); const env = rq.configureClientECS({ hosts, grantee: role, }); // THEN expect(env).toHaveProperty('RENDER_QUEUE_URI'); expect(env.RENDER_QUEUE_URI).toMatch(/http:\/\/.*:8080$/); expectCDK(isolatedStack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', ToPort: 8080, SourceSecurityGroupId: { 'Fn::GetAtt': [ isolatedStack.getLogicalId(hosts[0].connections.securityGroups[0].node.defaultChild as CfnElement), 'GroupId', ], }, })); expectCDK(isolatedStack).to(haveResourceLike('AWS::EC2::Instance', { DependsOn: arrayWith( 'RenderQueueLBPublicListenerBBF15D5F', 'RenderQueueRCSTaskA9AE70D3', ), }, ResourcePart.CompleteDefinition)); }); test('Linux Instance can connect', () => { // WHEN const host = new Instance(isolatedStack, 'Host', { vpc, instanceType: InstanceType.of( InstanceClass.R4, InstanceSize.LARGE, ), machineImage: MachineImage.latestAmazonLinux({ generation: AmazonLinuxGeneration.AMAZON_LINUX_2 }), }); rq.configureClientInstance({ host, }); // THEN const userData = isolatedStack.resolve(host.userData.render()); expect(userData).toStrictEqual({ 'Fn::Join': [ '', [ "#!/bin/bash\nmkdir -p $(dirname '/tmp/", { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '\')\naws s3 cp \'s3://', { Ref: RQ_CONNECTION_ASSET.Bucket }, '/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '\' \'/tmp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '\'\n' + 'if [ -f \"/etc/profile.d/deadlineclient.sh\" ]; then\n' + ' source \"/etc/profile.d/deadlineclient.sh\"\n' + 'fi\n' + '"${DEADLINE_PATH}/deadlinecommand" -executeScriptNoGui "/tmp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, `" --render-queue "http://renderqueue.${ZONE_NAME}:8080" \n` + 'rm -f "/tmp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '"\n' + 'if service --status-all | grep -q "Deadline 10 Launcher"; then\n' + ' service deadline10launcher restart\n' + 'fi', ], ], }); // Make sure we execute the script with the correct args expectCDK(isolatedStack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', ToPort: 8080, SourceSecurityGroupId: { 'Fn::GetAtt': [ isolatedStack.getLogicalId(host.connections.securityGroups[0].node.defaultChild as CfnElement), 'GroupId', ], }, })); expectCDK(isolatedStack).to(haveResourceLike('AWS::EC2::Instance', { DependsOn: arrayWith( 'RenderQueueLBPublicListenerBBF15D5F', 'RenderQueueRCSTaskA9AE70D3', ), }, ResourcePart.CompleteDefinition)); }); test('Windows Instance can connect', () => { // WHEN const host = new Instance(isolatedStack, 'Host', { vpc, instanceType: InstanceType.of( InstanceClass.R4, InstanceSize.LARGE, ), machineImage: MachineImage.latestWindows( WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_CORE_BASE), }); rq.configureClientInstance({ host, }); // THEN const userData = isolatedStack.resolve(host.userData.render()); expect(userData).toStrictEqual({ 'Fn::Join': [ '', [ '<powershell>mkdir (Split-Path -Path \'C:/temp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '\' ) -ea 0\n' + 'Read-S3Object -BucketName \'', { Ref: RQ_CONNECTION_ASSET.Bucket }, '\' -key \'', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '\' -file \'C:/temp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '\' -ErrorAction Stop\n' + '$ErrorActionPreference = "Stop"\n' + '$DEADLINE_PATH = (get-item env:"DEADLINE_PATH").Value\n' + '& "$DEADLINE_PATH/deadlinecommand.exe" -executeScriptNoGui "C:/temp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, `" --render-queue "http://renderqueue.${ZONE_NAME}:8080" 2>&1\n` + 'Remove-Item -Path "C:/temp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '"\n' + 'If (Get-Service "deadline10launcherservice" -ErrorAction SilentlyContinue) {\n' + ' Restart-Service "deadline10launcherservice"\n' + '} Else {\n' + ' & "$DEADLINE_PATH/deadlinelauncher.exe" -shutdownall 2>&1\n' + ' & "$DEADLINE_PATH/deadlinelauncher.exe" -nogui 2>&1\n' + '}</powershell>', ], ], }); // Make sure we execute the script with the correct args expectCDK(isolatedStack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', ToPort: 8080, SourceSecurityGroupId: { 'Fn::GetAtt': [ isolatedStack.getLogicalId(host.connections.securityGroups[0].node.defaultChild as CfnElement), 'GroupId', ], }, })); expectCDK(isolatedStack).to(haveResourceLike('AWS::EC2::Instance', { DependsOn: arrayWith( 'RenderQueueLBPublicListenerBBF15D5F', 'RenderQueueRCSTaskA9AE70D3', ), }, ResourcePart.CompleteDefinition)); }); }); describe('externalProtocol is https', () => { let isolatedStack: Stack; let zone: PrivateHostedZone; let rq: RenderQueue; const HOSTNAME = 'renderqueue'; const ZONE_NAME = 'renderfarm.local'; const CERT_ARN = 'arn:a:b:c:dcertarn'; const CA_ARN = 'arn:aws:secretsmanager:123456789012:secret:ca/arn'; beforeEach(() => { // GIVEN isolatedStack = new Stack(app, 'IsolatedStack'); zone = new PrivateHostedZone(isolatedStack, 'RenderQueueZone', { vpc, zoneName: ZONE_NAME, }); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, hostname: { hostname: HOSTNAME, zone, }, trafficEncryption: { externalTLS: { acmCertificate: Certificate.fromCertificateArn(stack, 'Certificate', CERT_ARN), acmCertificateChain: Secret.fromSecretArn(stack, 'CA_Cert', CA_ARN), }, }, }; // WHEN rq = new RenderQueue(isolatedStack, 'RenderQueue', props); }); test('ECS can connect', () => { // WHEN const hosts = [new Instance(isolatedStack, 'Host', { vpc, instanceType: InstanceType.of( InstanceClass.R4, InstanceSize.LARGE, ), machineImage: MachineImage.latestAmazonLinux({ generation: AmazonLinuxGeneration.AMAZON_LINUX_2 }), })]; const role = new Role(isolatedStack, 'Role', {assumedBy: new AccountRootPrincipal()}); const env = rq.configureClientECS({ hosts, grantee: role, }); // THEN expect(env).toHaveProperty('RENDER_QUEUE_URI'); expect(env.RENDER_QUEUE_URI).toMatch(/https:\/\/.*:4433$/); expect(env).toHaveProperty('RENDER_QUEUE_TLS_CA_CERT_URI', CA_ARN); expectCDK(isolatedStack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', ToPort: 4433, SourceSecurityGroupId: { 'Fn::GetAtt': [ isolatedStack.getLogicalId(hosts[0].connections.securityGroups[0].node.defaultChild as CfnElement), 'GroupId', ], }, })); }); test('Linux Instance can connect', () => { // WHEN const host = new Instance(isolatedStack, 'Host', { vpc, instanceType: InstanceType.of( InstanceClass.R4, InstanceSize.LARGE, ), machineImage: MachineImage.latestAmazonLinux({ generation: AmazonLinuxGeneration.AMAZON_LINUX_2 }), }); rq.configureClientInstance({ host, }); // THEN const userData = isolatedStack.resolve(host.userData.render()); expect(userData).toStrictEqual({ 'Fn::Join': [ '', [ "#!/bin/bash\nmkdir -p $(dirname '/tmp/", { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '\')\naws s3 cp \'s3://', { Ref: RQ_CONNECTION_ASSET.Bucket }, '/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '\' \'/tmp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '\'\n' + 'if [ -f \"/etc/profile.d/deadlineclient.sh\" ]; then\n' + ' source \"/etc/profile.d/deadlineclient.sh\"\n' + 'fi\n' + '"${DEADLINE_PATH}/deadlinecommand" -executeScriptNoGui "/tmp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, `" --render-queue "https://renderqueue.${ZONE_NAME}:4433" --tls-ca "${CA_ARN}"\n` + 'rm -f "/tmp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '"\n' + 'if service --status-all | grep -q "Deadline 10 Launcher"; then\n' + ' service deadline10launcher restart\n' + 'fi', ], ], }); // Make sure we execute the script with the correct args expectCDK(isolatedStack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', ToPort: 4433, SourceSecurityGroupId: { 'Fn::GetAtt': [ isolatedStack.getLogicalId(host.connections.securityGroups[0].node.defaultChild as CfnElement), 'GroupId', ], }, })); }); test('Windows Instance can connect', () => { // WHEN const host = new Instance(isolatedStack, 'Host', { vpc, instanceType: InstanceType.of( InstanceClass.R4, InstanceSize.LARGE, ), machineImage: MachineImage.latestWindows( WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_CORE_BASE), }); rq.configureClientInstance({ host, }); // THEN const userData = isolatedStack.resolve(host.userData.render()); expect(userData).toStrictEqual({ 'Fn::Join': [ '', [ '<powershell>mkdir (Split-Path -Path \'C:/temp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '\' ) -ea 0\n' + 'Read-S3Object -BucketName \'', { Ref: RQ_CONNECTION_ASSET.Bucket }, '\' -key \'', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '\' -file \'C:/temp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '\' -ErrorAction Stop\n' + '$ErrorActionPreference = "Stop"\n' + '$DEADLINE_PATH = (get-item env:"DEADLINE_PATH").Value\n' + '& "$DEADLINE_PATH/deadlinecommand.exe" -executeScriptNoGui "C:/temp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, `" --render-queue "https://renderqueue.${ZONE_NAME}:4433" --tls-ca \"${CA_ARN}\" 2>&1\n` + 'Remove-Item -Path "C:/temp/', { 'Fn::Select': [ 0, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, { 'Fn::Select': [ 1, { 'Fn::Split': [ '||', { Ref: RQ_CONNECTION_ASSET.Key }, ], }, ], }, '"\n' + 'If (Get-Service "deadline10launcherservice" -ErrorAction SilentlyContinue) {\n' + ' Restart-Service "deadline10launcherservice"\n' + '} Else {\n' + ' & "$DEADLINE_PATH/deadlinelauncher.exe" -shutdownall 2>&1\n' + ' & "$DEADLINE_PATH/deadlinelauncher.exe" -nogui 2>&1\n' + '}</powershell>', ], ], }); // Make sure we execute the script with the correct args expectCDK(isolatedStack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', ToPort: 4433, SourceSecurityGroupId: { 'Fn::GetAtt': [ isolatedStack.getLogicalId(host.connections.securityGroups[0].node.defaultChild as CfnElement), 'GroupId', ], }, })); }); }); }); test('can specify subnets', () => { // GIVEN const subnets = [ Subnet.fromSubnetAttributes(dependencyStack, 'Subnet1', { subnetId: 'SubnetID1', availabilityZone: 'us-west-2a', }), Subnet.fromSubnetAttributes(dependencyStack, 'Subnet2', { subnetId: 'SubnetID2', availabilityZone: 'us-west-2b', }), ]; const isolatedStack = new Stack(app, 'IsolatedStack'); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, vpcSubnets: { subnets, }, vpcSubnetsAlb: { subnets, }, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); expectCDK(isolatedStack).to(haveResource('AWS::AutoScaling::AutoScalingGroup', { VPCZoneIdentifier: arrayWith( 'SubnetID1', 'SubnetID2', ), })); expectCDK(isolatedStack).to(haveResource('AWS::ElasticLoadBalancingV2::LoadBalancer', { Subnets: [ 'SubnetID1', 'SubnetID2', ], })); }); test('can specify instance type', () => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); const props: RenderQueueProps = { images, instanceType: InstanceType.of(InstanceClass.C5, InstanceSize.LARGE), repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); // THEN expectCDK(isolatedStack).to(haveResourceLike('AWS::AutoScaling::LaunchConfiguration', { InstanceType: 'c5.large', })); }); test('no deletion protection', () => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, deletionProtection: false, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); // THEN expectCDK(isolatedStack).to(not(haveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', { LoadBalancerAttributes: arrayWith( { Key: 'deletion_protection.enabled', Value: 'true', }, ), Scheme: ABSENT, Type: ABSENT, }))); }); test('drop invalid http header fields enabled', () => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); // THEN expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', { LoadBalancerAttributes: arrayWith( { Key: 'routing.http.drop_invalid_header_fields.enabled', Value: 'true', }, ), })); }); describe('hostname', () => { // GIVEN const zoneName = 'mydomain.local'; describe('not specified, with no TLS', () => { let isolatedStack: Stack; beforeEach(() => { // GIVEN isolatedStack = new Stack(app, 'IsolatedStack'); const nonSmRepository = new Repository(dependencyStack, 'NonSMRepository', { vpc, version, secretsManagementSettings: { enabled: false }, }); const props: RenderQueueProps = { images, repository: nonSmRepository, trafficEncryption: { externalTLS: { enabled: false } }, version: new VersionQuery(isolatedStack, 'Version'), vpc, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); }); // THEN test('does not create a record set', () => { expectCDK(isolatedStack).notTo(haveResource('AWS::Route53::RecordSet')); }); }); test('not specified, with TLS', () => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, trafficEncryption: { externalTLS: { }, }, }; const renderQueue = new RenderQueue(isolatedStack, 'RenderQueue', props); expectCDK(isolatedStack).to(haveResource('AWS::Route53::RecordSet', { Name: 'renderqueue.aws-rfdk.com.', Type: 'A', AliasTarget: objectLike({ HostedZoneId: isolatedStack.resolve(renderQueue.loadBalancer.loadBalancerCanonicalHostedZoneId), }), })); }); describe('specified with zone but no hostname', () => { let zone: PrivateHostedZone; let isolatedStack: Stack; let renderQueue: RenderQueue; beforeEach(() => { // GIVEN zone = new PrivateHostedZone(dependencyStack, 'Zone', { vpc, zoneName, }); isolatedStack = new Stack(app, 'IsolatedStack'); const props: RenderQueueProps = { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, hostname: { zone, }, }; // WHEN renderQueue = new RenderQueue(isolatedStack, 'RenderQueue', props); }); // THEN test('creates a record set using default hostname', () => { const loadBalancerLogicalId = dependencyStack.getLogicalId( renderQueue.loadBalancer.node.defaultChild as CfnElement, ); expectCDK(isolatedStack).to(haveResource('AWS::Route53::RecordSet', { Name: `renderqueue.${zoneName}.`, Type: 'A', AliasTarget: objectLike({ HostedZoneId: { 'Fn::GetAtt': [ loadBalancerLogicalId, 'CanonicalHostedZoneID', ], }, }), })); }); }); test.each([ [false], [true], ])('specified with TLS enabled == %s', (isTlsEnabled: boolean) => { // GIVEN const zone = new PrivateHostedZone(dependencyStack, 'Zone', { vpc, zoneName, }); const hostname = 'testrq'; const isolatedStack = new Stack(app, 'IsolatedStack'); const nonSmRepository = new Repository(dependencyStack, 'NonSMRepository', { vpc, version, secretsManagementSettings: { enabled: false }, }); const props: RenderQueueProps = { images, repository: nonSmRepository, version: new VersionQuery(isolatedStack, 'Version'), vpc, hostname: { hostname, zone, }, trafficEncryption: { externalTLS: { enabled: isTlsEnabled }, }, }; // WHEN const renderQueue = new RenderQueue(isolatedStack, 'RenderQueue', props); // THEN const loadBalancerLogicalId = dependencyStack.getLogicalId( renderQueue.loadBalancer.node.defaultChild as CfnElement, ); expectCDK(isolatedStack).to(haveResource('AWS::Route53::RecordSet', { Name: `${hostname}.${zoneName}.`, Type: 'A', AliasTarget: objectLike({ HostedZoneId: { 'Fn::GetAtt': [ loadBalancerLogicalId, 'CanonicalHostedZoneID', ], }, }), })); }); test.each([ ['rq.somedomain.local'], ['1startswithnumber'], ['-startswithhyphen'], ['endswith-'], ['contains$symbol'], ['thisstringisexactlysixtyfourcharacterswhichisonelargerthanthemax'], ])('.hostname validation - %s', (hostname: string) => { // GIVEN const zone = new PrivateHostedZone(dependencyStack, 'Zone', { zoneName: 'somedomain.local', vpc, }); const props: RenderQueueProps = { images, repository, version, vpc, hostname: { hostname, zone, }, }; // WHEN function when() { new RenderQueue(stack, 'NewRenderQueue', props); } // THEN expect(when).toThrow(/Invalid RenderQueue hostname/); }); }); describe('Access Logs', () => { let isolatedStack: Stack; let isolatedVpc: Vpc; let isolatedRepository: Repository; let isolatedVersion: IVersion; let isolatedimages: RenderQueueImages; let accessBucket: Bucket; beforeEach(() => { // GIVEN isolatedStack = new Stack(app, 'IsolatedStack', { env: { region: 'us-east-1', }, }); isolatedVpc = new Vpc(isolatedStack, 'Vpc'); isolatedVersion = new VersionQuery(isolatedStack, 'Version'); isolatedRepository = new Repository(isolatedStack, 'Repo', { version: isolatedVersion, vpc: isolatedVpc, }); isolatedimages = { remoteConnectionServer: rcsImage, }; accessBucket = new Bucket(isolatedStack, 'AccessBucket'); }); test('enabling access logs sets attributes and policies', () => { // GIVEN const props: RenderQueueProps = { images: isolatedimages, repository: isolatedRepository, version: isolatedVersion, vpc: isolatedVpc, accessLogs: { destinationBucket: accessBucket, }, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); // THEN expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', { LoadBalancerAttributes: arrayWith( { Key: 'access_logs.s3.enabled', Value: 'true', }, { Key: 'access_logs.s3.bucket', Value: { Ref: 'AccessBucketE2803D76', }, }, ), })); expectCDK(isolatedStack).to(haveResourceLike('AWS::S3::BucketPolicy', { Bucket: { Ref: 'AccessBucketE2803D76', }, PolicyDocument: { Statement: arrayWith( { Action: 's3:PutObject', Condition: { StringEquals: { 's3:x-amz-acl': 'bucket-owner-full-control', }, }, Effect: 'Allow', Principal: { Service: 'delivery.logs.amazonaws.com', }, Resource: { 'Fn::Join': [ '', [ { 'Fn::GetAtt': [ 'AccessBucketE2803D76', 'Arn', ], }, '/*', ], ], }, }, { Action: 's3:GetBucketAcl', Effect: 'Allow', Principal: { Service: 'delivery.logs.amazonaws.com', }, Resource: { 'Fn::GetAtt': [ 'AccessBucketE2803D76', 'Arn', ], }, }, { Action: [ 's3:PutObject*', 's3:Abort*', ], Effect: 'Allow', Principal: { AWS: { 'Fn::Join': [ '', [ 'arn:', { Ref: 'AWS::Partition', }, ':iam::127311923021:root', ], ], }, }, Resource: { 'Fn::Join': [ '', [ { 'Fn::GetAtt': [ 'AccessBucketE2803D76', 'Arn', ], }, '/AWSLogs/', { Ref: 'AWS::AccountId', }, '/*', ], ], }, }, ), }, })); }); test('enabling access logs works with prefix', () => { // GIVEN const props: RenderQueueProps = { images: isolatedimages, repository: isolatedRepository, version: isolatedVersion, vpc: isolatedVpc, accessLogs: { destinationBucket: accessBucket, prefix: 'PREFIX_STRING', }, }; // WHEN new RenderQueue(isolatedStack, 'RenderQueue', props); // THEN expectCDK(isolatedStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', { LoadBalancerAttributes: arrayWith( { Key: 'access_logs.s3.enabled', Value: 'true', }, { Key: 'access_logs.s3.bucket', Value: { Ref: 'AccessBucketE2803D76', }, }, { Key: 'access_logs.s3.prefix', Value: 'PREFIX_STRING', }, ), })); expectCDK(isolatedStack).to(haveResourceLike('AWS::S3::BucketPolicy', { Bucket: { Ref: 'AccessBucketE2803D76', }, PolicyDocument: { Statement: arrayWith( { Action: 's3:PutObject', Condition: { StringEquals: { 's3:x-amz-acl': 'bucket-owner-full-control', }, }, Effect: 'Allow', Principal: { Service: 'delivery.logs.amazonaws.com', }, Resource: { 'Fn::Join': [ '', [ { 'Fn::GetAtt': [ 'AccessBucketE2803D76', 'Arn', ], }, '/*', ], ], }, }, { Action: 's3:GetBucketAcl', Effect: 'Allow', Principal: { Service: 'delivery.logs.amazonaws.com', }, Resource: { 'Fn::GetAtt': [ 'AccessBucketE2803D76', 'Arn', ], }, }, { Action: [ 's3:PutObject*', 's3:Abort*', ], Effect: 'Allow', Principal: { AWS: { 'Fn::Join': [ '', [ 'arn:', { Ref: 'AWS::Partition', }, ':iam::127311923021:root', ], ], }, }, Resource: { 'Fn::Join': [ '', [ { 'Fn::GetAtt': [ 'AccessBucketE2803D76', 'Arn', ], }, '/PREFIX_STRING/AWSLogs/', { Ref: 'AWS::AccountId', }, '/*', ], ], }, }, ), }, })); }); }); describe('tagging', () => { testConstructTags({ constructName: 'RenderQueue', createConstruct: () => { return stack; }, resourceTypeCounts: { 'AWS::ECS::Cluster': 1, 'AWS::EC2::SecurityGroup': 2, 'AWS::IAM::Role': 10, 'AWS::AutoScaling::AutoScalingGroup': 1, 'AWS::Lambda::Function': 6, 'AWS::SNS::Topic': 1, 'AWS::ECS::TaskDefinition': 1, 'AWS::DynamoDB::Table': 5, 'AWS::SecretsManager::Secret': 4, 'AWS::ElasticLoadBalancingV2::LoadBalancer': 1, 'AWS::ElasticLoadBalancingV2::TargetGroup': 1, 'AWS::ECS::Service': 1, }, }); }); describe('SEP Policies', () => { test('with resource tracker', () => { // WHEN renderQueueCommon.addSEPPolicies(); // THEN expectCDK(stack).to(countResourcesLike('AWS::IAM::Role', 1, { ManagedPolicyArns: arrayWith( { 'Fn::Join': [ '', [ 'arn:', { Ref: 'AWS::Partition', }, ':iam::aws:policy/AWSThinkboxDeadlineSpotEventPluginAdminPolicy', ], ], }, { 'Fn::Join': [ '', [ 'arn:', { Ref: 'AWS::Partition', }, ':iam::aws:policy/AWSThinkboxDeadlineResourceTrackerAdminPolicy', ], ], }, ), })); }); test('no resource tracker', () => { // WHEN renderQueueCommon.addSEPPolicies(false); // THEN expectCDK(stack).to(haveResourceLike('AWS::IAM::Role', { ManagedPolicyArns: arrayWith( { 'Fn::Join': [ '', [ 'arn:', { Ref: 'AWS::Partition', }, ':iam::aws:policy/AWSThinkboxDeadlineSpotEventPluginAdminPolicy', ], ], }, ), })); expectCDK(stack).notTo(haveResourceLike('AWS::IAM::Role', { ManagedPolicyArns: arrayWith( { 'Fn::Join': [ '', [ 'arn:', { Ref: 'AWS::Partition', }, ':iam::aws:policy/AWSThinkboxDeadlineResourceTrackerAdminPolicy', ], ], }, ), })); }); }); test('creates WaitForStableService by default', () => { // THEN expectCDK(stack).to(haveResourceLike('Custom::RFDK_WaitForStableService', { cluster: stack.resolve(renderQueueCommon.cluster.clusterArn), // eslint-disable-next-line dot-notation services: [stack.resolve(renderQueueCommon['pattern'].service.serviceArn)], })); }); describe('Security Groups', () => { let backendSecurityGroup: SecurityGroup; let frontendSecurityGroup: SecurityGroup; beforeEach(() => { backendSecurityGroup = new SecurityGroup(stack, 'ASGSecurityGroup', { vpc }); frontendSecurityGroup = new SecurityGroup(stack, 'LBSecurityGroup', { vpc }); }); test('adds security groups on construction', () => { // GIVEN const securityGroups: RenderQueueSecurityGroups = { backend: backendSecurityGroup, frontend: frontendSecurityGroup, }; // WHEN new RenderQueue(stack, 'RenderQueue', { images, repository, version: renderQueueVersion, vpc, securityGroups, }); // THEN assertSecurityGroupsWereAdded(securityGroups); }); test('adds backend security groups post-construction', () => { // GIVEN const renderQueue = new RenderQueue(stack, 'RenderQueue', { images, repository, version: renderQueueVersion, vpc, }); // WHEN renderQueue.addBackendSecurityGroups(backendSecurityGroup); // THEN assertSecurityGroupsWereAdded({ backend: backendSecurityGroup, }); }); test('adds frontend security groups post-construction', () => { // GIVEN const renderQueue = new RenderQueue(stack, 'RenderQueue', { images, repository, version: renderQueueVersion, vpc, }); // WHEN renderQueue.addFrontendSecurityGroups(frontendSecurityGroup); // THEN assertSecurityGroupsWereAdded({ frontend: frontendSecurityGroup, }); }); test('security groups added post-construction are not attached to Connections object', () => { // GIVEN const renderQueue = new RenderQueue(stack, 'RenderQueue', { images, repository, version: renderQueueVersion, vpc, }); renderQueue.addBackendSecurityGroups(backendSecurityGroup); renderQueue.addFrontendSecurityGroups(frontendSecurityGroup); const peerSecurityGroup = new SecurityGroup(stack, 'PeerSecurityGroup', { vpc }); // WHEN renderQueue.connections.allowFrom(peerSecurityGroup, Port.tcp(22)); // THEN // Existing LoadBalancer security groups shouldn't have the ingress rule added expectCDK(stack).notTo(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', FromPort: 22, ToPort: 22, GroupId: stack.resolve(frontendSecurityGroup.securityGroupId), SourceSecurityGroupId: stack.resolve(peerSecurityGroup.securityGroupId), })); // Existing AutoScalingGroup security groups shouldn't have the ingress rule added expectCDK(stack).notTo(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', FromPort: 22, ToPort: 22, GroupId: stack.resolve(backendSecurityGroup.securityGroupId), SourceSecurityGroupId: stack.resolve(peerSecurityGroup.securityGroupId), })); }); function assertSecurityGroupsWereAdded(securityGroups: RenderQueueSecurityGroups) { if (securityGroups.backend !== undefined) { expectCDK(stack).to(haveResourceLike('AWS::AutoScaling::LaunchConfiguration', { SecurityGroups: arrayWith(stack.resolve(securityGroups.backend.securityGroupId)), })); } if (securityGroups.frontend !== undefined) { expectCDK(stack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', { SecurityGroups: arrayWith(stack.resolve(securityGroups.frontend.securityGroupId)), })); } } }); test('validates VersionQuery is not in a different stack', () => { // GIVEN const newStack = new Stack(app, 'NewStack'); // WHEN new RenderQueue(newStack, 'RenderQueueNew', { images, repository, version, vpc, }); // WHEN function synth() { SynthUtils.synthesize(newStack); } // THEN expect(synth).toThrow('A VersionQuery can not be supplied from a different stack'); }); test('Does not enable filesystem cache by default', () => { expectCDK(stack).notTo(haveResourceLike('AWS::AutoScaling::LaunchConfiguration', { UserData: { 'Fn::Base64': { 'Fn::Join': arrayWith(arrayWith(' >> /etc/ecs/ecs.config\nsudo iptables --insert FORWARD 1 --in-interface docker+ --destination 169.254.169.254/32 --jump DROP\nsudo service iptables save\necho ECS_AWSVPC_BLOCK_IMDS=true >> /etc/ecs/ecs.config\nyum install -yq awscli unzip\n# RenderQueue file caching enabled\nmkdir -p $(dirname \'/tmp/')), }, }, })); }); test('Enables filesystem cache if required', () => { // GIVEN const isolatedStack = new Stack(app, 'IsolatedStack'); // WHEN new RenderQueue(isolatedStack, 'RenderQueue', { images, repository, version: new VersionQuery(isolatedStack, 'Version'), vpc, enableLocalFileCaching: true, }); // THEN // Note: If this test breaks/fails, then it is probable that the // 'Does not enable filesystem cache by default' test above will also require // updating/fixing. expectCDK(isolatedStack).to(haveResourceLike('AWS::AutoScaling::LaunchConfiguration', { UserData: { 'Fn::Base64': { 'Fn::Join': arrayWith(arrayWith(' >> /etc/ecs/ecs.config\nsudo iptables --insert FORWARD 1 --in-interface docker+ --destination 169.254.169.254/32 --jump DROP\nsudo service iptables save\necho ECS_AWSVPC_BLOCK_IMDS=true >> /etc/ecs/ecs.config\nyum install -yq awscli unzip\n# RenderQueue file caching enabled\nmkdir -p $(dirname \'/tmp/')), }, }, })); }); test('runs as RCS user', () => { // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: arrayWith( objectLike({ User: '1000:1000' }), ), })); }); describe('Secrets Management', () => { let rqSecretsManagementProps: RenderQueueProps; beforeEach(() => { rqSecretsManagementProps = { vpc, images, repository, version: renderQueueVersion, trafficEncryption: { internalProtocol: ApplicationProtocol.HTTPS, externalTLS: { enabled: true }, }, }; }); test('throws if internal protocol is not HTTPS', () => { // WHEN expect(() => new RenderQueue(stack, 'SecretsManagementRenderQueue', { ...rqSecretsManagementProps, trafficEncryption: { internalProtocol: ApplicationProtocol.HTTP, }, })) // THEN .toThrowError(/The internal protocol on the Render Queue is not HTTPS./); }); test('throws if external TLS is not enabled', () => { // WHEN expect(() => new RenderQueue(stack, 'SecretsManagementRenderQueue', { ...rqSecretsManagementProps, trafficEncryption: { externalTLS: { enabled: false }, }, })) // THEN .toThrowError(/External TLS on the Render Queue is not enabled./); }); test('throws if repository does not have SM credentials', () => { // WHEN expect(() => new RenderQueue(stack, 'SecretsManagementRenderQueue', { ...rqSecretsManagementProps, repository: { ...repository, secretsManagementSettings: { ...repository.secretsManagementSettings, credentials: undefined, }, } as Repository, })) // THEN .toThrowError(/The Repository does not have Secrets Management credentials/); }); test('throws if deadline version is too low', () => { // GIVEN const oldVersion = new VersionQuery(new Stack(app, 'OldDeadlineVersionStack'), 'OldDeadlineVersion', { version: '10.0.0.0' }); // WHEN expect(() => new RenderQueue(stack, 'SecretsManagementRenderQueue', { ...rqSecretsManagementProps, version: oldVersion, })) // THEN /* eslint-disable-next-line dot-notation */ .toThrowError(`The supplied Deadline version (${oldVersion.versionString}) does not support Deadline Secrets Management in RFDK. Either upgrade Deadline to the minimum required version (${Version.MINIMUM_SECRETS_MANAGEMENT_VERSION.versionString}) or disable the feature in the Repository's construct properties.`); }); test('grants read permissions to secrets management credentials', () => { // WHEN const rq = new RenderQueue(stack, 'SecretsManagementRenderQueue', rqSecretsManagementProps); // THEN expectCDK(stack).to(haveResourceLike('AWS::IAM::Policy', { PolicyDocument: objectLike({ Statement: arrayWith({ Action: [ 'secretsmanager:GetSecretValue', 'secretsmanager:DescribeSecret', ], Effect: 'Allow', Resource: stack.resolve((repository.secretsManagementSettings.credentials!.node.defaultChild as CfnSecret).ref), }), }), Roles: [stack.resolve((rq.node.tryFindChild('RCSTask') as Ec2TaskDefinition).taskRole.roleName)], })); }); test('defines secrets management credentials environment variable', () => { // WHEN new RenderQueue(stack, 'SecretsManagementRenderQueue', rqSecretsManagementProps); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: arrayWith(objectLike({ Environment: arrayWith({ Name: 'RCS_SM_CREDENTIALS_URI', Value: stack.resolve((repository.secretsManagementSettings.credentials!.node.defaultChild as CfnSecret).ref), }), })), })); }); test('creates and mounts docker volume for deadline key pairs', () => { // WHEN new RenderQueue(stack, 'SecretsManagementRenderQueue', rqSecretsManagementProps); // THEN expectCDK(stack).to(haveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: arrayWith(objectLike({ MountPoints: arrayWith({ ContainerPath: '/home/ec2-user/.config/.mono/keypairs', ReadOnly: false, SourceVolume: 'deadline-user-keypairs', }), })), Volumes: arrayWith({ DockerVolumeConfiguration: { Autoprovision: true, Driver: 'local', Scope: 'shared', }, Name: 'deadline-user-keypairs', }), })); }); describe('client calls .configureSecretsManagementAutoRegistration()', () => { let callParams: any; let clientInstance: Instance; let identityRegistrationSettings: SecretsManagementIdentityRegistration; let launchConfiguration: CfnLaunchConfiguration; let rqVpcSubnets: SubnetSelection; const RQ_SUBNET_IDS = ['SubnetID1', 'SubnetID2']; beforeEach(() => { // GIVEN const subnets = [ Subnet.fromSubnetAttributes(dependencyStack, 'Subnet1', { subnetId: RQ_SUBNET_IDS[0], availabilityZone: 'us-west-2a', }), Subnet.fromSubnetAttributes(dependencyStack, 'Subnet2', { subnetId: RQ_SUBNET_IDS[1], availabilityZone: 'us-west-2b', }), ]; rqVpcSubnets = { subnets, }; const rq = new RenderQueue(stack, 'SecretsManagementRenderQueue', { ...rqSecretsManagementProps, vpcSubnets: rqVpcSubnets, }); clientInstance = new Instance(stack, 'ClientInstance', { instanceType: new InstanceType('t3.micro'), machineImage: new AmazonLinuxImage(), vpc, }); callParams = { dependent: clientInstance, registrationStatus: SecretsManagementRegistrationStatus.REGISTERED, role: SecretsManagementRole.CLIENT, vpc, vpcSubnets: { subnetType: SubnetType.PRIVATE }, }; launchConfiguration = ( // @ts-ignore rq.deploymentInstance .node.findChild('ASG') .node.findChild('LaunchConfig') ) as CfnLaunchConfiguration; // @ts-ignore identityRegistrationSettings = rq.identityRegistrationSettings; jest.spyOn(identityRegistrationSettings, 'addSubnetIdentityRegistrationSetting'); // WHEN rq.configureSecretsManagementAutoRegistration(callParams); }); test('registration is delegated to SecretsManagementIdentityRegistration', () => { // THEN expect(identityRegistrationSettings.addSubnetIdentityRegistrationSetting).toHaveBeenCalledWith(callParams); }); test('deployment instance is created using specified subnets', () => { // THEN expectCDK(stack).to(haveResourceLike('AWS::AutoScaling::AutoScalingGroup', { LaunchConfigurationName: stack.resolve(launchConfiguration.ref), VPCZoneIdentifier: arrayWith( ...RQ_SUBNET_IDS, ), })); }); }); }); test('.backendConnections is associated with ASG security group rules', () => { // GIVEN const instance = new Instance(dependencyStack, 'BackendConnectionInstance', { instanceType: InstanceType.of(InstanceClass.T3, InstanceSize.MICRO), machineImage: MachineImage.latestAmazonLinux(), vpc, }); const portNumber = 5555; const port = Port.tcp(portNumber); const asgSecurityGroup = renderQueueCommon.asg.connections.securityGroups[0]; // WHEN renderQueueCommon.backendConnections.allowFrom(instance, port); // THEN expectCDK(stack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', Description: `from ${instance.connections.securityGroups[0].uniqueId}:${portNumber}`, GroupId: stack.resolve(asgSecurityGroup.securityGroupId), SourceSecurityGroupId: stack.resolve(instance.connections.securityGroups[0].securityGroupId), FromPort: portNumber, ToPort: portNumber, })); }); });
the_stack
//const Z_FILTERED = 1; //const Z_HUFFMAN_ONLY = 2; //const Z_RLE = 3; const Z_FIXED = 4; //const Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ const Z_BINARY = 0; const Z_TEXT = 1; //const Z_ASCII = 1; // = Z_TEXT const Z_UNKNOWN = 2; function zero(buf: any) { buf.fill(0, 0, buf.length); } // From zutil.h const STORED_BLOCK = 0; const STATIC_TREES = 1; const DYN_TREES = 2; /* The three kinds of block type */ const MIN_MATCH = 3; const MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ const LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ const LITERALS = 256; /* number of literal bytes 0..255 */ const L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ const D_CODES = 30; /* number of distance codes */ const BL_CODES = 19; /* number of codes used to transfer the bit lengths */ const HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ const MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ const Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ const MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ const END_BLOCK = 256; /* end of block literal code */ const REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ const REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ const REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ /* eslint-disable comma-spacing,array-bracket-spacing */ const extra_lbits = /* extra bits for each length code */ [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, ]; const extra_dbits = /* extra bits for each distance code */ [ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, ]; const extra_blbits = /* extra bits for each bit length code */ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]; const bl_order = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15, ]; /* eslint-enable comma-spacing,array-bracket-spacing */ /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps const DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 const static_ltree = new Array((L_CODES + 2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ const static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ const _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ const _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ const base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ const base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ class StaticTreeDesc { static_tree: any; /* static tree or NULL */ extra_bits: any; /* extra bits for each code or NULL */ extra_base: any; /* base index for extra_bits */ elems: any; /* max number of elements in the tree */ max_length: any; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects has_stree: any; constructor( static_tree: any, extra_bits: any, extra_base: any, elems: any, max_length: any, ) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; } } let static_l_desc: any; let static_d_desc: any; let static_bl_desc: any; class TreeDesc { dyn_tree: any; /* the dynamic tree */ max_code: any; /* largest code with non zero frequency */ stat_desc: any; /* the corresponding static tree */ constructor(dyn_tree: any, stat_desc: any) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ } } function d_code(dist: any) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short(s: any, w: any) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s: any, value: any, length: any) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s: any, c: any, tree: any) { send_bits(s, tree[c * 2], /*.Code*/ tree[c * 2 + 1] /*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code: any, len: any) { let res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s: any) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s: any, desc: any) { let tree = desc.dyn_tree; let max_code = desc.max_code; let stree = desc.stat_desc.static_tree; let has_stree = desc.stat_desc.has_stree; let extra = desc.stat_desc.extra_bits; let base = desc.stat_desc.extra_base; let max_length = desc.stat_desc.max_length; let h; /* heap index */ let n, m; /* iterate over the tree elements */ let bits; /* bit length */ let xbits; /* extra bits */ let f; /* frequency */ let overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max] * 2 + 1] /*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1] /*.Dad*/ * 2 + 1] /*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1] /*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) continue; /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n - base]; } f = tree[n * 2] /*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n * 2 + 1] /*.Len*/ + xbits); } } if (overflow === 0) return; // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length - 1; while (s.bl_count[bits] === 0) bits--; s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) continue; if (tree[m * 2 + 1] /*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m * 2 + 1] /*.Len*/) * tree[m * 2] /*.Freq*/; tree[m * 2 + 1] /*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree: any, max_code: any, bl_count: any) { let next_code = new Array( MAX_BITS + 1, ); /* next code value for each bit length */ let code = 0; /* running code value */ let bits; /* bit index */ let n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits - 1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { let len = tree[n * 2 + 1] /*.Len*/; if (len === 0) continue; /* Now reverse the bits */ tree[n * 2] /*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { let n; /* iterates over tree elements */ let bits; /* bit counter */ let length; /* length value */ let code; /* code value */ let dist; /* distance index */ let bl_count = new Array(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES - 1; code++) { base_length[code] = length; for (n = 0; n < (1 << extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length - 1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1 << extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n * 2 + 1] /*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n * 2 + 1] /*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n * 2 + 1] /*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n * 2 + 1] /*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES + 1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n * 2 + 1] /*.Len*/ = 5; static_dtree[n * 2] /*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc( static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS, ); static_d_desc = new StaticTreeDesc( static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, ); static_bl_desc = new StaticTreeDesc( new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS, ); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s: any) { let n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) s.dyn_ltree[n * 2] /*.Freq*/ = 0; for (n = 0; n < D_CODES; n++) s.dyn_dtree[n * 2] /*.Freq*/ = 0; for (n = 0; n < BL_CODES; n++) s.bl_tree[n * 2] /*.Freq*/ = 0; s.dyn_ltree[END_BLOCK * 2] /*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s: any) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s: any, buf: any, len: any, header: any) { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } s.pending_buf.set(s.window.subarray(buf, buf + len), s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree: any, n: any, m: any, depth: any) { let _n2 = n * 2; let _m2 = m * 2; return (tree[_n2] /*.Freq*/ < tree[_m2] /*.Freq*/ || (tree[_n2] /*.Freq*/ === tree[_m2] /*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s: any, tree: any, k: any) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { let v = s.heap[k]; let j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if ( j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth) ) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) break; /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // let SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s: any, ltree: any, dtree: any) { let dist; /* distance of matched string */ let lc; /* match length or unmatched char (if dist == 0) */ let lx = 0; /* running index in l_buf */ let code; /* the code to send */ let extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code + LITERALS + 1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s: any, desc: any) { let tree = desc.dyn_tree; let stree = desc.stat_desc.static_tree; let has_stree = desc.stat_desc.has_stree; let elems = desc.stat_desc.elems; let n, m; /* iterate over heap elements */ let max_code = -1; /* largest code with non zero frequency */ let node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2] /*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1] /*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2] /*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node * 2 + 1] /*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1 /*int /2*/); n >= 1; n--) pqdownheap(s, tree, n); /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/ ]; s.heap[1/*SMALLEST*/ ] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1 /*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/ ]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2] /*.Freq*/ = tree[n * 2] /*.Freq*/ + tree[m * 2] /*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n * 2 + 1] /*.Dad*/ = tree[m * 2 + 1] /*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/ ] = node++; pqdownheap(s, tree, 1 /*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/ ]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s: any, tree: any, max_code: any) { let n; /* iterates over all tree elements */ let prevlen = -1; /* last emitted length */ let curlen; /* length of current code */ let nextlen = tree[0 * 2 + 1] /*.Len*/; /* length of next code */ let count = 0; /* repeat count of the current code */ let max_count = 7; /* max repeat count */ let min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code + 1) * 2 + 1] /*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1] /*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2] /*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) s.bl_tree[curlen * 2] /*.Freq*/++; s.bl_tree[REP_3_6 * 2] /*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10 * 2] /*.Freq*/++; } else { s.bl_tree[REPZ_11_138 * 2] /*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s: any, tree: any, max_code: any) { let n; /* iterates over all tree elements */ let prevlen = -1; /* last emitted length */ let curlen; /* length of current code */ let nextlen = tree[0 * 2 + 1] /*.Len*/; /* length of next code */ let count = 0; /* repeat count of the current code */ let max_count = 7; /* max repeat count */ let min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1] /*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count - 3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count - 3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count - 11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s: any) { let max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex] * 2 + 1] /*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s: any, lcodes: any, dcodes: any, blcodes: any) { let rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes - 1, 5); send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1], /*.Len*/ 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s: any) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ let black_mask = 0xf3ffc07f; let n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n * 2] /*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if ( s.dyn_ltree[9 * 2] /*.Freq*/ !== 0 || s.dyn_ltree[10 * 2] /*.Freq*/ !== 0 || s.dyn_ltree[13 * 2] /*.Freq*/ !== 0 ) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2] /*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } let static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ export function _tr_init(s: any) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ export function _tr_stored_block(s: any, buf: any, stored_len: any, last: any) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ export function _tr_align(s: any) { send_bits(s, STATIC_TREES << 1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ export function _tr_flush_block(s: any, buf: any, stored_len: any, last: any) { let opt_lenb, static_lenb; /* opt_len and static_len in bytes */ let max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len + 3 + 7) >>> 3; static_lenb = (s.static_len + 3 + 7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) opt_lenb = static_lenb; } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); send_all_trees( s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1, ); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ export function _tr_tally(s: any, dist: any, lc: any) { //let out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc * 2] /*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2] /*.Freq*/++; s.dyn_dtree[d_code(dist) * 2] /*.Freq*/++; } // (!) This block is disabled in zlib defaults, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize - 1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ }
the_stack
import { root, text, list, listItem, paragraph, strong, brk, link, inlineCode, table, tableRow, tableCell, code, html } from 'mdast-builder'; import { ApiClass, ApiConstructor, ApiConstructSignature, ApiDocumentedItem, ApiEnum, ApiFunction, ApiInterface, ApiItem, ApiItemKind, ApiMethod, ApiMethodSignature, ApiModel, ApiPackage, ApiParameterListMixin, ApiPropertyItem, ApiTypeAlias, Parameter, ApiDeclaredItem, Excerpt, ApiEntryPoint, ExcerptTokenKind } from '@microsoft/api-extractor-model'; import { DocSection, DocParagraph, DocPlainText, DocLinkTag, DocSoftBreak, DocCodeSpan, DocBlock, DocHtmlStartTag } from '@microsoft/tsdoc'; import { Node, Parent } from 'unist'; import { section, itemSections, Ctor, itemsOfType, SectionTitle, filterUndef, FrontmatterEntires } from './macros'; import 'array.prototype.flatmap'; import 'array.prototype.flat'; /** * Information about the context of a documentation process. */ export interface DocumentationContext { model: ApiModel; pkg: ApiPackage; pkgEntry: ApiEntryPoint; } /** * Binds a function to a documentation context. */ function withCtx< F extends (ctx: DocumentationContext, ...args: A) => R, A extends any[], R >(ctx: DocumentationContext, fn: F): (...args: A) => R { return (...args: A) => fn(ctx, ...args); } /** * Heuristic that decides if a parameter utilizes object destructuring. */ function isDestructuredParam(param: Parameter): boolean { return param.name.startsWith('{') && param.name.endsWith('}'); } /** * Heuristic that decides if a parameter is required or not */ function isRequiredParam(item: ApiDeclaredItem, param: Parameter): boolean { // If a `?` is found in the excerpt token before the type, we assume that this // parameter is optional, e.g. `?: ` before the token `string` return !item.excerptTokens[ param.parameterTypeExcerpt.tokenRange.startIndex - 1 ].text.includes('?'); } /** * Prepends a list of child nodes to the first found paragraph. If no paragraph * is found, the children aren't inserted. */ function prependFirstParagraph( nodes: readonly Node[], children: readonly Node[] ): Node[] { // Find the first paragraph const firstPara = nodes.find(node => node.type === 'paragraph'); if (firstPara !== undefined) { // Prepend the new children (firstPara as Parent).children.unshift(...children); } return nodes as Node[]; } /** * Formats the name of a package as a URL-friendly slug. * * @remarks * Excludes the common `@slack/` at the start of most package names and replaces * sequences of (1+) non-alphanumeric characters with a hyphen. */ export function formatPkgSlug(pkg: ApiPackage): string { return pkg.name .replace(/@slack\//i, '') .replace(/[^a-zA-Z0-9]+($)?/g, '-'); } /** * Attempts to link to a target API item by its name. */ function tryLinkName( ctx: DocumentationContext, name: string, child: Node ): Node { // Attempt to find the target item const [target] = ctx.pkgEntry.findMembersByName(name); // TODO: handle multiple targets? // If the target isn't found, simply return the child w/o a link if (target === undefined) { return child; } // TODO: We don't solidly know the URL to link to this item. The below works // for GitHub-style heading `id`s. return link(`#${target.displayName.toLowerCase()}`, undefined, child); } /** * Formats a type excerpt (like `{}`) to be more human-friendly and possibly * link to the type(s) it refers to. */ function formatExcerptReferences( ctx: DocumentationContext, excerpt: Excerpt ): Node[] { // Bail early for object types/interface shorthand by searching for anything // that looks like an object (which starts and ends with `{` and `}`) and // might be followed by a number of array brackets (`[]`) if (excerpt.text.match(/^{(?:\s|\S)*}(?:\[\])*$/) !== null) { // TODO: The information about this object (its properties and such) are now // lost. How can we retain that information? return [inlineCode('object')]; } return [ // HTML `<code>` tags need to be used in order to let links within the // inline code segment to work. html('<code>'), ...excerpt.tokens // Get the relevant tokens .filter( (_, i) => i >= excerpt.tokenRange.startIndex && i < excerpt.tokenRange.endIndex ) // Map `Content`-kind tokens to just their text & `Reference`-kind tokens by // their own format function .map(token => token.kind === ExcerptTokenKind.Content ? text(token.text) : tryLinkName(ctx, token.text, text(token.text)) ), html('</code>') ]; } /** * Converts a DocSection to an array of `mdast` paragraphs. */ function convertDocSection( ctx: DocumentationContext, section: DocSection ): Node[] { // Elements within sections are paragraphs return (section.nodes as readonly DocParagraph[]).map(para => paragraph( para.nodes // Filter out soft breaks .filter(node => !(node instanceof DocSoftBreak)) // Convert DocNodes to mdast nodes .map(node => { if (node instanceof DocPlainText) { // Plain text maps to `text` nodes return text(node.text); } else if (node instanceof DocLinkTag) { // Links map to links. The URI depends on the destination. if (node.codeDestination !== undefined) { const name = node.codeDestination.memberReferences[0] .memberIdentifier!.identifier; return tryLinkName(ctx, name, inlineCode(name)); } else if (node.urlDestination !== undefined) { return link(node.urlDestination, undefined, [ text( node.linkText === undefined ? node.urlDestination : node.linkText ) ]); } else { throw new Error('misformatted DocLinkTag'); } } else if (node instanceof DocCodeSpan) { // Code spans map to inline code nodes return inlineCode(node.code); } else if (node instanceof DocHtmlStartTag) { // NOTE: It seems like this is usually `<br />` tags return html(node.emitAsHtml()); } else { throw new Error(`unknown DocNode type encountered: '${node.kind}'`); } }) ) ); } /** * Converts a DocBlock to a titled section. */ function convertDocBlock( ctx: DocumentationContext, title: SectionTitle, block: DocBlock ): Node[] { return section(title, convertDocSection(ctx, block.content)); } /** * Attempts to extract and format documentation from associated comments with a * documentable API item. * * @remarks * Extracts: * - The description (if any). * - The remarks (if any). * - An example (if any). */ function itemDocumentation( ctx: DocumentationContext, item: ApiDocumentedItem ): Node[] { // Short circuit if there's no documentation comment for this item if (item.tsdocComment === undefined) { return []; } // Attempt to find the `@example` block const exampleBlock = item.tsdocComment.customBlocks.find( block => block.blockTag.tagNameWithUpperCase === '@EXAMPLE' ); return [ // TODO: handle `@deprecation` tags by making a big, flashy "this is // deprecated" alert for this item // Summary convertDocSection(ctx, item.tsdocComment.summarySection), // Remarks item.tsdocComment.remarksBlock !== undefined ? convertDocBlock(ctx, [5, 'Remarks'], item.tsdocComment.remarksBlock) : [], // Example exampleBlock !== undefined ? convertDocBlock(ctx, [5, 'Example'], exampleBlock) : [] ].flat(); } /** * Generates the title for a function-like item (e.g. a function, method, * constructor). * * @remarks * The generated string looks like `name(param1, param2, param3)` where: * - `name` is either the value of this function's `name` argument (if * provided) or the function-like's name. * - `paramX` is the name of the parameter or `opts` if the parameter is * defined using object destructuring. */ function fnLikeTitle(item: ApiParameterListMixin, name?: string): Node[] { // TODO: linkify parameters? // TODO: configurable name for destructutred params instead of always "opts" return [ text( `${name === undefined ? item.displayName : name}(${item.parameters .map(param => (isDestructuredParam(param) ? 'opts' : param.name)) .join(', ')})` ) ]; } /** * Generates information about a function-like (which includes functions, * methods, constructors, and constructor signatures). * * @remarks * Includes: * - Comment-provided documentation (if any). * - A table describing the function's parameters (if any). * - Each parameter is described by its name, type, whether it's required or * not, and any documentation comment-provided description. If none of the * parameters have descriptions, the description column from the table is * excluded. */ function documentFnLike( ctx: DocumentationContext, item: ApiFunction | ApiMethod | ApiConstructor | ApiConstructSignature ): Node[] { // Determine which parameter is an options parameter (if there is one) const optsParam = item.parameters.find(isDestructuredParam); const [optsTarget = undefined] = optsParam !== undefined ? ctx.pkgEntry.findMembersByName(optsParam.parameterTypeExcerpt.text) : []; const hasOpts = optsParam !== undefined && optsTarget !== undefined; // Hide the "Description" column if none of the parameters have descriptions const paramsHaveDesc = item.parameters.some( param => param.tsdocParamBlock !== undefined ); const hasReturnDoc = item.tsdocComment !== undefined && item.tsdocComment.remarksBlock !== undefined; return [ // Documentation itemDocumentation(ctx, item), // Parameters item.parameters.length === 0 ? [] : [ strong(text('Parameters:')), table(['center', 'center', 'center', null] as any, [ tableRow( filterUndef([ tableCell(text('Name')), tableCell(text('Type')), tableCell(text('Required')), paramsHaveDesc ? tableCell(text('Description')) : undefined ]) ), ...item.parameters.map(param => tableRow( filterUndef([ // Name tableCell( text(hasOpts && param === optsParam ? 'opts' : param.name) ), // Type tableCell( formatExcerptReferences(ctx, param.parameterTypeExcerpt) ), // Required tableCell(text(isRequiredParam(item, param) ? '✓' : '✗')), // Description paramsHaveDesc ? tableCell( param.tsdocParamBlock === undefined ? text( hasOpts && param === optsParam ? 'See options.' : '' ) : convertDocSection( ctx, param.tsdocParamBlock.content ) ) : undefined ]) ) ) ]) ], // Options hasOpts ? [ strong(text('Options:')), // We assume that `opts` is a non-empty interface documentClassLikeProps(ctx, optsTarget as ApiInterface) as Node ] : [], // Return value 'returnTypeExcerpt' in item ? prependFirstParagraph( hasReturnDoc ? convertDocSection(ctx, item.tsdocComment!.returnsBlock!.content) : [paragraph()], [ // Section title strong(text('Returns')), // Return type text(' '), ...formatExcerptReferences(ctx, item.returnTypeExcerpt), // Separate return title from description ...(hasReturnDoc ? [text(':'), brk, brk] : []) ] ) : [] ].flat(); } /** * Generates information about the properties/fields of a class-like. * * @remarks * Creates a table including the prop's/field's name, type, and a documentation * comment-provided description. If none of the props/fields include a * description, that column of the table is excluded. */ function documentClassLikeProps( ctx: DocumentationContext, item: ApiClass | ApiInterface ): Node | undefined { const props = itemsOfType(item.members, ApiPropertyItem); // Hide the "Description" column if none of the props have descriptions const propsHaveDesc = props.some(prop => prop.tsdocComment !== undefined); return props.length === 0 ? undefined : table(['center', 'center', null] as any, [ tableRow( filterUndef([ tableCell(text('Name')), tableCell(text('Type')), propsHaveDesc ? tableCell(text('Description')) : undefined ]) ), ...props.map(prop => tableRow( filterUndef([ // Name tableCell(text(prop.name)), // Type tableCell(formatExcerptReferences(ctx, prop.propertyTypeExcerpt)), // TODO: other tsdoc sections? // Description propsHaveDesc ? tableCell( prop.tsdocComment === undefined ? text('') : convertDocSection(ctx, prop.tsdocComment.summarySection) ) : undefined ]) ) ) ]); } /** * Generates information about a class or interface. * * @remarks * Includes: * - Comment documentation associated with the class-like (if any). * - Constructors (formatted as `new {ClassLikeName}(parameters)`) (if any). * - A table of fields/properties (if any). * - Methods (if any). */ function documentClassLike( ctx: DocumentationContext, item: ApiClass | ApiInterface ): Node[] { const ctorKind: Ctor<ApiConstructor | ApiConstructSignature> = item instanceof ApiClass ? ApiConstructor : ApiConstructSignature; const methodKind: Ctor<ApiMethod | ApiMethodSignature> = item instanceof ApiClass ? ApiMethod : ApiMethodSignature; // Get the properties/fields documentation const propsTable = documentClassLikeProps(ctx, item); return [ // Documentation itemDocumentation(ctx, item), // Constructor(s) itemsOfType(item.members, ctorKind).flatMap(ctorItem => section( // These headings are at depth 5 to match other members [4, fnLikeTitle(ctorItem, `new ${item.name}`)], documentFnLike(ctx, ctorItem) ) ), // Fields/properties propsTable === undefined ? [] : section([3, 'Fields'], propsTable), // Methods itemSections( [3, 'Methods'], itemsOfType(item.members, methodKind), withCtx(ctx, documentFnLike), fnLikeTitle ) ].flat(); } /** * Generates information about an enum. * * @remarks * Lists all the members of the enum & any accompanying comment documentation * for each member. */ function documentEnum(ctx: DocumentationContext, item: ApiEnum): Node[] { return [ // Documentation itemDocumentation(ctx, item), // Members section( [3, 'Members'], list( 'unordered', item.members.map(member => listItem( prependFirstParagraph( member.tsdocComment === undefined ? [paragraph()] : convertDocSection(ctx, member.tsdocComment.summarySection), [ // Member name strong(text(member.name)), // Separate summary from member name text(member.tsdocComment === undefined ? '' : ': ') ] ) ) ) ) ) ].flat(); } /** * Generates information about a type alias. * * @remarks * Includes the relevant definition of the type alias (the part after `=` but * before `;` in `type X = ...;`) and attempts to make an English description * of the type alias. */ function documentTypeAlias( ctx: DocumentationContext, item: ApiTypeAlias ): Node[] { // A few tokens are skipped: // - [0]: "export declare type " // - [1]: this type alias' name // - [2]: " = " // - [length - 1]: ";" const tokens = item.excerptTokens.filter( (_, i, arr) => i > 2 && i < arr.length - 1 ); // Attempt to describe the type alias. let description: Node[] = []; if ( tokens .filter(token => token.kind === ExcerptTokenKind.Content) .every(token => token.text === ' | ') ) { // Follows the form `A | B | C | ... | Z` description = [ text('One of:'), list( 'unordered', tokens .filter(token => token.kind === ExcerptTokenKind.Reference) .map(token => listItem(tryLinkName(ctx, token.text, inlineCode(token.text))) ) ) ]; } return [ // Documentation itemDocumentation(ctx, item), // Excerpt [code('ts', tokens.map(token => token.text).join(''))], // Description of the type alias description ].flat(); } /** * Filters out noisy items from the `@slack/web-api` package docs. */ function filterWebApi(item: ApiItem): boolean { if (item instanceof ApiInterface) { // Skip all `*Arguments` and `*Response` interfaces return !(item.name.endsWith('Arguments') || item.name.endsWith('Response')); } else if (item instanceof ApiClass) { // Ignore the `Methods` abstract class as well return item.name !== 'Methods'; } return true; } /** * Generates information about a package in an API model. */ export function documentPkg(model: ApiModel, pkg: ApiPackage): [FrontmatterEntires, Node] { // Every package is only expected to have one entry point if ( pkg.members.length !== 1 || pkg.members[0].kind !== ApiItemKind.EntryPoint ) { throw new Error(`expected only one entry point in package "${pkg.name}"`); } // Create the context object for this process const ctx: DocumentationContext = { model, pkg, pkgEntry: pkg.members[0] as ApiEntryPoint }; // Pick an item filter depending on the package const itemFilter = pkg.name === '@slack/web-api' ? filterWebApi : () => true; // All top-level API members in this package const apiItems = ctx.pkgEntry.members.filter(itemFilter); return [ { // The title of the page is just the package name title: `"${pkg.name}"`, // See the `formatPkgSlug` for the format of the slug slug: formatPkgSlug(pkg) }, root( [ ...itemSections( [1, 'Classes'], itemsOfType(apiItems, ApiClass), withCtx(ctx, documentClassLike) ), ...itemSections( [1, 'Functions'], itemsOfType(apiItems, ApiFunction), withCtx(ctx, documentFnLike), fnLikeTitle ), ...itemSections( [1, 'Enums'], itemsOfType(apiItems, ApiEnum), withCtx(ctx, documentEnum) ), ...itemSections( [1, 'Interfaces'], itemsOfType(apiItems, ApiInterface), withCtx(ctx, documentClassLike) ), ...itemSections( [1, 'Type Aliases'], itemsOfType(apiItems, ApiTypeAlias), withCtx(ctx, documentTypeAlias) ) ] ) ]; } /** * Creates an index page linking to each package in an API model. */ export function documentModel(model: ApiModel): [FrontmatterEntires, Node] { return [ { title: 'Reference Documentation', parmalink: '/reference/' }, root( [ paragraph([strong(text('Packages:'))]), list( 'unordered', model.packages.map(pkg => listItem(link(formatPkgSlug(pkg), undefined, text(pkg.name))) ) ) ] ) ]; }
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview Code to record and configure the units of measurement shown for various heights, distances etc. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; export var isFlightSim = VRS.isFlightSim || false; // <-- true if the flight sim page was loaded VRS.globalOptions.unitDisplayHeight = VRS.globalOptions.unitDisplayHeight || VRS.Height.Feet; // The default unit for altitudes. VRS.globalOptions.unitDisplaySpeed = VRS.globalOptions.unitDisplaySpeed || VRS.Speed.Knots; // The default unit for speeds. VRS.globalOptions.unitDisplayDistance = VRS.globalOptions.unitDisplayDistance || VRS.Distance.Kilometre; // The default unit for distances. VRS.globalOptions.unitDisplayPressure = VRS.globalOptions.unitDisplayPressure || VRS.Pressure.InHg; // The default unit for pressures. VRS.globalOptions.unitDisplayVsiPerSecond = VRS.globalOptions.unitDisplayVsiPerSecond !== undefined ? VRS.globalOptions.unitDisplayVsiPerSecond : VRS.isFlightSim; // True if vertical speeds are to be shown per second rather than per minute. VRS.globalOptions.unitDisplayFLTransitionAltitude = VRS.globalOptions.unitDisplayFLTransitionAltitude || 18000; // The default flight level transition altitude. VRS.globalOptions.unitDisplayFLTransitionHeightUnit = VRS.globalOptions.unitDisplayFLTransitionHeightUnit || VRS.Height.Feet; // The units that FLTransitionAltitude is in. VRS.globalOptions.unitDisplayFLHeightUnit = VRS.globalOptions.unitDisplayFLHeightUnit || VRS.Height.Feet; // The units that flight levels are displayed in. VRS.globalOptions.unitDisplayAllowConfiguration = VRS.globalOptions.unitDisplayAllowConfiguration !== undefined ? VRS.globalOptions.unitDisplayAllowConfiguration : true; // True if users can configure the display units, false if they cannot. VRS.globalOptions.unitDisplayAltitudeType = VRS.globalOptions.unitDisplayAltitudeType !== undefined ? VRS.globalOptions.unitDisplayAltitudeType : false; // True if altitude types are to be shown by default. VRS.globalOptions.unitDisplayVerticalSpeedType = VRS.globalOptions.unitDisplayVerticalSpeedType !== undefined ? VRS.globalOptions.unitDisplayVerticalSpeedType : false; // True if vertical speed types are to be shown by default. VRS.globalOptions.unitDisplaySpeedType = VRS.globalOptions.unitDisplaySpeedType !== undefined ? VRS.globalOptions.unitDisplaySpeedType : true; // True if speed types are to be shown by default. VRS.globalOptions.unitDisplayTrackType = VRS.globalOptions.unitDisplayTrackType !== undefined ? VRS.globalOptions.unitDisplayTrackType : false; // True if track types are to be shown by default. VRS.globalOptions.unitDisplayUsePressureAltitude = VRS.globalOptions.unitDisplayUsePressureAltitude !== undefined ? VRS.globalOptions.unitDisplayUsePressureAltitude : true; // True to use pressure altitudes when we have a choice between pressure and geometric altitudes. /** * The state object that instances of UnitDisplayPreferences save between sessions. */ export interface UnitDisplayPreferences_SaveState { distanceUnit: DistanceEnum; heightUnit: HeightEnum; speedUnit: SpeedEnum; pressureUnit: PressureEnum; vsiPerSecond: boolean; flTransitionAlt: number; flTransitionUnit: HeightEnum; flHeightUnit: HeightEnum; showAltType: boolean; showVsiType: boolean; showSpeedType: boolean; showTrackType: boolean; usePressureAltitude: boolean; } /** * A class that brings together the various units of measurement that the user can configure. */ export class UnitDisplayPreferences implements ISelfPersist<UnitDisplayPreferences_SaveState> { private _Dispatcher = new VRS.EventHandler({ name: 'VRS.UnitDisplayPreferences' }); private _Events = { unitChanged: 'unitChanged', distanceUnitChanged: 'distanceUnitChanged', heightUnitChanged: 'heightUnitChanged', speedUnitChanged: 'speedUnitChanged', pressureUnitChanged: 'pressureUnitChanged', showVsiInSecondsChanged: 'showVsiSecondsChanged', flAltitudeChanged: 'flAltitudeChanged', flTransUnitChanged: 'flTransUnitChanged', flHeightUnitChanged: 'flHeightUnitChanged', showAltitudeTypeChanged: 'showAltTypeChanged', showVerticalSpeedTypeChanged: 'showVsiTypeChanged', showSpeedTypeChanged: 'showSpeedTypeChanged', showTrackTypeChanged: 'showTrackTypeChanged', usePressureAltitudeChanged: 'usePressureAltitudeChanged' } private _Name: string; private _DistanceUnit: DistanceEnum; private _HeightUnit: HeightEnum; private _SpeedUnit: SpeedEnum; private _PressureUnit: PressureEnum; private _ShowVerticalSpeedPerSecond: boolean; private _ShowAltitudeType: boolean; private _ShowVerticalSpeedType: boolean; private _ShowSpeedType: boolean; private _ShowTrackType: boolean; private _UsePressureAltitude: boolean; private _FlightLevelTransitionAltitude: number; private _FlightLevelTransitionHeightUnit: HeightEnum; private _FlightLevelHeightUnit: HeightEnum; constructor(name?: string) { this._Name = name || 'vrsUnitDisplayPreferences'; this._DistanceUnit = VRS.globalOptions.unitDisplayDistance; this._HeightUnit = VRS.globalOptions.unitDisplayHeight; this._SpeedUnit = VRS.globalOptions.unitDisplaySpeed; this._PressureUnit = VRS.globalOptions.unitDisplayPressure; this._ShowVerticalSpeedPerSecond = VRS.globalOptions.unitDisplayVsiPerSecond; this._ShowAltitudeType = VRS.globalOptions.unitDisplayAltitudeType; this._ShowVerticalSpeedType = VRS.globalOptions.unitDisplayVerticalSpeedType; this._ShowSpeedType = VRS.globalOptions.unitDisplaySpeedType; this._ShowTrackType = VRS.globalOptions.unitDisplayTrackType; this._UsePressureAltitude = VRS.globalOptions.unitDisplayUsePressureAltitude; this._FlightLevelTransitionAltitude = VRS.globalOptions.unitDisplayFLTransitionAltitude; this._FlightLevelTransitionHeightUnit = VRS.globalOptions.unitDisplayFLTransitionHeightUnit; this._FlightLevelHeightUnit = VRS.globalOptions.unitDisplayFLHeightUnit; if(VRS.serverConfig) { var config = VRS.serverConfig.get(); if(config) { this.setDistanceUnit(config.InitialDistanceUnit); this.setHeightUnit(config.InitialHeightUnit); this.setSpeedUnit(config.InitialSpeedUnit); } } } getName = () : string => { return this._Name; } getDistanceUnit = () : DistanceEnum => { return this._DistanceUnit; } setDistanceUnit = (value: DistanceEnum) => { if(this._DistanceUnit !== value) { this._DistanceUnit = value; this._Dispatcher.raise(this._Events.distanceUnitChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.Distance ]); } } getHeightUnit = () : HeightEnum => { return this._HeightUnit; } setHeightUnit = (value: HeightEnum) => { if(this._HeightUnit !== value) { this._HeightUnit = value; this._Dispatcher.raise(this._Events.heightUnitChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.Height ]); } } getSpeedUnit = () : SpeedEnum => { return this._SpeedUnit; } setSpeedUnit = (value: SpeedEnum) => { if(this._SpeedUnit !== value) { this._SpeedUnit = value; this._Dispatcher.raise(this._Events.speedUnitChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.Speed ]); } } getPressureUnit = () : PressureEnum => { return this._PressureUnit; } setPressureUnit = (value: PressureEnum) => { if(this._PressureUnit !== value) { this._PressureUnit = value; this._Dispatcher.raise(this._Events.pressureUnitChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.Pressure ]); } } getShowVerticalSpeedPerSecond = () : boolean => { return this._ShowVerticalSpeedPerSecond; } setShowVerticalSpeedPerSecond = (value: boolean) => { if(this._ShowVerticalSpeedPerSecond !== value) { this._ShowVerticalSpeedPerSecond = value; this._Dispatcher.raise(this._Events.showVsiInSecondsChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.VsiSeconds ]); } } getShowAltitudeType = () : boolean => { return this._ShowAltitudeType; } setShowAltitudeType = (value: boolean) => { if(this._ShowAltitudeType !== value) { this._ShowAltitudeType = value; this._Dispatcher.raise(this._Events.showAltitudeTypeChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.Height ]); } } getShowVerticalSpeedType = () : boolean => { return this._ShowVerticalSpeedType; } setShowVerticalSpeedType = (value: boolean) => { if(this._ShowVerticalSpeedType !== value) { this._ShowVerticalSpeedType = value; this._Dispatcher.raise(this._Events.showVerticalSpeedTypeChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.Height ]); } } getShowSpeedType = () : boolean => { return this._ShowSpeedType; } setShowSpeedType = (value: boolean) => { if(this._ShowSpeedType !== value) { this._ShowSpeedType = value; this._Dispatcher.raise(this._Events.showSpeedTypeChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.Speed ]); } } getShowTrackType = () : boolean => { return this._ShowTrackType; } setShowTrackType = (value: boolean) => { if(this._ShowTrackType !== value) { this._ShowTrackType = value; this._Dispatcher.raise(this._Events.showTrackTypeChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.Angle ]); } } getUsePressureAltitude = () : boolean => { return this._UsePressureAltitude; } setUsePressureAltitude = (value: boolean) => { if(this._UsePressureAltitude !== value) { this._UsePressureAltitude = value; this._Dispatcher.raise(this._Events.usePressureAltitudeChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.Height ]); } } getFlightLevelTransitionAltitude = () : number => { return this._FlightLevelTransitionAltitude; } setFlightLevelTransitionAltitude = (value: number) => { if(this._FlightLevelTransitionAltitude !== value) { this._FlightLevelTransitionAltitude = value; this._Dispatcher.raise(this._Events.flAltitudeChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.FLTransitionAltitude ]); } } getFlightLevelTransitionHeightUnit = () : HeightEnum => { return this._FlightLevelTransitionHeightUnit; } setFlightLevelTransitionHeightUnit = (value: HeightEnum) => { if(this._FlightLevelTransitionHeightUnit !== value) { this._FlightLevelTransitionHeightUnit = value; this._Dispatcher.raise(this._Events.flTransUnitChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.FLTransitionHeightUnit ]); } } getFlightLevelHeightUnit = () : HeightEnum => { return this._FlightLevelHeightUnit; } setFlightLevelHeightUnit = (value: HeightEnum) => { if(this._FlightLevelHeightUnit !== value) { this._FlightLevelHeightUnit = value; this._Dispatcher.raise(this._Events.flHeightUnitChanged); this._Dispatcher.raise(this._Events.unitChanged, [ VRS.DisplayUnitDependency.FLHeightUnit ]); } } /** * Returns an array of every possible altitude unit value and their text keys. */ static getAltitudeUnitValues() : ValueText[] { return [ new VRS.ValueText({ value: VRS.Height.Feet, textKey: 'Feet' }), new VRS.ValueText({ value: VRS.Height.Metre, textKey: 'Metres' }) ]; } /** * Returns an array of every possible distance unit value and their text keys. */ static getDistanceUnitValues() : ValueText[] { return [ new VRS.ValueText({ value: VRS.Distance.Kilometre, textKey: 'Kilometres' }), new VRS.ValueText({ value: VRS.Distance.NauticalMile, textKey: 'NauticalMiles' }), new VRS.ValueText({ value: VRS.Distance.StatuteMile, textKey: 'StatuteMiles' }) ]; } /** * Returns an array of every possible speed unit value and their text keys. */ static getSpeedUnitValues() : ValueText[] { return [ new VRS.ValueText({ value: VRS.Speed.KilometresPerHour, textKey: 'KilometresPerHour' }), new VRS.ValueText({ value: VRS.Speed.Knots, textKey: 'Knots' }), new VRS.ValueText({ value: VRS.Speed.MilesPerHour, textKey: 'MilesPerHour' }) ]; } /** * Returns an array of every possible pressure unit value and their text keys. */ static getPressureUnitValues() : ValueText[] { return [ new VRS.ValueText({ value: VRS.Pressure.InHg, textKey: 'InHgDescription' }), new VRS.ValueText({ value: VRS.Pressure.Millibar, textKey: 'MillibarDescription' }), new VRS.ValueText({ value: VRS.Pressure.MmHg, textKey: 'MmHgDescription' }) ]; } hookDistanceUnitChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.distanceUnitChanged, callback, forceThis); } hookHeightUnitChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.heightUnitChanged, callback, forceThis); } hookSpeedUnitChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.speedUnitChanged, callback, forceThis); } hookPressureUnitChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.pressureUnitChanged, callback, forceThis); } hookShowVerticalSpeedPerSecondChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.showVsiInSecondsChanged, callback, forceThis); } hookShowAltitudeTypeChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.showAltitudeTypeChanged, callback, forceThis); } hookShowVerticalSpeedTypeChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.showVerticalSpeedTypeChanged, callback, forceThis); } hookShowSpeedTypeChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.showSpeedTypeChanged, callback, forceThis); } hookShowTrackTypeChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.showTrackTypeChanged, callback, forceThis); } hookFlightLevelTransitionAltitudeChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.flAltitudeChanged, callback, forceThis); } hookFlightLevelTransitionHeightUnitChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.flTransUnitChanged, callback, forceThis); } hookFlightLevelHeightUnitChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.flHeightUnitChanged, callback, forceThis); } hookUsePressureAltitudeChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.usePressureAltitudeChanged, callback, forceThis); } /** * Raised when any of the units have been changed. */ hookUnitChanged = (callback: (dependency?: DisplayUnitDependencyEnum) => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.unitChanged, callback, forceThis); } unhook = (hookResult: IEventHandle) => { this._Dispatcher.unhook(hookResult); } /** * Creates the option pane for the configuration of display units. */ createOptionPane = (displayOrder: number) : OptionPane => { var self = this; var pane = new VRS.OptionPane({ name: 'vrsUnitDisplayPreferences_' + this._Name, titleKey: 'PaneUnits', displayOrder: displayOrder }); var distanceUnitValues = UnitDisplayPreferences.getDistanceUnitValues(); var altitudeUnitValues = UnitDisplayPreferences.getAltitudeUnitValues(); var speedUnitValues = UnitDisplayPreferences.getSpeedUnitValues(); var pressureUnitValues = UnitDisplayPreferences.getPressureUnitValues(); if(VRS.globalOptions.unitDisplayAllowConfiguration) { pane.addField(new VRS.OptionFieldCheckBox({ name: 'showVsiInSeconds', labelKey: 'ShowVsiInSeconds', getValue: this.getShowVerticalSpeedPerSecond, setValue: this.setShowVerticalSpeedPerSecond, saveState: this.saveState })); pane.addField(new VRS.OptionFieldCheckBox({ name: 'showAltitudeType', labelKey: 'ShowAltitudeType', getValue: this.getShowAltitudeType, setValue: this.setShowAltitudeType, saveState: this.saveState })); pane.addField(new VRS.OptionFieldCheckBox({ name: 'showVerticalSpeedType', labelKey: 'ShowVerticalSpeedType', getValue: this.getShowVerticalSpeedType, setValue: this.setShowVerticalSpeedType, saveState: this.saveState })); pane.addField(new VRS.OptionFieldCheckBox({ name: 'showSpeedType', labelKey: 'ShowSpeedType', getValue: this.getShowSpeedType, setValue: this.setShowSpeedType, saveState: this.saveState })); pane.addField(new VRS.OptionFieldCheckBox({ name: 'showTrackType', labelKey: 'ShowTrackType', getValue: this.getShowTrackType, setValue: this.setShowTrackType, saveState: this.saveState })); pane.addField(new VRS.OptionFieldCheckBox({ name: 'usePressureAltitude', labelKey: 'UsePressureAltitude', getValue: this.getUsePressureAltitude, setValue: this.setUsePressureAltitude, saveState: this.saveState })); pane.addField(new VRS.OptionFieldComboBox({ name: 'distanceUnit', labelKey: 'Distances', getValue: this.getDistanceUnit, setValue: this.setDistanceUnit, saveState: this.saveState, values: distanceUnitValues })); pane.addField(new VRS.OptionFieldComboBox({ name: 'heightUnit', labelKey: 'Heights', getValue: this.getHeightUnit, setValue: this.setHeightUnit, saveState: this.saveState, values: altitudeUnitValues })); pane.addField(new VRS.OptionFieldComboBox({ name: 'speedUnit', labelKey: 'Speeds', getValue: this.getSpeedUnit, setValue: this.setSpeedUnit, saveState: this.saveState, values: speedUnitValues })); pane.addField(new VRS.OptionFieldComboBox({ name: 'pressureUnit', labelKey: 'Pressures', getValue: this.getPressureUnit, setValue: this.setPressureUnit, saveState: this.saveState, values: pressureUnitValues })); pane.addField(new VRS.OptionFieldNumeric({ name: 'flTransAltitude', labelKey: 'FlightLevelTransitionAltitude', getValue: this.getFlightLevelTransitionAltitude, setValue: this.setFlightLevelTransitionAltitude, saveState: this.saveState, inputWidth: VRS.InputWidth.SixChar, min: -10000, max: 99900, decimals: 0, step: 100, keepWithNext: true })); pane.addField(new VRS.OptionFieldComboBox({ name: 'flTransUnit', getValue: this.getFlightLevelTransitionHeightUnit, setValue: this.setFlightLevelTransitionHeightUnit, saveState: this.saveState, values: altitudeUnitValues })); pane.addField(new VRS.OptionFieldComboBox({ name: 'flHeightUnit', labelKey: 'FlightLevelHeightUnit', getValue: this.getFlightLevelHeightUnit, setValue: this.setFlightLevelHeightUnit, saveState: this.saveState, values: altitudeUnitValues })); } return pane; } /** * Stores the current state of the object. */ saveState = () => { VRS.configStorage.saveWithoutPrefix(this.persistenceKey(), this.createSettings()); } /** * Returns the previously stored state of the object or the current state if no state was previously saved. */ loadState = () : UnitDisplayPreferences_SaveState => { var savedSettings = VRS.configStorage.loadWithoutPrefix(this.persistenceKey(), {}); return $.extend(this.createSettings(), savedSettings); } /** * Applies a previously stored state to the object. */ applyState = (settings: UnitDisplayPreferences_SaveState) => { this.setDistanceUnit(settings.distanceUnit); this.setHeightUnit(settings.heightUnit); this.setSpeedUnit(settings.speedUnit); this.setPressureUnit(settings.pressureUnit); this.setShowVerticalSpeedPerSecond(settings.vsiPerSecond); this.setFlightLevelTransitionAltitude(settings.flTransitionAlt); this.setFlightLevelTransitionHeightUnit(settings.flTransitionUnit); this.setFlightLevelHeightUnit(settings.flHeightUnit); this.setShowAltitudeType(settings.showAltType); this.setShowVerticalSpeedType(settings.showVsiType); this.setShowSpeedType(settings.showSpeedType); this.setShowTrackType(settings.showTrackType); this.setUsePressureAltitude(settings.usePressureAltitude); } /** * Loads and applies a previously stored state. */ loadAndApplyState = () => { this.applyState(this.loadState()); } /** * Returns the key used to store the state. */ private persistenceKey = () : string => { return 'unitDisplayPreferences-' + this.getName(); } /** * Returns the current state of the object. */ private createSettings = () : UnitDisplayPreferences_SaveState => { return { distanceUnit: this.getDistanceUnit(), heightUnit: this.getHeightUnit(), speedUnit: this.getSpeedUnit(), pressureUnit: this.getPressureUnit(), vsiPerSecond: this.getShowVerticalSpeedPerSecond(), flTransitionAlt: this.getFlightLevelTransitionAltitude(), flTransitionUnit: this.getFlightLevelTransitionHeightUnit(), flHeightUnit: this.getFlightLevelHeightUnit(), showAltType: this.getShowAltitudeType(), showVsiType: this.getShowVerticalSpeedType(), showSpeedType: this.getShowSpeedType(), showTrackType: this.getShowTrackType(), usePressureAltitude: this.getUsePressureAltitude() }; } } }
the_stack
import {Observable} from "rxjs/Observable"; import * as _ from "underscore"; import {Subject} from "rxjs/Subject"; import {SaveFeedResponse} from "../../../../feeds/define-feed-ng2/model/save-feed-response.model"; import {Feed} from "../../../../model/feed/feed.model"; import {FeedDataTransformation} from "../../../../model/feed-data-transformation"; import {KyloObject} from "../../../../../../lib/common/common.model"; export namespace FlowChart { export class FlowchartModelBase { // Width of a node. static defaultNodeWidth = 250; // Amount of space reserved for displaying the node's name. static nodeNameHeight = 75; // Height of a connector in a node. static connectorHeight = 35; static attributeHeight = 25; static CONNECTOR_LOCATION = {TOP: "TOP", BOTTOM: "BOTTOM", LEFT: "LEFT", RIGHT: "RIGHT"}; static connectorRadius = 5; static nextConnectorID = 1 public static maxHeight = -1; // Compute the Y coordinate of a connector, given its index. /** * @Deprecated * @param connectorIndex * @returns {number} */ static computeConnectorY(connectorIndex: any) { return FlowchartModelBase.nodeNameHeight + (connectorIndex * FlowchartModelBase.connectorHeight); } // Compute the position of a connector in the graph. /** * @Deprecated * @param node * @param connectorIndex * @param inputConnector * @returns {{x: *, y: *}} */ static computeConnectorPosOld(node: any, connectorIndex: any, inputConnector: any){ return { x: node.x() + (inputConnector ? 0 : node.width ? node.width() : FlowchartModelBase.defaultNodeWidth), y: node.y() + FlowchartModelBase.computeConnectorY(connectorIndex), }; } static computeConnectorPos(node: any, connector: any){ var x: any = 0; if (connector.location() == FlowchartModelBase.CONNECTOR_LOCATION.LEFT || connector.location() == FlowchartModelBase.CONNECTOR_LOCATION.RIGHT) { x = node.x() + (connector.location() == FlowchartModelBase.CONNECTOR_LOCATION.LEFT ? 0 : node.width ? node.width() : FlowchartModelBase.defaultNodeWidth); } else { //center the top and bottom x = node.x() + (node.width ? node.width() : FlowchartModelBase.defaultNodeWidth) / 2; } var y = 0; if (connector.location() == FlowchartModelBase.CONNECTOR_LOCATION.LEFT || connector.location() == FlowchartModelBase.CONNECTOR_LOCATION.RIGHT) { y = node.y() + (node.height()) / 2 } else { y = node.y() + (connector.location() == FlowchartModelBase.CONNECTOR_LOCATION.TOP ? 0 : node.height()) } return { x: x, y: y }; } // Create view model for a list of data models. static createConnectorsViewModel(connectorDataModels: any, x: any, parentNode: any){ var viewModels: any = []; if (connectorDataModels) { for (var i = 0; i < connectorDataModels.length; ++i) { var connectorViewModel = new FlowChart.ConnectorViewModel(connectorDataModels[i], x, FlowchartModelBase.computeConnectorY(i), parentNode); viewModels.push(connectorViewModel); } } return viewModels; } static createConnectorViewModel(connectorDataModel: any, x: any, y: any, parentNode: any){ var connectorViewModel: any = null if (connectorDataModel) { connectorViewModel = new FlowChart.ConnectorViewModel(connectorDataModel, x, y, parentNode); } return connectorViewModel; } // // Helper function. // static computeConnectionTangentOffset(pt1: any, pt2: any){ return (pt2.x - pt1.x) / 2; } // // Compute the tangent for the bezier curve. // static computeConnectionSourceTangentX(pt1: any, pt2: any){ return pt1.x + FlowchartModelBase.computeConnectionTangentOffset(pt1, pt2); } // // Compute the tangent for the bezier curve. // static computeConnectionSourceTangentY(pt1: any, pt2: any) { return pt1.y; } // // Compute the tangent for the bezier curve. // static computeConnectionSourceTangent(pt1: any, pt2: any){ return { x: FlowchartModelBase.computeConnectionSourceTangentX(pt1, pt2), y: FlowchartModelBase.computeConnectionSourceTangentY(pt1, pt2), }; } // // Compute the tangent for the bezier curve. // static computeConnectionDestTangentX(pt1: any, pt2: any) { return pt2.x - FlowchartModelBase.computeConnectionTangentOffset(pt1, pt2); } // // Compute the tangent for the bezier curve. // static computeConnectionDestTangentY(pt1: any, pt2: any){ return pt2.y; } // // Compute the tangent for the bezier curve. // static computeConnectionDestTangent(pt1: any, pt2: any){ return { x: FlowchartModelBase.computeConnectionDestTangentX(pt1, pt2), y: FlowchartModelBase.computeConnectionDestTangentY(pt1, pt2), }; } } export interface ConnectionCallbackResponse { connectionViewModel: ConnectionViewModel; connectionDataModel:any; src:NodeViewModel; dest:NodeViewModel; inputConnector?:ConnectorViewModel; outputConnector?:ConnectorViewModel; } // View model for a connector. export class ConnectorViewModel extends FlowchartModelBase { data : any; _parentNode : any; _x : any; _y : any; TRIANGLE_SIZE : number = 30; constructor(connectorDataModel: any, x: any, y: any, parentNode: any) { super(); this.data = connectorDataModel; this._parentNode = parentNode; this._x = x; this._y = y; this.TRIANGLE_SIZE = 30; } // The name of the connector. name () { return this.data.name; } trianglePoints() { var start: any = ""; var end: any = ""; var point: any = ""; var point2: any = ""; if (this.location() == ConnectorViewModel.CONNECTOR_LOCATION.BOTTOM) { start = this.x() - this.TRIANGLE_SIZE / 2 + "," + this.y(); end = this.x() + this.TRIANGLE_SIZE / 2 + "," + this.y(); point = this.x() + "," + (this.y() + this.TRIANGLE_SIZE); //point2 = this.x()+","+(this.y()+this.TRIANGLE_SIZE); } else if (this.location() == ConnectorViewModel.CONNECTOR_LOCATION.TOP) { start = this.x() - this.TRIANGLE_SIZE / 2 + "," + this.y(); end = this.x() + this.TRIANGLE_SIZE / 2 + "," + this.y(); point = this.x() + "," + (this.y() - this.TRIANGLE_SIZE); } if (this.location() == ConnectorViewModel.CONNECTOR_LOCATION.LEFT) { start = this.x() + "," + (this.y() - this.TRIANGLE_SIZE / 2); end = this.x() + "," + (this.y() + this.TRIANGLE_SIZE / 2); point = (this.x() - this.TRIANGLE_SIZE) + "," + this.y(); } else if (this.location() == ConnectorViewModel.CONNECTOR_LOCATION.RIGHT) { start = this.x() + "," + (this.y() - this.TRIANGLE_SIZE / 2); end = this.x() + "," + (this.y() + this.TRIANGLE_SIZE / 2); point = (this.x() + this.TRIANGLE_SIZE) + "," + this.y(); } return start + " " + end + " " + point; } location() { return this.data.location; } id(){ return this.data.id; } // X coordinate of the connector. x(){ return this._x; }; // // Y coordinate of the connector. // y(){ return this._y ; } // // The parent node that the connector is attached to. // parentNode(){ return this._parentNode; } }; // // View model for a node. // export class NodeViewModel extends FlowchartModelBase{ data : any; connectors : FlowChart.ConnectorViewModel[] = []; leftConnectors : any[] = []; rightConnectors : any[] = []; bottomConnectors : any[] = []; topConnectors : any[] = []; // Set to true when the node is selected. _selected : boolean = false; inputConnectors:any; outputConnectors:any; constructor(nodeDataModel: any) { super(); this.data = nodeDataModel; // set the default width value of the node if (!this.data.width || this.data.width < 0) { this.data.width = NodeViewModel.defaultNodeWidth; } this.createConnectors(); } /** * generate the id for the connector * @param {number} index * @return {string} * @private */ private _newId(index:number){ return this.data.id+"|"+index; } createConnectors(){ var connectors: any = this.data.connectors; var leftConnector: any = connectors.left; if (leftConnector) { leftConnector.location = NodeViewModel.CONNECTOR_LOCATION.LEFT; leftConnector.id = this._newId(0);//NodeViewModel.nextConnectorID++; var connectorViewModel = NodeViewModel.createConnectorViewModel(leftConnector, 0, this.height() / 2, this); this.leftConnectors.push(connectorViewModel); this.connectors.push(connectorViewModel); } var rightConnector = connectors.right; if (rightConnector) { rightConnector.location = NodeViewModel.CONNECTOR_LOCATION.RIGHT; rightConnector.id = this._newId(1);//NodeViewModel.nextConnectorID++; var connectorViewModel = NodeViewModel.createConnectorViewModel(rightConnector, this.data.width, this.height() / 2, this); this.rightConnectors.push(connectorViewModel); this.connectors.push(connectorViewModel); } var topConnector = connectors.top; if (topConnector) { topConnector.location = NodeViewModel.CONNECTOR_LOCATION.TOP; topConnector.id = this._newId(2); //NodeViewModel.nextConnectorID++; var connectorViewModel = NodeViewModel.createConnectorViewModel(topConnector, this.data.width / 2, 0, this); this.topConnectors.push(connectorViewModel); this.connectors.push(connectorViewModel); } var bottomConnector = connectors.bottom; if (bottomConnector) { bottomConnector.location = NodeViewModel.CONNECTOR_LOCATION.BOTTOM; bottomConnector.id = this._newId(3); //NodeViewModel.nextConnectorID++; var connectorViewModel = NodeViewModel.createConnectorViewModel(bottomConnector, this.data.width / 2, this.height(), this); this.bottomConnectors.push(connectorViewModel); this.connectors.push(connectorViewModel); } } // Name of the node. name(){ return this.data.name || ""; } // X coordinate of the node. x = () => { return this.data.x; } // Y coordinate of the node. y(){ return this.data.y; } // // Width of the node. // width(){ return this.data.width; } // // Height of the node. // height() { let h = this.data.height; if (h) { // } else if (this.data.nodeAttributes && this.data.nodeAttributes.attributes) { h = 95 + NodeViewModel.attributeHeight * this.data.nodeAttributes.attributes.length; } else { var numConnectors = Math.max( this.inputConnectors.length, this.outputConnectors.length); h = NodeViewModel.computeConnectorY(numConnectors); } return FlowchartModelBase.maxHeight == -1 ? h : (h < FlowchartModelBase.maxHeight ? h : FlowchartModelBase.maxHeight); } // Select the node. select(){ this._selected = true; } // Deselect the node. deselect(){ this._selected = false; } // // Toggle the selection state of the node. // toggleSelected(){ this._selected = !this._selected; } // // Returns true if the node is selected. // selected() { return this._selected; } // // Internal function to add a connector. _addConnector(connectorDataModel: any, x: any, connectorsDataModel: any, connectorsViewModel: any){ var connectorViewModel: any = new FlowChart.ConnectorViewModel(connectorDataModel, x, NodeViewModel.computeConnectorY(connectorsViewModel.length), this); connectorsDataModel.push(connectorDataModel); // Add to node's view model. connectorsViewModel.push(connectorViewModel); } // // Add an input connector to the node. //TODO change to AddTop, addLeft, addRight,..etc // addInputConnector(connectorDataModel: any){ if (!this.data.inputConnectors) { this.data.inputConnectors = []; } this._addConnector(connectorDataModel, 0, this.data.inputConnectors, this.inputConnectors); } // // Add an ouput connector to the node. // addOutputConnector(connectorDataModel: any){ if (!this.data.outputConnectors) { this.data.outputConnectors = []; } this._addConnector(connectorDataModel, this.data.width, this.data.outputConnectors, this.outputConnectors); } getAllConnectors(){ return this.connectors; } } // // View model for a connection. // export class ConnectionViewModel extends FlowchartModelBase{ data : any; source : any; dest : any; _selected : boolean; constructor(connectionDataModel: any, sourceConnector: any = undefined, destConnector: any = undefined) { super(); this.data = connectionDataModel; this.source = sourceConnector; this.dest = destConnector; // Set to true when the connection is selected. this._selected = false; } name() { return this.data.name || ""; } sourceCoordX() { return this.source.parentNode().x() + this.source.x(); } sourceCoordY(){ return this.source.parentNode().y() + this.source.y(); }; edit(){ this.data.edit(this); } sourceCoord() { return { x: this.sourceCoordX(), y: this.sourceCoordY() }; } sourceTangentX(){ return ConnectionViewModel.computeConnectionSourceTangentX(this.sourceCoord(), this.destCoord()); } sourceTangentY(){ return ConnectionViewModel.computeConnectionSourceTangentY(this.sourceCoord(), this.destCoord()); } destCoordX(){ return this.dest.parentNode().x() + this.dest.x(); } destCoordY(){ return this.dest.parentNode().y() + this.dest.y(); } destCoord(){ return { x: this.destCoordX(), y: this.destCoordY() }; } destTangentX(){ return ConnectionViewModel.computeConnectionDestTangentX(this.sourceCoord(), this.destCoord()); } destTangentY() { return ConnectionViewModel.computeConnectionDestTangentY(this.sourceCoord(), this.destCoord()); } middleX(scale: any){ if (typeof (scale) == "undefined") scale = 0.5; return this.sourceCoordX() * (1 - scale) + this.destCoordX() * scale; } middleY(scale: any){ if (typeof (scale) == "undefined") scale = 0.5; return this.sourceCoordY() * (1 - scale) + this.destCoordY() * scale; } // // Select the connection. // select(){ this._selected = true; } // // Deselect the connection. // deselect(){ this._selected = false; } // // Toggle the selection state of the connection. // toggleSelected(){ this._selected = !this._selected; } // // Returns true if the connection is selected. // selected(){ return this._selected; } } export class ChartDataModel implements KyloObject{ nodes:any[]; connections:any[]; public static OBJECT_TYPE:string = 'ChartDataModel' public objectType:string = ChartDataModel.OBJECT_TYPE; public constructor(init?: Partial<ChartDataModel>) { Object.assign(this, init); if(this.nodes == undefined){ this.nodes = [] } if(this.connections == undefined){ this.connections = [] } } } /** * View model for the chart. * * @public * @constructor * @param {Object} chartDataModel the data model for the chart */ export class ChartViewModel extends FlowchartModelBase{ data: ChartDataModel; nodes: NodeViewModel[] = []; connections: ConnectionViewModel[] = []; connectionMap: {[key: string]: ConnectionViewModel} = {} /** * Allow other components to listen for changes * */ public onEditConnection$: Observable<ConnectionCallbackResponse>; /** * The datasets subject for listening */ private onEditConnectionSubject: Subject<ConnectionCallbackResponse>; /** * Allow other components to listen for changes * */ public onCreateConnection$: Observable<ConnectionCallbackResponse>; /** * The datasets subject for listening */ private onCreateConnectionSubject: Subject<ConnectionCallbackResponse>; /** * Allow other components to listen for changes * */ public onDeleteSelected$: Observable<any>; /** * The datasets subject for listening */ private onDeleteSelectedSubject: Subject<any>; constructor(private chartDataModel: ChartDataModel) { super(); // Reference to the underlying data. this.data = chartDataModel; // Create a view-model for nodes. this.nodes = this._createNodesViewModel(this.data.nodes); // Create a view-model for connections. this.connections = this._createConnectionsViewModel(this.data.connections); this.onEditConnectionSubject = new Subject<ConnectionCallbackResponse>(); this.onEditConnection$ = this.onEditConnectionSubject.asObservable(); this.onCreateConnectionSubject = new Subject<ConnectionCallbackResponse>(); this.onCreateConnection$ = this.onCreateConnectionSubject.asObservable(); this.onDeleteSelectedSubject = new Subject<any>(); this.onDeleteSelected$ = this.onDeleteSelectedSubject.asObservable(); }; // // Create a view model for a new connection. // createNewConnection(startConnector: any, endConnector: any){ var connectionsDataModel: any = this.data.connections; if (!connectionsDataModel) { connectionsDataModel = this.data.connections = []; } var connectionsViewModel: any = this.connections; if (!connectionsViewModel) { connectionsViewModel = this.connections = []; } var startNode: any = startConnector.parentNode(); var startNodeConnectors: any = startNode.getAllConnectors(); var startConnectorIndex: any = startNodeConnectors.indexOf(startConnector); var startConnectorType: any = 'input'; if (startConnectorIndex == -1) { throw new Error("Failed to find source connector within either inputConnectors or outputConnectors of source node."); } var endNode: any = endConnector.parentNode(); var endNodeConnectors: any = endNode.getAllConnectors(); var endConnectorIndex: any = endNodeConnectors.indexOf(endConnector); var endConnectorType: any = 'input'; if (endConnectorIndex == -1) { throw new Error("Failed to find dest connector within inputConnectors or outputConnectors of dest node."); } if (startNode == endNode) { throw new Error("Failed to create connection. Cannot link a node with itthis.") } var startNode: any = { nodeID: startNode.data.id, connectorIndex: startConnectorIndex, connectorID: startConnector.data.id } var endNode: any = { nodeID: endNode.data.id, connectorIndex: endConnectorIndex, connectorId: endConnector.data.id } /* var connectionDataModel: any = { id:_.uniqueId('connection-'), source: startConnectorType == 'output' ? startNode : endNode, dest: startConnectorType == 'output' ? endNode : startNode }; */ var connectionDataModel: any = { id:_.uniqueId('connection-'), source: startNode, dest: endNode }; connectionsDataModel.push(connectionDataModel); // var outputConnector: any = startConnectorType == 'output' ? startConnector : endConnector; // var inputConnector: any = startConnectorType == 'output' ? endConnector : startConnector; var src: any = this.findNode(connectionDataModel.source.nodeID); var dest: any = this.findNode(connectionDataModel.dest.nodeID); //connectionDataModel.name = src.name()+" - "+dest.name(); connectionDataModel.joinKeys = {}; var connectionViewModel = new FlowChart.ConnectionViewModel(connectionDataModel, startConnector, endConnector); connectionDataModel.edit = (viewModel: any) => { this.onEditConnectionSubject.next({connectionViewModel:connectionViewModel, connectionDataModel:connectionDataModel, src:src, dest:dest}) } connectionsViewModel.push(connectionViewModel); this.connectionMap[connectionDataModel.id] = connectionViewModel; this.onCreateConnectionSubject.next({connectionViewModel:connectionViewModel, connectionDataModel:connectionDataModel, src:src, dest:dest, inputConnector:startConnector, outputConnector:endConnector}) } // // Add a node to the view model. // addNode(nodeDataModel: any){ if (!this.data.nodes) { this.data.nodes = []; } // // Update the data model. // this.data.nodes.push(nodeDataModel); // // Update the view model. // this.nodes.push(new NodeViewModel(nodeDataModel)); } // // Select all nodes and connections in the chart. // selectAll(){ var nodes = this.nodes; for (var i = 0; i < nodes.length; ++i) { var node = nodes[i]; node.select(); } var connections = this.connections; for (var i = 0; i < connections.length; ++i) { var connection = connections[i]; connection.select(); } } // // Deselect all nodes and connections in the chart. // deselectAll(){ var nodes = this.nodes; for (var i = 0; i < nodes.length; ++i) { var node = nodes[i]; node.deselect(); } var connections = this.connections; for (var i = 0; i < connections.length; ++i) { var connection = connections[i]; connection.deselect(); } } // // Update the location of the node and its connectors. // updateSelectedNodesLocation(deltaX: any, deltaY: any){ var selectedNodes: any = this.getSelectedNodes(); for (var i = 0; i < selectedNodes.length; ++i) { var node = selectedNodes[i]; node.data.x += deltaX; node.data.y += deltaY; } } // Handle mouse click on a particular node. // handleNodeClicked(node: any, ctrlKey: any){ if (ctrlKey) { node.toggleSelected(); } else { this.deselectAll(); node.select(); } // Move node to the end of the list so it is rendered after all the other. // This is the way Z-order is done in SVG. var nodeIndex = this.nodes.indexOf(node); if (nodeIndex == -1) { throw new Error("Failed to find node in view model!"); } this.nodes.splice(nodeIndex, 1); this.nodes.push(node); } // // Handle mouse down on a connection. // handleConnectionMouseDown(connection: ConnectionViewModel, ctrlKey: any){ if (ctrlKey) { connection.toggleSelected(); } else { this.deselectAll(); connection.select(); } } // // Delete all nodes and connections that are selected. // deleteSelected(){ var newNodeViewModels: any = []; var newNodeDataModels: any = []; var deletedNodeIds: any = []; // Sort nodes into: // nodes to keep and // nodes to delete. for (var nodeIndex = 0; nodeIndex < this.nodes.length; ++nodeIndex) { var node: FlowChart.NodeViewModel = this.nodes[nodeIndex]; if (!node.selected()) { // Only retain non-selected nodes. newNodeViewModels.push(node); newNodeDataModels.push(node.data); } else { // Keep track of nodes that were deleted, so their connections can also // be deleted. deletedNodeIds.push(node.data.id); } } var newConnectionViewModels: any = []; var newConnectionDataModels: any = []; // // Remove connections that are selected. // Also remove connections for nodes that have been deleted. // for (var connectionIndex = 0; connectionIndex < this.connections.length; ++connectionIndex) { var connection: any = this.connections[connectionIndex]; if (!connection.selected() && deletedNodeIds.indexOf(connection.data.source.nodeID) === -1 && deletedNodeIds.indexOf(connection.data.dest.nodeID) === -1) { // // The nodes this connection is attached to, where not deleted, // so keep the connection. // newConnectionViewModels.push(connection); newConnectionDataModels.push(connection.data); } else { //deleted delete this.connectionMap[connection.data.id]; } } // // Update nodes and connections. // this.nodes = newNodeViewModels; this.data.nodes = newNodeDataModels; this.connections = newConnectionViewModels; this.data.connections = newConnectionDataModels; this.onDeleteSelectedSubject.next(); } // // Select nodes and connections that fall within the selection rect. // applySelectionRect(selectionRect: any){ this.deselectAll(); for (var i = 0; i < this.nodes.length; ++i) { var node = this.nodes[i]; if (node.x() >= selectionRect.x && node.y() >= selectionRect.y && node.x() + node.width() <= selectionRect.x + selectionRect.width && node.y() + node.height() <= selectionRect.y + selectionRect.height) { // Select nodes that are within the selection rect. node.select(); } } for (var i = 0; i < this.connections.length; ++i) { var connection: any = this.connections[i]; if (connection.source.parentNode().selected() && connection.dest.parentNode().selected()) { // Select the connection if both its parent nodes are selected. connection.select(); } } } // Get the array of nodes that are currently selected. getSelectedNodes(){ var selectedNodes: any = []; for (var i = 0; i < this.nodes.length; ++i) { var node = this.nodes[i]; if (node.selected()) { selectedNodes.push(node); } } return selectedNodes; } // // Get the array of connections that are currently selected. // getSelectedConnections(){ var selectedConnections: any = []; for (var i = 0; i < this.connections.length; ++i) { var connection: any = this.connections[i]; if (connection.selected()) { selectedConnections.push(connection); } } return selectedConnections; } findConnectorById(connectorId:string){ const [nodeId, connectorIndex] = connectorId.split("|"); return this.findConnector(nodeId, connectorIndex); } findConnection(connectionId:string){ return this.connectionMap[connectionId]; } // // Find a specific node within the chart. // findNode(nodeID: any){ for (var i = 0; i < this.nodes.length; ++i) { var node = this.nodes[i]; if (node.data.id == nodeID) { return node; } } throw new Error("Failed to find node " + nodeID); } findConnector(nodeID: any, connectorIndex: any){ var node = this.findNode(nodeID); if (!node.connectors || node.connectors.length <= connectorIndex) { throw new Error("Node " + nodeID + " has invalid input connectors."); } return node.connectors[connectorIndex]; } // // Find a specific input connector within the chart. // findInputConnector(nodeID: any, connectorIndex: any){ var node: any = this.findNode(nodeID); if (!node.inputConnectors || node.inputConnectors.length <= connectorIndex) { throw new Error("Node " + nodeID + " has invalid input connectors."); } return node.inputConnectors[connectorIndex]; } // // Find a specific output connector within the chart. // findOutputConnector(nodeID: any, connectorIndex: any){ var node: any = this.findNode(nodeID); if (!node.outputConnectors || node.outputConnectors.length <= connectorIndex) { throw new Error("Node " + nodeID + " has invalid output connectors."); } return node.outputConnectors[connectorIndex]; } // // Create a view model for connection from the data model. // private _createConnectionViewModel(connectionDataModel: any) : ConnectionViewModel { // Create connection view var sourceConnector: any = this.findConnector(connectionDataModel.source.nodeID, connectionDataModel.source.connectorIndex); var destConnector: any = this.findConnector(connectionDataModel.dest.nodeID, connectionDataModel.dest.connectorIndex); var connectionViewModel: any = new FlowChart.ConnectionViewModel(connectionDataModel, sourceConnector, destConnector); // Set callback function for editing the connection var source = this.findNode(connectionDataModel.source.nodeID); var dest = this.findNode(connectionDataModel.dest.nodeID); connectionDataModel.edit = () => { this.onEditConnectionSubject.next({connectionViewModel:connectionViewModel, connectionDataModel:connectionDataModel, src:source, dest:dest}); }; // Return connection view return connectionViewModel; } // // Wrap the connections data-model in a view-model. // private _createConnectionsViewModel(connectionsDataModel: any) { var connectionsViewModel: any = []; if (connectionsDataModel) { for (var i = 0; i < connectionsDataModel.length; ++i) { //ensure the id exists let connectionDataModel = connectionsDataModel[i]; if(connectionDataModel.id == undefined) { connectionDataModel.id = _.uniqueId("connection-"); } let connectionViewModel = this._createConnectionViewModel(connectionDataModel); connectionsViewModel.push(connectionViewModel); this.connectionMap[connectionViewModel.data.id] = connectionViewModel; } } return connectionsViewModel; }; // // Wrap the nodes data-model in a view-model. // private _createNodesViewModel(nodesDataModel: any): NodeViewModel[] { const nodesViewModel = []; if (nodesDataModel) { for (let i = 0; i < nodesDataModel.length; ++i) { nodesViewModel.push(new NodeViewModel(nodesDataModel[i])); } } return nodesViewModel; } } }
the_stack
import { query as q } from 'faunadb'; import { MethodDispatch, Query } from '~/factory/constructors/method'; import { ResultData } from '~/factory/constructors/result'; import { FactoryContext } from '~/types/factory/factory.context'; import { FactoryRole } from '~/types/factory/factory.role'; import { action } from './action'; import { BiotaFunctionName } from './constructors'; import { document } from './document'; // tslint:disable-next-line: only-arrow-functions export const role: FactoryContext<FactoryRole> = function (context): FactoryRole { // tslint:disable-next-line: only-arrow-functions return (name = null) => { return { get() { const inputs = { name }; // ---- const query = Query( { doc: q.Get(q.Role(q.Var('name'))), }, q.Var('doc'), ); // ---- const offline = 'factory.role.get'; const online = { name: BiotaFunctionName('RoleGet'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, insert(options) { const inputs = { name, options }; // --- const query = Query( { annotated: ResultData(document(q.Var('ctx'))().annotate('insert', q.Select('data', q.Var('options'), {}))), doc: q.CreateFunction(q.Merge(q.Var('options'), { name: q.Var('name'), data: q.Var('annotated') })), action: action(q.Var('ctx'))('insert', q.Var('doc')).log(), }, q.Var('doc'), q.Var('action'), ); // --- const offline = 'factory.role.insert'; const online = { name: BiotaFunctionName('RoleInsert'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, update(options) { const inputs = { name, options }; // --- const query = Query( { annotated: ResultData(document(q.Var('ctx'))().annotate('update', q.Select('data', q.Var('options'), {}))), doc: q.Update(q.Role(q.Var('name')), q.Merge(q.Var('options'), { data: q.Var('annotated') })), action: action(q.Var('ctx'))('update', q.Var('doc')).log(), }, q.Var('doc'), q.Var('action'), ); // --- const offline = 'factory.role.update'; const online = { name: BiotaFunctionName('RoleUpdate'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, upsert(options) { const inputs = { name, options }; // --- const query = Query( { doc: q.If( q.Exists(q.Role(q.Var('name'))), ResultData(role(q.Var('ctx'))(q.Var('name')).update(q.Var('options'))), ResultData(role(q.Var('ctx'))(q.Var('name')).insert(q.Var('options'))), ), }, q.Var('doc'), ); // --- const offline = 'factory.role.upsert'; const online = { name: BiotaFunctionName('RoleUpsert'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, replace(options) { const inputs = { name, options }; // --- const query = Query( { current_doc: ResultData(role(q.Var('ctx'))(q.Var('name')).get()), annotated: ResultData( document(q.Var('ctx'))().annotate( 'replace', q.Merge(q.Select('data', q.Var('options'), {}), { _auth: q.Select('_auth', q.Var('current_doc'), {}), _membership: q.Select('_membership', q.Var('current_doc'), {}), _validity: q.Select('_validity', q.Var('current_doc'), {}), _activity: q.Select('_activity', q.Var('current_doc'), {}), }), ), ), doc: q.Replace(q.Role(q.Var('name')), q.Merge(q.Var('options'), { data: q.Var('annotated') })), action: action(q.Var('ctx'))('replace', q.Var('doc')).log(), }, q.Var('doc'), q.Var('action'), ); // --- const offline = 'factory.role.replace'; const online = { name: BiotaFunctionName('RoleReplace'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, repsert(options) { const inputs = { name, options }; // --- const query = Query( { doc: q.If( q.Exists(q.Role(q.Var('name'))), ResultData(role(q.Var('ctx'))(q.Var('name')).replace(q.Var('options'))), ResultData(role(q.Var('ctx'))(q.Var('name')).insert(q.Var('options'))), ), }, q.Var('doc'), ); // --- const offline = 'factory.role.repsert'; const online = { name: BiotaFunctionName('RoleRepsert'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, delete() { const inputs = { name }; // --- const query = Query( { doc: ResultData(document(q.Var('ctx'))(q.Role(q.Var('name'))).validity.delete()), }, q.Var('doc'), ); // --- const offline = 'factory.role.delete'; const online = { name: BiotaFunctionName('RoleDelete'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, forget() { const inputs = { name }; // --- const query = Query( { annotated: ResultData(document(q.Var('ctx'))().annotate('forget')), annotated_doc: ResultData(role(q.Var('ctx'))(q.Var('name')).upsert(q.Var('annotated'))), action: action(q.Var('ctx'))('forget', q.Var('annotated_doc')).log(), doc: q.Delete(q.Var('name')), }, q.Var('doc'), q.Var('action'), ); // --- const offline = 'factory.role.forget'; const online = { name: BiotaFunctionName('RoleForget'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, drop() { const inputs = { name }; // --- const query = Query( { doc: q.If(q.Exists(q.Role(q.Var('name'))), role(q.Var('ctx'))(q.Var('name')).forget(), false), }, q.Var('doc'), ); // --- const offline = 'factory.role.drop'; const online = { name: BiotaFunctionName('RoleClean'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, membership: { distinct(membership) { const inputs = { name, membership }; // --- const query = Query( { membership_resource: q.Select('resource', q.Var('membership')), current_membership_raw: q.Select('membership', q.Get(q.Role(q.Var('name'))), []), current_membership: q.If( q.IsObject(q.Var('current_membership_raw')), [q.Var('current_membership_raw')], q.Var('current_membership_raw'), ), same_current_membership: q.Filter( q.Var('current_membership'), q.Lambda('cm', q.Equals(q.Select('resource', q.Var('cm')), q.Var('membership_resource'))), ), current_membership_except_new: q.Filter( q.Var('current_membership'), q.Lambda('cm', q.Not(q.Equals(q.Select('resource', q.Var('cm')), q.Var('membership_resource')))), ), new_membership: q.Merge(q.Select(0, q.Var('same_current_membership'), {}), q.Var('membership')), new_memberships: q.Append(q.Var('current_membership_except_new'), [q.Var('new_membership')]), }, q.Var('new_memberships'), ); // --- const offline = 'factory.role.membership.distinct'; const online = { name: BiotaFunctionName('RoleMembershipDistinct'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, difference(resource) { const inputs = { name, resource }; // --- const query = Query( { current_membership_raw: q.Select('membership', q.Get(q.Role(q.Var('name'))), []), current_membership: q.If( q.IsObject(q.Var('current_membership_raw')), [q.Var('current_membership_raw')], q.Var('current_membership_raw'), ), membership_filtered: q.Filter( q.Var('current_membership'), q.Lambda('cm', q.Not(q.Equals(q.Select('resource', q.Var('cm')), q.Var('resource')))), ), }, q.Var('membership_filtered'), ); // --- const offline = 'factory.role.membership.difference'; const online = { name: BiotaFunctionName('RoleMembershipDifference'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, set(membership) { const inputs = { name, membership }; // --- const query = Query( { doc: ResultData( role(q.Var('ctx'))(q.Var('name')).upsert({ membership: ResultData(role(q.Var('ctx'))(q.Var('name')).membership.distinct(q.Var('membership'))), }), ), }, q.Var('doc'), ); // --- const offline = 'factory.role.membership.set'; const online = { name: BiotaFunctionName('RoleMembershipSet'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, setMany(membershipList) { const inputs = { name, membershipList }; // --- const query = Query( { iterations: q.Map( q.Var('membershipList'), q.Lambda( ['membership'], ResultData( role(q.Var('ctx'))(q.Var('name')).upsert({ membership: ResultData(role(q.Var('ctx'))(q.Var('name')).membership.distinct(q.Var('membership'))), }), ), ), ), doc: q.Select(q.Subtract(q.Count(q.Var('iterations')), 1), q.Var('iterations'), null), }, q.Var('doc'), ); // --- const offline = 'factory.role.membership.setMany'; const online = { name: BiotaFunctionName('RoleMembershipSetMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, remove(resource) { const inputs = { name, resource }; // --- const query = Query( { doc: ResultData( role(q.Var('ctx'))(q.Var('name')).upsert({ membership: ResultData(role(q.Var('ctx'))(q.Var('name')).membership.difference(q.Var('resource'))), }), ), }, q.Var('doc'), ); // --- const offline = 'factory.role.membership.remove'; const online = { name: BiotaFunctionName('RoleMembershipRemove'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, removeMany(resourceList) { const inputs = { name, resourceList }; // --- const query = Query( { iterations: q.Map( q.Var('resourceList'), q.Lambda( ['resource'], ResultData( role(q.Var('ctx'))(q.Var('name')).upsert({ membership: ResultData(role(q.Var('ctx'))(q.Var('name')).membership.difference(q.Var('resource'))), }), ), ), ), doc: q.Select(q.Subtract(q.Count(q.Var('iterations')), 1), q.Var('iterations'), null), }, q.Var('doc'), ); // --- const offline = 'factory.role.membership.removeMany'; const online = { name: BiotaFunctionName('RoleMembershipRemoveMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, }, privilege: { distinct(privilege) { const inputs = { name, privilege }; // --- const query = Query( { privilege_resource: q.Select('resource', q.Var('privilege')), has_privilege_resource: q.If(q.IsRef(q.Var('privilege_resource')), true, q.Abort("Privilege doesn't have a resource")), current_privilege_raw: q.Select('privileges', q.Get(q.Role(q.Var('name'))), []), current_privilege: q.If( q.IsObject(q.Var('current_privilege_raw')), [q.Var('current_privilege_raw')], q.Var('current_privilege_raw'), ), same_current_privilege: q.Filter( q.Var('current_privilege'), q.Lambda('cm', q.Equals(q.Select('resource', q.Var('cm')), q.Var('privilege_resource'))), ), current_privilege_except_new: q.Filter( q.Var('current_privilege'), q.Lambda('cm', q.Not(q.Equals(q.Select('resource', q.Var('cm')), q.Var('privilege_resource')))), ), new_privilege_actions: q.Merge( q.Select([0, 'actions'], q.Var('same_current_privilege'), {}), q.Select('actions', q.Var('privilege'), {}), ), new_privileges: q.Append(q.Var('current_privilege_except_new'), [ { resource: q.Select('resource', q.Var('privilege')), actions: q.Var('new_privilege_actions'), }, ]), }, q.Var('new_privileges'), ); // --- const offline = 'factory.role.privilege.distinct'; const online = { name: BiotaFunctionName('RolePrivilegeDistinct'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, difference(resource) { const inputs = { name, resource }; // --- const query = Query( { current_privileges_raw: q.Select('privileges', q.Get(q.Role(q.Var('name'))), []), current_privileges: q.If( q.IsObject(q.Var('current_privileges_raw')), [q.Var('current_privileges_raw')], q.Var('current_privileges_raw'), ), privileges_filtered: q.Filter( q.Var('current_privileges'), q.Lambda('cm', q.Not(q.Equals(q.Select('resource', q.Var('cm')), q.Var('resource')))), ), }, q.Var('privileges_filtered'), ); // --- const offline = 'factory.role.privilege.difference'; const online = { name: BiotaFunctionName('RolePrivilegeDifference'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, set(privilege) { const inputs = { name, privilege }; // --- const query = Query( { doc: ResultData( role(q.Var('ctx'))(q.Var('name')).upsert({ privileges: ResultData(role(q.Var('ctx'))(q.Var('name')).privilege.distinct(q.Var('privilege'))), }), ), }, q.Var('doc'), ); // --- const offline = 'factory.role.privilege.set'; const online = { name: BiotaFunctionName('RolePrivilegesSet'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, setMany(privilegeList) { const inputs = { name, privilegeList }; // --- const query = Query( { iterations: q.Map( q.Var('privilegeList'), q.Lambda( ['privilege'], ResultData( role(q.Var('ctx'))(q.Var('name')).upsert({ privileges: ResultData(role(q.Var('ctx'))(q.Var('name')).privilege.distinct(q.Var('privilege'))), }), ), ), ), doc: q.Select(q.Subtract(q.Count(q.Var('iterations')), 1), q.Var('iterations'), null), }, q.Var('doc'), ); // --- const offline = 'factory.role.privilege.setMany'; const online = { name: BiotaFunctionName('RolePrivilegesSetMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, scaffold(privilege) { const inputs = { name, privilege }; // --- const query = Query( { doc: ResultData( role(q.Var('ctx'))(q.Var('name')).upsert({ privileges: ResultData(role(q.Var('ctx'))(q.Var('name')).privilege.distinct(q.Var('privilege'))), }), ), }, q.Var('doc'), ); // --- const offline = 'factory.role.privilege.set'; const online = { name: BiotaFunctionName('RolePrivilegesSet'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, remove(resource) { const inputs = { name, resource }; // --- const query = Query( { doc: ResultData( role(q.Var('ctx'))(q.Var('name')).upsert({ privileges: ResultData(role(q.Var('ctx'))(q.Var('name')).privilege.difference(q.Var('resource'))), }), ), }, q.Var('doc'), ); // --- const offline = 'factory.role.privilege.remove'; const online = { name: BiotaFunctionName('RolePrivilegesRemove'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, removeMany(resourceList) { const inputs = { name, resourceList }; // --- const query = Query( { iterations: q.Map( q.Var('resourceList'), q.Lambda( ['resource'], ResultData( role(q.Var('ctx'))(q.Var('name')).upsert({ privileges: ResultData(role(q.Var('ctx'))(q.Var('name')).privilege.difference(q.Var('resource'))), }), ), ), ), doc: q.Select(q.Subtract(q.Count(q.Var('iterations')), 1), q.Var('iterations'), null), }, q.Var('doc'), ); // --- const offline = 'factory.role.privilege.removeMany'; const online = { name: BiotaFunctionName('RolePrivilegesRemoveMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, }, expireAt(at) { // alias const inputs = { name, at }; // ---- const query = Query( { doc: ResultData(document(q.Var('ctx'))(q.Role(q.Var('name'))).validity.expire(q.Var('at'))), }, q.Var('doc'), ); // ---- const offline = 'factory.role.expireAt'; const online = { name: BiotaFunctionName('RoleExpireAt'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, expireIn(delay) { // alias const inputs = { name, delay }; // ---- const query = Query( { doc: ResultData( document(q.Var('ctx'))(q.Role(q.Var('name'))).validity.expire(q.TimeAdd(q.Now(), q.ToNumber(q.Var('delay')), 'milliseconds')), ), }, q.Var('doc'), ); // ---- const offline = 'factory.role.expireIn'; const online = { name: BiotaFunctionName('RoleExpireIn'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, expireNow() { // alias const inputs = { name }; // ---- const query = Query( { doc: ResultData(document(q.Var('ctx'))(q.Role(q.Var('name'))).validity.expire(q.Now())), }, q.Var('doc'), ); // ---- const offline = 'factory.role.expireNow'; const online = { name: BiotaFunctionName('RoleExpireNow'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, restore() { // alias const inputs = { name }; // ---- const query = Query( { doc: ResultData(document(q.Var('ctx'))(q.Role(q.Var('name'))).validity.restore()), }, q.Var('doc'), ); // ---- const offline = 'factory.collection.restore'; const online = { name: BiotaFunctionName('RoleRestore'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, }; }; };
the_stack
import { NodeProject } from "."; import { JsonFile } from "../json"; export interface TypescriptConfigOptions { /** * @default "tsconfig.json" */ readonly fileName?: string; /** * Specifies a list of glob patterns that match TypeScript files to be included in compilation. * * @default - all .ts files recursively */ readonly include?: string[]; /** * Filters results from the "include" option. * * @default - node_modules is excluded by default */ readonly exclude?: string[]; /** * Compiler options to use. */ readonly compilerOptions: TypeScriptCompilerOptions; } /** * Determines how modules get resolved. * * @see https://www.typescriptlang.org/docs/handbook/module-resolution.html */ export enum TypeScriptModuleResolution { /** * TypeScript's former default resolution strategy. * * @see https://www.typescriptlang.org/docs/handbook/module-resolution.html#classic */ CLASSIC = "classic", /** * Resolution strategy which attempts to mimic the Node.js module resolution strategy at runtime. * * @see https://www.typescriptlang.org/docs/handbook/module-resolution.html#node */ NODE = "node", } /** * Determines how JSX should get transformed into valid JavaScript. * * @see https://www.typescriptlang.org/docs/handbook/jsx.html */ export enum TypeScriptJsxMode { /** * Keeps the JSX as part of the output to be further consumed by another transform step (e.g. Babel). */ PRESERVE = "preserve", /** * Converts JSX syntax into React.createElement, does not need to go through a JSX transformation before use, and the output will have a .js file extension. */ REACT = "react", /** * Keeps all JSX like 'preserve' mode, but output will have a .js extension. */ REACT_NATIVE = "react-native", /** * Passes `key` separately from props and always passes `children` as props (since React 17). * * @see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#react-17-jsx-factories */ REACT_JSX = "react-jsx", /** * Same as `REACT_JSX` with additional debug data. */ REACT_JSXDEV = "react-jsxdev", } export interface TypeScriptCompilerOptions { /** * Allow JavaScript files to be compiled. * * @default false */ readonly allowJs?: boolean; /** * Ensures that your files are parsed in the ECMAScript strict mode, and emit “use strict” * for each source file. * * @default true */ readonly alwaysStrict?: boolean; /** * Offers a way to configure the root directory for where declaration files are emitted. * */ readonly declarationDir?: string; /** * To be specified along with the above * */ readonly declaration?: boolean; /** * Emit __importStar and __importDefault helpers for runtime babel * ecosystem compatibility and enable --allowSyntheticDefaultImports for * typesystem compatibility. * * @default false */ readonly esModuleInterop?: boolean; /** * Enables experimental support for decorators, which is in stage 2 of the TC39 standardization process. * * @default true */ readonly experimentalDecorators?: boolean; /** * Enables experimental support for decorators, which is in stage 2 of the TC39 standardization process. * Decorators are a language feature which hasn’t yet been fully ratified into the JavaScript specification. * This means that the implementation version in TypeScript may differ from the implementation in JavaScript when it it decided by TC39. * You can find out more about decorator support in TypeScript in the handbook. * * @see https://www.typescriptlang.org/docs/handbook/decorators.html * @default undefined */ readonly emitDecoratorMetadata?: boolean; /** * Disallow inconsistently-cased references to the same file. * * @default false */ readonly forceConsistentCasingInFileNames?: boolean; /** * When set, instead of writing out a .js.map file to provide source maps, * TypeScript will embed the source map content in the .js files. * * @default true */ readonly inlineSourceMap?: boolean; /** * When set, TypeScript will include the original content of the .ts file as an embedded * string in the source map. This is often useful in the same cases as inlineSourceMap. * * @default true */ readonly inlineSources?: boolean; /** * Perform additional checks to ensure that separate compilation (such as * with transpileModule or @babel/plugin-transform-typescript) would be safe. * * @default false */ readonly isolatedModules?: boolean; /** * Support JSX in .tsx files: "react", "preserve", "react-native" etc. * * @default undefined */ readonly jsx?: TypeScriptJsxMode; /** * Reference for type definitions / libraries to use (eg. ES2016, ES5, ES2018). * * @default [ "es2018" ] */ readonly lib?: string[]; /** * Sets the module system for the program. * See https://www.typescriptlang.org/docs/handbook/modules.html#ambient-modules. * * @default "CommonJS" */ readonly module?: string; /** * Determine how modules get resolved. Either "Node" for Node.js/io.js style resolution, or "Classic". * * @default "node" */ readonly moduleResolution?: TypeScriptModuleResolution; /** * Do not emit outputs. * * @default false */ readonly noEmit?: boolean; /** * Do not emit compiler output files like JavaScript source code, source-maps or * declarations if any errors were reported. * * @default true */ readonly noEmitOnError?: boolean; /** * Report errors for fallthrough cases in switch statements. Ensures that any non-empty * case inside a switch statement includes either break or return. This means you won’t * accidentally ship a case fallthrough bug. * * @default true */ readonly noFallthroughCasesInSwitch?: boolean; /** * In some cases where no type annotations are present, TypeScript will fall back to a * type of any for a variable when it cannot infer the type. * * @default true */ readonly noImplicitAny?: boolean; /** * When enabled, TypeScript will check all code paths in a function to ensure they * return a value. * * @default true */ readonly noImplicitReturns?: boolean; /** * Raise error on ‘this’ expressions with an implied ‘any’ type. * * @default true */ readonly noImplicitThis?: boolean; /** * Raise error on use of the dot syntax to access fields which are not defined. * * @default true */ readonly noPropertyAccessFromIndexSignature?: boolean; /** * Raise error when accessing indexes on objects with unknown keys defined in index signatures. * * @default true */ readonly noUncheckedIndexedAccess?: boolean; /** * Report errors on unused local variables. * * @default true */ readonly noUnusedLocals?: boolean; /** * Report errors on unused parameters in functions. * * @default true */ readonly noUnusedParameters?: boolean; /** * Allows importing modules with a ‘.json’ extension, which is a common practice * in node projects. This includes generating a type for the import based on the static JSON shape. * * @default true */ readonly resolveJsonModule?: boolean; /** * Skip type checking of all declaration files (*.d.ts). * * @default false */ readonly skipLibCheck?: boolean; /** * The strict flag enables a wide range of type checking behavior that results in stronger guarantees * of program correctness. Turning this on is equivalent to enabling all of the strict mode family * options, which are outlined below. You can then turn off individual strict mode family checks as * needed. * * @default true */ readonly strict?: boolean; /** * When strictNullChecks is false, null and undefined are effectively ignored by the language. * This can lead to unexpected errors at runtime. * When strictNullChecks is true, null and undefined have their own distinct types and you’ll * get a type error if you try to use them where a concrete value is expected. * * @default true */ readonly strictNullChecks?: boolean; /** * When set to true, TypeScript will raise an error when a class property was declared but * not set in the constructor. * * @default true */ readonly strictPropertyInitialization?: boolean; /** * Do not emit declarations for code that has an @internal annotation in it’s JSDoc comment. * * @default true */ readonly stripInternal?: boolean; /** * Modern browsers support all ES6 features, so ES6 is a good choice. You might choose to set * a lower target if your code is deployed to older environments, or a higher target if your * code is guaranteed to run in newer environments. * * @default "ES2018" */ readonly target?: string; /** * Output directory for the compiled files. */ readonly outDir?: string; /** * Specifies the root directory of input files. * * Only use to control the output directory structure with `outDir`. */ readonly rootDir?: string; /** * Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ readonly allowSyntheticDefaultImports?: boolean; /** * Lets you set a base directory to resolve non-absolute module names. * * You can define a root folder where you can do absolute file resolution. */ readonly baseUrl?: string; /** * A series of entries which re-map imports to lookup locations relative to the baseUrl, there is a larger coverage of paths in the handbook. * * paths lets you declare how TypeScript should resolve an import in your require/imports. */ readonly paths?: { [key: string]: string[] }; } export class TypescriptConfig { public readonly compilerOptions: TypeScriptCompilerOptions; public readonly include: string[]; public readonly exclude: string[]; public readonly fileName: string; public readonly file: JsonFile; constructor(project: NodeProject, options: TypescriptConfigOptions) { const fileName = options.fileName ?? "tsconfig.json"; this.include = options.include ?? ["**/*.ts"]; this.exclude = options.exclude ?? ["node_modules"]; this.fileName = fileName; this.compilerOptions = options.compilerOptions; this.file = new JsonFile(project, fileName, { obj: { compilerOptions: this.compilerOptions, include: () => this.include, exclude: () => this.exclude, }, }); project.npmignore?.exclude(`/${fileName}`); } public addInclude(pattern: string) { this.include.push(pattern); } public addExclude(pattern: string) { this.exclude.push(pattern); } }
the_stack
import {EventAggregator, Subscription} from 'aurelia-event-aggregator'; import {bindable, inject, observable} from 'aurelia-framework'; import * as Bluebird from 'bluebird'; import {IShape} from '@process-engine/bpmn-elements_contracts'; import {DataModels} from '@process-engine/management_api_contracts'; import {IDiagram} from '@process-engine/solutionexplorer.contracts'; import {IEventFunction, ISolutionEntry, InspectPanelTab, NotificationType} from '../../../contracts/index'; import environment from '../../../environment'; import {IInspectProcessInstanceService} from './contracts'; import {DiagramViewer} from './components/diagram-viewer/diagram-viewer'; import {InspectPanel} from './components/inspect-panel/inspect-panel'; import {DEFAULT_PAGESIZE} from './components/inspect-panel/components/process-instance-list/process-instance-list'; import {NotificationService} from '../../../services/notification-service/notification.service'; @inject('InspectProcessInstanceService', EventAggregator, 'NotificationService') export class InspectProcessInstance { @bindable public correlations: Array<DataModels.Correlations.Correlation>; @bindable public correlationToSelect: DataModels.Correlations.Correlation; @bindable public processInstanceIdToSelect: string; @bindable public processInstanceToSelect: DataModels.Correlations.ProcessInstance; @bindable public flowNodeToSelect: string; @bindable public activeDiagram: IDiagram; @bindable public activeSolutionEntry: ISolutionEntry; @bindable public selectedCorrelation: DataModels.Correlations.Correlation; @bindable public selectedProcessInstance: DataModels.Correlations.ProcessInstance; @bindable public inspectPanelFullscreen: boolean = false; @observable public bottomPanelHeight: number = 250; @observable public tokenViewerWidth: number = 250; @bindable public diagramViewer: DiagramViewer; @bindable public inspectPanel: InspectPanel; @bindable public inspectPanelTabToShow: InspectPanelTab; @bindable public totalCorrelationCount: number; @bindable public totalProcessInstanceCount: number; public correlationOffset: number = 0; public correlationLimit: number = DEFAULT_PAGESIZE; public processInstanceOffset: number = 0; public processInstanceLimit: number = DEFAULT_PAGESIZE; public processInstances: Array<DataModels.Correlations.ProcessInstance>; public token: string; public showInspectPanel: boolean = true; public showTokenViewer: boolean = false; public bottomPanelResizeDiv: HTMLDivElement; public rightPanelResizeDiv: HTMLDivElement; public selectedFlowNode: IShape; public viewIsAttached: boolean = false; private inspectProcessInstanceService: IInspectProcessInstanceService; private eventAggregator: EventAggregator; private notificationService: NotificationService; private subscriptions: Array<Subscription>; private updateCorrelationPromise: any; private updateProcessInstancePromise: any; constructor( InspectProcessInstanceService: IInspectProcessInstanceService, eventAggregator: EventAggregator, notificationService: NotificationService, ) { this.inspectProcessInstanceService = InspectProcessInstanceService; this.eventAggregator = eventAggregator; this.notificationService = notificationService; } public async attached(): Promise<void> { this.updateProcessInstances(); this.updateCorrelations(); this.eventAggregator.publish(environment.events.statusBar.showInspectProcessInstanceButtons, true); this.subscriptions = [ this.eventAggregator.subscribe( environment.events.inspectProcessInstance.showInspectPanel, (showInspectPanel: boolean) => { this.showInspectPanel = showInspectPanel; }, ), this.eventAggregator.subscribe( environment.events.inspectProcessInstance.showTokenViewer, (showTokenViewer: boolean) => { this.showTokenViewer = showTokenViewer; }, ), this.eventAggregator.subscribe( environment.events.inspectProcessInstance.updateProcessInstances, async (payload) => { const {offset, limit} = payload; this.processInstanceOffset = offset; this.processInstanceLimit = limit; await this.updateProcessInstances(); }, ), this.eventAggregator.subscribe(environment.events.inspectProcessInstance.updateCorrelations, async (payload) => { const {offset, limit} = payload; this.correlationOffset = offset; this.correlationLimit = limit; await this.updateCorrelations(); }), ]; this.bottomPanelResizeDiv.addEventListener('mousedown', (mouseDownEvent: Event) => { const windowEvent: Event = mouseDownEvent || window.event; windowEvent.cancelBubble = true; const mousemoveFunction: IEventFunction = (mouseMoveEvent: MouseEvent): void => { this.resizeInspectPanel(mouseMoveEvent); document.getSelection().empty(); }; const mouseUpFunction: IEventFunction = (): void => { document.removeEventListener('mousemove', mousemoveFunction); document.removeEventListener('mouseup', mouseUpFunction); }; document.addEventListener('mousemove', mousemoveFunction); document.addEventListener('mouseup', mouseUpFunction); }); this.rightPanelResizeDiv.addEventListener('mousedown', (mouseDownEvent: Event) => { const windowEvent: Event = mouseDownEvent || window.event; windowEvent.cancelBubble = true; const mousemoveFunction: IEventFunction = (mouseMoveEvent: MouseEvent): void => { this.resizeTokenViewer(mouseMoveEvent); document.getSelection().empty(); }; const mouseUpFunction: IEventFunction = (): void => { document.removeEventListener('mousemove', mousemoveFunction); document.removeEventListener('mouseup', mouseUpFunction); }; document.addEventListener('mousemove', mousemoveFunction); document.addEventListener('mouseup', mouseUpFunction); }); this.viewIsAttached = true; const previousTokenViewerState: boolean = JSON.parse( window.localStorage.getItem('tokenViewerInspectCollapseState'), ); this.showTokenViewer = previousTokenViewerState || false; const flowNodeToSelectExists: boolean = this.flowNodeToSelect !== undefined; if (flowNodeToSelectExists) { this.diagramViewer.selectFlowNode(this.flowNodeToSelect); } const shouldDisplaySpecificInspectPanelTab: boolean = this.inspectPanelTabToShow !== undefined; if (shouldDisplaySpecificInspectPanelTab) { this.inspectPanel.changeTab(this.inspectPanelTabToShow); } if (this.processInstanceIdToSelect) { try { const processInstanceToSelect = await this.inspectProcessInstanceService.getProcessInstanceById( this.activeSolutionEntry.identity, this.processInstanceIdToSelect, this.activeDiagram.id, ); this.correlationToSelect = await this.inspectProcessInstanceService.getCorrelationById( this.activeSolutionEntry.identity, processInstanceToSelect.correlationId, ); this.processInstanceToSelect = processInstanceToSelect; } catch (error) { this.notificationService.showNotification( NotificationType.ERROR, 'The requested ProcessInstance to select could not be found.', ); } } } private async updateCorrelations(): Promise<void> { let correlationList: DataModels.Correlations.CorrelationList; try { correlationList = await this.getCorrelationsForProcessModel(); } catch (error) { this.eventAggregator.publish(environment.events.inspectProcessInstance.noCorrelationsFound, true); this.correlations = []; this.totalCorrelationCount = 0; } // https://github.com/process-engine/process_engine_runtime/issues/432 if (correlationList && correlationList.totalCount === 0) { this.eventAggregator.publish(environment.events.inspectProcessInstance.noCorrelationsFound, true); this.correlations = []; this.totalCorrelationCount = 0; } else if (correlationList) { this.correlations = correlationList.correlations; this.totalCorrelationCount = correlationList.totalCount; } } private async updateProcessInstances(): Promise<void> { let processInstanceList; try { const noCorrelationSelected: boolean = this.selectedCorrelation === undefined; if (noCorrelationSelected) { this.processInstances = []; this.totalProcessInstanceCount = 0; return; } processInstanceList = await this.getProcessInstancesForCorrelation(); } catch (error) { this.eventAggregator.publish(environment.events.inspectProcessInstance.noCorrelationsFound, true); this.processInstances = []; this.totalProcessInstanceCount = 0; } // https://github.com/process-engine/process_engine_runtime/issues/432 if (processInstanceList && processInstanceList.totalCount === 0) { this.eventAggregator.publish(environment.events.inspectProcessInstance.noCorrelationsFound, true); this.processInstances = []; this.totalProcessInstanceCount = 0; } else if (processInstanceList) { this.processInstances = processInstanceList.processInstances; this.totalProcessInstanceCount = processInstanceList.totalCount; } } private getProcessInstancesForCorrelation(): Promise<DataModels.Correlations.ProcessInstanceList> { if (this.updateProcessInstancePromise) { this.updateProcessInstancePromise.cancel(); } this.updateProcessInstancePromise = new Bluebird.Promise( async (resolve: Function, reject: Function): Promise<any> => { try { const processInstances = await this.inspectProcessInstanceService.getProcessInstancesForCorrelation( this.activeSolutionEntry.identity, this.selectedCorrelation.id, this.processInstanceOffset, this.processInstanceLimit, ); resolve(processInstances); } catch (error) { reject(error); } }, ); return this.updateProcessInstancePromise; } private getCorrelationsForProcessModel(): Promise<DataModels.Correlations.CorrelationList> { if (this.updateCorrelationPromise) { this.updateCorrelationPromise.cancel(); } this.updateCorrelationPromise = new Bluebird.Promise( async (resolve: Function, reject: Function): Promise<any> => { try { const correlations = await this.inspectProcessInstanceService.getAllCorrelationsForProcessModelId( this.activeSolutionEntry.identity, this.activeDiagram.id, this.correlationOffset, this.correlationLimit, ); resolve(correlations); } catch (error) { reject(error); } }, ); return this.updateCorrelationPromise; } public detached(): void { this.eventAggregator.publish(environment.events.statusBar.showInspectProcessInstanceButtons, false); for (const subscription of this.subscriptions) { subscription.dispose(); } } public async activeDiagramChanged(): Promise<void> { if (!this.viewIsAttached) { return; } this.correlationOffset = 0; this.processInstanceOffset = 0; this.processInstanceIdToSelect = undefined; this.processInstanceToSelect = undefined; this.correlationToSelect = undefined; this.selectedProcessInstance = undefined; this.selectedCorrelation = undefined; this.updateProcessInstances(); this.updateCorrelations(); } public selectedCorrelationChanged(): void { if (this.viewIsAttached) { this.updateProcessInstances(); } } private resizeInspectPanel(mouseEvent: MouseEvent): void { const mouseYPosition: number = mouseEvent.clientY; const menuBarHeight: number = 40; const inspectProcessInstance: HTMLElement = this.bottomPanelResizeDiv.parentElement.parentElement; const inspectPanelHeightWithStatusBar: number = inspectProcessInstance.clientHeight + menuBarHeight; const minInspectPanelHeight: number = 250; const newBottomPanelHeight: number = inspectPanelHeightWithStatusBar - mouseYPosition; this.bottomPanelHeight = Math.max(newBottomPanelHeight, minInspectPanelHeight); } private resizeTokenViewer(mouseEvent: MouseEvent): void { const mouseXPosition: number = mouseEvent.clientX; const inspectProcessInstance: HTMLElement = this.bottomPanelResizeDiv.parentElement.parentElement; const minSpaceForDiagramViewer: number = 300; const windowWidth: number = window.innerWidth; const rightToolbarWidth: number = 36; const minTokenViewerWidth: number = 250; const maxTokenViewerWidth: number = inspectProcessInstance.clientWidth - minSpaceForDiagramViewer; const newTokenViewerWidth: number = windowWidth - mouseXPosition - rightToolbarWidth; /* * This sets the new width of the token viewer to the minimum or maximum width, * if the new width is smaller than the minimum or bigger than the maximum width. */ this.tokenViewerWidth = Math.min(maxTokenViewerWidth, Math.max(newTokenViewerWidth, minTokenViewerWidth)); } }
the_stack
* Unit tests for convolutional.ts. */ import * as tfc from '@tensorflow/tfjs-core'; import {scalar, Tensor, tensor1d, tensor3d, tensor4d, tensor5d, util} from '@tensorflow/tfjs-core'; import * as tfl from '../index'; import {InitializerIdentifier} from '../initializers'; import {ActivationIdentifier} from '../keras_format/activation_config'; import {DataFormat, InterpolationFormat, PaddingMode, Shape} from '../keras_format/common'; import {describeMathCPU, describeMathCPUAndGPU, describeMathGPU, expectTensorsClose} from '../utils/test_utils'; import {conv1d, conv1dWithBias, conv2d, conv2dWithBiasActivation, conv3d, conv3dWithBias} from './convolutional'; describeMathCPUAndGPU('conv1dWithBias', () => { const xLength4Data = [10, 20, 40, 80]; const kernelLength2Data = [1, -1]; const biasScalarData = 2.2; // In the basic case, this convolves [10, 20, 40, 80] with the kernel [1, -1], // producing [-10, -20, -40], and adds the bias 2.2, producing // [-7.8, -17.8, -37.7]. The test is reproduced for either 1 or 2 output // channels, and several reasonable data formats. const outChannelsArray = [1, 2]; const dataFormats: DataFormat[] = [undefined, 'channelsFirst', 'channelsLast']; const paddingModes: PaddingMode[] = [undefined, 'same', 'valid']; const stride = 1; for (const outChannels of outChannelsArray) { for (const dataFormat of dataFormats) { for (const paddingMode of paddingModes) { const testTitle = `outChannels=${outChannels}, stride=${stride}, ` + `${paddingMode}, ${dataFormat}`; it(testTitle, () => { let x: Tensor = tensor3d(xLength4Data, [1, 4, 1]); if (dataFormat === 'channelsFirst') { x = tfc.transpose(x, [0, 2, 1]); // NWC -> NCW. } let kernelData: number[] = []; let biasData: number[] = []; for (let i = 0; i < outChannels; ++i) { kernelData = kernelData.concat(kernelLength2Data); biasData = biasData.concat([biasScalarData + i]); } const kernel = tfc.transpose( tensor3d(kernelData, [1, outChannels, 2]), [2, 0, 1]); const bias = tensor1d(biasData); const y = conv1dWithBias(x, kernel, bias, stride, paddingMode, dataFormat); let yExpectedShape: [number, number, number]; let yExpectedData: number[]; if (paddingMode === 'valid' || paddingMode === undefined) { if (outChannels === 1) { yExpectedShape = [1, 3, 1]; yExpectedData = [-7.8, -17.8, -37.8]; } else if (outChannels === 2) { yExpectedShape = [1, 3, 2]; yExpectedData = [-7.8, -6.8, -17.8, -16.8, -37.8, -36.8]; } } else if (paddingMode === 'same') { if (outChannels === 1) { yExpectedShape = [1, 4, 1]; yExpectedData = [-7.8, -17.8, -37.8, 82.2]; } else if (outChannels === 2) { yExpectedShape = [1, 4, 2]; yExpectedData = [-7.8, -6.8, -17.8, -16.8, -37.8, -36.8, 82.2, 83.2]; } } expectTensorsClose(y, tensor3d(yExpectedData, yExpectedShape)); }); } } } }); describeMathCPUAndGPU('conv1d', () => { const xLength4Data = [10, 20, 40, 80]; const kernelLength2Data = [1, -1]; const outChannels = 2; const dataFormat = 'channelsLast'; const paddingMode = 'valid'; const strides = [2, 1]; const dilations = [1, 2]; const expectations = [[-10, -10, -40, -40], [-30, -30, -60, -60]]; for (let i = 0; i < strides.length; ++i) { const stride = strides[i]; const dilationRate = dilations[i]; const expectation = expectations[i]; const testTitle = `outChannels=${outChannels}, stride=${stride}, ` + `${paddingMode}, dilationRate=${dilationRate}, ${dataFormat}`; it(testTitle, () => { const x = tensor3d(xLength4Data, [1, 4, 1]); let kernelData: number[] = []; for (let i = 0; i < outChannels; ++i) { kernelData = kernelData.concat(kernelLength2Data); } const kernel = tfc.transpose(tensor3d(kernelData, [1, outChannels, 2]), [2, 0, 1]); const y = conv1d(x, kernel, stride, paddingMode, dataFormat, dilationRate); expectTensorsClose(y, tensor3d(expectation, [1, 2, 2])); }); } }); describeMathCPUAndGPU('conv2d', () => { const x4by4Data = [[[ [10, 30, 50, 70], [20, 40, 60, 80], [-10, -30, -50, -70], [-20, -40, -60, -80] ]]]; const kernel2by2Data = [1, 0, 0, -1]; const dataFormats: DataFormat[] = [undefined, 'channelsFirst', 'channelsLast']; const paddingModes: PaddingMode[] = [undefined, 'same', 'valid']; const stridesArray = [1, 2]; for (const dataFormat of dataFormats) { for (const paddingMode of paddingModes) { for (const stride of stridesArray) { const testTitle = `stride=${stride}, ${paddingMode}, ` + `${dataFormat}`; it(testTitle, () => { let x: Tensor = tensor4d(x4by4Data, [1, 1, 4, 4]); if (dataFormat !== 'channelsFirst') { x = tfc.transpose(x, [0, 2, 3, 1]); // NCHW -> NHWC. } const kernel = tensor4d(kernel2by2Data, [2, 2, 1, 1]); const y = conv2d(x, kernel, [stride, stride], 'valid', dataFormat); let yExpected: Tensor; if (stride === 1) { yExpected = tensor4d( [[[[-30, -30, -30], [50, 90, 130], [30, 30, 30]]]], [1, 1, 3, 3]); } else if (stride === 2) { yExpected = tensor4d([[[[-30, -30], [30, 30]]]], [1, 1, 2, 2]); } if (dataFormat !== 'channelsFirst') { yExpected = tfc.transpose(yExpected, [0, 2, 3, 1]); } expectTensorsClose(y, yExpected); }); } } } it('Invalid filters leads to Error', () => { expect(() => tfl.layers.conv2d({filters: 2.5, kernelSize: 3})) .toThrowError(/filters.*positive integer.*2\.5\.$/); }); }); describeMathCPUAndGPU('conv2dWithBiasActivation', () => { const x4by4Data = [[[ [10, 30, 50, 70], [20, 40, 60, 80], [-10, -30, -50, -70], [-20, -40, -60, -80] ]]]; const kernel2by2Data = [1, 0, 0, -1]; const biasScalarData = [2.2]; const outChannelsArray = [2, 3]; const dataFormats: DataFormat[] = [undefined, 'channelsFirst', 'channelsLast']; const paddingModes: PaddingMode[] = [undefined, 'same', 'valid']; const stridesArray = [1, 2]; for (const outChannels of outChannelsArray) { for (const dataFormat of dataFormats) { for (const paddingMode of paddingModes) { for (const stride of stridesArray) { const testTitle = `outChannels=${outChannels}, stride=${stride}, ` + `${paddingMode}, ${dataFormat}`; it(testTitle, () => { let x: Tensor = tensor4d(x4by4Data, [1, 1, 4, 4]); if (dataFormat !== 'channelsFirst') { x = tfc.transpose(x, [0, 2, 3, 1]); // NCHW -> NHWC. } let kernelData: number[] = []; let biasData: number[] = []; for (let i = 0; i < outChannels; ++i) { kernelData = kernelData.concat(kernel2by2Data); biasData = biasData.concat(biasScalarData); } const kernel = tfc.transpose( tensor4d(kernelData, [outChannels, 2, 2, 1]), [1, 2, 3, 0]); const bias = tensor1d(biasData); const y = conv2dWithBiasActivation( x, kernel, bias, [stride, stride], 'valid', dataFormat); let yExpectedShape: [number, number, number, number]; let yExpectedDataPerChannel: number[]; if (stride === 1) { yExpectedShape = [1, outChannels, 3, 3]; yExpectedDataPerChannel = [-30, -30, -30, 50, 90, 130, 30, 30, 30]; } else if (stride === 2) { yExpectedShape = [1, outChannels, 2, 2]; yExpectedDataPerChannel = [-30, -30, 30, 30]; } for (let i = 0; i < yExpectedDataPerChannel.length; ++i) { yExpectedDataPerChannel[i] += biasScalarData[0]; } let yExpectedData: number[] = []; for (let i = 0; i < outChannels; ++i) { yExpectedData = yExpectedData.concat(yExpectedDataPerChannel); } let yExpected: Tensor = tensor4d(yExpectedData, yExpectedShape); if (dataFormat !== 'channelsFirst') { yExpected = tfc.transpose(yExpected, [0, 2, 3, 1]); } expectTensorsClose(y, yExpected); }); } } } } }); describeMathCPU('Conv2D Layers: Symbolic', () => { const filtersArray = [1, 64]; const paddingModes: PaddingMode[] = [undefined, 'valid', 'same']; const dataFormats: DataFormat[] = ['channelsFirst', 'channelsLast']; const kernelSizes = [[2, 2], [3, 4]]; // In this test suite, `undefined` means strides is the same as kernelSize. const stridesArray = [undefined, 1]; for (const filters of filtersArray) { for (const padding of paddingModes) { for (const dataFormat of dataFormats) { for (const kernelSize of kernelSizes) { for (const stride of stridesArray) { const strides = stride || kernelSize; const testTitle = `filters=${filters}, kernelSize=${ JSON.stringify(kernelSize)}, ` + `strides=${JSON.stringify(strides)}, ` + `${dataFormat}, ${padding}`; it(testTitle, () => { const inputShape = dataFormat === 'channelsFirst' ? [2, 16, 11, 9] : [2, 11, 9, 16]; const symbolicInput = new tfl.SymbolicTensor('float32', inputShape, null, [], null); const conv2dLayer = tfl.layers.conv2d({ filters, kernelSize, strides, padding, dataFormat, }); const output = conv2dLayer.apply(symbolicInput) as tfl.SymbolicTensor; let outputRows: number; let outputCols: number; if (stride === undefined) { // Same strides as kernelSize. outputRows = kernelSize[0] === 2 ? 5 : 3; if (padding === 'same') { outputRows++; } outputCols = kernelSize[1] === 2 ? 4 : 2; if (padding === 'same') { outputCols++; } } else { // strides: 1. outputRows = kernelSize[0] === 2 ? 10 : 9; if (padding === 'same') { outputRows += kernelSize[0] - 1; } outputCols = kernelSize[1] === 2 ? 8 : 6; if (padding === 'same') { outputCols += kernelSize[1] - 1; } } let expectedShape: [number, number, number, number]; if (dataFormat === 'channelsFirst') { expectedShape = [2, filters, outputRows, outputCols]; } else { expectedShape = [2, outputRows, outputCols, filters]; } expect(output.shape).toEqual(expectedShape); expect(output.dtype).toEqual(symbolicInput.dtype); }); } } } } } it('missing config.kernelSize throws exception', () => { // tslint:disable-next-line:no-any expect((filters: 1) => tfl.layers.conv2d({filters: 1} as any)) .toThrowError(/kernelSize/); }); it('bad config.kernelSize shape throws exception', () => { expect(() => tfl.layers.conv2d({filters: 1, kernelSize: [1, 1, 1]})) .toThrowError( /kernelSize argument must be an integer or tuple of 2 integers/); }); it('bad config.kernelSize shape throws exception', () => { expect(() => tfl.layers.conv2d({filters: 1, kernelSize: [1, 1, 1, 1]})) .toThrowError( /kernelSize to be number or number\[\] with length 1, 2, or 3/); }); it('missing config.filters throws exception', () => { // tslint:disable-next-line:no-any expect(() => tfl.layers.conv2d({kernelSize: 1} as any)) .toThrowError(/filters to be a 'number' > 0/); }); it('bad config.filters value throws exception', () => { // tslint:disable-next-line:no-any expect(() => tfl.layers.conv2d({kernelSize: 1, filters: 0} as any)) .toThrowError(/filters to be a 'number' > 0/); }); }); describeMathCPUAndGPU('Conv2D Layer: Tensor', () => { const x4by4Data = [[[ [10, 30, 50, 70], [20, 40, 60, 80], [-10, -30, -50, -70], [-20, -40, -60, -80] ]]]; const useBiases = [false, true]; const biasInitializers: InitializerIdentifier[] = ['zeros', 'ones']; const activations: ActivationIdentifier[] = [null, 'linear', 'relu']; for (const useBias of useBiases) { for (const biasInitializer of biasInitializers) { for (const activation of activations) { const testTitle = `useBias=${useBias}, biasInitializer=${biasInitializer}, ` + `activation=${activation}`; it(testTitle, () => { const x = tensor4d(x4by4Data, [1, 1, 4, 4]); const conv2dLayer = tfl.layers.conv2d({ filters: 1, kernelSize: [2, 2], strides: [2, 2], dataFormat: 'channelsFirst', useBias, kernelInitializer: 'ones', biasInitializer, activation }); const y = conv2dLayer.apply(x) as Tensor; let yExpectedData = [100, 260, -100, -260]; if (useBias && biasInitializer === 'ones') { yExpectedData = yExpectedData.map(element => element + 1); } if (activation === 'relu') { yExpectedData = yExpectedData.map(element => element >= 0 ? element : 0); } const yExpected = tensor4d(yExpectedData, [1, 1, 2, 2]); expectTensorsClose(y, yExpected); }); } } } it('CHANNEL_LAST', () => { // Convert input to CHANNEL_LAST. const x = tfc.transpose(tensor4d(x4by4Data, [1, 1, 4, 4]), [0, 2, 3, 1]); const conv2dLayer = tfl.layers.conv2d({ filters: 1, kernelSize: [2, 2], strides: [2, 2], dataFormat: 'channelsLast', useBias: false, kernelInitializer: 'ones', activation: 'linear' }); const y = conv2dLayer.apply(x) as Tensor; const yExpected = tensor4d([100, 260, -100, -260], [1, 2, 2, 1]); expectTensorsClose(y, yExpected); }); const dilationRateValues: Array<number|[number, number]> = [2, [2, 2]]; for (const dilationRate of dilationRateValues) { it(`CHANNEL_LAST, dilationRate=${dilationRate}`, () => { const x = tensor4d( [[ [ [0.89240986], [0.54892443], [0.24670805], [0.03983783], [0.56602233] ], [ [0.21421895], [0.58529864], [0.60060781], [0.66895784], [0.08855761] ], [ [0.56657235], [0.25803428], [0.17971111], [0.65166403], [0.70492866] ], [ [0.46641512], [0.05765411], [0.52517211], [0.62557303], [0.30612501] ], [ [0.8406994], [0.56932724], [0.96028134], [0.34666753], [0.04458038] ] ]], [1, 5, 5, 1]); const conv2dLayer = tfl.layers.conv2d({ filters: 1, kernelSize: [2, 2], strides: 1, dataFormat: 'channelsLast', useBias: false, kernelInitializer: 'ones', activation: 'linear', dilationRate }); const y = conv2dLayer.apply(x) as Tensor; const yExpected = tensor4d( [[ [[1.8854014], [1.4984605], [1.6973702]], [[1.8064139], [1.9374835], [1.5204625]], [[2.547264], [1.8256931], [1.8895016]] ]], [1, 3, 3, 1]); expectTensorsClose(y, yExpected); }); } const explicitDefaultDilations: Array<number|[number, number]> = [1, [1, 1]]; for (const explicitDefaultDilation of explicitDefaultDilations) { const testTitle = 'Explicit default dilation rate: ' + JSON.stringify(explicitDefaultDilation); it(testTitle, () => { const conv2dLayer = tfl.layers.conv2d({ filters: 1, kernelSize: [2, 2], strides: [2, 2], dataFormat: 'channelsFirst', useBias: false, kernelInitializer: 'ones', dilationRate: explicitDefaultDilation }); const x = tensor4d(x4by4Data, [1, 1, 4, 4]); const y = conv2dLayer.apply(x) as Tensor; const yExpected = tensor4d([100, 260, -100, -260], [1, 1, 2, 2]); expectTensorsClose(y, yExpected); }); } }); describeMathCPUAndGPU('conv3d', () => { // # The following TensorFlow Python code is used to verify the results of // # the 3D convolutions. // // ```python // import numpy as np // import tensorflow as tf // tf.enable_eager_execution() // // x = np.arange(64, dtype=np.float32).reshape(1, 4, 4, 4, 1) // # Shape of kernel is (height, width, depth, input_ch, output_ch) // kernel = np.array([ // 1, 1, 1, -1, -1, 1, 1, 1 // ], dtype=np.float32).reshape(2, 2, 2, 1, 1) // // # Strides (1, 1, 1) // outputs = tf.nn.conv3d( // input=x, filter=kernel, strides=[1, 1, 1, 1, 1], padding='VALID') // outputs.numpy().flatten() // # Output: // # array([ 42., 46., 50., 58., 62., 66., 74., 78., 82., 106., // # 110., 114., 122., 126., 130., 138., 142., 146., 170., 174., // # 178., 186., 190., 194., 202., 206., 210.], dtype=float32) // outputs.numpy().shape # (1, 3, 3, 3, 1) // // # Strides (2, 2, 2) // outputs = tf.nn.conv3d( // input=x, filter=kernel, strides=[1, 2, 2, 2, 1], padding='VALID') // outputs.numpy().flatten() // # Output: // # array([ 42., 50., 74., 82., 170., 178., 202., 210.], dtype=float32) // outputs.numpy().shape # (1, 2, 2, 2, 1) // ``` const x4by4by4Data = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63 ]; const kernel2by2by2Data = [1, 1, 1, -1, -1, 1, 1, 1]; const dataFormats: DataFormat[] = [undefined, 'channelsFirst', 'channelsLast']; const paddingModes: PaddingMode[] = [undefined, 'same', 'valid']; const stridesArray = [1, 2]; for (const dataFormat of dataFormats) { for (const paddingMode of paddingModes) { for (const stride of stridesArray) { const testTitle = `stride=${stride}, ${paddingMode}, ` + `${dataFormat}`; it(testTitle, () => { let x = tensor5d(x4by4by4Data, [1, 1, 4, 4, 4]); if (dataFormat !== 'channelsFirst') { x = tfc.transpose(x, [0, 2, 3, 4, 1]); // NCDHW -> NDHWC. } const kernel = tensor5d(kernel2by2by2Data, [2, 2, 2, 1, 1]); const y = conv3d(x, kernel, [stride, stride, stride], 'valid', dataFormat); let yExpected: Tensor; if (stride === 1) { // See validation Python code in comment above. yExpected = tensor5d( [ 42., 46., 50., 58., 62., 66., 74., 78., 82., 106., 110., 114., 122., 126., 130., 138., 142., 146., 170., 174., 178., 186., 190., 194., 202., 206., 210. ], [1, 1, 3, 3, 3]); } else if (stride === 2) { // See validation Python code in comment above. yExpected = tensor5d( [42., 50., 74., 82., 170., 178., 202., 210.], [1, 1, 2, 2, 2]); } if (dataFormat !== 'channelsFirst') { yExpected = tfc.transpose(yExpected, [0, 2, 3, 4, 1]); } expectTensorsClose(y, yExpected); }); } } } const biasScalarData = [2.2]; const outChannelsArray = [2, 3]; for (const outChannels of outChannelsArray) { for (const dataFormat of dataFormats) { for (const paddingMode of paddingModes) { for (const stride of stridesArray) { const testTitle = `outChannels=${outChannels}, stride=${stride}, ` + `${paddingMode}, ${dataFormat}`; it(testTitle, () => { let x: Tensor = tensor5d(x4by4by4Data, [1, 1, 4, 4, 4]); if (dataFormat !== 'channelsFirst') { x = tfc.transpose(x, [0, 2, 3, 4, 1]); // NCDHW -> NDHWC. } let kernelData: number[] = []; let biasData: number[] = []; for (let i = 0; i < outChannels; ++i) { kernelData = kernelData.concat(kernel2by2by2Data); biasData = biasData.concat(biasScalarData); } const kernel = tfc.transpose( tensor5d(kernelData, [outChannels, 2, 2, 2, 1]), [1, 2, 3, 4, 0]); const bias = tensor1d(biasData); const y = conv3dWithBias( x, kernel, bias, [stride, stride, stride], 'valid', dataFormat); let yExpectedShape: [number, number, number, number, number]; let yExpectedDataPerChannel: number[]; if (stride === 1) { yExpectedShape = [1, outChannels, 3, 3, 3]; // See validation Python code above. yExpectedDataPerChannel = [ 42., 46., 50., 58., 62., 66., 74., 78., 82., 106., 110., 114., 122., 126., 130., 138., 142., 146., 170., 174., 178., 186., 190., 194., 202., 206., 210. ]; } else if (stride === 2) { yExpectedShape = [1, outChannels, 2, 2, 2]; // See validation Python code above. yExpectedDataPerChannel = [42., 50., 74., 82., 170., 178., 202., 210.]; } for (let i = 0; i < yExpectedDataPerChannel.length; ++i) { yExpectedDataPerChannel[i] += biasScalarData[0]; } let yExpectedData: number[] = []; for (let i = 0; i < outChannels; ++i) { yExpectedData = yExpectedData.concat(yExpectedDataPerChannel); } let yExpected: Tensor = tensor5d(yExpectedData, yExpectedShape); if (dataFormat !== 'channelsFirst') { yExpected = tfc.transpose(yExpected, [0, 2, 3, 4, 1]); } expectTensorsClose(y, yExpected); }); } } } } }); describeMathCPU('Conv3D Layers: Symbolic', () => { const filtersArray = [1, 64]; const paddingModes: PaddingMode[] = [undefined, 'valid', 'same']; const dataFormats: DataFormat[] = ['channelsFirst', 'channelsLast']; const kernelSizes = [[2, 2, 2], [3, 4, 4]]; // In this test suite, `undefined` means strides is the same as kernelSize. const stridesArray = [undefined, 1]; for (const filters of filtersArray) { for (const padding of paddingModes) { for (const dataFormat of dataFormats) { for (const kernelSize of kernelSizes) { for (const stride of stridesArray) { const strides = stride || kernelSize; const testTitle = `filters=${filters}, kernelSize=${ JSON.stringify(kernelSize)}, ` + `strides=${JSON.stringify(strides)}, ` + `${dataFormat}, ${padding}`; it(testTitle, () => { const inputShape = dataFormat === 'channelsFirst' ? [2, 16, 11, 9, 9] : [2, 11, 9, 9, 16]; const symbolicInput = new tfl.SymbolicTensor('float32', inputShape, null, [], null); const conv3dLayer = tfl.layers.conv3d({ filters, kernelSize, strides, padding, dataFormat, }); const output = conv3dLayer.apply(symbolicInput) as tfl.SymbolicTensor; let outputRows: number; let outputCols: number; let outputDepth: number; if (stride === undefined) { // Same strides as kernelSize. outputRows = kernelSize[0] === 2 ? 5 : 3; if (padding === 'same') { outputRows++; } outputCols = kernelSize[1] === 2 ? 4 : 2; if (padding === 'same') { outputCols++; } outputDepth = kernelSize[2] === 2 ? 4 : 2; if (padding === 'same') { outputDepth++; } } else { // strides: 1. outputRows = kernelSize[0] === 2 ? 10 : 9; if (padding === 'same') { outputRows += kernelSize[0] - 1; } outputCols = kernelSize[1] === 2 ? 8 : 6; if (padding === 'same') { outputCols += kernelSize[1] - 1; } outputDepth = kernelSize[2] === 2 ? 8 : 6; if (padding === 'same') { outputDepth += kernelSize[1] - 1; } } let expectedShape: [number, number, number, number, number]; if (dataFormat === 'channelsFirst') { expectedShape = [2, filters, outputRows, outputCols, outputDepth]; } else { expectedShape = [2, outputRows, outputCols, outputDepth, filters]; } expect(output.shape).toEqual(expectedShape); expect(output.dtype).toEqual(symbolicInput.dtype); }); } } } } } it('Invalid filters leads to Error', () => { expect(() => tfl.layers.conv3d({filters: 2.5, kernelSize: 3})) .toThrowError(/filters.*positive integer.*2\.5\.$/); }); it('missing config.kernelSize throws exception', () => { // tslint:disable-next-line:no-any expect((filters: 1) => tfl.layers.conv3d({filters: 1} as any)) .toThrowError(/kernelSize/); }); it('scalar config.kernelSize shape does not throw exception', () => { expect(() => tfl.layers.conv3d({filters: 1, kernelSize: 1})) .not.toThrowError(); }); it('bad config.kernelSize shape throws exception', () => { expect(() => tfl.layers.conv3d({filters: 1, kernelSize: [1, 1]})) .toThrowError( /kernelSize argument must be an integer or tuple of 3 integers/); }); it('bad config.kernelSize shape throws exception', () => { expect(() => tfl.layers.conv2d({filters: 1, kernelSize: [1, 1, 1, 1]})) .toThrowError( /kernelSize to be number or number\[\] with length 1, 2, or 3/); }); it('missing config.filters throws exception', () => { // tslint:disable-next-line:no-any expect(() => tfl.layers.conv3d({kernelSize: 1} as any)) .toThrowError(/filters to be a 'number' > 0/); }); it('bad config.filters value throws exception', () => { // tslint:disable-next-line:no-any expect(() => tfl.layers.conv3d({kernelSize: 1, filters: 0} as any)) .toThrowError(/filters to be a 'number' > 0/); }); }); describeMathCPUAndGPU('Conv3D Layer: Tensor', () => { // # The following TensorFlow Python code is used to verify the results of // # the 3D convolution layer. // // ```python // import numpy as np // import tensorflow as tf // tf.enable_eager_execution() // // x = np.arange(64, dtype=np.float32).reshape(1, 4, 4, 4, 1) // layer = tf.keras.layers.Conv3D( // filters=1, kernel_size=(2, 2, 2), strides=(2, 2, 2), // use_bias=True, kernel_initializer='ones', bias_initializer='zeros') // outputs = layer(x) // outputs.numpy().flatten() // # Output: // # array([ 84., 100., 148., 164., 340., 356., 404., 420.], dtype=float32) // outputs.numpy().shape // # Output: // # (1, 2, 2, 2, 1) // # TensorFlow Keras (Python) does not have a CPU implementation for channels // # first yet, so the validation code uses channels last. Axes 1 and 4 would // # be swapped to get channels first. // ``` const x4by4by4Data = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63 ]; const useBiases = [false, true]; const biasInitializers: InitializerIdentifier[] = ['zeros', 'ones']; const activations: ActivationIdentifier[] = [null, 'linear', 'relu']; for (const useBias of useBiases) { for (const biasInitializer of biasInitializers) { for (const activation of activations) { const testTitle = `useBias=${useBias}, biasInitializer=${biasInitializer}, ` + `activation=${activation}`; it(testTitle, () => { const x = tensor5d(x4by4by4Data, [1, 1, 4, 4, 4]); const conv3dLayer = tfl.layers.conv3d({ filters: 1, kernelSize: [2, 2, 2], strides: [2, 2, 2], dataFormat: 'channelsFirst', useBias, kernelInitializer: 'ones', biasInitializer, activation }); const y = conv3dLayer.apply(x) as Tensor; // See validation Python code above. let yExpectedData = [84., 100., 148., 164., 340., 356., 404., 420.]; if (useBias && biasInitializer === 'ones') { yExpectedData = yExpectedData.map(element => element + 1); } if (activation === 'relu') { yExpectedData = yExpectedData.map(element => element >= 0 ? element : 0); } const yExpected = tensor5d(yExpectedData, [1, 1, 2, 2, 2]); expectTensorsClose(y, yExpected); }); } } } it('CHANNEL_LAST', () => { // Convert input to CHANNEL_LAST. const x = tfc.transpose(tensor5d(x4by4by4Data, [1, 1, 4, 4, 4]), [0, 2, 3, 4, 1]); const conv3dLayer = tfl.layers.conv3d({ filters: 1, kernelSize: [2, 2, 2], strides: [2, 2, 2], dataFormat: 'channelsLast', useBias: false, kernelInitializer: 'ones', activation: 'linear' }); const y = conv3dLayer.apply(x) as Tensor; // See validation Python code above. const yExpected = tensor5d( [84., 100., 148., 164., 340., 356., 404., 420.], [1, 2, 2, 2, 1]); expectTensorsClose(y, yExpected); }); // # The following TensorFlow Python code is used to verify the results of // # the 3D convolution layer with dilation. // // ```python // import numpy as np // import tensorflow as tf // tf.enable_eager_execution() // // np.random.seed(42) // x = np.random.rand(1, 4, 4, 4, 1) // layer = tf.keras.layers.Conv3D( // filters=1, kernel_size=(2, 2, 2), strides=1, dilation_rate=2, // use_bias=False, kernel_initializer='ones', activation='linear') // outputs = layer(x) // outputs.numpy().flatten() // # Output: // # array([2.91534395, 6.38913542, 2.78770771, 3.1383292 , 3.04194573, // # 3.59669644, 4.85877068, 3.16763418]) // outputs.numpy().shape // # Output: // # (1, 2, 2, 2, 1) // ``` const dilationRateValues: Array<number|[number, number, number]> = [2, [2, 2, 2]]; for (const dilationRate of dilationRateValues) { it(`CHANNEL_LAST, dilationRate=${dilationRate}`, () => { const x = tensor5d( [ 0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864, 0.15599452, 0.05808361, 0.86617615, 0.60111501, 0.70807258, 0.02058449, 0.96990985, 0.83244264, 0.21233911, 0.18182497, 0.18340451, 0.30424224, 0.52475643, 0.43194502, 0.29122914, 0.61185289, 0.13949386, 0.29214465, 0.36636184, 0.45606998, 0.78517596, 0.19967378, 0.51423444, 0.59241457, 0.04645041, 0.60754485, 0.17052412, 0.06505159, 0.94888554, 0.96563203, 0.80839735, 0.30461377, 0.09767211, 0.68423303, 0.44015249, 0.12203823, 0.49517691, 0.03438852, 0.9093204, 0.25877998, 0.66252228, 0.31171108, 0.52006802, 0.54671028, 0.18485446, 0.96958463, 0.77513282, 0.93949894, 0.89482735, 0.59789998, 0.92187424, 0.0884925, 0.19598286, 0.04522729, 0.32533033, 0.38867729, 0.27134903, 0.82873751, 0.35675333 ], [1, 4, 4, 4, 1]); const conv3dLayer = tfl.layers.conv3d({ filters: 1, kernelSize: [2, 2, 2], strides: 1, dataFormat: 'channelsLast', useBias: false, kernelInitializer: 'ones', activation: 'linear', dilationRate }); const y = conv3dLayer.apply(x) as Tensor; // See validation Python code above. const yExpected = tensor5d( [ 2.91534395, 6.38913542, 2.78770771, 3.1383292, 3.04194573, 3.59669644, 4.85877068, 3.16763418 ], [1, 2, 2, 2, 1]); expectTensorsClose(y, yExpected); }); } const explicitDefaultDilations: Array<number|[number, number, number]> = [1, [1, 1, 1]]; for (const explicitDefaultDilation of explicitDefaultDilations) { const testTitle = 'Explicit default dilation rate: ' + JSON.stringify(explicitDefaultDilation); it(testTitle, () => { const conv3dLayer = tfl.layers.conv3d({ filters: 1, kernelSize: [2, 2, 2], strides: [2, 2, 2], dataFormat: 'channelsFirst', useBias: false, kernelInitializer: 'ones', dilationRate: explicitDefaultDilation }); const x = tensor5d(x4by4by4Data, [1, 1, 4, 4, 4]); const y = conv3dLayer.apply(x) as Tensor; const yExpected = tensor5d( [84., 100., 148., 164., 340., 356., 404., 420.], [1, 1, 2, 2, 2]); expectTensorsClose(y, yExpected); }); } }); describeMathCPU('Conv2DTranspose: Symbolic', () => { const filtersArray = [1, 64]; const paddingModes: PaddingMode[] = [undefined, 'valid', 'same']; const kernelSizes = [2, [2, 2], [3, 4]]; const stridesArray = [undefined, 2]; for (const filters of filtersArray) { for (const padding of paddingModes) { for (const kernelSize of kernelSizes) { for (const strides of stridesArray) { const testTitle = `filters=${filters}, paddingMode=${padding},` + `kernelSize=${JSON.stringify(kernelSize)}, strides=${strides}`; it(testTitle, () => { const inputShape = [2, 11, 9, 16]; const x = new tfl.SymbolicTensor('float32', inputShape, null, [], null); const layer = tfl.layers.conv2dTranspose( {filters, kernelSize, padding, strides}); const y = layer.apply(x) as tfl.SymbolicTensor; let expectedShape: [number, number, number, number]; if (strides === undefined) { if (padding === 'valid' || padding === undefined) { if (kernelSize as number === 2 || util.arraysEqual(kernelSize as number[], [2, 2])) { expectedShape = [2, 12, 10, filters]; } else if (util.arraysEqual(kernelSize as number[], [3, 4])) { expectedShape = [2, 13, 12, filters]; } } else if (padding === 'same') { expectedShape = [2, 11, 9, filters]; } } else { if (padding === 'valid' || padding === undefined) { if (kernelSize as number === 2 || util.arraysEqual(kernelSize as number[], [2, 2])) { expectedShape = [2, 22, 18, filters]; } else if (util.arraysEqual(kernelSize as number[], [3, 4])) { expectedShape = [2, 23, 20, filters]; } } else if (padding === 'same') { expectedShape = [2, 22, 18, filters]; } } expect(y.shape).toEqual(expectedShape); }); } } } } it('Correct weight names', () => { const x = new tfl.SymbolicTensor('float32', [1, 2, 3, 4], null, [], null); const layer = tfl.layers.conv2dTranspose({filters: 2, kernelSize: [3, 3]}); layer.apply(x); // Let the layer build first. expect(layer.weights.length).toEqual(2); expect(layer.weights[0].name.indexOf('/kernel')).toBeGreaterThan(0); expect(layer.weights[1].name.indexOf('/bias')).toBeGreaterThan(0); }); }); describeMathCPUAndGPU('Conv2DTranspose: Tensor', () => { const dataFormats: DataFormat[] = ['channelsFirst', 'channelsLast']; const stridesArray = [2, [2, 2]]; for (const dataFormat of dataFormats) { for (const strides of stridesArray) { const testTitle = `filters=8, kernelSize=[2,2], padding=valid, strides=${strides}` + `dataFormat=${dataFormat}`; it(testTitle, () => { const filters = 8; const kernelSize = [2, 2]; const padding = 'valid'; const strides = 2; const layer = tfl.layers.conv2dTranspose({ filters, kernelSize, padding, strides, dataFormat, kernelInitializer: 'ones', biasInitializer: 'ones' }); const x = tfc.ones([2, 3, 4, 2]); const y = layer.apply(x) as Tensor; if (dataFormat === 'channelsLast') { expectTensorsClose(y, tfc.ones([2, 6, 8, 8]).mul(scalar(3))); } else { expectTensorsClose(y, tfc.ones([2, 8, 8, 4]).mul(scalar(4))); } }); } } }); describeMathCPU('Conv1D Layers: Symbolic', () => { const filtersArray = [1, 4]; const paddingModes: PaddingMode[] = [undefined, 'valid', 'same']; const stridesArray = [undefined, 1]; for (const filters of filtersArray) { for (const padding of paddingModes) { for (const strides of stridesArray) { const testTitle = `filters=${filters}, padding=${padding}, ` + `strides=${strides}`; it(testTitle, () => { const inputShape = [2, 8, 3]; const symbolicInput = new tfl.SymbolicTensor('float32', inputShape, null, [], null); const conv1dLayer = tfl.layers.conv1d({ filters, kernelSize: 2, strides, padding, dataFormat: 'channelsLast', }); const output = conv1dLayer.apply(symbolicInput) as tfl.SymbolicTensor; const expectedShape = [2, 7, filters]; if (padding === 'same') { expectedShape[1] = 8; } expect(output.shape).toEqual(expectedShape); expect(output.dtype).toEqual(symbolicInput.dtype); }); } } } it('bad config.kernelSize shape throws exception', () => { expect(() => tfl.layers.conv1d({filters: 1, kernelSize: [1, 1]})) .toThrowError(/kernelSize.*1/); }); }); describeMathCPUAndGPU('Conv1D Layer: Tensor', () => { const xLength4Data = [10, -30, -50, 70]; // In the most basic case, applying an all-ones convolutional kernel to // the 1D input above gives [-20, -80, 20]. Then adding all-ones bias to // it gives [-19, -79, 21]. const stridesValues = [1, 2]; const activations: ActivationIdentifier[] = ['linear', 'relu']; for (const strides of stridesValues) { for (const activation of activations) { const testTitle = `useBias=true, biasInitializer=ones, ` + `activation=${activation}; strides=${strides}`; it(testTitle, () => { const x = tensor3d(xLength4Data, [1, 4, 1]); const conv1dLayer = tfl.layers.conv1d({ filters: 1, kernelSize: 2, strides, dataFormat: 'channelsLast', useBias: true, kernelInitializer: 'ones', biasInitializer: 'ones', activation }); const y = conv1dLayer.apply(x) as Tensor; let yExpectedShape: [number, number, number]; let yExpectedData: number[]; if (strides === 1) { yExpectedShape = [1, 3, 1]; yExpectedData = [-19, -79, 21]; } else { yExpectedShape = [1, 2, 1]; yExpectedData = [-19, 21]; } if (activation === 'relu') { yExpectedData = yExpectedData.map(x => x > 0 ? x : 0); } const yExpected = tensor3d(yExpectedData, yExpectedShape); expectTensorsClose(y, yExpected); }); } } const dilationRates: Array<number|[number]> = [2, [2]]; for (const dilationRate of dilationRates) { it(`dilationRate = ${dilationRate}`, () => { const x = tensor3d( [ 0.0024236, 0.54829558, 0.47628448, 0.2971449, 0.7984293, 0.71802861, 0.53109141, 0.85882819 ], [1, 8, 1]); const conv1dLayer = tfl.layers.conv1d({ filters: 1, kernelSize: 2, strides: 1, useBias: true, kernelInitializer: 'ones', biasInitializer: 'ones', dilationRate, }); const y = conv1dLayer.apply(x) as Tensor; const yExpected = tensor3d( [1.478708, 1.8454404, 2.2747138, 2.0151734, 2.3295207, 2.5768569], [1, 6, 1]); expectTensorsClose(y, yExpected); }); } it('missing config.kernelSize throws exception', () => { // tslint:disable-next-line:no-any expect((filters: 1) => tfl.layers.conv1d({filters: 1} as any)) .toThrowError(/required key 'kernelSize' not in config/); }); it('bad config.kernelSize throws exception', () => { expect(() => tfl.layers.conv1d({filters: 1, kernelSize: [1, 1, 1]})) .toThrowError( /kernelSize argument must be an integer or tuple of 1 integers/); }); it('missing config.filters throws exception', () => { // tslint:disable-next-line:no-any expect(() => tfl.layers.conv1d({kernelSize: 1} as any)) .toThrowError(/filters to be a 'number' > 0/); }); it('bad config.filters throws exception', () => { // tslint:disable-next-line:no-any expect(() => tfl.layers.conv1d({kernelSize: 1, filters: 0} as any)) .toThrowError(/filters to be a 'number' > 0/); }); }); describeMathCPU('SeparableConv2D Layers: Symbolic', () => { const filtersArray = [1, 8]; const paddingModes: PaddingMode[] = [undefined, 'valid', 'same']; const dataFormats: DataFormat[] = ['channelsFirst', 'channelsLast']; const kernelSizes = [[2, 2], [3, 4]]; // In this test suite, `undefined` means strides is the same as kernelSize. const stridesArray = [undefined, 1]; const dilationRates = [undefined, 2]; for (const filters of filtersArray) { for (const padding of paddingModes) { for (const dataFormat of dataFormats) { for (const kernelSize of kernelSizes) { for (const stride of stridesArray) { for (const dilationRate of dilationRates) { const strides = stride || kernelSize; const testTitle = `filters=${filters}, kernelSize=${ JSON.stringify(kernelSize)}, ` + `strides=${JSON.stringify(strides)}, ` + `dataFormat=${dataFormat}, padding=${padding}, ` + `dilationRate=${dilationRate}`; it(testTitle, () => { const inputShape = dataFormat === 'channelsFirst' ? [2, 16, 11, 9] : [2, 11, 9, 16]; const symbolicInput = new tfl.SymbolicTensor( 'float32', inputShape, null, [], null); const layer = tfl.layers.separableConv2d({ filters, kernelSize, strides, padding, dataFormat, dilationRate, }); const output = layer.apply(symbolicInput) as tfl.SymbolicTensor; let outputRows: number; let outputCols: number; if (dilationRate == null) { if (stride === undefined) { // Same strides as kernelSize. outputRows = kernelSize[0] === 2 ? 5 : 3; if (padding === 'same') { outputRows++; } outputCols = kernelSize[1] === 2 ? 4 : 2; if (padding === 'same') { outputCols++; } } else { // strides: 1. outputRows = kernelSize[0] === 2 ? 10 : 9; if (padding === 'same') { outputRows += kernelSize[0] - 1; } outputCols = kernelSize[1] === 2 ? 8 : 6; if (padding === 'same') { outputCols += kernelSize[1] - 1; } } } else { if (padding === 'same') { if (stride === undefined) { // Same strides as kernelSize. outputRows = kernelSize[0] === 2 ? 6 : 4; outputCols = kernelSize[1] === 2 ? 5 : 3; } else { // strides: 1. outputRows = 11; outputCols = 9; } } else { if (stride === undefined) { // Same strides as kernelSize. outputRows = kernelSize[0] === 2 ? 5 : 3; outputCols = kernelSize[1] === 2 ? 4 : 1; } else { // strides: 1. outputRows = kernelSize[0] === 2 ? 9 : 7; outputCols = kernelSize[1] === 2 ? 7 : 3; } } } let expectedShape: [number, number, number, number]; if (dataFormat === 'channelsFirst') { expectedShape = [2, filters, outputRows, outputCols]; } else { expectedShape = [2, outputRows, outputCols, filters]; } expect(output.shape).toEqual(expectedShape); expect(output.dtype).toEqual(symbolicInput.dtype); }); } } } } } } it('Incorrect input rank throws error', () => { const layer = tfl.layers.separableConv2d({ filters: 1, kernelSize: [2, 2], strides: 1, }); const symbolicInput = new tfl.SymbolicTensor('float32', [2, 3, 4], null, [], null); expect(() => layer.apply(symbolicInput)).toThrowError(/rank 4/); }); it('Undefined channel axis throws error', () => { const layer = tfl.layers.separableConv2d({ filters: 1, kernelSize: [2, 2], strides: 1, }); const symbolicInput = new tfl.SymbolicTensor('float32', [1, , 2, 3, null], null, [], null); expect(() => layer.apply(symbolicInput)) .toThrowError(/channel dimension .* should be defined/); }); }); describeMathGPU('SeparableConv2D Layer: Tensor', () => { const x5by5Data = [ 1, 3, 5, 7, 9, 2, 4, 6, 8, 10, -1, -3, -5, -7, -9, -2, -4, -6, -8, -10, -1, 1, -1, 1, -1 ]; const dataFormats: DataFormat[] = ['channelsFirst', 'channelsLast']; const dilationRates: number[] = [undefined, 2]; const useBiases = [false, true]; const biasInitializers: InitializerIdentifier[] = ['zeros', 'ones']; const activations: ActivationIdentifier[] = [null, 'linear', 'relu']; for (const dataFormat of dataFormats) { for (const dilationRate of dilationRates) { for (const useBias of useBiases) { for (const biasInitializer of biasInitializers) { for (const activation of activations) { const testTitle = `dataFormat=${dataFormat}, ` + `dilationRate=${dilationRate}, ` + `useBias=${useBias}, biasInitializer=${biasInitializer}, ` + `activation=${activation}`; it(testTitle, () => { let x = tensor4d(x5by5Data, [1, 5, 5, 1]); if (dataFormat === 'channelsFirst') { x = tfc.transpose(x, [0, 3, 1, 2]); // NHWC -> NCHW. } const conv2dLayer = tfl.layers.separableConv2d({ depthMultiplier: 1, filters: 1, kernelSize: [2, 2], strides: 1, dilationRate, dataFormat, useBias, depthwiseInitializer: 'ones', pointwiseInitializer: 'ones', biasInitializer, activation }); const y = conv2dLayer.apply(x) as Tensor; let yExpectedData: number[]; if (dilationRate === 2) { yExpectedData = [0, 0, 0, 0, 0, 0, -8, -8, -16]; } else { yExpectedData = [ 10, 18, 26, 34, 2, 2, 2, 2, -10, -18, -26, -34, -6, -10, -14, -18 ]; } if (useBias && biasInitializer === 'ones') { yExpectedData = yExpectedData.map(element => element + 1); } if (activation === 'relu') { yExpectedData = yExpectedData.map(element => element >= 0 ? element : 0); } let yExpected = dilationRate === 2 ? tensor4d(yExpectedData, [1, 3, 3, 1]) : tensor4d(yExpectedData, [1, 4, 4, 1]); if (dataFormat === 'channelsFirst') { // NHWC -> NCHW. yExpected = tfc.transpose(yExpected, [0, 3, 1, 2]); } expectTensorsClose(y, yExpected); }); } } } } } it('missing config.kernelSize throws exception', () => { // tslint:disable-next-line:no-any expect((filters: 1) => tfl.layers.separableConv2d({filters: 1} as any)) .toThrowError(/kernelSize/); }); it('bad config.kernelSize throws exception', () => { expect( () => tfl.layers.separableConv2d({filters: 1, kernelSize: [1, 1, 1]})) .toThrowError(/kernelSize/); }); it('missing config.filters throws exception', () => { // tslint:disable-next-line:no-any expect(() => tfl.layers.separableConv2d({kernelSize: 1} as any)) .toThrowError(/filters/); }); it('bad config.filters throws exception', () => { // tslint:disable-next-line:no-any expect(() => tfl.layers.separableConv2d({kernelSize: 1, filters: 0} as any)) .toThrowError(/filters/); }); }); describeMathCPUAndGPU('Cropping2D Layer', () => { it('check with undefined channels type', () => { const layer = tfl.layers.cropping2D({cropping: [[1, 0], [1, 0]]}); const x = tensor4d( [ [[[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]]], ], [1, 3, 3, 1]); const y = tensor4d( [ [[[5], [6]], [[8], [9]]], ], [1, 2, 2, 1]); expectTensorsClose(layer.apply(x, null) as Tensor, y); }); it('check with channels last', () => { const layer = tfl.layers.cropping2D( {cropping: [[1, 1], [1, 1]], dataFormat: 'channelsLast'}); const x = tensor4d( [ [[[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]]], ], [1, 3, 3, 1]); const y = tensor4d( [ [[[5]]], ], [1, 1, 1, 1]); expectTensorsClose(layer.apply(x, null) as Tensor, y); }); it('check with channels first', () => { const layer = tfl.layers.cropping2D( {cropping: [[1, 1], [1, 1]], dataFormat: 'channelsFirst'}); const x = tensor4d( [ [[[1, 2, 3], [3, 4, 5], [6, 7, 8]]], ], [1, 1, 3, 3]); const y = tensor4d( [ [[[4]]], ], [1, 1, 1, 1]); expectTensorsClose(layer.apply(x, null) as Tensor, y); }); it('check with non-square tensor', () => { const layer = tfl.layers.cropping2D( {cropping: [[1, 1], [1, 1]], dataFormat: 'channelsFirst'}); const x = tensor4d( [ [[[1, 2, 3, 4], [3, 4, 5, 6], [6, 7, 8, 9]]], ], [1, 1, 3, 4]); const y = tensor4d( [ [[[4, 5]]], ], [1, 1, 1, 2]); expect(layer.computeOutputShape(x.shape)).toEqual(y.shape); expectTensorsClose(layer.apply(x, null) as Tensor, y); }); }); describeMathCPU('UpSampling2D Layer: Symbolic', () => { const dataFormats: DataFormat[] = ['channelsFirst', 'channelsLast']; const interpolatinFormats: InterpolationFormat[] = ['nearest', 'bilinear']; const sizes = [undefined, [2, 2]]; const undeterminedDimensionArray: string[] = [null, 'height', 'both']; for (const dataFormat of dataFormats) { for (const interpolation of interpolatinFormats) { for (const size of sizes) { for (const undeterminedDimension of undeterminedDimensionArray) { const testTitle = `size = ${size}, ${dataFormat}, ${interpolation}` + `undetermined dimension = ${ JSON.stringify(undeterminedDimension)}`; it(testTitle, () => { let inputShape: Shape; if (undeterminedDimension == null) { inputShape = dataFormat === 'channelsFirst' ? [2, 16, 11, 9] : [2, 11, 9, 16]; } else if (undeterminedDimension === 'height') { inputShape = dataFormat === 'channelsFirst' ? [2, 16, null, 9] : [2, null, 9, 16]; } else if (undeterminedDimension === 'both') { inputShape = dataFormat === 'channelsFirst' ? [2, 16, null, null] : [2, null, null, 16]; } const symbolicInput = new tfl.SymbolicTensor('float32', inputShape, null, [], null); const upSampling2dLayer = tfl.layers.upSampling2d({ size, dataFormat, interpolation, }); const output = upSampling2dLayer.apply(symbolicInput) as tfl.SymbolicTensor; let outputRows: number; let outputCols: number; if (size === undefined) { outputRows = 2; outputCols = 2; } else { outputRows = size[0]; outputCols = size[1]; } let expectedShape: [number, number, number, number]; if (undeterminedDimension == null) { if (dataFormat === 'channelsFirst') { outputRows *= inputShape[2]; outputCols *= inputShape[3]; expectedShape = [2, 16, outputRows, outputCols]; } else { outputRows *= inputShape[1]; outputCols *= inputShape[2]; expectedShape = [2, outputRows, outputCols, 16]; } } else if (undeterminedDimension === 'height') { if (dataFormat === 'channelsFirst') { outputCols *= inputShape[3]; expectedShape = [2, 16, null, outputCols]; } else { outputCols *= inputShape[2]; expectedShape = [2, null, outputCols, 16]; } } else if (undeterminedDimension === 'both') { if (dataFormat === 'channelsFirst') { expectedShape = [2, 16, null, null]; } else { outputCols *= inputShape[2]; expectedShape = [2, null, null, 16]; } } expect(output.shape).toEqual(expectedShape); }); } } } } }); describeMathCPUAndGPU('UpSampling2D Layer', () => { it('check with default values', () => { const layer = tfl.layers.upSampling2d({}); const x = tensor4d( [ [[[1], [2]], [[3], [4]]], ], [1, 2, 2, 1]); const y = tensor4d( [ [ [[1], [1], [2], [2]], [[1], [1], [2], [2]], [[3], [3], [4], [4]], [[3], [3], [4], [4]] ], ], [1, 4, 4, 1]); expectTensorsClose(layer.apply(x, null) as Tensor, y); }); it('channels last', () => { const layer = tfl.layers.upSampling2d({size: [2, 2], dataFormat: 'channelsLast'}); const x = tensor4d( [ [[[1], [2]], [[3], [4]]], ], [1, 2, 2, 1]); const y = tensor4d( [ [ [[1], [1], [2], [2]], [[1], [1], [2], [2]], [[3], [3], [4], [4]], [[3], [3], [4], [4]] ], ], [1, 4, 4, 1]); expectTensorsClose(layer.apply(x, null) as Tensor, y); }); it('channels first', () => { const layer = tfl.layers.upSampling2d({size: [2, 2], dataFormat: 'channelsFirst'}); const x = tensor4d( [ [[[1, 2], [3, 4]]], ], [1, 1, 2, 2]); const y = tensor4d( [ [[[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]]], ], [1, 1, 4, 4]); expectTensorsClose(layer.apply(x, null) as Tensor, y); }); it('varying input image sizes', () => { const layer = tfl.layers.upSampling2d({size: [2, 2], dataFormat: 'channelsLast'}); const x1 = tensor4d( [ [[[1], [2]], [[3], [4]]], ], [1, 2, 2, 1]); const y1 = tensor4d( [ [ [[1], [1], [2], [2]], [[1], [1], [2], [2]], [[3], [3], [4], [4]], [[3], [3], [4], [4]] ], ], [1, 4, 4, 1]); expectTensorsClose(layer.apply(x1, null) as Tensor, y1); const x2 = tensor4d( [ [[[1], [2]]], ], [1, 1, 2, 1]); const y2 = tensor4d( [ [ [[1], [1], [2], [2]], [[1], [1], [2], [2]], ], ], [1, 2, 4, 1]); expectTensorsClose(layer.apply(x2, null) as Tensor, y2); }); it('interpolation bilinear', () => { const layer = tfl.layers.upSampling2d({size: [2, 2], interpolation: 'bilinear'}); const x = tensor4d( [ [[[1], [2]], [[3], [4]]], ], [1, 2, 2, 1]); const y = tensor4d( [ [ [[1], [1.5], [2], [2]], [[2], [2.5], [3], [3]], [[3], [3.5], [4], [4]], [[3], [3.5], [4], [4]] ], ], [1, 4, 4, 1]); expectTensorsClose(layer.apply(x, null) as Tensor, y); }); it('interpolation nearest', () => { const layer = tfl.layers.upSampling2d( {size: [2, 2], dataFormat: 'channelsFirst', interpolation: 'nearest'}); const x = tensor4d( [ [[[1, 2], [3, 4]]], ], [1, 1, 2, 2]); const y = tensor4d( [ [[[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]]], ], [1, 1, 4, 4]); expectTensorsClose(layer.apply(x, null) as Tensor, y); }); }); describeMathCPU('Conv3DTranspose: Symbolic', () => { const filtersArray = [1, 64]; const paddingModes: PaddingMode[] = ['valid', 'same']; const kernelSizes = [[2, 2, 2], [3, 4, 4]]; const stridesArray = [1, 3]; for (const filters of filtersArray) { for (const padding of paddingModes) { for (const kernelSize of kernelSizes) { for (const strides of stridesArray) { const testTitle = `filters=${filters}, paddingMode=${padding},` + `kernelSize=${JSON.stringify(kernelSize)}, strides=${strides}`; it(testTitle, () => { const inputShape = [1, 2, 11, 9, 16]; const x = new tfl.SymbolicTensor('float32', inputShape, null, [], null); const layer = tfl.layers.conv3dTranspose( {filters, kernelSize, padding, strides}); const y = layer.apply(x) as tfl.SymbolicTensor; let expectedShape: [number, number, number, number, number]; if (strides === 1) { if (padding === 'same') { expectedShape = [1, 2, 11, 9, filters]; } else { if (kernelSize[0] === 2) { expectedShape = [1, 3, 12, 10, filters]; } else { expectedShape = [1, 4, 14, 12, filters]; } } } else if (strides === 3) { if (padding === 'same') { expectedShape = [1, 6, 33, 27, filters]; } else { if (kernelSize[0] === 2) { expectedShape = [1, 6, 33, 27, filters]; } else { expectedShape = [1, 6, 34, 28, filters]; } } } expect(y.shape).toEqual(expectedShape); }); } } } } it('Correct weight names', () => { const x = new tfl.SymbolicTensor('float32', [1, 2, 3, 4, 5], null, [], null); const layer = tfl.layers.conv3dTranspose({filters: 2, kernelSize: [3, 3, 3]}); layer.apply(x); // Let the layer build first. expect(layer.weights.length).toEqual(2); expect(layer.weights[0].name.indexOf('/kernel')).toBeGreaterThan(0); expect(layer.weights[1].name.indexOf('/bias')).toBeGreaterThan(0); }); }); describeMathCPUAndGPU('Conv3DTranspose: Tensor', () => { const dataFormats: DataFormat[] = ['channelsFirst', 'channelsLast']; const stridesArray = [1, 2]; for (const dataFormat of dataFormats) { for (const strides of stridesArray) { const testTitle = `filters=8, kernelSize=[2,2], padding=valid, strides=${strides}` + `dataFormat=${dataFormat}`; it(testTitle, () => { const filters = 8; const kernelSize = [2, 2, 2]; const padding = 'valid'; const strides = 2; const layer = tfl.layers.conv3dTranspose({ filters, kernelSize, padding, strides, dataFormat, kernelInitializer: 'ones', biasInitializer: 'ones' }); const x = tfc.ones([2, 3, 4, 5, 2]); const y = layer.apply(x) as Tensor; if (dataFormat === 'channelsLast') { expectTensorsClose(y, tfc.ones([2, 6, 8, 10, 8]).mul(scalar(3))); } else { expectTensorsClose(y, tfc.ones([2, 8, 8, 10, 4]).mul(scalar(4))); } }); } } });
the_stack
import { Map as ImmutableMap, Record } from 'immutable'; import { ClientType } from '@colony/colony-js'; import { Transaction, TRANSACTION_STATUSES } from '~immutable/index'; import reducer from '../transactions'; import { CoreTransactions, TransactionsListMap } from '../../state/index'; import { createTxAction, transactionSent, transactionHashReceived, transactionEstimateError, transactionReceiptError, transactionSendError, transactionSucceeded, transactionReceiptReceived, } from '../../actionCreators'; const testActions = (actions, initialState) => actions.reduce((state, [action, assertions]) => { const newState = reducer(state, action); if (typeof assertions === 'function') assertions(newState); return newState; }, initialState); describe(`core: reducers (transactions)`, () => { test('Initial state', () => { // @ts-ignore const newState = reducer(undefined, { type: 'NOT_SUPPORTED_BY_THIS_REDUCER', }); expect(newState.list).toEqual(ImmutableMap()); }); const eventData = { myEventParam: 123 }; const from = 'my wallet address'; const hash = 'my transaction hash'; const blockHash = 'blockHash'; const blockNumber = 123; const options = { gasPrice: 4 }; const params = [123]; const id = 'my transaction id'; const existingTxId = 'my existing tx id'; const context = ClientType.NetworkClient; const methodName = 'createColony'; const initialState = CoreTransactions({ list: ImmutableMap({ [existingTxId]: Transaction({ createdAt: new Date(2018, 0, 1), context, from, id, methodName, options, params, status: TRANSACTION_STATUSES.READY, }), }) as TransactionsListMap, }); // Actions const createdTx = createTxAction(id, from, { context, methodName, options, params, }); const sentTx = transactionSent(id); const hashReceived = transactionHashReceived(id, { hash, params, blockHash, blockNumber, }); // @ts-ignore const receiptReceived = transactionReceiptReceived(id, { receipt: { hash } }); // @ts-ignore const eventDataReceived = transactionSucceeded(id, { eventData }); const sendError = transactionSendError(id, new Error('oh no, send error')); const receiptError = transactionReceiptError( id, new Error('oh no, receipt error'), ); const estimateError = transactionEstimateError( id, new Error('oh no, estimate error'), ); test('Sends successfully', () => { testActions( [ [ createdTx, (state) => { // Ideally we should evaluate the state based on the whole map, // but jest has some unexpected results when using `toEqual` // with immutable maps. expect(state.list.size).toBe(2); const existingTx = state.list.get(existingTxId); expect(Record.isRecord(existingTx)).toBe(true); const expectedTx = initialState.list.get(existingTxId); expect(existingTx.toJS()).toEqual(expectedTx && expectedTx.toJS()); const tx = state.list.get(id); expect(Record.isRecord(tx)).toBe(true); expect(tx.toJS()).toEqual({ context, createdAt: expect.any(Date), error: undefined, eventData: undefined, from, gasLimit: undefined, gasPrice: undefined, group: undefined, hash: undefined, id, loadingRelated: false, methodName, options, params, receipt: undefined, /* * Initial status is set to `READY` */ status: 'READY', }); }, ], [ sentTx, (state) => { expect(state.list.size).toBe(2); const existingTx = state.list.get(existingTxId); expect(Record.isRecord(existingTx)).toBe(true); const expectedTx = initialState.list.get(existingTxId); expect(existingTx.toJS()).toEqual(expectedTx && expectedTx.toJS()); const tx = state.list.get(id); expect(Record.isRecord(tx)).toBe(true); expect(tx.toJS()).toEqual({ context, createdAt: expect.any(Date), error: undefined, eventData: undefined, from, gasLimit: undefined, gasPrice: undefined, group: undefined, hash: undefined, id, loadingRelated: false, methodName, options, params, receipt: undefined, /* * During sending the transaction is set to 'PENDING' */ status: 'PENDING', }); }, ], [ hashReceived, (state) => { expect(state.list.size).toBe(2); const existingTx = state.list.get(existingTxId); expect(Record.isRecord(existingTx)).toBe(true); const expectedTx = initialState.list.get(existingTxId); expect(existingTx.toJS()).toEqual(expectedTx && expectedTx.toJS()); const tx = state.list.get(id); expect(Record.isRecord(tx)).toBe(true); expect(tx.toJS()).toEqual({ context, createdAt: expect.any(Date), error: undefined, eventData: undefined, from, gasLimit: undefined, gasPrice: undefined, group: undefined, hash, // Hash should have been set id, loadingRelated: false, methodName, options, params, receipt: undefined, /* * During sending the transaction is set to 'PENDING' */ status: 'PENDING', }); }, ], [ receiptReceived, (state) => { expect(state.list.size).toBe(2); const existingTx = state.list.get(existingTxId); expect(Record.isRecord(existingTx)).toBe(true); const expectedTx = initialState.list.get(existingTxId); expect(existingTx.toJS()).toEqual(expectedTx && expectedTx.toJS()); const tx = state.list.get(id); expect(Record.isRecord(tx)).toBe(true); expect(tx.toJS()).toEqual({ context, createdAt: expect.any(Date), error: undefined, eventData: undefined, from, gasLimit: undefined, gasPrice: undefined, group: undefined, hash, id, loadingRelated: false, methodName, options, params, receipt: expect.any(Object), // should have been set status: 'PENDING', }); }, ], [ eventDataReceived, (state) => { expect(state.list.size).toBe(2); const existingTx = state.list.get(existingTxId); expect(Record.isRecord(existingTx)).toBe(true); const expectedTx = initialState.list.get(existingTxId); expect(existingTx.toJS()).toEqual(expectedTx && expectedTx.toJS()); const tx = state.list.get(id); expect(Record.isRecord(tx)).toBe(true); expect(tx.toJS()).toEqual({ context, createdAt: expect.any(Date), error: undefined, eventData, // should have been set from, gasLimit: undefined, gasPrice: undefined, group: undefined, hash, id, loadingRelated: false, methodName, options, params, receipt: expect.any(Object), /* * If it went through successfully, it's set to `SUCCEEDED` */ status: 'SUCCEEDED', }); }, ], ], initialState, ); }); test('Handles send error', () => { testActions( [ [createdTx], [ sendError, (state) => { expect(state.list.size).toBe(2); const existingTx = state.list.get(existingTxId); expect(Record.isRecord(existingTx)).toBe(true); const expectedTx = initialState.list.get(existingTxId); expect(existingTx.toJS()).toEqual(expectedTx && expectedTx.toJS()); const tx = state.list.get(id); expect(Record.isRecord(tx)).toBe(true); expect(tx.toJS()).toEqual({ context, createdAt: expect.any(Date), error: { type: 'SEND', message: 'oh no, send error', }, eventData: undefined, from, gasLimit: undefined, gasPrice: undefined, group: undefined, hash: undefined, id, loadingRelated: false, methodName, options, params, receipt: undefined, /* * If it failed, it's set to `failed`... obviously */ status: 'FAILED', }); }, ], ], initialState, ); }); test('Handles receipt error', () => { testActions( [ [createdTx], [sentTx], [hashReceived], [ receiptError, (state) => { expect(state.list.size).toBe(2); const existingTx = state.list.get(existingTxId); expect(Record.isRecord(existingTx)).toBe(true); const expectedTx = initialState.list.get(existingTxId); expect(existingTx.toJS()).toEqual(expectedTx && expectedTx.toJS()); const tx = state.list.get(id); expect(Record.isRecord(tx)).toBe(true); expect(tx.toJS()).toEqual({ context, createdAt: expect.any(Date), error: { type: 'RECEIPT', message: 'oh no, receipt error', }, eventData: undefined, from, gasLimit: undefined, gasPrice: undefined, group: undefined, hash, id, loadingRelated: false, methodName, options, params, receipt: undefined, /* * If it failed, it's set to `failed`... obviously */ status: 'FAILED', }); }, ], ], initialState, ); }); test('Handles estimate error', () => { testActions( [ [createdTx], [sentTx], [hashReceived], [receiptReceived], [ estimateError, (state) => { expect(state.list.size).toBe(2); const existingTx = state.list.get(existingTxId); expect(Record.isRecord(existingTx)).toBe(true); const expectedTx = initialState.list.get(existingTxId); expect(existingTx.toJS()).toEqual(expectedTx && expectedTx.toJS()); const tx = state.list.get(id); expect(Record.isRecord(tx)).toBe(true); expect(tx.toJS()).toEqual({ context, createdAt: expect.any(Date), error: { type: 'ESTIMATE', message: 'oh no, estimate error', }, eventData: undefined, from, gasLimit: undefined, gasPrice: undefined, group: undefined, hash, id, loadingRelated: false, methodName, options, params, receipt: expect.any(Object), /* * If it failed, it's set to `failed`... obviously */ status: 'FAILED', }); }, ], ], initialState, ); }); });
the_stack
import * as chai from 'chai' import chaiAsPromised from 'chai-as-promised' import { _importCryptoKey, importCryptoKey, WebCryptoKdf, deriveKeyCommitment, currySubtleFunction, getEncryptHelper, getDecryptionHelper, buildAlgorithmForKDF, } from '../src/index' import { WebCryptoEncryptionMaterial, WebCryptoDecryptionMaterial, WebCryptoAlgorithmSuite, AlgorithmSuiteIdentifier, KeyringTraceFlag, isValidCryptoKey, SignatureKey, VerificationKey, AwsEsdkJsCryptoKeyPair, AwsEsdkJsKeyUsage, } from '@aws-crypto/material-management' import { synchronousRandomValues, getWebCryptoBackend, getZeroByteSubtle, getNonZeroByteBackend, } from '@aws-crypto/web-crypto-backend' import { fromBase64 } from '@aws-sdk/util-base64-browser' chai.use(chaiAsPromised) const { expect } = chai declare const CryptoKey: CryptoKey describe('_importCryptoKey', () => { it('can import WebCryptoEncryptionMaterial with a algorithm suite without a KDF', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, material, ['encrypt']) expect(cryptoKey).to.be.instanceOf(CryptoKey) expect(isValidCryptoKey(cryptoKey, material)).to.equal(true) }) it('can import WebCryptoEncryptionMaterial with a algorithm suite with a KDF', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, material, ['deriveKey']) expect(cryptoKey).to.be.instanceOf(CryptoKey) expect(isValidCryptoKey(cryptoKey, material)).to.equal(true) }) it('can import WebCryptoDecryptionMaterial with a algorithm suite without a KDF', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const material = new WebCryptoDecryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, material, ['decrypt']) expect(cryptoKey).to.be.instanceOf(CryptoKey) expect(isValidCryptoKey(cryptoKey, material)).to.equal(true) }) it('can import WebCryptoDecryptionMaterial with a algorithm suite with a KDF', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) const material = new WebCryptoDecryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, material, ['deriveKey']) expect(cryptoKey).to.be.instanceOf(CryptoKey) expect(isValidCryptoKey(cryptoKey, material)).to.equal(true) }) }) describe('importCryptoKey', () => { it('can import when backend is isFullSupportWebCryptoBackend', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const cryptoKey = await importCryptoKey(backend, material, ['encrypt']) expect(cryptoKey).to.be.instanceOf(CryptoKey) expect(isValidCryptoKey(cryptoKey, material)).to.equal(true) }) it('can import when backend is mixed support', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const realBackend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(realBackend) /* Insuring that the backend support is mixed is complicated. * So I just make a mixed backend and pass that. */ const mixedSupportBackend = { nonZeroByteSubtle: subtle, zeroByteSubtle: subtle, } as any const mixedBackendCryptoKey = await importCryptoKey( mixedSupportBackend, material, ['encrypt'] ) expect(mixedBackendCryptoKey).to.not.be.instanceOf(CryptoKey) const { nonZeroByteCryptoKey, zeroByteCryptoKey } = mixedBackendCryptoKey as any expect(nonZeroByteCryptoKey).to.be.instanceOf(CryptoKey) expect(zeroByteCryptoKey).to.be.instanceOf(CryptoKey) expect(isValidCryptoKey(nonZeroByteCryptoKey, material)).to.equal(true) expect(isValidCryptoKey(zeroByteCryptoKey, material)).to.equal(true) }) }) describe('deriveKeyCommitment', () => { it('can derive commitment', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = new Uint8Array(suite.keyLengthBytes).fill(1) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, material, ['deriveKey']) const keyCommitment = await deriveKeyCommitment( subtle, material, cryptoKey, new Uint8Array(32) ) expect(keyCommitment).to.deep.equal( fromBase64('Ctu53IjHBCn5rUr4sfaOC8wqzDwxrKoMOJItVBX9+Xk=') ) }) it('can assert commitment', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 ) const material = new WebCryptoDecryptionMaterial(suite, {}) const udk = new Uint8Array(suite.keyLengthBytes).fill(1) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, material, ['deriveKey']) const commitKey = fromBase64('Ctu53IjHBCn5rUr4sfaOC8wqzDwxrKoMOJItVBX9+Xk=') const keyCommitment = await deriveKeyCommitment( subtle, material, cryptoKey, new Uint8Array(32), commitKey ) expect(keyCommitment).to.deep.equal(commitKey) }) it('Check for early return (Postcondition): Algorithm suites without commitment do not have a commitment.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 ) const material = new WebCryptoDecryptionMaterial(suite, {}) const udk = new Uint8Array(suite.keyLengthBytes).fill(1) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, material, ['deriveKey']) const keyCommitment = await deriveKeyCommitment( subtle, material, cryptoKey, new Uint8Array(32) ) expect(keyCommitment).to.deep.equal(undefined) }) it('Postcondition: Non-committing WebCrypto algorithm suites *must* not have a commitment.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 ) const material = new WebCryptoDecryptionMaterial(suite, {}) const udk = new Uint8Array(suite.keyLengthBytes).fill(1) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, material, ['deriveKey']) const commitKey = fromBase64('Ctu53IjHBCn5rUr4sfaOC8wqzDwxrKoMOJItVBX9+Xk=') await expect( deriveKeyCommitment( subtle, material, cryptoKey, new Uint8Array(32), commitKey ) ).to.rejectedWith(Error, 'Commitment not supported.') }) it('Precondition: Commit key requires 256 bits of entropy.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = new Uint8Array(suite.keyLengthBytes).fill(1) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, material, ['deriveKey']) await expect( deriveKeyCommitment(subtle, material, cryptoKey, new Uint8Array(31)) ).to.rejectedWith( Error, 'Nonce is not the correct length for committed algorithm suite.' ) }) it('Precondition: If material is WebCryptoDecryptionMaterial the key commitments *must* match.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 ) const udk = new Uint8Array(suite.keyLengthBytes).fill(1) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const commitKey = fromBase64('Ctu53IjHBCn5rUr4sfaOC8wqzDwxrKoMOJItVBX9+Xk=') const encryptionMaterial = new WebCryptoEncryptionMaterial( suite, {} ).setUnencryptedDataKey(udk, { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, }) const decryptionMaterial = new WebCryptoDecryptionMaterial( suite, {} ).setUnencryptedDataKey(udk, { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, }) const decryptCryptoKey = await _importCryptoKey( subtle, decryptionMaterial, ['deriveKey'] ) const encryptCryptoKey = await _importCryptoKey( subtle, encryptionMaterial, ['deriveKey'] ) await expect( deriveKeyCommitment( subtle, encryptionMaterial, encryptCryptoKey, new Uint8Array(32), commitKey ) ).to.rejectedWith(Error, 'Invalid arguments.') await expect( deriveKeyCommitment( subtle, decryptionMaterial, decryptCryptoKey, new Uint8Array(32), new Uint8Array(32) ) ).to.rejectedWith(Error, 'Commitment does not match.') }) }) describe('buildAlgorithmForKDF', () => { it('basic non-committing suite', () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) buildAlgorithmForKDF(suite, new Uint8Array(16)) }) it('basic committing suite', () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY ) buildAlgorithmForKDF(suite, new Uint8Array(32)) }) it('Precondition: Valid HKDF values must exist for browsers.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) const nonKdfSuite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) expect(() => buildAlgorithmForKDF(suite, undefined as any)).to.throw( 'Invalid HKDF values.' ) expect(() => buildAlgorithmForKDF(nonKdfSuite, new Uint8Array(16)) ).to.throw('Invalid HKDF values.') }) it('Precondition: The message ID length must match the specification.', () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) expect(() => buildAlgorithmForKDF(suite, new Uint8Array(15))).to.throw( 'Message id length does not match specification.' ) }) it('Precondition: The message id length must match the algorithm suite.', () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY ) expect(() => buildAlgorithmForKDF(suite, new Uint8Array(16))).to.throw( 'Message id length does not match specification.' ) }) }) describe('WebCryptoKdf', () => { it('returns a valid kdf key', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, material, ['deriveKey']) const { deriveKey } = await WebCryptoKdf( subtle, material, cryptoKey, ['encrypt'], new Uint8Array(16) ) expect(deriveKey).to.be.instanceOf(CryptoKey) expect(isValidCryptoKey(deriveKey, material)).to.equal(true) // for kdf... expect(deriveKey !== cryptoKey).to.equal(true) }) it('Check for early return (Postcondition): No WebCrypto KDF, just return the unencrypted data key.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, material, ['encrypt']) const { deriveKey } = await WebCryptoKdf( subtle, material, cryptoKey, ['encrypt'], new Uint8Array(16) ) expect(deriveKey).to.be.instanceOf(CryptoKey) expect(isValidCryptoKey(deriveKey, material)).to.equal(true) // for non-kdf... expect(deriveKey === cryptoKey).to.equal(true) }) it('Postcondition: The derived key must conform to the algorith suite specification.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const subtleHack = { deriveKey() { return {} as any }, } as any const cryptoKey = await _importCryptoKey(subtle, material, ['deriveKey']) await expect( WebCryptoKdf( subtleHack, material, cryptoKey, ['encrypt'], new Uint8Array(16) ) ).to.rejectedWith(Error) }) }) describe('currySubtleFunction', () => { it('can get encrypt', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const cryptoKey = await importCryptoKey(backend, material, ['encrypt']) material.setCryptoKey(cryptoKey, trace) const testInfo = currySubtleFunction(material, backend, 'encrypt') expect(testInfo).to.be.a('function') const { getSubtleEncrypt: testIvAad } = await testInfo(new Uint8Array(16)) expect(testIvAad).to.be.a('function') const iv = new Uint8Array(suite.ivLength) const aad = new Uint8Array(1) const testFunction = testIvAad(iv, aad) expect(testFunction).to.be.a('function') const test = await testFunction(new Uint8Array(16)) expect(test).to.be.instanceOf(ArrayBuffer) }) it('Precondition: The material must have a CryptoKey.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() // 'Material must have a CryptoKey.' expect(() => currySubtleFunction(material, backend, 'encrypt')).to.throw() }) it('Precondition: The cryptoKey and backend must match in terms of Mixed vs Full support.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) /* Insuring that the backend support is mixed is complicated. * So I just make a mixed backend and pass that. */ const mixedSupportBackend = { nonZeroByteSubtle: subtle, zeroByteSubtle: subtle, } as any /* I always want the cryptoKey to not match the backend. */ const cryptoKey = await _importCryptoKey(subtle, material, ['encrypt']) material.setCryptoKey(cryptoKey, trace) // 'CryptoKey vs WebCrypto backend mismatch.' expect(() => currySubtleFunction(mixedSupportBackend, backend, 'encrypt') ).to.throw() }) it('Precondition: The length of the IV must match the WebCryptoAlgorithmSuite specification.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() const cryptoKey = await importCryptoKey(backend, material, ['encrypt']) material.setCryptoKey(cryptoKey, trace) const testInfo = currySubtleFunction(material, backend, 'encrypt') expect(testInfo).to.be.a('function') const { getSubtleEncrypt: testIvAad } = await testInfo(new Uint8Array(16)) expect(testIvAad).to.be.a('function') const iv = new Uint8Array(suite.ivLength - 1) const aad = new Uint8Array(1) expect(() => testIvAad(iv, aad)).to.throw() }) it('can encrypt/decrypt 0 bytes', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() /* All of this _only_ matters in the case of a mixed backend. * So I force the issue. */ const mixedBackend = { nonZeroByteSubtle: getZeroByteSubtle(backend), zeroByteSubtle: getNonZeroByteBackend(backend), randomValues: backend.randomValues, } const cryptoKey = await importCryptoKey(mixedBackend, material, [ 'encrypt', 'decrypt', ]) material.setCryptoKey(cryptoKey, trace) const iv = new Uint8Array(suite.ivLength) const aad = new Uint8Array(1) const tagLengthBytes = suite.tagLength / 8 // Encrypt const testEncryptInfo = currySubtleFunction( material, mixedBackend, 'encrypt' ) const { getSubtleEncrypt: testEncryptIvAad } = await testEncryptInfo( new Uint8Array(1) ) const testEncryptFunction = testEncryptIvAad(iv, aad) const testEncryptedData = await testEncryptFunction(new Uint8Array(0)) // Because I encrypted 0 bytes, the data should _only_ be tagLength expect(testEncryptedData.byteLength).to.equal(tagLengthBytes) // Decrypt const testDecryptInfo = currySubtleFunction( material, mixedBackend, 'decrypt' ) const testDecryptIvAad = await testDecryptInfo(new Uint8Array(1)) const testDecryptFunction = testDecryptIvAad(iv, aad) const testDecryptedData = await testDecryptFunction( new Uint8Array(testEncryptedData) ) // Because I encrypted 0 bytes, the data should be 0 length expect(testDecryptedData.byteLength).to.equal(0) }) it('Precondition: The WebCrypto AES-GCM decrypt API expects the data *and* tag together.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const material = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) const backend = await getWebCryptoBackend() /* All of this _only_ matters in the case of a mixed backend. * So I force the issue. */ const mixedBackend = { nonZeroByteSubtle: getZeroByteSubtle(backend), zeroByteSubtle: getNonZeroByteBackend(backend), randomValues: backend.randomValues, } const cryptoKey = await importCryptoKey(mixedBackend, material, [ 'encrypt', 'decrypt', ]) material.setCryptoKey(cryptoKey, trace) const iv = new Uint8Array(suite.ivLength) const aad = new Uint8Array(1) const tagLengthBytes = suite.tagLength / 8 // Encrypt const testEncryptInfo = currySubtleFunction( material, mixedBackend, 'encrypt' ) const { getSubtleEncrypt: testEncryptIvAad } = await testEncryptInfo( new Uint8Array(1) ) const testEncryptFunction = testEncryptIvAad(iv, aad) const testEncryptedData = await testEncryptFunction(new Uint8Array(0)) // Because I encrypted 0 bytes, the data should _only_ be tagLength expect(testEncryptedData.byteLength).to.equal(tagLengthBytes) // Decrypt const testDecryptInfo = currySubtleFunction( material, mixedBackend, 'decrypt' ) const testDecryptIvAad = await testDecryptInfo(new Uint8Array(1)) const testDecryptFunction = testDecryptIvAad(iv, aad) for (let i = 0; tagLengthBytes > i; i++) { await expect( testDecryptFunction(new Uint8Array(testEncryptedData.slice(0, i))) ).to.eventually.rejectedWith(Error, 'Invalid data length.') } }) it('no kdf, simple backend, can encrypt/decrypt', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const encryptionMaterial = new WebCryptoEncryptionMaterial(suite, {}) const decryptionMaterial = new WebCryptoDecryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const encryptTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } const decryptTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } encryptionMaterial.setUnencryptedDataKey(udk, encryptTrace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, encryptionMaterial, [ 'encrypt', 'decrypt', ]) encryptionMaterial.setCryptoKey(cryptoKey, encryptTrace) decryptionMaterial.setCryptoKey(cryptoKey, decryptTrace) const info = synchronousRandomValues(16) const iv = synchronousRandomValues(suite.ivLength) const aad = synchronousRandomValues(5) const data = new Uint8Array([1, 2, 3, 4, 5]) const { getSubtleEncrypt } = await currySubtleFunction( encryptionMaterial, backend, 'encrypt' )(info) const ciphertext = await getSubtleEncrypt(iv, aad)(data) const plaintext = await ( await currySubtleFunction(decryptionMaterial, backend, 'decrypt')(info) )( iv, aad )(new Uint8Array(ciphertext)) expect(new Uint8Array(plaintext)).to.deep.equal(data) }) it('KDF, simple backend, can encrypt/decrypt', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) const encryptionMaterial = new WebCryptoEncryptionMaterial(suite, {}) const decryptionMaterial = new WebCryptoDecryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const encryptTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } const decryptTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } encryptionMaterial.setUnencryptedDataKey(udk, encryptTrace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, encryptionMaterial, [ 'deriveKey', ]) encryptionMaterial.setCryptoKey(cryptoKey, encryptTrace) decryptionMaterial.setCryptoKey(cryptoKey, decryptTrace) const info = synchronousRandomValues(16) const iv = synchronousRandomValues(suite.ivLength) const aad = synchronousRandomValues(5) const data = new Uint8Array([1, 2, 3, 4, 5]) const ciphertext = await ( await currySubtleFunction(encryptionMaterial, backend, 'encrypt')(info) ).getSubtleEncrypt( iv, aad )(data) const plaintext = await ( await currySubtleFunction(decryptionMaterial, backend, 'decrypt')(info) )( iv, aad )(new Uint8Array(ciphertext)) expect(new Uint8Array(plaintext)).to.deep.equal(data) }) it('no kdf, mixed backend, can encrypt/decrypt', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16 ) const encryptionMaterial = new WebCryptoEncryptionMaterial(suite, {}) const decryptionMaterial = new WebCryptoDecryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const encryptTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } const decryptTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } encryptionMaterial.setUnencryptedDataKey(udk, encryptTrace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) /* Insuring that the backend support is mixed is complicated. * So I just make a mixed backend and pass that. */ const mixedSupportBackend = { nonZeroByteSubtle: subtle, zeroByteSubtle: subtle, } as any const cryptoKey = await importCryptoKey( mixedSupportBackend, encryptionMaterial, ['encrypt', 'decrypt'] ) encryptionMaterial.setCryptoKey(cryptoKey, encryptTrace) decryptionMaterial.setCryptoKey(cryptoKey, decryptTrace) const messageId = synchronousRandomValues(16) const iv = synchronousRandomValues(suite.ivLength) const aad = synchronousRandomValues(5) const data = new Uint8Array([1, 2, 3, 4, 5]) const ciphertext = await ( await currySubtleFunction( encryptionMaterial, mixedSupportBackend, 'encrypt' )(messageId) ).getSubtleEncrypt( iv, aad )(data) const plaintext = await ( await currySubtleFunction( decryptionMaterial, mixedSupportBackend, 'decrypt' )(messageId) )( iv, aad )(new Uint8Array(ciphertext)) expect(new Uint8Array(plaintext)).to.deep.equal(data) const ciphertextZeroByteData = await ( await currySubtleFunction( encryptionMaterial, mixedSupportBackend, 'encrypt' )(messageId) ).getSubtleEncrypt( iv, aad )(new Uint8Array(0)) const plaintextZeroByteData = await ( await currySubtleFunction( decryptionMaterial, mixedSupportBackend, 'decrypt' )(messageId) )( iv, aad )(new Uint8Array(ciphertextZeroByteData)) expect(new Uint8Array(plaintextZeroByteData)).to.deep.equal( new Uint8Array(0) ) }) it('kdf, mixed backend, can encrypt/decrypt', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) const encryptionMaterial = new WebCryptoEncryptionMaterial(suite, {}) const decryptionMaterial = new WebCryptoDecryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const encryptTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } const decryptTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } encryptionMaterial.setUnencryptedDataKey(udk, encryptTrace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) /* Insuring that the backend support is mixed is complicated. * So I just make a mixed backend and pass that. */ const mixedSupportBackend = { nonZeroByteSubtle: subtle, zeroByteSubtle: subtle, } as any const cryptoKey = await importCryptoKey( mixedSupportBackend, encryptionMaterial, ['deriveKey'] ) encryptionMaterial.setCryptoKey(cryptoKey, encryptTrace) decryptionMaterial.setCryptoKey(cryptoKey, decryptTrace) const info = synchronousRandomValues(16) const iv = synchronousRandomValues(suite.ivLength) const aad = synchronousRandomValues(5) const data = new Uint8Array([1, 2, 3, 4, 5]) const ciphertext = await ( await currySubtleFunction( encryptionMaterial, mixedSupportBackend, 'encrypt' )(info) ).getSubtleEncrypt( iv, aad )(data) const plaintext = await ( await currySubtleFunction( decryptionMaterial, mixedSupportBackend, 'decrypt' )(info) )( iv, aad )(new Uint8Array(ciphertext)) expect(new Uint8Array(plaintext)).to.deep.equal(data) const ciphertextZeroByteData = await ( await currySubtleFunction( encryptionMaterial, mixedSupportBackend, 'encrypt' )(info) ).getSubtleEncrypt( iv, aad )(new Uint8Array(0)) const plaintextZeroByteData = await ( await currySubtleFunction( decryptionMaterial, mixedSupportBackend, 'decrypt' )(info) )( iv, aad )(new Uint8Array(ciphertextZeroByteData)) expect(new Uint8Array(plaintextZeroByteData)).to.deep.equal( new Uint8Array(0) ) }) }) // getEncryptHelper // getDecryptionHelper describe('getEncryptHelper/getDecryptionHelper', () => { it('encryption helpers without a signature', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) const encryptionMaterial = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const encryptTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } encryptionMaterial.setUnencryptedDataKey(udk, encryptTrace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, encryptionMaterial, [ 'deriveKey', ]) encryptionMaterial.setCryptoKey(cryptoKey, encryptTrace) const test = await getEncryptHelper(encryptionMaterial) expect(test.getEncryptInfo).to.be.a('function') expect(test.subtleSign).to.equal(undefined) expect(test.dispose).to.be.a('function') }) it('decryption helpers without a signature ', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) const decryptionMaterial = new WebCryptoDecryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const encryptTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } decryptionMaterial.setUnencryptedDataKey(udk, encryptTrace) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, decryptionMaterial, [ 'deriveKey', ]) decryptionMaterial.setCryptoKey(cryptoKey, encryptTrace) const test = await getDecryptionHelper(decryptionMaterial) expect(test.getDecryptInfo).to.be.a('function') expect(test.subtleVerify).to.equal(undefined) expect(test.dispose).to.be.a('function') }) it('encryption helpers with a signature', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) const encryptionMaterial = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const { signatureKey } = await sigKeys(suite) const encryptTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } encryptionMaterial .setUnencryptedDataKey(udk, encryptTrace) .setSignatureKey(signatureKey) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, encryptionMaterial, [ 'deriveKey', ]) encryptionMaterial.setCryptoKey(cryptoKey, encryptTrace) const test = await getEncryptHelper(encryptionMaterial) expect(test.getEncryptInfo).to.be.a('function') expect(test.subtleSign).to.be.a('function') expect(test.dispose).to.be.a('function') }) it('decryption helpers with a signature ', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) const decryptionMaterial = new WebCryptoDecryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const { verificationKey } = await sigKeys(suite) const decryptionTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } decryptionMaterial .setUnencryptedDataKey(udk, decryptionTrace) .setVerificationKey(verificationKey) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, decryptionMaterial, [ 'deriveKey', ]) decryptionMaterial.setCryptoKey(cryptoKey, decryptionTrace) const test = await getDecryptionHelper(decryptionMaterial) expect(test.getDecryptInfo).to.be.a('function') expect(test.subtleVerify).to.be.a('function') expect(test.dispose).to.be.a('function') }) it('Precondition: WebCryptoEncryptionMaterial must have a valid data key.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) const encryptionMaterial = new WebCryptoEncryptionMaterial(suite, {}) await expect(getEncryptHelper(encryptionMaterial)).to.rejectedWith(Error) }) it('Precondition: WebCryptoDecryptionMaterial must have a valid data key.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) const decryptionMaterial = new WebCryptoDecryptionMaterial(suite, {}) await expect(getDecryptionHelper(decryptionMaterial)).to.rejectedWith(Error) }) it('can verify what was signed', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) const decryptionMaterial = new WebCryptoDecryptionMaterial(suite, {}) const encryptionMaterial = new WebCryptoEncryptionMaterial(suite, {}) const udk = synchronousRandomValues(suite.keyLengthBytes) const { signatureKey, verificationKey } = await sigKeys(suite) const encryptTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } const decryptionTrace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } decryptionMaterial .setUnencryptedDataKey(udk, decryptionTrace) .setVerificationKey(verificationKey) encryptionMaterial .setUnencryptedDataKey(udk, encryptTrace) .setSignatureKey(signatureKey) const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const cryptoKey = await _importCryptoKey(subtle, encryptionMaterial, [ 'deriveKey', ]) encryptionMaterial.setCryptoKey(cryptoKey, encryptTrace) decryptionMaterial.setCryptoKey(cryptoKey, decryptionTrace) const { subtleSign } = await getEncryptHelper(encryptionMaterial) const { subtleVerify } = await getDecryptionHelper(decryptionMaterial) const data = new Uint8Array([1, 2, 3, 4, 5]) // Make Typescript happy if (!subtleSign || !subtleVerify) throw new Error('never') const sig = await subtleSign(data) const test = await subtleVerify(new Uint8Array(sig), data) expect(test).to.equal(true) }) }) /* A simple helper to get signature/verification keys. * Basically a copy from the cmm. */ async function sigKeys(suite: WebCryptoAlgorithmSuite) { const { signatureCurve: namedCurve } = suite if (!namedCurve) throw new Error('never') const backend = await getWebCryptoBackend() const subtle = getZeroByteSubtle(backend) const webCryptoAlgorithm = { name: 'ECDSA', namedCurve } const extractable = false const usages = ['sign', 'verify'] as AwsEsdkJsKeyUsage[] const format = 'raw' const { publicKey, privateKey } = (await subtle.generateKey( webCryptoAlgorithm, extractable, usages )) as AwsEsdkJsCryptoKeyPair const publicKeyBytes = await subtle.exportKey(format, publicKey) const compressPoint = SignatureKey.encodeCompressPoint( new Uint8Array(publicKeyBytes), suite ) const signatureKey = new SignatureKey(privateKey, compressPoint, suite) const verificationKey = new VerificationKey(publicKey, suite) return { signatureKey, verificationKey } }
the_stack
import { AnyDescriptorProto, DescriptorProto, DescriptorRegistry, EnumDescriptorProto, FieldDescriptorProto, FieldDescriptorProto_Label, FieldDescriptorProto_Type, FileDescriptorProto, MethodDescriptorProto, ScalarValueType, ServiceDescriptorProto, SymbolTable } from "@protobuf-ts/plugin-framework"; import * as yaml from 'yaml'; import { OpenAPIV3 } from "openapi-types"; import { createLocalTypeName } from "../local-type-name"; import { getMethod, HttpOption, Pattern } from "./gateway"; interface OpenAPIDoc { fileName: string, content: string, } export enum OpenAPIType { GATEWAY, TWIRP } /** * Generate twirp compliant OpenAPI doc * @param ctx * @param files * @param type */ export async function genOpenAPI(ctx: any, files: readonly FileDescriptorProto[], type: OpenAPIType) { const documents: OpenAPIDoc[] = []; files.forEach(file => { file.service.forEach((service) => { const document: OpenAPIV3.Document = { openapi: "3.0.3", info: { title: `${service.name}`, version: "1.0.0", description: genDescription(ctx, service), }, paths: type === OpenAPIType.TWIRP ? genTwirpPaths(ctx, file, service) : genGatewayPaths(ctx, file, service), components: genComponents(ctx, service.method), } const fileName = type === OpenAPIType.TWIRP ? `${service.name?.toLowerCase()}.twirp.openapi.yaml` : `${service.name?.toLowerCase()}.openapi.yaml` documents.push({ fileName, content: yaml.stringify(document), }); }) }) return documents; } /** * Generates OpenAPI Twirp URI paths * @param ctx * @param file * @param service */ function genTwirpPaths(ctx: any, file: FileDescriptorProto, service: ServiceDescriptorProto) { return service.method.reduce((paths, method) => { const description = genDescription(ctx, method); paths[`/${file.package ? file.package + "." : ""}${service.name}/${method.name}`] = { post: { summary: description, operationId: `${service.name}_${method.name}`, requestBody: { required: true, content: { "application/json": { schema: { $ref: genRef(ctx, method.inputType!) } } } }, responses: { "200": { description: "OK", content: { "application/json": { schema: { $ref: genRef(ctx, method.outputType!), } } } } } } } return paths; }, {} as OpenAPIV3.PathsObject) } /** * Generates OpenAPI Twrip Gateway URI paths * @param ctx * @param file * @param service */ function genGatewayPaths(ctx: any, file: FileDescriptorProto, service: ServiceDescriptorProto) { const registry = ctx.registry as DescriptorRegistry; /** * Build paths recursively * @param method * @param httpSpec * @param paths */ function buildPath(method: MethodDescriptorProto, httpSpec: HttpOption, paths: OpenAPIV3.PathsObject) { const httpMethod = getMethod(httpSpec) const description = genDescription(ctx, method); const pathItem = { [httpMethod]: { summary: description, operationId: `${service.name}_${method.name}`, } } as OpenAPIV3.PathItemObject const inputMessage = registry.resolveTypeName(method.inputType!) as DescriptorProto; const outPutMessage = registry.resolveTypeName(method.outputType!) as DescriptorProto; // All methods except GET have body if (httpMethod !== Pattern.GET) { pathItem[httpMethod]!.requestBody = genGatewayBody(ctx, httpSpec, inputMessage) } // All methods might have params pathItem[httpMethod]!.parameters = genGatewayParams(ctx, httpSpec, inputMessage) pathItem[httpMethod]!.responses = genGatewayResponse(ctx, httpSpec, outPutMessage) paths[`${httpSpec[httpMethod]}`] = pathItem; if (httpSpec.additional_bindings) { buildPath(method, httpSpec.additional_bindings, paths) } } return service.method.reduce((paths, method) => { const options = ctx.interpreter.readOptions(method); if (!options || options && !options["google.api.http"]) { return paths; } const httpSpec = options["google.api.http"] as HttpOption buildPath(method, httpSpec, paths); return paths; }, {} as OpenAPIV3.PathsObject) } /** * Generate OpenAPI Gateway Response * @param ctx * @param httpOptions * @param message */ function genGatewayResponse(ctx: any, httpOptions: HttpOption, message: DescriptorProto): OpenAPIV3.ResponsesObject { let schema: OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject = {}; if (httpOptions.responseBody) { schema = { type: "object", properties: { [httpOptions.responseBody]: { $ref: `#/components/schemas/${message.name}` } } } } else { schema = { $ref: `#/components/schemas/${message.name}` } } return { "200": { description: "OK", content: { "application/json": { schema, } } } } } /** * Generate OpenAPI Gateway Response * @param ctx * @param httpOptions * @param message */ function genGatewayBody(ctx: any, httpOptions: HttpOption, message: DescriptorProto): OpenAPIV3.RequestBodyObject { const schema: OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject = {} if (httpOptions.body === "*") { (schema as OpenAPIV3.ReferenceObject).$ref = `#/components/schemas/${message.name}` } else if (httpOptions.body) { const subField = message.field.find(field => field.name === httpOptions.body); if (!subField) { throw new Error(`the body field ${httpOptions.body} cannot be mapped to message ${message.name}`) } schema.properties = { [httpOptions.body]: genField(ctx, subField), } } return { required: true, content: { "application/json": { schema, } } } } /** * Generates OpenAPI Gateway Parameters * @param ctx * @param httpOptions * @param message */ function genGatewayParams(ctx: any, httpOptions: HttpOption, message: DescriptorProto): (OpenAPIV3.ReferenceObject | OpenAPIV3.ParameterObject)[] { const httpMethod = getMethod(httpOptions) const params = parseUriParams(httpOptions[httpMethod]) const urlParams = message.field .filter((field) => params.find((param) => param === field.name) ) .map((field) => { return { name: field.name, in: "path", required: true, schema: { ...genField(ctx, field) } } as OpenAPIV3.ParameterObject }) if (httpOptions.body === "*") { return urlParams } const queryString = message.field .filter((field) => field.name !== httpOptions.body && !params.find(param => param === field.name!) ) .map((field) => { return { name: field.name, in: "query", schema: { ...genField(ctx, field) } } as OpenAPIV3.ParameterObject }) return [ ...queryString, ...urlParams, ] } /** * Generates OpenAPI Components * @param ctx * @param methods */ function genComponents(ctx: any, methods: MethodDescriptorProto[]) { const components: OpenAPIV3.ComponentsObject = { schemas: {} }; methods.reduce((schemas, method) => { genSchema(ctx, schemas, method.inputType!); genSchema(ctx, schemas, method.outputType!); return schemas; }, components.schemas) return components; } /** * Generate OpenAPI Schemas * @param ctx * @param schemas * @param typeName */ function genSchema(ctx: any, schemas: OpenAPIV3.ComponentsObject["schemas"], typeName: string) { const registry = ctx.registry as DescriptorRegistry; const localName = localMessageName(ctx, typeName); if (!localName) { return; } const descriptor = registry.resolveTypeName(typeName) as DescriptorProto; if (schemas![localName]) { return; } // Handle OneOf if (descriptor.field.some((field) => registry.isUserDeclaredOneof(field))) { schemas![localName] = genOneOfType(ctx, descriptor); descriptor.oneofDecl.forEach((oneOfField, index) => { const oneOfTyName = `${localName}_${capitalizeFirstLetter(oneOfField.name!)}`; const oneOfFields = descriptor.field.filter(field => { return field.oneofIndex === index; }) schemas![oneOfTyName] = genOneOfTypeKind(ctx, descriptor, oneOfFields); }) } else { schemas![localName] = genType(ctx, descriptor); } descriptor.field.forEach((field) => { if (field.type !== FieldDescriptorProto_Type.MESSAGE || !registry.isMapField(field)) { return; } if (registry.isMapField(field)) { const entry = registry.resolveTypeName(field.typeName!) if (DescriptorProto.is(entry)) { const valueField = entry.field.find(fd => fd.number === 2); if (!valueField) { return; } if (valueField.type !== FieldDescriptorProto_Type.MESSAGE) { return; } field = valueField } } else if (registry.isSyntheticElement(descriptor)) { return; } genSchema(ctx, schemas, field.typeName!); }) } /** * Generate an OpenAPI type * @param ctx * @param message */ function genType(ctx: any, message: DescriptorProto): OpenAPIV3.SchemaObject { const description = genDescription(ctx, message) return { properties: genMessageProperties(ctx, message), description, } } /** * Generate a Protobuf to OpenAPI oneof type * @param ctx * @param message */ function genOneOfType(ctx: any, message: DescriptorProto): OpenAPIV3.SchemaObject { const description = genDescription(ctx, message) const oneOf = { allOf: [ { type: "object", properties: genMessageProperties(ctx, message), }, ] as (OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject)[], description, } message.oneofDecl.forEach((field) => { oneOf.allOf.push({ $ref: `#/components/schemas/${message.name}_${capitalizeFirstLetter(field.name!)}` }) }) return oneOf; } /** * Generate one of type * @param ctx * @param message * @param oneOfFields */ function genOneOfTypeKind(ctx: any, message: DescriptorProto, oneOfFields: FieldDescriptorProto[]): OpenAPIV3.SchemaObject { return { oneOf: oneOfFields.map((oneOf) => { return { type: "object", properties: { [oneOf.name!]: genField(ctx, oneOf), } } }) } } /** * Generate message properties * @param ctx * @param message */ function genMessageProperties(ctx: any, message: DescriptorProto): OpenAPIV3.SchemaObject["properties"] { const registry = ctx.registry as DescriptorRegistry; return message.field.reduce((fields, field) => { if (registry.isUserDeclaredOneof(field)) { return fields } fields![field.name!] = genField(ctx, field!) return fields }, {} as OpenAPIV3.SchemaObject["properties"]); } /** * Generates OpenAPI $ref * @param ctx * @param name */ function genRef(ctx: any, name: string) { const messageType = localMessageName(ctx, name) return `#/components/schemas/${messageType}` } /** * Generate field definition * @param ctx * @param field */ function genField(ctx: any, field: FieldDescriptorProto): OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject { let openApiType: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject const registry = ctx.registry as DescriptorRegistry; switch (field.type) { case FieldDescriptorProto_Type.DOUBLE: case FieldDescriptorProto_Type.FLOAT: case FieldDescriptorProto_Type.BOOL: case FieldDescriptorProto_Type.STRING: case FieldDescriptorProto_Type.FIXED32: case FieldDescriptorProto_Type.FIXED64: case FieldDescriptorProto_Type.INT32: case FieldDescriptorProto_Type.INT64: case FieldDescriptorProto_Type.SFIXED32: case FieldDescriptorProto_Type.SFIXED64: case FieldDescriptorProto_Type.SINT32: case FieldDescriptorProto_Type.SINT64: case FieldDescriptorProto_Type.UINT32: case FieldDescriptorProto_Type.UINT64: openApiType = { type: genScalar(field.type), } break; case FieldDescriptorProto_Type.BYTES: openApiType = { type: "array", items: { type: "integer", } } break; case FieldDescriptorProto_Type.ENUM: const enumType = registry.getEnumFieldEnum(field) openApiType = genEnum(enumType); break; case FieldDescriptorProto_Type.MESSAGE: // Map type if (registry.isMapField(field)) { const mapTypeValue = registry.getMapValueType(field) if (typeof mapTypeValue === "number") { const scalar = mapTypeValue as ScalarValueType; openApiType = { type: "object", additionalProperties: { type: genScalar(scalar) } } } else if (EnumDescriptorProto.is(mapTypeValue)) { openApiType = { type: "object", additionalProperties: { ...genEnum(mapTypeValue) } } } else if (DescriptorProto.is(mapTypeValue)) { openApiType = { type: "object", additionalProperties: { $ref: `#/components/schemas/${mapTypeValue.name}`, } } } else { throw new Error("map value not supported") } break } openApiType = { $ref: genRef(ctx, field.typeName!), } break default: throw new Error(`${field.name} of type ${field.type} not supported`) } const description = genDescription(ctx, field) if (field.label === FieldDescriptorProto_Label.REPEATED && !registry.isMapField(field)) { return { type: "array", items: openApiType, description: description || "", } } if (field.type !== FieldDescriptorProto_Type.MESSAGE) { (openApiType as OpenAPIV3.SchemaObject).description = description || ""; } return openApiType; } /** * Generates enum definition * @param enumType */ function genEnum(enumType: EnumDescriptorProto): OpenAPIV3.SchemaObject { return { type: 'string', enum: enumType.value.map((value) => { return value.name }) } } /** * Generate scalar * @param type */ function genScalar(type: FieldDescriptorProto_Type) { switch (type) { case FieldDescriptorProto_Type.BOOL: return "boolean" case FieldDescriptorProto_Type.DOUBLE: case FieldDescriptorProto_Type.FLOAT: return "number" case FieldDescriptorProto_Type.STRING: return "string" case FieldDescriptorProto_Type.FIXED32: case FieldDescriptorProto_Type.FIXED64: case FieldDescriptorProto_Type.INT32: case FieldDescriptorProto_Type.INT64: case FieldDescriptorProto_Type.SFIXED32: case FieldDescriptorProto_Type.SFIXED64: case FieldDescriptorProto_Type.SINT32: case FieldDescriptorProto_Type.SINT64: case FieldDescriptorProto_Type.UINT32: case FieldDescriptorProto_Type.UINT64: return "integer" default: throw new Error(`${type} is not a scalar value`) } } /** * Generates the description * @param ctx * @param descriptor */ function genDescription(ctx: any, descriptor: AnyDescriptorProto) { const registry = ctx.registry as DescriptorRegistry; const source = registry.sourceCodeComments(descriptor); const description = source.leading || source.trailing || ""; return description.trim(); } /** * Format protobuf name * @param ctx * @param name */ function localMessageName(ctx: any, name: string) { const registry = ctx.registry as DescriptorRegistry; const symbols = ctx.symbols as SymbolTable; const entry = symbols.find(registry.resolveTypeName(name!))!; if (!entry) { return ""; } return createLocalTypeName(entry.descriptor, registry); } function parseUriParams(uri: string) { return getMatches(uri, /{([a-zA-Z_0-9]+)}/g, 1) } function getMatches(str: string, regex: RegExp, index: number = 1) { const matches = []; let match; while (match = regex.exec(str)) { matches.push(match[index]); } return matches; } function capitalizeFirstLetter(str: string) { return str.charAt(0).toUpperCase() + str.slice(1); }
the_stack
import { gg } from "../../gg"; import { PanelComponent } from "./PanelComponent"; import { PanelConfig } from "./PanelConfig"; import { PanelStateEnum } from "./PanelStateEnum"; /** * 面板路由器 * * 面板结构如下: * * - 图层1 * - 面板1 * - 面板2 * - 图层2 * - 面板3 * - 面板4 * - ... * * 根据面板所以依附的图层节点的zIndex 来决定面板的显示前后顺序(zIndex大的图层会挡住zIndex小的图层) * * 本工具提供以下方法: * * * init * * preload * * load * * loadAsync * * show * * showAsync * * hide * * hideAsync * * destroy * * getPanelState * * @author caizhitao * @created 2020-11-28 09:51:33 */ export default class PanelRouter { private static Tag = "PanelRouter"; /** * 是否允许输出调试Log */ private _enabledLog: boolean = true; /** * 所有UI图层的根节点 */ private _rootNode: cc.Node = null; /** * 记录图层节点的Map * * key: 图层节点zIndex * value: 图层节点 */ private _layerNodeMap: Map<number, cc.Node> = new Map(); /** * 记录面板缓存的Map * * * key: 面板Prefab路径 * * value: 面板缓存(节点、状态) */ private _panelCacheMap: Map<string, PanelCache> = new Map(); /** * 初始化面板路由器 * * @param rootNode 图层根节点(此节点建议最好是扩充全屏的) * @param enableDebugLog 是否允许打印面板路由器操作日志 */ init(rootNode: cc.Node, enableDebugLog: boolean) { this._enabledLog = enableDebugLog; this._rootNode = rootNode; } /** * 预加载面板资源(只下载到本地,不加载解析到内存) */ preload(panelConfig: PanelConfig) { let preloadBundlePrefab = (bundle: cc.AssetManager.Bundle) => { let prefabPath = panelConfig.prefabPath.substring(panelConfig.prefabPath.indexOf("/") + 1); bundle.preload(prefabPath); }; let bundleName = panelConfig.prefabPath.substring(0, panelConfig.prefabPath.indexOf("/")); let bundle: cc.AssetManager.Bundle = cc.assetManager.getBundle(bundleName); if (bundle == null) { cc.assetManager.loadBundle(bundleName, (error: Error, bundle: cc.AssetManager.Bundle) => { preloadBundlePrefab(bundle); }); } else { preloadBundlePrefab(bundle); } } /** * (Promise)加载面板资源(加载到内存) */ loadAsync(panelConfig: PanelConfig): Promise<void> { return new Promise<void>((resolve, reject) => { this.load(panelConfig, (error: Error) => { error ? reject(error) : resolve(); }); }); } /** * 加载面板资源(加载到内存) */ load(panelConfig: PanelConfig, onCompleted: (error?: Error) => void) { let prefabPath = panelConfig.prefabPath; let panelCache = this._panelCacheMap.get(prefabPath); if (panelCache) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试加载面板", "面板已加载成功"); onCompleted(null); return; } this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试加载面板", "面板还不存在,将开始加载面板"); // 初始化面板状态并记录下来 panelCache = { node: null, prefab: null, state: PanelStateEnum.Loading, }; this._panelCacheMap.set(prefabPath, panelCache); // 开始加载面板 panelCache.state = PanelStateEnum.Loading; this._loadBundlePrefab(panelConfig, null, (error: Error, prefab: cc.Prefab) => { // 加载完毕后,需要在此获取面板状态 // 因为加载是一个过程,这个过程中,面板可能被销毁了等等之类,因此加载完毕后,重新获取面板状态 panelCache = this._panelCacheMap.get(prefabPath); if (error) { // 处理面板实际加载失败的逻辑 this._enabledLog && gg.logger.error(PanelRouter.Tag, prefabPath, "尝试加载面板", "加载面板失败", error); if (!panelCache) { this._enabledLog && gg.logger.warn(PanelRouter.Tag, prefabPath, "尝试加载面板", "当前已经找不到面板记录,可能面板加载过程中触发销毁,导致加载结束后找不到对应面板记录"); } else { if ( panelCache.state === PanelStateEnum.LoadFailure || panelCache.state === PanelStateEnum.LoadSuccess || panelCache.state === PanelStateEnum.Showing || panelCache.state === PanelStateEnum.Showed || panelCache.state === PanelStateEnum.Hiding || panelCache.state === PanelStateEnum.Hided ) { this._enabledLog && gg.logger.error(PanelRouter.Tag, prefabPath, "尝试加载面板", "面板状态异常,原则上不会出现这个状态", panelCache.state); } else { // 更新面板状态 panelCache.node = null; panelCache.prefab = null; panelCache.state = PanelStateEnum.LoadFailure; } } } else { // 处理面板实际加载成功的逻辑 this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试加载面板", "加载面板成功"); if (!panelCache) { this._enabledLog && gg.logger.warn(PanelRouter.Tag, prefabPath, "尝试加载面板", "当前已经找不到面板记录,可能面板加载过程中触发销毁,导致加载结束后找不到对应面板记录"); // 销毁 prefab prefab.decRef(); } else { if ( panelCache.state === PanelStateEnum.LoadFailure || panelCache.state === PanelStateEnum.LoadSuccess || panelCache.state === PanelStateEnum.Showing || panelCache.state === PanelStateEnum.Showed || panelCache.state === PanelStateEnum.Hiding || panelCache.state === PanelStateEnum.Hided ) { this._enabledLog && gg.logger.error(PanelRouter.Tag, prefabPath, "尝试加载面板", "面板状态异常,原则上不会出现这个状态", panelCache.state); } else { // 更新面板状态 panelCache.node = null; panelCache.prefab = prefab; panelCache.state = PanelStateEnum.LoadSuccess; // Prefab 引用 + 1 panelCache.prefab.addRef(); } } } onCompleted(error); }); } private _loadBundlePrefab( panelConfig: PanelConfig, onProgress: (finish: number, total: number, item: cc.AssetManager.RequestItem) => void, onCompleted: (error: Error, prefab: cc.Prefab) => void ) { let loadBundlePrefab = (bundle: cc.AssetManager.Bundle) => { let prefabPath = panelConfig.prefabPath.substring(panelConfig.prefabPath.indexOf("/") + 1); bundle.load(prefabPath, cc.Prefab, onProgress, (error: Error, prefab: cc.Prefab) => { onCompleted(error, prefab); }); }; let bundleName = panelConfig.prefabPath.substring(0, panelConfig.prefabPath.indexOf("/")); let bundle: cc.AssetManager.Bundle = cc.assetManager.getBundle(bundleName); if (bundle == null) { cc.assetManager.loadBundle(bundleName, (error: Error, bundle: cc.AssetManager.Bundle) => { loadBundlePrefab(bundle); }); } else { loadBundlePrefab(bundle); } } /** * (Promise)展示面板 * * @param option 展示面板的参数 */ showAsync(option: CommonPanelOption) { return new Promise<void>((resolve, reject) => { this.show({ panel: option.panel, data: option.data, onShowed: (error) => { error ? reject(error) : resolve(); }, }); }); } /** * 展示面板 * * @param option 展示面板的参数 */ show(option: ShowPanelOption) { let prefabPath = option.panel.prefabPath; let panelCache = this._panelCacheMap.get(prefabPath); if (!panelCache) { this._enabledLog && gg.logger.error(PanelRouter.Tag, prefabPath, "尝试展示面板", "面板还没有加载,不能展示"); option.onShowed && option.onShowed(new Error("show error")); return; } if (panelCache.state === PanelStateEnum.Loading) { this._enabledLog && gg.logger.error(PanelRouter.Tag, prefabPath, "尝试展示面板", "面板在加载中,不能展示"); option.onShowed && option.onShowed(new Error("show error")); return; } if (panelCache.state === PanelStateEnum.LoadFailure) { this._enabledLog && gg.logger.error(PanelRouter.Tag, prefabPath, "尝试展示面板", "面板加载失败,不能展示"); option.onShowed && option.onShowed(new Error("show error")); return; } if (panelCache.state === PanelStateEnum.LoadSuccess) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试展示面板", "面板已加载成功,将尝试展示面板"); this._showPanel(option, panelCache); return; } if (panelCache.state === PanelStateEnum.Showing) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试展示面板", "面板正在展示中"); this._showPanel(option, panelCache); return; } if (panelCache.state === PanelStateEnum.Showed) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试展示面板", "面板已展示"); this._showPanel(option, panelCache); return; } if (panelCache.state === PanelStateEnum.Hiding) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试展示面板", "面板在隐藏中,将停止隐藏动画,并立即开始展示"); this._showPanel(option, panelCache); return; } if (panelCache.state === PanelStateEnum.Hided) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试展示面板", "面板已隐藏,将重新展示"); this._showPanel(option, panelCache); return; } } private _showPanel(option: ShowPanelOption, panelCache: PanelCache) { if (panelCache.node == null) { // 获取面板层级节点 let panelLayerNode = this._layerNodeMap.get(option.panel.layerZIndex); if (panelLayerNode == null) { panelLayerNode = new cc.Node(); panelLayerNode.zIndex = option.panel.layerZIndex; // 为图层添加 Widget 组件,扩充至全屏尺寸 let widget: cc.Widget = panelLayerNode.addComponent(cc.Widget); widget.top = 0; widget.bottom = 0; widget.left = 0; widget.right = 0; widget.isAlignTop = true; widget.isAlignBottom = true; widget.isAlignLeft = true; widget.isAlignRight = true; widget.alignMode = cc.Widget.AlignMode.ON_WINDOW_RESIZE; // 将图层节点添加到根节点中 this._rootNode.addChild(panelLayerNode); // 缓存层级节点 this._layerNodeMap.set(option.panel.layerZIndex, panelLayerNode); } // 将面板加入到层级节点中 let panelNode = cc.instantiate(panelCache.prefab); panelNode.setPosition(cc.v2(0, 0)); panelNode.setParent(panelLayerNode); panelCache.node = panelNode; } panelCache.state = PanelStateEnum.Showing; panelCache.node.active = true; panelCache.node.getComponent(PanelComponent).show({ data: option.data, onShowed: () => { this._enabledLog && gg.logger.log(PanelRouter.Tag, option.panel.prefabPath, "尝试展示面板", "面板已经展示完成"); panelCache.state = PanelStateEnum.Showed; option.onShowed && option.onShowed(); }, }); } /** * (Promise)隐藏面板 * * @param option 隐藏面板的参数 */ hideAsync(option: CommonPanelOption) { return new Promise<void>((resolve, reject) => { this.hide({ panel: option.panel, data: option.data, onHided: (error) => { error ? reject(error) : resolve(); }, }); }); } /** * 隐藏面板 * * @param option 隐藏面板的参数 */ hide(option: HidePanelOption) { let prefabPath = option.panel.prefabPath; let panelCache = this._panelCacheMap.get(prefabPath); if (!panelCache) { this._enabledLog && gg.logger.error(PanelRouter.Tag, prefabPath, "尝试隐藏面板", "面板还没有加载,不能隐藏"); option.onHided && option.onHided(new Error("hide error")); return; } if (panelCache.state === PanelStateEnum.Loading) { this._enabledLog && gg.logger.error(PanelRouter.Tag, prefabPath, "尝试隐藏面板", "面板在加载中,不能隐藏"); option.onHided && option.onHided(new Error("hide error")); return; } if (panelCache.state === PanelStateEnum.LoadFailure) { this._enabledLog && gg.logger.error(PanelRouter.Tag, prefabPath, "尝试隐藏面板", "面板加载失败,不能隐藏"); option.onHided && option.onHided(new Error("hide error")); return; } if (panelCache.state === PanelStateEnum.LoadSuccess) { this._enabledLog && gg.logger.error(PanelRouter.Tag, prefabPath, "尝试隐藏面板", "面板已加载成功,但未展示,不能隐藏"); option.onHided && option.onHided(new Error("hide error")); return; } if (panelCache.state === PanelStateEnum.Showing) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试隐藏面板", "面板在展示中(可能正在执行展示动画),将停止展示并立即隐藏"); this._hidePanel(option, panelCache); return; } if (panelCache.state === PanelStateEnum.Showed) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试隐藏面板", "面板已展示,将立即隐藏"); this._hidePanel(option, panelCache); return; } if (panelCache.state === PanelStateEnum.Hiding) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试隐藏面板", "面板正在隐藏中"); this._hidePanel(option, panelCache); return; } if (panelCache.state === PanelStateEnum.Hided) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试隐藏面板", "面板已隐藏"); this._hidePanel(option, panelCache); return; } } private _hidePanel(option: HidePanelOption, panelCache: PanelCache) { panelCache.state = PanelStateEnum.Hiding; panelCache.node.getComponent(PanelComponent).hide({ data: option.data, onHided: () => { this._enabledLog && gg.logger.log(PanelRouter.Tag, option.panel.prefabPath, "尝试隐藏面板", "面板隐藏成功"); panelCache.state = PanelStateEnum.Hided; panelCache.node.active = false; option.onHided && option.onHided(); }, }); } /** * 销毁面板 * * @param option 销毁参数 */ destroy(option: CommonPanelOption) { let prefabPath = option.panel.prefabPath; let panel = this._panelCacheMap.get(prefabPath); if (!panel) { this._enabledLog && gg.logger.error(PanelRouter.Tag, prefabPath, "尝试销毁面板", "当前面板还不存在(建议检查为什么此时触发销毁方法)"); return; } if (panel.state === PanelStateEnum.Loading) { this._enabledLog && gg.logger.warn(PanelRouter.Tag, prefabPath, "尝试销毁面板", "面板在加载中时,将销毁面板资源(建议检查为什么此时触发了销毁方法)"); this._destroyPanel(panel, prefabPath); return; } if (panel.state === PanelStateEnum.LoadFailure) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试销毁面板", "面板加载已经失败,将销毁面板资源"); this._destroyPanel(panel, prefabPath); return; } if (panel.state === PanelStateEnum.LoadSuccess) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试销毁面板", "面板加载已经成功(但无后续操作),将销毁面板资源"); this._destroyPanel(panel, prefabPath); return; } if (panel.state === PanelStateEnum.Showing) { this._enabledLog && gg.logger.warn(PanelRouter.Tag, prefabPath, "尝试销毁面板", "面板在展示中(可能正在执行展示动画),将销毁面板资源(建议检查为什么此时触发了销毁方法)"); this._destroyPanel(panel, prefabPath); return; } if (panel.state === PanelStateEnum.Showed) { this._enabledLog && gg.logger.warn(PanelRouter.Tag, prefabPath, "尝试销毁面板", "面板已展示,将销毁面板资源(建议检查为什么此时触发了销毁方法)"); this._destroyPanel(panel, prefabPath); return; } if (panel.state === PanelStateEnum.Hiding) { this._enabledLog && gg.logger.warn(PanelRouter.Tag, prefabPath, "尝试销毁面板", "面板在隐藏中(可能正在执行隐藏动画),将销毁面板资源(建议检查为什么此时触发了销毁方法)"); this._destroyPanel(panel, prefabPath); return; } if (panel.state === PanelStateEnum.Hided) { this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试销毁面板", "面板已隐藏,将销毁面板资源"); this._destroyPanel(panel, prefabPath); return; } } private _destroyPanel(panelCache: PanelCache, prefabPath: string) { if (panelCache.node) { panelCache.node.destroy(); panelCache.node = null; } if (panelCache.prefab) { panelCache.prefab.decRef(); panelCache.prefab = null; } this._panelCacheMap.delete(prefabPath); this._enabledLog && gg.logger.log(PanelRouter.Tag, prefabPath, "尝试销毁面板", "面板销毁成功"); } /** * 获取面板当前状态 * * @returns 如果还没有创建或者已经销毁了,那么返回null,否则返回对应的状态 */ getPanelState(panelConfig: PanelConfig): PanelStateEnum { let panel = this._panelCacheMap.get(panelConfig.prefabPath); if (!panel) { return null; } return panel.state; } } interface PanelCache { /** * 面板节点(在面板状态为 Loading 和 LoadingFailure )的时候,节点是不存在的 */ node: cc.Node; /** * 面板 Prefab Asset */ prefab: cc.Prefab; /** * 面板状态 */ state: PanelStateEnum; } export interface CommonPanelOption { /** * 要操作的面板 */ panel: PanelConfig; /** * 操作面板时传入的参数 */ data?: any; } export interface ShowPanelOption extends CommonPanelOption { /** * 展示动画播完完毕之后回调(如果没有展示动画,则立即回调) * */ onShowed?( /** * 展示错误时,此参数存在 */ error?: Error ): void; } export interface HidePanelOption extends CommonPanelOption { /** * 隐藏动画播完完毕之后回调(如果没有隐藏动画,则立即回调) */ onHided?( /** * 隐藏错误时,此参数存在 */ error?: Error ): void; }
the_stack
import { TypeAssertion, PrimitiveTypeAssertion, PrimitiveValueTypeAssertion, RepeatedAssertion, SpreadAssertion, SequenceAssertion, OneOfAssertion, OptionalAssertion, EnumAssertion, ObjectAssertion, TypeAssertionMap, CodegenContext } from '../../types'; import { escapeString } from '../../lib/escape'; import { nvl2 } from './../util'; function formatTypeName(ty: TypeAssertion, ctx: CodegenContext, typeName: string) { if (typeName.includes('.') || ty.kind === 'symlink' || ty.kind === 'enum') { return generateCSharpCodeInner(ty, false, ctx); } return typeName; } function formatCSharpCodeDocComment(ty: TypeAssertion | string, nestLevel: number) { let code = ''; const indent = ' '.repeat(nestLevel); const docComment = typeof ty === 'string' ? ty : ty.docComment; if (docComment) { if (0 <= docComment.indexOf('\n')) { code += `${indent}/**\n${indent} ${ docComment .split('\n') .map(x => x.trimLeft()) .join(`\n${indent} `)}\n${indent} */\n`; } else { code += `${indent}/** ${docComment} */\n`; } } return code; } function formatMemberType(ty: TypeAssertion, ctx: CodegenContext): string { if (ty.typeName) { return formatTypeName(ty, ctx, ty.typeName); } else { switch (ty.kind) { case 'primitive': return generateCSharpCodePrimitive(ty, ctx); case 'primitive-value': return generateCSharpCodePrimitiveValue(ty, ctx); case 'repeated': return generateCSharpCodeRepeated(ty, ctx); case 'one-of': return generateCSharpCodeOneOf(ty, ctx); default: return 'object'; } } } function appendOptionalModifier(name: string) { switch (name) { case 'decimal': case 'int': case 'double': case 'bool': return `${name}?`; default: return name; } } function isNullableOneOf(ty: OneOfAssertion, ctx: CodegenContext) { const filtered = ty.oneOf.filter(x => !( x.kind === 'primitive' && (x.primitiveName === 'null' || x.primitiveName === 'undefined') || x.kind === 'primitive-value' && (x.value === null || x.value === void 0))); return (filtered.length === 1 && ty.oneOf.length !== 1 ? filtered[0] : null) ; } function generateCSharpCodePrimitive(ty: PrimitiveTypeAssertion, ctx: CodegenContext) { // TODO: Function, DateStr, DateTimeStr switch (ty.primitiveName) { case 'null': case 'undefined': return 'object'; case 'integer': return 'int'; case 'bigint': return 'decimal'; case 'number': return 'double'; case 'boolean': return 'bool'; default: return ty.primitiveName; } } function generateCSharpCodePrimitiveValue(ty: PrimitiveValueTypeAssertion, ctx: CodegenContext) { if (ty.value === null || ty.value === void 0) { return 'object'; } switch (typeof ty.primitiveName) { case 'bigint': return 'decimal'; default: switch (typeof ty.value) { case 'number': return 'double'; case 'string': return 'string'; case 'boolean': return 'bool'; default: return 'object'; } } } function generateCSharpCodeRepeated(ty: RepeatedAssertion, ctx: CodegenContext): string { return `${formatMemberType(ty.repeated, ctx)}[]`; } function generateCSharpCodeSpread(ty: SpreadAssertion, ctx: CodegenContext) { return ''; } function generateCSharpCodeSequence(ty: SequenceAssertion, ctx: CodegenContext) { return 'object[]'; } function generateCSharpCodeOneOf(ty: OneOfAssertion, ctx: CodegenContext) { const z = isNullableOneOf(ty, ctx); if (z) { return appendOptionalModifier(formatMemberType(z, ctx)); } else { return 'object'; } } function generateCSharpCodeOptional(ty: OptionalAssertion, ctx: CodegenContext) { return appendOptionalModifier(generateCSharpCodeInner(ty.optional, false, ctx)); } function generateCSharpCodeEnum(ty: EnumAssertion, ctx: CodegenContext) { return 'object'; } function addAttributes(ty: TypeAssertion, ctx: CodegenContext, typeName: string) { const attrs: string[] = []; let ty2: TypeAssertion = ty; if (ty2.kind !== 'optional') { switch (typeName) { case 'decimal': case 'int': case 'double': case 'bool': break; default: if (ty2.kind === 'one-of') { if (! isNullableOneOf(ty2, ctx)) { attrs.push('Required'); } } else { attrs.push('Required'); } break; } ty2 = ty; } switch (ty2.kind) { case 'primitive': { if (typeof ty2.minLength === 'number') { attrs.push(`MinLength(${ty2.minLength})`); } if (typeof ty2.maxLength === 'number') { attrs.push(`MaxLength(${ty2.maxLength})`); } if (ty2.minValue !== null && ty2.minValue !== void 0 || ty2.maxValue !== null && ty2.maxValue !== void 0) { switch (ty2.primitiveName) { case 'string': attrs.push(`Range(typeof(string), "${ nvl2(ty2.minValue, x => escapeString(x), '')}", "${ nvl2(ty2.maxValue, x => escapeString(x), '\\U00010FFFF')}")`); break; case 'bigint': attrs.push(`Range(typeof(decimal), ${ nvl2(ty2.minValue, x => `new decimal(@"${String(x)}").ToString()`, 'Decimal.MinValue')}, ${ nvl2(ty2.maxValue, x => `new decimal(@"${String(x)}").ToString()`, 'Decimal.MaxValue')})`); break; case 'integer': attrs.push(`Range(${ nvl2(ty2.minValue, x => `(int)${String(x)}`, 'Int32.MinValue')}, ${ nvl2(ty2.maxValue, x => `(int)${String(x)}`, 'Int32.MaxValue')})`); break; case 'number': attrs.push(`Range(${ nvl2(ty2.minValue, x => `(double)${String(x)}`, 'Double.MinValue')}, ${ nvl2(ty2.maxValue, x => `(double)${String(x)}`, 'Double.MaxValue')})`); break; } } if (ty2.pattern) { attrs.push(`RegularExpression(@"${ty2.pattern.source.replace(/"/g, '""')}")`); } } break; case 'repeated': { if (typeof ty2.min === 'number') { attrs.push(`MinLength(${ty2.min})`); } if (typeof ty2.max === 'number') { attrs.push(`MaxLength(${ty2.max})`); } } break; } if (0 < attrs.length) { return `[${attrs.join(', ')}]\n${' '.repeat(ctx.nestLevel + 1)}`; } else{ return ''; } } function generateCSharpCodeObject(ty: ObjectAssertion, isInterface: boolean, ctx: CodegenContext) { const sep = '\n\n'; const memberLines = ty.members.filter(x => !(x[2])) .map(x => { const typeName = x[1].typeName ? formatTypeName(x[1], {...ctx, nestLevel: ctx.nestLevel + 1}, x[1].typeName) : generateCSharpCodeInner(x[1], false, {...ctx, nestLevel: ctx.nestLevel + 1}); return ( `${formatCSharpCodeDocComment(x[3] || '', ctx.nestLevel + 1)}${ ' '.repeat(ctx.nestLevel + 1)}${addAttributes(x[1], ctx, typeName)}public ${ typeName} ${x[0]} { get; set; }` ); }); if (memberLines.length === 0) { return (`\n${ ' '.repeat(ctx.nestLevel)}{\n${ ' '.repeat(ctx.nestLevel)}}` ); } return (`\n${ ' '.repeat(ctx.nestLevel)}{\n${memberLines.join(sep)}\n${ ' '.repeat(ctx.nestLevel)}}` ); } function generateCSharpCodeInner(ty: TypeAssertion, isInterface: boolean, ctx: CodegenContext): string { switch (ty.kind) { case 'never': case 'any': case 'unknown': return 'object'; case 'primitive': return generateCSharpCodePrimitive(ty, ctx); case 'primitive-value': return generateCSharpCodePrimitiveValue(ty, ctx); case 'repeated': return generateCSharpCodeRepeated(ty, ctx); case 'spread': return generateCSharpCodeSpread(ty, ctx); case 'sequence': return generateCSharpCodeSequence(ty, ctx); case 'one-of': return generateCSharpCodeOneOf(ty, ctx); case 'optional': return generateCSharpCodeOptional(ty, ctx); case 'enum': return generateCSharpCodeEnum(ty, ctx); case 'object': return generateCSharpCodeObject(ty, isInterface, ctx); case 'symlink': if (ctx.schema?.has(ty.symlinkTargetName)) { const target = ctx.schema.get(ty.symlinkTargetName); switch (target?.ty.kind) { case 'enum': return 'object'; } } return ty.symlinkTargetName; case 'operator': throw new Error(`Unexpected type assertion: ${(ty as any).kind}`); default: throw new Error(`Unknown type assertion: ${(ty as any).kind}`); } } export function generateCSharpCode(schema: TypeAssertionMap): string { let code = `using System.ComponentModel.DataAnnotations; namespace Tynder.UserSchema { `; const ctx: CodegenContext = { nestLevel: 1, schema, }; for (const ty of schema.entries()) { const indent0 = ' '.repeat(ctx.nestLevel); if (ty[1].ty.kind === 'object') { // nothing to do } else if (ty[1].ty.kind === 'enum') { // nothing to do } else if (ty[1].ty.kind === 'never' && ty[1].ty.passThruCodeBlock) { // nothing to do } else { code += formatCSharpCodeDocComment(ty[1].ty, ctx.nestLevel); let tyName = 'System.Object'; switch (ty[1].ty.kind) { case 'primitive': switch (ty[1].ty.primitiveName) { case 'integer': tyName = 'System.Int32'; break; case 'bigint': tyName = 'System.Decimal'; break; case 'number': tyName = 'System.Double'; break; case 'boolean': tyName = 'System.Boolean'; break; case 'string': tyName = 'System.String'; break; } break; case 'primitive-value': if (ty[1].ty.value !== null && ty[1].ty.value !== void 0) { switch (typeof ty[1].ty.primitiveName) { case 'bigint': tyName = 'System.Decimal'; break; default: switch (typeof ty[1].ty.value) { case 'number': tyName = 'System.Double'; break; case 'boolean': tyName = 'System.Boolean'; break; case 'string': tyName = 'System.String'; break; } } } break; } code += `${indent0}using ${ty[0]} = ${tyName};\n\n`; } } let isFirst = true; for (const ty of schema.entries()) { const accessModifier = ty[1].exported ? 'public' : 'public'; const indent0 = ' '.repeat(ctx.nestLevel); const indent1 = ' '.repeat(ctx.nestLevel + 1); if (ty[1].ty.kind === 'object' || ty[1].ty.kind === 'enum') { if (isFirst) { isFirst = false; code += '\n'; } else { code += '\n\n'; } code += formatCSharpCodeDocComment(ty[1].ty, ctx.nestLevel); } if (ty[1].ty.kind === 'object') { code += `${indent0}${accessModifier} class ${ty[0]}${ ty[1].ty.baseTypes && ty[1].ty.baseTypes.length ? ` : ${ ty[1].ty.baseTypes .filter(x => x.typeName) .map(x => formatTypeName(x, {...ctx, nestLevel: ctx.nestLevel + 1}, x.typeName as string)) .join(', ')}` : ''} ${ generateCSharpCodeInner(ty[1].ty, true, ctx)}\n`; } else if (ty[1].ty.kind === 'enum') { let value: number | null = 0; code += `${indent0}${accessModifier} static class ${ty[0]}\n${indent0}{\n${ ty[1].ty.values .map(x => `${ formatCSharpCodeDocComment(x[2] || '', ctx.nestLevel + 1)}${ indent1}${(() => { if (value !== null && x[1] === value) { value++; return `public static double ${x[0]} { get { return ${x[1]}; } }`; } else { if (typeof x[1] === 'number') { value = x[1] + 1; return `public static double ${x[0]} { get { return ${x[1]}; } }`; } else { return `public static string ${x[0]} { get { return "${escapeString(x[1])}"; } }`; } } })()}`) .join('\n\n')}\n${indent0}}\n`; } else if (ty[1].ty.kind === 'never' && ty[1].ty.passThruCodeBlock) { // nothing to do } else { // nothing to do } } return code + '}\n'; }
the_stack
import { Configs, Result, KubernetesObject, kubernetesObjectResult, SOURCE_PATH_ANNOTATION, SOURCE_INDEX_ANNOTATION, ID_ANNOTATION, LEGACY_SOURCE_PATH_ANNOTATION, LEGACY_SOURCE_INDEX_ANNOTATION, LEGACY_ID_ANNOTATION, } from 'kpt-functions'; import { isResourceHierarchy as isV3ResourceHierarchy, ResourceHierarchy as V3ResourceHierarchy, } from './gen/com.google.cloud.blueprints.v1alpha3'; import { isResourceHierarchy as isV2ResourceHierarchy, ResourceHierarchy as V2ResourceHierarchy, } from './gen/dev.cft.v1alpha2'; import { isResourceHierarchy as isV1ResourceHierarchy, ResourceHierarchy as V1ResourceHierarchy, } from './gen/dev.cft.v1alpha1'; import { FolderList } from './gen/com.google.cloud.cnrm.resourcemanager.v1beta1'; import { ObjectMeta } from 'kpt-functions/dist/src/gen/io.k8s.apimachinery.pkg.apis.meta.v1'; // Representation of a node in the hierarchy tree interface HierarchyNode { children: HierarchyNode[]; parent?: HierarchyNode; config?: KubernetesObject; kind?: string; name: string; } export interface Annotations { [key: string]: string; } /** * Entrypoint for kpt function business logic. See `usage` field for more details. * * @param configs In-memory document store for Kubernetes objects */ export async function generateFolders(configs: Configs) { configs.get(isV1ResourceHierarchy).forEach((hierarchy) => { configs.addResults(oldHierarchyWarning(hierarchy)); const layers: string[] = hierarchy.spec.layers; // Root node is the organization const root: HierarchyNode = { children: [], kind: 'Organization', name: `${hierarchy.spec.organization}`, // Annotation expects string type }; // Represent results as a binary tree const errorResult = generateV1HierarchyTree(root, layers, 0, hierarchy, []); // Report any errors; create configs + delete ResourceHierarchy resource if // no errors reported. if (errorResult) { configs.addResults(errorResult); } else { insertConfigs(root, configs); } }); // both v2 and v3 ResourceHierarchy generates the same folder hierarchy except v3 uses native KCC refs [ ...configs.get(isV3ResourceHierarchy), ...configs.get(isV2ResourceHierarchy), ].forEach((hierarchy) => { // if v2 add warning to upgrade if (isV2ResourceHierarchy(hierarchy)) { configs.addResults(oldHierarchyWarning(hierarchy)); } if ( hierarchy.spec.parentRef === undefined || hierarchy.spec.parentRef.external === undefined ) { configs.addResults(badParentErrorResult(hierarchy)); return; } if ( hierarchy.spec.parentRef.kind !== undefined && !['Organization', 'Folder'].includes(hierarchy.spec.parentRef.kind) ) { configs.addResults(badParentKindErrorResult(hierarchy)); return; } try { generateHierarchyTree(hierarchy, configs); } catch (e) { if (e instanceof MissingSubteeError) { configs.addResults(missingSubtreeErrorResult(e.message, hierarchy)); } else { throw e; } } }); } /** * Generate a warning for a v1/v2 hierarchy to upgrade to v3 * @param hierarchy The old hierarchy */ export function oldHierarchyWarning(hierarchy: KubernetesObject): Result { return kubernetesObjectResult( `ResourceHierarchy ${hierarchy.metadata.name} references an older Resource Hierarchy GroupVersion. Latest GroupVersion is blueprints.cloud.google.com/v1alpha3.`, hierarchy, undefined, 'warn' ); } /** * Generate an error for a hierarchy with an undefined parentRef * @param hierarchy The hierarchy to yield an error for */ export function badParentErrorResult(hierarchy: KubernetesObject): Result { return kubernetesObjectResult( `ResourceHierarchy ${hierarchy.metadata.name} has an undefined parentRef`, hierarchy, undefined, 'error' ); } /** * Generate an error for a hierarchy with an unsupported parentRef kind * @param hierarchy The hierarchy to yield an error for */ export function badParentKindErrorResult(hierarchy: KubernetesObject): Result { return kubernetesObjectResult( `ResourceHierarchy ${hierarchy.metadata.name} has an unsupported parentRef kind`, hierarchy, undefined, 'error' ); } /** * Generate an error for a hierarchy with a missing subtree * @param hierarchy The hierarchy to yield a missing subtree */ export function missingSubtreeErrorResult( subtree: string, hierarchy: KubernetesObject ): Result { return kubernetesObjectResult( `ResourceHierarchy ${hierarchy.metadata.name} references non-existent subtree "${subtree}"`, hierarchy, undefined, 'error' ); } class MissingSubteeError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, new.target.prototype); this.name = MissingSubteeError.name; } } /** * Creates a copy of the annotations object and removes annotations that generated * resources do not inherit from the ResourceHierarchy resource. * @param annotations The KRM annotations structure. * @returns The copy of annotations with non-inheritable keys removed. */ function filterNonInheritableAnnotations( annotations: Annotations ): Annotations { const copy: Annotations = { ...annotations }; delete copy['config.kubernetes.io/local-config']; delete copy['config.k8s.io/function']; // Do not inherit kpt SDK's internal annotations. delete copy[ID_ANNOTATION]; delete copy[LEGACY_ID_ANNOTATION]; delete copy[SOURCE_PATH_ANNOTATION]; delete copy[LEGACY_SOURCE_PATH_ANNOTATION]; delete copy[SOURCE_INDEX_ANNOTATION]; delete copy[LEGACY_SOURCE_INDEX_ANNOTATION]; return copy; } /** * Creates a representation of the resulting folder hierarchy from the * ResourceHierarchy object in a tree data structure. Each node contains the * corresponding config to generate. * * @param hierarchy The ResourceHierarchy to generate configs for * @param configs The Config list to insert folders into */ function generateHierarchyTree( hierarchy: V2ResourceHierarchy | V3ResourceHierarchy, configs: Configs ): Result | undefined { const root: HierarchyNode = { children: [], kind: `${hierarchy.spec.parentRef.kind ?? 'Organization'}`, // if no kind is specified, default to Organization name: `${hierarchy.spec.parentRef.external}`, // Annotation expects string type }; const namespace = hierarchy.metadata.namespace; const annotations: Annotations = filterNonInheritableAnnotations( hierarchy.metadata.annotations || {} ); const subtrees: { [key: string]: HierarchyNode } = {}; if (hierarchy.spec.subtrees !== undefined) { for (const name in hierarchy.spec.subtrees) { const node: HierarchyNode = { children: [], kind: 'Subtree', name, }; const children = hierarchy.spec.subtrees[name]; const subtree = generateTree(node, children as any[], subtrees); node.children = subtree.children; subtrees[name] = node; } } const tree = generateTree(root, hierarchy.spec.config, subtrees); const generateConfigs = (node: HierarchyNode, path: string[]) => { for (const child of node.children) { configs.insert( generateManifest( child.name, path, node, annotations, namespace, isV3ResourceHierarchy(hierarchy) ) ); generateConfigs(child, [...path, child.name]); } }; generateConfigs(tree, []); return undefined; } /** * Add a child into the parent * * @param parent The parent node to attach the child to * @param child The child to append * @param subtrees A map of subtrees which can be referenced */ function addChild( parent: HierarchyNode, child: any, subtrees: { [key: string]: HierarchyNode } ) { if (child === null) { return; } if (typeof child === 'string') { parent.children.push({ name: child, children: [], }); return; } if (typeof child === 'object') { const name = Object.keys(child)[0]; const node: HierarchyNode = { name, children: [], }; const children = child[name]; if (Array.isArray(children)) { generateTree(node, children, subtrees); } else if (typeof children === 'object') { const subtree = children['$subtree']; if (subtrees[subtree] === undefined) { throw new MissingSubteeError(subtree); } node.children = subtrees[subtree].children; } parent.children.push(node); } } /** * Generate a folder tree * * @param root The root node to build the tree from * @param children Top-level children to attach on the root * @param subtrees A map of subtrees which can be referenced */ function generateTree( root: HierarchyNode, children: any[], subtrees: { [key: string]: HierarchyNode } ): HierarchyNode { for (const child of children) { addChild(root, child, subtrees); } return root; } /** * Creates a representation of the resulting folder hierarchy from the * ResourceHierarchy object in a tree data structure. Each node contains the * corresponding config to generate. * * @param node The root node of the tree to generate. This is the organization. * @param layers The list of names of layers to create (levels of the tree). * @param layerIndex The index of which layer to process. Used for recursion. * @param hierarchy The object representing the ResourceHierarchy custom resource. * @param path The name of folders preceeding the current layer. Used to * generate the unique name of the k8s resource. */ function generateV1HierarchyTree( node: HierarchyNode, layers: string[], layerIndex: number, hierarchy: V1ResourceHierarchy, path: string[] ): Result | undefined { if (layerIndex >= layers.length) { return undefined; } const layer = layers[layerIndex]; const folders = hierarchy.spec.config[layer]; // No layer config entry if (folders === undefined) { return { severity: 'error', message: `Layer "${layer}" has no corresponding entry config entry. Either add to spec.config.${layer} or remove it from spec.layers `, }; } // Do not support annotation inheritance for v1; const annotations: Annotations = {}; for (const folder of folders) { const child = { name: folder, children: [], parent: node, config: generateManifest( folder, path, node, annotations, hierarchy.metadata.namespace ), }; const errorResult = generateV1HierarchyTree( child, layers, layerIndex + 1, hierarchy, [...path, folder] ); if (errorResult) { return errorResult; } node.children.push(child); } return undefined; } /** * Crafts a k8s manifest based on the input data and node info. * * @param name The name of the folder * @param path A list of names of the ancestors of the current folder. Used to * generate k8s resource name. * @param parent The parent node of the current folder. * @param namespace Namespace to generate the resource in. */ function generateManifest( name: string, path: string[], parent: HierarchyNode, annotations: Annotations, namespace?: string, nativeRef = false ): KubernetesObject { // Parent name is the metadata name const parentName = path.join('.') || parent.name; // hold annotationRef if any let annotationRef = {}; // hold nativeRefs if any let ref = {}; if (nativeRef) { // root node has no parent and both org/folder ref is external if (path.length === 0) { ref = parent.kind === 'Organization' ? { organizationRef: { external: parentName } } : { folderRef: { external: parentName } }; } else { ref = { folderRef: { name: normalize(parentName) } }; } } else { // generate annotation based ref const annotationName = parent.kind === 'Organization' ? 'cnrm.cloud.google.com/organization-id' : 'cnrm.cloud.google.com/folder-ref'; annotationRef = { [annotationName]: normalize(parentName) }; } let combinedAnnotations = {}; if ( Object.keys(annotations).length > 0 || Object.keys(annotationRef).length > 0 ) { combinedAnnotations = { annotations: { ...annotations, ...annotationRef } }; } const config = { apiVersion: FolderList.apiVersion, kind: 'Folder', metadata: { // TODO(jcwc): This only works up to 253 char (k8s name limit). Figure out // how to handle the edge cases beyond the character limit. name: normalize([...path, name].join('.')), ...combinedAnnotations, } as ObjectMeta, spec: { displayName: name, ...ref, }, }; // Add namespace if provided if (namespace !== undefined) { config.metadata.namespace = namespace; } return config; } /** * Normalizes name to fit the K8s DNS subdomain naming requirements * * @param name Non-normalized name */ export function normalize(name: string) { name = name.toLowerCase(); name = name.replace(/['"]/g, ''); name = name.replace(/[_ ]/g, '-'); name = name.replace(/[^a-z0-9\.\- ]/g, ''); return name; } /** * Iterates through the tree of configs and inserts them into the output config * result. * * @param root The root node of the tree * @param configs In-memory document store for Kubernetes objects */ function insertConfigs(root: HierarchyNode, configs: Configs): void { if (root === undefined) return; if (root.config !== undefined) { configs.insert(root.config); } for (const child of root.children) { insertConfigs(child, configs); } } generateFolders.usage = ` This function translates the "ResourceHierarchy" custom resource and transforms it to the resulting "Folder" custom resources constituting the hierarchy. Post translation, it'll be necessary to use the "kpt-folder-parent" function to translate the results into Cork configs. Example configuration: # hierarchy.yaml # The config below will generate a folder structure of the following # [org: 123456789012] # [dev] [prod] # [retail, finance] [retail, finance] apiVersion: blueprints.cloud.google.com/v1alpha3 kind: ResourceHierarchy metadata: annotations: config.k8s.io/function: | container: image: gcr.io/krm-blueprints/generate-folders:dev config.kubernetes.io/local-config: "true" name: root-hierarchy spec: parentRef: type: Organization external: 123456789012 config: - dev: - retail - finance - prod: - retail - finance `;
the_stack
import { WeComponent } from '../mixins/component'; import { clone, isEmptyObject } from '@mpkit/util'; import { getApiCategoryList } from '../modules/category'; import { convertApiMaterial, productToString } from '../modules/reader'; import ProductControllerMixin from '../mixins/product-controller'; import DataReaderMixin from '../mixins/data-reader'; import EbusMixin from '../mixins/ebus'; import { MpApiReaderComponentData, MpApiReaderComponentSpec } from '../../types/api-reader'; import { MpApiMaterial, MpProduct } from '../../types/product'; import { HookScope } from '../../types/common'; import { computeTime, rpxToPx } from '../modules/util'; import { MpDataReaderAction, MpDataReaderComponentData } from '../../types/reader'; import { ReaderStateController } from '../modules/reader-state'; import { wcScopeSingle } from '../../modules/util'; import { WeConsoleEvents } from '../../types/scope'; import { includeString } from '../modules/json'; const Spec: MpApiReaderComponentSpec = { data: { categoryList: getApiCategoryList(), activeCategory: 'all', detailMaterialId: null, detailFrom: null, materialActions: [ MpDataReaderAction.copy, MpDataReaderAction.top, MpDataReaderAction.keepSave, MpDataReaderAction.cancelAllKeepSave, MpDataReaderAction.mark, MpDataReaderAction.cancelAllMark ], affixIds: [], gridPageSize: 20, detailTab: 0, readerCols: [ { field: 'name', title: 'Name', width: 47.5, wrap: false }, { field: 'status', title: 'Status', width: 20, wrap: false }, { field: 'categorys', title: 'Type', width: 15, wrap: false }, // { // field: "initiator", // title: "Initiator", // width: 17.5, // wrap: false, // }, { field: 'time', title: 'Time', width: 17.5, wrap: false } ] }, methods: { addMaterial(data) { const material = convertApiMaterial(data, this.$wcUIConfig); material.categorys && this.refreshCategory(material.categorys); this.addMaterialToCategory(material); if (this.readerShowList.indexOf(material as MpApiMaterial) !== -1) { this.appendDataToGrid(material as MpApiMaterial); } }, refreshCategory(categoryVals?: string[]) { if (!categoryVals || !categoryVals.length) { this.setData({ categoryList: getApiCategoryList(this.$wcUIConfig) }); this.ApiStateController.setState('categorys', JSON.parse(JSON.stringify(this.data.categoryList))); } else if (this.data.categoryList.some((item) => !categoryVals.find((t) => t === item.value))) { const list = getApiCategoryList(this.$wcUIConfig); categoryVals.forEach((categoryVal) => { if (list.every((item) => item.value !== categoryVal)) { list.push({ name: categoryVal, value: categoryVal }); } }); this.setData({ categoryList: list }); this.ApiStateController.setState('categorys', JSON.parse(JSON.stringify(this.data.categoryList))); } }, reloadVlList(allList) { if (this.$DataGridMain) { this.$DataGridMain.replaceAllList(allList); this.$DataGridMain.reloadAffixList(); } }, filter(keyword) { const kd: string = typeof keyword === 'object' && 'detail' in keyword ? keyword.detail : (keyword as string); if (kd) { this.ApiStateController.setState('filterKeyWord', kd); } else { this.ApiStateController.removeState('filterKeyWord'); } this.filterMaterial(kd); this.reloadVlList(this.readerShowList); }, clear() { // 清空DataGrid操作缓存 delete this.dataGridWaitMaterials; this.clearMaterial(); this.syncAffixList(); this.reloadVlList(this.readerShowList); this.setDetailMaterial(); this.ApiStateController.clearProducts(); this.ApiStateController.removeState('selectedId'); }, setDetailMaterial(id?: string, tab?: number, from?: string) { this.setData({ detailMaterialId: id || '', detailTab: tab || 0, detailFrom: from || '' }); if (from) { this.ApiStateController.setState('selectedIdFrom', from); } else { this.ApiStateController.removeState('selectedIdFrom'); } if (id) { this.ApiStateController.setState('selectedId', id); } else { this.ApiStateController.removeState('selectedId'); } }, clearDetailMaterial() { this.setDetailMaterial(); }, onCategoryChange(activeCategory) { const category: string = typeof activeCategory === 'object' && activeCategory && activeCategory.currentTarget ? activeCategory.detail : activeCategory; this.changeCategory(category); this.reloadVlList(this.readerShowList); this.setDetailMaterial(); this.ApiStateController.setState('activeCategory', category); }, onWcProduct(type: string, data: MpProduct) { if (data.type === HookScope.Api || this?.materialExist?.[data.id]) { if (!this.materialExist) { this.materialExist = {}; } if (data.category) { this.materialExist[data.id] = data.category; } else if (!this.materialExist[data.id]) { this.materialExist[data.id] = 'other'; } this.addMaterial(data as MpProduct); } }, appendDataToGrid(material) { if (material.endTime && material.startTime) { material.time = computeTime(material.endTime - material.startTime); } if (this.$DataGridMain) { this.$DataGridMain.addItem(material); return; } if (!this.dataGridWaitMaterials) { this.dataGridWaitMaterials = []; } this.dataGridWaitMaterials.push(material); }, syncMarkList() { if (this.data.activeCategory === 'mark') { this.reloadVlList(this.readerShowList); } }, syncAffixList() { this.setData({ affixIds: clone(this.topMaterials || []) }); this.$DataGridMain.reloadAffixList(this.NormalMaterialCategoryMap.all); }, changeDetailTab(e) { this.setData({ detailTab: e.detail }); }, gridReady(e) { this.$DataGridMain = e.detail; if (this.dataGridWaitMaterials) { this.dataGridWaitMaterials.forEach((item) => { this.$DataGridMain.addItem(item); }); delete this.dataGridWaitMaterials; } if (this.ApiStateController) { const top = this.ApiStateController.getState('scrollTop'); if (top) { this.$DataGridMain.scrollTo(top); } this.$DataGridMain.onScroll((top: number) => { this.ApiStateController.setState('scrollTop', top); }); } }, tapGridCell(e) { const { rowId } = e.detail; if (rowId) { this.setDetailMaterial( rowId, null, 'tapCell' // col && col.field && col.field === "initiator" ? 3 : 0 ); } }, longpressGridRow(e) { const { rowId } = e.detail; if (rowId) { this.setDetailMaterial(rowId, null, 'longpressRow'); this.showMaterialAction(rowId).then(([action, oldSituation]) => { if (action === MpDataReaderAction.top) { this.ApiStateController.top(rowId, !oldSituation); return this.syncAffixList(); } if (action === MpDataReaderAction.mark) { this.ApiStateController.mark(rowId, !oldSituation); return this.syncMarkList(); } if (action === MpDataReaderAction.cancelAllMark) { this.ApiStateController.mark(null, false); return this.syncMarkList(); } if (action === MpDataReaderAction.keepSave) { this.ApiStateController.keepSave(rowId, !oldSituation); return; } if (action === MpDataReaderAction.cancelAllKeepSave) { this.ApiStateController.keepSave(null, false); } }); } }, materialFilterPolicy(k, item): boolean { const product = this.getProduct(item.id); if (!product) { return false; } if (includeString(item.name, k) || includeString(item.nameDesc, k)) { return true; } return false; }, copyMaterial(m: MpApiMaterial) { const product = this.getProduct(m.id); if (!product) { return; } if (this?.$wcUIConfig.copyPolicy) { return this.$wcUIConfig.copyPolicy(product); } wx.setClipboardData({ data: productToString(product) }); }, syncGridPageSize() { const grid = this.selectComponent('.fc-reader-body'); if (grid) { Promise.all([rpxToPx(40), grid.$getBoundingClientRect('.fc-datagrid-scroll')]).then( ([itemHeight, { height }]) => { this.setData({ gridPageSize: Math.ceil(height / itemHeight) }); } ); } } }, created() { setTimeout(() => { this.refreshCategory(); }, 400); this.ApiStateController = wcScopeSingle('ApiStateController') as ReaderStateController; this.$wcOn(WeConsoleEvents.WcMainComponentSizeChange, () => { this.syncGridPageSize(); }); }, attached() { if (this.$wcProductController) { const idList = this.ApiStateController.getProductIdList(); const activeCategory = this.ApiStateController.getState('activeCategory'); const filterKeyWord = this.ApiStateController.getState('filterKeyWord'); const categorys = this.ApiStateController.getState('categorys'); const selectedId = this.ApiStateController.getState('selectedId'); const selectedIdFrom = this.ApiStateController.getState('selectedIdFrom'); if (filterKeyWord) { this.filterKeyword = filterKeyWord; } const reanderData: Partial<MpApiReaderComponentData & MpDataReaderComponentData> = {}; if (activeCategory) { reanderData.activeCategory = activeCategory; } if (categorys?.length) { reanderData.categoryList = categorys; } if (selectedId) { reanderData.detailMaterialId = selectedId; } if (selectedIdFrom) { reanderData.detailFrom = selectedIdFrom; } this.keepSaveMaterials = this.ApiStateController.keepSave().reduce((sum, item) => { sum[item] = 1; return sum; }, {}); this.topMaterials = this.ApiStateController.top().concat([]); this.markMaterials = this.ApiStateController.mark().reduce((sum, item) => { sum[item] = 1; return sum; }, {}); if (!isEmptyObject(reanderData)) { this.setData({ reanderData }); } const products = this.$wcProductController.getList((item) => idList.some((id) => id === item.id)); products.forEach((item) => { this.addMaterial(item); }); } this.syncGridPageSize(); } }; WeComponent(ProductControllerMixin, EbusMixin, DataReaderMixin, Spec);
the_stack
import * as vscode from 'vscode'; import * as crypto from 'crypto'; import * as xml2js from 'xml2js'; import * as event from 'events'; import * as fs from 'fs'; import * as node_path from 'path'; import * as child_process from 'child_process'; import * as vscodeVariables from 'vscode-variables'; import { File } from '../lib/node_utility/File'; import { ResourceManager } from './ResourceManager'; import { FileWatcher } from '../lib/node_utility/FileWatcher'; import { Time } from '../lib/node_utility/Time'; import { isArray } from 'util'; import { CmdLineHandler } from './CmdLineHandler'; export function activate(context: vscode.ExtensionContext) { console.log('---- keil-assistant actived ----'); // init resource ResourceManager.getInstance(context); const prjExplorer = new ProjectExplorer(context); const subscriber = context.subscriptions; subscriber.push(vscode.commands.registerCommand('explorer.open', async () => { const uri = await vscode.window.showOpenDialog({ openLabel: 'Open a keil project', canSelectFolders: false, canSelectMany: false, filters: { 'keil project xml': ['uvproj', 'uvprojx'] } }); try { if (uri && uri.length > 0) { // load project const uvPrjPath = uri[0].fsPath; await prjExplorer.openProject(uvPrjPath); // switch workspace const result = await vscode.window.showInformationMessage( 'keil project load done !, switch workspace ?', 'Ok', 'Later'); if (result === 'Ok') { openWorkspace(new File(node_path.dirname(uvPrjPath))); } } } catch (error) { vscode.window.showErrorMessage(`open project failed !, msg: ${(<Error>error).message}`); } })); subscriber.push(vscode.commands.registerCommand('project.close', (item: IView) => prjExplorer.closeProject(item.prjID))); subscriber.push(vscode.commands.registerCommand('project.build', (item: IView) => prjExplorer.getTarget(item)?.build())); subscriber.push(vscode.commands.registerCommand('project.rebuild', (item: IView) => prjExplorer.getTarget(item)?.rebuild())); subscriber.push(vscode.commands.registerCommand('project.download', (item: IView) => prjExplorer.getTarget(item)?.download())); subscriber.push(vscode.commands.registerCommand('item.copyValue', (item: IView) => vscode.env.clipboard.writeText(item.tooltip || ''))); subscriber.push(vscode.commands.registerCommand('project.switch', (item: IView) => prjExplorer.switchTargetByProject(item))); subscriber.push(vscode.commands.registerCommand('project.active', (item: IView) => prjExplorer.activeProject(item))); prjExplorer.loadWorkspace(); } export function deactivate() { console.log('---- keil-assistant closed ----'); } //==================== Global Func=========================== function getMD5(data: string): string { const md5 = crypto.createHash('md5'); md5.update(data); return md5.digest('hex'); } function openWorkspace(wsFile: File) { vscode.commands.executeCommand('vscode.openFolder', vscode.Uri.parse(wsFile.ToUri())); } //=============================== interface IView { label: string; prjID: string; icons?: { light: string, dark: string }; tooltip?: string; contextVal?: string; getChildViews(): IView[] | undefined; } //=============================================== class Source implements IView { label: string; prjID: string; icons?: { light: string; dark: string; } | undefined; tooltip?: string | undefined; contextVal?: string | undefined = 'Source'; //--- readonly file: File; readonly enable: boolean; children: Source[] | undefined; constructor(pID: string, f: File, _enable: boolean = true) { this.prjID = pID; this.enable = _enable; this.file = f; this.label = this.file.name; this.tooltip = f.path; let iconName = ''; if (f.IsFile() === false) { iconName = 'FileWarning_16x'; } else if (_enable === false) { iconName = 'FileExclude_16x'; } else { iconName = this.getIconBySuffix(f.suffix.toLowerCase()); } this.icons = { dark: iconName, light: iconName }; } private getIconBySuffix(suffix: string): string { switch (suffix) { case '.c': return 'CFile_16x'; case '.h': case '.hpp': case '.hxx': case '.inc': return 'CPPHeaderFile_16x'; case '.cpp': case '.c++': case '.cxx': case '.cc': return 'CPP_16x'; case '.s': case '.a51': case '.asm': return 'AssemblerSourceFile_16x'; case '.lib': case '.a': return 'Library_16x'; default: return 'Text_16x'; } } getChildViews(): IView[] | undefined { return this.children; } } class FileGroup implements IView { label: string; prjID: string; tooltip?: string | undefined; contextVal?: string | undefined = 'FileGroup'; icons?: { light: string; dark: string; }; //---- sources: Source[]; constructor(pID: string, gName: string, disabled: boolean) { this.label = gName; this.prjID = pID; this.sources = []; this.tooltip = gName; const iconName = disabled ? 'FolderExclude_32x' : 'Folder_32x'; this.icons = { light: iconName, dark: iconName }; } getChildViews(): IView[] | undefined { return this.sources; } } interface KeilProjectInfo { prjID: string; vscodeDir: File; uvprjFile: File; logger: Console; toAbsolutePath(rePath: string): string; } interface uVisonInfo { schemaVersion: string | undefined; } class KeilProject implements IView, KeilProjectInfo { prjID: string; label: string; tooltip?: string | undefined; contextVal?: string | undefined = 'Project'; icons?: { light: string; dark: string; } = { light: 'DeactiveApplication_16x', dark: 'DeactiveApplication_16x' }; //------------- vscodeDir: File; uvprjFile: File; logger: Console; // uVison info uVsionFileInfo: uVisonInfo; private activeTargetName: string | undefined; private prevUpdateTime: number | undefined; protected _event: event.EventEmitter; protected watcher: FileWatcher; protected targetList: Target[]; constructor(_uvprjFile: File) { this._event = new event.EventEmitter(); this.uVsionFileInfo = <uVisonInfo>{}; this.targetList = []; this.vscodeDir = new File(_uvprjFile.dir + File.sep + '.vscode'); this.vscodeDir.CreateDir(); const logPath = this.vscodeDir.path + File.sep + 'keil-assistant.log'; this.logger = new console.Console(fs.createWriteStream(logPath, { flags: 'a+' })); this.uvprjFile = _uvprjFile; this.watcher = new FileWatcher(this.uvprjFile); this.prjID = getMD5(_uvprjFile.path); this.label = _uvprjFile.noSuffixName; this.tooltip = _uvprjFile.path; this.logger.log('[info] Log at : ' + Time.GetInstance().GetTimeStamp() + '\r\n'); this.watcher.OnChanged = () => { if (this.prevUpdateTime === undefined || this.prevUpdateTime + 2000 < Date.now()) { this.prevUpdateTime = Date.now(); // reset update time setTimeout(() => this.onReload(), 300); } }; this.watcher.Watch(); } on(event: 'dataChanged', listener: () => void): void; on(event: any, listener: () => void): void { this._event.on(event, listener); } private async onReload() { try { this.targetList.forEach((target) => target.close()); this.targetList = []; await this.load(); this.notifyUpdateView(); } catch (err) { if (err.code && err.code === 'EBUSY') { this.logger.log(`[Warn] uVision project file '${this.uvprjFile.name}' is locked !, delay 500 ms and retry !`); setTimeout(() => this.onReload(), 500); } else { vscode.window.showErrorMessage(`reload project failed !, msg: ${err.message}`); } } } async load() { const parser = new xml2js.Parser({ explicitArray: false }); const doc = await parser.parseStringPromise({ toString: () => { return this.uvprjFile.Read(); } }); const targets = doc['Project']['Targets']['Target']; // init uVsion info this.uVsionFileInfo.schemaVersion = doc['Project']['SchemaVersion']; if (isArray(targets)) { for (const target of targets) { this.targetList.push(Target.getInstance(this, this.uVsionFileInfo, target)); } } else { this.targetList.push(Target.getInstance(this, this.uVsionFileInfo, targets)); } for (const target of this.targetList) { await target.load(); target.on('dataChanged', () => this.notifyUpdateView()); } } notifyUpdateView() { this._event.emit('dataChanged'); } close() { this.watcher.Close(); this.targetList.forEach((target) => target.close()); this.logger.log('[info] project closed: ' + this.label); } toAbsolutePath(rePath: string): string { const path = rePath.replace(/\//g, File.sep); if (/^[a-z]:/i.test(path)) { return node_path.normalize(path); } return node_path.normalize(this.uvprjFile.dir + File.sep + path); } active() { this.icons = { light: 'ActiveApplication_16x', dark: 'ActiveApplication_16x' }; } deactive() { this.icons = { light: 'DeactiveApplication_16x', dark: 'DeactiveApplication_16x' }; } getTargetByName(name: string): Target | undefined { const index = this.targetList.findIndex((t) => { return t.targetName === name; }); if (index !== -1) { return this.targetList[index]; } } setActiveTarget(tName: string) { if (tName !== this.activeTargetName) { this.activeTargetName = tName; this.notifyUpdateView(); // notify data changed } } getActiveTarget(): Target | undefined { if (this.activeTargetName) { return this.getTargetByName(this.activeTargetName); } else if (this.targetList.length > 0) { return this.targetList[0]; } } getChildViews(): IView[] | undefined { if (this.activeTargetName) { const target = this.getTargetByName(this.activeTargetName); if (target) { return [target]; } } if (this.targetList.length > 0) { return [this.targetList[0]]; } return undefined; } getTargets(): Target[] { return this.targetList; } } abstract class Target implements IView { prjID: string; label: string; tooltip?: string | undefined; contextVal?: string | undefined = 'Target'; icons?: { light: string; dark: string; } = { light: 'Class_16x', dark: 'Class_16x' }; //------------- readonly targetName: string; protected _event: event.EventEmitter; protected project: KeilProjectInfo; protected cppConfigName: string; protected targetDOM: any; protected uvInfo: uVisonInfo; protected fGroups: FileGroup[]; protected includes: Set<string>; protected defines: Set<string>; private uv4LogFile: File; private uv4LogLockFileWatcher: FileWatcher; constructor(prjInfo: KeilProjectInfo, uvInfo: uVisonInfo, targetDOM: any) { this._event = new event.EventEmitter(); this.project = prjInfo; this.targetDOM = targetDOM; this.uvInfo = uvInfo; this.prjID = prjInfo.prjID; this.targetName = targetDOM['TargetName']; this.label = this.targetName; this.tooltip = this.targetName; this.cppConfigName = this.targetName; this.includes = new Set(); this.defines = new Set(); this.fGroups = []; this.uv4LogFile = new File(this.project.vscodeDir.path + File.sep + 'uv4.log'); this.uv4LogLockFileWatcher = new FileWatcher(new File(this.uv4LogFile.path + '.lock')); if (!this.uv4LogLockFileWatcher.file.IsFile()) { // create file if not existed this.uv4LogLockFileWatcher.file.Write(''); } this.uv4LogLockFileWatcher.Watch(); this.uv4LogLockFileWatcher.OnChanged = () => this.updateSourceRefs(); this.uv4LogLockFileWatcher.on('error', () => { this.uv4LogLockFileWatcher.Close(); if (!this.uv4LogLockFileWatcher.file.IsFile()) { // create file if not existed this.uv4LogLockFileWatcher.file.Write(''); } this.uv4LogLockFileWatcher.Watch(); }); } on(event: 'dataChanged', listener: () => void): void; on(event: any, listener: () => void): void { this._event.on(event, listener); } static getInstance(prjInfo: KeilProjectInfo, uvInfo: uVisonInfo, targetDOM: any): Target { if (prjInfo.uvprjFile.suffix.toLowerCase() === '.uvproj') { return new C51Target(prjInfo, uvInfo, targetDOM); } else { return new ArmTarget(prjInfo, uvInfo, targetDOM); } } private getDefCppProperties(): any { return { configurations: [ { name: this.cppConfigName, includePath: undefined, defines: undefined, intelliSenseMode: '${default}' } ], version: 4 }; } private updateCppProperties() { const proFile = new File(this.project.vscodeDir.path + File.sep + 'c_cpp_properties.json'); let obj: any; if (proFile.IsFile()) { try { obj = JSON.parse(proFile.Read()); } catch (error) { this.project.logger.log(error); obj = this.getDefCppProperties(); } } else { obj = this.getDefCppProperties(); } const configList: any[] = obj['configurations']; const index = configList.findIndex((conf) => { return conf.name === this.cppConfigName; }); if (index === -1) { configList.push({ name: this.cppConfigName, includePath: Array.from(this.includes).concat(['${default}']), defines: Array.from(this.defines), intelliSenseMode: '${default}' }); } else { configList[index]['includePath'] = Array.from(this.includes).concat(['${default}']); configList[index]['defines'] = Array.from(this.defines); } proFile.Write(JSON.stringify(obj, undefined, 4)); } async load(): Promise<void> { // check target is valid const err = this.checkProject(this.targetDOM); if (err) { throw err; } const incListStr: string = this.getIncString(this.targetDOM); const defineListStr: string = this.getDefineString(this.targetDOM); const _groups: any = this.getGroups(this.targetDOM); const sysIncludes = this.getSystemIncludes(this.targetDOM); // set includes this.includes.clear(); let incList = incListStr.split(';'); if (sysIncludes) { incList = incList.concat(sysIncludes); } incList.forEach((path) => { const realPath = path.trim(); if (realPath !== '') { this.includes.add(this.project.toAbsolutePath(realPath)); } }); // set defines this.defines.clear(); // add user macros defineListStr.split(/,|\s+/).forEach((define) => { if (define.trim() !== '') { this.defines.add(define); } }); // add system macros this.getSysDefines(this.targetDOM).forEach((define) => { this.defines.add(define); }); // set file groups this.fGroups = []; let groups: any[]; if (Array.isArray(_groups)) { groups = _groups; } else { groups = [_groups]; } for (const group of groups) { if (group['Files'] !== undefined) { let isGroupExcluded = false; let fileList: any[]; if (group['GroupOption']) { // check group is excluded const gOption = group['GroupOption']['CommonProperty']; if (gOption && gOption['IncludeInBuild'] === '0') { isGroupExcluded = true; } } const nGrp = new FileGroup(this.prjID, group['GroupName'], isGroupExcluded); if (Array.isArray(group['Files'])) { fileList = []; for (const files of group['Files']) { if (Array.isArray(files['File'])) { fileList = fileList.concat(files['File']); } else if (files['File'] !== undefined) { fileList.push(files['File']); } } } else { if (Array.isArray(group['Files']['File'])) { fileList = group['Files']['File']; } else if (group['Files']['File'] !== undefined) { fileList = [group['Files']['File']]; } else { fileList = []; } } for (const file of fileList) { const f = new File(this.project.toAbsolutePath(file['FilePath'])); let isFileExcluded = isGroupExcluded; if (isFileExcluded === false && file['FileOption']) { // check file is enable const fOption = file['FileOption']['CommonProperty']; if (fOption && fOption['IncludeInBuild'] === '0') { isFileExcluded = true; } } const nFile = new Source(this.prjID, f, !isFileExcluded); this.includes.add(f.dir); nGrp.sources.push(nFile); } this.fGroups.push(nGrp); } } this.updateCppProperties(); this.updateSourceRefs(); } private quoteString(str: string, quote: string = '"'): string { return str.includes(' ') ? (quote + str + quote) : str; } private runTask(name: string, commands: string[]) { const resManager = ResourceManager.getInstance(); let args: string[] = []; args.push('-o', this.uv4LogFile.path); args = args.concat(commands); const isCmd = /cmd.exe$/i.test(vscode.env.shell); const quote = isCmd ? '"' : '\''; const invokePrefix = isCmd ? '' : '& '; const cmdPrefixSuffix = isCmd ? '"' : ''; let commandLine = invokePrefix + this.quoteString(resManager.getBuilderExe(), quote) + ' '; commandLine += args.map((arg) => { return this.quoteString(arg, quote); }).join(' '); // use task if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) { const task = new vscode.Task({ type: 'keil-task' }, vscode.TaskScope.Global, name, 'shell'); task.execution = new vscode.ShellExecution(cmdPrefixSuffix + commandLine + cmdPrefixSuffix); task.isBackground = false; task.problemMatchers = this.getProblemMatcher(); task.presentationOptions = { echo: false, focus: false, clear: true }; vscode.tasks.executeTask(task); } else { const index = vscode.window.terminals.findIndex((ter) => { return ter.name === name; }); if (index !== -1) { vscode.window.terminals[index].hide(); vscode.window.terminals[index].dispose(); } const terminal = vscode.window.createTerminal(name); terminal.show(); terminal.sendText(commandLine); } } build() { this.runTask('build', this.getBuildCommand()); } rebuild() { this.runTask('rebuild', this.getRebuildCommand()); } download() { this.runTask('download', this.getDownloadCommand()); } updateSourceRefs() { const rePath = this.getOutputFolder(this.targetDOM); if (rePath) { const outPath = this.project.toAbsolutePath(rePath); this.fGroups.forEach((group) => { group.sources.forEach((source) => { if (source.enable) { // if source not disabled const refFile = File.fromArray([outPath, source.file.noSuffixName + '.d']); if (refFile.IsFile()) { const refFileList = this.parseRefLines(this.targetDOM, refFile.Read().split(/\r\n|\n/)) .map((rePath) => { return this.project.toAbsolutePath(rePath); }); source.children = refFileList.map((refFilePath) => { return new Source(source.prjID, new File(refFilePath)); }); } } }); }); this._event.emit('dataChanged'); } } close() { this.uv4LogLockFileWatcher.Close(); } getChildViews(): IView[] | undefined { return this.fGroups; } protected abstract checkProject(target: any): Error | undefined; protected abstract getIncString(target: any): string; protected abstract getDefineString(target: any): string; protected abstract getSysDefines(target: any): string[]; protected abstract getGroups(target: any): any[]; protected abstract getSystemIncludes(target: any): string[] | undefined; protected abstract getOutputFolder(target: any): string | undefined; protected abstract parseRefLines(target: any, lines: string[]): string[]; protected abstract getProblemMatcher(): string[]; protected abstract getBuildCommand(): string[]; protected abstract getRebuildCommand(): string[]; protected abstract getDownloadCommand(): string[]; } //=============================================== class C51Target extends Target { protected checkProject(target: any): Error | undefined { if (target['TargetOption']['Target51'] === undefined || target['TargetOption']['Target51']['C51'] === undefined) { return new Error(`This uVision project is not a C51 project, but have a 'uvproj' suffix !`); } } protected parseRefLines(target: any, lines: string[]): string[] { return []; } protected getOutputFolder(target: any): string | undefined { return undefined; } protected getSysDefines(target: any): string[] { return [ '__C51__', '__VSCODE_C51__', 'reentrant=', 'compact=', 'small=', 'large=', 'data=', 'idata=', 'pdata=', 'bdata=', 'xdata=', 'code=', 'bit=char', 'sbit=char', 'sfr=char', 'sfr16=int', 'sfr32=int', 'interrupt=', 'using=', '_at_=', '_priority_=', '_task_=' ]; } protected getSystemIncludes(target: any): string[] | undefined { const exeFile = new File(ResourceManager.getInstance().getC51UV4Path()); if (exeFile.IsFile()) { return [ node_path.dirname(exeFile.dir) + File.sep + 'C51' + File.sep + 'INC' ]; } return undefined; } protected getIncString(target: any): string { const target51 = target['TargetOption']['Target51']['C51']; return target51['VariousControls']['IncludePath']; } protected getDefineString(target: any): string { const target51 = target['TargetOption']['Target51']['C51']; return target51['VariousControls']['Define']; } protected getGroups(target: any): any[] { return target['Groups']['Group'] || []; } protected getProblemMatcher(): string[] { return ['$c51']; } protected getBuildCommand(): string[] { return [ '--uv4Path', ResourceManager.getInstance().getC51UV4Path(), '--prjPath', this.project.uvprjFile.path, '--targetName', this.targetName, '-c', '${uv4Path} -b ${prjPath} -j0 -t ${targetName}' ]; } protected getRebuildCommand(): string[] { return [ '--uv4Path', ResourceManager.getInstance().getC51UV4Path(), '--prjPath', this.project.uvprjFile.path, '--targetName', this.targetName, '-c', '${uv4Path} -r ${prjPath} -j0 -t ${targetName}' ]; } protected getDownloadCommand(): string[] { return [ '--uv4Path', ResourceManager.getInstance().getC51UV4Path(), '--prjPath', this.project.uvprjFile.path, '--targetName', this.targetName, '-c', '${uv4Path} -f ${prjPath} -j0 -t ${targetName}' ]; } } class MacroHandler { private regMatchers = { 'normal_macro': /^#define (\w+) (.*)$/, 'func_macro': /^#define (\w+\([^\)]*\)) (.*)$/ }; toExpression(macro: string): string | undefined { let mList = this.regMatchers['normal_macro'].exec(macro); if (mList && mList.length > 2) { return `${mList[1]}=${mList[2]}`; } mList = this.regMatchers['func_macro'].exec(macro); if (mList && mList.length > 2) { return `${mList[1]}=`; } } } class ArmTarget extends Target { private static readonly armccMacros: string[] = [ '__CC_ARM', '__arm__', '__align(x)=', '__ALIGNOF__(x)=', '__alignof__(x)=', '__asm(x)=', '__forceinline=', '__restrict=', '__global_reg(n)=', '__inline=', '__int64=long long', '__INTADDR__(expr)=0', '__irq=', '__packed=', '__pure=', '__smc(n)=', '__svc(n)=', '__svc_indirect(n)=', '__svc_indirect_r7(n)=', '__value_in_regs=', '__weak=', '__writeonly=', '__declspec(x)=', '__attribute__(x)=', '__nonnull__(x)=', '__register=', '__breakpoint(x)=', '__cdp(x,y,z)=', '__clrex()=', '__clz(x)=0U', '__current_pc()=0U', '__current_sp()=0U', '__disable_fiq()=', '__disable_irq()=', '__dmb(x)=', '__dsb(x)=', '__enable_fiq()=', '__enable_irq()=', '__fabs(x)=0.0', '__fabsf(x)=0.0f', '__force_loads()=', '__force_stores()=', '__isb(x)=', '__ldrex(x)=0U', '__ldrexd(x)=0U', '__ldrt(x)=0U', '__memory_changed()=', '__nop()=', '__pld(...)=', '__pli(...)=', '__qadd(x,y)=0', '__qdbl(x)=0', '__qsub(x,y)=0', '__rbit(x)=0U', '__rev(x)=0U', '__return_address()=0U', '__ror(x,y)=0U', '__schedule_barrier()=', '__semihost(x,y)=0', '__sev()=', '__sqrt(x)=0.0', '__sqrtf(x)=0.0f', '__ssat(x,y)=0', '__strex(x,y)=0U', '__strexd(x,y)=0', '__strt(x,y)=', '__swp(x,y)=0U', '__usat(x,y)=0U', '__wfe()=', '__wfi()=', '__yield()=', '__vfp_status(x,y)=0' ]; private static readonly armclangMacros: string[] = [ '__alignof__(x)=', '__asm(x)=', '__asm__(x)=', '__forceinline=', '__restrict=', '__volatile__=', '__inline=', '__inline__=', '__declspec(x)=', '__attribute__(x)=', '__nonnull__(x)=', '__unaligned=', '__promise(x)=', '__irq=', '__swi=', '__weak=', '__register=', '__pure=', '__value_in_regs=', '__breakpoint(x)=', '__current_pc()=0U', '__current_sp()=0U', '__disable_fiq()=', '__disable_irq()=', '__enable_fiq()=', '__enable_irq()=', '__force_stores()=', '__memory_changed()=', '__schedule_barrier()=', '__semihost(x,y)=0', '__vfp_status(x,y)=0', '__builtin_arm_nop()=', '__builtin_arm_wfi()=', '__builtin_arm_wfe()=', '__builtin_arm_sev()=', '__builtin_arm_sevl()=', '__builtin_arm_yield()=', '__builtin_arm_isb(x)=', '__builtin_arm_dsb(x)=', '__builtin_arm_dmb(x)=', '__builtin_bswap32(x)=0U', '__builtin_bswap16(x)=0U', '__builtin_arm_rbit(x)=0U', '__builtin_clz(x)=0U', '__builtin_arm_ldrex(x)=0U', '__builtin_arm_strex(x,y)=0U', '__builtin_arm_clrex()=', '__builtin_arm_ssat(x,y)=0U', '__builtin_arm_usat(x,y)=0U', '__builtin_arm_ldaex(x)=0U', '__builtin_arm_stlex(x,y)=0U' ]; private static armclangBuildinMacros: string[] | undefined; constructor(prjInfo: KeilProjectInfo, uvInfo: uVisonInfo, targetDOM: any) { super(prjInfo, uvInfo, targetDOM); ArmTarget.initArmclangMacros(); } protected checkProject(): Error | undefined { return undefined; } protected getOutputFolder(target: any): string | undefined { try { return <string>target['TargetOption']['TargetCommonOption']['OutputDirectory']; } catch (error) { return undefined; } } private gnu_parseRefLines(lines: string[]): string[] { const resultList: Set<string> = new Set(); for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) { let _line = lines[lineIndex]; let line = _line[_line.length - 1] === '\\' ? _line.substring(0, _line.length - 1) : _line; // remove char '\' let subLines = line.trim().split(/(?<![\\:]) /); if (lineIndex === 0) // first line { for (let i = 1; i < subLines.length; i++) // skip first sub line { resultList.add(subLines[i].trim().replace(/\\ /g, " ")); } } else // other lines, first char is whitespace { subLines.forEach((item) => { resultList.add(item.trim().replace(/\\ /g, " ")); }); } } return Array.from(resultList); } private ac5_parseRefLines(lines: string[], startIndex: number = 1): string[] { const resultList: Set<string> = new Set<string>(); for (let i = startIndex; i < lines.length; i++) { let sepIndex = lines[i].indexOf(": "); if (sepIndex > 0) { const line: string = lines[i].substring(sepIndex + 1).trim(); resultList.add(line); } } return Array.from(resultList); } protected parseRefLines(target: any, lines: string[]): string[] { if (target['uAC6'] === '1') { // ARMClang return this.gnu_parseRefLines(lines); } else { // ARMCC return this.ac5_parseRefLines(lines); } } private static initArmclangMacros() { if (ArmTarget.armclangBuildinMacros === undefined) { const armClangPath = node_path.dirname(node_path.dirname(ResourceManager.getInstance().getArmUV4Path())) + File.sep + 'ARM' + File.sep + 'ARMCLANG' + File.sep + 'bin' + File.sep + 'armclang.exe'; ArmTarget.armclangBuildinMacros = ArmTarget.getArmClangMacroList(armClangPath); } } protected getSysDefines(target: any): string[] { if (target['uAC6'] === '1') { // ARMClang return ArmTarget.armclangMacros.concat(ArmTarget.armclangBuildinMacros || []); } else { // ARMCC return ArmTarget.armccMacros; } } private static getArmClangMacroList(armClangPath: string): string[] { try { const cmdLine = CmdLineHandler.quoteString(armClangPath, '"') + ' ' + ['--target=arm-arm-none-eabi', '-E', '-dM', '-', '<nul'].join(' '); const lines = child_process.execSync(cmdLine).toString().split(/\r\n|\n/); const resList: string[] = []; const mHandler = new MacroHandler(); lines.filter((line) => { return line.trim() !== ''; }) .forEach((line) => { const value = mHandler.toExpression(line); if (value) { resList.push(value); } }); return resList; } catch (error) { return ['__GNUC__=4', '__GNUC_MINOR__=2', '__GNUC_PATCHLEVEL__=1']; } } protected getSystemIncludes(target: any): string[] | undefined { const exeFile = new File(ResourceManager.getInstance().getArmUV4Path()); if (exeFile.IsFile()) { const toolName = target['uAC6'] === '1' ? 'ARMCLANG' : 'ARMCC'; const incDir = new File(`${node_path.dirname(exeFile.dir)}${File.sep}ARM${File.sep}${toolName}${File.sep}include`); if (incDir.IsDir()) { return [incDir.path].concat( incDir.GetList(File.EMPTY_FILTER).map((dir) => { return dir.path; })); } return [incDir.path]; } return undefined; } protected getIncString(target: any): string { const dat = target['TargetOption']['TargetArmAds']['Cads']; return dat['VariousControls']['IncludePath']; } protected getDefineString(target: any): string { const dat = target['TargetOption']['TargetArmAds']['Cads']; return dat['VariousControls']['Define']; } protected getGroups(target: any): any[] { return target['Groups']['Group'] || []; } protected getProblemMatcher(): string[] { return ['$armcc', '$gcc']; } protected getBuildCommand(): string[] { return [ '--uv4Path', ResourceManager.getInstance().getArmUV4Path(), '--prjPath', this.project.uvprjFile.path, '--targetName', this.targetName, '-c', '${uv4Path} -b ${prjPath} -j0 -t ${targetName}' ]; } protected getRebuildCommand(): string[] { return [ '--uv4Path', ResourceManager.getInstance().getArmUV4Path(), '--prjPath', this.project.uvprjFile.path, '--targetName', this.targetName, '-c', '${uv4Path} -r ${prjPath} -j0 -t ${targetName}' ]; } protected getDownloadCommand(): string[] { return [ '--uv4Path', ResourceManager.getInstance().getArmUV4Path(), '--prjPath', this.project.uvprjFile.path, '--targetName', this.targetName, '-c', '${uv4Path} -f ${prjPath} -j0 -t ${targetName}' ]; } } //================================================ class ProjectExplorer implements vscode.TreeDataProvider<IView> { private ItemClickCommand: string = 'Item.Click'; onDidChangeTreeData: vscode.Event<IView>; private viewEvent: vscode.EventEmitter<IView>; private prjList: Map<string, KeilProject>; private currentActiveProject: KeilProject | undefined; constructor(context: vscode.ExtensionContext) { this.prjList = new Map(); this.viewEvent = new vscode.EventEmitter(); this.onDidChangeTreeData = this.viewEvent.event; context.subscriptions.push(vscode.window.registerTreeDataProvider('project', this)); context.subscriptions.push(vscode.commands.registerCommand(this.ItemClickCommand, (item) => this.onItemClick(item))); } async loadWorkspace() { if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) { const wsFilePath: string = vscode.workspace.workspaceFile && /^file:/.test(vscode.workspace.workspaceFile.toString()) ? node_path.dirname(vscode.workspace.workspaceFile.fsPath) : vscode.workspace.workspaceFolders[0].uri.fsPath; const workspace = new File(wsFilePath); if (workspace.IsDir()) { const excludeList = ResourceManager.getInstance().getProjectExcludeList(); const uvList = workspace.GetList([/\.uvproj[x]?$/i], File.EMPTY_FILTER).concat(ResourceManager.getInstance().getProjectFileLocationList()) .filter((file) => { return !excludeList.includes(file.name); }); for (const uvFile of uvList) { try { await this.openProject(vscodeVariables(uvFile)); } catch (error) { vscode.window.showErrorMessage(`open project: '${uvFile.name}' failed !, msg: ${(<Error>error).message}`); } } } } } async openProject(path: string): Promise<KeilProject | undefined> { const nPrj = new KeilProject(new File(path)); if (!this.prjList.has(nPrj.prjID)) { await nPrj.load(); nPrj.on('dataChanged', () => this.updateView()); this.prjList.set(nPrj.prjID, nPrj); if (this.currentActiveProject == undefined) { this.currentActiveProject = nPrj; this.currentActiveProject.active(); } this.updateView(); return nPrj; } } async closeProject(pID: string) { const prj = this.prjList.get(pID); if (prj) { prj.deactive(); prj.close(); this.prjList.delete(pID); this.updateView(); } } async activeProject(view: IView) { const project = this.prjList.get(view.prjID); if (project) { this.currentActiveProject?.deactive(); this.currentActiveProject = project; this.currentActiveProject?.active(); this.updateView(); } } async switchTargetByProject(view: IView) { const prj = this.prjList.get(view.prjID); if (prj) { const tList = prj.getTargets(); const targetName = await vscode.window.showQuickPick(tList.map((ele) => { return ele.targetName; }), { canPickMany: false, placeHolder: 'please select a target name for keil project' }); if (targetName) { prj.setActiveTarget(targetName); } } } getTarget(view?: IView): Target | undefined { if (view) { const prj = this.prjList.get(view.prjID); if (prj) { const targets = prj.getTargets(); const index = targets.findIndex((target) => { return target.targetName === view.label; }); if (index !== -1) { return targets[index]; } } } else { // get active target if (this.currentActiveProject) { return this.currentActiveProject.getActiveTarget(); } else { vscode.window.showWarningMessage('Not found any active project !'); } } } updateView() { this.viewEvent.fire(); } //---------------------------------- itemClickInfo: any = undefined; private async onItemClick(item: IView) { switch (item.contextVal) { case 'Source': { const source = <Source>item; const file = new File(node_path.normalize(source.file.path)); if (file.IsFile()) { // file exist, open it let isPreview: boolean = true; if (this.itemClickInfo && this.itemClickInfo.name === file.path && this.itemClickInfo.time + 260 > Date.now()) { isPreview = false; } // reset prev click info this.itemClickInfo = { name: file.path, time: Date.now() }; vscode.window.showTextDocument(vscode.Uri.parse(file.ToUri()), { preview: isPreview }); } else { vscode.window.showWarningMessage(`Not found file: ${source.file.path}`); } } break; default: break; } } getTreeItem(element: IView): vscode.TreeItem | Thenable<vscode.TreeItem> { const res = new vscode.TreeItem(element.label); res.contextValue = element.contextVal; res.tooltip = element.tooltip; res.collapsibleState = element.getChildViews() === undefined ? vscode.TreeItemCollapsibleState.None : vscode.TreeItemCollapsibleState.Collapsed; if (element instanceof Source) { res.command = { title: element.label, command: this.ItemClickCommand, arguments: [element] }; } if (element.icons) { res.iconPath = { light: ResourceManager.getInstance().getIconByName(element.icons.light), dark: ResourceManager.getInstance().getIconByName(element.icons.dark) }; } return res; } getChildren(element?: IView | undefined): vscode.ProviderResult<IView[]> { if (element === undefined) { return Array.from(this.prjList.values()); } else { return element.getChildViews(); } } }
the_stack
import * as jtv from '@mojotech/json-type-validation'; import _ from 'lodash'; /** * Interface for companion objects of serializable types. Its main purpose is * to serialize and deserialize values between raw JSON and typed values. * * @typeparam T The template type. */ export interface Serializable<T> { /** * @internal */ decoder: jtv.Decoder<T>; /** * @internal Encodes T in expected shape for JSON API. */ encode: (t: T) => unknown; } /** * Interface for objects representing Daml templates. It is similar to the * `Template` type class in Daml. * * @typeparam T The template type. * @typeparam K The contract key type. * @typeparam I The contract id type. * */ export interface Template<T extends object, K = unknown, I extends string = string> extends Serializable<T> { templateId: I; /** * @internal */ sdkVersion: '0.0.0-SDKVERSION'; /** * @internal */ keyDecoder: jtv.Decoder<K>; /** * @internal */ keyEncode: (k: K) => unknown; Archive: Choice<T, {}, {}, K>; } /** * Interface for objects representing Daml choices. * * @typeparam T The template type. * @typeparam K The contract key type. * @typeparam C The choice type. * @typeparam R The choice return type. * */ export interface Choice<T extends object, C, R, K = unknown> { /** * Returns the template to which this choice belongs. */ template: () => Template<T, K>; /** * @internal Returns a decoder to decode the choice arguments. * * Note: we never need to decode the choice arguments, as they are sent over * the API but not received. */ argumentDecoder: jtv.Decoder<C>; /** * @internal */ argumentEncode: (c: C) => unknown; /** * @internal Returns a deocoder to decode the return value. */ resultDecoder: jtv.Decoder<R>; // note: no encoder for result, as they cannot be sent, only received. /** * The choice name. */ choiceName: string; } /** * @internal */ const registeredTemplates: {[key: string]: Template<object>} = {}; /** * @internal */ export const registerTemplate = <T extends object>(template: Template<T>): void => { const templateId = template.templateId; const oldTemplate = registeredTemplates[templateId]; if (oldTemplate === undefined) { registeredTemplates[templateId] = template as unknown as Template<object, unknown, string>; console.debug(`Registered template ${templateId}.`); } else { console.warn(`Trying to re-register template ${templateId}.`); } } /** * @internal */ export const lookupTemplate = (templateId: string): Template<object> => { const template = registeredTemplates[templateId]; if (template === undefined) { throw Error(`Failed to look up template ${templateId}. Make sure your @daml/types version agrees with the used Daml SDK version.`); } return template; } /** * @internal Turn a thunk into a memoized version of itself. The memoized thunk * invokes the original thunk only on its first invocation and caches the result * for later uses. We use this to implement a version of `jtv.lazy` with * memoization. */ export function memo<A>(thunk: () => A): () => A { let memoized: () => A = () => { const cache = thunk(); memoized = (): A => cache; return cache; }; // NOTE(MH): Since we change `memoized` when the resultung thunk is invoked // for the first time, we need to return it "by reference". Thus, we return // a closure which contains a reference to `memoized`. return (): A => memoized(); } /** * @internal Variation of `jtv.lazy` which memoizes the computed decoder on its * first invocation. */ export function lazyMemo<A>(mkDecoder: () => jtv.Decoder<A>): jtv.Decoder<A> { return jtv.lazy(memo(mkDecoder)); } /** * The counterpart of Daml's `()` type. */ // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface Unit { // NOTE(MH): Although eslint claims that the empty interface and the type // `{}` are equivalent, that's not true. The former does not extend // `{[key: string]: string}` whereas the latter does. In other words, // `Unit extends {[key: string]: string} ? true : false` is `false`, // whereas `{} extends {[key: string]: string} ? true : false` is `true`. // This might become important for defining a better version of the // `Query<T>` type in @daml/ledger. } /** * Companion obect of the [[Unit]] type. */ export const Unit: Serializable<Unit> = { decoder: jtv.object({}), encode: (t: Unit) => t, } /** * The counterpart of Daml's `Bool` type. */ export type Bool = boolean; /** * Companion object of the [[Bool]] type. */ export const Bool: Serializable<Bool> = { decoder: jtv.boolean(), encode: (b: Bool) => b, } /** * The counterpart of Daml's `Int` type. * * We represent `Int`s as string in order to avoid a loss of precision. */ export type Int = string; /** * Companion object of the [[Int]] type. */ export const Int: Serializable<Int> = { decoder: jtv.string(), encode: (i: Int) => i, } /** * The counterpart of Daml's `Numeric` type. * * We represent `Numeric`s as string in order to avoid a loss of precision. The string must match * the regular expression `-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?`. */ export type Numeric = string; /** * The counterpart of Daml's `Decimal` type. * * In Daml, Decimal's are the same as Numeric with precision 10. * */ export type Decimal = Numeric; /** * Companion function of the [[Numeric]] type. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars export const Numeric = (_: number): Serializable<Numeric> => ({ decoder: jtv.string(), encode: (n: Numeric): unknown => n, }) /** * Companion object of the [[Decimal]] type. */ export const Decimal: Serializable<Decimal> = Numeric(10) /** * The counterpart of Daml's `Text` type. */ export type Text = string; /** * Companion object of the [[Text]] type. */ export const Text: Serializable<Text> = { decoder: jtv.string(), encode: (t: Text) => t, } /** * The counterpart of Daml's `Time` type. * * We represent `Times`s as strings with format `YYYY-MM-DDThh:mm:ss[.ssssss]Z`. */ export type Time = string; /** * Companion object of the [[Time]] type. */ export const Time: Serializable<Time> = { decoder: jtv.string(), encode: (t: Time) => t, } /** * The counterpart of Daml's `Party` type. * * We represent `Party`s as strings matching the regular expression `[A-Za-z0-9:_\- ]+`. */ export type Party = string; /** * Companion object of the [[Party]] type. */ export const Party: Serializable<Party> = { decoder: jtv.string(), encode: (p: Party) => p, } /** * The counterpart of Daml's `[T]` list type. * * We represent lists using arrays. * * @typeparam T The type of the list values. */ export type List<T> = T[]; /** * Companion object of the [[List]] type. */ export const List = <T>(t: Serializable<T>): Serializable<T[]> => ({ decoder: jtv.array(t.decoder), encode: (l: List<T>): unknown => l.map((element: T) => t.encode(element)), }); /** * The counterpart of Daml's `Date` type. * * We represent `Date`s as strings with format `YYYY-MM-DD`. */ export type Date = string; /** * Companion object of the [[Date]] type. */ export const Date: Serializable<Date> = { decoder: jtv.string(), encode: (d: Date) => d, } /** * Used to `brand` [[ContractId]]. */ const ContractIdBrand: unique symbol = Symbol(); /** * The counterpart of Daml's `ContractId T` type. * * We represent `ContractId`s as strings. Their exact format of these strings depends on the ledger * the Daml application is running on. * * The purpose of the intersection with `{ [ContractIdBrand]: T }` is to * prevent accidental use of a `ContractId<T>` when a `ContractId<U>` is * needed (unless `T` is a subtype of `U`). This technique is known as * "branding" in the TypeScript community. * * @typeparam T The contract template. */ export type ContractId<T> = string & { [ContractIdBrand]: T } /** * Companion object of the [[ContractId]] type. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars export const ContractId = <T>(_t: Serializable<T>): Serializable<ContractId<T>> => ({ decoder: jtv.string() as jtv.Decoder<ContractId<T>>, encode: (c: ContractId<T>): unknown => c, }); /** * The counterpart of Daml's `Optional T` type. * * @typeparam T The type of the optionally present value. */ export type Optional<T> = null | OptionalInner<T> /** * Inner type of [[Optional]]. */ type OptionalInner<T> = null extends T ? [] | [Exclude<T, null>] : T /** * This class does the actual work behind the [[Optional]] companion function. In addition to * implementing the [[Serializable]] interface it also stores the [[Serializable]] instance of the * payload of the [[Optional]] and uses it to provide a decoder for the [[OptionalInner]] type. * * @typeparam T The type of the optionally present value. */ class OptionalWorker<T> implements Serializable<Optional<T>> { decoder: jtv.Decoder<Optional<T>>; private innerDecoder: jtv.Decoder<OptionalInner<T>>; encode: (o: Optional<T>) => unknown; constructor(payload: Serializable<T>) { if (payload instanceof OptionalWorker) { // NOTE(MH): `T` is of the form `Optional<U>` for some `U` here, that is // `T = Optional<U> = null | OptionalInner<U>`. Since `null` does not // extend `OptionalInner<V>` for any `V`, this implies // `OptionalInner<U> = Exclude<T, null>`. This also implies // `OptionalInner<T> = [] | [Exclude<T, null>]`. type OptionalInnerU = Exclude<T, null> const payloadInnerDecoder = payload.innerDecoder as jtv.Decoder<unknown> as jtv.Decoder<OptionalInnerU>; this.innerDecoder = jtv.oneOf<[] | [Exclude<T, null>]>( jtv.constant<[]>([]), jtv.tuple([payloadInnerDecoder]), ) as jtv.Decoder<OptionalInner<T>>; this.encode = (o: Optional<T>): unknown => { if (o === null) { // Top-level enclosing Optional where the type argument is also // Optional and we represent None. return null; } else { // The current type is Optional<Optional<...>> and the current value // is Some x. Therefore the nested value is represented as [] for // x = None or as [y] for x = Some y. In both cases mapping the // encoder of the type parameter does the right thing. return (o as unknown as T[]).map(nested => payload.encode(nested)); } } } else { // NOTE(MH): `T` is not of the form `Optional<U>` here and hence `null` // does not extend `T`. Thus, `OptionalInner<T> = T`. this.innerDecoder = payload.decoder as jtv.Decoder<OptionalInner<T>>; this.encode = (o: Optional<T>): unknown => { if (o === null) { // This branch is only reached if we are at the top-level and the // entire type is a non-nested Optional, i.e. Optional<U> where U is // not Optional. Recursive calls from the other branch would stop // before reaching this case, as nested None are empty lists and // never null. return null; } else { return payload.encode(o as unknown as T); } } } this.decoder = jtv.oneOf(jtv.constant(null), this.innerDecoder); } } /** * Companion function of the [[Optional]] type. */ export const Optional = <T>(t: Serializable<T>): Serializable<Optional<T>> => new OptionalWorker(t); /** * The counterpart of Daml's `TextMap T` type. * * We represent `TextMap`s as dictionaries. * * @typeparam T The type of the map values. */ export type TextMap<T> = { [key: string]: T }; /** * Companion object of the [[TextMap]] type. */ export const TextMap = <T>(t: Serializable<T>): Serializable<TextMap<T>> => ({ decoder: jtv.dict(t.decoder), encode: (tm: TextMap<T>): unknown => { const out: {[key: string]: unknown} = {}; Object.keys(tm).forEach((k) => { out[k] = t.encode(tm[k]); }); return out; } }); /** * The counterpart of Daml's `DA.Map.Map K V` type. * * This is an immutable map which compares keys via deep equality. The order of * iteration is unspecified; the only guarantee is that the order in `keys` and * `values` match, i.e. `m.get(k)` is (deep-, value-based) equal to * `[...m.values()][[...m.keys()].findIndex((l) => _.isEqual(k, l))]` * * @typeparam K The type of the map keys. * @typeparam V The type of the map values. */ export interface Map<K, V> { get: (k: K) => V | undefined; has: (k: K) => boolean; set: (k: K, v: V) => Map<K, V>; delete: (k: K) => Map<K, V>; keys: () => Iterator<K, undefined, undefined>; values: () => Iterator<V, undefined, undefined>; entries: () => Iterator<[K, V], undefined, undefined>; entriesArray: () => [K, V][]; forEach: <T, U>(f: (value: V, key: K, map: Map<K, V>) => T, u?: U) => void; } function* it<T>(arr: T[]): Iterator<T, undefined, undefined> { for(let i = 0; i < arr.length; i++) { yield _.cloneDeep(arr[i]); } return undefined; } // This code assumes that the decoder is only ever used in decoding values // straight from the API responses, and said raw responses are never reused // afterwards. This should be enforced by this class not being exported and the // daml-ledger module not letting raw JSON responses escape without going // through this. // // Without that assumption, the constructor would need to deep-copy its kvs // argument. class MapImpl<K, V> implements Map<K, V> { private _kvs: [K, V][]; private _keys: K[]; private _values: V[]; constructor(kvs: [K, V][]) { // sorting done so that generic object deep comparison would find equal // maps equal (as defined by jest's expect().toEqual()) this._kvs = _.sortBy(kvs, kv => JSON.stringify(kv[0])); this._keys = this._kvs.map(e => e[0]); this._values = this._kvs.map(e => e[1]); } private _idx(k: K): number { return this._keys.findIndex((l) => _.isEqual(k, l)); } has(k: K): boolean { return this._idx(k) !== -1; } get(k: K): V | undefined { return _.cloneDeep(this._values[this._idx(k)]); } set(k: K, v: V): Map<K, V> { if (this.has(k)) { const cpy = this._kvs.slice(); cpy[this._idx(k)] = _.cloneDeep([k, v]); return new MapImpl(cpy); } else { const head: [K, V][] = _.cloneDeep([[k, v]]); return new MapImpl(head.concat(this._kvs)); } } delete(k: K): Map<K, V> { const i = this._idx(k); if (i !== -1) { return new MapImpl(this._kvs.slice(0, i).concat(this._kvs.slice(i + 1))); } else { return this; } } keys(): Iterator<K, undefined, undefined> { return it(this._keys); } values(): Iterator<V, undefined, undefined> { return it(this._values); } entries(): Iterator<[K, V], undefined, undefined> { return it(this._kvs); } entriesArray(): [K, V][] { return _.cloneDeep(this._kvs); } forEach<T, U>(f: (v: V, k: K, m: Map<K, V>) => T, u?: U): void { const g = u ? f.bind(u) : f; for(const [k, v] of this._kvs) { g(v, k, this); } } } export const emptyMap = <K, V>(): Map<K, V> => new MapImpl<K, V>([]); /** * Companion function of the [[GenMap]] type. */ export const Map = <K, V>(kd: Serializable<K>, vd: Serializable<V>): Serializable<Map<K, V>> => ({ decoder: jtv.array(jtv.tuple([kd.decoder, vd.decoder])).map(kvs => new MapImpl(kvs)), encode: (m: Map<K, V>): unknown => m.entriesArray(), });
the_stack
import {memory, ones, Tensor, tensor2d, train, zeros} from '@tensorflow/tfjs-core'; import * as tfl from '../index'; import {describeMathCPUAndGPU, expectTensorsClose} from '../utils/test_utils'; import {FakeNumericDataset} from './dataset_fakes'; import {ClassWeight, ClassWeightMap} from './training_utils'; describeMathCPUAndGPU('LayersModel.fit() with classWeight', () => { // Reference Python code: // ```py // import numpy as np // import tensorflow as tf // // model = tf.keras.Sequential() // model.add(tf.keras.layers.Dense( // units=3, // input_shape=[2], // kernel_initializer='zeros', // activation='softmax')) // model.compile(loss='categorical_crossentropy', // metrics=['acc'], // optimizer=tf.keras.optimizers.SGD(1.0)) // model.summary() // // xs = np.array([[0, 1], [0, 2], [1, 10], [1, 20], [2, -10], [2, -20]], // dtype=np.float32) // ys = np.array([[1, 0, 0], // [1, 0, 0], // [0, 1, 0], // [0, 1, 0], // [0, 0, 1], // [0, 0, 1]], dtype=np.float32) // // model.fit(xs, // ys, // epochs=2, // class_weight=[{ // 0: 1, // 1: 10, // 2: 1 // }]) // print(model.get_weights()[0]) // ``` it('One output, multi-class, one-hot encoding', async () => { const model = tfl.sequential(); model.add(tfl.layers.dense({ units: 3, inputShape: [2], kernelInitializer: 'zeros', activation: 'softmax' })); model.compile({ loss: 'categoricalCrossentropy', metrics: ['acc'], optimizer: train.sgd(1) }); const xs = tensor2d([[0, 1], [0, 2], [1, 10], [1, 20], [2, -10], [2, -20]]); const ys = tensor2d( [[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1]]); const numTensors0 = memory().numTensors; const history = await model.fit( xs, ys, {epochs: 2, classWeight: [{0: 1, 1: 10, 2: 1}]}); expect(memory().numTensors).toEqual(numTensors0); // Assert no memory leak. expect(history.history.loss.length).toEqual(2); // These loss values are different than what the values would be // if there is no class weighting. expect(history.history.loss[0]).toBeCloseTo(4.3944); expect(history.history.loss[1]).toBeCloseTo(5.3727); expect(history.history.acc.length).toEqual(2); expect(history.history.acc[0]).toBeCloseTo(0.3333); expect(history.history.acc[1]).toBeCloseTo(0.6667); }); it('One output, multi-class, one-hot encoding, batchSize = 2', async () => { const model = tfl.sequential(); model.add(tfl.layers.dense({ units: 3, inputShape: [2], kernelInitializer: 'zeros', activation: 'softmax' })); model.compile({ loss: 'categoricalCrossentropy', metrics: ['acc'], optimizer: train.sgd(1) }); const xs = tensor2d([[0, 1], [0, 2], [1, 10], [1, 20], [2, -10], [2, -20]]); const ys = tensor2d( [[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1]]); const numTensors0 = memory().numTensors; const history = await model.fit(xs, ys, { epochs: 2, batchSize: 2, shuffle: false, classWeight: [{0: 1, 1: 10, 2: 1}] }); expect(memory().numTensors).toEqual(numTensors0); // Assert no memory leak. expect(history.history.loss.length).toEqual(2); // These loss values are different than what the values would be // if there is no class weighting. expect(history.history.loss[0]).toBeCloseTo(59.2691); expect(history.history.loss[1]).toBeCloseTo(10.7454); expect(history.history.acc.length).toEqual(2); expect(history.history.acc[0]).toBeCloseTo(0.3333); expect(history.history.acc[1]).toBeCloseTo(0.3333); }); it('One output, multi-class, one-hot encoding, validationData', async () => { const model = tfl.sequential(); model.add(tfl.layers.dense({ units: 3, inputShape: [2], kernelInitializer: 'zeros', activation: 'softmax' })); model.compile({ loss: 'categoricalCrossentropy', metrics: ['acc'], optimizer: train.sgd(1) }); const xs = tensor2d([[0, 1], [0, 2], [1, 10], [1, 20], [2, -10], [2, -20]]); const ys = tensor2d( [[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1]]); const numTensors0 = memory().numTensors; const history = await model.fit(xs, ys, { epochs: 2, classWeight: [{0: 1, 1: 10, 2: 1}], validationData: [xs, ys] }); expect(memory().numTensors).toEqual(numTensors0); // Assert no memory leak. expect(history.history.loss.length).toEqual(2); // These loss values are different than what the values would be // if there is no class weighting. expect(history.history.loss[0]).toBeCloseTo(4.3944); expect(history.history.loss[1]).toBeCloseTo(5.3727); expect(history.history.acc.length).toEqual(2); expect(history.history.acc[0]).toBeCloseTo(0.3333); expect(history.history.acc[1]).toBeCloseTo(0.6667); expect(history.history.val_loss.length).toEqual(2); expect(history.history.val_loss[0]).toBeCloseTo(5.3727); expect(history.history.val_loss[1]).toBeCloseTo(5.3727); expect(history.history.val_acc.length).toEqual(2); expect(history.history.val_acc[0]).toBeCloseTo(0.6667); expect(history.history.val_acc[1]).toBeCloseTo(0.6667); }); it('One output, multi-class, one-hot encoding, validationSplit', async () => { const model = tfl.sequential(); model.add(tfl.layers.dense({ units: 3, inputShape: [2], kernelInitializer: 'zeros', activation: 'softmax' })); model.compile({ loss: 'categoricalCrossentropy', metrics: ['acc'], optimizer: train.sgd(1) }); const xs = tensor2d([[0, 1], [0, 2], [1, 10], [1, 20], [2, -10], [2, -20]]); const ys = tensor2d( [[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1]]); const numTensors0 = memory().numTensors; const history = await model.fit( xs, ys, {epochs: 2, classWeight: [{0: 1, 1: 10, 2: 1}], validationSplit: 0.5}); expect(memory().numTensors).toEqual(numTensors0); // Assert no memory leak. expect(history.history.loss.length).toEqual(2); // These loss values are different than what the values would be // if there is no class weighting. expect(history.history.loss[0]).toBeCloseTo(4.3944); expect(history.history.loss[1]).toBeCloseTo(10.7454); expect(history.history.acc.length).toEqual(2); expect(history.history.acc[0]).toBeCloseTo(0.6667); expect(history.history.acc[1]).toBeCloseTo(0.3333); expect(history.history.val_loss.length).toEqual(2); expect(history.history.val_loss[0]).toBeCloseTo(2.9903e-05); expect(history.history.val_loss[1]).toBeCloseTo(2.9903e-05); expect(history.history.val_acc.length).toEqual(2); expect(history.history.val_acc[0]).toBeCloseTo(1); expect(history.history.val_acc[1]).toBeCloseTo(1); }); it('One output, multi-class, sparse encoding', async () => { const model = tfl.sequential(); model.add(tfl.layers.dense({ units: 3, inputShape: [2], kernelInitializer: 'zeros', activation: 'softmax' })); model.compile( {loss: 'sparseCategoricalCrossentropy', optimizer: train.sgd(1)}); const xs = tensor2d([[0, 1], [0, 2], [1, 10], [1, 20], [2, -10], [2, -20]]); const ys = tensor2d([[0], [0], [1], [1], [2], [2]]); const numTensors0 = memory().numTensors; const history = await model.fit(xs, ys, {epochs: 2, classWeight: {0: 1, 1: 10, 2: 1}}); expect(memory().numTensors).toEqual(numTensors0); // Assert no memory leak. expect(history.history.loss.length).toEqual(2); // These loss values are different than what the values would be // if there is no class weighting. expect(history.history.loss[0]).toBeCloseTo(4.3944); expect(history.history.loss[1]).toBeCloseTo(5.3727); }); // Reference Python code. // ```py // import numpy as np // import tensorflow as tf // // model = tf.keras.Sequential() // model.add(tf.keras.layers.Dense( // units=1, // input_shape=[2], // kernel_initializer='zeros', // activation='sigmoid')) // model.compile(loss='binary_crossentropy', // optimizer=tf.keras.optimizers.SGD(1.0)) // model.summary() // // xs = np.array([[0, 1], [0, 2], [1, 10], [1, 20]], // dtype=np.float32) // ys = np.array([[0], [0], [1], [1]], dtype=np.float32) // // # model.fit(xs, ys, epochs=1) // model.fit(xs, // ys, // epochs=3, // class_weight=[{ // 0: 0.1, // 1: 0.9 // }]) // print(model.get_weights()[0]) // ``` it('One output, binary classes, sparse encoding', async () => { const model = tfl.sequential(); model.add(tfl.layers.dense({ units: 1, inputShape: [2], kernelInitializer: 'zeros', activation: 'sigmoid' })); model.compile({loss: 'binaryCrossentropy', optimizer: train.sgd(1)}); const xs = tensor2d([[0, 1], [0, 2], [1, 10], [1, 20]]); const ys = tensor2d([[0], [0], [1], [1]]); const numTensors0 = memory().numTensors; const history = await model.fit(xs, ys, {epochs: 2, classWeight: [{0: 0.1, 1: 0.9}]}); expect(memory().numTensors).toEqual(numTensors0); // Assert no memory leak. expect(history.history.loss.length).toEqual(2); // These loss values are different than what the values would be // if there is no class weighting. expect(history.history.loss[0]).toBeCloseTo(0.3466); expect(history.history.loss[1]).toBeCloseTo(0.2611); }); // Python Reference Code: // ```py // import numpy as np // import tensorflow as tf // // inp = tf.keras.Input(shape=[2]) // y1 = tf.keras.layers.Dense( // units=3, // input_shape=[2], // kernel_initializer='zeros', // activation='softmax')(inp) // y2 = tf.keras.layers.Dense( // units=1, // input_shape=[2], // kernel_initializer='zeros', // activation='sigmoid')(inp) // model = tf.keras.Model(inp, [y1, y2]) // model.compile( // loss=['sparse_categorical_crossentropy', 'binary_crossentropy'], // optimizer=tf.keras.optimizers.SGD(1.0)) // model.summary() // // xs = np.array( // [[0, 1], [0, 2], [1, 10], [1, 20], [2, 10], [2, 20]], // dtype=np.float32) // y1s = np.array( // [[0], [0], [1], [1], [2], [2]], dtype=np.float32) // y2s = np.array( // [[0], [0], [1], [1], [1], [1]], dtype=np.float32) // // # model.fit(xs, ys, epochs=1) // model.fit(xs, // [y1s, y2s], // epochs=3, // class_weight=[{ // 0: 0.1, // 1: 0.2, // 2: 0.7 // }, { // 0: 0.1, // 1: 0.9 // }]) // ``` it('Two outputs, classWeight as array', async () => { const inp = tfl.input({shape: [2]}); const y1 = tfl.layers .dense({ units: 3, inputShape: [2], kernelInitializer: 'zeros', activation: 'softmax' }) .apply(inp) as tfl.SymbolicTensor; const y2 = tfl.layers .dense({ units: 1, inputShape: [2], kernelInitializer: 'zeros', activation: 'sigmoid' }) .apply(inp) as tfl.SymbolicTensor; const model = tfl.model({inputs: inp, outputs: [y1, y2]}); model.compile({ loss: ['sparseCategoricalCrossentropy', 'binaryCrossentropy'], optimizer: train.sgd(1) }); const xs = tensor2d([[0, 1], [0, 2], [1, 10], [1, 20], [2, 10], [2, 20]]); const y1s = tensor2d([[0], [0], [1], [1], [2], [2]]); const y2s = tensor2d([[0], [0], [1], [1], [1], [1]]); const numTensors0 = memory().numTensors; const history = await model.fit( xs, [y1s, y2s], {epochs: 3, classWeight: [{0: 0.1, 1: 0.2, 2: 0.7}, {0: 0.1, 1: 0.9}]}); expect(memory().numTensors).toEqual(numTensors0); // Assert no memory leak. expect(history.history.loss.length).toEqual(3); expect(history.history.loss[0]).toBeCloseTo(0.8052); expect(history.history.loss[1]).toBeCloseTo(1.4887); expect(history.history.loss[2]).toBeCloseTo(1.4782); const lossKey0 = `${model.outputNames[0]}_loss`; expect(history.history[lossKey0].length).toEqual(3); expect(history.history[lossKey0][0]).toBeCloseTo(0.3662); expect(history.history[lossKey0][1]).toBeCloseTo(1.2553); expect(history.history[lossKey0][2]).toBeCloseTo(1.2485); const lossKey1 = `${model.outputNames[1]}_loss`; expect(history.history[lossKey1].length).toEqual(3); expect(history.history[lossKey1][0]).toBeCloseTo(0.4390); expect(history.history[lossKey1][1]).toBeCloseTo(0.2333); expect(history.history[lossKey1][2]).toBeCloseTo(0.2297); }); it('Two outputs, classWeight as array, one being null', async () => { const inp = tfl.input({shape: [2]}); const y1 = tfl.layers .dense({ units: 3, inputShape: [2], kernelInitializer: 'zeros', activation: 'softmax' }) .apply(inp) as tfl.SymbolicTensor; const y2 = tfl.layers .dense({ units: 1, inputShape: [2], kernelInitializer: 'zeros', activation: 'sigmoid' }) .apply(inp) as tfl.SymbolicTensor; const model = tfl.model({inputs: inp, outputs: [y1, y2]}); model.compile({ loss: ['sparseCategoricalCrossentropy', 'binaryCrossentropy'], optimizer: train.sgd(1) }); const xs = tensor2d([[0, 1], [0, 2], [1, 10], [1, 20], [2, 10], [2, 20]]); const y1s = tensor2d([[0], [0], [1], [1], [2], [2]]); const y2s = tensor2d([[0], [0], [1], [1], [1], [1]]); const numTensors0 = memory().numTensors; const history = await model.fit( xs, [y1s, y2s], {epochs: 3, classWeight: [null, {0: 0.1, 1: 0.9}], shuffle: false}); expect(memory().numTensors).toEqual(numTensors0); // Assert no memory leak. // Note that the following values don't match results from Python, // which is a bug in Python TensorFlow / tf.keras. But the final // kernel value does match Python results. (See b/136123157). expect(history.history.loss.length).toEqual(3); expect(history.history.loss[0]).toBeCloseTo(1.5376); expect(history.history.loss[1]).toBeCloseTo(3.1466); expect(history.history.loss[2]).toBeCloseTo(7.9620); const lossKey0 = `${model.outputNames[0]}_loss`; expect(history.history[lossKey0].length).toEqual(3); expect(history.history[lossKey0][0]).toBeCloseTo(1.0986); expect(history.history[lossKey0][1]).toBeCloseTo(2.9113); expect(history.history[lossKey0][2]).toBeCloseTo(7.7323); const lossKey1 = `${model.outputNames[1]}_loss`; expect(history.history[lossKey1].length).toEqual(3); expect(history.history[lossKey1][0]).toBeCloseTo(0.4390); expect(history.history[lossKey1][1]).toBeCloseTo(0.2333); expect(history.history[lossKey1][2]).toBeCloseTo(0.2298); expectTensorsClose(model.getWeights()[0], tensor2d([ [-0.3333333, -0.03197281, 0.3653062], [-2.0025878, 1.9823718, 0.02021614] ])); }); it('Two outputs, classWeight as map, one output no weighting', async () => { const inp = tfl.input({shape: [2]}); const y1 = tfl.layers .dense({ units: 3, inputShape: [2], kernelInitializer: 'zeros', activation: 'softmax' }) .apply(inp) as tfl.SymbolicTensor; const y2 = tfl.layers .dense({ units: 1, inputShape: [2], kernelInitializer: 'zeros', activation: 'sigmoid' }) .apply(inp) as tfl.SymbolicTensor; const model = tfl.model({inputs: inp, outputs: [y1, y2]}); model.compile({ loss: ['sparseCategoricalCrossentropy', 'binaryCrossentropy'], optimizer: train.sgd(1) }); const xs = tensor2d([[0, 1], [0, 2], [1, 10], [1, 20], [2, 10], [2, 20]]); const y1s = tensor2d([[0], [0], [1], [1], [2], [2]]); const y2s = tensor2d([[0], [0], [1], [1], [1], [1]]); const numTensors0 = memory().numTensors; const history = await model.fit(xs, [y1s, y2s], { epochs: 3, classWeight: { [model.outputNames[1]]: {0: 0.1, 1: 0.9}, }, shuffle: false }); expect(memory().numTensors).toEqual(numTensors0); // Assert no memory leak. // Note that the following values don't match results from Python, // which is a bug in Python TensorFlow / tf.keras. But the final // kernel value does match Python results. expect(history.history.loss.length).toEqual(3); expect(history.history.loss[0]).toBeCloseTo(1.5376); expect(history.history.loss[1]).toBeCloseTo(3.1466); expect(history.history.loss[2]).toBeCloseTo(7.9620); const lossKey0 = `${model.outputNames[0]}_loss`; expect(history.history[lossKey0].length).toEqual(3); expect(history.history[lossKey0][0]).toBeCloseTo(1.0986); expect(history.history[lossKey0][1]).toBeCloseTo(2.9113); expect(history.history[lossKey0][2]).toBeCloseTo(7.7323); const lossKey1 = `${model.outputNames[1]}_loss`; expect(history.history[lossKey1].length).toEqual(3); expect(history.history[lossKey1][0]).toBeCloseTo(0.4390); expect(history.history[lossKey1][1]).toBeCloseTo(0.2333); expect(history.history[lossKey1][2]).toBeCloseTo(0.2298); expectTensorsClose(model.getWeights()[0], tensor2d([ [-0.3333333, -0.03197281, 0.3653062], [-2.0025878, 1.9823718, 0.02021614] ])); }); it('Two outputs, classWeight as map', async () => { const inp = tfl.input({shape: [2]}); const y1 = tfl.layers .dense({ units: 3, inputShape: [2], kernelInitializer: 'zeros', activation: 'softmax' }) .apply(inp) as tfl.SymbolicTensor; const y2 = tfl.layers .dense({ units: 1, inputShape: [2], kernelInitializer: 'zeros', activation: 'sigmoid' }) .apply(inp) as tfl.SymbolicTensor; const model = tfl.model({inputs: inp, outputs: [y1, y2]}); model.compile({ loss: ['sparseCategoricalCrossentropy', 'binaryCrossentropy'], optimizer: train.sgd(1) }); const xs = tensor2d([[0, 1], [0, 2], [1, 10], [1, 20], [2, 10], [2, 20]]); const y1s = tensor2d([[0], [0], [1], [1], [2], [2]]); const y2s = tensor2d([[0], [0], [1], [1], [1], [1]]); const numTensors0 = memory().numTensors; const history = await model.fit(xs, [y1s, y2s], { epochs: 3, classWeight: { [model.outputNames[0]]: {0: 0.1, 1: 0.2, 2: 0.7}, [model.outputNames[1]]: {0: 0.1, 1: 0.9} } }); expect(memory().numTensors).toEqual(numTensors0); // Assert no memory leak. expect(history.history.loss.length).toEqual(3); expect(history.history.loss[0]).toBeCloseTo(0.8052); expect(history.history.loss[1]).toBeCloseTo(1.4887); expect(history.history.loss[2]).toBeCloseTo(1.4782); const lossKey0 = `${model.outputNames[0]}_loss`; expect(history.history[lossKey0].length).toEqual(3); expect(history.history[lossKey0][0]).toBeCloseTo(0.3662); expect(history.history[lossKey0][1]).toBeCloseTo(1.2553); expect(history.history[lossKey0][2]).toBeCloseTo(1.2485); const lossKey1 = `${model.outputNames[1]}_loss`; expect(history.history[lossKey1].length).toEqual(3); expect(history.history[lossKey1][0]).toBeCloseTo(0.4390); expect(history.history[lossKey1][1]).toBeCloseTo(0.2333); expect(history.history[lossKey1][2]).toBeCloseTo(0.2297); }); }); describeMathCPUAndGPU('LayersModel.fitDataset() with classWeight', () => { // Reference Python code: // ```py // import numpy as np // import tensorflow as tf // // batch_size = 8 // num_batches = 3 // epochs = 2 // // xs = np.ones([batch_size * num_batches * epochs, 1]) // ys = np.concatenate([ // np.zeros([int(batch_size * num_batches * epochs / 2), 1]), // np.ones([int(batch_size * num_batches * epochs / 2), 1])], // axis=0) // // dataset = tf.data.Dataset.from_tensor_slices( // (xs, ys)).batch(batch_size) // // model = tf.keras.Sequential() // model.add(tf.keras.layers.Dense( // 1, // input_shape=[1], // activation='sigmoid', // kernel_initializer='zeros')) // model.compile(loss='binary_crossentropy', // metrics=['acc'], // optimizer='sgd') // // history = model.fit( // dataset, // steps_per_epoch=num_batches, // epochs=epochs, // class_weight={0: 0.1, 1: 2}) // print(history.history) // ``` it('One output, binary crossentropy, acc metric', async () => { const model = tfl.sequential(); model.add(tfl.layers.dense({ units: 1, inputShape: [1], kernelInitializer: 'zeros', activation: 'sigmoid' })); model.compile( {loss: 'binaryCrossentropy', metrics: ['acc'], optimizer: 'sgd'}); const batchSize = 8; const batchesPerEpoch = 3; const epochs = 2; const xTensorsFunc = () => [ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1])]; const yTensorsFunc = () => [zeros([batchSize, 1]), zeros([batchSize, 1]), zeros([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1])]; const dataset = new FakeNumericDataset({ xShape: [1], yShape: [1], batchSize, numBatches: batchesPerEpoch * epochs, xTensorsFunc, yTensorsFunc }); const classWeight: ClassWeight = {0: 0.1, 1: 2}; // Do a burn-in call to account for initialization of cached tensors (for // the memory-leak check below). await model.fitDataset(dataset, {batchesPerEpoch, epochs: 1, classWeight}); model.setWeights([zeros([1, 1]), zeros([1])]); const numTensors0 = memory().numTensors; const history = await model.fitDataset(dataset, {batchesPerEpoch, epochs, classWeight}); const numTensors1 = memory().numTensors; expect(numTensors1).toEqual(numTensors0); // The loss and acc values are different if no classWeight is used. expect(history.history.loss.length).toEqual(2); expect(history.history.loss[0]).toBeCloseTo(0.0693); expect(history.history.loss[1]).toBeCloseTo(1.3695); expect(history.history.acc.length).toEqual(2); expect(history.history.acc[0]).toBeCloseTo(1); expect(history.history.acc[1]).toBeCloseTo(0.6667); }); // Reference Python code: // ```py // import numpy as np // import tensorflow as tf // // batch_size = 8 // num_batches = 3 // epochs = 2 // // xs = np.ones([batch_size * num_batches * epochs, 1]) // ys = np.concatenate([ // np.zeros([int(batch_size * num_batches * epochs / 2), 1]), // np.ones([int(batch_size * num_batches * epochs / 2), 1])], // axis=0) // // dataset = tf.data.Dataset.from_tensor_slices( // (xs, ys)).batch(batch_size) // // model = tf.keras.Sequential() // model.add(tf.keras.layers.Dense( // 1, // input_shape=[1], // activation='sigmoid', // kernel_initializer='zeros')) // model.compile(loss='binary_crossentropy', // metrics=['acc'], // optimizer='sgd') // // history = model.fit( // dataset, // steps_per_epoch=num_batches, // epochs=epochs, // class_weight={0: 0.1, 1: 2}) // print(history.history) // ``` it('One output, binary crossentropy,validation', async () => { const model = tfl.sequential(); model.add(tfl.layers.dense({ units: 1, inputShape: [1], kernelInitializer: 'zeros', activation: 'sigmoid' })); model.compile( {loss: 'binaryCrossentropy', metrics: ['acc'], optimizer: 'sgd'}); const batchSize = 8; const batchesPerEpoch = 3; const epochs = 2; const xTensorsFunc = () => [ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1])]; const yTensorsFunc = () => [zeros([batchSize, 1]), zeros([batchSize, 1]), zeros([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1])]; const dataset = new FakeNumericDataset({ xShape: [1], yShape: [1], batchSize, numBatches: batchesPerEpoch * epochs, xTensorsFunc, yTensorsFunc }); const classWeight: ClassWeight = {0: 0.1, 1: 2}; // Do a burn-in call to account for initialization of cached tensors (for // the memory-leak check below). await model.fitDataset( dataset, {batchesPerEpoch, epochs: 1, classWeight, validationData: dataset}); model.setWeights([zeros([1, 1]), zeros([1])]); const numTensors0 = memory().numTensors; const history = await model.fitDataset( dataset, {batchesPerEpoch, epochs, classWeight, validationData: dataset}); const numTensors1 = memory().numTensors; expect(numTensors1).toEqual(numTensors0); // The loss and acc values are different if no classWeight is used. expect(history.history.loss.length).toEqual(2); expect(history.history.loss[0]).toBeCloseTo(0.0693); expect(history.history.loss[1]).toBeCloseTo(1.3695); expect(history.history.acc.length).toEqual(2); expect(history.history.acc[0]).toBeCloseTo(1); expect(history.history.acc[1]).toBeCloseTo(0.6667); expect(history.history.val_loss.length).toEqual(2); expect(history.history.val_loss[0]).toBeCloseTo(0.693148); expect(history.history.val_loss[1]).toBeCloseTo(0.693546); expect(history.history.val_acc.length).toEqual(2); expect(history.history.val_acc[0]).toBeCloseTo(0.5); expect(history.history.val_acc[1]).toBeCloseTo(0.5); }); // Reference Python code: // ```py // import numpy as np // import tensorflow as tf // // batch_size = 8 // num_batches = 3 // epochs = 2 // // xs = np.ones([batch_size * num_batches * epochs, 1]) // ys1 = np.concatenate([ // np.zeros([int(batch_size * num_batches * epochs / 2), 1]), // np.ones([int(batch_size * num_batches * epochs / 2), 1])], // axis=0) // ys2 = np.concatenate([ // np.ones([int(batch_size * num_batches * epochs / 2), 1]), // np.zeros([int(batch_size * num_batches * epochs / 2), 1])], // axis=0) // // dataset = tf.data.Dataset.from_tensor_slices( // (xs, {'out1': ys1, 'out2': ys2})).batch(batch_size) // // inp = tf.keras.Input(shape=[1]) // out1 = tf.keras.layers.Dense( // 1, // input_shape=[1], // activation='sigmoid', // kernel_initializer='zeros', // name='out1')(inp) // out2 = tf.keras.layers.Dense( // 1, // input_shape=[1], // activation='sigmoid', // kernel_initializer='zeros', // name='out2')(inp) // // model = tf.keras.Model(inp, [out1, out2]) // model.compile( // loss=['binary_crossentropy', 'binary_crossentropy'], // optimizer='sgd') // // history = model.fit( // dataset, // steps_per_epoch=num_batches, // epochs=epochs, // class_weight=[{0: 0.1, 1: 2}, {0: 5, 1: 0.5}]) // print(history.history) // ``` it('Two outputs, binary crossentropy, acc metric', async () => { const inp = tfl.input({shape: [1]}); const out1 = tfl.layers .dense({ units: 1, inputShape: [1], kernelInitializer: 'zeros', activation: 'sigmoid' }) .apply(inp) as tfl.SymbolicTensor; const out2 = tfl.layers .dense({ units: 1, inputShape: [1], kernelInitializer: 'zeros', activation: 'sigmoid' }) .apply(inp) as tfl.SymbolicTensor; const model = tfl.model({inputs: inp, outputs: [out1, out2]}); model.compile( {loss: ['binaryCrossentropy', 'binaryCrossentropy'], optimizer: 'sgd'}); const batchSize = 8; const batchesPerEpoch = 3; const epochs = 2; const xTensorsFunc = () => [ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1])]; const yTensorsFunc = () => { const output: {[name: string]: Tensor[]} = {}; output[model.outputNames[0]] = [ zeros([batchSize, 1]), zeros([batchSize, 1]), zeros([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]) ]; output[model.outputNames[1]] = [ ones([batchSize, 1]), ones([batchSize, 1]), ones([batchSize, 1]), zeros([batchSize, 1]), zeros([batchSize, 1]), zeros([batchSize, 1]) ]; return output; }; const dataset = new FakeNumericDataset({ xShape: [1], yShape: {[model.outputNames[0]]: [1], [model.outputNames[1]]: [1]}, batchSize, numBatches: batchesPerEpoch * epochs, xTensorsFunc, yTensorsFunc }); const classWeight: ClassWeightMap = { [model.outputNames[0]]: {0: 0.1, 1: 2}, [model.outputNames[1]]: {0: 5, 1: 0.5} }; // Do a burn-in call to account for initialization of cached tensors (for // the memory-leak check below). await model.fitDataset(dataset, {batchesPerEpoch, epochs: 1, classWeight}); // model.setWeights([zeros([1, 1]), zeros([1])]); const numTensors0 = memory().numTensors; const history = await model.fitDataset(dataset, {batchesPerEpoch, epochs, classWeight}); const numTensors1 = memory().numTensors; expect(numTensors1).toEqual(numTensors0); // The loss and acc values are different if no classWeight is used. const totalLoss = history.history.loss; expect(totalLoss.length).toEqual(2); expect(totalLoss[0]).toBeCloseTo(0.4146); expect(totalLoss[1]).toBeCloseTo(4.7882); const loss0 = history.history[`${model.outputNames[0]}_loss`]; expect(loss0.length).toEqual(2); expect(loss0[0]).toBeCloseTo(0.0693); expect(loss0[1]).toBeCloseTo(1.3695); const loss1 = history.history[`${model.outputNames[1]}_loss`]; expect(loss1.length).toEqual(2); expect(loss1[0]).toBeCloseTo(0.3453); expect(loss1[1]).toBeCloseTo(3.4158); }); });
the_stack
import * as CLangCommon from '../clang-common'; import * as Either from '../either'; import * as Error from '../error'; import * as ObjectSpec from '../object-spec'; import * as ObjectSpecHelpers from '../object-spec-helpers'; import * as ObjectSpecParser from '../object-spec-parser'; describe('ObjectSpecParser', function () { describe('#parse', function () { it('parses a value object with two properties that are valid', function () { const valueFileContents = 'RMSomething {\n' + 'NSArray *someArray\n ' + 'BOOL someBoolean\n' + '}'; const actualResult: Either.Either<Error.Error[], ObjectSpec.Type> = ObjectSpecParser.parse(valueFileContents); const expectedFoundType: ObjectSpec.Type = { annotations: {}, attributes: [ new ObjectSpecHelpers.AttributeBuilder( 'someArray', new ObjectSpecHelpers.AttributeTypeBuilder( 'NSArray', 'NSArray*', 'NSObject', ), ).asObject(), new ObjectSpecHelpers.AttributeBuilder( 'someBoolean', new ObjectSpecHelpers.AttributeTypeBuilder('BOOL', 'BOOL', null), ).asObject(), ], comments: [], typeLookups: [], excludes: [], includes: [], typeName: 'RMSomething', libraryName: null, }; const expectedResult: Either.Either<Error.Error[], ObjectSpec.Type> = Either.Right<Error.Error[], ObjectSpec.Type>(expectedFoundType); expect(actualResult).toEqualJSON(expectedResult); }); it( 'parses a value object with two properties and lots of custom ' + 'information that is valid', function () { const valueFileContents = '%library name=RMSomethingLibrary\n' + '%type name=Foo library=Bar file=NSObject+Baz canForwardDeclare=false\n' + '%type name=Scumbag library=Steve\n' + 'RMSomething {\n' + ' %import file=RMSomeOtherFile library=RMCustomLibrary\n' + ' RMBlah *someBlah\n' + ' RMSomeValue(BOOL) someValue\n' + '}'; const actualResult: Either.Either<Error.Error[], ObjectSpec.Type> = ObjectSpecParser.parse(valueFileContents); const expectedFoundType: ObjectSpec.Type = { annotations: { library: [ { properties: { name: 'RMSomethingLibrary', }, }, ], type: [ { properties: { name: 'Foo', library: 'Bar', file: 'NSObject+Baz', canForwardDeclare: 'false', }, }, { properties: { name: 'Scumbag', library: 'Steve', }, }, ], }, attributes: [ new ObjectSpecHelpers.AttributeBuilder( 'someBlah', new ObjectSpecHelpers.AttributeTypeBuilder( 'RMBlah', 'RMBlah*', 'NSObject', ) .withFileTypeIsDefinedIn('RMSomeOtherFile') .withLibraryTypeIsDefinedIn('RMCustomLibrary'), ) .withAnnotations({ import: [ { properties: { file: 'RMSomeOtherFile', library: 'RMCustomLibrary', }, }, ], }) .asObject(), new ObjectSpecHelpers.AttributeBuilder( 'someValue', new ObjectSpecHelpers.AttributeTypeBuilder( 'RMSomeValue', 'RMSomeValue', 'BOOL', ), ).asObject(), ], comments: [], typeLookups: [ { name: 'Foo', library: 'Bar', file: 'NSObject+Baz', canForwardDeclare: false, }, { name: 'Scumbag', library: 'Steve', file: null, canForwardDeclare: true, }, ], excludes: [], includes: [], typeName: 'RMSomething', libraryName: 'RMSomethingLibrary', }; const expectedResult: Either.Either<Error.Error[], ObjectSpec.Type> = Either.Right<Error.Error[], ObjectSpec.Type>(expectedFoundType); expect(actualResult).toEqualJSON(expectedResult); }, ); it('parses a value object with two properties with nullability', function () { const valueFileContents = '%library name=RMSomethingLibrary\n' + 'RMSomething {\n' + ' %nullable\n' + ' RMBlah *someBlah\n' + ' %nonnull\n' + ' RMBlah *someValue\n' + '}'; const actualResult: Either.Either<Error.Error[], ObjectSpec.Type> = ObjectSpecParser.parse(valueFileContents); const expectedFoundType: ObjectSpec.Type = { annotations: { library: [ { properties: { name: 'RMSomethingLibrary', }, }, ], }, attributes: [ new ObjectSpecHelpers.AttributeBuilder( 'someBlah', new ObjectSpecHelpers.AttributeTypeBuilder( 'RMBlah', 'RMBlah*', 'NSObject', ), ) .withAnnotations({ nullable: [ { properties: {}, }, ], }) .withNullability(CLangCommon.Nullability.Nullable()) .asObject(), new ObjectSpecHelpers.AttributeBuilder( 'someValue', new ObjectSpecHelpers.AttributeTypeBuilder( 'RMBlah', 'RMBlah*', 'NSObject', ), ) .withAnnotations({ nonnull: [ { properties: {}, }, ], }) .withNullability(CLangCommon.Nullability.Nonnull()) .asObject(), ], comments: [], typeLookups: [], excludes: [], includes: [], typeName: 'RMSomething', libraryName: 'RMSomethingLibrary', }; const expectedResult: Either.Either<Error.Error[], ObjectSpec.Type> = Either.Right<Error.Error[], ObjectSpec.Type>(expectedFoundType); expect(actualResult).toEqualJSON(expectedResult); }); it('parses a value object with properties with generics', function () { const valueFileContents = '%library name=RMSomethingLibrary\n' + 'RMSomething {\n' + ' NSEvolvedDictionary<BOOL, NSFoo *, NSBar *, NSInteger> *multiple\n' + ' NSArray<NSDictionary<NSArray<NSString *>, NSString *> *> *nested\n' + ' NSDictionary<id<FooProtocol>, NSArray<id<BarProtocol>> *> *protocols\n' + ' CKAction<NSDictionary<NSArray<NSString *> *, id<FooProtocol>> *> ckAction\n' + '}'; const actualResult: Either.Either<Error.Error[], ObjectSpec.Type> = ObjectSpecParser.parse(valueFileContents); const expectedFoundType: ObjectSpec.Type = { annotations: { library: [ { properties: { name: 'RMSomethingLibrary', }, }, ], }, attributes: [ new ObjectSpecHelpers.AttributeBuilder( 'multiple', new ObjectSpecHelpers.AttributeTypeBuilder( 'NSEvolvedDictionary', 'NSEvolvedDictionary<BOOL, NSFoo *, NSBar *, NSInteger>*', 'NSObject', ).withReferencedGenericTypes([ { name: 'BOOL', conformingProtocol: null, referencedGenericTypes: [], }, { name: 'NSFoo', conformingProtocol: null, referencedGenericTypes: [], }, { name: 'NSBar', conformingProtocol: null, referencedGenericTypes: [], }, { name: 'NSInteger', conformingProtocol: null, referencedGenericTypes: [], }, ]), ).asObject(), new ObjectSpecHelpers.AttributeBuilder( 'nested', new ObjectSpecHelpers.AttributeTypeBuilder( 'NSArray', 'NSArray<NSDictionary<NSArray<NSString *>, NSString *> *>*', 'NSObject', ).withReferencedGenericTypes([ { name: 'NSDictionary', conformingProtocol: null, referencedGenericTypes: [ { name: 'NSArray', conformingProtocol: null, referencedGenericTypes: [ { name: 'NSString', conformingProtocol: null, referencedGenericTypes: [], }, ], }, { name: 'NSString', conformingProtocol: null, referencedGenericTypes: [], }, ], }, ]), ).asObject(), new ObjectSpecHelpers.AttributeBuilder( 'protocols', new ObjectSpecHelpers.AttributeTypeBuilder( 'NSDictionary', 'NSDictionary<id<FooProtocol>, NSArray<id<BarProtocol>> *>*', 'NSObject', ).withReferencedGenericTypes([ { name: 'id', conformingProtocol: 'FooProtocol', referencedGenericTypes: [], }, { name: 'NSArray', conformingProtocol: null, referencedGenericTypes: [ { name: 'id', conformingProtocol: 'BarProtocol', referencedGenericTypes: [], }, ], }, ]), ).asObject(), new ObjectSpecHelpers.AttributeBuilder( 'ckAction', new ObjectSpecHelpers.AttributeTypeBuilder( 'CKAction', 'CKAction<NSDictionary<NSArray<NSString *> *, id<FooProtocol>> *>', 'NSObject', ).withReferencedGenericTypes([ { name: 'NSDictionary', conformingProtocol: null, referencedGenericTypes: [ { name: 'NSArray', conformingProtocol: null, referencedGenericTypes: [ { name: 'NSString', conformingProtocol: null, referencedGenericTypes: [], }, ], }, { name: 'id', conformingProtocol: 'FooProtocol', referencedGenericTypes: [], }, ], }, ]), ).asObject(), ], comments: [], typeLookups: [], excludes: [], includes: [], typeName: 'RMSomething', libraryName: 'RMSomethingLibrary', }; const expectedResult: Either.Either<Error.Error[], ObjectSpec.Type> = Either.Right<Error.Error[], ObjectSpec.Type>(expectedFoundType); expect(actualResult).toEqualJSON(expectedResult); }); it('parses a value object with a generic type with no parameters', function () { const valueFileContents = 'RMSomething {\n FBFoo<> *foo\n}'; const actualResult: Either.Either<Error.Error[], ObjectSpec.Type> = ObjectSpecParser.parse(valueFileContents); const expectedFoundType: ObjectSpec.Type = { annotations: {}, attributes: [ new ObjectSpecHelpers.AttributeBuilder( 'foo', new ObjectSpecHelpers.AttributeTypeBuilder( 'FBFoo', 'FBFoo<>*', 'NSObject', ), ).asObject(), ], comments: [], typeLookups: [], excludes: [], includes: [], typeName: 'RMSomething', libraryName: null, }; const expectedResult: Either.Either<Error.Error[], ObjectSpec.Type> = Either.Right<Error.Error[], ObjectSpec.Type>(expectedFoundType); expect(actualResult).toEqualJSON(expectedResult); }); it('parses a value object which is invalid', function () { const valueFileContents = 'RMSomething {{}'; const actualResult: Either.Either<Error.Error[], ObjectSpec.Type> = ObjectSpecParser.parse(valueFileContents); const expectedResult: Either.Either<Error.Error[], ObjectSpec.Type> = Either.Left<Error.Error[], ObjectSpec.Type>([ Error.Error('(line 1, column 14) expected string matching {}}'), ]); expect(actualResult).toEqualJSON(expectedResult); }); it('parses an empty and valid value object', function () { const valueFileContents = 'RMSomething {}'; const actualResult: Either.Either<Error.Error[], ObjectSpec.Type> = ObjectSpecParser.parse(valueFileContents); const expectedResult: Either.Either<Error.Error[], ObjectSpec.Type> = Either.Right<Error.Error[], ObjectSpec.Type>({ annotations: {}, attributes: [], comments: [], typeLookups: [], excludes: [], includes: [], typeName: 'RMSomething', libraryName: null, }); expect(actualResult).toEqualJSON(expectedResult); }); }); });
the_stack
declare module androidx { export module biometric { export class AuthenticationCallbackProvider { public static class: java.lang.Class<androidx.biometric.AuthenticationCallbackProvider>; } export module AuthenticationCallbackProvider { export class Api28Impl { public static class: java.lang.Class<androidx.biometric.AuthenticationCallbackProvider.Api28Impl>; } export class Api30Impl { public static class: java.lang.Class<androidx.biometric.AuthenticationCallbackProvider.Api30Impl>; } export class Listener { public static class: java.lang.Class<androidx.biometric.AuthenticationCallbackProvider.Listener>; } } } } declare module androidx { export module biometric { export class AuthenticatorUtils { public static class: java.lang.Class<androidx.biometric.AuthenticatorUtils>; } } } declare module androidx { export module biometric { export class BiometricErrorData { public static class: java.lang.Class<androidx.biometric.BiometricErrorData>; public equals(param0: any): boolean; public hashCode(): number; } } } declare module androidx { export module biometric { export class BiometricFragment { public static class: java.lang.Class<androidx.biometric.BiometricFragment>; public onStart(): void; public onCreate(param0: globalAndroid.os.Bundle): void; public onActivityResult(param0: number, param1: number, param2: globalAndroid.content.Intent): void; public constructor(); public onStop(): void; } export module BiometricFragment { export class Api21Impl { public static class: java.lang.Class<androidx.biometric.BiometricFragment.Api21Impl>; } export class Api28Impl { public static class: java.lang.Class<androidx.biometric.BiometricFragment.Api28Impl>; } export class Api29Impl { public static class: java.lang.Class<androidx.biometric.BiometricFragment.Api29Impl>; } export class Api30Impl { public static class: java.lang.Class<androidx.biometric.BiometricFragment.Api30Impl>; } export class PromptExecutor { public static class: java.lang.Class<androidx.biometric.BiometricFragment.PromptExecutor>; public execute(param0: java.lang.Runnable): void; } export class ShowPromptForAuthenticationRunnable { public static class: java.lang.Class<androidx.biometric.BiometricFragment.ShowPromptForAuthenticationRunnable>; public run(): void; } export class StopDelayingPromptRunnable { public static class: java.lang.Class<androidx.biometric.BiometricFragment.StopDelayingPromptRunnable>; public run(): void; } export class StopIgnoringCancelRunnable { public static class: java.lang.Class<androidx.biometric.BiometricFragment.StopIgnoringCancelRunnable>; public run(): void; } } } } declare module androidx { export module biometric { export class BiometricManager { public static class: java.lang.Class<androidx.biometric.BiometricManager>; public static BIOMETRIC_SUCCESS: number; public static BIOMETRIC_STATUS_UNKNOWN: number; public static BIOMETRIC_ERROR_UNSUPPORTED: number; public static BIOMETRIC_ERROR_HW_UNAVAILABLE: number; public static BIOMETRIC_ERROR_NONE_ENROLLED: number; public static BIOMETRIC_ERROR_NO_HARDWARE: number; public static BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED: number; public canAuthenticate(param0: number): number; public static from(param0: globalAndroid.content.Context): androidx.biometric.BiometricManager; /** @deprecated */ public canAuthenticate(): number; } export module BiometricManager { export class Api29Impl { public static class: java.lang.Class<androidx.biometric.BiometricManager.Api29Impl>; } export class Api30Impl { public static class: java.lang.Class<androidx.biometric.BiometricManager.Api30Impl>; } export class Authenticators { public static class: java.lang.Class<androidx.biometric.BiometricManager.Authenticators>; /** * Constructs a new instance of the androidx.biometric.BiometricManager$Authenticators interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: {}); public constructor(); public static BIOMETRIC_WEAK: number; public static BIOMETRIC_STRONG: number; public static DEVICE_CREDENTIAL: number; } export class DefaultInjector extends androidx.biometric.BiometricManager.Injector { public static class: java.lang.Class<androidx.biometric.BiometricManager.DefaultInjector>; public getFingerprintManager(): androidx.core.hardware.fingerprint.FingerprintManagerCompat; public isDeviceSecurable(): boolean; public getBiometricManager(): globalAndroid.hardware.biometrics.BiometricManager; public isFingerprintHardwarePresent(): boolean; public isStrongBiometricGuaranteed(): boolean; public isDeviceSecuredWithCredential(): boolean; } export class Injector { public static class: java.lang.Class<androidx.biometric.BiometricManager.Injector>; /** * Constructs a new instance of the androidx.biometric.BiometricManager$Injector interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getBiometricManager(): globalAndroid.hardware.biometrics.BiometricManager; getFingerprintManager(): androidx.core.hardware.fingerprint.FingerprintManagerCompat; isDeviceSecurable(): boolean; isDeviceSecuredWithCredential(): boolean; isFingerprintHardwarePresent(): boolean; isStrongBiometricGuaranteed(): boolean }); public constructor(); public getFingerprintManager(): androidx.core.hardware.fingerprint.FingerprintManagerCompat; public isDeviceSecurable(): boolean; public getBiometricManager(): globalAndroid.hardware.biometrics.BiometricManager; public isFingerprintHardwarePresent(): boolean; public isStrongBiometricGuaranteed(): boolean; public isDeviceSecuredWithCredential(): boolean; } } } } declare module androidx { export module biometric { export class BiometricPrompt { public static class: java.lang.Class<androidx.biometric.BiometricPrompt>; public static ERROR_HW_UNAVAILABLE: number; public static ERROR_UNABLE_TO_PROCESS: number; public static ERROR_TIMEOUT: number; public static ERROR_NO_SPACE: number; public static ERROR_CANCELED: number; public static ERROR_LOCKOUT: number; public static ERROR_VENDOR: number; public static ERROR_LOCKOUT_PERMANENT: number; public static ERROR_USER_CANCELED: number; public static ERROR_NO_BIOMETRICS: number; public static ERROR_HW_NOT_PRESENT: number; public static ERROR_NEGATIVE_BUTTON: number; public static ERROR_NO_DEVICE_CREDENTIAL: number; public static ERROR_SECURITY_UPDATE_REQUIRED: number; public static AUTHENTICATION_RESULT_TYPE_UNKNOWN: number; public static AUTHENTICATION_RESULT_TYPE_DEVICE_CREDENTIAL: number; public static AUTHENTICATION_RESULT_TYPE_BIOMETRIC: number; public authenticate(param0: androidx.biometric.BiometricPrompt.PromptInfo, param1: androidx.biometric.BiometricPrompt.CryptoObject): void; public constructor(param0: androidx.fragment.app.Fragment, param1: androidx.biometric.BiometricPrompt.AuthenticationCallback); public constructor(param0: androidx.fragment.app.Fragment, param1: java.util.concurrent.Executor, param2: androidx.biometric.BiometricPrompt.AuthenticationCallback); public authenticate(param0: androidx.biometric.BiometricPrompt.PromptInfo): void; public constructor(param0: androidx.fragment.app.FragmentActivity, param1: java.util.concurrent.Executor, param2: androidx.biometric.BiometricPrompt.AuthenticationCallback); public cancelAuthentication(): void; public constructor(param0: androidx.fragment.app.FragmentActivity, param1: androidx.biometric.BiometricPrompt.AuthenticationCallback); } export module BiometricPrompt { export abstract class AuthenticationCallback { public static class: java.lang.Class<androidx.biometric.BiometricPrompt.AuthenticationCallback>; public onAuthenticationFailed(): void; public onAuthenticationError(param0: number, param1: string): void; public onAuthenticationSucceeded(param0: androidx.biometric.BiometricPrompt.AuthenticationResult): void; public constructor(); } export class AuthenticationResult { public static class: java.lang.Class<androidx.biometric.BiometricPrompt.AuthenticationResult>; public getAuthenticationType(): number; public getCryptoObject(): androidx.biometric.BiometricPrompt.CryptoObject; } export class CryptoObject { public static class: java.lang.Class<androidx.biometric.BiometricPrompt.CryptoObject>; public constructor(param0: java.security.Signature); public constructor(param0: globalAndroid.security.identity.IdentityCredential); public getSignature(): java.security.Signature; public getIdentityCredential(): globalAndroid.security.identity.IdentityCredential; public getMac(): javax.crypto.Mac; public constructor(param0: javax.crypto.Cipher); public getCipher(): javax.crypto.Cipher; public constructor(param0: javax.crypto.Mac); } export class PromptInfo { public static class: java.lang.Class<androidx.biometric.BiometricPrompt.PromptInfo>; public getNegativeButtonText(): string; public getAllowedAuthenticators(): number; public isConfirmationRequired(): boolean; public getSubtitle(): string; public getDescription(): string; /** @deprecated */ public isDeviceCredentialAllowed(): boolean; public getTitle(): string; } export module PromptInfo { export class Builder { public static class: java.lang.Class<androidx.biometric.BiometricPrompt.PromptInfo.Builder>; public setSubtitle(param0: string): androidx.biometric.BiometricPrompt.PromptInfo.Builder; public constructor(); public setDescription(param0: string): androidx.biometric.BiometricPrompt.PromptInfo.Builder; /** @deprecated */ public setDeviceCredentialAllowed(param0: boolean): androidx.biometric.BiometricPrompt.PromptInfo.Builder; public build(): androidx.biometric.BiometricPrompt.PromptInfo; public setTitle(param0: string): androidx.biometric.BiometricPrompt.PromptInfo.Builder; public setNegativeButtonText(param0: string): androidx.biometric.BiometricPrompt.PromptInfo.Builder; public setConfirmationRequired(param0: boolean): androidx.biometric.BiometricPrompt.PromptInfo.Builder; public setAllowedAuthenticators(param0: number): androidx.biometric.BiometricPrompt.PromptInfo.Builder; } } export class ResetCallbackObserver { public static class: java.lang.Class<androidx.biometric.BiometricPrompt.ResetCallbackObserver>; public resetCallback(): void; } } } } declare module androidx { export module biometric { export class BiometricViewModel { public static class: java.lang.Class<androidx.biometric.BiometricViewModel>; public constructor(); } export module BiometricViewModel { export class CallbackListener extends androidx.biometric.AuthenticationCallbackProvider.Listener { public static class: java.lang.Class<androidx.biometric.BiometricViewModel.CallbackListener>; } export class DefaultExecutor { public static class: java.lang.Class<androidx.biometric.BiometricViewModel.DefaultExecutor>; public execute(param0: java.lang.Runnable): void; } export class NegativeButtonListener { public static class: java.lang.Class<androidx.biometric.BiometricViewModel.NegativeButtonListener>; public onClick(param0: globalAndroid.content.DialogInterface, param1: number): void; } } } } declare module androidx { export module biometric { export class CancellationSignalProvider { public static class: java.lang.Class<androidx.biometric.CancellationSignalProvider>; } export module CancellationSignalProvider { export class Api16Impl { public static class: java.lang.Class<androidx.biometric.CancellationSignalProvider.Api16Impl>; } export class Injector { public static class: java.lang.Class<androidx.biometric.CancellationSignalProvider.Injector>; /** * Constructs a new instance of the androidx.biometric.CancellationSignalProvider$Injector interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getBiometricCancellationSignal(): globalAndroid.os.CancellationSignal; getFingerprintCancellationSignal(): androidx.core.os.CancellationSignal }); public constructor(); public getBiometricCancellationSignal(): globalAndroid.os.CancellationSignal; public getFingerprintCancellationSignal(): androidx.core.os.CancellationSignal; } } } } declare module androidx { export module biometric { export class CryptoObjectUtils { public static class: java.lang.Class<androidx.biometric.CryptoObjectUtils>; } export module CryptoObjectUtils { export class Api23Impl { public static class: java.lang.Class<androidx.biometric.CryptoObjectUtils.Api23Impl>; } export class Api28Impl { public static class: java.lang.Class<androidx.biometric.CryptoObjectUtils.Api28Impl>; } export class Api30Impl { public static class: java.lang.Class<androidx.biometric.CryptoObjectUtils.Api30Impl>; } } } } declare module androidx { export module biometric { export class DeviceUtils { public static class: java.lang.Class<androidx.biometric.DeviceUtils>; } } } declare module androidx { export module biometric { export class ErrorUtils { public static class: java.lang.Class<androidx.biometric.ErrorUtils>; } } } declare module androidx { export module biometric { export class FingerprintDialogFragment { public static class: java.lang.Class<androidx.biometric.FingerprintDialogFragment>; public onResume(): void; public onCreate(param0: globalAndroid.os.Bundle): void; public onCreateDialog(param0: globalAndroid.os.Bundle): globalAndroid.app.Dialog; public onPause(): void; public constructor(); public onCancel(param0: globalAndroid.content.DialogInterface): void; } export module FingerprintDialogFragment { export class Api21Impl { public static class: java.lang.Class<androidx.biometric.FingerprintDialogFragment.Api21Impl>; } export class Api26Impl { public static class: java.lang.Class<androidx.biometric.FingerprintDialogFragment.Api26Impl>; } } } } declare module androidx { export module biometric { export class KeyguardUtils { public static class: java.lang.Class<androidx.biometric.KeyguardUtils>; } export module KeyguardUtils { export class Api16Impl { public static class: java.lang.Class<androidx.biometric.KeyguardUtils.Api16Impl>; } export class Api23Impl { public static class: java.lang.Class<androidx.biometric.KeyguardUtils.Api23Impl>; } } } } declare module androidx { export module biometric { export class PackageUtils { public static class: java.lang.Class<androidx.biometric.PackageUtils>; } export module PackageUtils { export class Api23Impl { public static class: java.lang.Class<androidx.biometric.PackageUtils.Api23Impl>; } } } } //Generics information: // Utils.java declare module org { export module nativescript { export module plugins { export module fingerprint { export class Utils { public static class: java.lang.Class<org.nativescript.plugins.fingerprint.Utils>; public constructor(); public static createCryptoObject(param0: javax.crypto.Cipher): androidx.biometric.BiometricPrompt.CryptoObject; } } } } }
the_stack
import {HttpClient, HttpErrorResponse} from "@angular/common/http"; import {TdDialogService} from "@covalent/core/dialogs"; import * as moment from "moment"; import "rxjs/add/observable/empty"; import "rxjs/add/observable/of"; import "rxjs/add/operator/catch"; import "rxjs/add/operator/map"; import {Observable} from "rxjs/Observable"; import * as _ from "underscore"; import {DateFormatResponse} from "../../wrangler/api"; import {DataType} from "../../wrangler/api/column"; import {DateFormatType, DateFormatUnit, DialogService} from "../../wrangler/api/services/dialog.service"; import {ColumnController} from "../../wrangler/column-controller"; import {ColumnDelegate, DataCategory} from "../../wrangler/column-delegate"; import {ColumnUtil} from "../../wrangler/core/column-util"; import {StringUtils} from "../../../../common/utils/StringUtils"; import {HttpBackendClient} from "../../../../services/http-backend-client"; /** * Data types supported by Spark and Hive. */ const SparkDataType = { // Numeric types BYTE: new DataType("byte", "Byte", "mdi-numeric-1"), SHORT: new DataType("short", "Short", "mdi-numeric-2"), INT: new DataType("int", "Int", "mdi-numeric-2"), BIGINT: new DataType("bigint", "Bigint", "mdi mdi-numeric"), FLOAT: new DataType("float", "Float", "mdi mdi-surround-sound-2-0"), DOUBLE: new DataType("double", "Double", "mdi mdi-surround-sound-2-0"), DECIMAL: new DataType("decimal", "Decimal", "mdi mdi-surround-sound-2-0"), // Date/time types DATE: new DataType("date", "Date", "mdi mdi-calendar"), TIMESTAMP: new DataType("timestamp", "Timestamp", "mdi mdi-clock-outline"), // Misc types BOOLEAN: new DataType("boolean", "Boolean", "mdi mdi-toggle-switch-off-outline"), BINARY: new DataType("binary", "Binary", "mdi mdi-file-image"), STRING: new DataType("string", "String", "mdi mdi-format-color-text"), // Complex types ARRAY: new DataType("array", "Array", "mdi mdi-code-brackets"), MAP: new DataType("map", "Map", "mdi mdi-code-array"), STRUCT: new DataType("struct", "Struct", "mdi mdi-code-braces") }; /** * Response model for the format-date endpoint. */ interface FormatDateResponse { text: string; } /** * Response model for the parse-date endpoint. */ interface ParseDateResponse { date: number; } /** * Handles user interactions with a Spark column. */ export class SparkColumnDelegate extends ColumnDelegate { constructor(private column: any, dataType: string, controller: ColumnController, $mdDialog: TdDialogService, uiGridConstants: any, dialog: DialogService, private http: HttpClient, private RestUrlService: any) { super(dataType, controller, $mdDialog, uiGridConstants, dialog); } /** * Gets the display name of this column. */ private get displayName() { return ColumnUtil.getColumnDisplayName(this.column); } /** * Gets the field name of this column. */ private get fieldName() { return ColumnUtil.getColumnFieldName(this.column); } /** * Casts this column to the specified type. */ castTo(dataType: DataType): void { if (dataType === SparkDataType.BIGINT) { const formula = ColumnUtil.toFormula(this.fieldName + ".cast(\"bigint\")", this.column, {columns: (this.controller as any).tableColumns}); this.controller.addFunction(formula, {formula: formula, name: "Cast " + this.displayName + " to bigint"}); } if (dataType === SparkDataType.DATE) { return this.castToDate(); } if (dataType === SparkDataType.DOUBLE) { const formula = ColumnUtil.toFormula(this.fieldName + ".cast(\"double\")", this.column, {columns: (this.controller as any).tableColumns}); this.controller.addFunction(formula, {formula: formula, name: "Cast " + this.displayName + " to double"}); } if (dataType === SparkDataType.INT) { const formula = ColumnUtil.toFormula(this.fieldName + ".cast(\"int\")", this.column, {columns: (this.controller as any).tableColumns}); this.controller.addFunction(formula, {formula: formula, name: "Cast " + this.displayName + " to int"}); } if (dataType === SparkDataType.STRING) { return this.castToString(); } if (dataType === SparkDataType.TIMESTAMP) { return this.castToTimestamp(); } } /** * Gets the target data types supported for casting this column. */ getAvailableCasts(): DataType[] { switch (this.dataType) { case SparkDataType.BIGINT.value: case SparkDataType.INT.value: return [SparkDataType.DATE, SparkDataType.DOUBLE, SparkDataType.FLOAT, SparkDataType.STRING]; case SparkDataType.FLOAT.value: return [SparkDataType.DATE, SparkDataType.DOUBLE, SparkDataType.INT, SparkDataType.STRING]; case SparkDataType.DOUBLE.value: return [SparkDataType.DATE, SparkDataType.FLOAT, SparkDataType.INT, SparkDataType.STRING]; case SparkDataType.DATE.value: return [SparkDataType.STRING, SparkDataType.TIMESTAMP]; case SparkDataType.STRING.value: return [SparkDataType.BIGINT, SparkDataType.DATE, SparkDataType.DOUBLE, SparkDataType.FLOAT, SparkDataType.INT, SparkDataType.TIMESTAMP]; default: return [SparkDataType.STRING]; } } /** * Override default validate so we dont refresh teh grid * @param filter * @param table */ applyFilter(header: any, filter: any, table: any) { this.controller.addColumnFilter(filter, header, true) } applyFilters(header: any, filters: any[], table: any) { //filter out any filters that dont have anything let validFilters = _.filter(filters, (filter) => { return (typeof filter.term != "undefined" && filter.term != '') }); _.each(validFilters, (filter, i) => { let query = false; if (i == (validFilters.length - 1)) { query = true; } this.controller.addColumnFilter(filter, header, true) }); } sortColumn(direction: string, column: any, grid: any) { this.controller.addColumnSort(direction, column, true); } /** * Casts this column to a date type. */ private castToDate(): void { // Generate preview function const sampleValue = this.getSampleValue(); const preview = (sampleValue != null) ? (format: DateFormatResponse) => this.parseDate(sampleValue, format).map(date => date.toLocaleDateString()) : null; // Get date pattern from user if (this.dataCategory === DataCategory.NUMERIC) { this.dialog.openDateFormat({ message: "Enter the pattern for parsing this column as a date:", preview: preview, title: "Convert " + this.dataType.toLowerCase() + " to date", type: DateFormatType.TIMESTAMP }).subscribe(response => { // Build script let script = this.fieldName; if (response.unit === DateFormatUnit.MILLISECONDS) { script = "(" + script + "/1000)"; } script = "to_date(" + script + ".cast(\"timestamp\")).as(\"" + StringUtils.quote(this.displayName) + "\")"; // Add function to wrangler const formula = ColumnUtil.toFormula(script, this.column, {columns: (this.controller as any).tableColumns}); this.controller.addFunction(formula, {formula: formula, icon: "event", name: "Cast " + this.displayName + " to date"}); }); } else if (this.dataCategory === DataCategory.STRING) { this.dialog.openDateFormat({ message: "Enter the pattern for parsing this column as a date:", pattern: "yyyy-MM-dd", patternHint: "See java.text.SimpleDateFormat for pattern letters.", preview: preview, title: "Convert " + this.dataType.toLowerCase() + " to date" }).subscribe(response => { // Build script let script; if (response.type === DateFormatType.STRING) { script = "to_date(unix_timestamp(" + this.fieldName + ", \"" + StringUtils.quote(response.pattern) + "\").cast(\"timestamp\")).as(\"" + StringUtils.quote(this.displayName) + "\")"; } else if (response.type === DateFormatType.TIMESTAMP) { script = this.fieldName + ".cast(\"bigint\")"; if (response.unit === DateFormatUnit.MILLISECONDS) { script = "(" + script + "/1000)"; } script = "to_date(" + script + ".cast(\"timestamp\")).as(\"" + StringUtils.quote(this.displayName) + "\")"; } // Add function to wrangler const formula = ColumnUtil.toFormula(script, this.column, {columns: (this.controller as any).tableColumns}); this.controller.addFunction(formula, {formula: formula, icon: "event", name: "Cast " + this.displayName + " to date"}); }); } } /** * Converts this column to a string type. */ private castToString(): void { if (this.dataCategory === DataCategory.DATETIME) { const sampleValue = this.getSampleValue(); // Get date pattern from user this.dialog.openDateFormat({ message: "Enter the pattern for formatting this column as a string:", pattern: "yyyy-MM-dd", patternHint: "See java.text.SimpleDateFormat for pattern letters.", preview: (sampleValue != null) ? format => this.formatDate(new Date(sampleValue), format) : null, title: "Convert " + this.dataType.toLowerCase() + " to string" }).subscribe(response => { // Build script let script; if (response.type === DateFormatType.STRING) { script = "date_format(" + this.fieldName + ", \"" + StringUtils.quote(response.pattern) + "\").as(\"" + StringUtils.quote(this.displayName) + "\")"; } else if (response.type === DateFormatType.TIMESTAMP) { script = (this.dataCategory === DataCategory.NUMERIC) ? this.fieldName : "unix_timestamp(" + this.fieldName + ")"; if (response.unit === DateFormatUnit.SECONDS) { script += ".cast(\"bigint\")" } else if (response.unit === DateFormatUnit.MILLISECONDS) { script = "(" + script + ".cast(\"decimal(23,3)\") * 1000).cast(\"bigint\")"; } script += ".cast(\"string\").as(\"" + StringUtils.quote(this.displayName) + "\")"; } // Add function to wrangler const formula = ColumnUtil.toFormula(script, this.column, {columns: (this.controller as any).tableColumns}); this.controller.addFunction(formula, {formula: formula, icon: "format_quote", name: "Cast " + this.displayName + " to string"}); }); } else { const formula = ColumnUtil.toFormula(this.fieldName + ".cast(\"string\")", this.column, {columns: (this.controller as any).tableColumns}); this.controller.addFunction(formula, {formula: formula, icon: "format_quote", name: "Cast " + this.displayName + " to string"}); } } /** * Cast this column to a timestamp type. */ private castToTimestamp(): void { const sampleValue = this.getSampleValue(); // Detect ISO dates if (this.dataCategory === DataCategory.DATETIME) { const formula = ColumnUtil.toFormula("unix_timestamp(" + this.fieldName + ")", this.column, {columns: (this.controller as any).tableColumns}); this.controller.addFunction(formula, {formula: formula, icon: "access_time", name: "Cast " + this.displayName + " to timestamp"}); } else if (this.dataCategory === DataCategory.STRING) { // If ISO date then just convert it. Otherwise, prompt. this.dialog.openDateFormat({ message: "Enter the pattern for parsing this column as a timestamp:", pattern: "yyyy-MM-dd HH:mm:ss", patternHint: "See java.text.SimpleDateFormat for pattern letters.", preview: (sampleValue != null) ? format => this.parseDate(sampleValue, format).map(date => moment(date).format("YYYY-MM-DD HH:mm:ss")) : null, title: "Convert " + this.dataType.toLowerCase() + " to timestamp", type: DateFormatType.STRING }).subscribe(response => { const script = "unix_timestamp(" + this.fieldName + ", \"" + StringUtils.quote(response.pattern) + "\").cast('timestamp').as(\"" + StringUtils.quote(this.displayName) + "\")"; const formula = ColumnUtil.toFormula(script, this.column, {columns: (this.controller as any).tableColumns}); this.controller.addFunction(formula, {formula: formula, icon: "access_time", name: "Cast " + this.displayName + " to timestamp"}); }); } } /** * Formats the specified Date as a string. * * @param value - the date * @param format - the format configuration * @returns the date string */ private formatDate(value: Date, format: DateFormatResponse): Observable<string> { if (format.type === DateFormatType.STRING) { return this.http .get<FormatDateResponse>(this.RestUrlService.FORMAT_DATE, { params: { date: value.getTime().toString(), pattern: format.pattern } }) .map(response => response.text) .catch((response: HttpErrorResponse): Observable<string> => { throw response.error.message; }); } else if (format.type === DateFormatType.TIMESTAMP) { if (format.unit === DateFormatUnit.SECONDS) { return Observable.of(Math.floor(value.getTime() / 1000).toString()); } else if (format.unit === DateFormatUnit.MILLISECONDS) { return Observable.of(value.getTime().toString()); } } return Observable.empty(); } /** * Gets a sample value for this column. */ private getSampleValue() { const columnIndex = (this.controller as any).tableColumns.findIndex((column: any) => column.field === this.column.field); return (this.controller as any).tableRows.map((row: any) => row[columnIndex]).find((value: any) => value != null); } /** * Parses the specified string into a Date. * * @param value - the date string * @param format - the format configuration * @returns the Date */ private parseDate(value: string, format: DateFormatResponse): Observable<Date> { let date: Observable<Date> = null; if (format.type === DateFormatType.STRING) { date = this.http .get<ParseDateResponse>(this.RestUrlService.PARSE_DATE, { params: { pattern: format.pattern, text: value } }) .map(response => new Date(response.date)) .catch((response: HttpErrorResponse): Observable<Date> => { throw response.error.message; }); } else if (format.type === DateFormatType.TIMESTAMP) { if (format.unit === DateFormatUnit.SECONDS) { date = Observable.of(new Date(parseInt(value) * 1000)); } else if (format.unit === DateFormatUnit.MILLISECONDS) { date = Observable.of(new Date(parseInt(value))); } } if (date !== null) { return date.map(utc => new Date(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate(), utc.getUTCHours(), utc.getUTCMinutes(), utc.getUTCSeconds(), utc.getUTCMilliseconds())); } else { return Observable.empty(); } } }
the_stack
import classNames from 'classnames'; import { ipcRenderer } from 'electron'; import * as React from 'react'; import { i18n } from '../../common/i18n-preload'; import { Themes } from './notification-settings'; const whiteColorRegExp = new RegExp( /^(?:white|#fff(?:fff)?|rgba?\(\s*255\s*,\s*255\s*,\s*255\s*(?:,\s*1\s*)?\))$/i, ); const darkTheme = [ '#e23030', '#b5616a', '#ab8ead', '#ebc875', '#a3be77', '#58c6ff', '#ebab58', ]; const Colors = { dark: { regularFlashingNotificationBgColor: '#27588e', notificationBackgroundColor: '#27292c', notificationBorderColor: '#717681', mentionBackgroundColor: '#99342c', mentionBorderColor: '#ff5d50', }, light: { regularFlashingNotificationBgColor: '#aad4f8', notificationBackgroundColor: '#f1f1f3', notificationBorderColor: 'transparent', mentionBackgroundColor: '#fcc1b9', mentionBorderColor: 'transparent', }, }; type Theme = '' | Themes.DARK | Themes.LIGHT; interface INotificationState { title: string; company: string; body: string; image: string; icon: string | undefined; id: number; color: string; flash: boolean; isExternal: boolean; theme: Theme; hasReply: boolean; hasMention: boolean; isInputHidden: boolean; containerHeight: number; canSendMessage: boolean; } type mouseEventButton = | React.MouseEvent<HTMLDivElement> | React.MouseEvent<HTMLButtonElement>; type keyboardEvent = React.KeyboardEvent<HTMLInputElement>; // Notification container height const CONTAINER_HEIGHT = 100; const CONTAINER_HEIGHT_WITH_INPUT = 142; const LIGHT_THEME = '#EAEBEC'; const DARK_THEME = '#25272B'; export default class NotificationComp extends React.Component< {}, INotificationState > { private readonly eventHandlers = { onClose: (winKey) => (_event: mouseEventButton) => this.close(_event, winKey), onClick: (data) => (_event: mouseEventButton) => this.click(data), onContextMenu: (event) => this.contextMenu(event), onMouseEnter: (winKey) => (_event: mouseEventButton) => this.onMouseEnter(winKey), onMouseLeave: (winKey) => (_event: mouseEventButton) => this.onMouseLeave(winKey), onOpenReply: (winKey) => (event: mouseEventButton) => this.onOpenReply(event, winKey), onThumbsUp: () => (_event: mouseEventButton) => this.onThumbsUp(), onReply: (winKey) => (_event: mouseEventButton) => this.onReply(winKey), onKeyUp: (winKey) => (event: keyboardEvent) => this.onKeyUp(event, winKey), }; private input: React.RefObject<HTMLInputElement>; constructor(props) { super(props); this.state = { title: '', company: 'Symphony', body: '', image: '', icon: '', id: 0, color: '', flash: false, isExternal: false, theme: '', isInputHidden: true, hasReply: false, hasMention: false, containerHeight: CONTAINER_HEIGHT, canSendMessage: false, }; this.updateState = this.updateState.bind(this); this.onInputChange = this.onInputChange.bind(this); this.resetNotificationData = this.resetNotificationData.bind(this); this.getInputValue = this.getInputValue.bind(this); this.input = React.createRef(); } /** * Callback to handle event when a component is mounted */ public componentDidMount(): void { ipcRenderer.on('notification-data', this.updateState); } /** * Callback to handle event when a component is unmounted */ public componentWillUnmount(): void { ipcRenderer.removeListener('notification-data', this.updateState); } /** * Renders the component */ public render(): JSX.Element { const { title, body, id, color, isExternal, theme, containerHeight, icon, } = this.state; let themeClassName; if (theme) { themeClassName = theme; } else if (darkTheme.includes(color.toLowerCase())) { themeClassName = 'black-text'; } else { themeClassName = color && color.match(whiteColorRegExp) ? Themes.LIGHT : Themes.DARK; } const themeColors = this.getThemeColors(); const closeImgFilePath = `../renderer/assets/close-icon-${themeClassName}.svg`; let containerCssClass = `container ${themeClassName} `; const customCssClasses = this.getContainerCssClasses(); containerCssClass += customCssClasses.join(' '); return ( <div data-testid='NOTIFICATION_CONTAINER' className={containerCssClass} style={{ height: containerHeight, backgroundColor: themeColors.notificationBackgroundColor, borderColor: themeColors.notificationBorderColor, }} lang={i18n.getLocale()} onMouseEnter={this.eventHandlers.onMouseEnter(id)} onMouseLeave={this.eventHandlers.onMouseLeave(id)} > <div className={`close-button ${themeClassName}`} title={i18n.t('Close')()} > <img src={closeImgFilePath} title={i18n.t('Close')()} alt='close' onClick={this.eventHandlers.onClose(id)} /> </div> <div className='main-container' role='alert' onContextMenu={this.eventHandlers.onContextMenu} onClick={this.eventHandlers.onClick(id)} > <div className='logo-container'>{this.renderImage(icon)}</div> <div className='notification-container'> <div className='notification-header'> <div className='notification-header-content'> <span className={`title ${themeClassName}`}>{title}</span> {this.renderExtBadge(isExternal)} </div> {this.renderReplyButton(id, themeClassName)} </div> <span className={`message-preview ${themeClassName}`}>{body}</span> </div> </div> {this.renderRTE(themeClassName)} </div> ); } /** * Renders RTE * @param isInputHidden */ private renderRTE(themeClassName: string): JSX.Element | undefined { const { canSendMessage, isInputHidden, id } = this.state; const actionButtonContainer = classNames('rte-button-container', { 'action-container-margin': !isInputHidden, }); if (!isInputHidden) { return ( <div className='rte-container'> <div className='input-container'> <input className={themeClassName} autoFocus={true} onKeyUp={this.eventHandlers.onKeyUp(id)} onChange={this.onInputChange} ref={this.input} /> </div> <div className={actionButtonContainer}> <button className={`rte-thumbsup-button ${themeClassName}`} onClick={this.eventHandlers.onThumbsUp()} > 👍 </button> <button className={`rte-send-button ${themeClassName}`} onClick={this.eventHandlers.onReply(id)} disabled={!canSendMessage} title={i18n.t('Send')()} /> </div> </div> ); } return; } /** * Renders external badge if the content is from external * @param isExternal */ private renderExtBadge(isExternal: boolean): JSX.Element | undefined { if (!isExternal) { return; } return ( <div className='ext-badge-container'> <img src='../renderer/assets/notification-ext-badge.svg' alt='ext-badge' /> </div> ); } /** * Renders image if provided otherwise renders symphony logo * @param imageUrl */ private renderImage(imageUrl: string | undefined): JSX.Element | undefined { let imgClass = 'default-logo'; let url = '../renderer/assets/notification-symphony-logo.svg'; let alt = 'Symphony logo'; const isDefaultUrl = imageUrl && imageUrl.includes('default.png'); const shouldDisplayBadge = !!imageUrl && !isDefaultUrl; if (imageUrl && !isDefaultUrl) { imgClass = 'profile-picture'; url = imageUrl; alt = 'Profile picture'; } return ( <div className='logo'> <img className={imgClass} src={url} alt={alt} /> {this.renderSymphonyBadge(shouldDisplayBadge)} </div> ); } /** * Renders profile picture symphpony badge * @param hasImageUrl */ private renderSymphonyBadge(hasImageUrl: boolean): JSX.Element | undefined { if (hasImageUrl) { return ( <img src='../renderer/assets/symphony-badge.svg' alt='' className='profile-picture-badge' /> ); } return; } /** * Invoked when the notification window is clicked * * @param id {number} */ private click(id: number): void { ipcRenderer.send('notification-clicked', id); } /** * Closes the notification * * @param id {number} */ private close(event: any, id: number): void { event.stopPropagation(); ipcRenderer.send('close-notification', id); } /** * Disable context menu * * @param event */ private contextMenu(event): void { event.preventDefault(); } /** * Handle mouse enter * * @param id {number} */ private onMouseEnter(id: number): void { ipcRenderer.send('notification-mouseenter', id); } /** * Handle mouse over * * @param id {number} */ private onMouseLeave(id: number): void { const { isInputHidden } = this.state; ipcRenderer.send('notification-mouseleave', id, isInputHidden); } /** * Insets a thumbs up emoji * @private */ private onThumbsUp(): void { if (this.input.current) { const input = this.input.current.value; this.input.current.value = input + '👍'; this.onInputChange(); this.input.current.focus(); } } /** * Handles reply action * @param id * @private */ private onReply(id: number): void { let replyText = this.getInputValue(); if (replyText) { // need to replace 👍 with :thumbsup: to make sure client displays the correct emoji replyText = replyText.replace(/👍/g, ':thumbsup: '); ipcRenderer.send('notification-on-reply', id, replyText); } } /** * Displays an input on the notification * * @private */ private onOpenReply(event, id) { event.stopPropagation(); ipcRenderer.send('show-reply', id); this.setState( { isInputHidden: false, hasReply: false, containerHeight: CONTAINER_HEIGHT_WITH_INPUT, }, () => { this.input.current?.focus(); }, ); } /** * Trim and returns the input value * @private */ private getInputValue(): string | undefined { return this.input.current?.value.trim(); } /** * Handles key up event and enter keyCode * * @param event * @param id * @private */ private onKeyUp(event, id) { if (event.key === 'Enter' || event.keyCode === 13) { this.onReply(id); } } /** * Updates the send button state based on input change * @private */ private onInputChange() { if (this.input.current) { const inputText = this.input.current.value || ''; this.setState({ canSendMessage: inputText.trim().length > 0, }); } } /** * Sets the component state * * @param _event * @param data {Object} */ private updateState(_event, data): void { const { color } = data; // FYI: 1.5 sends hex color but without '#', reason why we check and add prefix if necessary. // Goal is to keep backward compatibility with 1.5 colors (SDA v. 9.2.0) const isOldColor = /^([A-Fa-f0-9]{6})/.test(color); data.color = isOldColor ? `#${color}` : this.isValidColor(color) ? color : ''; data.isInputHidden = true; data.containerHeight = CONTAINER_HEIGHT; // FYI: 1.5 doesn't send current theme. We need to deduce it from the color that is sent. // Goal is to keep backward compatibility with 1.5 themes (SDA v. 9.2.0) data.theme = isOldColor && darkTheme.includes(data.color) ? Themes.DARK : data.theme ? data.theme : Themes.LIGHT; this.resetNotificationData(); this.setState(data as INotificationState); } /** * Validates the color * @param color * @private */ private isValidColor(color: string): boolean { return /^#([A-Fa-f0-9]{6})/.test(color); } /** * Reset data for new notification * @private */ private resetNotificationData(): void { if (this.input.current) { this.input.current.value = ''; } } /** * Returns notification colors based on theme * @param theme Current theme, can be either light or dark */ private getThemeColors(): { [key: string]: string } { const { theme, flash, isExternal, hasMention, color } = this.state; const currentColors = theme === Themes.DARK ? { ...Colors.dark } : { ...Colors.light }; const externalFlashingBackgroundColor = theme === Themes.DARK ? '#70511f' : '#f6e5a6'; if (flash && theme) { if (isExternal) { if (!hasMention) { currentColors.notificationBorderColor = '#F7CA3B'; currentColors.notificationBackgroundColor = externalFlashingBackgroundColor; if (this.isCustomColor(color)) { currentColors.notificationBorderColor = this.getThemedCustomBorderColor( theme, color, ); currentColors.notificationBackgroundColor = color; } } else { currentColors.notificationBorderColor = '#F7CA3B'; } } else if (hasMention) { currentColors.notificationBorderColor = currentColors.notificationBorderColor; } else { // in case of regular message without mention // FYI: SDA versions prior to 9.2.3 do not support theme color properly, reason why SFE-lite is pushing notification default background color. // For this reason, to be backward compatible, we check if sent color correspond to 'default' background color. If yes, we should ignore it and not consider it as a custom color. currentColors.notificationBackgroundColor = this.isCustomColor(color) ? color : currentColors.regularFlashingNotificationBgColor; currentColors.notificationBorderColor = this.isCustomColor(color) ? this.getThemedCustomBorderColor(theme, color) : theme === Themes.DARK ? '#2996fd' : 'transparent'; } } else if (!flash) { if (hasMention) { currentColors.notificationBackgroundColor = currentColors.mentionBackgroundColor; currentColors.notificationBorderColor = currentColors.mentionBorderColor; } else if (this.isCustomColor(color)) { currentColors.notificationBackgroundColor = color; currentColors.notificationBorderColor = this.getThemedCustomBorderColor( theme, color, ); } else if (isExternal) { currentColors.notificationBorderColor = '#F7CA3B'; } } return currentColors; } /** * Renders reply button * @param id * @param theming */ private renderReplyButton( id: number, theming: string, ): JSX.Element | undefined { const { hasReply } = this.state; if (hasReply) { return ( <button className={`action-button ${theming}`} style={{ display: hasReply ? 'block' : 'none' }} title={i18n.t('Reply')()} onClick={this.eventHandlers.onOpenReply(id)} > {i18n.t('Reply')()} </button> ); } return; } /** * This function aims at providing toast notification css classes */ private getContainerCssClasses(): string[] { const customClasses: string[] = []; const { flash, theme, hasMention, isExternal } = this.state; if (flash && theme) { if (isExternal) { customClasses.push('external-border'); if (hasMention) { customClasses.push(`${theme}-ext-mention-flashing`); } else { customClasses.push(`${theme}-ext-flashing`); } } else if (hasMention) { customClasses.push(`${theme}-mention-flashing`); } else { // In case it's a regular message notification customClasses.push(`${theme}-flashing`); } } else if (isExternal) { customClasses.push('external-border'); } return customClasses; } /** * SDA versions prior to 9.2.3 do not support theme color properly, reason why SFE-lite is pushing notification default background color and theme. * For that reason, we try to identify if provided color is the default one or not. * @param color color sent through SDABridge * @returns boolean */ private isCustomColor(color: string): boolean { if (color && color !== LIGHT_THEME && color !== DARK_THEME) { return true; } return false; } /** * Function that allows to increase color brightness * @param hex hes color * @param percent percent * @returns new hex color */ private increaseBrightness(hex: string, percent: number) { // strip the leading # if it's there hex = hex.replace(/^\s*#|\s*$/g, ''); const r = parseInt(hex.substr(0, 2), 16); const g = parseInt(hex.substr(2, 2), 16); const b = parseInt(hex.substr(4, 2), 16); return ( '#' + // tslint:disable-next-line: no-bitwise (0 | ((1 << 8) + r + ((256 - r) * percent) / 100)) .toString(16) .substr(1) + // tslint:disable-next-line: no-bitwise (0 | ((1 << 8) + g + ((256 - g) * percent) / 100)) .toString(16) .substr(1) + // tslint:disable-next-line: no-bitwise (0 | ((1 << 8) + b + ((256 - b) * percent) / 100)).toString(16).substr(1) ); } /** * Returns custom border color * @param theme current theme * @param customColor color * @returns custom border color */ private getThemedCustomBorderColor(theme: string, customColor: string) { return theme === Themes.DARK ? this.increaseBrightness(customColor, 50) : 'transparent'; } }
the_stack
import { getCanvas } from "src/main/utils/canvas-pool"; import { getBarHeights, getCellSizes } from "src/main/utils/cell-sizing"; import ShaderBox from "src/main/utils/shaderbox"; import { staticDevicePixelRatio } from "src/main/utils/static-display"; import { bind } from "src/utils/bind"; import { Cell } from "src/worker/gamelogic/types"; import { AnimationDesc, AnimationName, idleSprites, processDoneCallback, staticSprites, textureTileSize } from "../animation"; import { easeInOutCubic, easeOutQuad, remap } from "../animation-helpers"; import { fadedLinesAlpha, fadeInAnimationLength, fadeOutAnimationLength, flashInAnimationLength, flashOutAnimationLength, idleAnimationLength, idleAnimationNumFrames, revealedAlpha, spriteSize } from "../constants"; import { Renderer } from "../renderer"; import { STATIC_TEXTURE } from "../texture-generators"; import fragmentShader from "./fragment.glsl"; import vertexShader from "./vertex.glsl"; const enum DynamicTileDataA { BITFIELD, DOT, STATIC_TILE, IDLE_ANIMATION_TIME } const enum DynamicTileDataB { HIGHLIGHT_OPACITY, FLASH_OPACITY, BORDER_OPACITY, BOXES_OPACITY } const enum BitfieldBits { FOCUS, INNER_CIRCLE } function generateCoords(x1: number, y1: number, x2: number, y2: number) { return [x1, y1, x1, y2, x2, y1, x2, y2]; } function generateGameFieldMesh( numTilesX: number, numTilesY: number, tileSize: number ): Float32Array { // TODO optimize me (avoid allocations) const vertices = []; for (let y = 0; y < numTilesY; y++) { for (let x = 0; x < numTilesX; x++) { vertices.push( ...generateCoords( x * tileSize, y * tileSize, (x + 1) * tileSize, (y + 1) * tileSize ) ); } } return new Float32Array(vertices); } function generateVertexIndices(numTilesX: number, numTilesY: number) { // TODO optimize me (avoid allocations) const indices = []; for (let i = 0; i < numTilesX * numTilesY; i++) { indices.push(i * 4, i * 4 + 1, i * 4 + 2, i * 4 + 2, i * 4 + 1, i * 4 + 3); } return indices; } export default class WebGlRenderer implements Renderer { private _canvas?: HTMLCanvasElement; private _dynamicTileDataB?: Float32Array; private _dynamicTileDataA?: Float32Array; private _shaderBox?: ShaderBox; private _numTilesX?: number; private _numTilesY?: number; private _lastFocus = [-1, -1]; private _tileSize?: number; private _renderLoopRunning = false; createCanvas(): HTMLCanvasElement { this._canvas = getCanvas("webgl"); return this._canvas; } init(numTilesX: number, numTilesY: number) { this._numTilesX = numTilesX; this._numTilesY = numTilesY; this._updateTileSize(); this._initShaderBox(); this._setupMesh(); this._setupTextures(); this._shaderBox!.setUniform1f("sprite_size", spriteSize); this._shaderBox!.setUniform1f( "tile_size", textureTileSize! * staticDevicePixelRatio ); this._shaderBox!.setUniform1f("idle_frames", idleAnimationNumFrames); this._updateFadeoutParameters(); this._startRenderLoop(); } updateFirstRect(rect: ClientRect | DOMRect) { this._assertShaderBox(); this._shaderBox!.setUniform2f("offset", [ rect.left * staticDevicePixelRatio, rect.top * staticDevicePixelRatio ]); } stop() { this._renderLoopRunning = false; } onResize() { if (!this._shaderBox) { return; } this._shaderBox!.resize(); if (this._updateTileSize()) { this._updateGridMesh(); } this._updateFadeoutParameters(); } beforeUpdate() { // Nothing to do here } afterUpdate() { // Nothing to do here } beforeCell( x: number, y: number, cell: Cell, animationList: AnimationDesc[], ts: number ) { // Nothing to do here } afterCell( x: number, y: number, cell: Cell, animationList: AnimationDesc[], ts: number ) { // Nothing to do here } render( x: number, y: number, cell: Cell, animation: AnimationDesc, ts: number ) { this._assertShaderBox(); // @ts-ignore this[animation.name](x, y, cell, animation, ts); this._updateDynamicTileData(x, y); } setFocus(x: number, y: number) { if (this._lastFocus[0] > -1 && this._lastFocus[1] > -1) { const [lastX, lastY] = this._lastFocus; const dynamicTileDataA = this._getDynamicTileDataAForTile(lastX, lastY); dynamicTileDataA[DynamicTileDataA.BITFIELD] &= ~(1 << BitfieldBits.FOCUS); this._updateDynamicTileData(lastX, lastY); } if (x > -1 && y > -1) { const dynamicTileDataA = this._getDynamicTileDataAForTile(x, y); dynamicTileDataA[DynamicTileDataA.BITFIELD] |= 1 << BitfieldBits.FOCUS; this._updateDynamicTileData(x, y); this._lastFocus = [x, y]; } } private _updateFadeoutParameters() { const { topBarHeight, bottomBarHeight } = getBarHeights(); this._shaderBox!.setUniform2f("paddings", [ topBarHeight * staticDevicePixelRatio, bottomBarHeight * staticDevicePixelRatio ]); } private _updateTileSize() { const { cellPadding, cellSize } = getCellSizes(); const newTileSize = (cellSize + 2 * cellPadding) * staticDevicePixelRatio; const hasChanged = newTileSize !== this._tileSize!; this._tileSize = newTileSize; return hasChanged; } private _updateDynamicTileData(x: number, y: number) { // Go through the _other_ 3 vertices and copy the (potentially modified) // dynamic tile data from vertex 0 to their respective buffers. // TODO: We can prevent running these loops by switching to ANGLE instanced // rendering. const dynamicTileDataA = this._getDynamicTileDataAForTile(x, y); const dynamicTileDataB = this._getDynamicTileDataBForTile(x, y); for (let i = 1; i < 4; i++) { this._getDynamicTileDataAForTile(x, y, i).set(dynamicTileDataA); this._getDynamicTileDataBForTile(x, y, i).set(dynamicTileDataB); } } private [AnimationName.IDLE]( x: number, y: number, cell: Cell, animation: AnimationDesc, ts: number ) { const dynamicTileDataA = this._getDynamicTileDataAForTile(x, y); const dynamicTileDataB = this._getDynamicTileDataBForTile(x, y); const animationLength = idleAnimationLength; const normalized = ((ts - animation.start) / animationLength) % 1; dynamicTileDataA[DynamicTileDataA.IDLE_ANIMATION_TIME] = normalized; let fadeInNormalized = (ts - (animation.fadeStart || 0)) / fadeInAnimationLength; if (fadeInNormalized > 1) { fadeInNormalized = 1; } dynamicTileDataB[DynamicTileDataB.BOXES_OPACITY] = remap( 0, 1, 1, fadedLinesAlpha, easeOutQuad(fadeInNormalized) ); dynamicTileDataA[DynamicTileDataA.DOT] = remap( 0, 1, 1, 0, easeOutQuad(fadeInNormalized) ); dynamicTileDataB[DynamicTileDataB.BORDER_OPACITY] = 1; dynamicTileDataA[DynamicTileDataA.BITFIELD] |= 1 << BitfieldBits.INNER_CIRCLE; } private [AnimationName.FLAGGED]( x: number, y: number, cell: Cell, animation: AnimationDesc, ts: number ) { const dynamicTileDataA = this._getDynamicTileDataAForTile(x, y); const dynamicTileDataB = this._getDynamicTileDataBForTile(x, y); const animationLength = idleAnimationLength; const normalized = ((ts - animation.start) / animationLength) % 1; dynamicTileDataA[DynamicTileDataA.IDLE_ANIMATION_TIME] = normalized; let fadeOutNormalized = (ts - (animation.fadeStart || 0)) / fadeOutAnimationLength; if (fadeOutNormalized > 1) { fadeOutNormalized = 1; } dynamicTileDataB[DynamicTileDataB.BOXES_OPACITY] = remap( 0, 1, fadedLinesAlpha, 1, easeOutQuad(fadeOutNormalized) ); dynamicTileDataA[DynamicTileDataA.DOT] = remap( 0, 1, 0, 1, easeOutQuad(fadeOutNormalized) ); dynamicTileDataB[DynamicTileDataB.BORDER_OPACITY] = 1; dynamicTileDataB[DynamicTileDataB.BORDER_OPACITY] = 1; } private [AnimationName.NUMBER]( x: number, y: number, cell: Cell, animation: AnimationDesc, ts: number ) { if (ts < animation.start) { return; } const dynamicTileDataA = this._getDynamicTileDataAForTile(x, y); const dynamicTileDataB = this._getDynamicTileDataBForTile(x, y); dynamicTileDataA[DynamicTileDataA.STATIC_TILE] = cell.touchingMines; dynamicTileDataB[DynamicTileDataB.BORDER_OPACITY] = cell.touchingMines <= 0 ? revealedAlpha : 0; dynamicTileDataA[DynamicTileDataA.BITFIELD] &= ~( 1 << BitfieldBits.INNER_CIRCLE ); dynamicTileDataA[DynamicTileDataA.DOT] = 0; dynamicTileDataB[DynamicTileDataB.BOXES_OPACITY] = 0; } private [AnimationName.HIGHLIGHT_IN]( x: number, y: number, cell: Cell, animation: AnimationDesc, ts: number ) { const dynamicTileDataA = this._getDynamicTileDataAForTile(x, y); const dynamicTileDataB = this._getDynamicTileDataBForTile(x, y); const animationLength = fadeInAnimationLength; let normalized = (ts - animation.start) / animationLength; if (normalized < 0) { normalized = 0; } if (normalized > 1) { processDoneCallback(animation); normalized = 1; } dynamicTileDataB[DynamicTileDataB.HIGHLIGHT_OPACITY] = easeOutQuad( normalized ); } private [AnimationName.HIGHLIGHT_OUT]( x: number, y: number, cell: Cell, animation: AnimationDesc, ts: number ) { const dynamicTileDataA = this._getDynamicTileDataAForTile(x, y); const dynamicTileDataB = this._getDynamicTileDataBForTile(x, y); const animationLength = fadeOutAnimationLength; let normalized = (ts - animation.start) / animationLength; if (normalized < 0) { normalized = 0; } if (normalized > 1) { processDoneCallback(animation); normalized = 1; } dynamicTileDataB[DynamicTileDataB.HIGHLIGHT_OPACITY] = 1 - easeOutQuad(normalized); } private [AnimationName.FLASH_IN]( x: number, y: number, cell: Cell, animation: AnimationDesc, ts: number ) { const dynamicTileDataA = this._getDynamicTileDataAForTile(x, y); const dynamicTileDataB = this._getDynamicTileDataBForTile(x, y); const animationLength = flashInAnimationLength; let normalized = (ts - animation.start) / animationLength; if (normalized < 0) { return; } if (normalized > 1) { processDoneCallback(animation); normalized = 1; } dynamicTileDataB[DynamicTileDataB.FLASH_OPACITY] = easeOutQuad(normalized); } private [AnimationName.FLASH_OUT]( x: number, y: number, cell: Cell, animation: AnimationDesc, ts: number ) { const dynamicTileDataA = this._getDynamicTileDataAForTile(x, y); const dynamicTileDataB = this._getDynamicTileDataBForTile(x, y); const animationLength = flashOutAnimationLength; let normalized = (ts - animation.start) / animationLength; if (normalized < 0) { return; } if (normalized > 1) { processDoneCallback(animation); normalized = 1; } dynamicTileDataB[DynamicTileDataB.FLASH_OPACITY] = 1 - easeInOutCubic(normalized); } private [AnimationName.MINED]( x: number, y: number, cell: Cell, animation: AnimationDesc, ts: number ) { if (ts < animation.start) { return; } const dynamicTileDataA = this._getDynamicTileDataAForTile(x, y); const dynamicTileDataB = this._getDynamicTileDataBForTile(x, y); dynamicTileDataA[DynamicTileDataA.STATIC_TILE] = STATIC_TEXTURE.MINE; dynamicTileDataA[DynamicTileDataA.BITFIELD] &= ~( 1 << BitfieldBits.INNER_CIRCLE ); dynamicTileDataB[DynamicTileDataB.BORDER_OPACITY] = 0; dynamicTileDataB[DynamicTileDataB.BOXES_OPACITY] = 0; } private _getDynamicTileDataAForTile( x: number, y: number, vertex: number = 0 ): Float32Array { const tileOffset = y * this._numTilesX! + x; const vertexOffset = tileOffset * 4 + vertex; const floatOffset = vertexOffset * 4; const byteOffset = floatOffset * 4; return new Float32Array(this._dynamicTileDataA!.buffer, byteOffset, 4); } private _getDynamicTileDataBForTile( x: number, y: number, vertex: number = 0 ): Float32Array { const tileOffset = y * this._numTilesX! + x; const vertexOffset = tileOffset * 4 + vertex; const floatOffset = vertexOffset * 4; const byteOffset = floatOffset * 4; return new Float32Array(this._dynamicTileDataB!.buffer, byteOffset, 4); } private _initShaderBox() { /** * We are setting up a WebGL context here. * * Per-vertex attributes: * - `pos`: Position of the vertex on screen in pixels. Starting at (0, 0) * in the top left corner. * - `tile_uv`: UV coordinates within each tile. Top-left corner is (0, 0), * bottom right corner is (1, 1). * - `dynamic_tile_data_a`: A `vec4` containing data according to the * `DynamicTileDataA` enum * - `dynamic_tile_data_b`: A `vec4` containing data according to the * `DynamicTileDataB` enum * * Uniforms: * - `offset`: Offset of the first tile’s top left corner from the top-left * corner of the screen. This effectively makes sure our WebGL tiles are * perfectly aligned with the inivisible table, including scroll position. * - `idle_sprites[n]`: Up to 4 texture samplers for the sprite of the idle * animation. * - `static_sprite`: Sampler for the static sprite. * - `sprite_size`: A single float for the size of the sprites in pixels * (they are assumed to be square). * - `tile_size`: A single float for the size of each tile in pixels. * - `idle_frames`: Number of frames the idle animation has. * - `paddings`: The vertical and horizontal paddings that define the fade-out. */ this._shaderBox = new ShaderBox(vertexShader, fragmentShader, { canvas: this._canvas, uniforms: [ "offset", "idle_sprites[0]", "idle_sprites[1]", "idle_sprites[2]", "idle_sprites[3]", "static_sprite", "sprite_size", "tile_size", "idle_frames", "paddings" ], scaling: staticDevicePixelRatio, antialias: false, mesh: [ { dimensions: 2, name: "pos" }, { dimensions: 2, name: "tile_uv" }, { name: "dynamic_tile_data_a", dimensions: 4, usage: "DYNAMIC_DRAW" }, { name: "dynamic_tile_data_b", dimensions: 4, usage: "DYNAMIC_DRAW" } ], indices: generateVertexIndices(this._numTilesX!, this._numTilesY!), clearColor: [0, 0, 0, 0] }); this._shaderBox!.resize(); } private _updateGridMesh() { const mesh = generateGameFieldMesh( this._numTilesX!, this._numTilesY!, this._tileSize! ); this._shaderBox!.updateVBO("pos", mesh); return mesh; } private _setupMesh() { const mesh = this._updateGridMesh(); // Repeat these UVs for all tiles. const uvs = [0, 1, 0, 0, 1, 1, 1, 0]; this._shaderBox!.updateVBO( "tile_uv", mesh.map((_, idx) => uvs[idx % uvs.length]) ); const numTiles = this._numTilesX! * this._numTilesY!; this._dynamicTileDataA = new Float32Array( new Array(numTiles * 4 * 4).fill(0).map((_, idx) => { const fieldIdx = Math.floor(idx / 16); const x = fieldIdx % this._numTilesX!; const y = Math.floor(fieldIdx / this._numTilesX!); switch (idx % 4) { case DynamicTileDataA.BITFIELD: return 1 << BitfieldBits.INNER_CIRCLE; case DynamicTileDataA.DOT: return 0; case DynamicTileDataA.STATIC_TILE: return -1; // Equivalent to “unrevealed” case DynamicTileDataA.IDLE_ANIMATION_TIME: return 0; default: return -1; // Never reached. Just to make TypeScript happy. } }) ); this._shaderBox!.updateVBO("dynamic_tile_data_a", this._dynamicTileDataA); this._dynamicTileDataB = new Float32Array( new Array(numTiles * 4 * 4).fill(0).map((_, idx) => { switch (idx % 4) { case DynamicTileDataB.BORDER_OPACITY: return 1; case DynamicTileDataB.BOXES_OPACITY: return fadedLinesAlpha; case DynamicTileDataB.FLASH_OPACITY: return 0; case DynamicTileDataB.HIGHLIGHT_OPACITY: return 0; default: return -1; // Never reached. Just to make TypeScript happy. } }) ); this._shaderBox!.updateVBO("dynamic_tile_data_b", this._dynamicTileDataB); } private _setupTextures() { // Due to the way internal WebGL state handling works, we // have to add all the textures first before we bind them. this._shaderBox!.addTexture(`staticSprite`, staticSprites![0]); for (let i = 0; i < idleSprites!.length; i++) { this._shaderBox!.addTexture(`idleSprite${i}`, idleSprites![i]); } for (let i = 0; i < idleSprites!.length; i++) { this._shaderBox!.activateTexture(`idleSprite${i}`, i + 1); this._shaderBox!.setUniform1i(`idle_sprites[${i}]`, i + 1); } this._shaderBox!.activateTexture(`staticSprite`, 0); this._shaderBox!.setUniform1i(`static_sprite`, 0); } private _startRenderLoop() { this._renderLoopRunning = true; requestAnimationFrame(this._renderLoop); } private _assertShaderBox() { if (!this._shaderBox) { throw Error("ShaderBox not initialized for WebGL renderer"); } } @bind private _renderLoop() { this._shaderBox!.updateVBO("dynamic_tile_data_a", this._dynamicTileDataA!); this._shaderBox!.updateVBO("dynamic_tile_data_b", this._dynamicTileDataB!); this._shaderBox!.draw(); if (this._renderLoopRunning) { requestAnimationFrame(this._renderLoop); } } }
the_stack
import { TypeAssertion, ValidationContext } from '../types'; import { validate, getType } from '../validator'; import { pick, patch } from '../picker'; import { compile } from '../compiler'; import { generateTypeScriptCode } from '../codegen'; import { serialize, deserialize } from '../serializer'; import { stereotypes as dateStereotypes } from '../stereotypes/date'; describe("fix-2", function() { it("stereotype-1a", function() { const schema = compile(` interface Foo { @stereotype('date') @range('=today first-date-of-mo', '=today last-date-of-mo') a: string; @stereotype('date') @range('2020-01-01', '2030-12-31') b: string; @stereotype('date') @range('2020-01-01', '=today +2yr @12mo @31day') c: string; } `); const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const d = (new Date()).toISOString().slice(0, 10); // toISOString returns date in UTC const z = validate<any>({ a: d, b: '2020-01-01', c: d, }, ty, ctx); expect(z).toEqual({value: { a: d, b: '2020-01-01', c: d, }}); } }); it("stereotype-1b", function() { const schema = compile(` interface Foo { @stereotype('lcdate') @range('=today first-date-of-mo', '=today last-date-of-mo') a: string; @stereotype('lcdate') @range('2020-01-01', '2030-12-31') b: string; @stereotype('lcdate') @range('2020-01-01', '=today +2yr @12mo @31day') c: string; } `); const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const d = (new Date( new Date().getTime() - new Date().getTimezoneOffset() * 60 * 1000)) .toISOString().slice(0, 10); // toISOString returns date in UTC const z = validate<any>({ a: d, b: '2020-01-01', c: d, }, ty, ctx); expect(z).toEqual({value: { a: d, b: '2020-01-01', c: d, }}); } }); it("stereotype-2a", function() { const schema = compile(` interface Foo { @stereotype('date') @range('=2020-02-22 first-date-of-mo', '=2020-02-22 last-date-of-mo') a: string; } `); const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-14' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14T00:00' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14T00:00Z' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-01' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-01' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-29' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-29' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-01-31' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-03-01' }, ty, ctx); expect(z).toEqual(null); } }); it("stereotype-2b", function() { const schema = compile(` interface Foo { @stereotype('lcdate') @range('=2020-02-22 first-date-of-mo', '=2020-02-22 last-date-of-mo') a: string; } `); const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-14' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14T00:00' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14T00:00Z' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-01' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-01' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-29' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-29' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-01-31' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-03-01' }, ty, ctx); expect(z).toEqual(null); } }); it("stereotype-3a", function() { const schema = compile(` interface Foo { @stereotype('date') @range('=2020-02-22 first-date-of-yr', '=2020-02-22 last-date-of-yr') a: string; } `); const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-14' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14T00:00' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14T00:00Z' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-01-01' }, ty, ctx); expect(z).toEqual({value: { a: '2020-01-01' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-12-31' }, ty, ctx); expect(z).toEqual({value: { a: '2020-12-31' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2019-12-31' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-01-01' }, ty, ctx); expect(z).toEqual(null); } }); it("stereotype-3b", function() { const schema = compile(` interface Foo { @stereotype('lcdate') @range('=2020-02-22 first-date-of-yr', '=2020-02-22 last-date-of-yr') a: string; } `); const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-14' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14T00:00' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14T00:00Z' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-01-01' }, ty, ctx); expect(z).toEqual({value: { a: '2020-01-01' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-12-31' }, ty, ctx); expect(z).toEqual({value: { a: '2020-12-31' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2019-12-31' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-01-01' }, ty, ctx); expect(z).toEqual(null); } }); it("stereotype-4a", function() { const schema = compile(` interface Foo { @stereotype('datetime') @range('=2020-02-22 first-date-of-mo', '=2020-02-22 last-date-of-mo') a: string; } `); const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14T00:00' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-14T00:00' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14T00:00Z' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-14T00:00Z' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-01' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-01T00:00' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-01T00:00' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-01T00:00Z' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-01T00:00Z' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-29' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-29T00:00' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-29T00:00' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-29T00:00Z' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-29T00:00Z' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-29T00:01' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-29T00:01Z' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-01-31' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-01-31T23:59' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-01-31T23:59Z' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-03-01' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-03-01T00:00' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-03-01T00:00Z' }, ty, ctx); expect(z).toEqual(null); } }); it("stereotype-4b", function() { const schema = compile(` interface Foo { @stereotype('lcdatetime') @range('=2020-02-22 first-date-of-mo', '=2020-02-22 last-date-of-mo') a: string; } `); const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14T00:00' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-14T00:00' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-14T00:00Z' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-14T00:00Z' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-01' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-01T00:00' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-01T00:00' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-01T00:00Z' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-01T00:00Z' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-29' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-29T00:00' }, ty, ctx); expect(z).toEqual({value: { a: '2020-02-29T00:00' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-29T00:00Z' }, ty, ctx); // expect(z).toEqual({value: { a: '2020-02-29T00:00Z' }}); // result will be chaged by your TZ } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-29T00:01' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-02-29T00:01Z' }, ty, ctx); // expect(z).toEqual(null); // result will be chaged by your TZ } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-01-31' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-01-31T23:59' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-01-31T23:59Z' }, ty, ctx); // expect(z).toEqual(null); // result will be chaged by your TZ } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-03-01' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-03-01T00:00' }, ty, ctx); expect(z).toEqual(null); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2020-03-01T00:00Z' }, ty, ctx); // expect(z).toEqual(null); // result will be chaged by your TZ } }); it("stereotype-5a", function() { const schemas = [compile(` interface Foo { @stereotype('date') @range('=2020-02-22 @2021yr @4mo @11day', '=2019-10-11 @2021yr @4mo @11day') a: string; } `), compile(` interface Foo { @stereotype('date') @range('=2020-02-22 @2021yr @4mo @11day', '=2019-10-11 @2021yr @4mo @11day') a?: string; } `)]; for (const schema of schemas) { const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-04-11' }, ty, ctx); expect(z).toEqual({value: { a: '2021-04-11' }}); } } }); it("stereotype-5b", function() { const schemas = [compile(` interface Foo { @stereotype('lcdate') @range('=2020-02-22 @2021yr @4mo @11day', '=2019-10-11 @2021yr @4mo @11day') a: string; } `), compile(` interface Foo { @stereotype('lcdate') @range('=2020-02-22 @2021yr @4mo @11day', '=2019-10-11 @2021yr @4mo @11day') a?: string; } `)]; for (const schema of schemas) { const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-04-11' }, ty, ctx); expect(z).toEqual({value: { a: '2021-04-11' }}); } } }); it("stereotype-6a", function() { const schemas = [compile(` interface Foo { @stereotype('datetime') @range('=2020-02-22 @2021yr @4mo @11day @20hr @32min @43sec @973ms', '=2019-10-11 @2021yr @4mo @11day @20hr @32min @43sec @973ms') a: string; } `), compile(` interface Foo { @stereotype('datetime') @range('=2020-02-22 @2021yr @4mo @11day @20hr @32min @43sec @973ms', '=2019-10-11 @2021yr @4mo @11day @20hr @32min @43sec @973ms') a?: string; } `)]; for (const schema of schemas) { const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-04-11T20:32:43.973' }, ty, ctx); expect(z).toEqual({value: { a: '2021-04-11T20:32:43.973' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-04-11T20:32:43.973Z' }, ty, ctx); expect(z).toEqual({value: { a: '2021-04-11T20:32:43.973Z' }}); } } }); it("stereotype-6b", function() { const schemas = [compile(` interface Foo { @stereotype('lcdatetime') @range('=2020-02-22 @2021yr @4mo @11day @20hr @32min @43sec @973ms', '=2019-10-11 @2021yr @4mo @11day @20hr @32min @43sec @973ms') a: string; } `), compile(` interface Foo { @stereotype('lcdatetime') @range('=2020-02-22 @2021yr @4mo @11day @20hr @32min @43sec @973ms', '=2019-10-11 @2021yr @4mo @11day @20hr @32min @43sec @973ms') a?: string; } `)]; for (const schema of schemas) { const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-04-11T20:32:43.973' }, ty, ctx); expect(z).toEqual({value: { a: '2021-04-11T20:32:43.973' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-04-11T20:32:43.973Z' }, ty, ctx); // expect(z).toEqual(null); // result will be chaged by your TZ } } }); it("stereotype-7a", function() { const schemas = [compile(` interface Foo { @stereotype('date') @range('=2020-02-05 +1yr +2mo +6days', '=2022-10-13 -1yr -6mo -2day') a: string; } `), compile(` interface Foo { @stereotype('date') @range('=2020-02-05 +1yr +2mo +6days', '=2022-10-13 -1yr -6mo -2day') a?: string; } `)]; for (const schema of schemas) { const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-04-11' }, ty, ctx); expect(z).toEqual({value: { a: '2021-04-11' }}); } } }); it("stereotype-7b", function() { const schemas = [compile(` interface Foo { @stereotype('lcdate') @range('=2020-02-05 +1yr +2mo +6days', '=2022-10-13 -1yr -6mo -2day') a: string; } `), compile(` interface Foo { @stereotype('lcdate') @range('=2020-02-05 +1yr +2mo +6days', '=2022-10-13 -1yr -6mo -2day') a?: string; } `)]; for (const schema of schemas) { const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-04-11' }, ty, ctx); expect(z).toEqual({value: { a: '2021-04-11' }}); } } }); it("stereotype-8a", function() { const schemas = [compile(` interface Foo { @stereotype('datetime') @range('=2020-02-05T01:02:03.456 +1yr +2mo +6days +19hr +30min +40sec +517ms', '=2022-10-13T23:59:58.987 -1yr -6mo -2day -3hr -27min -15sec -14ms') a: string; } `), compile(` interface Foo { @stereotype('datetime') @range('=2020-02-05T01:02:03.456 +1yr +2mo +6days +19hr +30min +40sec +517ms', '=2022-10-13T23:59:58.987 -1yr -6mo -2day -3hr -27min -15sec -14ms') a?: string; } `)]; for (const schema of schemas) { const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-04-11T20:32:43.973' }, ty, ctx); expect(z).toEqual({value: { a: '2021-04-11T20:32:43.973' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-04-11T20:32:43.973Z' }, ty, ctx); expect(z).toEqual({value: { a: '2021-04-11T20:32:43.973Z' }}); } } }); it("stereotype-8b", function() { const schemas = [compile(` interface Foo { @stereotype('lcdatetime') @range('=2020-02-05T01:02:03.456 +1yr +2mo +6days +19hr +30min +40sec +517ms', '=2022-10-13T23:59:58.987 -1yr -6mo -2day -3hr -27min -15sec -14ms') a: string; } `), compile(` interface Foo { @stereotype('lcdatetime') @range('=2020-02-05T01:02:03.456 +1yr +2mo +6days +19hr +30min +40sec +517ms', '=2022-10-13T23:59:58.987 -1yr -6mo -2day -3hr -27min -15sec -14ms') a?: string; } `)]; for (const schema of schemas) { const ty = getType(schema, 'Foo'); { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-04-11T20:32:43.973' }, ty, ctx); expect(z).toEqual({value: { a: '2021-04-11T20:32:43.973' }}); } { const ctx: Partial<ValidationContext> = { checkAll: true, stereotypes: new Map([ ...dateStereotypes, ]), }; const z = validate<any>({ a: '2021-04-11T20:32:43.973Z' }, ty, ctx); // expect(z).toEqual(null); // result will be chaged by your TZ } } }); });
the_stack
module fgui { export class GRoot extends GComponent { public static contentScaleLevel: number = 0; private _nativeStage: egret.Stage; private _modalLayer: GGraph; private _popupStack: Array<GObject>; private _justClosedPopups: Array<GObject>; private _modalWaitPane: GObject; private _tooltipWin: GObject; private _defaultTooltipWin: GObject; private _volumeScale: number; private static _inst: GRoot; public static touchScreen: boolean; public static contentScaleFactor: number = 1; public static touchDown: boolean; public static ctrlKeyDown: boolean; public static shiftKeyDown: boolean; public static mouseX: number; public static mouseY: number; public static get inst(): GRoot { if (GRoot._inst == null) new GRoot(); return GRoot._inst; } public constructor() { super(); if (GRoot._inst == null) GRoot._inst = this; this.opaque = false; this._volumeScale = 1; this._popupStack = new Array<GObject>(); this._justClosedPopups = new Array<GObject>(); this.displayObject.addEventListener(egret.Event.ADDED_TO_STAGE, this.__addedToStage, this); } public get nativeStage(): egret.Stage { return this._nativeStage; } public showWindow(win: Window): void { this.addChild(win); win.requestFocus(); if (win.x > this.width) win.x = this.width - win.width; else if (win.x + win.width < 0) win.x = 0; if (win.y > this.height) win.y = this.height - win.height; else if (win.y + win.height < 0) win.y = 0; this.adjustModalLayer(); } public hideWindow(win: Window): void { win.hide(); } public hideWindowImmediately(win: Window): void { if (win.parent == this) this.removeChild(win); this.adjustModalLayer(); } public bringToFront(win: Window): void { var cnt: number = this.numChildren; var i: number; if (this._modalLayer.parent != null && !win.modal) i = this.getChildIndex(this._modalLayer) - 1; else i = cnt - 1; for (; i >= 0; i--) { var g: GObject = this.getChildAt(i); if (g == win) return; if (g instanceof Window) break; } if (i >= 0) this.setChildIndex(win, i); } public showModalWait(msg?: string): void { if (UIConfig.globalModalWaiting != null) { if (this._modalWaitPane == null) this._modalWaitPane = UIPackage.createObjectFromURL(UIConfig.globalModalWaiting); this._modalWaitPane.setSize(this.width, this.height); this._modalWaitPane.addRelation(this, RelationType.Size); this.addChild(this._modalWaitPane); this._modalWaitPane.text = msg; } } public closeModalWait(): void { if (this._modalWaitPane != null && this._modalWaitPane.parent != null) this.removeChild(this._modalWaitPane); } public closeAllExceptModals(): void { var arr: Array<GObject> = this._children.slice(); var cnt: number = arr.length; for (var i: number = 0; i < cnt; i++) { var g: GObject = arr[i]; if ((g instanceof Window) && !g.modal) g.hide(); } } public closeAllWindows(): void { var arr: Array<GObject> = this._children.slice(); var cnt: number = arr.length; for (var i: number = 0; i < cnt; i++) { var g: GObject = arr[i]; if (g instanceof Window) g.hide(); } } public getTopWindow(): Window { var cnt: number = this.numChildren; for (var i: number = cnt - 1; i >= 0; i--) { var g: GObject = this.getChildAt(i); if (g instanceof Window) { return g; } } return null; } public get modalLayer(): GGraph { return this._modalLayer; } public get hasModalWindow(): boolean { return this._modalLayer.parent != null; } public get modalWaiting(): boolean { return this._modalWaitPane && this._modalWaitPane.inContainer; } public showPopup(popup: GObject, target?: GObject, dir?: PopupDirection | boolean): void { if (this._popupStack.length > 0) { var k: number = this._popupStack.indexOf(popup); if (k != -1) { for (var i: number = this._popupStack.length - 1; i >= k; i--) this.removeChild(this._popupStack.pop()); } } this._popupStack.push(popup); if (target) { var p: GObject = target; while (p) { if (p.parent == this) { if (popup.sortingOrder < p.sortingOrder) { popup.sortingOrder = p.sortingOrder; } break; } p = p.parent; } } this.addChild(popup); this.adjustModalLayer(); var pos: egret.Point; var sizeW: number = 0, sizeH: number = 0; if (target) { pos = target.localToRoot(); sizeW = target.width; sizeH = target.height; } else { pos = this.globalToLocal(GRoot.mouseX, GRoot.mouseY); } var xx: number, yy: number; xx = pos.x; if (xx + popup.width > this.width) xx = xx + sizeW - popup.width; yy = pos.y + sizeH; if (((dir === undefined || dir === PopupDirection.Auto) && pos.y + popup.height > this.height) || dir === false || dir === PopupDirection.Up) { yy = pos.y - popup.height - 1; if (yy < 0) { yy = 0; xx += sizeW / 2; } } popup.x = xx; popup.y = yy; } public togglePopup(popup: GObject, target?: GObject, dir?: PopupDirection | boolean): void { if (this._justClosedPopups.indexOf(popup) != -1) return; this.showPopup(popup, target, dir); } public hidePopup(popup?: GObject): void { if (popup) { var k: number = this._popupStack.indexOf(popup); if (k != -1) { for (var i: number = this._popupStack.length - 1; i >= k; i--) this.closePopup(this._popupStack.pop()); } } else { var cnt: number = this._popupStack.length; for (i = cnt - 1; i >= 0; i--) this.closePopup(this._popupStack[i]); this._popupStack.length = 0; } } public get hasAnyPopup(): boolean { return this._popupStack.length != 0; } private closePopup(target: GObject): void { if (target.parent) { if (target instanceof Window) target.hide(); else this.removeChild(target); } } public showTooltips(msg: string): void { if (this._defaultTooltipWin == null) { var resourceURL: string = UIConfig.tooltipsWin; if (!resourceURL) { console.error("UIConfig.tooltipsWin not defined"); return; } this._defaultTooltipWin = UIPackage.createObjectFromURL(resourceURL); } this._defaultTooltipWin.text = msg; this.showTooltipsWin(this._defaultTooltipWin); } public showTooltipsWin(tooltipWin: GObject, position?: egret.Point): void { this.hideTooltips(); this._tooltipWin = tooltipWin; var xx: number = 0; var yy: number = 0; if (!position) { xx = GRoot.mouseX + 10; yy = GRoot.mouseY + 20; } else { xx = position.x; yy = position.y; } var pt: egret.Point = this.globalToLocal(xx, yy); xx = pt.x; yy = pt.y; if (xx + this._tooltipWin.width > this.width) { xx = xx - this._tooltipWin.width - 1; if (xx < 0) xx = 10; } if (yy + this._tooltipWin.height > this.height) { yy = yy - this._tooltipWin.height - 1; if (xx - this._tooltipWin.width - 1 > 0) xx = xx - this._tooltipWin.width - 1; if (yy < 0) yy = 10; } this._tooltipWin.x = xx; this._tooltipWin.y = yy; this.addChild(this._tooltipWin); } public hideTooltips(): void { if (this._tooltipWin) { if (this._tooltipWin.parent) this.removeChild(this._tooltipWin); this._tooltipWin = null; } } public getObjectUnderPoint(globalX: number, globalY: number): GObject { var ret: egret.DisplayObject = this._nativeStage.$hitTest(globalX, globalY); if (ret) return ToolSet.displayObjectToGObject(ret); else return null; } public get focus(): GObject { return null; } public set focus(value: GObject) { } private setFocus(value: GObject) { } public get volumeScale(): number { return this._volumeScale; } public set volumeScale(value: number) { this._volumeScale = value; } public playOneShotSound(sound: egret.Sound, volumeScale?: number) { volumeScale = volumeScale || 1; var vs: number = this._volumeScale * volumeScale; var channel: egret.SoundChannel = sound.play(0, 1); channel.volume = vs; } private adjustModalLayer(): void { var cnt: number = this.numChildren; if (this._modalWaitPane && this._modalWaitPane.parent) this.setChildIndex(this._modalWaitPane, cnt - 1); for (var i: number = cnt - 1; i >= 0; i--) { var g: GObject = this.getChildAt(i); if ((g instanceof Window) && g.modal) { if (this._modalLayer.parent == null) this.addChildAt(this._modalLayer, i); else this.setChildIndexBefore(this._modalLayer, i); return; } } if (this._modalLayer.parent) this.removeChild(this._modalLayer); } private __addedToStage(evt: egret.Event): void { this.displayObject.removeEventListener(egret.Event.ADDED_TO_STAGE, this.__addedToStage, this); this._nativeStage = this.displayObject.stage; this._nativeStage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.__stageMouseDownCapture, this, true); this._nativeStage.addEventListener(egret.TouchEvent.TOUCH_END, this.__stageMouseUpCapture, this, true); this._nativeStage.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.__stageMouseMoveCapture, this, true); this._modalLayer = new GGraph(); this._modalLayer.setSize(this.width, this.height); this._modalLayer.drawRect(0, 0, 0, UIConfig.modalLayerColor, UIConfig.modalLayerAlpha); this._modalLayer.addRelation(this, RelationType.Size); this.displayObject.stage.addEventListener(egret.Event.RESIZE, this.__winResize, this); this.__winResize(null); } private __stageMouseDownCapture(evt: egret.TouchEvent): void { //GRoot.ctrlKeyDown = evt.ctrlKey; //GRoot.shiftKeyDown = evt.shiftKey; GRoot.mouseX = evt.stageX; GRoot.mouseY = evt.stageY; GRoot.touchDown = true; if (this._tooltipWin) this.hideTooltips(); this._justClosedPopups.length = 0; if (this._popupStack.length > 0) { let mc = <egret.DisplayObject>(evt.target); while (mc != this.displayObject.stage && mc) { if (mc["$owner"]) { var pindex: number = this._popupStack.indexOf(<GObject>mc["$owner"]); if (pindex != -1) { for (var i: number = this._popupStack.length - 1; i > pindex; i--) { var popup: GObject = this._popupStack.pop(); this.closePopup(popup); this._justClosedPopups.push(popup); } return; } } mc = mc.parent; } var cnt: number = this._popupStack.length; for (i = cnt - 1; i >= 0; i--) { popup = this._popupStack[i]; this.closePopup(popup); this._justClosedPopups.push(popup); } this._popupStack.length = 0; } } private __stageMouseMoveCapture(evt: egret.TouchEvent): void { //GRoot.ctrlKeyDown = evt.ctrlKey; //GRoot.shiftKeyDown = evt.shiftKey; GRoot.mouseX = evt.stageX; GRoot.mouseY = evt.stageY; } private __stageMouseUpCapture(evt: egret.TouchEvent): void { GRoot.touchDown = false; } private __winResize(evt: egret.Event): void { this.setSize(this._nativeStage.stageWidth, this._nativeStage.stageHeight); //console.info("screen size=" + w + "x" + h + "/" + this.width + "x" + this.height); } private updateContentScaleLevel(): void { var ss: number = 1;// Math.max(cc.view.getScaleX(), cc.view.getScaleY()); if (ss >= 3.5) GRoot.contentScaleLevel = 3; //x4 else if (ss >= 2.5) GRoot.contentScaleLevel = 2; //x3 else if (ss >= 1.5) GRoot.contentScaleLevel = 1; //x2 else GRoot.contentScaleLevel = 0; } } }
the_stack