text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as crypto from 'crypto'; import * as globals from './globals'; import * as logging from '../lib/logging/logging'; import * as loggingTypes from '../lib/loggingprovider/loggingprovider.types'; var log :logging.Log = new logging.Log('KeyVerify'); // KeyVerify's callbacks API from ZRTP protocol. export interface Delegate { // Send this message to the peer KeyVerify sendMessage(msg:Object) :Promise<void>; // Show this Short Authentication String to the user, and ask them // if it's the same as what their peer sees. resolve(true) if it // is, resolve(false) if not. showSAS(sas:string) :Promise<boolean>; }; export enum Type { Hello1, Hello2, Commit, DHPart1, DHPart2, Confirm1, Confirm2, Conf2Ack }; const HELLO1 = 'Hello1'; const HELLO2 = 'Hello2'; const COMMIT = 'Commit'; const DHPART1 = 'DHPart1'; const DHPART2 = 'DHPart2'; const CONFIRM1 = 'Confirm1'; const CONFIRM2 = 'Confirm2'; const CONF2ACK = 'Conf2Ack'; export namespace Messages { // Exported empty parent type. Keeps actual protocol messages // opaque to outside modules. export class Message { }; // // Protocol Messages. These are just type wrappers around the JSON // message formats. Their constructors should be trivial, and must // not have optional arguments. They are dynamically instantiated // in initStaticTables_() below, and the mechanism of dynamic // instantiation precludes optional args. // export class HelloMessage extends Message { constructor(public type: string, public version: string, public h3: string, public hk: string, public clientVersion: string, public mac: string) { super(); } }; export class CommitMessage extends Message { constructor(public type: string, public h2: string, public hk: string, public clientVersion: string, public hvi: string, public mac: string) { super(); } }; export class DHPartMessage extends Message { constructor(public type: string, public h1: string, public pkey: string, public mac: string) { super(); } }; export class ConfirmMessage extends Message { constructor(public type: string, public h0: string, public mac: string) { super(); } }; export class ConfAckMessage extends Message { constructor(public type:string) { super(); } }; export class Tagged { constructor( public type: Type, public value: Message) {} }; }; // // Hash facilities // export class HashPair { public b64 :string; constructor(public bin:Buffer) { this.b64 = bin.toString('base64'); } }; export class Hashes { public h0 :HashPair; public h1 :HashPair; public h2 :HashPair; public h3 :HashPair; }; function makeHash(s:string) :HashPair { let bin = crypto.createHash('sha256').update(s).digest(); return new HashPair(bin); } function hashBuffers(...bufs:Buffer[]) :HashPair { let buffer = Buffer.concat(bufs); let bin = crypto.createHash('sha256').update(buffer).digest(); return new HashPair(bin); } function hashString(s:string) :string { return crypto.createHash('sha256').update(s).digest('base64'); } // // Buffer utility functions // function str2buf(s:string) :Buffer { return new Buffer(s, 'utf8'); } function unb64(s:string) :Buffer { return new Buffer(s, 'base64'); } // Put out a multi-line hex dump of a given Node Buffer. function logBuffer(name:string, buf:Buffer) { var kBufWidth = 75; var linebuf = name + ':'; var remain_width = kBufWidth - linebuf.length; for (var i = 0; i < buf.length; i++) { // Not enough space on the line for another // byte of hex. Dump and put out more. if (remain_width < 3) { log.debug(linebuf); linebuf = ''; remain_width = kBufWidth; } var n :number = buf.readUInt8(i); var c = n.toString(16); if (c.length < 2) { c = '0' + c; } linebuf = linebuf + ' ' + c; remain_width -= 3; } // Write out last line. if (linebuf.length) { log.debug(linebuf); } } // Values from messages are base64 encoded, and many of the // cryptographic operations used in ZRTP require that they be // concatenated before we hash them. function unbase64Concat(...args:string[]) :Buffer { let buffers = args.map((val:string) => { return new Buffer(val, 'base64'); }); return Buffer.concat(buffers); } // A ZRTP Key Verification Session. After construction, its only // interface points are in readMessage() and in the delegate API // (Delegate above). There are two factory methods below: // InitiateVerify() and RespondToVerify() for the ZRTP initiator and // responder. export class KeyVerify { // Only written by set(), after verifying the message. private messages_: {[type:string]:Messages.Tagged}; // indexed by Type. // Only written and read by sendNextMessage(), between the time we // call generate_ and get its promise-return. private queuedGenerations_: {[type:string]:boolean}; // indexed by Type. // Initiator is the side of the connection that sends Hello1. That // same side sends Commit. private isInitiator_:boolean; private ourKey_:freedom.PgpProvider.PublicKey; private ourHashes_:Hashes; private resolvePromise_ : () => void; private rejectPromise_ : () => void; private sasApproved_ = false; private timeoutId_ :any = null; // Explicitly mark when we've already fired a resolution promise, to // prevent an attacker from passing us extra stuff that might make // us change our minds. private completed_:boolean; private pgp_ :freedom.PgpProvider.PgpProvider; // Data that requires expensive calculations to make. These are innately // hackey, and I don't like them. private s0_ :Buffer = null; private totalHash_ :Buffer = null; private static CLIENT_VERSION :string = '0.1'; private static PROTOCOL_VERSION :string = '1.0'; private static emptyPreReq :Type[] = []; // For message verification, the JSONification of an alphabetized // list of keys in each message. private static keyMap_ :{[type:string]:string} = {}; // For message verification, the list of prerequisite messages for // each message. private static prereqMap_ :{[msg:string]:[Type]} = {} // Which role receives which kinds of messages. Clearly this gets // complicated if we ever want to let either side initiate // verification. private static roleMessageMap_ :{[msg:string]:boolean} = {}; private generatorMap_ : {[msg:string]:((type:Type) =>Promise<Messages.Tagged>)} = {}; private messageReadMap_ :{[msg:string]:((msg:Object) => void )} = {}; // Messages are existing messages received or sent in the // conversation. Useful both for testing and for when this Verifier // is being created in response to a received message. constructor(private peerPubKey_: string, private delegate_: Delegate, messages?: {[type:string]:Messages.Tagged}, isInitiator?: boolean, ourHashes?: Hashes) { KeyVerify.initStaticTables_(); this.initDynamicTables_(); this.completed_ = false; this.totalHash_ = null; if (messages === undefined) { // Beginning of conversation. this.messages_ = {}; this.isInitiator_ = true; this.ourHashes_ = this.generateHashes_(); } else { // Peer started conversation, or this is a resumption (say, from a test // case). this.messages_ = messages; this.isInitiator_ = isInitiator; // See if we're a resumption. if (ourHashes) { this.ourHashes_ = ourHashes; } else { this.ourHashes_ = this.generateHashes_(); } } this.queuedGenerations_ = {}; } // Create a Messages.Tagged from an arbitrary message. Designed for // receiving Hello1 messages without the client having to know about // them. public static readFirstMessage(msg:any) : {[type:string]:Messages.Tagged} { KeyVerify.initStaticTables_(); if (msg['type'] && KeyVerify.structuralVerify_(msg) && msg.type === HELLO1) { if (msg.clientVersion !== KeyVerify.CLIENT_VERSION || msg.version !== KeyVerify.PROTOCOL_VERSION) { log.error('Invalid Hello message (versions): ', msg); return null; } var result :{[type:string]:Messages.Tagged} = {}; result[Type.Hello1] = new Messages.Tagged( Type.Hello1, new Messages.HelloMessage( msg.type, msg.version, msg.h3, msg.hk, msg.clientVersion, msg.mac)); return result; } return null; } public readMessage(msg:any) { if (msg['type'] && KeyVerify.structuralVerify_(msg) && this.protoVerify_(msg) && this.appropriateForRole_(msg.type)) { let type = msg.type; log.debug('readMessage: Got Message Type ' + type); this.messageReadMap_[type](msg); if (type !== CONF2ACK) { this.sendNextMessage(); } } else { // reject the message for member key mismatch. log.error('Invalid message received: ', msg); } } private readHello_ = (msg:any) => { // Validate this Hello message. Later versions may set some // local state to maintain compatability with prior versions // of uProxy. if (msg.clientVersion !== KeyVerify.CLIENT_VERSION || msg.version !== KeyVerify.PROTOCOL_VERSION) { log.error('Invalid Hello message (versions): ', msg); this.resolve_(false); return; } var rawType :number = parseInt(Type[msg.type]); // role 0 should receive hello2, and role 1 should receive hello1. if ((this.isInitiator_ && rawType !== Type.Hello2) || (!this.isInitiator_ && rawType !== Type.Hello1)) { log.error('Got the wrong Hello message (' + msg.type + ' [' + rawType + ']) for this role (' + this.isInitiator_ + ')'); this.resolve_(false); return; } this.set_(new Messages.Tagged( rawType, new Messages.HelloMessage(msg.type, msg.version, msg.h3, msg.hk, msg.clientVersion, msg.mac))); }; private readCommit_ = (msg:any) => { if (msg.clientVersion !== KeyVerify.CLIENT_VERSION) { log.error('Invalid Commit message (clientVersion)', msg); this.resolve_(false); return; } // Validate the Hello message's mac. let hello1 = <Messages.HelloMessage>this.messages_[Type.Hello1].value; let hello2 = <Messages.HelloMessage>this.messages_[Type.Hello2].value; if (msg.clientVersion !== hello1.clientVersion) { log.error('Client changed versions mid-conversation.', msg, hello1); this.resolve_(false); return; } let desiredMac = this.mac_(msg.h2, unb64(hello1.h3), str2buf(hello1.hk), str2buf(hello1.clientVersion)); if (hello1.mac !== desiredMac) { log.error('MAC mismatch (found ' + hello1.mac + ', wanted ' + desiredMac + ') for Hello1 found. h2: ', msg.h2, ' and Hello1: ', hello1); log.debug('msg.h2', msg.h2); logBuffer('unb64(hello1.h3)', unb64(hello1.h3)); logBuffer('unb64(hello1.hk)', unb64(hello1.hk)); logBuffer('str2buf(hello1.clientVersion)', str2buf(hello1.clientVersion)); this.resolve_(false); return; } // Validate that h3 is the hash of h2. hello1.h3 is peer's // ourHashes_.h3.b64. msg.h2 is peer's ourHashes_.h2.b64. // So, unb64 it, then hash it, then make a string of that. let desiredH3 = hashBuffers(unb64(msg.h2)).b64 if (hello1.h3 !== desiredH3) { log.error('Hash chain failure for h3: ', hello1.h3, ' and h2: ', msg.h2, ' (hashed to ', desiredH3, ')'); this.resolve_(false); return; } // Check that the peer can be the initiato. if (this.isInitiator_) { log.error('Currently, we only support that role 0 is initiator.'); this.resolve_(false); return; } this.set_(new Messages.Tagged( Type.Commit, new Messages.CommitMessage( msg.type, msg.h2, msg.hk, msg.clientVersion, msg.hvi, msg.mac))); } private readDHPart1_ = (msg:any) => { // We don't have an h2 value to check the hello2 message. let hello2 = <Messages.HelloMessage>this.messages_[Type.Hello2].value; if (hello2.hk !== hashString(msg.pkey)) { log.error('hash(pkey)/hk mismatch for DHPart1 (',msg.pkey, ') vs Hello2 (', hello2.hk, ')'); this.resolve_(false); return; } this.set_(new Messages.Tagged( Type.DHPart1, new Messages.DHPartMessage(msg.type, msg.h1, msg.pkey, msg.mac))); // There's an explicit choice here to treat the primary failure // mode - a failed SAS verification, the same as an I/O error. // Attackers may just kill the connection to look like an I/O // error, so we don't want the users to be mislead by the user // interface messaging here. Instead, let them try again and be // more careful about the numbers. If the numbers don't match up, // they know that they're under attack. this.calculateSAS_().then((sas:number) => { this.delegate_.showSAS(sas.toString()).then((result:boolean) => { this.sasApproved_ = result; if (result) { this.sendNextMessage(); } else { log.error('Failed SAS verification.'); this.resolve_(false); } }); }); } private readDHPart2_ = (msg:any) => { // Verify that this is the same hk. let commit = <Messages.CommitMessage>this.messages_[Type.Commit].value; let hello2 = <Messages.HelloMessage>this.messages_[Type.Hello2].value; if (commit.hk !== hashString(msg.pkey)) { log.error('hash(pkey)/hk mismatch for DHPart2 (',msg.pkey, ') vs Commit (', commit.hk, ')'); this.resolve_(false); return; } // Verify the mac of the Commit. if (commit.mac !== this.mac_(msg.h1, unb64(commit.h2), unb64(commit.hk), str2buf(commit.clientVersion), unb64(commit.hvi))) { log.error('MAC mismatch for Commit found. h1: ', msg.h1, ' and Commit: ', commit); this.resolve_(false); return; } // Check that hvi is correct. let hvi = hashBuffers( unb64(msg.h1), str2buf(msg.pkey), unb64(msg.mac), unb64(hello2.h3), unb64(hello2.hk), unb64(hello2.mac)).b64; if (hvi !== commit.hvi) { log.error('hvi Mismatch in commit. Wanted: ', hvi, ' got: ', msg); this.resolve_(false); return; } this.set_(new Messages.Tagged( Type.DHPart2, new Messages.DHPartMessage(msg.type, msg.h1, msg.pkey, msg.mac))); this.calculateSAS_().then((sas:number) => { this.delegate_.showSAS(sas.toString()).then((result:boolean) => { this.sasApproved_ = result; if (result) { this.sendNextMessage(); } else { log.error('Failed SAS verification.'); this.resolve_(false); } }); }); } private readConfirm1_ = (msg:any) => { // Validate DHpart1 let dhpart1 = <Messages.DHPartMessage>this.messages_[Type.DHPart1].value; if (dhpart1.mac !== this.mac_(msg.h0, unb64(dhpart1.h1), str2buf(dhpart1.pkey))) { log.error('CHECK: MAC mismatch for DHPart1 found. h0: ', msg.h0, ' and DHPart1: ', dhpart1); this.resolve_(false); return; } this.set_(new Messages.Tagged( Type.Confirm1, new Messages.ConfirmMessage(msg.type, msg.h0, msg.mac))); } private readConfirm2_ = (msg:any) => { // Validate DHpart2 let dhpart2 = <Messages.DHPartMessage>this.messages_[Type.DHPart2].value; if (dhpart2.mac !== this.mac_(msg.h0, unb64(dhpart2.h1), str2buf(dhpart2.pkey))) { log.error('CHECK: MAC mismatch for DHPart2 found. h0: ', msg.h0, ' and DHPart2: ', dhpart2); this.resolve_(false); return; } this.set_(new Messages.Tagged( Type.Confirm2, new Messages.ConfirmMessage(msg.type, msg.h0, msg.mac))); // Don't resolve here, wait until we've sent Conf2Ack. } private readConf2Ack_ = (msg:any) => { this.set_(new Messages.Tagged( Type.Conf2Ack, new Messages.ConfAckMessage(msg.type))); log.debug('ZRTP: EVERYTHING IS DONE!!'); this.resolve_(true); } private resolve_(res:boolean) { log.debug('resolve('+res+')'); this.completed_ = true; if (this.timeoutId_) { clearTimeout(this.timeoutId_); this.timeoutId_ = null; } if (res) { this.resolvePromise_(); } else { this.rejectPromise_(); } } // timeout_ms is a timeout, in milliseconds, to auto-reject. public start(timeout_ms ?:number) :Promise<void>{ log.debug('start() starting.'); if (this.completed_) { throw (new Error('KeyVerify.start: Already completed.')); } return this.loadKeys_().then(() => { log.debug('start() callback invoked.'); let result = new Promise<void>((resolve:any, reject:any) => { log.debug('start(): initializing result promises.'); this.resolvePromise_ = resolve; this.rejectPromise_ = reject; if (timeout_ms !== undefined && timeout_ms >= 0) { this.timeoutId_ = setTimeout( () => { if (!this.completed_) { log.info('Verification Timeout.'); this.resolve_(false); } else { log.error('Timeout occurred when already finished.'); } }, timeout_ms); } else { this.timeoutId_ = null; } this.sendNextMessage(); }); return result; }); } private loadKeys_() :Promise<void> { this.pgp_ = <freedom.PgpProvider.PgpProvider>globals.pgp; log.debug('loadKeys(): starting.'); // our public key is globals.publicKey, but we need the fingerprint, so // import the one in globals here, and get the higher-level object here. return this.pgp_.exportKey().then((key:freedom.PgpProvider.PublicKey) => { log.debug('loadKeys: got key ', key); this.ourKey_ = key; return; }); } // Logic for determining the next public sendNextMessage() { if (this.completed_) { throw (new Error('KeyVerify.sendNextMessage: Already completed.')); } log.debug('sendNextMessage(): starting.'); // Look at where we are in the conversation. // - figure out the latest message that isn't in the set. // - see if we have its prereq. // - send it. let msgType:Type; var shouldSend = true; if (this.isInitiator_) { if (this.messages_[Type.Conf2Ack]) { log.debug('sendNextMessage: done!'); this.resolve_(true); return; // all done. } else if (this.messages_[Type.Confirm1]) { shouldSend = this.sasApproved_; msgType = Type.Confirm2; } else if (this.messages_[Type.DHPart1]) { msgType = Type.DHPart2; } else if (this.messages_[Type.Hello2]) { msgType = Type.Commit; } else { msgType = Type.Hello1; } } else { if (this.messages_[Type.Conf2Ack]) { log.debug('sendNextMessage: done!'); this.resolve_(true); return; // all done. } else if (this.messages_[Type.Confirm2]) { msgType = Type.Conf2Ack; } else if (this.messages_[Type.DHPart2]) { shouldSend = this.sasApproved_; msgType = Type.Confirm1; } else if (this.messages_[Type.Commit]) { msgType = Type.DHPart1; } else { msgType = Type.Hello2; } } if (shouldSend && !this.messages_[msgType] && !this.queuedGenerations_[Type[msgType]]) { this.queuedGenerations_[Type[msgType]] = true; this.generate_(msgType).then( (msg:Messages.Tagged) => { this.queuedGenerations_[Type[msgType]] = false; this.set_(msg); this.delegate_.sendMessage(msg.value).then(() => { if (msgType === Type.Conf2Ack) { log.debug('ZRTP: EVERYTHING IS DONE ON THIS SIDE TOO'); this.resolve_(true); } }).catch((e:any) => { log.error('Failed to send message in ZRTP message. Resolving as ' + 'failure.', e); this.resolve_(false); }); }); } } // Message schema verification. private static structuralVerify_ (msg:any) :boolean { if (!msg.type || Object.keys(KeyVerify.roleMessageMap_).indexOf(msg['type']) < 0) { // Unknown type. return false; } // Verify that none of the values are blank. let allKeys = Object.keys(msg); for (let k in allKeys) { if (msg[allKeys[k]].length === '') { log.error('Verify msg ', msg, ' got empty value for key ', k); return false; } } // Verify that we only have the keys we're expecting. let type :string = msg.type.toString(); if (JSON.stringify(allKeys.sort()) !== KeyVerify.keyMap_[type]) { log.error('Verify msg ', msg, ' bad key set. Wanted ', KeyVerify.keyMap_[type], ' got ', allKeys.sort().join()); return false; } // Verify that we have all the prerequisite messages for this one. return true; } // Initialize KeyVerify.keyMap_ and other static tables for use. // It's safe to call this repeatedly. private static initStaticTables_() { if (KeyVerify.keyMap_[HELLO1]) { return; } else { // Initialize static maps used for message validation. // The key map isn't initialized yet, so build it. let setTableEntry = function(type: string, proto:any, prereqs:[Type], initiatorReceives:boolean) { // Create a new instance of the object, then grab the keys out // to make the list that we use for comparison in // structuralVerify_(). let obj = new proto(); KeyVerify.keyMap_[type] = JSON.stringify(Object.keys(obj).sort()); KeyVerify.prereqMap_[type] = prereqs; KeyVerify.roleMessageMap_[type] = initiatorReceives; } setTableEntry(HELLO1, Messages.HelloMessage, <[Type]>[], false); setTableEntry(HELLO2, Messages.HelloMessage, <[Type]>[], true); setTableEntry(COMMIT, Messages.CommitMessage, [Type.Hello1, Type.Hello2], false); setTableEntry(DHPART1, Messages.DHPartMessage, [Type.Commit], true); setTableEntry(DHPART2, Messages.DHPartMessage, [Type.DHPart1], false); setTableEntry(CONFIRM1, Messages.ConfirmMessage, [Type.DHPart2], true); setTableEntry(CONFIRM2, Messages.ConfirmMessage, [Type.Confirm1], false); setTableEntry(CONF2ACK, Messages.ConfAckMessage, [Type.Confirm2], true); } } private initDynamicTables_() { // These are all closed on 'this' now, so we have to init them per-instance. let setTableEntry = (type: string, genFn:((type:Type) =>Promise<Messages.Tagged>), readFn:((msg:Object) => void)) => { this.generatorMap_[type] = genFn; this.messageReadMap_[type] = readFn; } setTableEntry(HELLO1, this.makeHello_, this.readHello_); setTableEntry(HELLO2, this.makeHello_, this.readHello_); setTableEntry(COMMIT, this.makeCommit_, this.readCommit_); setTableEntry(DHPART1, this.makeDHPart_, this.readDHPart1_); setTableEntry(DHPART2, this.makeDHPart_, this.readDHPart2_); setTableEntry(CONFIRM1, this.makeConfirm_, this.readConfirm1_); setTableEntry(CONFIRM2, this.makeConfirm_, this.readConfirm2_); setTableEntry(CONF2ACK, this.makeConf2Ack_, this.readConf2Ack_); } // Message protocol-order verification. private protoVerify_ (msg:any) :boolean { let type :Type = parseInt(Type[msg.type.toString()]); for (let m in KeyVerify.prereqMap_[type]) { let t = KeyVerify.prereqMap_[type][m]; if (!this.messages_[t]) { log.error('Verify msg ', msg, ' missing prerequisite ', t); return false; } } return true; } // Whether we should even receive the given message type. If not, // perhaps we're under attack? private appropriateForRole_(type:string) :boolean { if (KeyVerify.roleMessageMap_[type] !== undefined) { return KeyVerify.roleMessageMap_[type] === this.isInitiator_; } else { return false; } } // Register a message as an accepted part of the conversation. The // message must have been a validated received message, or a message // we've sent. private set_(message: Messages.Tagged) :void { // parseInt returns NaN for non-ints, and NaNs always compare // false in </>/= comparisons. if (!(parseInt(message.type.toString()) < 0) && !(parseInt(message.type.toString()) >= 0)) { log.error('set_: bad type: ', message.type); } if (this.messages_[message.type]) { log.error('set_: already have a message of ', message.type, ' (' + Type[message.type] + ')'); this.resolve_(false); } else { log.error('set_: setting message of ', message.type, ' (' + Type[message.type] + ')'); this.messages_[message.type] = message; } } // // Message Generation // // Primary entry point is generate_, which just looks in an internal // table set up in the constructor. The table has to be set up // there, as we're using this-bound closures in the table. private generate_(type: Type) :Promise<Messages.Tagged> { if (this.completed_) { throw (new Error('KeyVerify.start: Already completed.')); } if (this.generatorMap_[Type[type]] !== undefined) { return this.generatorMap_[Type[type]](type); } else { log.error('generate(' + type + '<' + Type[type] + '>): can\'t generate this type.'); throw (new Error('generate(' + Type[type] + ') not yet implemented.')); } } private makeHello_ = (type: Type) :Promise<Messages.Tagged> => { log.debug('makeHello(' + type + ' <' + Type[type] + '>)'); let h3 = this.ourHashes_.h3, hk = this.ourKey_.key; logBuffer('makeHello: h3:', h3.bin); logBuffer('makeHello: hk '+ hk + ' and str2buf\'d: ', str2buf(hk)); logBuffer('makeHello: clientVersion', str2buf(KeyVerify.CLIENT_VERSION)); let mac = this.mac_(this.ourHashes_.h2.b64, h3.bin,str2buf(hashString(hk)), str2buf(KeyVerify.CLIENT_VERSION)); log.debug('makeHello: mac: ', mac); let message = new Messages.Tagged(type, new Messages.HelloMessage( Type[type], KeyVerify.PROTOCOL_VERSION, h3.b64, hashString(hk), KeyVerify.CLIENT_VERSION, mac)); return Promise.resolve<Messages.Tagged>(message); } private makeDHPart_ = (type:Type) :Promise<Messages.Tagged> => { if (type !== (this.isInitiator_ ? Type.DHPart2 : Type.DHPart1)) { throw (new Error('makeDHPart: Bad type ' + Type[type] + ' for role ' + this.isInitiator_)); } let h1 = this.ourHashes_.h1; let pkey = this.ourKey_.key; let mac = this.mac_(this.ourHashes_.h0.b64, h1.bin, str2buf(pkey)); let message = new Messages.Tagged(type, new Messages.DHPartMessage( Type[type], h1.b64, pkey, mac)); return Promise.resolve<Messages.Tagged>(message); } private makeCommitWorker_(type:Type, dh2:Messages.Tagged) :Promise<Messages.Tagged> { // Don't depend on dhpart2 being in our saved messages yet, as we // may not have sent it out (just generated it). Pass it in as an // argument. let dhpart2 = <Messages.DHPartMessage>dh2.value; let hello = <Messages.HelloMessage>this.messages_[Type.Hello2].value; let hvi = hashBuffers( unb64(dhpart2.h1), str2buf(dhpart2.pkey), unb64(dhpart2.mac), unb64(hello.h3), unb64(hello.hk), unb64(hello.mac) ); let h2 = this.ourHashes_.h2; let hk = makeHash(this.ourKey_.key); let version = KeyVerify.CLIENT_VERSION; return Promise.resolve<Messages.Tagged>( new Messages.Tagged(Type.Commit, new Messages.CommitMessage( Type[Type.Commit], h2.b64, hk.b64, KeyVerify.CLIENT_VERSION, hvi.b64, this.mac_(this.ourHashes_.h1.b64, h2.bin, hk.bin, str2buf(version), hvi.bin)))); } private makeCommit_ = (type:Type) :Promise<Messages.Tagged> => { if (!this.isInitiator_ || type != Type.Commit) { throw (new Error('makeCommit: only supports making Commit messages ' + 'with role 0 being initiator.')); } if (!this.messages_[Type.DHPart2]) { return this.makeDHPart_(Type.DHPart2).then( (msg:Messages.Tagged) => { // Don't invoke this.set_(msg) here. We only set() when we've // sent or received a message.. TODO: consider caching this // message for later transmission. return this.makeCommitWorker_(type, msg); }); } else { return this.makeCommitWorker_(type, this.messages_[Type.DHPart2]); } } private makeConfirm_ = (type:Type) :Promise<Messages.Tagged> => { if (type !== Type.Confirm1 && type !== Type.Confirm2) { throw (new Error('makeConfirm cannot make ' + Type[type] + ' messages')); } return this.calculateS0_().then( (s0 :Buffer) => { let h0 = this.ourHashes_.h0; return new Messages.Tagged(type, new Messages.ConfirmMessage( Type[type], h0.b64, this.mac_(s0.toString('base64'), h0.bin))); }); } private makeConf2Ack_ = (type:Type) :Promise<Messages.Tagged> => { if (type !== Type.Conf2Ack) { throw (new Error('makeConf2Ack can only make Conf2Ack.')); } return Promise.resolve<Messages.Tagged>( new Messages.Tagged(type, new Messages.ConfAckMessage(CONF2ACK))); }; // // Crypto Stuff // // This is all based off of ZRTP (RFC 6189), with keys that don't // expire, and no caching. private generateHashes_() :Hashes { var result : Hashes = new Hashes(); let h1Hash = crypto.createHash('sha256'), h2Hash = crypto.createHash('sha256'), h3Hash = crypto.createHash('sha256'); let h0 = crypto.randomBytes(256 / 8); result.h0 = new HashPair(h0); h1Hash.update(h0); let h1 = h1Hash.digest(); result.h1 = new HashPair(h1); h2Hash.update(h1); let h2 = h2Hash.digest(); result.h2 = new HashPair(h2); h3Hash.update(h2); let h3 = h3Hash.digest(); result.h3 = new HashPair(h3); let hashes :[string] = [h3.toString('base64'), h2.toString('base64'), h1.toString('base64'), h0.toString('base64')]; log.debug('Generated hashes: ', hashes); return result; } private calculateS0_() :Promise<Buffer> { if (this.s0_ !== null) { logBuffer('s0: calculateS0_: State=' + this.state_() + ', returning cached', this.s0_); return Promise.resolve<Buffer>(this.s0_); } return this.pgp_.ecdhBob('P_256', this.peerPubKey_).then( (result:ArrayBuffer) => { log.debug('CALCULATING s0'); let be64Zero = new Buffer(8), beZero = new Buffer(4), beOne = new Buffer(4); be64Zero.fill(0); beZero.fill(0); beOne.writeInt32BE(1,0); // RFC6189-4.4.1.4 let total_hash = this.calculateTotalHash_(); let resultBuffer = new Buffer(new Uint8Array(result)); let s0_input = Buffer.concat([ beOne, resultBuffer, new Buffer('ZRTP-HMAC-KDF'), be64Zero, be64Zero, total_hash, beZero, beZero, beZero]); let s0 = crypto.createHash('sha256').update(s0_input).digest(); logBuffer('s0', s0); this.s0_ = s0; return s0; }); } // Return a 16 bit number useful as a "short authentication string." // This is an arbitrary selection, RFC6189 uses it as an example // value, but the underlying calculation pulls the first 32 bits // out. We just truncate that (again, to emphasize the tragedy of // lost entropy) to 16 bits and return it as a number. private calculateSAS_() :Promise<number> { return this.calculateS0_().then( (s0:Buffer) => { let be64Zero = new Buffer(8), be32Zero = new Buffer(4), beOne = new Buffer(4); be64Zero.fill(0); be32Zero.fill(0); beOne.writeInt32BE(1,0); let total_hash = this.calculateTotalHash_(); let kdf_context = Buffer.concat([ be64Zero, be64Zero, total_hash ]); logBuffer('kdf_context', kdf_context); // RFC6189-4.5.2 let sashash = this.kdf_(s0, 'SAS', kdf_context, 256); logBuffer('sashash', sashash); let sasvalue = sashash.slice(0, 4); logBuffer('sasvalue', sasvalue); let sasHumanInt :number = sasvalue.slice(0,2).readUInt16BE(0); return sasHumanInt; }); } private calculateTotalHash_() :Buffer { let hello_r :Messages.HelloMessage; // We only support role 0 committing, making role 1 (who sent // hello2) the responder. hello_r = <Messages.HelloMessage>this.messages_[Type.Hello2].value; let commit = <Messages.CommitMessage> this.messages_[Type.Commit].value; let dhpart1 = <Messages.DHPartMessage> this.messages_[Type.DHPart1].value; let dhpart2 = <Messages.DHPartMessage> this.messages_[Type.DHPart2].value; let elems = { 'hello_r.h3': hello_r.h3, 'hello_r.hk': hello_r.hk, 'hello_r.mac': hello_r.mac, 'commit.h2': commit.h2, 'commit.hk': commit.hk, 'commit.clientVersion': commit.clientVersion, 'commit.hvi': commit.hvi, 'dhpart1.h1': dhpart1.h1, 'dhpart1.pkey': dhpart1.pkey, 'dhpart1.mac': dhpart1.mac, 'dhpart2.h1': dhpart2.h1, 'dhpart2.pkey': dhpart2.pkey, 'dhpart2.mac': dhpart2.mac }; log.debug('totalHash: keys to total_hash_buf: ', elems); let first_hash_buf = unbase64Concat(hello_r.h3, hello_r.hk, hello_r.mac, commit.h2, commit.hk); let cv_buf = new Buffer(commit.clientVersion); let second_hash_buf = unbase64Concat(commit.hvi, dhpart1.h1); let dh1k_buf = new Buffer(dhpart1.pkey); let third_hash_buf = unbase64Concat(dhpart1.mac, dhpart2.h1); let dh2k_buf = new Buffer(dhpart2.pkey); let fourth_hash_buf = unbase64Concat(dhpart2.mac); let total_hash_buf = Buffer.concat( [ first_hash_buf, cv_buf, second_hash_buf, dh1k_buf, third_hash_buf, dh2k_buf, fourth_hash_buf ] ); logBuffer('total_hash_buf', total_hash_buf); log.debug('totalHash: init-role: ', this.isInitiator_); log.debug('totalHash: hello_r: h3:', hello_r.h3, ', hk:', hello_r.hk, ', mac:', hello_r.mac); log.debug('totalHash: commit: h2: ', commit.h2, ', hk:', commit.hk, ', clientVersion:', commit.clientVersion, ', hvi:', commit.hvi); log.debug('totalHash: dhpart1: h1:', dhpart1.h1, ', pkey:', dhpart1.pkey, ', mac:', dhpart1.mac); log.debug('totalHash: dhpart2: h1:', dhpart2.h1, ', pkey:', dhpart2.pkey, ', mac:', dhpart2.mac); log.debug('totalHash: total_hash_buf: ', total_hash_buf); let hashed = crypto.createHash('sha256').update(total_hash_buf).digest(); log.debug('totalHash: resulting hash is ', hashed); this.totalHash_ = hashed; return hashed; } // 'key' is a regular buffer, that we re-encode into a base64 string // for fullHmac. private kdf_(key :Buffer, label :string, context :Buffer, numbits :number) :Buffer{ var oneBuf = new Buffer(4); var lenBuf = new Buffer(4); oneBuf.writeInt32BE(1, 0); lenBuf.writeInt32BE(numbits, 0); var b64Key = key.toString('base64'); var zeroByte :Buffer= new Buffer(1); zeroByte.fill(0); var completeValue = Buffer.concat([ oneBuf, new Buffer(label), zeroByte, Buffer.concat([context]), lenBuf]); var full_hmac = this.fullHmac_(b64Key, completeValue.toString('base64')); log.debug('kdf: full_hmac: ', full_hmac); return full_hmac.slice(0, Math.ceil(numbits / 8)); } // key and value are both base64-encoded. private fullHmac_(key:string, value:string) :Buffer { return crypto.createHmac('sha256', new Buffer(key, 'base64')) .update(new Buffer(value, 'base64')).digest(); } // key is base64 encoded. values are buffers. private mac_(key:string, ...values:Buffer[]) :string { let valueB64 = Buffer.concat(values).toString('base64'); let full_hmac = this.fullHmac_(key, valueB64); let sliced = full_hmac.slice(0,2); let result = Buffer.concat([sliced]).toString('base64'); log.debug('mac_(key <b64>:' + key + ', val <bin>:', values, '): full_hmac: ' + full_hmac.toString('hex') + ', sliced: ' + sliced.toString('hex') + ', result: ' + result); return result; } private state_() :string { return '{' + Object.keys(this.messages_).map((key: any, index:number) => { return Type[key]; }).join(',') + '}'; } }; // Create a ZRTP verificaiton session in response to an incoming // message. To send the first response, invoke start() on the // returned object. export function RespondToVerify(peerPubKey :string, delegate :Delegate, firstMessage:any) :KeyVerify { let parsedFirstMsg = KeyVerify.readFirstMessage(firstMessage); if (parsedFirstMsg !== null) { return new KeyVerify( peerPubKey, delegate, parsedFirstMsg, false); } else { return null; } } // Create a ZRTP verification session. To send the first message, // invoke start() on the returned object. export function InitiateVerify(peerPubKey :string, delegate :Delegate) :KeyVerify { return new KeyVerify(peerPubKey, delegate); }
the_stack
import React, { ReactNode, useImperativeHandle, Ref, forwardRef, useRef, MutableRefObject, useState, useEffect } from 'react' import AyCard from '../AyCard' import { theme } from '../Theme' import { Form, Row, Col, Input } from 'antd' import { AyFormField, AyFormProps, FieldListener, RegisterFieldProps } from './ay-form' import { copy } from '../utils' import { AySearchField } from '../AySearch/ay-search' import { AnyKeyProps } from '../types/AnyKeyProps' import { install } from './FieldsInit' import { FORM_TYPE_SELECT, FORM_TYPE_PASSWORD, FORM_TYPE_INPUT, FORM_TYPE_CUSTOM, FORM_TYPE_DATE, FORM_TYPE_TEXTAREA, FORM_TYPE_DATE_RANGE, FORM_TYPE_NUMBER, FORM_TYPE_PERCENT, FORM_TYPE_CARD, FORM_TYPE_GROUP, FORM_TYPE_INPUT_GROUP } from '../constant' import './ay-form.less' import moment from 'moment' import 'moment/locale/zh-cn' import { AySearchTableField } from '../AySearchTable/ay-search-table' import { ColProps } from 'antd/lib/col' moment.locale('zh-cn') const defaultLayout = { labelCol: { flex: '120px' }, wrapperCol: { flex: '1' } } const fieldMap: AnyKeyProps = {} /** * 注册一个 field type * @param fieldType field 类型 * @param field 注册的 field */ export const registerField = (fieldType: string, field: RegisterFieldProps) => { fieldMap[fieldType] = field } // 初始化注册 field install(registerField) /** * 获取隐藏配置项 * @param field 配置项 */ const getNoVisibleField = (field: AyFormField | AySearchTableField): AyFormField | AySearchTableField => { return { ...field, title: '', type: 'empty' } } /** * 生成 placeholder * @param field 配置项 */ const getPlaceholder = (field: AyFormField | AySearchTableField): string => { const defaultProps = field.props if (defaultProps && defaultProps.placeholder) { return defaultProps.placeholder } if (!field.type) { return `请输入${field.title || ''}` } if ( [FORM_TYPE_INPUT, FORM_TYPE_NUMBER, FORM_TYPE_PERCENT, FORM_TYPE_PASSWORD, FORM_TYPE_TEXTAREA].includes(field.type) ) { return `请输入${field.title || ''}` } else if ([FORM_TYPE_SELECT, FORM_TYPE_DATE].includes(field.type)) { return `请选择${field.title || ''}` } return '请输入' + field.title || '' } /** * 获得配置列表 * @param fields 配置列表 */ export const getDefaultValue = (fields: Array<AyFormField | AySearchField | AySearchTableField>) => { let form: AnyKeyProps = {} fields.forEach((field: AyFormField | AySearchField | AySearchTableField) => { if (field.type === FORM_TYPE_CARD || field.type === FORM_TYPE_GROUP || field.type === FORM_TYPE_INPUT_GROUP) { form = { ...form, ...getDefaultValue(field.children || []) } return } let type = field.type || 'input' const key = field?.key || '' // 如果配置项里存在默认值,直接返回默认值,否则从默认值表里获取 if (field.hasOwnProperty('defaultValue')) { // 日期类型的需要通过 moment 转一遍 if (type === FORM_TYPE_DATE && field.defaultValue) { form[key] = moment(field.defaultValue) } else { form[key] = field.defaultValue } } else if (type) { if (fieldMap[type]) { const fieldItem = fieldMap[type] let defaultValue = fieldItem.defaultValue defaultValue = typeof defaultValue === 'object' ? copy(defaultValue) : defaultValue form[key] = defaultValue } else { form[key] = undefined } } }) return form } export const getFieldDefaultValue = (key: string, fields: Array<AyFormField | AySearchField | AySearchTableField>) => { if (!key) { return '' } let field: any = getField(key, fields) if (field) { let type = field.type || 'input' // 如果配置项里存在默认值,直接返回默认值,否则从默认值表里获取 if (field.hasOwnProperty('defaultValue')) { return field.defaultValue } else if (type) { if (fieldMap[type]) { const fieldItem = fieldMap[type] let defaultValue = fieldItem.defaultValue defaultValue = typeof defaultValue === 'object' ? copy(defaultValue) : defaultValue return defaultValue } else { return '' } } } } /** * 根据不同的 type 生成不同种类的标签 Tag * @param field 配置项 */ const getTag = ( field: AyFormField | AySearchTableField, fields: Array<AyFormField | AySearchTableField>, formInstans: AnyKeyProps, addFieldListener: (key: string, fieldListener: FieldListener) => void, removeFiledListener: (key: string, fieldListener: FieldListener) => void, readonly?: boolean ) => { let { type } = field type = type || 'input' let tag: ReactNode = null if (fieldMap[type || '']) { let fieldItem = fieldMap[type || ''] tag = fieldItem.render({ field, setFieldsValue: formInstans.setFieldsValue, formInstans, readonly: readonly || field.readonly || false, addFieldListener, removeFiledListener, getFieldValue: formInstans.getFieldValue }) } else { switch (type) { case FORM_TYPE_CUSTOM: if (typeof field.renderContent === 'function') { tag = field.renderContent(field, formInstans.getFieldsValue() || getDefaultValue(fields)) } break } } return tag } /** * 通过配置列表转 Form.Item * @param fields 配置列表 * @param formInstans form 实例 * @param addFieldListener 添加 form 监听事件 * @param removeFiledListener 移除 form 监听事件 * @param props form 的 props * @param childrenType 子类型 */ const getFormItem = ( fields: Array<AyFormField | AySearchTableField>, formInstans: AnyKeyProps, addFieldListener: (key: string, fieldListener: FieldListener) => void, removeFiledListener: (key: string, fieldListener: FieldListener) => void, props: AyFormProps, childrenType?: 'group' | 'card' | 'input-group' ) => { const { span, readonly, formLayout, gutter } = props const ayFormProps: AyFormProps = props return fields.map((field: AyFormField | AySearchTableField) => { const fieldSpan = field.span !== 0 ? field.span || span || 12 : span || 12 if (field.type === FORM_TYPE_CARD) { return ( <Col key={field.key ?? Math.random()} span={24}> <AyCard title={field.title} {...field.props}> <Row gutter={gutter}> {getFormItem( field.children as Array<AyFormField | AySearchTableField>, formInstans, addFieldListener, removeFiledListener, ayFormProps, FORM_TYPE_CARD )} </Row> </AyCard> </Col> ) } let visible = true // 隐藏该项目,保留占位,但是保留值 if (field.visible !== undefined) { visible = typeof field.visible === 'function' ? field.visible() : field.visible } let hidden = false // 隐藏该项目,不保留占位,但是保留值 if (field.hidden !== undefined) { hidden = typeof field.hidden === 'function' ? field.hidden() : field.hidden } // 隐藏该项,只显示占位,保留 form 值 if (!visible || hidden) { field = getNoVisibleField(field) } // 设置 Form.Item 的属性 let props: AnyKeyProps = { ...field.formItemProps, label: field.title, name: field.key, extra: field.help } // 组合元素的 formItem 不需要样式 if (childrenType === FORM_TYPE_GROUP || childrenType === FORM_TYPE_INPUT_GROUP) { props.noStyle = true } // 设定 开关、多选框 等的值类型 (这是 ant design form 的限制) if (field.type && fieldMap[field.type]) { props.valuePropName = fieldMap[field.type].valuePropName || 'value' } // 设置每个【表单项】的占位 const colProps: ColProps = { span: fieldSpan, offset: field.offset } // 不保留占位 if (hidden) { colProps.span = 0 colProps.xs = 0 colProps.sm = 0 colProps.md = 0 colProps.lg = 0 colProps.xl = 0 } // 填充 rules 属性 if (field.rules) { props.rules = [...field.rules] } // 填充快捷 required 属性 if (field.required) { let rule = { required: true, message: getPlaceholder(field) } if (props.rules) { props.rules.push(rule) } else { props.rules = [rule] } } let tag: ReactNode switch (field.type) { case FORM_TYPE_GROUP: tag = ( <Row className="ay-form-group"> {getFormItem( field.children as Array<AyFormField | AySearchTableField>, formInstans, addFieldListener, removeFiledListener, ayFormProps, FORM_TYPE_GROUP )} </Row> ) break case FORM_TYPE_INPUT_GROUP: tag = ( <Input.Group compact> {getFormItem( field.children as Array<AyFormField | AySearchTableField>, formInstans, addFieldListener, removeFiledListener, ayFormProps, FORM_TYPE_INPUT_GROUP )} </Input.Group> ) break default: tag = getTag(field, fields, formInstans, addFieldListener, removeFiledListener, readonly) break } const content = field.render ? ( field.render(field, formInstans.getFieldsValue() || getDefaultValue(fields)) ) : ( <Form.Item {...props}>{tag}</Form.Item> ) if (formLayout === 'inline' || childrenType === FORM_TYPE_INPUT_GROUP) { return content } return ( <Col key={field.key} {...colProps}> {content} </Col> ) }) } const getField = (key: string, fields: Array<AyFormField | AySearchTableField>) => { let field: AyFormField | AySearchTableField | null = null const loop = (fields: Array<AyFormField | AySearchTableField>) => { for (let i = 0; i < fields.length; i++) { let item = fields[i] if (item.key === key) { field = item } else if (Array.isArray(item.children) && item.children.length) { loop(item.children) } } } loop(fields) return field } /** * 格式化 日期 * @param values 格式化的数据 * @param fields 配置项 */ const formatValues = (values: AnyKeyProps, fields: Array<AyFormField | AySearchTableField>): AnyKeyProps => { let result: AnyKeyProps = {} for (let key in values) { if (key.startsWith('__')) { continue } let value = values[key] let field: any = getField(key, fields) if (value && field) { // 获得格式化日期格式 let formatRule: string = field?.props?.showTime === true ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD' if (field.formatRule) { formatRule = field.formatRule } if (Array.isArray(value) && field.type === FORM_TYPE_DATE_RANGE) { // 区间类型取 startKey 与 endKey if (value[0]) { if (typeof value[0] === 'string') { result[field.startKey || 'startDate'] = value[0] } else { result[field.startKey || 'startDate'] = value[0]?.format(formatRule) || null } } if (value[1]) { if (typeof value[1] === 'string') { result[field.endKey || 'endDate'] = value[1] } else { result[field.endKey || 'endDate'] = value[1]?.format(formatRule) || null } } } else if (field.type === FORM_TYPE_DATE) { // 单值类型直接转 if (typeof value === 'string') { result[key] = value } else { result[key] = value?.format(formatRule) || null } } else { result[key] = value } } else { result[key] = value // undefined 视为 null if (value === undefined) { result[key] = null } } } return result } /** * 提交表单,如果有 onConfirm 事件传入,则触发一次 * @param values 表单值 * @param onConfirm 提交表单事件 */ const handleConfirm = ( values: AnyKeyProps, fields: Array<AyFormField | AySearchTableField>, onConfirm?: (values: AnyKeyProps) => void ) => { if (onConfirm) { onConfirm(formatValues(values, fields)) } } /** * 支持表单改变事件监听 * @param changedValues 改变的值 * @param allValues 表单所有的值 * @param fields 所有的饿配置项 * @param setFieldsValue 设置表单值的方法 */ const handleChange = ( changedValues: AnyKeyProps, allValues: AnyKeyProps, fields: Array<AyFormField | AySearchTableField>, setFieldsValue: (params: AnyKeyProps) => void, listnerList: Array<{ key: string; fieldListener: FieldListener }> ) => { for (let key in changedValues) { let field: any = getField(key, fields) if (field) { let value = changedValues[key] if (field.onChange) { field.onChange(value, allValues, setFieldsValue) } // 如果监听器里命中目标,则触发目标事件 listnerList.forEach((item: { key: string; fieldListener: FieldListener }) => { if (item.key === key && field) { item.fieldListener(value, field) } }) } } } /** * 获取 AyForm 样式 * @param className 外部 className * @param desc 是否处于文档模式 * @param readonly 是否处于只读模式 */ const getAyFormClassName = (className?: string, desc?: boolean, readonly?: boolean) => { const classList = ['ay-form', theme] if (className) { classList.push(className) } if (desc) { classList.push('desc') } if (readonly) { classList.push('readonly') } return classList.join(' ') } /** * antd form 原生支持的方法尽数暴露出去 */ const funcs = [ 'getFieldValue', 'getFieldsValue', 'getFieldError', 'getFieldsError', 'isFieldTouched', 'isFieldsTouched', 'isFieldValidating', 'resetFields', 'scrollToField', 'setFields', 'setFieldsValue', 'submit', 'validateFields' ] export default forwardRef(function AyForm(props: AyFormProps, ref: Ref<any>) { const { fields, formLayout = 'horizontal', onConfirm, children, props: defaultProps, readonly, desc, layout, className, style, labelAlign, gutter } = props /** 控制 any form 的实例 */ const formRef: MutableRefObject<any> = useRef() let [listnerList, setListnerList] = useState<Array<any>>([]) /** 暴露出去的 form 的实例,允许父组件通过 ref 调用方法 */ const formInstans: AnyKeyProps = {} const [inited, setInited] = useState<boolean>(false) let [mirrorFields, setMirrorFields] = useState<Array<AyFormField | AySearchTableField>>(fields) /** 刷新渲染用 */ let [refresh, setRefresh] = useState<number>(0) /** 填充方法 */ funcs.forEach(func => { formInstans[func] = (...args: any) => formRef.current[func](...args) }) formInstans.setFieldsValue = (values: AnyKeyProps) => { fields.forEach(field => { if (field.type === FORM_TYPE_DATE) { if (values[field?.key || '']) { values[field?.key || ''] = moment(values[field?.key || '']) } } }) formRef.current.setFieldsValue(values) refresh += 1 setRefresh(refresh) } // 改变 field formInstans.refreshFields = () => { mirrorFields = [...fields] setMirrorFields(mirrorFields) } useEffect(() => { setMirrorFields(fields) }, [fields]) /** * 获取 field 的值 * 如果 field 还没有渲染完,那获得的是 defaultValue * @param key field 的 key * @param readonly 是否只读 */ const getFieldValue = (key: string, readonly?: boolean) => { if (inited) { let value = formRef.current.getFieldValue(key) let field: any = getField(key, fields) if (field && value) { // 获得格式化日期格式 let formatRule: string = field?.props?.showTime === true ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD' if (field.formatRule) { formatRule = field.formatRule } // 只读模式下,格式化日期取 readonlyFormatRule if (field.readonlyFormatRule && readonly) { formatRule = field.readonlyFormatRule } if (field.type === FORM_TYPE_DATE) { // 日期格式化 value = value?.format(formatRule) || null } else if (Array.isArray(value) && field.type === FORM_TYPE_DATE_RANGE) { // 日期区间格式化 value = [value[0]?.format(formatRule) || null, value[1]?.format(formatRule) || null] } } return value } else { return getFieldDefaultValue(key, fields) } } /** * 根据 fields 获取 values * @param fields 配置项 * @param readonly 是否只读 * @returns object */ const getValues = (fields: AyFormField | AySearchTableField, readonly?: boolean) => { let result: AnyKeyProps = {} fields.forEach((field: AyFormField | AySearchTableField) => { if (!field.key) { return } // 获取每个单个的值 let value = getFieldValue(field.key, readonly) // 处理子层数据 if (field.children && field.children.length) { let values = getValues(field.children, readonly) result = { ...result, ...values } } result[field.key] = value }) return result } /** * 获取所有 field 的值 * @param readonly 是否只读 */ const getFieldsValue = (readonly?: boolean) => { return getValues(fields, readonly) } /** 覆盖 antd Form getFieldValue 方法 */ formInstans.getFieldValue = getFieldValue /** 覆盖 antd Form getFieldsValue 方法 */ formInstans.getFieldsValue = getFieldsValue /** * 获取过滤后所有的 field 的值 */ const getFormatFieldsValue = (readonly?: boolean) => { let values = getFieldsValue(readonly) return formatValues(values, fields) } /** 添加 getFormatFiledsValue 的值 */ formInstans.getFormatFieldsValue = getFormatFieldsValue /** 暴露方法 */ useImperativeHandle(ref, () => formInstans) const addFieldListener = (key: string, fieldListener: FieldListener) => { listnerList.push({ key, fieldListener }) setListnerList(listnerList) } const removeFiledListener = (key: string, fieldListener: FieldListener) => { let index = listnerList.findIndex(item => item.fieldListener === fieldListener) listnerList.splice(index, 1) setListnerList(listnerList) } const formItemLayout = formLayout === 'horizontal' ? { ...defaultLayout, ...layout } : null useEffect(() => { setInited(true) }, []) return ( <div className={getAyFormClassName(className, desc, readonly)} style={style}> <Form ref={formRef} {...formItemLayout} labelAlign={labelAlign} layout={formLayout} name={props.name || 'ay-form'} initialValues={getDefaultValue(mirrorFields)} onFinish={values => handleConfirm(values, mirrorFields, onConfirm)} onValuesChange={(changedValues, allValues) => handleChange(changedValues, allValues, mirrorFields, formInstans.setFieldsValue, listnerList) } {...defaultProps} > <Row gutter={gutter}> {getFormItem(mirrorFields, formInstans, addFieldListener, removeFiledListener, props)} {children} </Row> </Form> </div> ) })
the_stack
import React, { ReactNode } from "react"; import { Provider as FluentUIThemeProvider, mergeThemes, teamsTheme, teamsDarkTheme, teamsHighContrastTheme, ComponentVariablesInput, ThemePrepared, } from "@fluentui/react-northstar"; import { ComponentVariablesObject, ThemeInput } from "@fluentui/styles"; import { defaultV2ThemeOverrides, darkV2ThemeOverrides, highContrastThemeOverrides, TeamsTheme, } from "../themes"; import { TLocale, TTranslations, default as builtInTranslations, } from "../translations"; export enum IThemeTeamsClient { HighContrast = "contrast", Dark = "dark", Default = "default", } /** * The Provider’s props configure how these components should be rendered: the color palette to use * as `themeName`, the language as `lang`, and any languages to make available through * `translations`. Its children should be a single component from this library. * * @public */ export interface IThemeProviderProps { children: ReactNode; lang: TLocale; themeName: TeamsTheme | IThemeTeamsClient; translations?: { [locale: string]: TTranslations }; } export const teamsNextVariableAssignments = { componentVariables: { TableRow: ({ colorScheme }: ComponentVariablesInput) => ({ color: colorScheme.default.foreground1, }), }, componentStyles: { Box: { root: ({ variables }: ComponentVariablesObject) => ({ color: variables.color, backgroundColor: variables.backgroundColor, borderColor: variables.borderColor, borderWidth: variables.borderWidth, boxShadow: variables.elevation, }), }, ButtonContent: { root: ({ variables }: ComponentVariablesObject) => ({ fontWeight: variables.fontWeight, }), }, Card: { root: ({ variables }: ComponentVariablesObject) => ({ boxShadow: variables.elevation, "&:hover": { boxShadow: variables.hoverElevation }, "&:focus": { boxShadow: variables.elevation }, }), }, Checkbox: { label: ({ variables }: ComponentVariablesObject) => ({ flex: variables.labelFlex, }), }, Flex: { root: ({ variables }: ComponentVariablesObject) => ({ color: variables.color, backgroundColor: variables.backgroundColor, boxShadow: variables.elevation, }), }, ListItem: { root: ({ variables }: ComponentVariablesObject) => ({ color: variables.color, backgroundColor: variables.backgroundColor, fontWeight: variables.fontWeight, ...(variables.hoverBackgroundColor && { "&:hover": { backgroundColor: variables.hoverBackgroundColor, }, }), }), }, ToolbarItem: { root: ({ variables }: ComponentVariablesObject) => ({ color: variables.color, fontWeight: variables.fontWeight, }), }, PopupContent: { content: ({ variables }: ComponentVariablesObject) => ({ boxShadow: variables.elevation, borderWidth: variables.borderWidth, }), }, PopupButton: { root: ({ variables }: ComponentVariablesObject) => ({ color: variables.color, }), }, TableRow: { root: ({ variables }: ComponentVariablesObject) => { return { height: variables.compactRow ? variables.compactRowHeight : variables.defaultRowHeight, minHeight: variables.compactRow ? variables.compactRowMinHeight : variables.defaultRowMinHeight, alignItems: variables.cellVerticalAlignment, }; }, }, TableCell: { root: ({ variables }: ComponentVariablesObject) => ({ paddingTop: variables.compactRow ? variables.compactRowVerticalPadding : variables.defaultRowVerticalPadding, paddingBottom: variables.compactRow ? variables.compactRowVerticalPadding : variables.defaultRowVerticalPadding, }), }, TreeItem: { root: ({ variables }: ComponentVariablesObject) => ({ color: variables.color, }), }, }, }; export const themes: { [themeKey: string]: ThemeInput<any> } = { [TeamsTheme.Default]: mergeThemes( teamsTheme, teamsNextVariableAssignments, defaultV2ThemeOverrides ), [TeamsTheme.Dark]: mergeThemes( teamsDarkTheme, teamsNextVariableAssignments, darkV2ThemeOverrides ), [TeamsTheme.HighContrast]: mergeThemes( teamsHighContrastTheme, teamsNextVariableAssignments, highContrastThemeOverrides ), }; /** * @public */ export const HVCThemeProvider = ({ children, lang, themeName, translations, }: IThemeProviderProps) => { // [v-wishow] todo: translations will (presumably) eventually need to be loaded asynchronously switch (themeName) { case IThemeTeamsClient.Dark: themeName = TeamsTheme.Dark; break; case IThemeTeamsClient.Default: themeName = TeamsTheme.Default; break; case IThemeTeamsClient.HighContrast: themeName = TeamsTheme.HighContrast; break; } const theme = themes[themeName]; const rtl = lang === "fa"; if (theme.siteVariables) { theme.siteVariables.lang = lang; theme.siteVariables.rtl = rtl; theme.siteVariables.t = (translations && translations[lang]) || builtInTranslations[lang]; } const customScrollbarStyles = // From `react-perfect-scrollbar`: `/* * Container style */ .ps { overflow: hidden !important; overflow-anchor: none; -ms-overflow-style: none; touch-action: auto; -ms-touch-action: auto; } /* * Scrollbar rail styles */ .ps__rail-x { display: none; opacity: 1; transition: background-color .2s linear, opacity .2s linear; -webkit-transition: background-color .2s linear, opacity .2s linear; height: 6px; /* there must be 'bottom' or 'top' for ps__rail-x */ bottom: 2px; /* please don't change 'position' */ position: absolute; } .ps__rail-y { display: none; opacity: 1; transition: background-color .2s linear, opacity .2s linear; -webkit-transition: background-color .2s linear, opacity .2s linear; width: 6px; /* there must be 'right' or 'left' for ps__rail-y */ ${rtl ? "left" : "right"}: 2px; /* please don't change 'position' */ position: absolute; } .ps--active-x > .ps__rail-x, .ps--active-y > .ps__rail-y { display: block; background-color: transparent; } .ps:hover > .ps__rail-x, .ps:hover > .ps__rail-y, .ps--focus > .ps__rail-x, .ps--focus > .ps__rail-y, .ps--scrolling-x > .ps__rail-x, .ps--scrolling-y > .ps__rail-y { opacity: 1; } .ps .ps__rail-x:hover, .ps .ps__rail-y:hover, .ps .ps__rail-x:focus, .ps .ps__rail-y:focus, .ps .ps__rail-x.ps--clicking, .ps .ps__rail-y.ps--clicking { opacity: 1; } /* * Scrollbar thumb styles */ .ps__thumb-x { opacity: ${themeName === TeamsTheme.HighContrast ? "1" : "0.2"}; background-color: ${ theme.siteVariables!.colorScheme.default.foreground }; border-radius: 9999px; transition: background-color .2s linear, height .2s ease-in-out; -webkit-transition: background-color .2s linear, height .2s ease-in-out; height: 6px; /* there must be 'bottom' for ps__thumb-x */ bottom: 2px; /* please don't change 'position' */ position: absolute; z-index: 1000; } .ps__thumb-y { opacity: ${themeName === TeamsTheme.HighContrast ? "1" : "0.2"}; background-color: ${ theme.siteVariables!.colorScheme.default.foreground }; border-radius: 9999px; transition: background-color .2s linear, width .2s ease-in-out; -webkit-transition: background-color .2s linear, width .2s ease-in-out; width: 6px; /* there must be 'right' for ps__thumb-y */ right: 2px; /* please don't change 'position' */ position: absolute; z-index: 1000; } .ps__rail-x:hover > .ps__thumb-x, .ps__rail-x:focus > .ps__thumb-x, .ps__rail-x.ps--clicking .ps__thumb-x { background-color: ${ theme.siteVariables!.colorScheme.default.foreground }; height: 6px; } .ps__rail-y:hover > .ps__thumb-y, .ps__rail-y:focus > .ps__thumb-y, .ps__rail-y.ps--clicking .ps__thumb-y { background-color: ${ theme.siteVariables!.colorScheme.default.foreground }; width: 6px; } /* MS supports */ @supports (-ms-overflow-style: none) { .ps { overflow: auto !important; } } @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) { .ps { overflow: auto !important; } } .scrollbar-container { position: relative; height: 100%; }`; return ( <FluentUIThemeProvider theme={theme} rtl={rtl} style={{ backgroundColor: theme.siteVariables && theme.siteVariables.colorScheme.default.background2, }} > <style> {` html, body, #root, #root > .ui-provider { min-height: 100% } ::-webkit-scrollbar { width: .75rem } ::-webkit-scrollbar-track { background-color: ${theme.siteVariables?.colorScheme.default.background2}; } ::-webkit-scrollbar-thumb { background-color: ${theme.siteVariables?.colorScheme.onyx.border2}; border-radius: .75rem; border: 3px solid transparent; background-clip: content-box; } ::-webkit-scrollbar-thumb:hover { background-color: ${theme.siteVariables?.colorScheme.default.foreground2}; } canvas { border-radius: 3px; transition: box-shadow .05s .1s ease-out; } canvas:focus { outline: none; box-shadow: inset 0 0 0 2px ${theme.siteVariables?.colorScheme.default.foregroundActive}; } ` + customScrollbarStyles} </style> <svg viewBox="0 0 1 1" style={{ position: "absolute", left: "-9999px", top: "-9999px" }} role="none" > <defs> <clipPath id="avatar-clip-path--hex--large" clipPathUnits="objectBoundingBox" > <path d="M0.781177 0.107772L0.989252 0.461033C1.00358 0.485327 1.00358 0.514647 0.989252 0.538941L0.781177 0.892202C0.765728 0.918452 0.735978 0.934783 0.703609 0.934783H0.296347C0.264007 0.934783 0.234257 0.918452 0.218808 0.892202L0.0107039 0.538941C-0.00356796 0.514647 -0.00356796 0.485327 0.0107039 0.461033L0.218808 0.107772C0.234257 0.0815495 0.264007 0.065218 0.296347 0.065218H0.703609C0.735978 0.065218 0.765728 0.0815495 0.781177 0.107772" /> </clipPath> <clipPath id="avatar-clip-path--hex--medium" clipPathUnits="objectBoundingBox" > <path d="M0.781177 0.0990553L0.989252 0.460166C1.00358 0.485 1.00358 0.514972 0.989252 0.539805L0.781177 0.900916C0.765728 0.92775 0.735978 0.944444 0.703609 0.944444H0.296347C0.264007 0.944444 0.234257 0.92775 0.218808 0.900916L0.0107039 0.539805C-0.00356796 0.514972 -0.00356796 0.485 0.0107039 0.460166L0.218808 0.0990553C0.234257 0.0722498 0.264007 0.0555553 0.296347 0.0555553H0.703609C0.735978 0.0555553 0.765728 0.0722498 0.781177 0.0990553" /> </clipPath> <clipPath id="avatar-clip-path--hex--small" clipPathUnits="objectBoundingBox" > <path d="M0.781177 0.10532L0.989252 0.460789C1.00358 0.485234 1.00358 0.514738 0.989252 0.539184L0.781177 0.894652C0.765728 0.921066 0.735978 0.9375 0.703609 0.9375H0.296347C0.264007 0.9375 0.234257 0.921066 0.218808 0.894652L0.0107039 0.539184C-0.00356796 0.514738 -0.00356796 0.485234 0.0107039 0.460789L0.218808 0.10532C0.234257 0.0789336 0.264007 0.0625 0.296347 0.0625H0.703609C0.735978 0.0625 0.765728 0.0789336 0.781177 0.10532Z" /> </clipPath> </defs> </svg> {children} </FluentUIThemeProvider> ); };
the_stack
import { createConnection, TextDocuments, ProposedFeatures, InitializeParams, DidChangeConfigurationNotification, TextDocumentPositionParams, TextDocumentSyncKind, InitializeResult, TextDocumentChangeEvent, RenameParams, DocumentSymbolParams, ExecuteCommandParams, CompletionParams, } from 'vscode-languageserver'; import { CodeActionParams } from 'vscode-languageserver-protocol'; import { TextDocument } from 'vscode-languageserver-textdocument'; // We need to import this to include reflect functionality import 'reflect-metadata'; import { AURELIA_COMMANDS, AURELIA_COMMANDS_KEYS, CodeActionMap, } from './common/constants'; import { Logger } from './common/logging/logger'; import { MyLodash } from './common/MyLodash'; import { UriUtils } from './common/view/uri-utils'; import { AureliaProjects } from './core/AureliaProjects'; import { AureliaServer } from './core/aureliaServer'; import { globalContainer } from './core/container'; import { ExtensionSettings, settingsName, } from './feature/configuration/DocumentSettings'; const logger = new Logger('Server'); // Create a connection for the server. The connection uses Node's IPC as a transport. // Also include all preview / proposed LSP features. export const connection = createConnection(ProposedFeatures.all); // Create a simple text document manager. The text document manager // supports full document sync only const documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument); let hasConfigurationCapability: boolean = false; let hasWorkspaceFolderCapability: boolean = false; // let hasDiagnosticRelatedInformationCapability: boolean = false; let hasServerInitialized = false; let aureliaServer: AureliaServer; connection.onInitialize(async (params: InitializeParams) => { const capabilities = params.capabilities; // Does the client support the `workspace/configuration` request? // If not, we will fall back using global settings hasConfigurationCapability = !!( capabilities.workspace && Boolean(capabilities.workspace.configuration) ); hasWorkspaceFolderCapability = !!( capabilities.workspace && Boolean(capabilities.workspace.workspaceFolders) ); // hasDiagnosticRelatedInformationCapability = Boolean( // capabilities.textDocument?.publishDiagnostics?.relatedInformation // ); const result: InitializeResult = { capabilities: { textDocumentSync: TextDocumentSyncKind.Full, // Tell the client that the server supports code completion completionProvider: { resolveProvider: false, // eslint-disable-next-line @typescript-eslint/quotes triggerCharacters: [' ', '.', '[', '"', "'", '{', '<', ':', '|', '$'], }, definitionProvider: true, // hoverProvider: true, codeActionProvider: true, renameProvider: true, documentSymbolProvider: true, workspaceSymbolProvider: true, executeCommandProvider: { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore commands: AURELIA_COMMANDS, }, }, }; if (hasWorkspaceFolderCapability) { result.capabilities.workspace = { workspaceFolders: { supported: true, }, }; } return result; }); // eslint-disable-next-line @typescript-eslint/no-misused-promises connection.onInitialized(async () => { if (hasConfigurationCapability) { // Register for all configuration changes. void connection.client.register( DidChangeConfigurationNotification.type, undefined ); await initAurelia(); const should = await shouldInit(); if (!should) return; hasServerInitialized = true; } if (hasWorkspaceFolderCapability) { connection.workspace.onDidChangeWorkspaceFolders((_event) => { connection.console.log('Workspace folder change event received.'); }); } }); // connection.onDidOpenTextDocument(() => {}); // Only keep settings for open documents // documents.onDidClose((e) => { // documentSettings.settingsMap.delete(e.document.uri); // }); connection.onCodeAction(async (codeActionParams: CodeActionParams) => { if (hasServerInitialized === false) return; const codeAction = await aureliaServer.onCodeAction(codeActionParams); if (codeAction) { return codeAction; } }); connection.onCompletion(async (completionParams: CompletionParams) => { const documentUri = completionParams.textDocument.uri; const document = documents.get(documentUri); if (!document) { throw new Error('No document found'); } const completions = await aureliaServer.onCompletion( document, completionParams ); if (completions != null) { return completions; } }); // This handler resolves additional information for the item selected in // the completion list. // connection.onCompletionResolve( // (item: CompletionItem): CompletionItem => { // return item; // } // ); connection.onDefinition( async ({ position, textDocument }: TextDocumentPositionParams) => { const documentUri = textDocument.uri.toString(); const document = documents.get(documentUri); // < if (!document) return null; const definition = await aureliaServer.onDefinition(document, position); if (definition) { return definition; } return null; } ); // The content of a text document has changed. This event is emitted // when the text document first opened or when its content has changed. documents.onDidChangeContent( MyLodash.debouncePromise( async (change: TextDocumentChangeEvent<TextDocument>) => { if (!hasServerInitialized) return; // const diagnosticsParams = await aureliaServer.sendDiagnostics( // change.document // ); // connection.sendDiagnostics(diagnosticsParams); await aureliaServer.onConnectionDidChangeContent(change); }, 400 ) ); connection.onDidChangeConfiguration(async () => { console.log('[server.ts] onDidChangeConfiguration'); if (!hasConfigurationCapability) return; await initAurelia(true); }); connection.onDidChangeWatchedFiles((_change) => { // Monitored files have change in VSCode connection.console.log('We received an file change event'); }); documents.onDidSave(async (change: TextDocumentChangeEvent<TextDocument>) => { await aureliaServer.onDidSave(change); }); connection.onDocumentSymbol(async (params: DocumentSymbolParams) => { if (hasServerInitialized === false) return; const symbols = await aureliaServer.onDocumentSymbol(params.textDocument.uri); return symbols; }); // connection.onWorkspaceSymbol(async (params: WorkspaceSymbolParams) => { connection.onWorkspaceSymbol(async () => { if (hasServerInitialized === false) return; // const workspaceSymbols = aureliaServer.onWorkspaceSymbol(params.query); try { const workspaceSymbols = aureliaServer.onWorkspaceSymbol(); return workspaceSymbols; } catch (error) { error; /* ? */ } }); // connection.onHover( // async ({ position, textDocument }: TextDocumentPositionParams) => { // const documentUri = textDocument.uri.toString(); // const document = documents.get(documentUri); // < // if (!document) return null; // const hovered = await aureliaServer.onHover( // document.getText(), // position, // documentUri, // ); // return hovered; // } // ); connection.onExecuteCommand( async (executeCommandParams: ExecuteCommandParams) => { const command = executeCommandParams.command as AURELIA_COMMANDS_KEYS; switch (command) { case 'extension.au.reloadExtension': { await initAurelia(true); break; } case CodeActionMap['refactor.aTag'].command: { logger.log( `Command executed: "${CodeActionMap['refactor.aTag'].title}"` ); break; } default: { // console.log('no command'); } } // async () => { return null; } ); connection.onRenameRequest( async ({ position, textDocument, newName }: RenameParams) => { const documentUri = textDocument.uri; const document = documents.get(documentUri); if (!document) { throw new Error('No document found'); } const renamed = await aureliaServer.onRenameRequest( document, position, newName ); if (renamed) { return renamed; } } ); // connection.onPrepareRename(async (prepareRename: PrepareRenameParams) => { // /* prettier-ignore */ console.log('TCL: prepareRename', prepareRename); // return new ResponseError(0, 'failed'); // }); connection.onRequest('aurelia-get-component-list', () => { const aureliaProjects = globalContainer.get(AureliaProjects); // TODO: use .getBy instead of getAll const { aureliaProgram } = aureliaProjects.getAll()[0]; if (!aureliaProgram) return; return aureliaProgram.aureliaComponents.getAll().map((cList) => { const { componentName, className, viewFilePath, viewModelFilePath, baseViewModelFileName, } = cList; return { componentName, className, viewFilePath, viewModelFilePath, baseViewModelFileName, }; }); }); // Make the text document manager listen on the connection // for open, change and close text document events documents.listen(connection); // Listen on the connection connection.listen(); async function initAurelia(forceReinit?: boolean) { const extensionSettings = (await connection.workspace.getConfiguration({ section: settingsName, })) as ExtensionSettings; const rootDirectory = await getRootDirectory(extensionSettings); extensionSettings.aureliaProject = { ...extensionSettings.aureliaProject, rootDirectory, }; aureliaServer = new AureliaServer( globalContainer, extensionSettings, documents ); await aureliaServer.onConnectionInitialized(extensionSettings, forceReinit); } async function getRootDirectory(extensionSettings: ExtensionSettings) { const workspaceFolders = await connection.workspace.getWorkspaceFolders(); if (workspaceFolders === null) return; const workspaceRootUri = workspaceFolders[0].uri; let rootDirectory = workspaceRootUri; const settingRoot = extensionSettings.aureliaProject?.rootDirectory; if (settingRoot != null && settingRoot !== '') { rootDirectory = settingRoot; } return rootDirectory; } async function shouldInit() { const workspaceFolders = await connection.workspace.getWorkspaceFolders(); if (workspaceFolders === null) return false; const workspaceRootUri = workspaceFolders[0].uri; const tsConfigPath = UriUtils.toSysPath(workspaceRootUri); const aureliaProjects = globalContainer.get(AureliaProjects); const targetProject = aureliaProjects.getBy(tsConfigPath); if (!targetProject) return false; return true; }
the_stack
import { LogLevel } from './../../chat21-core/utils/constants'; import { ElementRef, Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { Http, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; // services import { Globals } from '../utils/globals'; import { getImageUrlThumb, stringToBoolean, convertColorToRGBA, getParameterByName, stringToNumber } from '../utils/utils'; import { TemplateBindingParseResult } from '@angular/compiler'; import { AppConfigService } from './app-config.service'; import { __core_private_testing_placeholder__ } from '@angular/core/testing'; import { ProjectModel } from '../../models/project'; import { AppStorageService } from '../../chat21-core/providers/abstract/app-storage.service'; import { LoggerService } from '../../chat21-core/providers/abstract/logger.service'; import { LoggerInstance } from '../../chat21-core/providers/logger/loggerInstance'; import { invertColor, isJsonString } from '../../chat21-core/utils/utils'; @Injectable() export class GlobalSettingsService { globals: Globals; el: ElementRef; obsSettingsService: BehaviorSubject<boolean>; private logger: LoggerService = LoggerInstance.getInstance() constructor( public http: Http, private appStorageService: AppStorageService, // private settingsService: SettingsService, public appConfigService: AppConfigService ) { this.obsSettingsService = new BehaviorSubject<boolean>(null); } /** * load paramiters * 0 - imposto globals con i valori di default * 1 - imposto il projectId * 2 - recupero i parametri principali dal settings: projectid, persistence, userToken, userId, filterByRequester * 3 - recupero i parametri dal server * 4 - attendo la risposta del server e richiamo setParameters per il settaggio dei parametri */ initWidgetParamiters(globals: Globals, el: ElementRef) { const that = this; this.globals = globals; this.el = el; // ------------------------------- // /** * SETTING LOCAL DEFAULT: * set the default globals parameters */ this.globals.initDefafultParameters(); /** SET PROJECT ID */ let projectid: string; try { projectid = this.setProjectId(); } catch (error) { this.logger.error('[GLOBAL-SET] > Error :' + error); return; } /** SET main Paramiters */ this.setMainParametersFromSettings(globals); /**SET TENANT parameter */ this.globals.tenant = this.appConfigService.getConfig().firebaseConfig.tenant /**SET LOGLEVEL parameter */ this.globals.logLevel = this.appConfigService.getConfig().logLevel /**SET PERSISTENCE parameter */ this.globals.persistence = this.appConfigService.getConfig().authPersistence // ------------------------------- // /** LOAD PARAMETERS FROM SERVER * load parameters from server * set parameters in globals */ // const projectid = globals.projectid; this.getProjectParametersById(projectid).subscribe( response => { const project = response['project']; // console.log('1 - setParameters ', project); if (project) { that.globals.project.initialize( project['id'], project['activeOperatingHours'], project['channels'], project['name'], project['createdAt'], project['createdBy'], project['isActiveSubscription'], project['profile'], project['agents'], project['trialDays'], project['type'], project['status'], project['trialDaysLeft'], project['trialExpired'], project['updatedAt'], project['versions'] ); } // console.log('globals.project ----------------->', that.globals.project); that.setParameters(response); }, (error) => { // console.log('2 - ::getProjectParametersById', error); that.setParameters(null); }, () => { // console.log('3 - setParameters '); // that.setParameters(null); }); } /** SET PROGECTID ** * set projectId with the following order: * 1 - get projectId from settings * 2 - get projectId from attributeHtml * 3 - get projectId from UrlParameters */ setProjectId() { // get projectid for settings// try { const projectid = this.globals.windowContext['tiledeskSettings']['projectid']; if (projectid) { this.globals.projectid = projectid; } // this.globals.setParameter('projectid', projectid); } catch (error) { this.logger.error('[GLOBAL-SET] setProjectId 1 > Error :' + error); } // get projectid for attributeHtml// try { const projectid = this.el.nativeElement.getAttribute('projectid'); if (projectid) { this.globals.projectid = projectid; } // this.globals.setParameter('projectid', projectid); } catch (error) { this.logger.error('[GLOBAL-SET] setProjectId 2 > Error :' + error); } // get projectid for UrlParameters// try { const projectid = getParameterByName(this.globals.windowContext, 'tiledesk_projectid'); if (projectid) { this.globals.projectid = projectid; } // this.globals.setParameter('projectid', projectid); } catch (error) { this.logger.error('[GLOBAL-SET] setProjectId 3 > Error :' + error); } // this.logger.debug('[GLOBAL-SET] setProjectId projectid: ', this.globals.projectid); return this.globals.projectid; } /** * 1: get Project Id From Settings * recupero i parametri principali dal settings: * projectid * persistence * filterByRequester * userToken * userId * ... */ // https://www.davidbcalhoun.com/2011/checking-for-undefined-null-and-empty-variables-in-javascript/ setMainParametersFromSettings(globals: Globals) { let tiledeskSettings: any; try { const baseLocation = this.globals.windowContext['tiledesk'].getBaseLocation(); this.logger.debug('[GLOBAL-SET] 1 > baseLocation: ', baseLocation); if (typeof baseLocation !== 'undefined') { this.globals.baseLocation = baseLocation; } } catch (error) { this.logger.error('[GLOBAL-SET] setMainParametersFromSettings baseLocation > Error :', error); } try { tiledeskSettings = this.globals.windowContext['tiledeskSettings']; } catch (error) { this.logger.error('[GLOBAL-SET] setMainParametersFromSettings tiledeskSettings > Error :', error); } try { const persistence = tiledeskSettings['persistence']; if (typeof persistence !== 'undefined') { this.globals.persistence = persistence; } } catch (error) { this.logger.error('[GLOBAL-SET] setMainParametersFromSettings persistence > Error :', error); } // try { // const userToken = tiledeskSettings['userToken']; // if (typeof userToken !== 'undefined') { this.globals.userToken = userToken; } // } catch (error) { // this.logger.error('[GLOBAL-SET] setMainParametersFromSettings userToken > Error :', error); // } // try { // const userId = tiledeskSettings['userId']; // if (typeof userId !== 'undefined') { this.globals.userId = userId; } // } catch (error) { // this.logger.error('[GLOBAL-SET] setMainParametersFromSettings userId > Error :', error); // } try { const filterByRequester = tiledeskSettings['filterByRequester']; this.logger.debug('[GLOBAL-SET] setMainParametersFromSettings > filterByRequester: ', filterByRequester); if (typeof filterByRequester !== 'undefined') { this.globals.filterByRequester = (filterByRequester === true) ? true : false; } } catch (error) { this.logger.error('[GLOBAL-SET] setMainParametersFromSettings filterByRequester > Error :', error); } try { const isLogEnabled = tiledeskSettings['isLogEnabled']; if (typeof isLogEnabled !== 'undefined') { this.globals.isLogEnabled = (isLogEnabled === true) ? true : false; } } catch (error) { this.logger.error('[GLOBAL-SET] setMainParametersFromSettings isLogEnabled > Error :', error); } try { const departmentID = tiledeskSettings['departmentID']; if (typeof departmentID !== 'undefined') { this.globals.departmentID = departmentID; } } catch (error) { this.logger.error('[GLOBAL-SET] setMainParametersFromSettings departmentID > Error :', error); } try { const showAttachmentButton = tiledeskSettings['showAttachmentButton']; // tslint:disable-next-line:max-line-length if (typeof showAttachmentButton !== 'undefined') { this.globals.showAttachmentButton = (showAttachmentButton === true) ? true : false; } } catch (error) { this.logger.error('[GLOBAL-SET] setMainParametersFromSettings showAttachmentButton > Error :', error); } try { const showAllConversations = tiledeskSettings['showAllConversations']; // tslint:disable-next-line:max-line-length if (typeof showAllConversations !== 'undefined') { this.globals.showAllConversations = (showAllConversations === true) ? true : false; } } catch (error) { this.logger.error('[GLOBAL-SET] setMainParametersFromSettings showAllConversations > Error :', error); } // try { // const privacyField = tiledeskSettings['privacyField']; // if (typeof privacyField !== 'undefined') { this.globals.privacyField = privacyField; } // } catch (error) { // this.logger.error('[GLOBAL-SET] setMainParametersFromSettings privacyField > Error :', error); // } // -------------------------------------- // // const windowContext = globals.windowContext; // if (!windowContext['tiledesk']) { // // mi trovo in una pg index senza iframe // return; // } else { // // mi trovo in una pg con iframe // const baseLocation = windowContext['tiledesk'].getBaseLocation(); // if (baseLocation !== undefined) { // globals.baseLocation = baseLocation; // } // } // let TEMP: any; // const tiledeskSettings = windowContext['tiledeskSettings']; // TEMP = tiledeskSettings['projectid']; // if (TEMP !== undefined) { // globals.projectid = TEMP; // } // TEMP = tiledeskSettings['persistence']; // // this.logger.debug('[GLOBAL-SET] setMainParametersFromSettings - persistence:: ', TEMP); // if (TEMP !== undefined) { // globals.persistence = TEMP; // // globals.setParameter('persistence', TEMP); // } // TEMP = tiledeskSettings['userToken']; // // this.logger.debug('[GLOBAL-SET] setMainParametersFromSettings - userToken:: ', TEMP); // if (TEMP !== undefined) { // globals.userToken = TEMP; // // globals.setParameter('userToken', TEMP); // } // TEMP = tiledeskSettings['userId']; // // this.logger.debug('[GLOBAL-SET] setMainParametersFromSettings - userId:: ', TEMP); // if (TEMP !== undefined) { // globals.userId = TEMP; // // globals.setParameter('userId', TEMP); // } // TEMP = tiledeskSettings['filterByRequester']; // // this.logger.debug('[GLOBAL-SET] setMainParametersFromSettings - filterByRequester:: ', TEMP); // if (TEMP !== undefined) { // globals.filterByRequester = (TEMP === false) ? false : true; // // globals.setParameter('filterByRequester', (TEMP === false) ? false : true); // } // TEMP = tiledeskSettings['isLogEnabled']; // // this.logger.debug('[GLOBAL-SET] setMainParametersFromSettings - isLogEnabled:: ', TEMP); // if (TEMP !== undefined) { // globals.isLogEnabled = (TEMP === false) ? false : true; // // globals.setParameter('isLogEnabled', (TEMP === false) ? false : true); // } } /** * */ // setProjectIdAndPrimaryParametersFromEl(el: ElementRef, globals: Globals) { // // https://stackoverflow.com/questions/45732346/externally-pass-values-to-an-angular-application // let TEMP: any; // TEMP = el.nativeElement.getAttribute('projectid'); // if (TEMP !== null) { // globals.projectid = TEMP; // } // } /** * 2: getProjectParametersByIdFromServer * recupero i parametri dal server */ // getProjectParametersById(globals: Globals, el: ElementRef) { // const that = this; // return new Promise((res, rej) => { // const id = globals.projectid; // this.settingsService.getProjectParametersById(id) // .subscribe(response => { // res(response); // }, // errMsg => { // that.logger.error('[GLOBAL-SET] getProjectParametersById --> http ERROR MESSAGE', errMsg); // rej(errMsg); // }, // () => { // that.logger.debug('[GLOBAL-SET] getProjectParametersById --> API ERROR NESSUNO'); // rej('NULL'); // }); // }); // } /** * 3: setParameters * imposto i parametri secondo il seguente ordine: * A: se il server ha restituito dei parametri imposto i parametri in global * B: imposto i parametri recuperati da settings in global * C: imposto i parametri recuperati da attributes html in global * D: imposto i parametri recuperati da url parameters in global * E: imposto i parametri recuperati dallo storage in global */ setParameters(response: any ) { this.logger.debug('[GLOBAL-SET] ***** setParameters ***** ', response) if (response !== null) { this.setVariablesFromService(this.globals, response); } this.setVariableFromStorage(this.globals); this.setVariablesFromSettings(this.globals); this.setVariablesFromAttributeHtml(this.globals, this.el); this.setVariablesFromUrlParameters(this.globals); this.setDepartmentFromExternal(); /** set color with gradient from theme's colors */ this.globals.setColorWithGradient(); /** set css iframe from parameters */ this.setCssIframe(); this.logger.debug('[GLOBAL-SET] ***** END SET PARAMETERS *****'); this.obsSettingsService.next(true); } /** * */ setCssIframe() { // tslint:disable-next-line:max-line-length // this.logger.debug('[GLOBAL-SET] ***** setCssIframe *****', this.globals.windowContext.document.getElementById('tiledeskdiv')); const divTiledeskiframe = this.globals.windowContext.document.getElementById('tiledeskdiv'); if (!divTiledeskiframe) { return; } if (this.globals.align === 'left') { divTiledeskiframe.classList.add('align-left'); divTiledeskiframe.style.left = this.globals.marginX; } else { divTiledeskiframe.classList.add('align-right'); divTiledeskiframe.style.right = this.globals.marginX; } if (this.globals.isMobile === false) { divTiledeskiframe.style.bottom = this.globals.marginY; } else { divTiledeskiframe.style.bottom = '0px'; } // console.log('this.globals.fullscreenMode' + this.globals.fullscreenMode); if (this.globals.fullscreenMode === true) { divTiledeskiframe.style.left = 0; divTiledeskiframe.style.right = 0; divTiledeskiframe.style.top = 0; divTiledeskiframe.style.bottom = 0; divTiledeskiframe.style.width = '100%'; divTiledeskiframe.style.height = '100%'; divTiledeskiframe.style.maxHeight = 'none'; divTiledeskiframe.style.maxWidth = 'none'; } } /** * A: setVariablesFromService */ setVariablesFromService(globals: Globals, response: any) { this.logger.debug('[GLOBAL-SET] > setVariablesFromService :' , response); this.globals = globals; // DEPARTMENTS try { const departments = response.departments; // console.log('---->departments', response.departments); if (typeof departments !== 'undefined') { // globals.setParameter('departments', response.departments); this.initDepartments(departments); } } catch (error) { this.initDepartments(null); this.logger.error('[GLOBAL-SET] setVariablesFromService > Error is departments: ', error); } // DEPARTMENTS // if (response && response.departments !== null) { // this.logger.debug('[GLOBAL-SET] response DEP ::::', response.departments); // // globals.setParameter('departments', response.departments); // this.initDepartments(response.departments); // } // AVAILABLE AGENTS try { const user_available = response.user_available; if (typeof user_available !== 'undefined') { this.logger.debug('[GLOBAL-SET] setVariablesFromService > user_available ::::', user_available); this.setAvailableAgentsStatus(user_available); } } catch (error) { this.setAvailableAgentsStatus(null); this.logger.error('[GLOBAL-SET] setVariablesFromService > Error is departments: ', error); } // AVAILABLE AGENTS // if (response && response.user_available !== null) { // //this.logger.error('[GLOBAL-SET] setVariablesFromService > user_available ::::', response.user_available); // this.setAvailableAgentsStatus(response.user_available); // } // WIDGET try { const variables = response.project.widget; if (typeof variables !== 'undefined') { for (const key of Object.keys(variables)) { if (key === 'align' && variables[key] === 'left') { const divWidgetContainer = globals.windowContext.document.getElementById('tiledeskdiv'); divWidgetContainer.style.left = '0!important'; globals['align']= 'left' } else if (key === 'align' && variables[key] === 'right') { const divWidgetContainer = globals.windowContext.document.getElementById('tiledeskdiv'); divWidgetContainer.style.right = '0!important'; globals['align']= 'right' } // if (variables[key] && variables[key] !== null && key !== 'online_msg') { // globals[key] = stringToBoolean(variables[key]); //-> fare test perchè se param è !== string allora ritorna string e non boolean // } if (variables.hasOwnProperty('calloutTimer')) { globals['calloutTimer'] = variables['calloutTimer']; } if (variables.hasOwnProperty('dynamicWaitTimeReply')) { globals['dynamicWaitTimeReply'] = variables['dynamicWaitTimeReply']; } if (variables.hasOwnProperty('logoChat')) { globals['logoChat'] = variables['logoChat']; } if (variables.hasOwnProperty('preChatForm')) { globals['preChatForm'] = variables['preChatForm']; } if (variables.hasOwnProperty('preChatFormCustomFieldsEnabled')) { if(variables.hasOwnProperty('preChatFormJson')) globals['preChatFormJson'] = variables['preChatFormJson']; } if (variables.hasOwnProperty('themeColor')) { globals['themeColor'] = variables['themeColor']; globals['bubbleSentBackground']=variables['themeColor']; globals['bubbleSentTextColor']= invertColor(variables['themeColor'], true); globals['buttonBackgroundColor']= invertColor(variables['themeColor'], true); globals['buttonTextColor'] = variables['themeColor']; globals['buttonHoverTextColor'] = invertColor(variables['themeColor'], true); globals['buttonHoverBackgroundColor'] = variables['themeColor']; } if (variables.hasOwnProperty('themeForegroundColor')) { // globals[key] = stringToBoolean(variables[key]); -> fare test perchè se param è !== string allora ritorna string e non boolean globals['themeForegroundColor'] = variables['themeForegroundColor']; // globals['bubbleMsgSentTextColor'] = variables['themeForegroundColor']; } if (variables.hasOwnProperty('nativeRating')) { globals['nativeRating'] = variables['nativeRating']; } } } } catch (error) { this.logger.error('[GLOBAL-SET] setVariablesFromService widget > Error :', error); } // IP try { const strIp = response['ip']; const IP = strIp.split(',').shift(); if ( !this.globals.attributes ) { this.globals.attributes = {}; } this.globals.attributes['ipAddress'] = IP; this.globals.setAttributeParameter('ipAddress', IP); this.logger.debug('[GLOBAL-SET] setVariablesFromService > ipAddress :', IP); // console.log('this.globals.attributes.IP ----------------->', this.globals.attributes); } catch (error) { this.logger.error('[GLOBAL-SET] setVariablesFromService > ipAddress > Error :', error); } // if (response && response.project && response.project.widget !== null) { // this.logger.debug('[GLOBAL-SET] setVariablesFromService response.widget: ', response.project.widget); // const variables = response.project.widget; // if (!variables || variables === undefined) { // return; // } // for (const key of Object.keys(variables)) { // // this.logger.debug('[GLOBAL-SET] setVariablesFromService SET globals from service KEY ---------->', key); // // this.logger.debug('[GLOBAL-SET] setVariablesFromService SET globals from service VAL ---------->', variables[key]); // // sposto l'intero frame a sx se align è = left // if (key === 'align' && variables[key] === 'left') { // const divWidgetContainer = globals.windowContext.document.getElementById('tiledeskiframe'); // divWidgetContainer.style.left = '0'; // } // if (variables[key] && variables[key] !== null) { // globals[key] = stringToBoolean(variables[key]); // } // } // // this.logger.error('[GLOBAL-SET] setVariablesFromService SET globals == ---------->', globals); // } } /** * B: getVariablesFromSettings */ setVariablesFromSettings(globals: Globals) { // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings'); const windowContext = globals.windowContext; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings windowContext', globals.windowContext); if (!windowContext['tiledesk']) { return; } else { const baseLocation = windowContext['tiledesk'].getBaseLocation(); if (baseLocation !== undefined) { // globals.setParameter('baseLocation', baseLocation); globals.baseLocation = baseLocation; } } let TEMP: any; const tiledeskSettings = windowContext['tiledeskSettings']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > tiledeskSettings: ', tiledeskSettings); TEMP = tiledeskSettings['tenant']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > tenant:: ', TEMP); if (TEMP !== undefined) { globals.tenant = TEMP; // globals.setParameter('tenant', TEMP); } TEMP = tiledeskSettings['recipientId']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > recipientId:: ', TEMP); if (TEMP !== undefined) { globals.recipientId = TEMP; // globals.setParameter('recipientId', TEMP); } TEMP = tiledeskSettings['widgetTitle']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > widgetTitle:: ', TEMP); if (TEMP !== undefined) { globals.widgetTitle = TEMP; // globals.setParameter('widgetTitle', TEMP); } TEMP = tiledeskSettings['poweredBy']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > poweredBy:: ', TEMP); if (TEMP !== undefined) { globals.poweredBy = TEMP; // globals.setParameter('poweredBy', TEMP); } TEMP = tiledeskSettings['userEmail']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > userEmail:: ', TEMP); if (TEMP !== undefined) { globals.userEmail = TEMP; // globals.setParameter('userEmail', TEMP); } TEMP = tiledeskSettings['userFullname']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > userFullname:: ', TEMP); if (TEMP !== undefined) { globals.userFullname = TEMP; // globals.setParameter('userFullname', TEMP); } TEMP = tiledeskSettings['preChatForm']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > preChatForm:: ', TEMP]); if (TEMP !== undefined) { globals.preChatForm = (TEMP === true) ? true : false; // globals.setParameter('preChatForm', (TEMP === false) ? false : true); } TEMP = tiledeskSettings['isOpen']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > isOpen:: ', TEMP); if (TEMP !== undefined) { globals.isOpen = (TEMP === true) ? true : false; // globals.setParameter('isOpen', (TEMP === false) ? false : true); } TEMP = tiledeskSettings['channelType']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > channelType:: ', TEMP); if (TEMP !== undefined) { globals.channelType = TEMP; // globals.setParameter('channelType', TEMP); } TEMP = tiledeskSettings['lang']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > lang:: ', TEMP); if (TemplateBindingParseResult) { globals.lang = TEMP; // globals.setParameter('lang', TEMP); } TEMP = tiledeskSettings['align']; if (TEMP !== undefined) { globals.align = TEMP; const divWidgetContainer = windowContext.document.getElementById('tiledeskdiv'); if (globals.align === 'left') { divWidgetContainer.classList.add('align-left'); } else { divWidgetContainer.classList.add('align-right'); } } TEMP = tiledeskSettings['marginX']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > marginX:: ', TEMP); if (TEMP !== undefined) { globals.marginX = TEMP; // globals.setParameter('marginX', TEMP); } TEMP = tiledeskSettings['marginY']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > marginY:: ', TEMP); if (TEMP !== undefined) { globals.marginY = TEMP; // globals.setParameter('marginY', TEMP); } TEMP = tiledeskSettings['launcherWidth']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > launcherWidth:: ', TEMP); if (TEMP !== undefined) { globals.launcherWidth = TEMP; // globals.setParameter('launcherWidth', TEMP); } TEMP = tiledeskSettings['launcherHeight']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > launcherHeight:: ', TEMP); if (TEMP !== undefined) { globals.launcherHeight = TEMP; // globals.setParameter('launcherHeight', TEMP); } TEMP = tiledeskSettings['baloonImage']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > baloonImage:: ', TEMP); if (TEMP !== undefined) { globals.baloonImage = TEMP; // globals.setParameter('baloonImage', TEMP); } TEMP = tiledeskSettings['baloonShape']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > baloonShape:: ', TEMP); if (TEMP !== undefined) { globals.baloonShape = TEMP; // globals.setParameter('baloonShape', TEMP); } TEMP = tiledeskSettings['calloutTimer']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > calloutTimer:: ', TEMP); if (TEMP !== undefined) { globals.calloutTimer = TEMP; // globals.setParameter('calloutTimer', TEMP); } TEMP = tiledeskSettings['calloutTitle']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > calloutTitle:: ', TEMP); if (TEMP !== undefined) { globals.calloutTitle = TEMP; // globals.setParameter('calloutTitle', TEMP); } TEMP = tiledeskSettings['calloutMsg']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > calloutMsg:: ', TEMP); if (TEMP !== undefined) { globals.calloutMsg = TEMP; // globals.setParameter('calloutMsg', TEMP); } TEMP = tiledeskSettings['fullscreenMode']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > fullscreenMode:: ', TEMP); if (TEMP !== undefined) { globals.fullscreenMode = TEMP; // globals.setParameter('fullscreenMode', TEMP); } TEMP = tiledeskSettings['hideHeaderCloseButton']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > hideHeaderCloseButton:: ', TEMP); if (TEMP !== undefined) { globals.hideHeaderCloseButton = TEMP; // globals.setParameter('hideHeaderCloseButton', TEMP); } TEMP = tiledeskSettings['themeColor']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > themeColor:: ', TEMP); if (TEMP !== undefined) { globals.themeColor = convertColorToRGBA(TEMP, 100); globals.bubbleSentBackground = convertColorToRGBA(TEMP, 100); globals.bubbleSentTextColor = invertColor(TEMP, true) globals.buttonBackgroundColor = invertColor(TEMP, true); globals.buttonTextColor = convertColorToRGBA(TEMP, 100); globals.buttonHoverBackgroundColor = convertColorToRGBA(TEMP, 100); globals.buttonHoverTextColor = invertColor(TEMP, true); // globals.setParameter('themeColor', convertColorToRGBA(TEMP, 100)); } TEMP = tiledeskSettings['themeForegroundColor']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > themeForegroundColor:: ', TEMP); if (TEMP !== undefined) { globals.themeForegroundColor = convertColorToRGBA(TEMP, 100); // globals.bubbleMsgSentTextColor = convertColorToRGBA(TEMP, 100); // globals.setParameter('themeForegroundColor', convertColorToRGBA(TEMP, 100)); } TEMP = tiledeskSettings['allowTranscriptDownload']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > allowTranscriptDownload:: ', TEMP); if (TEMP !== undefined) { globals.allowTranscriptDownload = (TEMP === true) ? true : false; // globals.setParameter('allowTranscriptDownload', TEMP); } TEMP = tiledeskSettings['startFromHome']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > startFromHome:: ', TEMP); if (TEMP !== undefined) { globals.startFromHome = (TEMP === true) ? true : false; // globals.setParameter('startFromHome', (TEMP === false) ? false : true); } TEMP = tiledeskSettings['logoChat']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > logoChat:: ', TEMP); if (TEMP !== undefined) { globals.logoChat = TEMP; // globals.setParameter('logoChat', TEMP); } TEMP = tiledeskSettings['welcomeTitle']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > welcomeTitle:: ', TEMP); if (TEMP !== undefined) { globals.welcomeTitle = TEMP; // globals.setParameter('welcomeTitle', TEMP); } TEMP = tiledeskSettings['welcomeMsg']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > welcomeMsg:: ', TEMP); if (TEMP !== undefined) { globals.welcomeMsg = TEMP; // globals.setParameter('welcomeMsg', TEMP); } TEMP = tiledeskSettings['autoStart']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > autoStart:: ', TEMP); if (TEMP !== undefined) { globals.autoStart = (TEMP === true) ? true : false; // globals.setParameter('autoStart', (TEMP === false) ? false : true); } TEMP = tiledeskSettings['startHidden']; if (TEMP !== undefined) { globals.startHidden = (TEMP === true) ? true : false; } TEMP = tiledeskSettings['isShown']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > isShown:: ', TEMP); if (TEMP !== undefined) { globals.isShown = (TEMP === true) ? true : false; // globals.setParameter('isShown', (TEMP === false) ? false : true); } TEMP = tiledeskSettings['filterByRequester']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > filterByRequester:: ', TEMP); if (TEMP !== undefined) { globals.filterByRequester = (TEMP === true) ? true : false; // globals.setParameter('filterByRequester', (TEMP === false) ? false : true); } TEMP = tiledeskSettings['showWaitTime']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > showWaitTime:: ', TEMP); if (TEMP !== undefined) { globals.showWaitTime = (TEMP === true) ? true : false; // globals.setParameter('showWaitTime', (TEMP === false) ? false : true); } TEMP = tiledeskSettings['showAvailableAgents']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > showAvailableAgents:: ', TEMP); if (TEMP !== undefined) { globals.showAvailableAgents = (TEMP === true) ? true : false; // globals.setParameter('showAvailableAgents', (TEMP === false) ? false : true); } TEMP = tiledeskSettings['showLogoutOption']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > showLogoutOption:: ', TEMP); if (TEMP !== undefined) { globals.showLogoutOption = (TEMP === true) ? true : false; // globals.setParameter('showLogoutOption', (TEMP === false) ? false : true); } TEMP = tiledeskSettings['customAttributes']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > customAttributes:: ', TEMP]); if (TEMP !== undefined) { globals.customAttributes = TEMP; } TEMP = tiledeskSettings['showAttachmentButton']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > showAttachmentButton:: ', TEMP]); if (TEMP !== undefined) { globals.showAttachmentButton = (TEMP === true) ? true : false; } TEMP = tiledeskSettings['showAllConversations']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > showAllConversations:: ', TEMP]); if (TEMP !== undefined) { globals.showAllConversations = (TEMP === true) ? true : false; } // TEMP = tiledeskSettings['privacyField']; // // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > privacyField:: ', TEMP]); // if (TEMP !== undefined) { // globals.privacyField = TEMP; // } TEMP = tiledeskSettings['dynamicWaitTimeReply']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > dynamicWaitTimeReply:: ', TEMP]); if (TEMP !== undefined) { globals.dynamicWaitTimeReply = TEMP; } TEMP = tiledeskSettings['soundEnabled']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > soundEnabled:: ', TEMP]); if (TEMP !== undefined) { globals.soundEnabled = TEMP; } TEMP = tiledeskSettings['openExternalLinkButton']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > openExternalLinkButton:: ', TEMP]); if (TEMP !== undefined) { globals.openExternalLinkButton = TEMP; } TEMP = tiledeskSettings['hideHeaderConversationOptionsMenu']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > hideHeaderConversationOptionsMenu:: ', TEMP]); if (TEMP !== undefined) { globals.hideHeaderConversationOptionsMenu = TEMP; } TEMP = tiledeskSettings['hideSettings']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > hideSettings:: ', TEMP]); if (TEMP !== undefined) { globals.hideSettings = TEMP; } TEMP = tiledeskSettings['logLevel']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > logLevel:: ', TEMP]); if (TEMP !== undefined) { globals.logLevel = TEMP; } TEMP = tiledeskSettings['preChatFormJson']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > preChatFormJson:: ', TEMP]); if (TEMP !== undefined) { if(isJsonString(TEMP)){ globals.preChatFormJson = TEMP; } } TEMP = tiledeskSettings['bubbleSentBackground']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > bubbleSentBackground:: ', TEMP); if (TEMP !== undefined) { globals.bubbleSentBackground = convertColorToRGBA(TEMP, 100); globals.bubbleSentTextColor = invertColor(TEMP, true); globals.buttonBackgroundColor= invertColor(TEMP, true); globals.buttonTextColor = convertColorToRGBA(TEMP, 100); globals.buttonHoverBackgroundColor = convertColorToRGBA(TEMP, 100); globals.buttonHoverTextColor = invertColor(TEMP, true); } TEMP = tiledeskSettings['bubbleSentTextColor']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > bubbleSentTextColor:: ', TEMP]); if (TEMP !== undefined) { globals.bubbleSentTextColor = convertColorToRGBA(TEMP, 100); } TEMP = tiledeskSettings['bubbleReceivedBackground']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > bubbleReceivedBackground:: ', TEMP); if (TEMP !== undefined) { globals.bubbleReceivedBackground = convertColorToRGBA(TEMP, 100); globals.bubbleReceivedTextColor = invertColor(TEMP, true) } TEMP = tiledeskSettings['bubbleReceivedTextColor']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > bubbleReceivedTextColor:: ', TEMP]); if (TEMP !== undefined) { globals.bubbleReceivedTextColor = convertColorToRGBA(TEMP, 100); } TEMP = tiledeskSettings['fontSize']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > fontSize:: ', TEMP]); if (TEMP !== undefined) { globals.fontSize = TEMP; } TEMP = tiledeskSettings['fontFamily']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > fontFamily:: ', TEMP]); if (TEMP !== undefined) { globals.fontFamily = TEMP; } TEMP = tiledeskSettings['buttonFontSize']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > buttonFontSize:: ', TEMP]); if (TEMP !== undefined) { globals.buttonFontSize = TEMP; } TEMP = tiledeskSettings['buttonBackgroundColor']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > buttonBackgroundColor:: ', TEMP]); if (TEMP !== undefined) { globals.buttonBackgroundColor = convertColorToRGBA(TEMP, 100); globals.buttonTextColor = invertColor(TEMP, true); globals.buttonHoverBackgroundColor = invertColor(TEMP, true); globals.buttonHoverTextColor = convertColorToRGBA(TEMP, 100); } TEMP = tiledeskSettings['buttonTextColor']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > buttonTextColor:: ', TEMP]); if (TEMP !== undefined) { globals.buttonTextColor = convertColorToRGBA(TEMP, 100); globals.buttonHoverBackgroundColor = convertColorToRGBA(TEMP, 100); } TEMP = tiledeskSettings['buttonHoverBackgroundColor']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > buttonHoverBackgroundColor:: ', TEMP]); if (TEMP !== undefined) { globals.buttonHoverBackgroundColor = convertColorToRGBA(TEMP, 100); } TEMP = tiledeskSettings['buttonHoverTextColor']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > buttonHoverTextColor:: ', TEMP]); if (TEMP !== undefined) { globals.buttonHoverTextColor = convertColorToRGBA(TEMP, 100); } TEMP = tiledeskSettings['singleConversation']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > singleConversation:: ', TEMP]); if (TEMP !== undefined) { globals.singleConversation = (TEMP === true) ? true : false;; } TEMP = tiledeskSettings['nativeRating']; // this.logger.debug('[GLOBAL-SET] setVariablesFromSettings > nativeRating:: ', TEMP]); if (TEMP !== undefined) { globals.nativeRating = (TEMP === true) ? true : false;; } } /** * C: getVariablesFromAttributeHtml * desueto, potrebbe essere commentato. */ setVariablesFromAttributeHtml(globals: Globals, el: ElementRef) { // this.logger.debug('[GLOBAL-SET] getVariablesFromAttributeHtml', el); // const projectid = el.nativeElement.getAttribute('projectid'); // if (projectid !== null) { // globals.setParameter('projectid', projectid); // } // https://stackoverflow.com/questions/45732346/externally-pass-values-to-an-angular-application let TEMP: any; TEMP = el.nativeElement.getAttribute('tenant'); if (TEMP !== null) { this.globals.tenant = TEMP; } TEMP = el.nativeElement.getAttribute('recipientId'); if (TEMP !== null) { this.globals.recipientId = TEMP; } TEMP = el.nativeElement.getAttribute('widgetTitle'); if (TEMP !== null) { this.globals.widgetTitle = TEMP; } TEMP = el.nativeElement.getAttribute('poweredBy'); if (TEMP !== null) { this.globals.poweredBy = TEMP; } // TEMP = el.nativeElement.getAttribute('userId'); // if (TEMP !== null) { // this.globals.userId = TEMP; // } TEMP = el.nativeElement.getAttribute('userEmail'); if (TEMP !== null) { this.globals.userEmail = TEMP; } TEMP = el.nativeElement.getAttribute('userFullname'); if (TEMP !== null) { this.globals.userFullname = TEMP; } TEMP = el.nativeElement.getAttribute('preChatForm'); if (TEMP !== null) { this.globals.preChatForm = (TEMP === true) ? true : false; } TEMP = el.nativeElement.getAttribute('isOpen'); if (TEMP !== null) { this.globals.isOpen = (TEMP === true) ? true : false; } TEMP = el.nativeElement.getAttribute('channelType'); if (TEMP !== null) { this.globals.channelType = TEMP; } TEMP = el.nativeElement.getAttribute('lang'); if (TEMP !== null) { this.globals.lang = TEMP; } TEMP = el.nativeElement.getAttribute('align'); if (TEMP !== null) { this.globals.align = TEMP; } TEMP = el.nativeElement.getAttribute('marginX'); if (TEMP !== null) { this.globals.marginX = TEMP; } TEMP = el.nativeElement.getAttribute('marginY'); if (TEMP !== null) { this.globals.marginY = TEMP; } TEMP = el.nativeElement.getAttribute('launcherWidth'); if (TEMP !== null) { this.globals.launcherWidth = TEMP; } TEMP = el.nativeElement.getAttribute('launcherHeight'); if (TEMP !== null) { this.globals.launcherHeight= TEMP; } TEMP = el.nativeElement.getAttribute('baloonImage'); if (TEMP !== null) { this.globals.baloonImage= TEMP; } TEMP = el.nativeElement.getAttribute('baloonShape'); if (TEMP !== null) { this.globals.baloonShape= TEMP; } TEMP = el.nativeElement.getAttribute('calloutTimer'); if (TEMP !== null) { this.globals.calloutTimer = TEMP; } TEMP = el.nativeElement.getAttribute('welcomeMsg'); if (TEMP !== null) { this.globals.welcomeMsg = TEMP; } TEMP = el.nativeElement.getAttribute('welcomeTitle'); if (TEMP !== null) { this.globals.welcomeTitle = TEMP; } TEMP = el.nativeElement.getAttribute('calloutTitle'); if (TEMP !== null) { this.globals.calloutTitle = TEMP; } TEMP = el.nativeElement.getAttribute('calloutMsg'); if (TEMP !== null) { this.globals.calloutMsg = TEMP; } TEMP = el.nativeElement.getAttribute('startFromHome'); if (TEMP !== null) { this.globals.startFromHome = (TEMP === true) ? true : false; } TEMP = el.nativeElement.getAttribute('logoChat'); if (TEMP !== null) { this.globals.logoChat = TEMP; } TEMP = el.nativeElement.getAttribute('autoStart'); if (TEMP !== null) { this.globals.autoStart = (TEMP === true) ? true : false; } TEMP = el.nativeElement.getAttribute('startHidden'); if (TEMP !== null) { this.globals.startHidden = (TEMP === true) ? true : false; } TEMP = el.nativeElement.getAttribute('isShown'); if (TEMP !== null) { this.globals.isShown = (TEMP === true) ? true : false; } TEMP = el.nativeElement.getAttribute('isLogEnabled'); if (TEMP !== null) { this.globals.isLogEnabled = (TEMP === true) ? true : false; } TEMP = el.nativeElement.getAttribute('filterByRequester'); if (TEMP !== null) { this.globals.filterByRequester = (TEMP === true) ? true : false; } TEMP = el.nativeElement.getAttribute('showAttachmentButton'); if (TEMP !== null) { this.globals.showAttachmentButton = (TEMP === true) ? true : false; } TEMP = el.nativeElement.getAttribute('departmentID'); if (TEMP !== null) { this.globals.departmentID = TEMP; } TEMP = el.nativeElement.getAttribute('showAllConversations'); if (TEMP !== null) { this.globals.showAllConversations = (TEMP === true) ? true : false; } // TEMP = el.nativeElement.getAttribute('privacyField'); // if (TEMP !== null) { // this.globals.privacyField = TEMP; // } TEMP = el.nativeElement.getAttribute('dynamicWaitTimeReply'); if (TEMP !== null) { this.globals.dynamicWaitTimeReply = TEMP; } TEMP = el.nativeElement.getAttribute('soundEnabled'); if (TEMP !== null) { this.globals.soundEnabled = TEMP; } TEMP = el.nativeElement.getAttribute('openExternalLinkButton'); if (TEMP !== null) { this.globals.openExternalLinkButton = TEMP; } TEMP = el.nativeElement.getAttribute('hideHeaderConversationOptionsMenu'); if (TEMP !== null) { this.globals.hideHeaderConversationOptionsMenu = TEMP; } TEMP = el.nativeElement.getAttribute('hideSettings'); if (TEMP !== null) { this.globals.hideSettings = TEMP; } TEMP = el.nativeElement.getAttribute('logLevel'); if (TEMP !== null) { this.globals.logLevel = TEMP; } TEMP = el.nativeElement.getAttribute('preChatFormJson'); if (TEMP !== null) { this.globals.preChatFormJson = TEMP; } TEMP = el.nativeElement.getAttribute('fontSize'); if (TEMP !== null) { this.globals.fontSize = TEMP; } TEMP = el.nativeElement.getAttribute('fontFamily'); if (TEMP !== null) { this.globals.fontFamily = TEMP; } TEMP = el.nativeElement.getAttribute('buttonFontSize'); if (TEMP !== null) { this.globals.buttonFontSize = TEMP; } TEMP = el.nativeElement.getAttribute('buttonBackgroundColor'); if (TEMP !== null) { this.globals.buttonBackgroundColor = TEMP; } TEMP = el.nativeElement.getAttribute('buttonTextColor'); if (TEMP !== null) { this.globals.buttonTextColor = TEMP; } TEMP = el.nativeElement.getAttribute('buttonHoverBackgroundColor'); if (TEMP !== null) { this.globals.buttonHoverBackgroundColor = TEMP; } TEMP = el.nativeElement.getAttribute('buttonHoverTextColor'); if (TEMP !== null) { this.globals.buttonHoverTextColor = TEMP; } TEMP = el.nativeElement.getAttribute('singleConversation'); if (TEMP !== null) { this.globals.singleConversation = (TEMP === true) ? true : false; } TEMP = el.nativeElement.getAttribute('nativeRating'); if (TEMP !== null) { this.globals.nativeRating = (TEMP === true) ? true : false; } } /** * D: setVariableFromUrlParameters */ setVariablesFromUrlParameters(globals: Globals) { this.logger.debug('[GLOBAL-SET] setVariablesFromUrlParameters: '); const windowContext = globals.windowContext; let TEMP: any; TEMP = getParameterByName(windowContext, 'tiledesk_tenant'); if (TEMP) { globals.tenant = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_recipientId'); if (TEMP) { globals.recipientId = stringToBoolean(TEMP); } // TEMP = getParameterByName(windowContext, 'tiledesk_projectid'); // if (TEMP) { // globals.projectid = stringToBoolean(TEMP); // } TEMP = getParameterByName(windowContext, 'tiledesk_widgetTitle'); if (TEMP) { globals.widgetTitle = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_poweredBy'); if (TEMP) { globals.poweredBy = stringToBoolean(TEMP); } // TEMP = getParameterByName(windowContext, 'tiledesk_userid'); // if (TEMP) { // globals.userId = stringToBoolean(TEMP); // } TEMP = getParameterByName(windowContext, 'tiledesk_userEmail'); if (TEMP) { globals.userEmail = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_userFullname'); if (TEMP) { globals.userFullname = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_channelType'); if (TEMP) { globals.channelType = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_lang'); if (TEMP) { globals.lang = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_calloutTimer'); if (TEMP) { globals.calloutTimer = Number(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_align'); if (TEMP) { globals.align = stringToBoolean(TEMP); const divWidgetContainer = windowContext.document.getElementById('tiledeskdiv'); if (globals.align === 'left') { divWidgetContainer.classList.add('align-left'); } else { divWidgetContainer.classList.add('align-right'); } } TEMP = getParameterByName(windowContext, 'tiledesk_marginX'); if (TEMP) { globals.marginX = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_marginY'); if (TEMP) { globals.marginY = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_launcherWidth'); if (TEMP) { globals.launcherWidth = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_launcherHeight'); if (TEMP) { globals.launcherHeight = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_baloonImage'); if (TEMP) { globals.baloonImage = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_baloonShape'); if (TEMP) { globals.baloonShape = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_welcomeMsg'); if (TEMP) { globals.welcomeMsg = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_calloutTitle'); if (TEMP) { globals.calloutTitle = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_calloutMsg'); if (TEMP) { globals.calloutMsg = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_hideHeaderCloseButton'); if (TEMP) { globals.hideHeaderCloseButton = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_themeColor'); if (TEMP) { const themecolor = stringToBoolean(TEMP); globals.themeColor = convertColorToRGBA(themecolor, 100); globals.bubbleSentBackground = convertColorToRGBA(themecolor, 100); globals.buttonBackgroundColor = invertColor(themecolor, true); globals.buttonTextColor = convertColorToRGBA(themecolor, 100); globals.buttonHoverBackgroundColor = convertColorToRGBA(themecolor, 100); globals.buttonHoverTextColor = invertColor(themecolor, true); } TEMP = getParameterByName(windowContext, 'tiledesk_themeForegroundColor'); if (TEMP) { const themeforegroundcolor = stringToBoolean(TEMP); globals.themeForegroundColor = convertColorToRGBA(themeforegroundcolor, 100); globals.bubbleSentTextColor = convertColorToRGBA(themeforegroundcolor, 100); } TEMP = getParameterByName(windowContext, 'tiledesk_logoChat'); if (TEMP) { globals.logoChat = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_welcomeTitle'); if (TEMP) { globals.welcomeTitle = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_autoStart'); if (TEMP) { globals.autoStart = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_startHidden'); if (TEMP) { globals.startHidden = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_isShown'); if (TEMP) { globals.isShown = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_isLogEnabled'); if (TEMP) { globals.isLogEnabled = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_filterByRequester'); if (TEMP) { globals.filterByRequester = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_showWaitTime'); if (TEMP) { globals.showWaitTime = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_showAvailableAgents'); if (TEMP) { globals.showAvailableAgents = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_showLogoutOption'); if (TEMP) { globals.showLogoutOption = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_preChatForm'); if (TEMP) { globals.preChatForm = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_isOpen'); if (TEMP) { globals.isOpen = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_allowTranscriptDownload'); if (TEMP) { globals.allowTranscriptDownload = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_startFromHome'); if (TEMP) { globals.startFromHome = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_fullscreenMode'); if (TEMP) { globals.fullscreenMode = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_customAttributes'); if (TEMP) { globals.customAttributes = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_showAttachmentButton'); if (TEMP) { globals.showAttachmentButton = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_departmentID'); if (TEMP) { globals.departmentID = TEMP; } TEMP = getParameterByName(windowContext, 'tiledesk_persistence'); if (TEMP) { globals.persistence = TEMP; } TEMP = getParameterByName(windowContext, 'tiledesk_showAllConversations'); if (TEMP) { globals.showAllConversations = stringToBoolean(TEMP); } // TEMP = getParameterByName(windowContext, 'tiledesk_privacyField'); // if (TEMP) { // globals.privacyField = TEMP; // } TEMP = getParameterByName(windowContext, 'tiledesk_jwt'); if (TEMP) { globals.jwt = TEMP; } TEMP = getParameterByName(windowContext, 'tiledesk_dynamicWaitTimeReply'); if (TEMP) { globals.dynamicWaitTimeReply = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_soundEnabled'); if (TEMP) { globals.soundEnabled = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_openExternalLinkButton'); if (TEMP) { globals.openExternalLinkButton = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_hideHeaderConversationOptionsMenu'); if (TEMP) { globals.hideHeaderConversationOptionsMenu = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_hideSettings'); if (TEMP) { globals.hideSettings = stringToBoolean(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_logLevel'); if (TEMP) { globals.logLevel = TEMP; } TEMP = getParameterByName(windowContext, 'tiledesk_preChatFormJson'); if (TEMP) { globals.preChatFormJson = JSON.parse(TEMP); } TEMP = getParameterByName(windowContext, 'tiledesk_bubbleSentBackground'); if (TEMP) { const bubbleSentBackground = stringToBoolean(TEMP); globals.bubbleSentBackground = convertColorToRGBA(bubbleSentBackground, 100); globals.bubbleSentTextColor = invertColor(bubbleSentBackground, true) globals.buttonBackgroundColor= invertColor(bubbleSentBackground, true); globals.buttonTextColor = convertColorToRGBA(bubbleSentBackground, 100); globals.buttonHoverBackgroundColor = convertColorToRGBA(bubbleSentBackground, 100); globals.buttonHoverTextColor = invertColor(bubbleSentBackground, true); } TEMP = getParameterByName(windowContext, 'tiledesk_bubbleSentTextColor'); if (TEMP) { const bubbleSentTextColor = stringToBoolean(TEMP); globals.bubbleSentTextColor = convertColorToRGBA(bubbleSentTextColor, 100); } TEMP = getParameterByName(windowContext, 'tiledesk_bubbleReceivedBackground'); if (TEMP) { const bubbleReceivedBackground = stringToBoolean(TEMP); globals.bubbleReceivedBackground = convertColorToRGBA(bubbleReceivedBackground, 100); globals.bubbleReceivedTextColor = invertColor(TEMP, true) } TEMP = getParameterByName(windowContext, 'tiledesk_bubbleReceivedTextColor'); if (TEMP) { const bubbleReceivedTextColor = stringToBoolean(TEMP); globals.bubbleReceivedTextColor = convertColorToRGBA(bubbleReceivedTextColor, 100); } TEMP = getParameterByName(windowContext, 'tiledesk_fontSize'); if (TEMP) { globals.fontSize = TEMP; } TEMP = getParameterByName(windowContext, 'tiledesk_fontFamily'); if (TEMP) { globals.fontFamily = TEMP; } TEMP = getParameterByName(windowContext, 'tiledesk_buttonFontSize'); if (TEMP) { globals.buttonFontSize = TEMP; } TEMP = getParameterByName(windowContext, 'tiledesk_buttonBackgroundColor'); if (TEMP) { const buttonBackgroundColor = stringToBoolean(TEMP); globals.buttonBackgroundColor = convertColorToRGBA(buttonBackgroundColor, 100); globals.buttonTextColor = invertColor(buttonBackgroundColor, true); globals.buttonHoverBackgroundColor = invertColor(buttonBackgroundColor, true); globals.buttonHoverTextColor = convertColorToRGBA(buttonBackgroundColor, 100); } TEMP = getParameterByName(windowContext, 'tiledesk_buttonTextColor'); if (TEMP) { const buttonTextColor = stringToBoolean(TEMP); globals.buttonTextColor = convertColorToRGBA(buttonTextColor, 100); } TEMP = getParameterByName(windowContext, 'tiledesk_buttonHoverBackgroundColor'); if (TEMP) { const buttonHoverBackgroundColor = stringToBoolean(TEMP); globals.buttonHoverBackgroundColor = convertColorToRGBA(buttonHoverBackgroundColor, 100); } TEMP = getParameterByName(windowContext, 'tiledesk_buttonHoverTextColor'); if (TEMP) { const buttonHoverTextColor = stringToBoolean(TEMP); globals.buttonHoverTextColor = convertColorToRGBA(buttonHoverTextColor, 100); } TEMP = getParameterByName(windowContext, 'tiledesk_singleConversation'); if (TEMP) { globals.singleConversation = stringToBoolean(TEMP);; } TEMP = getParameterByName(windowContext, 'tiledesk_nativeRating'); if (TEMP) { globals.nativeRating = stringToBoolean(TEMP); } } /** * E: setVariableFromStorage * recupero il dictionary global dal local storage * aggiorno tutti i valori di globals * @param globals */ setVariableFromStorage(globals: Globals) { this.logger.debug('[GLOBAL-SET] setVariableFromStorage :::::::: SET VARIABLE ---------->', Object.keys(globals)); for (const key of Object.keys(globals)) { const val = this.appStorageService.getItem(key); // this.logger.debug('[GLOBAL-SET] setVariableFromStorage SET globals KEY ---------->', key); // this.logger.debug('[GLOBAL-SET] setVariableFromStorage SET globals VAL ---------->', val); if (val && val !== null) { // globals.setParameter(key, val); globals[key] = stringToBoolean(val); } // this.logger.debug('[GLOBAL-SET] setVariableFromStorage SET globals == ---------->', globals); } } // ========= begin:: GET DEPARTEMENTS ============// /** * INIT DEPARTMENT: * get departments list * set department default * CALL AUTHENTICATION */ initDepartments(departments: any) { this.globals.setParameter('departmentSelected', null); this.globals.setParameter('departmentDefault', null); this.logger.debug('[GLOBAL-SET] initDepartments departments ::::', departments); if (departments === null ) { return; } this.globals.departments = departments; // console.log('departments.length', departments.length); if (departments.length === 1) { // UN SOLO DEPARTMENT const department = departments[0]; this.logger.debug('[GLOBAL-SET] initDepartments DEPARTMENT FIRST ::::', departments[0]); this.globals.setParameter('departmentDefault', departments[0]); if (department && department.online_msg && department.online_msg !== '') { this.globals.online_msg = department.online_msg; } if (department && department.offline_msg && department.offline_msg !== '') { this.globals.offline_msg = department.offline_msg; } // if (department['offline_msg']) { // this.globals.offline_msg = department['offline_msg']; // } // if (department['online_msg']) { // this.globals.online_msg = department['online_msg']; // } this.setDepartment(departments[0]); // return false; } else if (departments.length > 1) { // CI SONO + DI 2 DIPARTIMENTI this.logger.debug('[GLOBAL-SET] initDepartments > CI SONO + DI 2 DIPARTIMENTI ::::', departments[0]); let i = 0; departments.forEach(department => { if (department['default'] === true) { // this.globals.departmentDefault = department; if (department && department.online_msg && department.online_msg !== '') { this.globals.online_msg = department.online_msg; } if (department && department.offline_msg && department.offline_msg !== '') { this.globals.offline_msg = department.offline_msg; } // if (department['offline_msg']) { // this.globals.offline_msg = department['offline_msg']; // } // if (department['online_msg']) { // this.globals.online_msg = department['online_msg']; // } // console.log('this.globals.offline_msg ::::', department['offline_msg']); // console.log('this.globals.online_msg ::::', department['online_msg']); departments.splice(i, 1); return; } i++; }); this.globals.setParameter('departmentDefault', departments[0]); this.setDepartment(departments[0]); } else { // DEPARTMENT DEFAULT NON RESTITUISCE RISULTATI !!!! this.logger.error('[GLOBAL-SET] initDepartments > DEPARTMENT DEFAULT NON RESTITUISCE RISULTATI ::::'); // return; } this.setDepartmentFromExternal(); // chiamata ridondante viene fatta nel setParameters come ultima operazione } setDepartmentFromExternal() { // se esiste un departmentID impostato dall'esterno, // creo un department di default e lo imposto come department di default // this.logger.debug('[GLOBAL-SET] setDepartmentFromExternal > EXTERNAL departmentID ::::' + this.globals.departmentID); let isValidID = false; if (this.globals.departmentID) { this.globals.departments.forEach(department => { if (department._id === this.globals.departmentID) { this.logger.debug('[GLOBAL-SET] setDepartmentFromExternal > EXTERNAL DEPARTMENT ::::' + department._id); this.globals.setParameter('departmentDefault', department); this.setDepartment(department); isValidID = true; return; } }); if (isValidID === false) { // se l'id passato non corrisponde a nessun id dipartimento esistente viene annullato // per permettere di passare dalla modale dell scelta del dipartimento se necessario (+ di 1 dipartimento presente) this.globals.departmentID = null; } this.logger.debug('[GLOBAL-SET] setDepartmentFromExternal > END departmentID ::::' + this.globals.departmentID + isValidID); } } /** * SET DEPARTMENT: * set department selected * save department selected in attributes * save attributes in this.appStorageService */ setDepartment(department) { this.logger.debug('[GLOBAL-SET] setDepartment: ', JSON.stringify(department)); this.globals.setParameter('departmentSelected', department); // let attributes = this.globals.attributes; let attributes: any = JSON.parse(this.appStorageService.getItem('attributes')); if (!attributes) { attributes = { departmentId: department._id, departmentName: department.name }; } else { attributes.departmentId = department._id; attributes.departmentName = department.name; } // this.logger.debug('[GLOBAL-SET] setDepartment > department.online_msg: ', department.online_msg); // this.logger.debug('[GLOBAL-SET] setDepartment > department.offline_msg: ', department.offline_msg); this.logger.debug('[GLOBAL-SET] setDepartment > setAttributes: ', JSON.stringify(attributes)); this.globals.setParameter('departmentSelected', department); this.globals.setParameter('attributes', attributes); this.appStorageService.setItem('attributes', JSON.stringify(attributes)); } // ========= end:: GET DEPARTEMENTS ============// // ========= begin:: GET AVAILABLE AGENTS STATUS ============// /** setAvailableAgentsStatus * verifica se c'è un'agent disponibile */ private setAvailableAgentsStatus(availableAgents) { this.globals.setParameter('availableAgentsStatus', false); if ( availableAgents === null ) { return; } if (availableAgents.length > 0) { // this.globals.areAgentsAvailable = true; // this.globals.setParameter('areAgentsAvailable', true); // this.globals.setParameter('areAgentsAvailableText', this.globals.AGENT_AVAILABLE); const arrayAgents = []; availableAgents.forEach((element, index: number) => { element.imageurl = getImageUrlThumb(element.id); arrayAgents.push(element); if (index >= 4) { return; } // this.logger.debug('[GLOBAL-SET] setAvailableAgentsStatus > index, ' - element->', element); }); // availableAgents.forEach(element => { // element.imageurl = getImageUrlThumb(element.id); // arrayAgents.push(element); // }); // let limit = arrayAgents.length; // if (arrayAgents.length > 5) { // limit = 5; // } this.globals.availableAgents = arrayAgents; this.globals.setParameter('availableAgentsStatus', true); // this.globals.setParameter('availableAgents', availableAgents); // this.logger.debug('[GLOBAL-SET] setAvailableAgentsStatus > element->', this.globals.availableAgents); // this.logger.debug('[GLOBAL-SET] setAvailableAgentsStatus > areAgentsAvailable->', this.globals.areAgentsAvailable); // this.logger.debug('[GLOBAL-SET] setAvailableAgentsStatus > areAgentsAvailableText->', this.globals.areAgentsAvailableText); } } // ========= end:: GET AVAILABLE AGENTS STATUS ============// getProjectParametersById(id: string): Observable<any[]> { if(id){ const API_URL = this.appConfigService.getConfig().apiUrl; const url = API_URL + id + '/widgets'; // console.log('getProjectParametersById: ', url); const headers = new Headers(); headers.append('Content-Type', 'application/json'); return this.http.get(url, { headers }) .map((response) => response.json()); } } }
the_stack
import ApoloMutate from './graphqlMutate' import snapbar from '../functions/module/snackbar' import mutateCreateComment from '../graphql/mutateCreateComment.gql' export interface CommentForm { author: string, email: string, url: string, comment: string, comment_post_ID: number, comment_parent: number, nonce: string } export interface PostCallbackData { data: { postComment: Data } } export interface Data { succeed: boolean message: string comment_ID: number comment_author: string comment_author_avatar: string comment_parent: number content: string date: string level: number location: string role: string ua: string url: string } /** * Class to do actions on comment form and listen events on comment list reply button * @since 4.0.0 * * @method public constructor() * @method static set_comment_form_value() * @method static reset_comment_form_button_listener() * @method static reset_comment_form() * @method static reply_to_listener() * @method static cancel_reply_listener() * @method public submit_listener() */ export class CreateComment { public author: string public email: string public url: string public comment: string public comment_post_ID: number public comment_parent: number public nonce: string public root_parent: number /** * create new comment * @since 4.0.0 */ public constructor() { // this.cancel_reply_listener() this.submit_listener() } /** * set the comment form preload information * @since 4.0.0 * @param {CommentForm} data */ public static set_comment_form_value(data: CommentForm) { // let form = <HTMLLIElement>document.getElementById(`commentform`) let input_author = <HTMLInputElement>document.getElementById(`author`) let input_email = <HTMLInputElement>document.getElementById(`email`) let input_url = <HTMLInputElement>document.getElementById(`url`) let input_comment_post_ID = <HTMLInputElement>document.getElementById(`comment_post_ID`) let input_comment_parent = <HTMLInputElement>document.getElementById(`comment_parent`) let input_nonce = <HTMLInputElement>document.getElementById(`nonce`) let textarea_comment = <HTMLTextAreaElement>document.getElementById(`comment`) input_author.value = data.author input_email.value = data.email input_url.value = data.url input_comment_post_ID.value = String(data.comment_post_ID) input_comment_parent.value = String(data.comment_parent) input_nonce.value = data.nonce textarea_comment.value = data.comment } /** * reset comment form * needs to call in ListComments::nav_turn() and cancel_reply_callback() * @since 4.0.0 * * @param {boolean} keep keep the existing comment text? */ public static reset_comment_form(keep: boolean = true) { document.getElementById('reply-to-info').style.display = 'none' let comment: string = keep ? (<HTMLTextAreaElement>document.getElementById(`comment`)).value : null // TODO: use from cookie let default_form: CommentForm = { 'author': (<HTMLInputElement>document.getElementById(`author`)).value, 'email': (<HTMLInputElement>document.getElementById(`email`)).value, 'url': (<HTMLInputElement>document.getElementById(`url`)).value, 'comment': comment, 'comment_post_ID': Number((<HTMLInputElement>document.getElementById(`comment_post_ID`)).value), 'comment_parent': 0, 'nonce': (<HTMLInputElement>document.getElementById(`nonce`)).value } this.set_comment_form_value(default_form) let comment_form = document.querySelector(`#commentform`) let default_wrapper = document.querySelector(`.commetn-form-wrapper`) default_wrapper.appendChild(comment_form) } /** * listen reset comment form button * @since 4.0.0 */ public static reset_comment_form_button_listener() { // TODO } /** * popup user info in a folat window * @since 4.0.0 */ public static uesr_info_hover_listener() { // TODO } /** * creat comment item for response data * @since 4.0.0 * TODO: we can add a is_approved area * @return DocumentFragment */ public static creat_comment_item(data: Data): DocumentFragment { let li: HTMLTemplateElement = document.querySelector('#comment-list-li-template') let li_clone: DocumentFragment = document.importNode(li.content, true) let comment = data li_clone.querySelector('.comment-item').setAttribute('id', `comment-${comment.comment_ID}`) li_clone.querySelector('.content').innerHTML = (comment.content ? comment.content : '').trim() li_clone.querySelector('.time').textContent = comment.date li_clone.querySelector('.name').textContent = comment.comment_author li_clone.querySelector('.avatar img').setAttribute('src', comment.comment_author_avatar) li_clone.querySelector('a.avatar').setAttribute('href', comment.url) li_clone.querySelector('a.name').setAttribute('href', comment.url) li_clone.querySelector('.location').textContent = comment.location li_clone.querySelector('.reply').remove() let like = (<HTMLElement>li_clone.querySelector('.like')), dislike = (<HTMLElement>li_clone.querySelector('.dislike')) like.style.display = 'none' dislike.style.display = 'none' return li_clone } /** * Listener for reply button `CreateComment.reply_to_listener()` * call after list build! Not in constructor! * show reload every time refresh list * @since 4.0.0 */ public static reply_to_listener() { let reply = document.querySelectorAll(`.reply`) for (let i = 0; i < reply.length; i++) { reply[i].addEventListener('click', this.reply_to_listener_callback, false) } } /** * callback of reply_to_listener * @since 4.0.0 * @param MouseEvent event */ public static reply_to_listener_callback(event: MouseEvent) { let element: Element = event['path'][0] let to_comment_id: number = Number(element.getAttribute('data-reply-to')) let target_place = <HTMLElement>document.querySelector(`#comment-${to_comment_id} .reply-form`) let comment_form = <HTMLElement>document.querySelector(`#commentform`) target_place.appendChild(comment_form) target_place.style.display = 'block' // add reply to author name let reply_to_author: string = (<HTMLElement>document.querySelector(`#comment-${to_comment_id} .name`)).innerText document.getElementById(`reply-to-author`).innerText = reply_to_author document.getElementById(`reply-to-link`).setAttribute(`href`, `#comment-${to_comment_id}`) document.getElementById('reply-to-info').style.display = 'block' // cancel reply CreateComment.cancel_reply_listener() // set form data let form_data: CommentForm = { 'author': (<HTMLInputElement>document.getElementById(`author`)).value, 'email': (<HTMLInputElement>document.getElementById(`email`)).value, 'url': (<HTMLInputElement>document.getElementById(`url`)).value, 'comment': (<HTMLTextAreaElement>document.getElementById(`comment`)).value, 'comment_post_ID': Number((<HTMLInputElement>document.getElementById(`comment_post_ID`)).value), 'comment_parent': to_comment_id, 'nonce': (<HTMLInputElement>document.getElementById(`nonce`)).value } CreateComment.set_comment_form_value(form_data) // TODO: add a mirror (not actually a form, only need // to add a click listener to reset comment form) to // the default comment form place } /** * Listener for cancel reply button * @since 4.0.0 */ public static cancel_reply_listener() { document.getElementById('cancel-reply').addEventListener('click', callback, false) function callback(event: MouseEvent) { CreateComment.reset_comment_form(true) } } /** * Listener for submit button * @since 4.0.0 */ public submit_listener() { // add event listener to comment form // - do else by submit_callback if (document.querySelector('#commentform')) { const form = document.querySelector('#commentform') form.addEventListener('submit', this.submit_callback.bind(this), false) } } /** * submit event callback * @since 4.0.0 * @param {Event} event */ public submit_callback(event: Event) { // prevent the default behavior to avoid a form submit to reload the page event.preventDefault() // get formdata // let element: Element = event['path'][0] this.author = (<HTMLInputElement>document.getElementById("author")).value this.email = (<HTMLInputElement>document.getElementById("email")).value this.url = (<HTMLInputElement>document.getElementById("url")).value this.comment = (<HTMLInputElement>document.getElementById("comment")).value this.comment_post_ID = Number((<HTMLInputElement>document.getElementById("comment_post_ID")).value) this.comment_parent = Number((<HTMLInputElement>document.getElementById("comment_parent")).value) this.nonce = (<HTMLInputElement>document.getElementById("nonce")).value // create a hack place: // save the root parent id in this.root_parent // then insert new item by root_parent in mutate_callback() // HINT: insert in the last li will not influent nav or collapse if (this.comment_parent === 0) { // is replying to a post directly this.root_parent = 0 } else { let parent: Element = document.querySelector(`#comment-${this.comment_parent}`).parentElement.parentElement.parentElement if (parent.classList.contains('comment-item')) { // if the post replying to has a parent, that means, new one will be a child-child this.root_parent = Number(parent.getAttribute('id').substr(8)) } else { // if the post replying to has a parent, that means, new one will be a child this.root_parent = this.comment_parent } } // mutation let mutation = this.mutate() } /** * mutation callback * @since 4.0.0 * @param {PostCallbackData} data mutation callback */ public mutate_callback(dataJson: PostCallbackData) { // handle data let data: Data = dataJson.data.postComment if (!data.succeed) { this.error_handle(data) return } // generate new element for data let data_ele: DocumentFragment = CreateComment.creat_comment_item(data) let ul: Element, lis: NodeListOf<Element> if (this.root_parent === 0) { ul = document.querySelector(`ul#comment-list-ul-root`) lis = document.querySelectorAll(`ul#comment-list-ul-root>li`) } else { ul = document.querySelector(`#comment-${this.root_parent} ul.comment-list-ul`) lis = document.querySelectorAll(`#comment-${this.root_parent} ul.comment-list-ul>li`) } let last_li = lis[lis.length - 1] if (lis.length > 0) { last_li.parentElement.insertBefore(data_ele, last_li.nextSibling) } else { ul.appendChild(data_ele) } // remove leave-first-comment title let leave_first_notice = document.getElementById('leave-first-comment') if (typeof (leave_first_notice) !== 'undefined' && leave_first_notice !== null) leave_first_notice.remove() // reset comment form CreateComment.reset_comment_form(false) // TODO: scroll page // TODO: add anomation // raise a snapbar snapbar(data.message) } /** * handle error in data, raise a error info * @since 4.0.0 * @param {Data} data mutation callback */ public error_handle(data: Data) { snapbar(data.message, 0) } private mutate() { const mutation = { mutation: mutateCreateComment, variables: { "input": { "clientMutationId": "PostComment", "author": this.author, "email": this.email, "url": this.url, "comment": this.comment, "comment_post_ID": this.comment_post_ID, "comment_parent": this.comment_parent, "_wp_unfiltered_html_comment": this.nonce } } } const client: ApoloMutate = new ApoloMutate(mutation, this.mutate_callback.bind(this)) client.do() } }
the_stack
import { FormDefinitionRepresentation } from '../model/formDefinitionRepresentation'; import { FormValueRepresentation } from '../model/formValueRepresentation'; import { IdentityLinkRepresentation } from '../model/identityLinkRepresentation'; import { ResultListDataRepresentationProcessDefinitionRepresentation } from '../model/resultListDataRepresentationProcessDefinitionRepresentation'; import { ResultListDataRepresentationRuntimeDecisionTableRepresentation } from '../model/resultListDataRepresentationRuntimeDecisionTableRepresentation'; import { ResultListDataRepresentationRuntimeFormRepresentation } from '../model/resultListDataRepresentationRuntimeFormRepresentation'; import { BaseApi } from './base.api'; import { throwIfNotDefined } from '../../../assert'; /** * Processdefinitions service. * @module ProcessdefinitionsApi */ export class ProcessDefinitionsApi extends BaseApi { /** * Add a user or group involvement to a process definition * * * * @param processDefinitionId processDefinitionId * @param identityLinkRepresentation identityLinkRepresentation * @return Promise<IdentityLinkRepresentation> */ createIdentityLink(processDefinitionId: string, identityLinkRepresentation: IdentityLinkRepresentation): Promise<IdentityLinkRepresentation> { throwIfNotDefined(processDefinitionId, 'processDefinitionId'); throwIfNotDefined(identityLinkRepresentation, 'identityLinkRepresentation'); let postBody = identityLinkRepresentation; let pathParams = { 'processDefinitionId': processDefinitionId }; let queryParams = {}; let headerParams = {}; let formParams = {}; let contentTypes = ['application/json']; let accepts = ['application/json']; return this.apiClient.callApi( '/api/enterprise/process-definitions/{processDefinitionId}/identitylinks', 'POST', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts, IdentityLinkRepresentation); } /** * Remove a user or group involvement from a process definition * * * * @param processDefinitionId Process definition ID * @param family Identity type * @param identityId User or group ID * @return Promise<{}> */ deleteIdentityLink(processDefinitionId: string, family: string, identityId: string): Promise<any> { throwIfNotDefined(processDefinitionId, 'processDefinitionId'); throwIfNotDefined(family, 'family'); throwIfNotDefined(identityId, 'identityId'); let postBody = null; let pathParams = { 'processDefinitionId': processDefinitionId, 'family': family, 'identityId': identityId }; let queryParams = {}; let headerParams = {}; let formParams = {}; let contentTypes = ['application/json']; let accepts = ['application/json']; return this.apiClient.callApi( '/api/enterprise/process-definitions/{processDefinitionId}/identitylinks/{family}/{identityId}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts); } /** * Get a user or group involvement with a process definition * * * * @param processDefinitionId Process definition ID * @param family Identity type * @param identityId User or group ID * @return Promise<IdentityLinkRepresentation> */ getIdentityLinkType(processDefinitionId: string, family: string, identityId: string): Promise<IdentityLinkRepresentation> { throwIfNotDefined(processDefinitionId, 'processDefinitionId'); throwIfNotDefined(family, 'family'); throwIfNotDefined(identityId, 'identityId'); let postBody = null; let pathParams = { 'processDefinitionId': processDefinitionId, 'family': family, 'identityId': identityId }; let queryParams = {}; let headerParams = {}; let formParams = {}; let contentTypes = ['application/json']; let accepts = ['application/json']; return this.apiClient.callApi( '/api/enterprise/process-definitions/{processDefinitionId}/identitylinks/{family}/{identityId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts, IdentityLinkRepresentation); } /** * List either the users or groups involved with a process definition * * * * @param processDefinitionId processDefinitionId * @param family Identity type * @return Promise<IdentityLinkRepresentation> */ getIdentityLinksForFamily(processDefinitionId: string, family: string): Promise<IdentityLinkRepresentation> { throwIfNotDefined(processDefinitionId, 'processDefinitionId'); throwIfNotDefined(family, 'family'); let postBody = null; let pathParams = { 'processDefinitionId': processDefinitionId, 'family': family }; let queryParams = {}; let headerParams = {}; let formParams = {}; let contentTypes = ['application/json']; let accepts = ['application/json']; return this.apiClient.callApi( '/api/enterprise/process-definitions/{processDefinitionId}/identitylinks/{family}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts, IdentityLinkRepresentation); } /** * List the users and groups involved with a process definition * * * * @param processDefinitionId processDefinitionId * @return Promise<IdentityLinkRepresentation> */ getIdentityLinks(processDefinitionId: string): Promise<IdentityLinkRepresentation> { throwIfNotDefined(processDefinitionId, 'processDefinitionId'); let postBody = null; let pathParams = { 'processDefinitionId': processDefinitionId }; let queryParams = {}; let headerParams = {}; let formParams = {}; let contentTypes = ['application/json']; let accepts = ['application/json']; return this.apiClient.callApi( '/api/enterprise/process-definitions/{processDefinitionId}/identitylinks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts, IdentityLinkRepresentation); } /** * List the decision tables associated with a process definition * * * * @param processDefinitionId processDefinitionId * @return Promise<ResultListDataRepresentationRuntimeDecisionTableRepresentation> */ getProcessDefinitionDecisionTables(processDefinitionId: string): Promise<ResultListDataRepresentationRuntimeDecisionTableRepresentation> { throwIfNotDefined(processDefinitionId, 'processDefinitionId'); let postBody = null; let pathParams = { 'processDefinitionId': processDefinitionId }; let queryParams = {}; let headerParams = {}; let formParams = {}; let contentTypes = ['application/json']; let accepts = ['application/json']; return this.apiClient.callApi( '/api/enterprise/process-definitions/{processDefinitionId}/decision-tables', 'GET', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts, ResultListDataRepresentationRuntimeDecisionTableRepresentation); } /** * List the forms associated with a process definition * * * * @param processDefinitionId processDefinitionId * @return Promise<ResultListDataRepresentationRuntimeFormRepresentation> */ getProcessDefinitionForms(processDefinitionId: string): Promise<ResultListDataRepresentationRuntimeFormRepresentation> { throwIfNotDefined(processDefinitionId, 'processDefinitionId'); let postBody = null; let pathParams = { 'processDefinitionId': processDefinitionId }; let queryParams = {}; let headerParams = {}; let formParams = {}; let contentTypes = ['application/json']; let accepts = ['application/json']; return this.apiClient.callApi( '/api/enterprise/process-definitions/{processDefinitionId}/forms', 'GET', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts, ResultListDataRepresentationRuntimeFormRepresentation); } /** * Retrieve the start form for a process definition * * * @param processDefinitionId processDefinitionId * @return Promise<FormDefinitionRepresentation> */ getProcessDefinitionStartForm(processDefinitionId: string): Promise<FormDefinitionRepresentation> { let postBody = null; let pathParams = { 'processDefinitionId': processDefinitionId }; let queryParams = {}; let headerParams = {}; let formParams = {}; let contentTypes = ['application/json']; let accepts = ['application/json']; return this.apiClient.callApi( '/api/enterprise/process-definitions/{processDefinitionId}/start-form', 'GET', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts, FormDefinitionRepresentation); } /** * Retrieve a list of process definitions * * Get a list of process definitions (visible within the tenant of the user) * * @param opts Optional parameters * @param opts.latest latest * @param opts.appDefinitionId appDefinitionId * @param opts.deploymentId deploymentId * @return Promise<ResultListDataRepresentationProcessDefinitionRepresentation> */ getProcessDefinitions(opts?: any): Promise<ResultListDataRepresentationProcessDefinitionRepresentation> { opts = opts || {}; let postBody = null; let pathParams = {}; let queryParams = { 'latest': opts['latest'], 'appDefinitionId': opts['appDefinitionId'], 'deploymentId': opts['deploymentId'] }; let headerParams = {}; let formParams = {}; let contentTypes = ['application/json']; let accepts = ['application/json']; return this.apiClient.callApi( '/api/enterprise/process-definitions', 'GET', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts, ResultListDataRepresentationProcessDefinitionRepresentation); } /** * Retrieve field values (eg. the typeahead field) * * @param processDefinitionId processDefinitionId * * @return Promise<FormValueRepresentation[]> */ getRestFieldValues(processDefinitionId: string, field: string): Promise<FormValueRepresentation []> { let postBody = null; let pathParams = { 'processDefinitionId': processDefinitionId, 'field': field }; let queryParams = {}; let headerParams = {}; let formParams = {}; let contentTypes = ['application/json']; let accepts = ['application/json']; return this.apiClient.callApi( '/api/enterprise/process-definitions/{processDefinitionId}/start-form-values/{field}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts, FormValueRepresentation); } /** * Retrieve field values (eg. the table field) * * @param processDefinitionId processDefinitionId * * @return Promise<FormValueRepresentation []> */ getRestTableFieldValues(processDefinitionId: string, field: string, column: string): Promise<FormValueRepresentation []> { let postBody = null; let pathParams = { 'processDefinitionId': processDefinitionId, 'field': field, 'column': column }; let queryParams = {}; let headerParams = {}; let formParams = {}; let contentTypes = ['application/json']; let accepts = ['application/json']; return this.apiClient.callApi( '/api/enterprise/process-definitions/{processDefinitionId}/start-form-values/{field}/{column}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts, FormValueRepresentation); } }
the_stack
import { Benchmark, BenchmarkType, convertToMap, DisplayMode, Framework, FrameworkType, RawResult, Result, ResultTableData, SORT_BY_GEOMMEAN_CPU, categories } from "./Common" import {benchmarks as benchmark_orig, frameworks, results as rawResults} from './results'; // Temporarily disable script bootup time const benchmarks = benchmark_orig.filter(b => b.id!=='32_startup-bt'); // eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-var-requires const jStat: any = require('jStat').jStat; const results: Result[] = (rawResults as RawResult[]).map(res => Object.assign(({framework: res.f, benchmark: res.b, values: res.v}), {mean: res.v ? jStat.mean(res.v) : Number.NaN, median: res.v ? jStat.median(res.v) : Number.NaN, standardDeviation: res.v ? jStat.stdev(res.v, true): Number.NaN})); const removeKeyedSuffix = (value: string) => { if (value.endsWith('-non-keyed')) return value.substring(0,value.length-10) else if (value.endsWith('-keyed')) return value.substring(0,value.length-6) return value; } const mappedFrameworks = frameworks.map(f => ({name: f.name, displayname: removeKeyedSuffix(f.name), issues: f.issues ?? [], type:f.keyed ? FrameworkType.KEYED : FrameworkType.NON_KEYED})); const allBenchmarks = benchmarks.reduce((set, b) => set.add(b), new Set<Benchmark>() ); const allFrameworks = mappedFrameworks.reduce((set, f) => set.add(f), new Set<Framework>() ); const resultLookup = convertToMap(results); interface BenchmarkLists { [idx: number]: Benchmark[]; } interface FrameworkLists { [idx: number]: Framework[]; } interface ResultTables { [idx: number]: ResultTableData|undefined; } interface CompareWith { [idx: number]: Framework|undefined; } export interface State { benchmarkLists: BenchmarkLists; frameworkLists: FrameworkLists; benchmarks: Array<Benchmark>; frameworks: Array<Framework>; selectedBenchmarks: Set<Benchmark>; selectedFrameworksDropDown: Set<Framework>; resultTables: ResultTables; sortKey: string; displayMode: DisplayMode; compareWith: CompareWith; categories: Set<number>; } export const areAllBenchmarksSelected = (state: State, type: BenchmarkType) => state.benchmarkLists[type].every(b => state.selectedBenchmarks.has(b)) export const isNoneBenchmarkSelected = (state: State, type: BenchmarkType) => state.benchmarkLists[type].every(b => !state.selectedBenchmarks.has(b)) export const areAllFrameworksSelected = (state: State, type: FrameworkType) => state.frameworkLists[type].every(f => state.selectedFrameworksDropDown.has(f)) export const isNoneFrameworkSelected = (state: State, type: FrameworkType) => state.frameworkLists[type].every(f => !state.selectedFrameworksDropDown.has(f)) const preInitialState: State = { // static benchmarks: benchmarks, benchmarkLists: { [BenchmarkType.CPU]: benchmarks.filter(b => b.type === BenchmarkType.CPU), [BenchmarkType.MEM]: benchmarks.filter(b => b.type === BenchmarkType.MEM), [BenchmarkType.STARTUP]: benchmarks.filter(b => b.type === BenchmarkType.STARTUP) }, frameworks: mappedFrameworks, frameworkLists: { [FrameworkType.KEYED]: mappedFrameworks.filter(f => f.type === FrameworkType.KEYED), [FrameworkType.NON_KEYED]: mappedFrameworks.filter(f => f.type === FrameworkType.NON_KEYED), }, // dynamic selectedBenchmarks: allBenchmarks, selectedFrameworksDropDown: allFrameworks, sortKey: SORT_BY_GEOMMEAN_CPU, displayMode: DisplayMode.DisplayMedian, resultTables: { [FrameworkType.KEYED]: undefined, [FrameworkType.NON_KEYED]: undefined }, compareWith: { [FrameworkType.KEYED]: undefined, [FrameworkType.NON_KEYED]: undefined }, categories: new Set([1,2,3,4]) } function updateResultTable({frameworks, benchmarks, selectedFrameworksDropDown: selectedFrameworks, selectedBenchmarks, sortKey, displayMode, compareWith, categories}: State) { return { [FrameworkType.KEYED]: new ResultTableData(frameworks, benchmarks, resultLookup, selectedFrameworks, selectedBenchmarks, FrameworkType.KEYED, sortKey, displayMode, compareWith[FrameworkType.KEYED], categories), [FrameworkType.NON_KEYED]: new ResultTableData(frameworks, benchmarks, resultLookup, selectedFrameworks, selectedBenchmarks, FrameworkType.NON_KEYED, sortKey, displayMode, compareWith[FrameworkType.NON_KEYED], categories) } } const initialState: State = { ...preInitialState, resultTables: updateResultTable(preInitialState) } interface SelectFrameworkAction { type: 'SELECT_FRAMEWORK'; data: {framework: Framework; add: boolean}} export const selectFramework = (framework: Framework, add: boolean): SelectFrameworkAction => { return {type: 'SELECT_FRAMEWORK', data: {framework, add}} } interface SelectAllFrameworksAction { type: 'SELECT_ALL_FRAMEWORKS'; data: {frameworkType: FrameworkType; add: boolean}} export const selectAllFrameworks = (frameworkType: FrameworkType, add: boolean): SelectAllFrameworksAction => { return {type: 'SELECT_ALL_FRAMEWORKS', data: {frameworkType, add}} } interface SelectCategoryAction { type: 'SELECT_CATEGORY'; data: {categoryId: number; add: boolean}} export const selectCategory = (categoryId: number, add: boolean): SelectCategoryAction => { return {type: 'SELECT_CATEGORY', data: {categoryId, add}} } interface SelectAllCategoriesAction { type: 'SELECT_ALL_CATEGORIES'; data: {add: boolean}} export const selectAllCategories = (add: boolean): SelectAllCategoriesAction => { return {type: 'SELECT_ALL_CATEGORIES', data: {add}} } interface SelectBenchmarkAction { type: 'SELECT_BENCHMARK'; data: {benchmark: Benchmark; add: boolean}} export const selectBenchmark = (benchmark: Benchmark, add: boolean): SelectBenchmarkAction => { return {type: 'SELECT_BENCHMARK', data: {benchmark, add}} } interface SelectAllBenchmarksAction { type: 'SELECT_ALL_BENCHMARKS'; data: {benchmarkType: BenchmarkType; add: boolean}} export const selectAllBenchmarks = (benchmarkType: BenchmarkType, add: boolean): SelectAllBenchmarksAction => { return {type: 'SELECT_ALL_BENCHMARKS', data: {benchmarkType, add}} } interface SelectDisplayModeAction { type: 'SELECT_DISPLAYMODE'; data: {displayMode: DisplayMode}} export const selectDisplayMode = (displayMode: DisplayMode): SelectDisplayModeAction => { return {type: 'SELECT_DISPLAYMODE', data: {displayMode}} } interface CompareAction { type: 'COMPARE'; data: {framework: Framework}} export const compare = (framework: Framework): CompareAction => { return {type: 'COMPARE', data: {framework}} } interface StopCompareAction { type: 'STOP_COMPARE'; data: {framework: Framework}} export const stopCompare = (framework: Framework): StopCompareAction => { return {type: 'STOP_COMPARE', data: {framework}} } interface SortAction { type: 'SORT'; data: {sortKey: string}} export const sort = (sortKey: string): SortAction => { return {type: 'SORT', data: {sortKey}} } type Action = SelectFrameworkAction | SelectAllFrameworksAction | SelectBenchmarkAction | SelectAllBenchmarksAction | SelectDisplayModeAction | CompareAction |StopCompareAction | SortAction | SelectCategoryAction | SelectAllCategoriesAction; // eslint-disable-next-line @typescript-eslint/no-explicit-any export const reducer = (state = initialState, action: Action): State => { console.log("reducer", action) switch (action.type) { case 'SELECT_FRAMEWORK': { const newSelectedFramework = new Set(state.selectedFrameworksDropDown); if (action.data.add) newSelectedFramework.add(action.data.framework); else newSelectedFramework.delete(action.data.framework); const t = {...state, selectedFrameworksDropDown: newSelectedFramework}; return {...t, resultTables: updateResultTable(t)}; } case 'SELECT_ALL_FRAMEWORKS': { const newSelectedFramework = new Set(state.selectedFrameworksDropDown); for (const f of (action.data.frameworkType === FrameworkType.KEYED ? state.frameworkLists[FrameworkType.KEYED] : state.frameworkLists[FrameworkType.NON_KEYED])) { if (action.data.add) newSelectedFramework.add(f); else newSelectedFramework.delete(f); } const t = {...state, selectedFrameworksDropDown: newSelectedFramework}; return {...t, resultTables: updateResultTable(t)}; } case 'SELECT_BENCHMARK': { const newSelectedBenchmark = new Set(state.selectedBenchmarks); if (action.data.add) newSelectedBenchmark.add(action.data.benchmark); else newSelectedBenchmark.delete(action.data.benchmark); const t = {...state, selectedBenchmarks: newSelectedBenchmark}; return {...t, resultTables: updateResultTable(t)}; } case 'SELECT_ALL_BENCHMARKS': { const newSelectedBenchmark = new Set(state.selectedBenchmarks); // action.data.benchmarkType for (const b of state.benchmarkLists[BenchmarkType.CPU]) { if (action.data.add) newSelectedBenchmark.add(b) else newSelectedBenchmark.delete(b) } const t = {...state, selectedBenchmarks: newSelectedBenchmark} return {...t, resultTables: updateResultTable(t)} } case 'SELECT_DISPLAYMODE': { const t = {...state, displayMode: action.data.displayMode}; return {...t, resultTables: updateResultTable(t)}; } case 'COMPARE': { const compareWith = {...state.compareWith}; compareWith[action.data.framework.type] = action.data.framework; const t = {...state, compareWith: compareWith}; return {...t, resultTables: updateResultTable(t)}; } case 'STOP_COMPARE': { const compareWith = {...state.compareWith}; compareWith[action.data.framework.type] = undefined; const t = {...state, compareWith: compareWith}; return {...t, resultTables: updateResultTable(t)}; } case 'SORT': { const t = {...state, sortKey: action.data.sortKey}; return {...t, resultTables: updateResultTable(t)}; } case 'SELECT_CATEGORY': { const categories = new Set(state.categories); if (action.data.add) { categories.add(action.data.categoryId); } else { categories.delete(action.data.categoryId); } const t = {...state, categories}; return {...t, resultTables: updateResultTable(t)}; } case 'SELECT_ALL_CATEGORIES': { const newCategories = (action.data.add) ? new Set(categories.map(c => c.id)) : new Set<number>(); const t = {...state, categories: newCategories}; return {...t, resultTables: updateResultTable(t)}; } default: return state; } }
the_stack
namespace colibri.ui.controls.viewers { export const TREE_ICON_SIZE = RENDER_ICON_SIZE; export const LABEL_MARGIN = TREE_ICON_SIZE + 0; export declare type TreeIconInfo = { rect: Rect, obj: any }; export class TreeViewer extends Viewer { private _treeRenderer: TreeViewerRenderer; private _treeIconList: TreeIconInfo[]; constructor(id: string, ...classList: string[]) { super(id, "TreeViewer", ...classList); this.getCanvas().addEventListener("click", e => this.onClick(e)); this._treeRenderer = new TreeViewerRenderer(this); this._treeIconList = []; this.setContentProvider(new controls.viewers.EmptyTreeContentProvider()); } expandRoots(repaint = true) { const roots = this.getContentProvider().getRoots(this.getInput()); for (const root of roots) { this.setExpanded(root, true); } if (repaint) { this.repaint(); } } setExpandWhenOpenParentItem() { this.eventOpenItem.addListener(obj => { if (this.getContentProvider().getChildren(obj).length > 0) { this.setExpanded(obj, !this.isExpanded(obj)); this.repaint(); } }); } async expandCollapseBranch() { const obj = this.getSelectionFirstElement(); if (obj) { const children = this.getContentProvider().getChildren(obj); if (children.length > 0) { this.setExpanded(obj, !this.isExpanded(obj)); this.repaint(); } else { const path = this.getObjectPath(obj); // pop obj path.pop(); // pop parent const parent = path.pop(); if (parent) { await this.reveal(parent); this.setExpanded(parent, false); this.setSelection([parent]); } } } } getTreeRenderer() { return this._treeRenderer; } setTreeRenderer(treeRenderer: TreeViewerRenderer): void { this._treeRenderer = treeRenderer; } canSelectAtPoint(e: MouseEvent) { const icon = this.getTreeIconAtPoint(e); return icon === null; } async revealAndSelect(...objects: any[]): Promise<void> { await this.reveal(...objects); this.setSelection(objects); } async reveal(...objects: any[]): Promise<void> { if (objects.length === 0) { return; } for (const obj of objects) { const path = this.getObjectPath(obj); this.revealPath(path); } try { if (!(this.getContainer().getContainer() instanceof ScrollPane)) { return; } } catch (e) { return; } const scrollPane = this.getContainer().getContainer() as ScrollPane; const paintResult = this.getTreeRenderer().paint(true); const objSet = new Set(objects); let found = false; let y = -this._contentHeight; const b = this.getBounds(); const items = paintResult.paintItems; items.sort((i1, i2) => i1.y - i2.y); for (const item of items) { if (objSet.has(item.data)) { y = (item.y - b.height / 2 + item.h / 2) - this.getScrollY(); found = true; break; } } if (found) { this.setScrollY(-y); this.repaint(); scrollPane.layout(); } } private revealPath(path: any[]) { for (let i = 0; i < path.length - 1; i++) { this.setExpanded(path[i], true); } } findElementByLabel(label: string) { const list = this.getContentProvider().getRoots(this.getInput()); return this.findElementByLabel_inList(list, label); } private findElementByLabel_inList(list: any[], label: string) { if (list) { for (const child of list) { const found = this.findElementByLabel_inElement(child, label); if (found) { return found; } } } return undefined; } private findElementByLabel_inElement(elem: any, label: string) { const elemLabel = this.getLabelProvider().getLabel(elem); if (label === elemLabel) { return elem; } const list = this.getContentProvider().getChildren(elem); return this.findElementByLabel_inList(list, label); } getObjectPath(obj: any) { const list = this.getContentProvider().getRoots(this.getInput()); const path = []; this.getObjectPath2(obj, path, list); return path; } private getObjectPath2(obj: any, path: any[], children: any[]): boolean { const contentProvider = this.getContentProvider(); for (const child of children) { path.push(child); if (obj === child) { return true; } const newChildren = contentProvider.getChildren(child); const found = this.getObjectPath2(obj, path, newChildren); if (found) { return true; } path.pop(); } return false; } private getTreeIconAtPoint(e: MouseEvent) { for (const icon of this._treeIconList) { if (icon.rect.contains(e.offsetX, e.offsetY)) { return icon; } } return null; } private onClick(e: MouseEvent) { const icon = this.getTreeIconAtPoint(e); if (icon) { this.setExpanded(icon.obj, !this.isExpanded(icon.obj)); this.repaint(); } } visitObjects(visitor: (obj: any) => void) { const provider = this.getContentProvider(); const list = provider ? provider.getRoots(this.getInput()) : []; this.visitObjects2(list, visitor); } private visitObjects2(objects: any[], visitor: (obj: any) => void) { for (const obj of objects) { visitor(obj); if (this.isExpanded(obj) || this.getFilterText() !== "") { const list = this.getContentProvider().getChildren(obj); this.visitObjects2(list, visitor); } } } protected paint(fullPaint: boolean): void { const result = this._treeRenderer.paint(fullPaint); this._contentHeight = result.contentHeight; this._paintItems = result.paintItems; this._treeIconList = result.treeIconList; } getFirstVisibleElement() { if (this._paintItems && this._paintItems.length > 0) { return this._paintItems[0].data; } } getVisibleElements() { if (this._paintItems) { return this._paintItems.map(item => item.data); } return []; } setFilterText(filter: string) { super.setFilterText(filter); this.maybeFilter(); } private _filterTime = 0; private _token = 0; private _delayOnManyChars = 100; private _delayOnFewChars = 200; private _howMuchIsFewChars = 3; setFilterDelay(delayOnManyChars: number, delayOnFewChars: number, howMuchIsFewChars: number) { this._delayOnManyChars = delayOnManyChars; this._delayOnFewChars = delayOnFewChars; this._howMuchIsFewChars = howMuchIsFewChars; } private maybeFilter() { const now = Date.now(); const count = this.getFilterText().length; const delay = count <= this._howMuchIsFewChars ? this._delayOnFewChars : this._delayOnManyChars; if (now - this._filterTime > delay) { this._filterTime = now; this._token++; this.filterNow(); } else { const token = this._token; requestAnimationFrame(() => { if (token === this._token) { this.maybeFilter(); } }); } } private filterNow() { this.prepareFiltering(true); if (this.getFilterText().length > 0) { this.expandFilteredParents(this.getContentProvider().getRoots(this.getInput())); } this.repaint(); } private expandFilteredParents(objects: any[]): void { const contentProvider = this.getContentProvider(); for (const obj of objects) { if (this.isFilterIncluded(obj)) { const children = contentProvider.getChildren(obj); if (children.length > 0) { this.setExpanded(obj, true); this.expandFilteredParents(children); } } } } protected buildFilterIncludeMap() { const provider = this.getContentProvider(); const roots = provider ? provider.getRoots(this.getInput()) : []; this.buildFilterIncludeMap2(roots); } private buildFilterIncludeMap2(objects: any[]): boolean { let result = false; for (const obj of objects) { let resultThis = this.matches(obj); const children = this.getContentProvider().getChildren(obj); const resultChildren = this.buildFilterIncludeMap2(children); resultThis = resultThis || resultChildren; if (resultThis) { this._filterIncludeSet.add(obj); result = true; } } return result; } getContentProvider(): ITreeContentProvider { return super.getContentProvider() as ITreeContentProvider; } } }
the_stack
import * as spec from '@jsii/spec'; import * as clone from 'clone'; import { toSnakeCase } from 'codemaker/lib/case-utils'; import * as fs from 'fs-extra'; import * as reflect from 'jsii-reflect'; import { Rosetta, TargetLanguage, enforcesStrictMode, markDownToJavaDoc, ApiLocation, } from 'jsii-rosetta'; import * as path from 'path'; import * as xmlbuilder from 'xmlbuilder'; import { TargetBuilder, BuildOptions } from '../builder'; import { Generator } from '../generator'; import * as logging from '../logging'; import { jsiiToPascalCase } from '../naming-util'; import { JsiiModule } from '../packaging'; import { PackageInfo, Target, findLocalBuildDirs, TargetOptions, } from '../target'; import { shell, Scratch, slugify, setExtend } from '../util'; import { VERSION, VERSION_DESC } from '../version'; import { stabilityPrefixFor, renderSummary } from './_utils'; import { toMavenVersionRange, toReleaseVersion } from './version-utils'; import { TargetName } from './index'; // eslint-disable-next-line @typescript-eslint/no-var-requires,@typescript-eslint/no-require-imports const spdxLicenseList = require('spdx-license-list'); const BUILDER_CLASS_NAME = 'Builder'; const ANN_NOT_NULL = '@org.jetbrains.annotations.NotNull'; const ANN_NULLABLE = '@org.jetbrains.annotations.Nullable'; const ANN_INTERNAL = '@software.amazon.jsii.Internal'; /** * Build Java packages all together, by generating an aggregate POM * * This will make the Java build a lot more efficient (~300%). * * Do this by copying the code into a temporary directory, generating an aggregate * POM there, and then copying the artifacts back into the respective output * directories. */ export class JavaBuilder implements TargetBuilder { private readonly targetName = 'java'; public constructor( private readonly modules: readonly JsiiModule[], private readonly options: BuildOptions, ) {} public async buildModules(): Promise<void> { if (this.modules.length === 0) { return; } if (this.options.codeOnly) { // Simple, just generate code to respective output dirs await Promise.all( this.modules.map((module) => this.generateModuleCode( module, this.options, this.outputDir(module.outputDirectory), ), ), ); return; } // Otherwise make a single tempdir to hold all sources, build them together and copy them back out const scratchDirs: Array<Scratch<any>> = []; try { const tempSourceDir = await this.generateAggregateSourceDir( this.modules, this.options, ); scratchDirs.push(tempSourceDir); // Need any old module object to make a target to be able to invoke build, though none of its settings // will be used. const target = this.makeTarget(this.modules[0], this.options); const tempOutputDir = await Scratch.make(async (dir) => { logging.debug(`Building Java code to ${dir}`); await target.build(tempSourceDir.directory, dir); }); scratchDirs.push(tempOutputDir); await this.copyOutArtifacts( tempOutputDir.directory, tempSourceDir.object, ); if (this.options.clean) { await Scratch.cleanupAll(scratchDirs); } } catch (e) { logging.warn( `Exception occurred, not cleaning up ${scratchDirs .map((s) => s.directory) .join(', ')}`, ); throw e; } } private async generateModuleCode( module: JsiiModule, options: BuildOptions, where: string, ): Promise<void> { const target = this.makeTarget(module, options); logging.debug(`Generating Java code into ${where}`); await target.generateCode(where, module.tarball); } private async generateAggregateSourceDir( modules: readonly JsiiModule[], options: BuildOptions, ): Promise<Scratch<TemporaryJavaPackage[]>> { return Scratch.make(async (tmpDir: string) => { logging.debug(`Generating aggregate Java source dir at ${tmpDir}`); const ret: TemporaryJavaPackage[] = []; const generatedModules = modules .map((module) => ({ module, relativeName: slugify(module.name) })) .map(({ module, relativeName }) => ({ module, relativeName, sourceDir: path.join(tmpDir, relativeName), })) .map(({ module, relativeName, sourceDir }) => this.generateModuleCode(module, options, sourceDir).then(() => ({ module, relativeName, })), ); for await (const { module, relativeName } of generatedModules) { ret.push({ relativeSourceDir: relativeName, relativeArtifactsDir: moduleArtifactsSubdir(module), outputTargetDirectory: module.outputDirectory, }); } await this.generateAggregatePom( tmpDir, ret.map((m) => m.relativeSourceDir), ); await this.generateMavenSettingsForLocalDeps(tmpDir); return ret; }); } private async generateAggregatePom(where: string, moduleNames: string[]) { const aggregatePom = xmlbuilder .create( { project: { '@xmlns': 'http://maven.apache.org/POM/4.0.0', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd', '#comment': [ `Generated by jsii-pacmak@${VERSION_DESC} on ${new Date().toISOString()}`, ], modelVersion: '4.0.0', packaging: 'pom', groupId: 'software.amazon.jsii', artifactId: 'aggregatepom', version: '1.0.0', modules: { module: moduleNames, }, }, }, { encoding: 'UTF-8' }, ) .end({ pretty: true }); logging.debug(`Generated ${where}/pom.xml`); await fs.writeFile(path.join(where, 'pom.xml'), aggregatePom); } private async copyOutArtifacts( artifactsRoot: string, packages: TemporaryJavaPackage[], ) { logging.debug('Copying out Java artifacts'); // The artifacts directory looks like this: // /tmp/XXX/software/amazon/awscdk/something/v1.2.3 // /else/v1.2.3 // /entirely/v1.2.3 // // We get the 'software/amazon/awscdk/something' path from the package, identifying // the files we need to copy, including Maven metadata. But we need to recreate // the whole path in the target directory. await Promise.all( packages.map(async (pkg) => { const artifactsSource = path.join( artifactsRoot, pkg.relativeArtifactsDir, ); const artifactsDest = path.join( this.outputDir(pkg.outputTargetDirectory), pkg.relativeArtifactsDir, ); await fs.mkdirp(artifactsDest); await fs.copy(artifactsSource, artifactsDest, { recursive: true }); }), ); } /** * Decide whether or not to append 'java' to the given output directory */ private outputDir(declaredDir: string) { return this.options.languageSubdirectory ? path.join(declaredDir, this.targetName) : declaredDir; } /** * Generates maven settings file for this build. * @param where The generated sources directory. This is where user.xml will be placed. * @param currentOutputDirectory The current output directory. Will be added as a local maven repo. */ private async generateMavenSettingsForLocalDeps(where: string) { const filePath = path.join(where, 'user.xml'); // traverse the dep graph of this module and find all modules that have // an <outdir>/java directory. we will add those as local maven // repositories which will resolve instead of Maven Central for those // module. this enables building against local modules (i.e. in lerna // repositories or linked modules). const allDepsOutputDirs = new Set<string>(); const resolvedModules = this.modules.map(async (mod) => ({ module: mod, localBuildDirs: await findLocalBuildDirs( mod.moduleDirectory, this.targetName, ), })); for await (const { module, localBuildDirs } of resolvedModules) { setExtend(allDepsOutputDirs, localBuildDirs); // Also include output directory where we're building to, in case we build multiple packages into // the same output directory. allDepsOutputDirs.add( path.join( module.outputDirectory, this.options.languageSubdirectory ? this.targetName : '', ), ); } const localRepos = Array.from(allDepsOutputDirs); // if java-runtime is checked-out and we can find a local repository, // add it to the list. const localJavaRuntime = await findJavaRuntimeLocalRepository(); if (localJavaRuntime) { localRepos.push(localJavaRuntime); } logging.debug('local maven repos:', localRepos); const profileName = 'local-jsii-modules'; const settings = xmlbuilder .create( { settings: { '@xmlns': 'http://maven.apache.org/POM/4.0.0', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd', '#comment': [ `Generated by jsii-pacmak@${VERSION_DESC} on ${new Date().toISOString()}`, ], // Do *not* attempt to ask the user for stuff... interactiveMode: false, // Use a non-default local repository to isolate from cached artifacts... localRepository: path.resolve(where, '.m2', 'repository'), // Register locations of locally-sourced dependencies profiles: { profile: { id: profileName, repositories: { repository: localRepos.map((repo) => ({ id: repo.replace(/[\\/:"<>|?*]/g, '$'), url: `file://${repo}`, })), }, }, }, activeProfiles: { activeProfile: profileName, }, }, }, { encoding: 'UTF-8' }, ) .end({ pretty: true }); logging.debug(`Generated ${filePath}`); await fs.writeFile(filePath, settings); return filePath; } private makeTarget(module: JsiiModule, options: BuildOptions): Target { return new Java({ targetName: this.targetName, packageDir: module.moduleDirectory, assembly: module.assembly, fingerprint: options.fingerprint, force: options.force, arguments: options.arguments, rosetta: options.rosetta, }); } } interface TemporaryJavaPackage { /** * Where the sources are (relative to the source root) */ relativeSourceDir: string; /** * Where the artifacts will be stored after build (relative to build dir) */ relativeArtifactsDir: string; /** * Where the artifacts ought to go for this particular module */ outputTargetDirectory: string; } /** * Return the subdirectory of the output directory where the artifacts for this particular package are produced */ function moduleArtifactsSubdir(module: JsiiModule) { const groupId = module.assembly.targets!.java!.maven.groupId; const artifactId = module.assembly.targets!.java!.maven.artifactId; return `${groupId.replace(/\./g, '/')}/${artifactId}`; } export default class Java extends Target { public static toPackageInfos(assm: spec.Assembly): { [language: string]: PackageInfo; } { const groupId = assm.targets!.java!.maven.groupId; const artifactId = assm.targets!.java!.maven.artifactId; const releaseVersion = toReleaseVersion(assm.version, TargetName.JAVA); const url = `https://repo1.maven.org/maven2/${groupId.replace( /\./g, '/', )}/${artifactId}/${assm.version}/`; return { java: { repository: 'Maven Central', url, usage: { 'Apache Maven': { language: 'xml', code: xmlbuilder .create({ dependency: { groupId, artifactId, version: releaseVersion }, }) .end({ pretty: true }) .replace(/<\?\s*xml(\s[^>]+)?>\s*/m, ''), }, 'Apache Buildr': `'${groupId}:${artifactId}:jar:${releaseVersion}'`, 'Apache Ivy': { language: 'xml', code: xmlbuilder .create({ dependency: { '@groupId': groupId, '@name': artifactId, '@rev': releaseVersion, }, }) .end({ pretty: true }) .replace(/<\?\s*xml(\s[^>]+)?>\s*/m, ''), }, 'Groovy Grape': `@Grapes(\n@Grab(group='${groupId}', module='${artifactId}', version='${releaseVersion}')\n)`, 'Gradle / Grails': `compile '${groupId}:${artifactId}:${releaseVersion}'`, }, }, }; } public static toNativeReference(type: spec.Type, options: any) { const [, ...name] = type.fqn.split('.'); return { java: `import ${[options.package, ...name].join('.')};` }; } protected readonly generator: JavaGenerator; public constructor(options: TargetOptions) { super(options); this.generator = new JavaGenerator(options.rosetta); } public async build(sourceDir: string, outDir: string): Promise<void> { const url = `file://${outDir}`; const mvnArguments = new Array<string>(); for (const arg of Object.keys(this.arguments)) { if (!arg.startsWith('mvn-')) { continue; } mvnArguments.push(`--${arg.slice(4)}`); mvnArguments.push(this.arguments[arg].toString()); } await shell( 'mvn', [ // If we don't run in verbose mode, turn on quiet mode ...(this.arguments.verbose ? [] : ['--quiet']), '--batch-mode', ...mvnArguments, 'deploy', `-D=altDeploymentRepository=local::default::${url}`, '--settings=user.xml', ], { cwd: sourceDir, env: { // Twiddle the JVM settings a little for Maven. Delaying JIT compilation // brings down Maven execution time by about 1/3rd (15->10s, 30->20s) MAVEN_OPTS: `${ process.env.MAVEN_OPTS ?? '' } -XX:+TieredCompilation -XX:TieredStopAtLevel=1`, }, retry: { maxAttempts: 5 }, }, ); } } // ################## // # CODE GENERATOR # // ################## const MODULE_CLASS_NAME = '$Module'; const INTERFACE_PROXY_CLASS_NAME = 'Jsii$Proxy'; const INTERFACE_DEFAULT_CLASS_NAME = 'Jsii$Default'; // Struct that stores metadata about a property that can be used in Java code generation. interface JavaProp { // Documentation for the property docs?: spec.Docs; // The original JSII property spec this struct was derived from spec: spec.Property; // The original JSII type this property was defined on definingType: spec.Type; // Canonical name of the Java property (eg: 'MyProperty') propName: string; // The original canonical name of the JSII property jsiiName: string; // Field name of the Java property (eg: 'myProperty') fieldName: string; // The java type for the property (eg: 'List<String>') fieldJavaType: string; // The java type for the parameter (e.g: 'List<? extends SomeType>') paramJavaType: string; // The NativeType representation of the property's type fieldNativeType: string; // The raw class type of the property that can be used for marshalling (eg: 'List.class') fieldJavaClass: string; // List of types that the property is assignable from. Used to overload setters. javaTypes: string[]; // True if the property is optional. nullable: boolean; // True if the property has been transitively inherited from a base class. inherited: boolean; // True if the property is read-only once initialized. immutable: boolean; } class JavaGenerator extends Generator { // When the code-generator needs to generate code for a property or method that has the same name as a member of this list, the name will // be automatically modified to avoid compile errors. Most of these are java language reserved keywords. In addition to those, any keywords that // are likely to conflict with auto-generated methods or properties (eg: 'build') are also considered reserved. private static readonly RESERVED_KEYWORDS = [ 'abstract', 'assert', 'boolean', 'break', 'build', 'byte', 'case', 'catch', 'char', 'class', 'const', 'continue', 'default', 'double', 'do', 'else', 'enum', 'extends', 'false', 'final', 'finally', 'float', 'for', 'goto', 'if', 'implements', 'import', 'instanceof', 'int', 'interface', 'long', 'native', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'short', 'static', 'strictfp', 'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'true', 'try', 'void', 'volatile', 'while', ]; /** * Turns a raw javascript property name (eg: 'default') into a safe Java property name (eg: 'defaultValue'). * @param propertyName the raw JSII property Name */ private static safeJavaPropertyName(propertyName: string) { if (!propertyName) { return propertyName; } if (JavaGenerator.RESERVED_KEYWORDS.includes(propertyName)) { return `${propertyName}Value`; } return propertyName; } /** * Turns a raw javascript method name (eg: 'import') into a safe Java method name (eg: 'doImport'). * @param methodName */ private static safeJavaMethodName(methodName: string) { if (!methodName) { return methodName; } if (JavaGenerator.RESERVED_KEYWORDS.includes(methodName)) { return `do${jsiiToPascalCase(methodName)}`; } return methodName; } /** If false, @Generated will not include generator version nor timestamp */ private emitFullGeneratorInfo?: boolean; private moduleClass!: string; /** * A map of all the modules ever referenced during code generation. These include * direct dependencies but can potentially also include transitive dependencies, when, * for example, we need to refer to their types when flatting the class hierarchy for * interface proxies. */ private readonly referencedModules: { [name: string]: spec.AssemblyConfiguration; } = {}; public constructor(private readonly rosetta: Rosetta) { super({ generateOverloadsForMethodWithOptionals: true }); } protected onBeginAssembly(assm: spec.Assembly, fingerprint: boolean) { this.emitFullGeneratorInfo = fingerprint; this.moduleClass = this.emitModuleFile(assm); this.emitAssemblyPackageInfo(assm); } protected onEndAssembly(assm: spec.Assembly, fingerprint: boolean) { this.emitMavenPom(assm, fingerprint); delete this.emitFullGeneratorInfo; } protected getAssemblyOutputDir(mod: spec.Assembly) { const dir = this.toNativeFqn(mod.name).replace(/\./g, '/'); return path.join('src', 'main', 'resources', dir); } protected onBeginClass(cls: spec.ClassType, abstract: boolean) { this.openFileIfNeeded(cls); this.addJavaDocs(cls, { api: 'type', fqn: cls.fqn }); const classBase = this.getClassBase(cls); const extendsExpression = classBase ? ` extends ${classBase}` : ''; let implementsExpr = ''; if (cls.interfaces?.length ?? 0 > 0) { implementsExpr = ` implements ${cls .interfaces!.map((x) => this.toNativeFqn(x)) .join(', ')}`; } const nested = this.isNested(cls); const inner = nested ? ' static' : ''; const absPrefix = abstract ? ' abstract' : ''; if (!nested) { this.emitGeneratedAnnotation(); } this.emitStabilityAnnotations(cls); this.code.line( `@software.amazon.jsii.Jsii(module = ${this.moduleClass}.class, fqn = "${cls.fqn}")`, ); this.code.openBlock( `public${inner}${absPrefix} class ${cls.name}${extendsExpression}${implementsExpr}`, ); this.emitJsiiInitializers(cls); this.emitStaticInitializer(cls); } protected onEndClass(cls: spec.ClassType) { if (cls.abstract) { const type = this.reflectAssembly.findType(cls.fqn) as reflect.ClassType; this.emitProxy(type); } else { this.emitClassBuilder(cls); } this.code.closeBlock(); this.closeFileIfNeeded(cls); } protected onInitializer(cls: spec.ClassType, method: spec.Initializer) { this.code.line(); // If needed, patching up the documentation to point users at the builder pattern this.addJavaDocs(method, { api: 'initializer', fqn: cls.fqn }); this.emitStabilityAnnotations(method); // Abstract classes should have protected initializers const initializerAccessLevel = cls.abstract ? 'protected' : this.renderAccessLevel(method); this.code.openBlock( `${initializerAccessLevel} ${cls.name}(${this.renderMethodParameters( method, )})`, ); this.code.line( 'super(software.amazon.jsii.JsiiObject.InitializationMode.JSII);', ); this.code.line( `software.amazon.jsii.JsiiEngine.getInstance().createNewObject(this${this.renderMethodCallArguments( method, )});`, ); this.code.closeBlock(); } protected onInitializerOverload( cls: spec.ClassType, overload: spec.Method, _originalInitializer: spec.Method, ) { this.onInitializer(cls, overload); } protected onField( _cls: spec.ClassType, _prop: spec.Property, _union?: spec.UnionTypeReference, ) { /* noop */ } protected onProperty(cls: spec.ClassType, prop: spec.Property) { this.emitProperty(cls, prop, cls); } protected onStaticProperty(cls: spec.ClassType, prop: spec.Property) { if (prop.const) { this.emitConstProperty(cls, prop); } else { this.emitProperty(cls, prop, cls); } } /** * Since we expand the union setters, we will use this event to only emit the getter which returns an Object. */ protected onUnionProperty( cls: spec.ClassType, prop: spec.Property, _union: spec.UnionTypeReference, ) { this.emitProperty(cls, prop, cls); } protected onMethod(cls: spec.ClassType, method: spec.Method) { this.emitMethod(cls, method); } protected onMethodOverload( cls: spec.ClassType, overload: spec.Method, _originalMethod: spec.Method, ) { this.onMethod(cls, overload); } protected onStaticMethod(cls: spec.ClassType, method: spec.Method) { this.emitMethod(cls, method); } protected onStaticMethodOverload( cls: spec.ClassType, overload: spec.Method, _originalMethod: spec.Method, ) { this.emitMethod(cls, overload); } protected onBeginEnum(enm: spec.EnumType) { this.openFileIfNeeded(enm); this.addJavaDocs(enm, { api: 'type', fqn: enm.fqn }); if (!this.isNested(enm)) { this.emitGeneratedAnnotation(); } this.emitStabilityAnnotations(enm); this.code.line( `@software.amazon.jsii.Jsii(module = ${this.moduleClass}.class, fqn = "${enm.fqn}")`, ); this.code.openBlock(`public enum ${enm.name}`); } protected onEndEnum(enm: spec.EnumType) { this.code.closeBlock(); this.closeFileIfNeeded(enm); } protected onEnumMember(parentType: spec.EnumType, member: spec.EnumMember) { this.addJavaDocs(member, { api: 'member', fqn: parentType.fqn, memberName: member.name, }); this.emitStabilityAnnotations(member); this.code.line(`${member.name},`); } /** * Namespaces are handled implicitly by onBeginClass(). * * Only emit package-info in case this is a submodule */ protected onBeginNamespace(ns: string) { const submodule = this.assembly.submodules?.[ns]; if (submodule) { this.emitSubmodulePackageInfo(this.assembly, ns); } } protected onEndNamespace(_ns: string) { /* noop */ } protected onBeginInterface(ifc: spec.InterfaceType) { this.openFileIfNeeded(ifc); this.addJavaDocs(ifc, { api: 'type', fqn: ifc.fqn }); // all interfaces always extend JsiiInterface so we can identify that it is a jsii interface. const interfaces = ifc.interfaces ?? []; const bases = [ 'software.amazon.jsii.JsiiSerializable', ...interfaces.map((x) => this.toNativeFqn(x)), ].join(', '); const nested = this.isNested(ifc); const inner = nested ? ' static' : ''; if (!nested) { this.emitGeneratedAnnotation(); } this.code.line( `@software.amazon.jsii.Jsii(module = ${this.moduleClass}.class, fqn = "${ifc.fqn}")`, ); this.code.line( `@software.amazon.jsii.Jsii.Proxy(${ifc.name}.${INTERFACE_PROXY_CLASS_NAME}.class)`, ); this.emitStabilityAnnotations(ifc); this.code.openBlock( `public${inner} interface ${ifc.name} extends ${bases}`, ); } protected onEndInterface(ifc: spec.InterfaceType) { this.emitMultiplyInheritedOptionalProperties(ifc); if (ifc.datatype) { this.emitDataType(ifc); } else { const type = this.reflectAssembly.findType( ifc.fqn, ) as reflect.InterfaceType; this.emitProxy(type); // We don't emit Jsii$Default if the assembly opted out of it explicitly. // This is mostly to facilitate compatibility testing... if (hasDefaultInterfaces(this.reflectAssembly)) { this.emitDefaultImplementation(type); } } this.code.closeBlock(); this.closeFileIfNeeded(ifc); } protected onInterfaceMethod(ifc: spec.InterfaceType, method: spec.Method) { this.code.line(); const returnType = method.returns ? this.toDecoratedJavaType(method.returns) : 'void'; this.addJavaDocs(method, { api: 'member', fqn: ifc.fqn, memberName: method.name, }); this.emitStabilityAnnotations(method); this.code.line( `${returnType} ${method.name}(${this.renderMethodParameters(method)});`, ); } protected onInterfaceMethodOverload( ifc: spec.InterfaceType, overload: spec.Method, _originalMethod: spec.Method, ) { this.onInterfaceMethod(ifc, overload); } protected onInterfaceProperty(ifc: spec.InterfaceType, prop: spec.Property) { const getterType = this.toDecoratedJavaType(prop); const propName = jsiiToPascalCase( JavaGenerator.safeJavaPropertyName(prop.name), ); // for unions we only generate overloads for setters, not getters. this.code.line(); this.addJavaDocs(prop, { api: 'member', fqn: ifc.fqn, memberName: prop.name, }); this.emitStabilityAnnotations(prop); if (prop.optional) { if (prop.overrides) { this.code.line('@Override'); } this.code.openBlock(`default ${getterType} get${propName}()`); this.code.line('return null;'); this.code.closeBlock(); } else { this.code.line(`${getterType} get${propName}();`); } if (!prop.immutable) { const setterTypes = this.toDecoratedJavaTypes(prop); for (const type of setterTypes) { this.code.line(); this.addJavaDocs(prop, { api: 'member', fqn: ifc.fqn, memberName: prop.name, }); if (prop.optional) { if (prop.overrides) { this.code.line('@Override'); } this.code.line('@software.amazon.jsii.Optional'); this.code.openBlock( `default void set${propName}(final ${type} value)`, ); this.code.line( `throw new UnsupportedOperationException("'void " + getClass().getCanonicalName() + "#set${propName}(${type})' is not implemented!");`, ); this.code.closeBlock(); } else { this.code.line(`void set${propName}(final ${type} value);`); } } } } /** * Emits a local default implementation for optional properties inherited from * multiple distinct parent types. This remvoes the default method dispatch * ambiguity that would otherwise exist. * * @param ifc the interface to be processed. * * @see https://github.com/aws/jsii/issues/2256 */ private emitMultiplyInheritedOptionalProperties(ifc: spec.InterfaceType) { if (ifc.interfaces == null || ifc.interfaces.length <= 1) { // Nothing to do if we don't have parent interfaces, or if we have exactly one return; } const inheritedOptionalProps = ifc.interfaces .map(allOptionalProps.bind(this)) // Calculate how many direct parents brought a given optional property .reduce((histogram, entry) => { for (const [name, spec] of Object.entries(entry)) { histogram[name] = histogram[name] ?? { spec, count: 0 }; histogram[name].count += 1; } return histogram; }, {} as Record<string, { readonly spec: spec.Property; count: number }>); const localProps = new Set(ifc.properties?.map((prop) => prop.name) ?? []); for (const { spec, count } of Object.values(inheritedOptionalProps)) { if (count < 2 || localProps.has(spec.name)) { continue; } this.onInterfaceProperty(ifc, spec); } function allOptionalProps(this: JavaGenerator, fqn: string) { const type = this.findType(fqn) as spec.InterfaceType; const result: Record<string, spec.Property> = {}; for (const prop of type.properties ?? []) { // Adding artifical "overrides" here for code-gen quality's sake. result[prop.name] = { ...prop, overrides: type.fqn }; } // Include optional properties of all super interfaces in the result for (const base of type.interfaces ?? []) { for (const [name, prop] of Object.entries( allOptionalProps.call(this, base), )) { if (!(name in result)) { result[name] = prop; } } } return result; } } private emitAssemblyPackageInfo(mod: spec.Assembly) { if (!mod.docs) { return; } const { packageName } = this.toNativeName(mod); const packageInfoFile = this.toJavaFilePath( mod, `${mod.name}.package-info`, ); this.code.openFile(packageInfoFile); this.code.line('/**'); if (mod.readme) { for (const line of markDownToJavaDoc( this.convertSamplesInMarkdown(mod.readme.markdown, { api: 'moduleReadme', moduleFqn: mod.name, }), ).split('\n')) { this.code.line(` * ${line.replace(/\*\//g, '*{@literal /}')}`); } } if (mod.docs.deprecated) { this.code.line(' *'); // Javac won't allow @deprecated on packages, while @Deprecated is aaaabsolutely fine. Duh. this.code.line(` * Deprecated: ${mod.docs.deprecated}`); } this.code.line(' */'); this.emitStabilityAnnotations(mod); this.code.line(`package ${packageName};`); this.code.closeFile(packageInfoFile); } private emitSubmodulePackageInfo(assembly: spec.Assembly, moduleFqn: string) { const mod = assembly.submodules?.[moduleFqn]; if (!mod?.readme?.markdown) { return; } const { packageName } = translateFqn(assembly, moduleFqn); const packageInfoFile = this.toJavaFilePath( assembly, `${moduleFqn}.package-info`, ); this.code.openFile(packageInfoFile); this.code.line('/**'); if (mod.readme) { for (const line of markDownToJavaDoc( this.convertSamplesInMarkdown(mod.readme.markdown, { api: 'moduleReadme', moduleFqn, }), ).split('\n')) { this.code.line(` * ${line.replace(/\*\//g, '*{@literal /}')}`); } } this.code.line(' */'); this.code.line(`package ${packageName};`); this.code.closeFile(packageInfoFile); } private emitMavenPom(assm: spec.Assembly, fingerprint: boolean) { if (!assm.targets?.java) { throw new Error(`Assembly ${assm.name} does not declare a java target`); } const comment = fingerprint ? { '#comment': [ `Generated by jsii-pacmak@${VERSION_DESC} on ${new Date().toISOString()}`, `@jsii-pacmak:meta@ ${JSON.stringify(this.metadata)}`, ], } : {}; this.code.openFile('pom.xml'); this.code.line( xmlbuilder .create( { project: { '@xmlns': 'http://maven.apache.org/POM/4.0.0', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', '@xsi:schemaLocation': 'http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd', ...comment, modelVersion: '4.0.0', name: '${project.groupId}:${project.artifactId}', description: assm.description, url: assm.homepage, licenses: { license: getLicense(), }, developers: { developer: mavenDevelopers(), }, scm: { connection: `scm:${assm.repository.type}:${assm.repository.url}`, url: assm.repository.url, }, groupId: assm.targets.java.maven.groupId, artifactId: assm.targets.java.maven.artifactId, version: makeVersion( assm.version, assm.targets.java.maven.versionSuffix, ), packaging: 'jar', properties: { 'project.build.sourceEncoding': 'UTF-8' }, dependencies: { dependency: mavenDependencies.call(this) }, build: { plugins: { plugin: [ { groupId: 'org.apache.maven.plugins', artifactId: 'maven-compiler-plugin', version: '3.8.1', configuration: { source: '1.8', target: '1.8' }, }, { groupId: 'org.apache.maven.plugins', artifactId: 'maven-jar-plugin', version: '3.2.0', configuration: { archive: { index: true, manifest: { addDefaultImplementationEntries: true, addDefaultSpecificationEntries: true, }, }, }, }, { groupId: 'org.apache.maven.plugins', artifactId: 'maven-source-plugin', version: '3.2.1', executions: { execution: { id: 'attach-sources', goals: { goal: 'jar' }, }, }, }, { groupId: 'org.apache.maven.plugins', artifactId: 'maven-javadoc-plugin', version: '3.2.0', executions: { execution: { id: 'attach-javadocs', goals: { goal: 'jar' }, }, }, configuration: { failOnError: false, show: 'protected', sourceFileExcludes: { // Excluding the $Module classes so they won't pollute the docsite. They otherwise // are all collected at the top of the classlist, burrying useful information under // a lot of dry scrolling. exclude: ['**/$Module.java'], }, // Adding these makes JavaDoc generation about a 3rd faster (which is far and away the most // expensive part of the build) additionalJOption: [ '-J-XX:+TieredCompilation', '-J-XX:TieredStopAtLevel=1', ], }, }, { groupId: 'org.apache.maven.plugins', artifactId: 'maven-enforcer-plugin', version: '3.0.0-M3', executions: { execution: { id: 'enforce-maven', goals: { goal: 'enforce' }, configuration: { rules: { requireMavenVersion: { version: '3.6' }, }, }, }, }, }, { groupId: 'org.codehaus.mojo', artifactId: 'versions-maven-plugin', version: '2.8.1', configuration: { generateBackupPoms: false, }, }, ], }, }, }, }, { encoding: 'UTF-8' }, ) .end({ pretty: true }), ); this.code.closeFile('pom.xml'); /** * Combines a version number with an optional suffix. The suffix, when present, must begin with * '-' or '.', and will be concatenated as-is to the version number.. * * @param version the semantic version number * @param suffix the suffix, if any. */ function makeVersion(version: string, suffix?: string): string { if (!suffix) { return toReleaseVersion(version, TargetName.JAVA); } if (!suffix.startsWith('-') && !suffix.startsWith('.')) { throw new Error( `versionSuffix must start with '-' or '.', but received ${suffix}`, ); } return `${version}${suffix}`; } function mavenDependencies(this: JavaGenerator) { const dependencies = new Array<MavenDependency>(); for (const [depName, version] of Object.entries( this.assembly.dependencies ?? {}, )) { const dep = this.assembly.dependencyClosure?.[depName]; if (!dep?.targets?.java) { throw new Error( `Assembly ${assm.name} depends on ${depName}, which does not declare a java target`, ); } dependencies.push({ groupId: dep.targets.java.maven.groupId, artifactId: dep.targets.java.maven.artifactId, version: toMavenVersionRange( version, dep.targets.java.maven.versionSuffix, ), }); } // The JSII java runtime base classes dependencies.push({ groupId: 'software.amazon.jsii', artifactId: 'jsii-runtime', version: toMavenVersionRange(`^${VERSION}`), }); // Provides @org.jetbrains.* dependencies.push({ groupId: 'org.jetbrains', artifactId: 'annotations', version: '[16.0.3,20.0.0)', }); // Provides @javax.annotation.Generated for JDKs >= 9 dependencies.push({ '#comment': 'Provides @javax.annotation.Generated for JDKs >= 9', groupId: 'javax.annotation', artifactId: 'javax.annotation-api', version: '[1.3.2,1.4.0)', scope: 'compile', }); return dependencies; } function mavenDevelopers() { return [assm.author, ...(assm.contributors ?? [])].map(toDeveloper); function toDeveloper(person: spec.Person) { const developer: any = { [person.organization ? 'organization' : 'name']: person.name, roles: { role: person.roles }, }; // We cannot set "undefined" or "null" to a field - this causes invalid XML to be emitted (per POM schema). if (person.email) { developer.email = person.email; } if (person.url) { developer[person.organization ? 'organizationUrl' : 'url'] = person.url; } return developer; } } /** * Get the maven-style license block for a the assembly. * @see https://maven.apache.org/pom.html#Licenses */ function getLicense() { const spdx = spdxLicenseList[assm.license]; return ( spdx && { name: spdx.name, url: spdx.url, distribution: 'repo', comments: spdx.osiApproved ? 'An OSI-approved license' : undefined, } ); } } private emitStaticInitializer(cls: spec.ClassType) { const consts = (cls.properties ?? []).filter((x) => x.const); if (consts.length === 0) { return; } const javaClass = this.toJavaType(cls); this.code.line(); this.code.openBlock('static'); for (const prop of consts) { const constName = this.renderConstName(prop); const propType = this.toNativeType(prop.type, { forMarshalling: true }); const statement = `software.amazon.jsii.JsiiObject.jsiiStaticGet(${javaClass}.class, "${prop.name}", ${propType})`; this.code.line( `${constName} = ${this.wrapCollection( statement, prop.type, prop.optional, )};`, ); } this.code.closeBlock(); } private renderConstName(prop: spec.Property) { return this.code.toSnakeCase(prop.name).toLocaleUpperCase(); // java consts are SNAKE_UPPER_CASE } private emitConstProperty(parentType: spec.Type, prop: spec.Property) { const propType = this.toJavaType(prop.type); const propName = this.renderConstName(prop); const access = this.renderAccessLevel(prop); this.code.line(); this.addJavaDocs(prop, { api: 'member', fqn: parentType.fqn, memberName: prop.name, }); this.emitStabilityAnnotations(prop); this.code.line(`${access} final static ${propType} ${propName};`); } private emitProperty( cls: spec.Type, prop: spec.Property, definingType: spec.Type, { defaultImpl = false, final = false, includeGetter = true, overrides = !!prop.overrides, }: { defaultImpl?: boolean; final?: boolean; includeGetter?: boolean; overrides?: boolean; } = {}, ) { const getterType = this.toDecoratedJavaType(prop); const setterTypes = this.toDecoratedJavaTypes(prop, { covariant: prop.static, }); const propName = jsiiToPascalCase( JavaGenerator.safeJavaPropertyName(prop.name), ); const modifiers = [defaultImpl ? 'default' : this.renderAccessLevel(prop)]; if (prop.static) modifiers.push('static'); if (prop.abstract && !defaultImpl) modifiers.push('abstract'); if (final && !prop.abstract && !defaultImpl) modifiers.push('final'); const javaClass = this.toJavaType(cls); // for unions we only generate overloads for setters, not getters. if (includeGetter) { this.code.line(); this.addJavaDocs(prop, { api: 'member', fqn: definingType.fqn, memberName: prop.name, }); if (overrides && !prop.static) { this.code.line('@Override'); } this.emitStabilityAnnotations(prop); const signature = `${modifiers.join(' ')} ${getterType} get${propName}()`; if (prop.abstract && !defaultImpl) { this.code.line(`${signature};`); } else { this.code.openBlock(signature); let statement; if (prop.static) { statement = `software.amazon.jsii.JsiiObject.jsiiStaticGet(${this.toJavaType( cls, )}.class, `; } else { statement = 'software.amazon.jsii.Kernel.get(this, '; } statement += `"${prop.name}", ${this.toNativeType(prop.type, { forMarshalling: true, })})`; this.code.line( `return ${this.wrapCollection(statement, prop.type, prop.optional)};`, ); this.code.closeBlock(); } } if (!prop.immutable) { for (const type of setterTypes) { this.code.line(); this.addJavaDocs(prop, { api: 'member', fqn: cls.fqn, memberName: prop.name, }); if (overrides && !prop.static) { this.code.line('@Override'); } this.emitStabilityAnnotations(prop); const signature = `${modifiers.join( ' ', )} void set${propName}(final ${type} value)`; if (prop.abstract && !defaultImpl) { this.code.line(`${signature};`); } else { this.code.openBlock(signature); let statement = ''; if (prop.static) { statement += `software.amazon.jsii.JsiiObject.jsiiStaticSet(${javaClass}.class, `; } else { statement += 'software.amazon.jsii.Kernel.set(this, '; } const value = prop.optional ? 'value' : `java.util.Objects.requireNonNull(value, "${prop.name} is required")`; statement += `"${prop.name}", ${value});`; this.code.line(statement); this.code.closeBlock(); } } } } private emitMethod( cls: spec.Type, method: spec.Method, { defaultImpl = false, final = false, overrides = !!method.overrides, }: { defaultImpl?: boolean; final?: boolean; overrides?: boolean } = {}, ) { const returnType = method.returns ? this.toDecoratedJavaType(method.returns) : 'void'; const modifiers = [ defaultImpl ? 'default' : this.renderAccessLevel(method), ]; if (method.static) modifiers.push('static'); if (method.abstract && !defaultImpl) modifiers.push('abstract'); if (final && !method.abstract && !defaultImpl) modifiers.push('final'); const async = !!method.async; const methodName = JavaGenerator.safeJavaMethodName(method.name); const signature = `${returnType} ${methodName}(${this.renderMethodParameters( method, )})`; this.code.line(); this.addJavaDocs(method, { api: 'member', fqn: cls.fqn, memberName: method.name, }); this.emitStabilityAnnotations(method); if (overrides && !method.static) { this.code.line('@Override'); } if (method.abstract && !defaultImpl) { this.code.line(`${modifiers.join(' ')} ${signature};`); } else { this.code.openBlock(`${modifiers.join(' ')} ${signature}`); this.code.line(this.renderMethodCall(cls, method, async)); this.code.closeBlock(); } } /** * We are now going to build a class that can be used as a proxy for untyped * javascript objects that implement this interface. we want java code to be * able to interact with them, so we will create a proxy class which * implements this interface and has the same methods. * * These proxies are also used to extend abstract classes to allow the JSII * engine to instantiate an abstract class in Java. */ private emitProxy(type: reflect.InterfaceType | reflect.ClassType) { const name = INTERFACE_PROXY_CLASS_NAME; this.code.line(); this.code.line('/**'); this.code.line( ' * A proxy class which represents a concrete javascript instance of this type.', ); this.code.line(' */'); const baseInterfaces = this.defaultInterfacesFor(type, { includeThisType: true, }); if (type.isInterfaceType() && !hasDefaultInterfaces(type.assembly)) { // Extend this interface directly since this module does not have the Jsii$Default baseInterfaces.push(this.toNativeFqn(type.fqn)); } const suffix = type.isInterfaceType() ? `extends software.amazon.jsii.JsiiObject implements ${baseInterfaces.join( ', ', )}` : `extends ${this.toNativeFqn(type.fqn)}${ baseInterfaces.length > 0 ? ` implements ${baseInterfaces.join(', ')}` : '' }`; const modifiers = type.isInterfaceType() ? 'final' : 'private static final'; this.code.line(ANN_INTERNAL); this.code.openBlock(`${modifiers} class ${name} ${suffix}`); this.code.openBlock( `protected ${name}(final software.amazon.jsii.JsiiObjectRef objRef)`, ); this.code.line('super(objRef);'); this.code.closeBlock(); // emit all properties for (const reflectProp of type.allProperties.filter( (prop) => prop.abstract && (prop.parentType.fqn === type.fqn || prop.parentType.isClassType() || !hasDefaultInterfaces(prop.assembly)), )) { const prop = clone(reflectProp.spec); prop.abstract = false; // Emitting "final" since this is a proxy and nothing will/should override this this.emitProperty(type.spec, prop, reflectProp.definingType.spec, { final: true, overrides: true, }); } // emit all the methods for (const reflectMethod of type.allMethods.filter( (method) => method.abstract && (method.parentType.fqn === type.fqn || method.parentType.isClassType() || !hasDefaultInterfaces(method.assembly)), )) { const method = clone(reflectMethod.spec); method.abstract = false; // Emitting "final" since this is a proxy and nothing will/should override this this.emitMethod(type.spec, method, { final: true, overrides: true }); for (const overloadedMethod of this.createOverloadsForOptionals(method)) { overloadedMethod.abstract = false; this.emitMethod(type.spec, overloadedMethod, { final: true, overrides: true, }); } } this.code.closeBlock(); } private emitDefaultImplementation(type: reflect.InterfaceType) { const baseInterfaces = [type.name, ...this.defaultInterfacesFor(type)]; this.code.line(); this.code.line('/**'); this.code.line( ` * Internal default implementation for {@link ${type.name}}.`, ); this.code.line(' */'); this.code.line(ANN_INTERNAL); this.code.openBlock( `interface ${INTERFACE_DEFAULT_CLASS_NAME} extends ${baseInterfaces .sort() .join(', ')}`, ); for (const property of type.allProperties.filter( (prop) => prop.abstract && // Only checking the getter - java.lang.Object has no setters. !isJavaLangObjectMethodName(`get${jsiiToPascalCase(prop.name)}`) && (prop.parentType.fqn === type.fqn || !hasDefaultInterfaces(prop.assembly)), )) { this.emitProperty(type.spec, property.spec, property.definingType.spec, { defaultImpl: true, overrides: type.isInterfaceType(), }); } for (const method of type.allMethods.filter( (method) => method.abstract && !isJavaLangObjectMethodName(method.name) && (method.parentType.fqn === type.fqn || !hasDefaultInterfaces(method.assembly)), )) { this.emitMethod(type.spec, method.spec, { defaultImpl: true, overrides: type.isInterfaceType(), }); } this.code.closeBlock(); } private emitStabilityAnnotations(entity: spec.Documentable) { if (!entity.docs) { return; } if (entity.docs.stability) { this.code.line( `@software.amazon.jsii.Stability(software.amazon.jsii.Stability.Level.${_level( entity.docs.stability, )})`, ); } if ( entity.docs.stability === spec.Stability.Deprecated || entity.docs.deprecated ) { this.code.line('@Deprecated'); } function _level(stability: spec.Stability): string { switch (stability) { case spec.Stability.Deprecated: return 'Deprecated'; case spec.Stability.Experimental: return 'Experimental'; case spec.Stability.External: // Rendering 'External' out as publicly visible state is confusing. As far // as users are concerned we just advertise this as stable. return 'Stable'; case spec.Stability.Stable: return 'Stable'; default: throw new Error(`Unexpected stability: ${stability as any}`); } } } private toJavaProp( property: spec.Property, definingType: spec.Type, inherited: boolean, ): JavaProp { const safeName = JavaGenerator.safeJavaPropertyName(property.name); const propName = jsiiToPascalCase(safeName); return { docs: property.docs, spec: property, definingType, propName, jsiiName: property.name, nullable: !!property.optional, fieldName: this.code.toCamelCase(safeName), fieldJavaType: this.toJavaType(property.type), paramJavaType: this.toJavaType(property.type, { covariant: true }), fieldNativeType: this.toNativeType(property.type), fieldJavaClass: `${this.toJavaType(property.type, { forMarshalling: true, })}.class`, javaTypes: this.toJavaTypes(property.type, { covariant: true }), immutable: property.immutable ?? false, inherited, }; } private emitClassBuilder(cls: spec.ClassType) { // Not rendering if there is no initializer, or if the initializer is protected or variadic if (cls.initializer == null || cls.initializer.protected) { return; } // Not rendering if the initializer has no parameters if (cls.initializer.parameters == null) { return; } // Not rendering if there is a nested "Builder" class if ( this.reflectAssembly.tryFindType(`${cls.fqn}.${BUILDER_CLASS_NAME}`) != null ) { return; } // Find the first struct parameter of the constructor (if any) const firstStruct = cls.initializer.parameters.find((param) => { if (!spec.isNamedTypeReference(param.type)) { return false; } const paramType = this.reflectAssembly.tryFindType(param.type.fqn); return paramType?.isDataType(); }); // Not rendering if there is no struct parameter if (firstStruct == null) { return; } const structType = this.reflectAssembly.findType( (firstStruct.type as spec.NamedTypeReference).fqn, ) as reflect.InterfaceType; const structParamName = this.code.toCamelCase( JavaGenerator.safeJavaPropertyName(firstStruct.name), ); const structBuilder = `${this.toJavaType( firstStruct.type, )}.${BUILDER_CLASS_NAME}`; const positionalParams = cls.initializer.parameters .filter((p) => p !== firstStruct) .map((param) => ({ param, fieldName: this.code.toCamelCase( JavaGenerator.safeJavaPropertyName(param.name), ), javaType: this.toJavaType(param.type), })); const builtType = this.toJavaType(cls); this.code.line(); this.code.line('/**'); // eslint-disable-next-line prettier/prettier this.code.line( ` * ${stabilityPrefixFor( cls.initializer, )}A fluent builder for {@link ${builtType}}.`, ); this.code.line(' */'); this.emitStabilityAnnotations(cls.initializer); this.code.openBlock( `public static final class ${BUILDER_CLASS_NAME} implements software.amazon.jsii.Builder<${builtType}>`, ); // Static factory method(s) for (const params of computeOverrides(positionalParams)) { const dummyMethod: spec.Method = { docs: { stability: cls.initializer.docs?.stability ?? cls.docs?.stability, returns: `a new instance of {@link ${BUILDER_CLASS_NAME}}.`, }, name: 'create', parameters: params.map((param) => param.param), }; this.addJavaDocs(dummyMethod, { api: 'member', fqn: cls.fqn, memberName: dummyMethod.name, }); this.emitStabilityAnnotations(cls.initializer); this.code.openBlock( `public static ${BUILDER_CLASS_NAME} create(${params .map( (param) => `final ${param.javaType}${param.param.variadic ? '...' : ''} ${ param.fieldName }`, ) .join(', ')})`, ); this.code.line( `return new ${BUILDER_CLASS_NAME}(${positionalParams .map((param, idx) => (idx < params.length ? param.fieldName : 'null')) .join(', ')});`, ); this.code.closeBlock(); } // Private properties this.code.line(); for (const param of positionalParams) { this.code.line( `private final ${param.javaType}${param.param.variadic ? '[]' : ''} ${ param.fieldName };`, ); } this.code.line( `private ${ firstStruct.optional ? '' : 'final ' }${structBuilder} ${structParamName};`, ); // Private constructor this.code.line(); this.code.openBlock( `private ${BUILDER_CLASS_NAME}(${positionalParams .map( (param) => `final ${param.javaType}${param.param.variadic ? '...' : ''} ${ param.fieldName }`, ) .join(', ')})`, ); for (const param of positionalParams) { this.code.line(`this.${param.fieldName} = ${param.fieldName};`); } if (!firstStruct.optional) { this.code.line(`this.${structParamName} = new ${structBuilder}();`); } this.code.closeBlock(); // Fields for (const prop of structType.allProperties) { const fieldName = this.code.toCamelCase( JavaGenerator.safeJavaPropertyName(prop.name), ); this.code.line(); const setter: spec.Method = { name: fieldName, docs: { ...prop.spec.docs, stability: prop.spec.docs?.stability, returns: '{@code this}', }, parameters: [ { name: fieldName, type: spec.CANONICAL_ANY, // We don't quite care in this context! docs: prop.spec.docs, }, ], }; for (const javaType of this.toJavaTypes(prop.type.spec!, { covariant: true, })) { this.addJavaDocs(setter, { api: 'member', fqn: prop.definingType.fqn, // Could be inherited memberName: prop.name, }); this.emitStabilityAnnotations(prop.spec); this.code.openBlock( `public ${BUILDER_CLASS_NAME} ${fieldName}(final ${javaType} ${fieldName})`, ); this.code.line( `this.${structParamName}${ firstStruct.optional ? '()' : '' }.${fieldName}(${fieldName});`, ); this.code.line('return this;'); this.code.closeBlock(); } } // Final build method this.code.line(); this.code.line('/**'); this.code.line( ` * @returns a newly built instance of {@link ${builtType}}.`, ); this.code.line(' */'); this.emitStabilityAnnotations(cls.initializer); this.code.line('@Override'); this.code.openBlock(`public ${builtType} build()`); const params = cls.initializer.parameters.map((param) => { if (param === firstStruct) { return firstStruct.optional ? `this.${structParamName} != null ? this.${structParamName}.build() : null` : `this.${structParamName}.build()`; } return `this.${ positionalParams.find((p) => param === p.param)!.fieldName }`; }); this.code.indent(`return new ${builtType}(`); params.forEach((param, idx) => this.code.line(`${param}${idx < params.length - 1 ? ',' : ''}`), ); this.code.unindent(');'); this.code.closeBlock(); // Optional builder initialization if (firstStruct.optional) { this.code.line(); this.code.openBlock(`private ${structBuilder} ${structParamName}()`); this.code.openBlock(`if (this.${structParamName} == null)`); this.code.line(`this.${structParamName} = new ${structBuilder}();`); this.code.closeBlock(); this.code.line(`return this.${structParamName};`); this.code.closeBlock(); } this.code.closeBlock(); } private emitBuilderSetter( prop: JavaProp, builderName: string, parentType: spec.InterfaceType, ) { for (const type of prop.javaTypes) { this.code.line(); this.code.line('/**'); this.code.line( ` * Sets the value of {@link ${parentType.name}#${getterFor( prop.fieldName, )}}`, ); const summary = prop.docs?.summary ?? 'the value to be set'; this.code.line( ` * ${paramJavadoc(prop.fieldName, prop.nullable, summary)}`, ); if (prop.docs?.remarks != null) { const indent = ' '.repeat(7 + prop.fieldName.length); const remarks = markDownToJavaDoc( this.convertSamplesInMarkdown(prop.docs.remarks, { api: 'member', fqn: prop.definingType.fqn, memberName: prop.jsiiName, }), ).trimRight(); for (const line of remarks.split('\n')) { this.code.line(` * ${indent} ${line}`); } } this.code.line(' * @return {@code this}'); if (prop.docs?.deprecated) { this.code.line(` * @deprecated ${prop.docs.deprecated}`); } this.code.line(' */'); this.emitStabilityAnnotations(prop.spec); // We add an explicit cast if both types are generic but they are not identical (one is covariant, the other isn't) const explicitCast = type.includes('<') && prop.fieldJavaType.includes('<') && type !== prop.fieldJavaType ? `(${prop.fieldJavaType})` : ''; if (explicitCast !== '') { // We'll be doing a safe, but unchecked cast, so suppress that warning this.code.line('@SuppressWarnings("unchecked")'); } this.code.openBlock( `public ${builderName} ${prop.fieldName}(${type} ${prop.fieldName})`, ); this.code.line( `this.${prop.fieldName} = ${explicitCast}${prop.fieldName};`, ); this.code.line('return this;'); this.code.closeBlock(); } function getterFor(fieldName: string): string { const [first, ...rest] = fieldName; return `get${first.toUpperCase()}${rest.join('')}`; } } private emitInterfaceBuilder( classSpec: spec.InterfaceType, constructorName: string, props: JavaProp[], ) { // Start builder() this.code.line(); this.code.line('/**'); this.code.line( ` * @return a {@link ${BUILDER_CLASS_NAME}} of {@link ${classSpec.name}}`, ); this.code.line(' */'); this.emitStabilityAnnotations(classSpec); this.code.openBlock(`static ${BUILDER_CLASS_NAME} builder()`); this.code.line(`return new ${BUILDER_CLASS_NAME}();`); this.code.closeBlock(); // End builder() // Start Builder this.code.line('/**'); this.code.line(` * A builder for {@link ${classSpec.name}}`); this.code.line(' */'); this.emitStabilityAnnotations(classSpec); this.code.openBlock( `public static final class ${BUILDER_CLASS_NAME} implements software.amazon.jsii.Builder<${classSpec.name}>`, ); props.forEach((prop) => this.code.line(`${prop.fieldJavaType} ${prop.fieldName};`), ); props.forEach((prop) => this.emitBuilderSetter(prop, BUILDER_CLASS_NAME, classSpec), ); // Start build() this.code.line(); this.code.line('/**'); this.code.line(' * Builds the configured instance.'); this.code.line(` * @return a new instance of {@link ${classSpec.name}}`); this.code.line( ' * @throws NullPointerException if any required attribute was not provided', ); this.code.line(' */'); this.emitStabilityAnnotations(classSpec); this.code.line('@Override'); this.code.openBlock(`public ${classSpec.name} build()`); this.code.line(`return new ${constructorName}(this);`); this.code.closeBlock(); // End build() this.code.closeBlock(); // End Builder } private emitDataType(ifc: spec.InterfaceType) { // collect all properties from all base structs and dedupe by name. It is assumed that the generation of the // assembly will not permit multiple overloaded inherited properties with the same name and that this will be // enforced by Typescript constraints. const propsByName: { [name: string]: JavaProp } = {}; function collectProps( this: JavaGenerator, currentIfc: spec.InterfaceType, isBaseClass = false, ) { for (const property of currentIfc.properties ?? []) { const javaProp = this.toJavaProp(property, currentIfc, isBaseClass); propsByName[javaProp.propName] = javaProp; } // add props of base struct for (const base of currentIfc.interfaces ?? []) { collectProps.call( this, this.findType(base) as spec.InterfaceType, true, ); } } collectProps.call(this, ifc); const props = Object.values(propsByName); this.emitInterfaceBuilder(ifc, INTERFACE_PROXY_CLASS_NAME, props); // Start implementation class this.code.line(); this.code.line('/**'); this.code.line(` * An implementation for {@link ${ifc.name}}`); this.code.line(' */'); this.emitStabilityAnnotations(ifc); this.code.line(ANN_INTERNAL); this.code.openBlock( `final class ${INTERFACE_PROXY_CLASS_NAME} extends software.amazon.jsii.JsiiObject implements ${ifc.name}`, ); // Immutable properties props.forEach((prop) => this.code.line(`private final ${prop.fieldJavaType} ${prop.fieldName};`), ); // Start JSII reference constructor this.code.line(); this.code.line('/**'); this.code.line( ' * Constructor that initializes the object based on values retrieved from the JsiiObject.', ); this.code.line(' * @param objRef Reference to the JSII managed object.'); this.code.line(' */'); this.code.openBlock( `protected ${INTERFACE_PROXY_CLASS_NAME}(final software.amazon.jsii.JsiiObjectRef objRef)`, ); this.code.line('super(objRef);'); props.forEach((prop) => this.code.line( `this.${prop.fieldName} = software.amazon.jsii.Kernel.get(this, "${prop.jsiiName}", ${prop.fieldNativeType});`, ), ); this.code.closeBlock(); // End JSII reference constructor // Start builder constructor this.code.line(); this.code.line('/**'); this.code.line( ' * Constructor that initializes the object based on literal property values passed by the {@link Builder}.', ); this.code.line(' */'); if (props.some((prop) => prop.fieldJavaType !== prop.paramJavaType)) { this.code.line('@SuppressWarnings("unchecked")'); } this.code.openBlock( `protected ${INTERFACE_PROXY_CLASS_NAME}(final ${BUILDER_CLASS_NAME} builder)`, ); this.code.line( 'super(software.amazon.jsii.JsiiObject.InitializationMode.JSII);', ); props.forEach((prop) => { const explicitCast = prop.fieldJavaType !== prop.paramJavaType ? `(${prop.fieldJavaType})` : ''; this.code.line( `this.${prop.fieldName} = ${explicitCast}${_validateIfNonOptional( `builder.${prop.fieldName}`, prop, )};`, ); }); this.code.closeBlock(); // End literal constructor // Getters props.forEach((prop) => { this.code.line(); this.code.line('@Override'); this.code.openBlock( `public final ${prop.fieldJavaType} get${prop.propName}()`, ); this.code.line(`return this.${prop.fieldName};`); this.code.closeBlock(); }); // emit $jsii$toJson which will be called to serialize this object when sent to JS this.code.line(); this.code.line('@Override'); this.code.line(ANN_INTERNAL); this.code.openBlock( 'public com.fasterxml.jackson.databind.JsonNode $jsii$toJson()', ); this.code.line( 'final com.fasterxml.jackson.databind.ObjectMapper om = software.amazon.jsii.JsiiObjectMapper.INSTANCE;', ); this.code.line( `final com.fasterxml.jackson.databind.node.ObjectNode data = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode();`, ); this.code.line(); for (const prop of props) { if (prop.nullable) { this.code.openBlock(`if (this.get${prop.propName}() != null)`); } this.code.line( `data.set("${prop.spec.name}", om.valueToTree(this.get${prop.propName}()));`, ); if (prop.nullable) { this.code.closeBlock(); } } this.code.line(); this.code.line( 'final com.fasterxml.jackson.databind.node.ObjectNode struct = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode();', ); this.code.line(`struct.set("fqn", om.valueToTree("${ifc.fqn}"));`); this.code.line('struct.set("data", data);'); this.code.line(); this.code.line( 'final com.fasterxml.jackson.databind.node.ObjectNode obj = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode();', ); this.code.line('obj.set("$jsii.struct", struct);'); this.code.line(); this.code.line('return obj;'); this.code.closeBlock(); // End $jsii$toJson // Generate equals() override this.emitEqualsOverride(ifc.name, props); // Generate hashCode() override this.emitHashCodeOverride(props); this.code.closeBlock(); // End implementation class function _validateIfNonOptional(variable: string, prop: JavaProp): string { if (prop.nullable) { return variable; } return `java.util.Objects.requireNonNull(${variable}, "${prop.fieldName} is required")`; } } private emitEqualsOverride(className: string, props: JavaProp[]) { // A class without properties does not need to override equals() if (props.length === 0) { return; } this.code.line(); this.code.line('@Override'); this.code.openBlock('public final boolean equals(final Object o)'); this.code.line('if (this == o) return true;'); // This was already checked by `super.equals(o)`, so we skip it here... this.code.line( 'if (o == null || getClass() != o.getClass()) return false;', ); this.code.line(); this.code.line( `${className}.${INTERFACE_PROXY_CLASS_NAME} that = (${className}.${INTERFACE_PROXY_CLASS_NAME}) o;`, ); this.code.line(); const initialProps = props.slice(0, props.length - 1); const finalProp = props[props.length - 1]; initialProps.forEach((prop) => { const predicate = prop.nullable ? `this.${prop.fieldName} != null ? !this.${prop.fieldName}.equals(that.${prop.fieldName}) : that.${prop.fieldName} != null` : `!${prop.fieldName}.equals(that.${prop.fieldName})`; this.code.line(`if (${predicate}) return false;`); }); // The final (returned predicate) is the inverse of the other ones const finalPredicate = finalProp.nullable ? `this.${finalProp.fieldName} != null ? this.${finalProp.fieldName}.equals(that.${finalProp.fieldName}) : ` + `that.${finalProp.fieldName} == null` : `this.${finalProp.fieldName}.equals(that.${finalProp.fieldName})`; this.code.line(`return ${finalPredicate};`); this.code.closeBlock(); } private emitHashCodeOverride(props: JavaProp[]) { // A class without properties does not need to override hashCode() if (props.length === 0) { return; } this.code.line(); this.code.line('@Override'); this.code.openBlock('public final int hashCode()'); const firstProp = props[0]; const remainingProps = props.slice(1); this.code.line(`int result = ${_hashCodeForProp(firstProp)};`); remainingProps.forEach((prop) => this.code.line(`result = 31 * result + (${_hashCodeForProp(prop)});`), ); this.code.line('return result;'); this.code.closeBlock(); function _hashCodeForProp(prop: JavaProp) { return prop.nullable ? `this.${prop.fieldName} != null ? this.${prop.fieldName}.hashCode() : 0` : `this.${prop.fieldName}.hashCode()`; } } private openFileIfNeeded(type: spec.Type) { if (this.isNested(type)) { return; } this.code.openFile(this.toJavaFilePath(this.assembly, type)); this.code.line( `package ${this.toNativeName(this.assembly, type).packageName};`, ); this.code.line(); } private closeFileIfNeeded(type: spec.Type) { if (this.isNested(type)) { return; } this.code.closeFile(this.toJavaFilePath(this.assembly, type)); } private isNested(type: spec.Type) { if (!this.assembly.types || !type.namespace) { return false; } const parent = `${type.assembly}.${type.namespace}`; return parent in this.assembly.types; } private toJavaFilePath(assm: spec.Assembly, fqn: string): string; private toJavaFilePath(assm: spec.Assembly, type: spec.Type): string; private toJavaFilePath(assm: spec.Assembly, what: spec.Type | string) { const fqn = typeof what === 'string' ? what : what.fqn; const { packageName, typeNames } = translateFqn(assm, fqn); if (typeNames.length === 0) { throw new Error( `toJavaFilePath: ${fqn} must indicate a type, but doesn't: ${JSON.stringify( { packageName, typeNames }, )}`, ); } return `${path.join( 'src', 'main', 'java', ...packageName.split('.'), typeNames[0], )}.java`; } private toJavaResourcePath(assm: spec.Assembly, fqn: string, ext = '.txt') { const { packageName, typeName } = this.toNativeName(assm, { fqn, kind: spec.TypeKind.Class, assembly: assm.name, name: fqn.replace(/.*\.([^.]+)$/, '$1'), }); const parts = [ ...packageName.split('.'), `${typeName.split('.')[0]}${ext}`, ]; // Resource names are /-delimited paths (even on Windows *wink wink*) const name = parts.join('/'); const filePath = path.join('src', 'main', 'resources', ...parts); return { filePath, name }; } // eslint-disable-next-line complexity private addJavaDocs( doc: spec.Documentable, apiLoc: ApiLocation, defaultText?: string, ) { if ( !defaultText && Object.keys(doc.docs ?? {}).length === 0 && !((doc as spec.Method).parameters ?? []).some( (p) => Object.keys(p.docs ?? {}).length !== 0, ) ) { return; } const docs = (doc.docs = doc.docs ?? {}); const paras = []; if (docs.summary) { paras.push(renderSummary(docs)); } else if (defaultText) { paras.push(defaultText); } if (docs.remarks) { paras.push( markDownToJavaDoc( this.convertSamplesInMarkdown(docs.remarks, apiLoc), ).trimRight(), ); } if (docs.default) { paras.push(`Default: ${docs.default}`); // NOTE: there is no annotation in JavaDoc for this } if (docs.example) { paras.push('Example:'); const convertedExample = this.convertExample(docs.example, apiLoc); // We used to use the slightly nicer `<pre>{@code ...}</pre>`, which doesn't // require (and therefore also doesn't allow) escaping special characters. // // However, code samples may contain block quotes of their own ('*/') that // would terminate the block comment from the PoV of the Java tokenizer, and // since `{@code ... }` doesn't allow any escaping, there's also no way to encode // '*/' in a way that would (a) hide it from the tokenizer and (b) give '*/' back // after processing JavaDocs. // // Hence, we just resort to HTML-encoding everything (same as we do for code // examples that have been translated from MarkDown). paras.push( markDownToJavaDoc(['```', convertedExample, '```'].join('\n')), ); } const tagLines = []; if (docs.returns) { tagLines.push(`@return ${docs.returns}`); } if (docs.see) { tagLines.push(`@see ${docs.see}`); } if (docs.deprecated) { tagLines.push(`@deprecated ${docs.deprecated}`); } // Params if ((doc as spec.Method).parameters) { const method = doc as spec.Method; if (method.parameters) { for (const param of method.parameters) { const summary = param.docs?.summary; tagLines.push(paramJavadoc(param.name, param.optional, summary)); } } } if (tagLines.length > 0) { paras.push(tagLines.join('\n')); } const lines = new Array<string>(); for (const para of paras) { if (lines.length > 0) { lines.push('<p>'); } lines.push(...para.split('\n').filter((l) => l !== '')); } this.code.line('/**'); for (const line of lines) { this.code.line(` * ${line}`); } this.code.line(' */'); } private getClassBase(cls: spec.ClassType) { if (!cls.base) { return 'software.amazon.jsii.JsiiObject'; } return this.toJavaType({ fqn: cls.base }); } private toDecoratedJavaType( optionalValue: spec.OptionalValue, { covariant = false } = {}, ): string { const result = this.toDecoratedJavaTypes(optionalValue, { covariant }); if (result.length > 1) { return `${ optionalValue.optional ? ANN_NULLABLE : ANN_NOT_NULL } java.lang.Object`; } return result[0]; } private toDecoratedJavaTypes( optionalValue: spec.OptionalValue, { covariant = false } = {}, ): string[] { return this.toJavaTypes(optionalValue.type, { covariant }).map( (nakedType) => `${optionalValue.optional ? ANN_NULLABLE : ANN_NOT_NULL} ${nakedType}`, ); } private toJavaType( type: spec.TypeReference, opts?: { forMarshalling?: boolean; covariant?: boolean }, ): string { const types = this.toJavaTypes(type, opts); if (types.length > 1) { return 'java.lang.Object'; } return types[0]; } private toNativeType( type: spec.TypeReference, { forMarshalling = false, covariant = false } = {}, ): string { if (spec.isCollectionTypeReference(type)) { const nativeElementType = this.toNativeType(type.collection.elementtype, { forMarshalling, covariant, }); switch (type.collection.kind) { case spec.CollectionKind.Array: return `software.amazon.jsii.NativeType.listOf(${nativeElementType})`; case spec.CollectionKind.Map: return `software.amazon.jsii.NativeType.mapOf(${nativeElementType})`; default: throw new Error( `Unsupported collection kind: ${type.collection.kind as any}`, ); } } return `software.amazon.jsii.NativeType.forClass(${this.toJavaType(type, { forMarshalling, covariant, })}.class)`; } private toJavaTypes( typeref: spec.TypeReference, { forMarshalling = false, covariant = false } = {}, ): string[] { if (spec.isPrimitiveTypeReference(typeref)) { return [this.toJavaPrimitive(typeref.primitive)]; } else if (spec.isCollectionTypeReference(typeref)) { return [this.toJavaCollection(typeref, { forMarshalling, covariant })]; } else if (spec.isNamedTypeReference(typeref)) { return [this.toNativeFqn(typeref.fqn)]; } else if (typeref.union) { const types = new Array<string>(); for (const subtype of typeref.union.types) { for (const t of this.toJavaTypes(subtype, { forMarshalling, covariant, })) { types.push(t); } } return types; } throw new Error(`Invalid type reference: ${JSON.stringify(typeref)}`); } private toJavaCollection( ref: spec.CollectionTypeReference, { forMarshalling, covariant, }: { forMarshalling: boolean; covariant: boolean }, ) { const elementJavaType = this.toJavaType(ref.collection.elementtype, { covariant, }); const typeConstraint = covariant ? makeCovariant(elementJavaType) : elementJavaType; switch (ref.collection.kind) { case spec.CollectionKind.Array: return forMarshalling ? 'java.util.List' : `java.util.List<${typeConstraint}>`; case spec.CollectionKind.Map: return forMarshalling ? 'java.util.Map' : `java.util.Map<java.lang.String, ${typeConstraint}>`; default: throw new Error( `Unsupported collection kind: ${ref.collection.kind as any}`, ); } function makeCovariant(javaType: string): string { // Don't emit a covariant expression for String (it's `final` in Java) if (javaType === 'java.lang.String') { return javaType; } return `? extends ${javaType}`; } } private toJavaPrimitive(primitive: spec.PrimitiveType) { switch (primitive) { case spec.PrimitiveType.Boolean: return 'java.lang.Boolean'; case spec.PrimitiveType.Date: return 'java.time.Instant'; case spec.PrimitiveType.Json: return 'com.fasterxml.jackson.databind.node.ObjectNode'; case spec.PrimitiveType.Number: return 'java.lang.Number'; case spec.PrimitiveType.String: return 'java.lang.String'; case spec.PrimitiveType.Any: return 'java.lang.Object'; default: throw new Error(`Unknown primitive type: ${primitive as any}`); } } private renderMethodCallArguments(method: spec.Callable) { if (!method.parameters || method.parameters.length === 0) { return ''; } const regularParams = method.parameters.filter((p) => !p.variadic); const values = regularParams.map(_renderParameter); const valueStr = `new Object[] { ${values.join(', ')} }`; if (method.variadic) { const valuesStream = `java.util.Arrays.<Object>stream(${valueStr})`; const lastParam = method.parameters[method.parameters.length - 1]; const restStream = `java.util.Arrays.<Object>stream(${lastParam.name})`; const fullStream = regularParams.length > 0 ? `java.util.stream.Stream.concat(${valuesStream}, ${restStream})` : restStream; return `, ${fullStream}.toArray(Object[]::new)`; } return `, ${valueStr}`; function _renderParameter(param: spec.Parameter) { const safeName = JavaGenerator.safeJavaPropertyName(param.name); return isNullable(param) ? safeName : `java.util.Objects.requireNonNull(${safeName}, "${safeName} is required")`; } } private renderMethodCall( cls: spec.TypeReference, method: spec.Method, async: boolean, ) { let statement = ''; if (method.static) { const javaClass = this.toJavaType(cls); statement += `software.amazon.jsii.JsiiObject.jsiiStaticCall(${javaClass}.class, `; } else { statement += `software.amazon.jsii.Kernel.${ async ? 'asyncCall' : 'call' }(this, `; } statement += `"${method.name}"`; if (method.returns) { statement += `, ${this.toNativeType(method.returns.type, { forMarshalling: true, })}`; } else { statement += ', software.amazon.jsii.NativeType.VOID'; } statement += `${this.renderMethodCallArguments(method)})`; if (method.returns) { statement = this.wrapCollection( statement, method.returns.type, method.returns.optional, ); } if (method.returns) { return `return ${statement};`; } return `${statement};`; } /** * Wraps a collection into an unmodifiable collection else returns the existing statement. * @param statement The statement to wrap if necessary. * @param type The type of the object to wrap. * @param optional Whether the value is optional (can be null/undefined) or not. * @returns The modified or original statement. */ private wrapCollection( statement: string, type: spec.TypeReference, optional?: boolean, ): string { if (spec.isCollectionTypeReference(type)) { let wrapper: string; switch (type.collection.kind) { case spec.CollectionKind.Array: wrapper = 'unmodifiableList'; break; case spec.CollectionKind.Map: wrapper = 'unmodifiableMap'; break; default: throw new Error( `Unsupported collection kind: ${type.collection.kind as any}`, ); } // In the case of "optional", the value needs ot be explicitly cast to allow for cases where the raw type was returned. return optional ? `java.util.Optional.ofNullable((${this.toJavaType( type, )})(${statement})).map(java.util.Collections::${wrapper}).orElse(null)` : `java.util.Collections.${wrapper}(${statement})`; } return statement; } private renderMethodParameters(method: spec.Callable) { const params = []; if (method.parameters) { for (const p of method.parameters) { // We can render covariant parameters only for methods that aren't overridable... so only for static methods currently. params.push( `final ${this.toDecoratedJavaType(p, { covariant: (method as spec.Method).static, })}${p.variadic ? '...' : ''} ${JavaGenerator.safeJavaPropertyName( p.name, )}`, ); } } return params.join(', '); } private renderAccessLevel(method: spec.Callable | spec.Property) { return method.protected ? 'protected' : 'public'; } private makeModuleClass(moduleName: string) { return `${this.toNativeFqn(moduleName)}.${MODULE_CLASS_NAME}`; } private emitModuleFile(mod: spec.Assembly) { const moduleName = mod.name; const moduleClass = this.makeModuleClass(moduleName); const { filePath: moduleResFile, name: moduleResName } = this.toJavaResourcePath(mod, `${mod.name}.${MODULE_CLASS_NAME}`); this.code.openFile(moduleResFile); for (const fqn of Object.keys(this.assembly.types ?? {})) { this.code.line(`${fqn}=${this.toNativeFqn(fqn, { binaryName: true })}`); } this.code.closeFile(moduleResFile); const moduleFile = this.toJavaFilePath(mod, { assembly: mod.name, fqn: `${mod.name}.${MODULE_CLASS_NAME}`, kind: spec.TypeKind.Class, name: MODULE_CLASS_NAME, }); this.code.openFile(moduleFile); this.code.line(`package ${this.toNativeName(mod).packageName};`); this.code.line(); if (Object.keys(mod.dependencies ?? {}).length > 0) { this.code.line('import static java.util.Arrays.asList;'); this.code.line(); } this.code.line('import java.io.BufferedReader;'); this.code.line('import java.io.InputStream;'); this.code.line('import java.io.InputStreamReader;'); this.code.line('import java.io.IOException;'); this.code.line('import java.io.Reader;'); this.code.line('import java.io.UncheckedIOException;'); this.code.line(); this.code.line('import java.nio.charset.StandardCharsets;'); this.code.line(); this.code.line('import java.util.HashMap;'); if (Object.keys(mod.dependencies ?? {}).length > 0) { this.code.line('import java.util.List;'); } this.code.line('import java.util.Map;'); this.code.line(); this.code.line('import software.amazon.jsii.JsiiModule;'); this.code.line(); this.code.line(ANN_INTERNAL); this.code.openBlock( `public final class ${MODULE_CLASS_NAME} extends JsiiModule`, ); this.code.line( 'private static final Map<String, String> MODULE_TYPES = load();', ); this.code.line(); this.code.openBlock('private static Map<String, String> load()'); this.code.line('final Map<String, String> result = new HashMap<>();'); this.code.line( `final ClassLoader cl = ${MODULE_CLASS_NAME}.class.getClassLoader();`, ); this.code.line( `try (final InputStream is = cl.getResourceAsStream("${moduleResName}");`, ); this.code.line( ' final Reader rd = new InputStreamReader(is, StandardCharsets.UTF_8);', ); this.code.openBlock( ' final BufferedReader br = new BufferedReader(rd))', ); this.code.line('br.lines()'); this.code.line(' .filter(line -> !line.trim().isEmpty())'); this.code.openBlock(' .forEach(line -> '); this.code.line('final String[] parts = line.split("=", 2);'); this.code.line('final String fqn = parts[0];'); this.code.line('final String className = parts[1];'); this.code.line('result.put(fqn, className);'); this.code.unindent('});'); // Proxy for closeBlock this.code.closeBlock(); this.code.openBlock('catch (final IOException exception)'); this.code.line('throw new UncheckedIOException(exception);'); this.code.closeBlock(); this.code.line('return result;'); this.code.closeBlock(); this.code.line(); this.code.line( 'private final Map<String, Class<?>> cache = new HashMap<>();', ); this.code.line(); // ctor this.code.openBlock(`public ${MODULE_CLASS_NAME}()`); this.code.line( `super("${moduleName}", "${ mod.version }", ${MODULE_CLASS_NAME}.class, "${this.getAssemblyFileName()}");`, ); this.code.closeBlock(); // ctor // dependencies if (mod.dependencies && Object.keys(mod.dependencies).length > 0) { const deps = []; for (const dep of Object.keys(mod.dependencies)) { deps.push(`${this.makeModuleClass(dep)}.class`); } this.code.line(); this.code.line('@Override'); this.code.openBlock( 'public List<Class<? extends JsiiModule>> getDependencies()', ); this.code.line(`return asList(${deps.join(', ')});`); this.code.closeBlock(); } this.code.line(); this.code.line('@Override'); this.code.openBlock( 'protected Class<?> resolveClass(final String fqn) throws ClassNotFoundException', ); this.code.openBlock('if (!MODULE_TYPES.containsKey(fqn))'); this.code.line( 'throw new ClassNotFoundException("Unknown JSII type: " + fqn);', ); this.code.closeBlock(); this.code.line('String className = MODULE_TYPES.get(fqn);'); this.code.openBlock('if (!this.cache.containsKey(className))'); this.code.line('this.cache.put(className, this.findClass(className));'); this.code.closeBlock(); this.code.line('return this.cache.get(className);'); this.code.closeBlock(); this.code.line(); this.code.openBlock('private Class<?> findClass(final String binaryName)'); this.code.openBlock('try'); this.code.line('return Class.forName(binaryName);'); this.code.closeBlock(); this.code.openBlock('catch (final ClassNotFoundException exception)'); this.code.line('throw new RuntimeException(exception);'); this.code.closeBlock(); this.code.closeBlock(); this.code.closeBlock(); this.code.closeFile(moduleFile); return moduleClass; } private emitJsiiInitializers(cls: spec.ClassType) { this.code.line(); this.code.openBlock( `protected ${cls.name}(final software.amazon.jsii.JsiiObjectRef objRef)`, ); this.code.line('super(objRef);'); this.code.closeBlock(); this.code.line(); this.code.openBlock( `protected ${cls.name}(final software.amazon.jsii.JsiiObject.InitializationMode initializationMode)`, ); this.code.line('super(initializationMode);'); this.code.closeBlock(); } /** * Computes the java FQN for a JSII FQN: * 1. Determine which assembly the FQN belongs to (first component of the FQN) * 2. Locate the `targets.java.package` value for that assembly (this assembly, or one of the dependencies) * 3. Return the java FQN: ``<module.targets.java.package>.<FQN stipped of first component>`` * * Records an assembly reference if the referenced FQN comes from a different assembly. * * @param fqn the JSII FQN to be used. * * @returns the corresponding Java FQN. * * @throws if the assembly the FQN belongs to does not have a `targets.java.package` set. */ private toNativeFqn( fqn: string, { binaryName }: { binaryName: boolean } = { binaryName: false }, ): string { const [mod] = fqn.split('.'); const depMod = this.findModule(mod); // Make sure any dependency (direct or transitive) of which any type is explicitly referenced by the generated // code is included in the generated POM's dependencies section (protecting the artifact from changes in the // dependencies' dependency structure). if (mod !== this.assembly.name) { this.referencedModules[mod] = depMod; const translated = translateFqn({ ...depMod, name: mod }, fqn); return [translated.packageName, ...translated.typeNames].join('.'); } const { packageName, typeName } = fqn === this.assembly.name ? this.toNativeName(this.assembly) : this.toNativeName(this.assembly, this.assembly.types![fqn]); const className = typeName && binaryName ? typeName.replace('.', '$') : typeName; return `${packageName}${className ? `.${className}` : ''}`; } /** * Computes Java name for a jsii assembly or type. * * @param assm The assembly that contains the type * @param type The type we want the name of */ private toNativeName(assm: spec.Assembly): { packageName: string; typeName: undefined; }; private toNativeName( assm: spec.Assembly, type: spec.Type, ): { packageName: string; typeName: string }; private toNativeName( assm: spec.Assembly, type?: spec.Type, ): { packageName: string; typeName?: string } { if (!type) { return { packageName: packageNameFromAssembly(assm) }; } const translated = translateFqn(assm, type.fqn); return { packageName: translated.packageName, typeName: translated.typeNames.join('.'), }; } /** * Emits an ``@Generated`` annotation honoring the ``this.emitFullGeneratorInfo`` setting. */ private emitGeneratedAnnotation() { const date = this.emitFullGeneratorInfo ? `, date = "${new Date().toISOString()}"` : ''; const generator = this.emitFullGeneratorInfo ? `jsii-pacmak/${VERSION_DESC}` : 'jsii-pacmak'; this.code.line( `@javax.annotation.Generated(value = "${generator}"${date})`, ); } private convertExample(example: string, api: ApiLocation): string { const translated = this.rosetta.translateExample( api, example, TargetLanguage.JAVA, enforcesStrictMode(this.assembly), ); return translated.source; } private convertSamplesInMarkdown(markdown: string, api: ApiLocation): string { return this.rosetta.translateSnippetsInMarkdown( api, markdown, TargetLanguage.JAVA, enforcesStrictMode(this.assembly), ); } /** * Fins the Java FQN of the default implementation interfaces that should be implemented when a new * default interface or proxy class is being emitted. * * @param type the type for which a default interface or proxy is emitted. * @param includeThisType whether this class's default interface should be included or not. * * @returns a list of Java fully qualified class names. */ private defaultInterfacesFor( type: reflect.ClassType | reflect.InterfaceType, { includeThisType = false }: { includeThisType?: boolean } = {}, ): string[] { const result = new Set<string>(); if ( includeThisType && hasDefaultInterfaces(type.assembly) && type.isInterfaceType() ) { result.add( `${this.toNativeFqn(type.fqn)}.${INTERFACE_DEFAULT_CLASS_NAME}`, ); } else { for (const iface of type.interfaces) { if (hasDefaultInterfaces(iface.assembly)) { result.add( `${this.toNativeFqn(iface.fqn)}.${INTERFACE_DEFAULT_CLASS_NAME}`, ); } else { for (const item of this.defaultInterfacesFor(iface)) { result.add(item); } } } if (type.isClassType() && type.base != null) { for (const item of this.defaultInterfacesFor(type.base)) { result.add(item); } } } return Array.from(result); } } /** * This models the POM schema for a <dependency> entity * @see https://maven.apache.org/pom.html#Dependencies */ interface MavenDependency { groupId: string; artifactId: string; version: string; type?: string; scope?: 'compile' | 'provided' | 'runtime' | 'test' | 'system'; systemPath?: string; optional?: boolean; '#comment'?: string; } /** * Looks up the `@jsii/java-runtime` package from the local repository. * If it contains a "maven-repo" directory, it will be added as a local maven repo * so when we build locally, we build against it and not against the one published * to Maven Central. */ function findJavaRuntimeLocalRepository() { try { // eslint-disable-next-line @typescript-eslint/no-var-requires,@typescript-eslint/no-require-imports,import/no-extraneous-dependencies const javaRuntime = require('@jsii/java-runtime'); logging.info( `Using local version of the Java jsii runtime package at: ${javaRuntime.repository}`, ); return javaRuntime.repository; } catch { return undefined; } } function isNullable(optionalValue: spec.OptionalValue | undefined): boolean { if (!optionalValue) { return false; } return ( optionalValue.optional || (spec.isPrimitiveTypeReference(optionalValue.type) && optionalValue.type.primitive === spec.PrimitiveType.Any) ); } function paramJavadoc( name: string, optional?: boolean, summary?: string, ): string { const parts = ['@param', name]; if (summary) { parts.push(endWithPeriod(summary)); } if (!optional) { parts.push('This parameter is required.'); } return parts.join(' '); } function endWithPeriod(s: string): string { s = s.trimRight(); if (!s.endsWith('.')) { return `${s}.`; } return s; } function computeOverrides<T extends { param: spec.Parameter }>( allParams: T[], ): Iterable<T[]> { return { [Symbol.iterator]: function* () { yield allParams; while (allParams.length > 0) { const lastParam = allParams[allParams.length - 1]; if (!lastParam.param.variadic && !lastParam.param.optional) { // Neither variadic nor optional -- we're done here! return; } allParams = allParams.slice(0, allParams.length - 1); // If the lastParam was variadic, we shouldn't generate an override without it only. if (lastParam.param.optional) { yield allParams; } } }, }; } type AssemblyLike = spec.AssemblyConfiguration & { name: string }; /** * Return the native package name from an assembly */ function packageNameFromAssembly(assm: AssemblyLike) { const javaPackage = assm.targets?.java?.package; if (!javaPackage) { throw new Error( `The module ${assm.name} does not have a java.package setting`, ); } return javaPackage; } /** * Analyzes and translates a jsii FQN to Java components * * The FQN can be of the assembly, a submodule, or a type. * * Any type can have the following characteristics: * * - Located in zero or more nested submodules. Any of these can have a Java * package name assigned--if none, the name is automatically determined by * snake casing. At least the assembly must have a Java package name assigned. * - Located in zero or more nested types (classes). * * Find up the set of namespaces until we find a submodule (or the assembly * itself) that has an explicit Java package name defined. * * Append all the namespaces that we crossed that didn't have a package name defined. * * Returns the Java package name determined this way, as well as the hierarchy of type * names inside the package. `typeNames` may be missing or empty if the FQN indicated * the assembly or a submodule, contains 1 element if the FQN indicated a top-level type, * multiple elements if the FQN indicated a nested type. */ function translateFqn( assm: AssemblyLike, originalFqn: string, ): { packageName: string; typeNames: string[] } { const implicitPackageNames = new Array<string>(); const typeNames = new Array<string>(); // We work ourselves upward through the FQN until we've found an explicit package let packageName = packageNameFromAssembly(assm); let fqn = originalFqn; while (fqn !== '' && fqn !== assm.name) { const [parentFqn, lastPart] = splitNamespace(fqn); const submodule = assm.submodules?.[fqn]; if (submodule) { const explicitPackage = submodule.targets?.java?.package; if (explicitPackage) { packageName = explicitPackage; // We can stop recursing, types cannot be the parent of a module and nothing upwards can change // the package name anymore break; } implicitPackageNames.unshift(`.${toSnakeCase(lastPart)}`); } else { // If it's not a submodule, it must be a type. typeNames.unshift(lastPart); } fqn = parentFqn; } if (fqn === '') { throw new Error(`Could not find '${originalFqn}' inside '${assm.name}'`); } return { packageName: `${packageName}${implicitPackageNames.join('')}`, typeNames, }; } /** * Determines whether the provided assembly exposes the "hasDefaultInterfaces" * jsii-pacmak feature flag. * * @param assembly the assembly that is tested * * @returns true if the Jsii$Default interfaces can be used */ function hasDefaultInterfaces(assembly: reflect.Assembly): boolean { return !!assembly.metadata?.jsii?.pacmak?.hasDefaultInterfaces; } /** * Whecks whether a name corresponds to a method on `java.lang.Object`. It is not * possible to emit default interface implementation for those names because * these would always be replaced by the implementations on `Object`. * * @param name the checked name * * @returns `true` if a default implementation cannot be generated for this name. */ function isJavaLangObjectMethodName(name: string): boolean { return JAVA_LANG_OBJECT_METHOD_NAMES.has(name); } const JAVA_LANG_OBJECT_METHOD_NAMES = new Set([ 'clone', 'equals', 'finalize', 'getClass', 'hashCode', 'notify', 'notifyAll', 'toString', 'wait', ]); /** * In a dotted string, strip off the last dotted component */ function splitNamespace(ns: string): [string, string] { const dot = ns.lastIndexOf('.'); if (dot === -1) { return ['', ns]; } return [ns.substr(0, dot), ns.substr(dot + 1)]; }
the_stack
import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import throttlingSettingsTabStyles from './throttlingSettingsTab.css.js'; import type * as SDK from '../../core/sdk/sdk.js'; import * as UI from '../../ui/legacy/legacy.js'; const UIStrings = { /** *@description Text in Throttling Settings Tab of the Network panel */ networkThrottlingProfiles: 'Network Throttling Profiles', /** *@description Text of add conditions button in Throttling Settings Tab of the Network panel */ addCustomProfile: 'Add custom profile...', /** *@description A value in milliseconds *@example {3} PH1 */ dms: '{PH1} `ms`', /** *@description Text in Throttling Settings Tab of the Network panel */ profileName: 'Profile Name', /** * @description Label for a textbox that sets the download speed in the Throttling Settings Tab. * Noun, short for 'download speed'. */ download: 'Download', /** * @description Label for a textbox that sets the upload speed in the Throttling Settings Tab. * Noun, short for 'upload speed'. */ upload: 'Upload', /** * @description Label for a textbox that sets the latency in the Throttling Settings Tab. */ latency: 'Latency', /** *@description Text in Throttling Settings Tab of the Network panel */ optional: 'optional', /** *@description Error message for Profile Name input in Throtting pane of the Settings *@example {49} PH1 */ profileNameCharactersLengthMust: 'Profile Name characters length must be between 1 to {PH1} inclusive', /** *@description Error message for Download and Upload inputs in Throttling pane of the Settings *@example {Download} PH1 *@example {0} PH2 *@example {10000000} PH3 */ sMustBeANumberBetweenSkbsToSkbs: '{PH1} must be a number between {PH2} `kbit/s` to {PH3} `kbit/s` inclusive', /** *@description Error message for Latency input in Throttling pane of the Settings *@example {0} PH1 *@example {1000000} PH2 */ latencyMustBeAnIntegerBetweenSms: 'Latency must be an integer between {PH1} `ms` to {PH2} `ms` inclusive', /** * @description Text in Throttling Settings Tab of the Network panel, indicating the download or * upload speed that will be applied in kilobits per second. * @example {25} PH1 */ dskbits: '{PH1} `kbit/s`', /** * @description Text in Throttling Settings Tab of the Network panel, indicating the download or * upload speed that will be applied in megabits per second. * @example {25.4} PH1 */ fsmbits: '{PH1} `Mbit/s`', }; const str_ = i18n.i18n.registerUIStrings('panels/mobile_throttling/ThrottlingSettingsTab.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); let throttlingSettingsTabInstance: ThrottlingSettingsTab; export class ThrottlingSettingsTab extends UI.Widget.VBox implements UI.ListWidget.Delegate<SDK.NetworkManager.Conditions> { private readonly list: UI.ListWidget.ListWidget<SDK.NetworkManager.Conditions>; private readonly customSetting: Common.Settings.Setting<SDK.NetworkManager.Conditions[]>; private editor?: UI.ListWidget.Editor<SDK.NetworkManager.Conditions>; constructor() { super(true); const header = this.contentElement.createChild('div', 'header'); header.textContent = i18nString(UIStrings.networkThrottlingProfiles); UI.ARIAUtils.markAsHeading(header, 1); const addButton = UI.UIUtils.createTextButton( i18nString(UIStrings.addCustomProfile), this.addButtonClicked.bind(this), 'add-conditions-button'); this.contentElement.appendChild(addButton); this.list = new UI.ListWidget.ListWidget(this); this.list.element.classList.add('conditions-list'); this.list.show(this.contentElement); this.customSetting = Common.Settings.Settings.instance().moduleSetting('customNetworkConditions'); this.customSetting.addChangeListener(this.conditionsUpdated, this); this.setDefaultFocusedElement(addButton); } static instance(opts = {forceNew: null}): ThrottlingSettingsTab { const {forceNew} = opts; if (!throttlingSettingsTabInstance || forceNew) { throttlingSettingsTabInstance = new ThrottlingSettingsTab(); } return throttlingSettingsTabInstance; } wasShown(): void { super.wasShown(); this.list.registerCSSFiles([throttlingSettingsTabStyles]); this.registerCSSFiles([throttlingSettingsTabStyles]); this.conditionsUpdated(); } private conditionsUpdated(): void { this.list.clear(); const conditions = this.customSetting.get(); for (let i = 0; i < conditions.length; ++i) { this.list.appendItem(conditions[i], true); } this.list.appendSeparator(); } private addButtonClicked(): void { this.list.addNewItem(this.customSetting.get().length, {title: () => '', download: -1, upload: -1, latency: 0}); } renderItem(conditions: SDK.NetworkManager.Conditions, _editable: boolean): Element { const element = document.createElement('div'); element.classList.add('conditions-list-item'); const title = element.createChild('div', 'conditions-list-text conditions-list-title'); const titleText = title.createChild('div', 'conditions-list-title-text'); const castedTitle = this.retrieveOptionsTitle(conditions); titleText.textContent = castedTitle; UI.Tooltip.Tooltip.install(titleText, castedTitle); element.createChild('div', 'conditions-list-separator'); element.createChild('div', 'conditions-list-text').textContent = throughputText(conditions.download); element.createChild('div', 'conditions-list-separator'); element.createChild('div', 'conditions-list-text').textContent = throughputText(conditions.upload); element.createChild('div', 'conditions-list-separator'); element.createChild('div', 'conditions-list-text').textContent = i18nString(UIStrings.dms, {PH1: conditions.latency}); return element; } removeItemRequested(_item: SDK.NetworkManager.Conditions, index: number): void { const list = this.customSetting.get(); list.splice(index, 1); this.customSetting.set(list); } retrieveOptionsTitle(conditions: SDK.NetworkManager.Conditions): string { // The title is usually an i18nLazyString except for custom values that are stored in the local storage in the form of a string. const castedTitle = typeof conditions.title === 'function' ? conditions.title() : conditions.title; return castedTitle; } commitEdit( conditions: SDK.NetworkManager.Conditions, editor: UI.ListWidget.Editor<SDK.NetworkManager.Conditions>, isNew: boolean): void { conditions.title = editor.control('title').value.trim(); const download = editor.control('download').value.trim(); conditions.download = download ? parseInt(download, 10) * (1000 / 8) : -1; const upload = editor.control('upload').value.trim(); conditions.upload = upload ? parseInt(upload, 10) * (1000 / 8) : -1; const latency = editor.control('latency').value.trim(); conditions.latency = latency ? parseInt(latency, 10) : 0; const list = this.customSetting.get(); if (isNew) { list.push(conditions); } this.customSetting.set(list); } beginEdit(conditions: SDK.NetworkManager.Conditions): UI.ListWidget.Editor<SDK.NetworkManager.Conditions> { const editor = this.createEditor(); editor.control('title').value = this.retrieveOptionsTitle(conditions); editor.control('download').value = conditions.download <= 0 ? '' : String(conditions.download / (1000 / 8)); editor.control('upload').value = conditions.upload <= 0 ? '' : String(conditions.upload / (1000 / 8)); editor.control('latency').value = conditions.latency ? String(conditions.latency) : ''; return editor; } private createEditor(): UI.ListWidget.Editor<SDK.NetworkManager.Conditions> { if (this.editor) { return this.editor; } const editor = new UI.ListWidget.Editor<SDK.NetworkManager.Conditions>(); this.editor = editor; const content = editor.contentElement(); const titles = content.createChild('div', 'conditions-edit-row'); const nameLabel = titles.createChild('div', 'conditions-list-text conditions-list-title'); const nameStr = i18nString(UIStrings.profileName); const nameLabelText = nameLabel.createChild('div', 'conditions-list-title-text'); nameLabelText.textContent = nameStr; titles.createChild('div', 'conditions-list-separator conditions-list-separator-invisible'); const downloadLabel = titles.createChild('div', 'conditions-list-text'); const downloadStr = i18nString(UIStrings.download); const downloadLabelText = downloadLabel.createChild('div', 'conditions-list-title-text'); downloadLabelText.textContent = downloadStr; titles.createChild('div', 'conditions-list-separator conditions-list-separator-invisible'); const uploadLabel = titles.createChild('div', 'conditions-list-text'); const uploadLabelText = uploadLabel.createChild('div', 'conditions-list-title-text'); const uploadStr = i18nString(UIStrings.upload); uploadLabelText.textContent = uploadStr; titles.createChild('div', 'conditions-list-separator conditions-list-separator-invisible'); const latencyLabel = titles.createChild('div', 'conditions-list-text'); const latencyStr = i18nString(UIStrings.latency); const latencyLabelText = latencyLabel.createChild('div', 'conditions-list-title-text'); latencyLabelText.textContent = latencyStr; const fields = content.createChild('div', 'conditions-edit-row'); const nameInput = editor.createInput('title', 'text', '', titleValidator); UI.ARIAUtils.setAccessibleName(nameInput, nameStr); fields.createChild('div', 'conditions-list-text conditions-list-title').appendChild(nameInput); fields.createChild('div', 'conditions-list-separator conditions-list-separator-invisible'); let cell = fields.createChild('div', 'conditions-list-text'); const downloadInput = editor.createInput('download', 'text', i18n.i18n.lockedString('kbit/s'), throughputValidator); cell.appendChild(downloadInput); UI.ARIAUtils.setAccessibleName(downloadInput, downloadStr); const downloadOptional = cell.createChild('div', 'conditions-edit-optional'); const optionalStr = i18nString(UIStrings.optional); downloadOptional.textContent = optionalStr; UI.ARIAUtils.setDescription(downloadInput, optionalStr); fields.createChild('div', 'conditions-list-separator conditions-list-separator-invisible'); cell = fields.createChild('div', 'conditions-list-text'); const uploadInput = editor.createInput('upload', 'text', i18n.i18n.lockedString('kbit/s'), throughputValidator); UI.ARIAUtils.setAccessibleName(uploadInput, uploadStr); cell.appendChild(uploadInput); const uploadOptional = cell.createChild('div', 'conditions-edit-optional'); uploadOptional.textContent = optionalStr; UI.ARIAUtils.setDescription(uploadInput, optionalStr); fields.createChild('div', 'conditions-list-separator conditions-list-separator-invisible'); cell = fields.createChild('div', 'conditions-list-text'); const latencyInput = editor.createInput('latency', 'text', i18n.i18n.lockedString('ms'), latencyValidator); UI.ARIAUtils.setAccessibleName(latencyInput, latencyStr); cell.appendChild(latencyInput); const latencyOptional = cell.createChild('div', 'conditions-edit-optional'); latencyOptional.textContent = optionalStr; UI.ARIAUtils.setDescription(latencyInput, optionalStr); return editor; function titleValidator(_item: SDK.NetworkManager.Conditions, _index: number, input: UI.ListWidget.EditorControl): UI.ListWidget.ValidatorResult { const maxLength = 49; const value = input.value.trim(); const valid = value.length > 0 && value.length <= maxLength; if (!valid) { const errorMessage = i18nString(UIStrings.profileNameCharactersLengthMust, {PH1: maxLength}); return {valid, errorMessage}; } return {valid, errorMessage: undefined}; } function throughputValidator( _item: SDK.NetworkManager.Conditions, _index: number, input: UI.ListWidget.EditorControl): UI.ListWidget.ValidatorResult { const minThroughput = 0; const maxThroughput = 10000000; const value = input.value.trim(); const parsedValue = Number(value); const throughput = input.getAttribute('aria-label'); const valid = !Number.isNaN(parsedValue) && parsedValue >= minThroughput && parsedValue <= maxThroughput; if (!valid) { const errorMessage = i18nString( UIStrings.sMustBeANumberBetweenSkbsToSkbs, {PH1: String(throughput), PH2: minThroughput, PH3: maxThroughput}); return {valid, errorMessage}; } return {valid, errorMessage: undefined}; } function latencyValidator(_item: SDK.NetworkManager.Conditions, _index: number, input: UI.ListWidget.EditorControl): UI.ListWidget.ValidatorResult { const minLatency = 0; const maxLatency = 1000000; const value = input.value.trim(); const parsedValue = Number(value); const valid = Number.isInteger(parsedValue) && parsedValue >= minLatency && parsedValue <= maxLatency; if (!valid) { const errorMessage = i18nString(UIStrings.latencyMustBeAnIntegerBetweenSms, {PH1: minLatency, PH2: maxLatency}); return {valid, errorMessage}; } return {valid, errorMessage: undefined}; } } } function throughputText(throughput: number): string { if (throughput < 0) { return ''; } const throughputInKbps = throughput / (1000 / 8); if (throughputInKbps < 1000) { return i18nString(UIStrings.dskbits, {PH1: throughputInKbps}); } if (throughputInKbps < 1000 * 10) { const formattedResult = (throughputInKbps / 1000).toFixed(1); return i18nString(UIStrings.fsmbits, {PH1: formattedResult}); } // TODO(petermarshall): Figure out if there is a difference we need to tell i18n about // for these two versions: one with decimal places and one without. return i18nString(UIStrings.fsmbits, {PH1: (throughputInKbps / 1000) | 0}); }
the_stack
import * as request from 'supertest'; import app from '../src/api/app'; import { User, Scan, connectToDatabase, Organization, OrganizationTag, UserType } from '../src/models'; import { createUserToken } from './util'; import { handler as scheduler } from '../src/tasks/scheduler'; import { Organizations } from 'aws-sdk'; jest.mock('../src/tasks/scheduler', () => ({ handler: jest.fn() })); describe('scan', () => { beforeAll(async () => { await connectToDatabase(); }); describe('list', () => { it('list by globalAdmin should return all scans', async () => { const name = 'test-' + Math.random(); await Scan.create({ name, arguments: {}, frequency: 999999 }).save(); await Scan.create({ name: name + '-2', arguments: {}, frequency: 999999 }).save(); const organization = await Organization.create({ name: 'test-' + Math.random(), rootDomains: ['test-' + Math.random()], ipBlocks: [], isPassive: false }).save(); const response = await request(app) .get('/scans') .set( 'Authorization', createUserToken({ userType: UserType.GLOBAL_ADMIN }) ) .expect(200); expect(response.body.scans.length).toBeGreaterThanOrEqual(2); expect(response.body.organizations.length).toBeGreaterThanOrEqual(1); expect( response.body.organizations.map((e) => e.id).indexOf(organization.id) ).toBeGreaterThan(-1); }); // it('list by globalView should fail', async () => { // const name = 'test-' + Math.random(); // await Scan.create({ // name, // arguments: {}, // frequency: 999999 // }).save(); // await Scan.create({ // name: name + '-2', // arguments: {}, // frequency: 999999 // }).save(); // const response = await request(app) // .get('/scans') // .set( // 'Authorization', // createUserToken({ // userType: UserType.GLOBAL_VIEW // }) // ) // .expect(403); // }); }); describe('listGranular', () => { it('list by regular user should return all granular scans', async () => { const name = 'test-' + Math.random(); const scan1 = await Scan.create({ name, arguments: {}, frequency: 999999, isGranular: false, isSingleScan: false }).save(); const scan2 = await Scan.create({ name: name + '-2', arguments: {}, frequency: 999999, isGranular: true, isSingleScan: false }).save(); const response = await request(app) .get('/granularScans') .set('Authorization', createUserToken({})) .expect(200); expect(response.body.scans.length).toBeGreaterThanOrEqual(1); expect(response.body.scans.map((e) => e.id).indexOf(scan1.id)).toEqual( -1 ); expect( response.body.scans.map((e) => e.id).indexOf(scan2.id) ).toBeGreaterThanOrEqual(-1); }); it('list by regular user should exclude single scans', async () => { const name = 'test-' + Math.random(); const scan1 = await Scan.create({ name, arguments: {}, frequency: 999999, isGranular: true, isSingleScan: false }).save(); const scan2 = await Scan.create({ name: name + '-2', arguments: {}, frequency: 999999, isGranular: true, isSingleScan: true }).save(); const response = await request(app) .get('/granularScans') .set('Authorization', createUserToken({})) .expect(200); expect(response.body.scans.length).toBeGreaterThanOrEqual(1); expect(response.body.scans.map((e) => e.id).indexOf(scan2.id)).toEqual( -1 ); }); }); describe('create', () => { it('create by globalAdmin should succeed', async () => { const user = await User.create({ firstName: '', lastName: '', email: Math.random() + '@crossfeed.cisa.gov', userType: UserType.GLOBAL_ADMIN }).save(); const name = 'censys'; const arguments_ = { a: 'b' }; const frequency = 999999; const response = await request(app) .post('/scans') .set( 'Authorization', createUserToken({ id: user.id, userType: UserType.GLOBAL_ADMIN }) ) .send({ name, arguments: arguments_, frequency, isGranular: false, organizations: [], isSingleScan: false, tags: [] }) .expect(200); expect(response.body.name).toEqual(name); expect(response.body.arguments).toEqual(arguments_); expect(response.body.frequency).toEqual(frequency); expect(response.body.isGranular).toEqual(false); expect(response.body.organizations).toEqual([]); expect(response.body.tags).toEqual([]); expect(response.body.createdBy.id).toEqual(user.id); }); it('create a granular scan by globalAdmin should succeed', async () => { const user = await User.create({ firstName: '', lastName: '', email: Math.random() + '@crossfeed.cisa.gov', userType: UserType.GLOBAL_ADMIN }).save(); const name = 'censys'; const arguments_ = { a: 'b' }; const frequency = 999999; const tag = await OrganizationTag.create({ name: 'test-' + Math.random() }).save(); const organization = await Organization.create({ name: 'test-' + Math.random(), rootDomains: ['test-' + Math.random()], ipBlocks: [], isPassive: false, tags: [tag] }).save(); const response = await request(app) .post('/scans') .set( 'Authorization', createUserToken({ id: user.id, userType: UserType.GLOBAL_ADMIN }) ) .send({ name, arguments: arguments_, frequency, isGranular: true, organizations: [organization.id], isSingleScan: false, tags: [tag] }) .expect(200); expect(response.body.name).toEqual(name); expect(response.body.arguments).toEqual(arguments_); expect(response.body.frequency).toEqual(frequency); expect(response.body.isGranular).toEqual(true); expect(response.body.organizations).toEqual([ { id: organization.id } ]); expect(response.body.tags[0].id).toEqual(tag.id); }); it('create by globalView should fail', async () => { const name = 'censys'; const arguments_ = { a: 'b' }; const frequency = 999999; const response = await request(app) .post('/scans') .set( 'Authorization', createUserToken({ userType: UserType.GLOBAL_VIEW }) ) .send({ name, arguments: arguments_, frequency, isGranular: false, organizations: [], isSingleScan: false }) .expect(403); expect(response.body).toEqual({}); }); }); describe('update', () => { it('update by globalAdmin should succeed', async () => { const scan = await Scan.create({ name: 'censys', arguments: {}, frequency: 999999 }).save(); const name = 'findomain'; const arguments_ = { a: 'b2' }; const frequency = 999991; const response = await request(app) .put(`/scans/${scan.id}`) .set( 'Authorization', createUserToken({ userType: UserType.GLOBAL_ADMIN }) ) .send({ name, arguments: arguments_, frequency, isGranular: false, organizations: [], isSingleScan: false, tags: [] }) .expect(200); expect(response.body.name).toEqual(name); expect(response.body.arguments).toEqual(arguments_); expect(response.body.frequency).toEqual(frequency); }); it('update a non-granular scan to a granular scan by globalAdmin should succeed', async () => { const scan = await Scan.create({ name: 'censys', arguments: {}, frequency: 999999, isGranular: false, isSingleScan: false }).save(); const tag = await OrganizationTag.create({ name: 'test-' + Math.random() }).save(); const organization = await Organization.create({ name: 'test-' + Math.random(), rootDomains: ['test-' + Math.random()], ipBlocks: [], isPassive: false, tags: [tag] }).save(); const name = 'findomain'; const arguments_ = { a: 'b2' }; const frequency = 999991; const response = await request(app) .put(`/scans/${scan.id}`) .set( 'Authorization', createUserToken({ userType: UserType.GLOBAL_ADMIN }) ) .send({ name, arguments: arguments_, frequency, isGranular: true, organizations: [organization.id], isSingleScan: false, tags: [tag] }) .expect(200); expect(response.body.name).toEqual(name); expect(response.body.arguments).toEqual(arguments_); expect(response.body.frequency).toEqual(frequency); expect(response.body.isGranular).toEqual(true); expect(response.body.organizations).toEqual([ { id: organization.id } ]); expect(response.body.tags[0].id).toEqual(tag.id); }); it('update by globalView should fail', async () => { const scan = await Scan.create({ name: 'censys', arguments: {}, frequency: 999999 }).save(); const name = 'findomain'; const arguments_ = { a: 'b2' }; const frequency = 999991; const response = await request(app) .put(`/scans/${scan.id}`) .set( 'Authorization', createUserToken({ userType: UserType.GLOBAL_VIEW }) ) .send({ name, arguments: arguments_, frequency }) .expect(403); expect(response.body).toEqual({}); }); }); describe('delete', () => { it('delete by globalAdmin should succeed', async () => { const scan = await Scan.create({ name: 'censys', arguments: {}, frequency: 999999 }).save(); const response = await request(app) .del(`/scans/${scan.id}`) .set( 'Authorization', createUserToken({ userType: UserType.GLOBAL_ADMIN }) ) .expect(200); expect(response.body.affected).toEqual(1); }); it('delete by globalView should fail', async () => { const scan = await Scan.create({ name: 'censys', arguments: {}, frequency: 999999 }).save(); const response = await request(app) .del(`/scans/${scan.id}`) .set( 'Authorization', createUserToken({ userType: UserType.GLOBAL_VIEW }) ) .expect(403); expect(response.body).toEqual({}); }); }); describe('get', () => { it('get by globalView should succeed', async () => { const scan = await Scan.create({ name: 'censys', arguments: {}, frequency: 999999 }).save(); const response = await request(app) .get(`/scans/${scan.id}`) .set( 'Authorization', createUserToken({ userType: UserType.GLOBAL_VIEW }) ) .expect(200); expect(response.body.scan.name).toEqual('censys'); }); it('get by regular user on a scan not from their org should fail', async () => { const scan = await Scan.create({ name: 'censys', arguments: {}, frequency: 999999 }).save(); const response = await request(app) .get(`/scans/${scan.id}`) .set('Authorization', createUserToken({})) .expect(403); expect(response.body).toEqual({}); }); }); }); describe('scheduler invoke', () => { it('invoke by globalAdmin should succeed', async () => { const response = await request(app) .post(`/scheduler/invoke`) .set( 'Authorization', createUserToken({ userType: UserType.GLOBAL_ADMIN }) ) .expect(200); expect(response.body).toEqual({}); expect(scheduler).toHaveBeenCalledTimes(1); }); it('invoke by globalView should fail', async () => { const response = await request(app) .post(`/scheduler/invoke`) .set( 'Authorization', createUserToken({ userType: UserType.GLOBAL_VIEW }) ) .expect(403); expect(response.body).toEqual({}); expect(scheduler).toHaveBeenCalledTimes(0); }); }); describe('run scan', () => { it('run scan should manualRunPending to true', async () => { const scan = await Scan.create({ name: 'censys', arguments: {}, frequency: 999999, lastRun: new Date() }).save(); const response = await request(app) .post(`/scans/${scan.id}/run`) .set( 'Authorization', createUserToken({ userType: UserType.GLOBAL_ADMIN }) ) .expect(200); expect(response.body.manualRunPending).toEqual(true); }); it('runScan by globalView should fail', async () => { const scan = await Scan.create({ name: 'censys', arguments: {}, frequency: 999999, lastRun: new Date() }).save(); const response = await request(app) .post(`/scans/${scan.id}/run`) .set( 'Authorization', createUserToken({ userType: UserType.GLOBAL_VIEW }) ) .expect(403); expect(response.body).toEqual({}); }); });
the_stack
import { ChallengeRegistry, ProxyFactory, MinimumViableMultisig, ERC20, SetStateCommitment, } from "@connext/contracts"; import { JsonRpcProvider, CONVENTION_FOR_ETH_ASSET_ID, CoinTransfer, SetStateCommitmentJSON, ChallengeEvents, ChallengeStatus, IStoreService, } from "@connext/types"; import { toBN, getRandomChannelSigner, getChainId } from "@connext/utils"; import { BigNumber, Wallet, Contract, constants, utils } from "ethers"; import { AppWithCounterClass, AppWithCounterAction, ActionType } from "./appWithCounter"; import { getMemoryStore } from "@connext/store"; import { MiniFreeBalance } from "./miniFreeBalance"; import { deployTestArtifactsToChain, mineBlock } from "./contracts"; import { CREATE_PROXY_AND_SETUP_GAS } from "./utils"; import { expect, verifyChallengeUpdatedEvent } from "./assertions"; const { One, Zero } = constants; const { Interface } = utils; export type TokenIndexedBalance = { [tokenAddress: string]: CoinTransfer[] }; export type CreatedAppInstanceOpts = { balances: TokenIndexedBalance; defaultTimeout: BigNumber; }; const MAX_FUNDING_RETRIES = 3; ///////////////////////////// // Context export const getAndInitStore = async (): Promise<IStoreService> => { const store = getMemoryStore(); await store.init(); await store.clear(); return store; }; export const setupContext = async ( shouldLoadStore: boolean = true, // ensure one is actually created when no opts provided providedOpts?: Partial<CreatedAppInstanceOpts>[], ) => { // setup constants / defaults const ethProvider = process.env.ETHPROVIDER_URL; const chainId = await getChainId(ethProvider!); const providers = { [chainId]: new JsonRpcProvider(ethProvider, await getChainId(ethProvider!)) }; const wallet = Wallet.fromMnemonic(process.env.SUGAR_DADDY!).connect(providers[chainId]); const signers = [getRandomChannelSigner(ethProvider), getRandomChannelSigner(ethProvider)]; const defaultAppOpts = { balances: { [CONVENTION_FOR_ETH_ASSET_ID]: [ { to: signers[0].address, amount: One }, { to: signers[1].address, amount: Zero }, ], }, defaultTimeout: Zero, }; const store = await getAndInitStore(); // deploy contracts await wallet.getTransactionCount(); const networkContext = await deployTestArtifactsToChain(wallet); await wallet.getTransactionCount(); const challengeRegistry = new Contract( networkContext.ChallengeRegistry, ChallengeRegistry.abi, wallet, ); // deploy multisig const proxyFactory = new Contract(networkContext.ProxyFactory, ProxyFactory.abi, wallet); const multisigAddress: string = await new Promise(async (resolve) => { proxyFactory.once("ProxyCreation", async (proxyAddress: string) => resolve(proxyAddress)); await proxyFactory.createProxyWithNonce( networkContext.MinimumViableMultisig, new Interface(MinimumViableMultisig.abi).encodeFunctionData("setup", [ [signers[0].address, signers[1].address], ]), 0, { gasLimit: CREATE_PROXY_AND_SETUP_GAS }, ); }); // if it is successfully deployed, should be able to call amount withdraw const withdrawn = await new Contract( multisigAddress, MinimumViableMultisig.abi, wallet, ).totalAmountWithdrawn(CONVENTION_FOR_ETH_ASSET_ID); expect(withdrawn).to.be.eq(Zero); // create objects from provided overrides const activeApps = (providedOpts || [defaultAppOpts]).map((provided, idx) => { const { balances, defaultTimeout } = { ...defaultAppOpts, ...provided, }; return new AppWithCounterClass( signers, multisigAddress, networkContext.AppWithAction, defaultTimeout, // default timeout toBN(idx).add(2), // channel nonce = idx + free-bal + 1 balances, ); }); const [freeBalance, channel] = MiniFreeBalance.channelFactory( signers, chainId, multisigAddress, networkContext, activeApps, { [CONVENTION_FOR_ETH_ASSET_ID]: [ { to: signers[0].address, amount: Zero }, { to: signers[1].address, amount: Zero }, ], [networkContext.Token]: [ { to: signers[0].address, amount: Zero }, { to: signers[1].address, amount: Zero }, ], }, ); // fund multisig with eth // gather all balance objects to reduce const appBalances: { [assetId: string]: CoinTransfer[] }[] = activeApps .map((app) => app.tokenIndexedBalances) .concat(freeBalance.balances); const channelBalances: { [assetId: string]: BigNumber } = {}; Object.keys(freeBalance.balances).forEach((assetId) => { let assetTotal = Zero; appBalances.forEach((tokenIndexed) => { const appTotal = (tokenIndexed[assetId] || [{ to: "", amount: Zero }]).reduce( (prev, curr) => { return { to: "", amount: curr.amount.add(prev.amount) }; }, ).amount; assetTotal = assetTotal.add(appTotal); }); channelBalances[assetId] = assetTotal; }); const token = new Contract(networkContext.Token, ERC20.abi, wallet); for (let i = 0; i < MAX_FUNDING_RETRIES; i++) { try { const tx = await wallet.sendTransaction({ to: multisigAddress, value: channelBalances[CONVENTION_FOR_ETH_ASSET_ID], }); await tx.wait(); expect(await providers[chainId].getBalance(multisigAddress)).to.be.eq( channelBalances[CONVENTION_FOR_ETH_ASSET_ID], ); break; } catch (e) { console.log(`Failed to fund ETH attempt ${i}/${MAX_FUNDING_RETRIES}..`); } } for (let i = 0; i < MAX_FUNDING_RETRIES; i++) { try { const tx = await token.transfer(multisigAddress, channelBalances[networkContext.Token]); await tx.wait(); expect(await token.balanceOf(multisigAddress)).to.be.eq( channelBalances[networkContext.Token], ); break; } catch (e) { console.log(`Failed to fund tokens attempt ${i}/${MAX_FUNDING_RETRIES}..`); } } ///////////////////////////////////////// // contract helper functions const setAndProgressState = async ( action: AppWithCounterAction, app: AppWithCounterClass = activeApps[0], ) => { const setState0 = SetStateCommitment.fromJson( await app.getDoubleSignedSetState(networkContext.ChallengeRegistry), ); app.latestAction = action; const setState1 = SetStateCommitment.fromJson( await app.getSingleSignedSetState(networkContext.ChallengeRegistry), ); await wallet.getTransactionCount(); const tx = await challengeRegistry.setAndProgressState( app.appIdentity, await setState0.getSignedAppChallengeUpdate(), await setState1.getSignedAppChallengeUpdate(), AppWithCounterClass.encodeState(app.latestState), AppWithCounterClass.encodeAction(app.latestAction), ); return tx.wait(); }; const setState = async ( app: AppWithCounterClass, commitment: SetStateCommitmentJSON, ): Promise<void> => { const setState = SetStateCommitment.fromJson(commitment); const [event, tx] = await Promise.all([ new Promise((resolve) => { challengeRegistry.on( ChallengeEvents.ChallengeUpdated, ( identityHash: string, status: ChallengeStatus, appStateHash: string, versionNumber: BigNumber, finalizesAt: BigNumber, ) => { const converted = { identityHash, status, appStateHash, versionNumber: toBN(versionNumber), finalizesAt: toBN(finalizesAt), }; resolve(converted); }, ); }), new Promise(async (resolve, reject) => { try { const tx = await challengeRegistry.setState( setState.appIdentity, await setState.getSignedAppChallengeUpdate(), ); const response = await tx.wait(); resolve(response); } catch (e) { reject(e.message); } }), mineBlock(providers[chainId]), ]); expect((tx as any).transactionHash).to.be.ok; await verifyChallengeUpdatedEvent(app, setState.toJson(), event as any, providers[chainId]); }; const progressState = async (app: AppWithCounterClass = activeApps[0]) => { expect(app.latestAction).to.be.ok; const setState = SetStateCommitment.fromJson( await app.getSingleSignedSetState(networkContext.ChallengeRegistry), ); const tx = await challengeRegistry.progressState( app.appIdentity, await setState.getSignedAppChallengeUpdate(), AppWithCounterClass.encodeState(app.latestState), AppWithCounterClass.encodeAction(app.latestAction!), ); return tx.wait(); }; const cancelChallenge = async (app: AppWithCounterClass = activeApps[0]) => { const tx = await challengeRegistry.cancelDispute( app.appIdentity, await app.getCancelDisputeRequest(), ); return tx.wait(); }; ///////////////////////////////////////// // store helper functions const loadStore = async (store: IStoreService) => { // create the channel await store.createStateChannel( channel, await freeBalance.getSetup(), await freeBalance.getInitialSetState(), ); // add the app + all commitments to the store for (const app of activeApps) { await store.createAppProposal( multisigAddress, app.getProposal(), app.toJson().appSeqNo, await app.getInitialSetState(networkContext.ChallengeRegistry), await app.getConditional(freeBalance.identityHash, networkContext), ); // no need to create intermediate free balance state, since // it will always be overwritten with most recent in store await store.createAppInstance( multisigAddress, app.toJson(), freeBalance.toJson(), await freeBalance.getSetState(), ); await store.updateAppInstance( multisigAddress, app.toJson(), await app.getDoubleSignedSetState(networkContext.ChallengeRegistry), ); } }; if (shouldLoadStore) { await loadStore(store); } const addActionToAppInStore = async ( store: IStoreService, appPriorToAction: AppWithCounterClass, action: AppWithCounterAction = { increment: One, actionType: ActionType.SUBMIT_COUNTER_INCREMENT, }, ): Promise<AppWithCounterClass> => { appPriorToAction.latestAction = action; const setState1 = await appPriorToAction.getSingleSignedSetState( networkContext.ChallengeRegistry, ); await store.updateAppInstance(multisigAddress, appPriorToAction.toJson(), setState1); return appPriorToAction; }; return { ethProvider, challengeRegistry, providers, wallet, signers, store, multisigAddress, activeApps, freeBalance, networkContext, channelBalances, setAndProgressState, setState, progressState, cancelChallenge, loadStore, addActionToAppInStore, }; };
the_stack
import {ChartImpl, TEST_ONLY} from './chart'; import {ChartCallbacks, RendererType, ScaleType} from './public_types'; import { assertSvgPathD, buildMetadata, buildSeries, createSeries, } from './testing'; describe('line_chart_v2/lib/integration test', () => { let dom: SVGElement; let callbacks: ChartCallbacks; let chart: ChartImpl; let rafSpy: jasmine.Spy; function getDomChildren(): ReadonlyArray<SVGElement> { return dom.children as unknown as ReadonlyArray<SVGElement>; } beforeEach(() => { rafSpy = spyOn(TEST_ONLY.util, 'requestAnimationFrame').and.callFake( (cb: FrameRequestCallback) => { cb(0); return 0; } ); dom = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); callbacks = { onDrawEnd: jasmine.createSpy(), onContextLost: jasmine.createSpy(), }; chart = new ChartImpl({ type: RendererType.SVG, container: dom, callbacks, domDimension: {width: 200, height: 100}, useDarkMode: false, }); chart.setXScaleType(ScaleType.LINEAR); chart.setYScaleType(ScaleType.LINEAR); }); describe('render', () => { it('renders data', () => { chart.setMetadata({ line: buildMetadata({id: 'line', visible: true}), }); chart.setViewBox({x: [0, 10], y: [0, 10]}); expect(dom.children.length).toBe(0); chart.setData([createSeries('line', (index) => index)]); expect(dom.children.length).toBe(1); const path = dom.children[0] as SVGPathElement; expect(path.tagName).toBe('path'); expect(path.getAttribute('d')).toBe( 'M0,100L20,90L40,80L60,70L80,60L100,50L120,40L140,30L160,20L180,10' ); }); it('handles data without metadata', () => { chart.setMetadata({}); chart.setViewBox({x: [0, 10], y: [0, 10]}); chart.setData([createSeries('line', (index) => index)]); expect(dom.children.length).toBe(0); }); it('handles metadata without data', () => { chart.setMetadata({ line1: buildMetadata({id: 'line1', visible: true}), line2: buildMetadata({id: 'line2', visible: true}), }); chart.setViewBox({x: [0, 10], y: [0, 10]}); chart.setData([createSeries('line1', (index) => index)]); expect(dom.children.length).toBe(1); }); }); describe('chart update', () => { it('updates lines on data and metadata changes', () => { chart.setMetadata({ line1: buildMetadata({id: 'line1', visible: true}), line2: buildMetadata({id: 'line2', visible: true}), }); chart.setViewBox({x: [0, 10], y: [0, 20]}); chart.setData([createSeries('line1', (index) => index)]); expect(dom.children.length).toBe(1); const path1 = dom.children[0] as SVGPathElement; expect(path1.getAttribute('d')).toBe( 'M0,100L20,95L40,90L60,85L80,80L100,75L120,70L140,65L160,60L180,55' ); expect(path1.style.display).toBe(''); chart.setData([ createSeries('line1', (index) => index), createSeries('line2', (index) => index * 2), ]); expect(dom.children.length).toBe(2); const path2 = dom.children[1] as SVGPathElement; expect(path2.getAttribute('d')).toBe( ( 'M0,100 L20,90 L40,80 L60,70 L80,60 L100,50 L120,40 L140,30 L160,20 ' + 'L180,10' ).replace(/ /g, '') ); chart.setMetadata({ line1: buildMetadata({id: 'line1', visible: false}), line2: buildMetadata({id: 'line2', visible: true}), }); expect(dom.children.length).toBe(2); const path1After = dom.children[0] as SVGPathElement; expect(path1After.style.display).toBe('none'); }); it('updates on viewBox changes', () => { chart.setMetadata({ line: buildMetadata({id: 'line', visible: true}), }); chart.setViewBox({x: [0, 10], y: [0, 20]}); chart.setData([createSeries('line', (index) => index)]); const path = dom.children[0] as SVGPathElement; expect(path.getAttribute('d')).toBe( ( 'M0,100 L20,95 L40,90 L60,85 L80,80 L100,75 L120,70 L140,65 L160,60 ' + 'L180,55' ).replace(/ /g, '') ); chart.setViewBox({x: [0, 10], y: [0, 10]}); expect(path.getAttribute('d')).toBe( ( 'M0,100 L20,90 L40,80 L60,70 L80,60 L100,50 L120,40 L140,30 L160,20 ' + 'L180,10' ).replace(/ /g, '') ); }); it('updates once a requestAnimationFrame', () => { chart.setMetadata({ line: buildMetadata({id: 'line', visible: true}), }); chart.setViewBox({x: [0, 10], y: [0, 100]}); chart.setData([createSeries('line', (index) => index)]); const path = dom.children[0] as SVGPathElement; const pathDBefore = path.getAttribute('d'); const rafCallbacks: FrameRequestCallback[] = []; rafSpy.and.callFake((cb: FrameRequestCallback) => { return rafCallbacks.push(cb); }); chart.setViewBox({x: [0, 10], y: [0, 1]}); expect(rafCallbacks.length).toBe(1); expect(path.getAttribute('d')).toBe(pathDBefore); rafCallbacks.shift()!(1); expect(path.getAttribute('d')).not.toBe(pathDBefore); chart.setViewBox({x: [0, 10], y: [0, 20]}); chart.setViewBox({x: [0, 10], y: [0, 10]}); expect(rafCallbacks.length).toBe(1); }); it('invokes onDrawEnd after a repaint', () => { // Could have been called in beforeEach. Reset. (callbacks.onDrawEnd as jasmine.Spy).calls.reset(); const rafCallbacks: FrameRequestCallback[] = []; rafSpy.and.callFake((cb: FrameRequestCallback) => { return rafCallbacks.push(cb); }); chart.setMetadata({ line: buildMetadata({id: 'line', visible: true}), }); chart.setData([createSeries('line', (index) => index)]); chart.setViewBox({x: [0, 10], y: [0, 1]}); rafCallbacks.shift()!(0); expect(callbacks.onDrawEnd).toHaveBeenCalledTimes(1); }); it('updates line when axis changes', () => { chart.resize({width: 100, height: 100}); chart.setMetadata({ line: buildMetadata({id: 'line', visible: true}), }); chart.setViewBox({x: [1, 100], y: [0, 10]}); chart.setData([ { id: 'line', points: [ {x: 1, y: 10}, {x: 10, y: 5}, {x: 100, y: 6}, ], }, ]); expect(dom.children.length).toBe(1); const before = dom.children[0] as SVGPathElement; expect(before.tagName).toBe('path'); expect(before.getAttribute('d')).toBe('M0,0L9.090909004211426,50L100,40'); chart.setXScaleType(ScaleType.LOG10); expect(dom.children.length).toBe(1); const after = dom.children[0] as SVGPathElement; expect(after.tagName).toBe('path'); expect(after.getAttribute('d')).toBe('M0,0L50,50L100,40'); }); }); describe('null handling', () => { function isTriangle(el: Element): boolean { return el.classList.contains('triangle'); } it('renders all NaNs as triangles at 0s (with size of 12)', () => { chart.resize({width: 100, height: 100}); chart.setViewBox({x: [0, 100], y: [0, 100]}); chart.setMetadata({line: buildMetadata({id: 'line', visible: true})}); chart.setData([ buildSeries({ id: 'line', points: [ {x: 0, y: NaN}, {x: 50, y: NaN}, {x: 100, y: NaN}, ], }), ]); const children = getDomChildren(); expect(children.length).toBe(3); const [triangle1, triangle2, triangle3] = children; expect(isTriangle(triangle1)).toBe(true); assertSvgPathD(triangle1, [ [-6, 103], [6, 103], [0, 93], ]); expect(isTriangle(triangle2)).toBe(true); assertSvgPathD(triangle2, [ [44, 103], [56, 103], [50, 93], ]); expect(isTriangle(triangle3)).toBe(true); assertSvgPathD(triangle3, [ [94, 103], [106, 103], [100, 93], ]); }); it('breaks line into parts when NaN appears in the middle', () => { chart.resize({width: 10, height: 10}); chart.setViewBox({x: [0, 10], y: [0, 10]}); chart.setMetadata({line: buildMetadata({id: 'line', visible: true})}); chart.setData([ buildSeries({ id: 'line', points: [ {x: 1, y: 1}, {x: 3, y: 5}, {x: 5, y: NaN}, {x: 7, y: 1}, {x: 9, y: 10}, ], }), ]); const children = getDomChildren(); expect(children.length).toBe(3); const [line1, triangle, line2] = children; expect(isTriangle(line1)).toBe(false); assertSvgPathD(line1, [ [1, 9], [3, 5], ]); expect(isTriangle(triangle)).toBe(true); assertSvgPathD(triangle, [ [-1, 8], [11, 8], [5, -2], ]); expect(isTriangle(line2)).toBe(false); assertSvgPathD(line2, [ [7, 9], [9, 0], ]); }); it('puts first NaN value in place of NaN when starts with NaN', () => { chart.resize({width: 10, height: 10}); chart.setViewBox({x: [0, 10], y: [0, 10]}); chart.setMetadata({line: buildMetadata({id: 'line', visible: true})}); chart.setData([ buildSeries({ id: 'line', points: [ {x: 1, y: NaN}, {x: 3, y: NaN}, {x: 5, y: 5}, {x: 7, y: 1}, {x: 9, y: 10}, ], }), ]); const children = getDomChildren(); expect(children.length).toBe(3); const [triangle1, triangle2, line] = children; expect(isTriangle(triangle1)).toBe(true); assertSvgPathD(triangle1, [ [-5, 8], [7, 8], [1, -2], ]); expect(isTriangle(triangle2)).toBe(true); assertSvgPathD(triangle2, [ [-3, 8], [9, 8], [3, -2], ]); expect(isTriangle(line)).toBe(false); assertSvgPathD(line, [ [5, 5], [7, 9], [9, 0], ]); }); it('renders triangle for trailing NaNs', () => { chart.resize({width: 10, height: 10}); chart.setViewBox({x: [0, 10], y: [0, 10]}); chart.setMetadata({line: buildMetadata({id: 'line', visible: true})}); chart.setData([ buildSeries({ id: 'line', points: [ {x: 1, y: 10}, {x: 3, y: 0}, {x: 7, y: NaN}, {x: 9, y: NaN}, ], }), ]); const children = getDomChildren(); expect(children.length).toBe(3); const [line, triangle1, triangle2] = children; expect(isTriangle(line)).toBe(false); assertSvgPathD(line, [ [1, 0], [3, 10], ]); expect(isTriangle(triangle1)).toBe(true); assertSvgPathD(triangle1, [ [1, 13], [13, 13], [7, 3], ]); expect(isTriangle(triangle2)).toBe(true); assertSvgPathD(triangle2, [ [3, 13], [15, 13], [9, 3], ]); }); it('renders circle for single non-NaN point in between NaNs', () => { chart.resize({width: 10, height: 10}); chart.setViewBox({x: [0, 10], y: [0, 10]}); chart.setMetadata({line: buildMetadata({id: 'line', visible: true})}); chart.setData([ buildSeries({ id: 'line', points: [ {x: 1, y: NaN}, {x: 2, y: 5}, {x: 3, y: NaN}, ], }), ]); const children = getDomChildren(); expect(children.length).toBe(3); const [triangle1, circle, triangle2] = children; expect(isTriangle(triangle1)).toBe(true); expect(isTriangle(triangle2)).toBe(true); expect(circle.nodeName).toBe('circle'); expect(circle.getAttribute('cx')).toBe('2'); expect(circle.getAttribute('cy')).toBe('5'); }); it('renders circle for aux but not NaNs', () => { chart.resize({width: 10, height: 10}); chart.setViewBox({x: [0, 10], y: [0, 10]}); chart.setMetadata({ aux: buildMetadata({id: 'aux', visible: true, aux: true}), }); chart.setData([ buildSeries({ id: 'aux', points: [ {x: -1, y: 5}, {x: 0, y: 5}, {x: 1, y: NaN}, {x: 2, y: 5}, {x: 3, y: NaN}, ], }), ]); const children = getDomChildren(); expect(children.length).toBe(2); const [line, circle] = children; expect(isTriangle(line)).toBe(false); expect(isTriangle(circle)).toBe(false); assertSvgPathD(line, [ [-1, 5], [0, 5], ]); expect(circle.nodeName).toBe('circle'); expect(circle.getAttribute('cx')).toBe('2'); expect(circle.getAttribute('cy')).toBe('5'); }); }); describe('webgl', () => { it('invokes onContextLost after losing webgl context', async () => { const canvas = document.createElement('canvas'); chart = new ChartImpl({ type: RendererType.WEBGL, container: canvas, callbacks, domDimension: {width: 200, height: 100}, useDarkMode: false, devicePixelRatio: 1, }); chart.setXScaleType(ScaleType.LINEAR); chart.setYScaleType(ScaleType.LINEAR); expect(callbacks.onContextLost).not.toHaveBeenCalled(); // For more info about forcing context loss, see // https://developer.mozilla.org/en-US/docs/Web/API/WEBGL_lose_context/loseContext const glExtension = canvas .getContext('webgl2') ?.getExtension('WEBGL_lose_context'); if (!glExtension) { console.log( 'The browser used for testing does not ' + 'support WebGL or extensions needed for testing.' ); return; } // The `loseContext` triggers the event asynchronously, which. const contextLostPromise = new Promise((resolve) => { canvas.addEventListener('webglcontextlost', resolve); }); glExtension.loseContext(); await contextLostPromise; expect(callbacks.onContextLost).toHaveBeenCalledTimes(1); }); }); });
the_stack
import { AfterContentInit, ChangeDetectionStrategy, Component, ElementRef, EventEmitter, Inject, Input, NgZone, Optional, Output, ViewEncapsulation } from '@angular/core'; import { DOWN_ARROW, END, ENTER, HOME, LEFT_ARROW, PAGE_DOWN, PAGE_UP, RIGHT_ARROW, UP_ARROW } from '../core/keyboard/keycodes'; import { DateLocale } from './date-locale'; import { DateUtil } from './date-util'; import { slideCalendar } from './datepicker-animations'; import { MATERIAL_COMPATIBILITY_MODE } from '../core'; /** * A calendar that is used as part of the datepicker. * @docs-private */ @Component({ moduleId: module.id, selector: 'md2-calendar', templateUrl: 'calendar.html', styleUrls: ['calendar.css'], host: { '[class.md2-calendar]': 'true', 'tabindex': '0', '(keydown)': '_handleCalendarBodyKeydown($event)', }, animations: [slideCalendar], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class Md2Calendar implements AfterContentInit { @Input() type: 'date' | 'time' | 'month' | 'datetime' = 'date'; /** A date representing the period (month or year) to start the calendar in. */ @Input() startAt: Date; /** Whether the calendar should be started in month or year view. */ @Input() startView: 'clock' | 'month' | 'year' = 'month'; /** The currently selected date. */ @Input() selected: Date; /** The minimum selectable date. */ @Input() minDate: Date; /** The maximum selectable date. */ @Input() maxDate: Date; @Input() timeInterval: number = 1; /** A function used to filter which dates are selectable. */ @Input() dateFilter: (date: Date) => boolean; /** Emits when the currently selected date changes. */ @Output() selectedChange = new EventEmitter<Date>(); /** Date filter for the month and year views. */ _dateFilterForViews = (date: Date) => { return !!date && (!this.dateFilter || this.dateFilter(date)) && (!this.minDate || this._util.compareDate(date, this.minDate) >= 0) && (!this.maxDate || this._util.compareDate(date, this.maxDate) <= 0); } /** * The current active date. This determines which time period is shown and which date is * highlighted when using keyboard navigation. */ get _activeDate(): Date { return this._clampedActiveDate; } set _activeDate(value: Date) { let oldActiveDate = this._clampedActiveDate; this._clampedActiveDate = this._util.clampDate(value, this.minDate, this.maxDate); if (oldActiveDate && this._clampedActiveDate && this._currentView === 'month' && !this._util.isSameMonthAndYear(oldActiveDate, this._clampedActiveDate)) { if (this._util.isInNextMonth(oldActiveDate, this._clampedActiveDate)) { this.calendarState('right'); } else { this.calendarState('left'); } } } private _clampedActiveDate: Date; /** Whether the calendar is in month view. */ _currentView: 'clock' | 'month' | 'year' = 'month'; _clockView: 'hour' | 'minute' = 'hour'; /** The label for the current calendar view. */ get _yearLabel(): string { return this._locale.getYearName(this._activeDate); } get _monthYearLabel(): string { return this._currentView === 'month' ? this._locale.getMonthLabel(this._activeDate) : this._locale.getYearName(this._activeDate); } get _dateLabel(): string { return this._locale.getDateLabel(this._activeDate); } get _hoursLabel(): string { return ('0' + this._locale.getHoursLabel(this._activeDate)).slice(-2); } get _minutesLabel(): string { return ('0' + this._locale.getMinutesLabel(this._activeDate)).slice(-2); } _calendarState: string; constructor(private _elementRef: ElementRef, private _ngZone: NgZone, private _locale: DateLocale, private _util: DateUtil) { } ngAfterContentInit() { this._activeDate = this.startAt || this._util.today(); this._elementRef.nativeElement.focus(); if (this.type === 'month') { this._currentView = 'year'; } else if (this.type === 'time') { this._currentView = 'clock'; } else { this._currentView = this.startView || 'month'; } } /** Handles date selection in the month view. */ _dateSelected(date: Date): void { if (this.type == 'date') { if (!this._util.sameDate(date, this.selected)) { this.selectedChange.emit(date); } } else { this._activeDate = date; this._currentView = 'clock'; } } /** Handles month selection in the year view. */ _monthSelected(month: Date): void { if (this.type == 'month') { if (!this._util.isSameMonthAndYear(month, this.selected)) { this.selectedChange.emit(this._util.getFirstDateOfMonth(month)); } } else { this._activeDate = month; this._currentView = 'month'; this._clockView = 'hour'; } } _timeSelected(date: Date): void { if (this._clockView !== 'minute') { this._activeDate = date; this._clockView = 'minute'; } else { if (!this._util.sameDateAndTime(date, this.selected)) { this.selectedChange.emit(date); } } } _onActiveDateChange(date: Date) { this._activeDate = date; } _yearClicked(): void { this._currentView = 'year'; } _dateClicked(): void { this._currentView = 'month'; } _hoursClicked(): void { this._currentView = 'clock'; this._clockView = 'hour'; } _minutesClicked(): void { this._currentView = 'clock'; this._clockView = 'minute'; } /** Handles user clicks on the previous button. */ _previousClicked(): void { this._activeDate = this._currentView === 'month' ? this._util.addCalendarMonths(this._activeDate, -1) : this._util.addCalendarYears(this._activeDate, -1); } /** Handles user clicks on the next button. */ _nextClicked(): void { this._activeDate = this._currentView === 'month' ? this._util.addCalendarMonths(this._activeDate, 1) : this._util.addCalendarYears(this._activeDate, 1); } /** Whether the previous period button is enabled. */ _previousEnabled(): boolean { if (!this.minDate) { return true; } return !this.minDate || !this._isSameView(this._activeDate, this.minDate); } /** Whether the next period button is enabled. */ _nextEnabled(): boolean { return !this.maxDate || !this._isSameView(this._activeDate, this.maxDate); } /** Handles keydown events on the calendar body. */ _handleCalendarBodyKeydown(event: KeyboardEvent): void { // TODO(mmalerba): We currently allow keyboard navigation to disabled dates, but just prevent // disabled ones from being selected. This may not be ideal, we should look into whether // navigation should skip over disabled dates, and if so, how to implement that efficiently. if (this._currentView === 'month') { this._handleCalendarBodyKeydownInMonthView(event); } else if (this._currentView === 'year') { this._handleCalendarBodyKeydownInYearView(event); } else { this._handleCalendarBodyKeydownInClockView(event); } } /** Whether the two dates represent the same view in the current view mode (month or year). */ private _isSameView(date1: Date, date2: Date): boolean { return this._currentView === 'month' ? this._util.getYear(date1) == this._util.getYear(date2) && this._util.getMonth(date1) == this._util.getMonth(date2) : this._util.getYear(date1) == this._util.getYear(date2); } /** Handles keydown events on the calendar body when calendar is in month view. */ private _handleCalendarBodyKeydownInMonthView(event: KeyboardEvent): void { switch (event.keyCode) { case LEFT_ARROW: this._activeDate = this._util.addCalendarDays(this._activeDate, -1); break; case RIGHT_ARROW: this._activeDate = this._util.addCalendarDays(this._activeDate, 1); break; case UP_ARROW: this._activeDate = this._util.addCalendarDays(this._activeDate, -7); break; case DOWN_ARROW: this._activeDate = this._util.addCalendarDays(this._activeDate, 7); break; case HOME: this._activeDate = this._util.addCalendarDays(this._activeDate, 1 - this._util.getDate(this._activeDate)); break; case END: this._activeDate = this._util.addCalendarDays(this._activeDate, (this._util.getNumDaysInMonth(this._activeDate) - this._util.getDate(this._activeDate))); break; case PAGE_UP: this._activeDate = event.altKey ? this._util.addCalendarYears(this._activeDate, -1) : this._util.addCalendarMonths(this._activeDate, -1); break; case PAGE_DOWN: this._activeDate = event.altKey ? this._util.addCalendarYears(this._activeDate, 1) : this._util.addCalendarMonths(this._activeDate, 1); break; case ENTER: if (this._dateFilterForViews(this._activeDate)) { this._dateSelected(this._activeDate); // Prevent unexpected default actions such as form submission. event.preventDefault(); } return; default: // Don't prevent default or focus active cell on keys that we don't explicitly handle. return; } // Prevent unexpected default actions such as form submission. event.preventDefault(); } /** Handles keydown events on the calendar body when calendar is in year view. */ private _handleCalendarBodyKeydownInYearView(event: KeyboardEvent): void { switch (event.keyCode) { case LEFT_ARROW: this._activeDate = this._util.addCalendarMonths(this._activeDate, -1); break; case RIGHT_ARROW: this._activeDate = this._util.addCalendarMonths(this._activeDate, 1); break; case UP_ARROW: this._activeDate = this._prevMonthInSameCol(this._activeDate); break; case DOWN_ARROW: this._activeDate = this._nextMonthInSameCol(this._activeDate); break; case HOME: this._activeDate = this._util.addCalendarMonths(this._activeDate, -this._util.getMonth(this._activeDate)); break; case END: this._activeDate = this._util.addCalendarMonths(this._activeDate, 11 - this._util.getMonth(this._activeDate)); break; case PAGE_UP: this._activeDate = this._util.addCalendarYears(this._activeDate, event.altKey ? -10 : -1); break; case PAGE_DOWN: this._activeDate = this._util.addCalendarYears(this._activeDate, event.altKey ? 10 : 1); break; case ENTER: this._monthSelected(this._activeDate); break; default: // Don't prevent default or focus active cell on keys that we don't explicitly handle. return; } // Prevent unexpected default actions such as form submission. event.preventDefault(); } /** Handles keydown events on the calendar body when calendar is in month view. */ private _handleCalendarBodyKeydownInClockView(event: KeyboardEvent): void { switch (event.keyCode) { case UP_ARROW: this._activeDate = this._clockView == 'hour' ? this._util.addCalendarHours(this._activeDate, 1) : this._util.addCalendarMinutes(this._activeDate, 1); break; case DOWN_ARROW: this._activeDate = this._clockView == 'hour' ? this._util.addCalendarHours(this._activeDate, -1) : this._util.addCalendarMinutes(this._activeDate, -1); break; case ENTER: this._timeSelected(this._activeDate); return; default: // Don't prevent default or focus active cell on keys that we don't explicitly handle. return; } // Prevent unexpected default actions such as form submission. event.preventDefault(); } /** * Determine the date for the month that comes before the given month in the same column in the * calendar table. */ private _prevMonthInSameCol(date: Date): Date { // Determine how many months to jump forward given that there are 2 empty slots at the beginning // of each year. let increment = this._util.getMonth(date) <= 4 ? -5 : (this._util.getMonth(date) >= 7 ? -7 : -12); return this._util.addCalendarMonths(date, increment); } /** * Determine the date for the month that comes after the given month in the same column in the * calendar table. */ private _nextMonthInSameCol(date: Date): Date { // Determine how many months to jump forward given that there are 2 empty slots at the beginning // of each year. let increment = this._util.getMonth(date) <= 4 ? 7 : (this._util.getMonth(date) >= 7 ? 5 : 12); return this._util.addCalendarMonths(date, increment); } private calendarState(direction: string): void { this._calendarState = direction; } _calendarStateDone() { this._calendarState = ''; } }
the_stack
import { EndpointsInputConfig, EndpointsResolvedConfig, RegionInputConfig, RegionResolvedConfig, resolveEndpointsConfig, resolveRegionConfig, } from "@aws-sdk/config-resolver"; import { getContentLengthPlugin } from "@aws-sdk/middleware-content-length"; import { getHostHeaderPlugin, HostHeaderInputConfig, HostHeaderResolvedConfig, resolveHostHeaderConfig, } from "@aws-sdk/middleware-host-header"; import { getLoggerPlugin } from "@aws-sdk/middleware-logger"; import { getRetryPlugin, resolveRetryConfig, RetryInputConfig, RetryResolvedConfig } from "@aws-sdk/middleware-retry"; import { AwsAuthInputConfig, AwsAuthResolvedConfig, getAwsAuthPlugin, resolveAwsAuthConfig, } from "@aws-sdk/middleware-signing"; import { getUserAgentPlugin, resolveUserAgentConfig, UserAgentInputConfig, UserAgentResolvedConfig, } from "@aws-sdk/middleware-user-agent"; import { HttpHandler as __HttpHandler } from "@aws-sdk/protocol-http"; import { Client as __Client, SmithyConfiguration as __SmithyConfiguration, SmithyResolvedConfiguration as __SmithyResolvedConfiguration, } from "@aws-sdk/smithy-client"; import { Credentials as __Credentials, Decoder as __Decoder, Encoder as __Encoder, Hash as __Hash, HashConstructor as __HashConstructor, HttpHandlerOptions as __HttpHandlerOptions, Logger as __Logger, Provider as __Provider, Provider, RegionInfoProvider, StreamCollector as __StreamCollector, UrlParser as __UrlParser, UserAgent as __UserAgent, } from "@aws-sdk/types"; import { AbortEnvironmentUpdateCommandInput, AbortEnvironmentUpdateCommandOutput, } from "./commands/AbortEnvironmentUpdateCommand"; import { ApplyEnvironmentManagedActionCommandInput, ApplyEnvironmentManagedActionCommandOutput, } from "./commands/ApplyEnvironmentManagedActionCommand"; import { AssociateEnvironmentOperationsRoleCommandInput, AssociateEnvironmentOperationsRoleCommandOutput, } from "./commands/AssociateEnvironmentOperationsRoleCommand"; import { CheckDNSAvailabilityCommandInput, CheckDNSAvailabilityCommandOutput, } from "./commands/CheckDNSAvailabilityCommand"; import { ComposeEnvironmentsCommandInput, ComposeEnvironmentsCommandOutput, } from "./commands/ComposeEnvironmentsCommand"; import { CreateApplicationCommandInput, CreateApplicationCommandOutput } from "./commands/CreateApplicationCommand"; import { CreateApplicationVersionCommandInput, CreateApplicationVersionCommandOutput, } from "./commands/CreateApplicationVersionCommand"; import { CreateConfigurationTemplateCommandInput, CreateConfigurationTemplateCommandOutput, } from "./commands/CreateConfigurationTemplateCommand"; import { CreateEnvironmentCommandInput, CreateEnvironmentCommandOutput } from "./commands/CreateEnvironmentCommand"; import { CreatePlatformVersionCommandInput, CreatePlatformVersionCommandOutput, } from "./commands/CreatePlatformVersionCommand"; import { CreateStorageLocationCommandInput, CreateStorageLocationCommandOutput, } from "./commands/CreateStorageLocationCommand"; import { DeleteApplicationCommandInput, DeleteApplicationCommandOutput } from "./commands/DeleteApplicationCommand"; import { DeleteApplicationVersionCommandInput, DeleteApplicationVersionCommandOutput, } from "./commands/DeleteApplicationVersionCommand"; import { DeleteConfigurationTemplateCommandInput, DeleteConfigurationTemplateCommandOutput, } from "./commands/DeleteConfigurationTemplateCommand"; import { DeleteEnvironmentConfigurationCommandInput, DeleteEnvironmentConfigurationCommandOutput, } from "./commands/DeleteEnvironmentConfigurationCommand"; import { DeletePlatformVersionCommandInput, DeletePlatformVersionCommandOutput, } from "./commands/DeletePlatformVersionCommand"; import { DescribeAccountAttributesCommandInput, DescribeAccountAttributesCommandOutput, } from "./commands/DescribeAccountAttributesCommand"; import { DescribeApplicationsCommandInput, DescribeApplicationsCommandOutput, } from "./commands/DescribeApplicationsCommand"; import { DescribeApplicationVersionsCommandInput, DescribeApplicationVersionsCommandOutput, } from "./commands/DescribeApplicationVersionsCommand"; import { DescribeConfigurationOptionsCommandInput, DescribeConfigurationOptionsCommandOutput, } from "./commands/DescribeConfigurationOptionsCommand"; import { DescribeConfigurationSettingsCommandInput, DescribeConfigurationSettingsCommandOutput, } from "./commands/DescribeConfigurationSettingsCommand"; import { DescribeEnvironmentHealthCommandInput, DescribeEnvironmentHealthCommandOutput, } from "./commands/DescribeEnvironmentHealthCommand"; import { DescribeEnvironmentManagedActionHistoryCommandInput, DescribeEnvironmentManagedActionHistoryCommandOutput, } from "./commands/DescribeEnvironmentManagedActionHistoryCommand"; import { DescribeEnvironmentManagedActionsCommandInput, DescribeEnvironmentManagedActionsCommandOutput, } from "./commands/DescribeEnvironmentManagedActionsCommand"; import { DescribeEnvironmentResourcesCommandInput, DescribeEnvironmentResourcesCommandOutput, } from "./commands/DescribeEnvironmentResourcesCommand"; import { DescribeEnvironmentsCommandInput, DescribeEnvironmentsCommandOutput, } from "./commands/DescribeEnvironmentsCommand"; import { DescribeEventsCommandInput, DescribeEventsCommandOutput } from "./commands/DescribeEventsCommand"; import { DescribeInstancesHealthCommandInput, DescribeInstancesHealthCommandOutput, } from "./commands/DescribeInstancesHealthCommand"; import { DescribePlatformVersionCommandInput, DescribePlatformVersionCommandOutput, } from "./commands/DescribePlatformVersionCommand"; import { DisassociateEnvironmentOperationsRoleCommandInput, DisassociateEnvironmentOperationsRoleCommandOutput, } from "./commands/DisassociateEnvironmentOperationsRoleCommand"; import { ListAvailableSolutionStacksCommandInput, ListAvailableSolutionStacksCommandOutput, } from "./commands/ListAvailableSolutionStacksCommand"; import { ListPlatformBranchesCommandInput, ListPlatformBranchesCommandOutput, } from "./commands/ListPlatformBranchesCommand"; import { ListPlatformVersionsCommandInput, ListPlatformVersionsCommandOutput, } from "./commands/ListPlatformVersionsCommand"; import { ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { RebuildEnvironmentCommandInput, RebuildEnvironmentCommandOutput } from "./commands/RebuildEnvironmentCommand"; import { RequestEnvironmentInfoCommandInput, RequestEnvironmentInfoCommandOutput, } from "./commands/RequestEnvironmentInfoCommand"; import { RestartAppServerCommandInput, RestartAppServerCommandOutput } from "./commands/RestartAppServerCommand"; import { RetrieveEnvironmentInfoCommandInput, RetrieveEnvironmentInfoCommandOutput, } from "./commands/RetrieveEnvironmentInfoCommand"; import { SwapEnvironmentCNAMEsCommandInput, SwapEnvironmentCNAMEsCommandOutput, } from "./commands/SwapEnvironmentCNAMEsCommand"; import { TerminateEnvironmentCommandInput, TerminateEnvironmentCommandOutput, } from "./commands/TerminateEnvironmentCommand"; import { UpdateApplicationCommandInput, UpdateApplicationCommandOutput } from "./commands/UpdateApplicationCommand"; import { UpdateApplicationResourceLifecycleCommandInput, UpdateApplicationResourceLifecycleCommandOutput, } from "./commands/UpdateApplicationResourceLifecycleCommand"; import { UpdateApplicationVersionCommandInput, UpdateApplicationVersionCommandOutput, } from "./commands/UpdateApplicationVersionCommand"; import { UpdateConfigurationTemplateCommandInput, UpdateConfigurationTemplateCommandOutput, } from "./commands/UpdateConfigurationTemplateCommand"; import { UpdateEnvironmentCommandInput, UpdateEnvironmentCommandOutput } from "./commands/UpdateEnvironmentCommand"; import { UpdateTagsForResourceCommandInput, UpdateTagsForResourceCommandOutput, } from "./commands/UpdateTagsForResourceCommand"; import { ValidateConfigurationSettingsCommandInput, ValidateConfigurationSettingsCommandOutput, } from "./commands/ValidateConfigurationSettingsCommand"; import { getRuntimeConfig as __getRuntimeConfig } from "./runtimeConfig"; export type ServiceInputTypes = | AbortEnvironmentUpdateCommandInput | ApplyEnvironmentManagedActionCommandInput | AssociateEnvironmentOperationsRoleCommandInput | CheckDNSAvailabilityCommandInput | ComposeEnvironmentsCommandInput | CreateApplicationCommandInput | CreateApplicationVersionCommandInput | CreateConfigurationTemplateCommandInput | CreateEnvironmentCommandInput | CreatePlatformVersionCommandInput | CreateStorageLocationCommandInput | DeleteApplicationCommandInput | DeleteApplicationVersionCommandInput | DeleteConfigurationTemplateCommandInput | DeleteEnvironmentConfigurationCommandInput | DeletePlatformVersionCommandInput | DescribeAccountAttributesCommandInput | DescribeApplicationVersionsCommandInput | DescribeApplicationsCommandInput | DescribeConfigurationOptionsCommandInput | DescribeConfigurationSettingsCommandInput | DescribeEnvironmentHealthCommandInput | DescribeEnvironmentManagedActionHistoryCommandInput | DescribeEnvironmentManagedActionsCommandInput | DescribeEnvironmentResourcesCommandInput | DescribeEnvironmentsCommandInput | DescribeEventsCommandInput | DescribeInstancesHealthCommandInput | DescribePlatformVersionCommandInput | DisassociateEnvironmentOperationsRoleCommandInput | ListAvailableSolutionStacksCommandInput | ListPlatformBranchesCommandInput | ListPlatformVersionsCommandInput | ListTagsForResourceCommandInput | RebuildEnvironmentCommandInput | RequestEnvironmentInfoCommandInput | RestartAppServerCommandInput | RetrieveEnvironmentInfoCommandInput | SwapEnvironmentCNAMEsCommandInput | TerminateEnvironmentCommandInput | UpdateApplicationCommandInput | UpdateApplicationResourceLifecycleCommandInput | UpdateApplicationVersionCommandInput | UpdateConfigurationTemplateCommandInput | UpdateEnvironmentCommandInput | UpdateTagsForResourceCommandInput | ValidateConfigurationSettingsCommandInput; export type ServiceOutputTypes = | AbortEnvironmentUpdateCommandOutput | ApplyEnvironmentManagedActionCommandOutput | AssociateEnvironmentOperationsRoleCommandOutput | CheckDNSAvailabilityCommandOutput | ComposeEnvironmentsCommandOutput | CreateApplicationCommandOutput | CreateApplicationVersionCommandOutput | CreateConfigurationTemplateCommandOutput | CreateEnvironmentCommandOutput | CreatePlatformVersionCommandOutput | CreateStorageLocationCommandOutput | DeleteApplicationCommandOutput | DeleteApplicationVersionCommandOutput | DeleteConfigurationTemplateCommandOutput | DeleteEnvironmentConfigurationCommandOutput | DeletePlatformVersionCommandOutput | DescribeAccountAttributesCommandOutput | DescribeApplicationVersionsCommandOutput | DescribeApplicationsCommandOutput | DescribeConfigurationOptionsCommandOutput | DescribeConfigurationSettingsCommandOutput | DescribeEnvironmentHealthCommandOutput | DescribeEnvironmentManagedActionHistoryCommandOutput | DescribeEnvironmentManagedActionsCommandOutput | DescribeEnvironmentResourcesCommandOutput | DescribeEnvironmentsCommandOutput | DescribeEventsCommandOutput | DescribeInstancesHealthCommandOutput | DescribePlatformVersionCommandOutput | DisassociateEnvironmentOperationsRoleCommandOutput | ListAvailableSolutionStacksCommandOutput | ListPlatformBranchesCommandOutput | ListPlatformVersionsCommandOutput | ListTagsForResourceCommandOutput | RebuildEnvironmentCommandOutput | RequestEnvironmentInfoCommandOutput | RestartAppServerCommandOutput | RetrieveEnvironmentInfoCommandOutput | SwapEnvironmentCNAMEsCommandOutput | TerminateEnvironmentCommandOutput | UpdateApplicationCommandOutput | UpdateApplicationResourceLifecycleCommandOutput | UpdateApplicationVersionCommandOutput | UpdateConfigurationTemplateCommandOutput | UpdateEnvironmentCommandOutput | UpdateTagsForResourceCommandOutput | ValidateConfigurationSettingsCommandOutput; export interface ClientDefaults extends Partial<__SmithyResolvedConfiguration<__HttpHandlerOptions>> { /** * The HTTP handler to use. Fetch in browser and Https in Nodejs. */ requestHandler?: __HttpHandler; /** * A constructor for a class implementing the {@link __Hash} interface * that computes the SHA-256 HMAC or checksum of a string or binary buffer. * @internal */ sha256?: __HashConstructor; /** * The function that will be used to convert strings into HTTP endpoints. * @internal */ urlParser?: __UrlParser; /** * A function that can calculate the length of a request body. * @internal */ bodyLengthChecker?: (body: any) => number | undefined; /** * A function that converts a stream into an array of bytes. * @internal */ streamCollector?: __StreamCollector; /** * The function that will be used to convert a base64-encoded string to a byte array. * @internal */ base64Decoder?: __Decoder; /** * The function that will be used to convert binary data to a base64-encoded string. * @internal */ base64Encoder?: __Encoder; /** * The function that will be used to convert a UTF8-encoded string to a byte array. * @internal */ utf8Decoder?: __Decoder; /** * The function that will be used to convert binary data to a UTF-8 encoded string. * @internal */ utf8Encoder?: __Encoder; /** * The runtime environment. * @internal */ runtime?: string; /** * Disable dyanamically changing the endpoint of the client based on the hostPrefix * trait of an operation. */ disableHostPrefix?: boolean; /** * Value for how many times a request will be made at most in case of retry. */ maxAttempts?: number | __Provider<number>; /** * Specifies which retry algorithm to use. */ retryMode?: string | __Provider<string>; /** * Optional logger for logging debug/info/warn/error. */ logger?: __Logger; /** * Unique service identifier. * @internal */ serviceId?: string; /** * The AWS region to which this client will send requests */ region?: string | __Provider<string>; /** * Default credentials provider; Not available in browser runtime. * @internal */ credentialDefaultProvider?: (input: any) => __Provider<__Credentials>; /** * Fetch related hostname, signing name or signing region with given region. * @internal */ regionInfoProvider?: RegionInfoProvider; /** * The provider populating default tracking information to be sent with `user-agent`, `x-amz-user-agent` header * @internal */ defaultUserAgentProvider?: Provider<__UserAgent>; } type ElasticBeanstalkClientConfigType = Partial<__SmithyConfiguration<__HttpHandlerOptions>> & ClientDefaults & RegionInputConfig & EndpointsInputConfig & RetryInputConfig & HostHeaderInputConfig & AwsAuthInputConfig & UserAgentInputConfig; /** * The configuration interface of ElasticBeanstalkClient class constructor that set the region, credentials and other options. */ export interface ElasticBeanstalkClientConfig extends ElasticBeanstalkClientConfigType {} type ElasticBeanstalkClientResolvedConfigType = __SmithyResolvedConfiguration<__HttpHandlerOptions> & Required<ClientDefaults> & RegionResolvedConfig & EndpointsResolvedConfig & RetryResolvedConfig & HostHeaderResolvedConfig & AwsAuthResolvedConfig & UserAgentResolvedConfig; /** * The resolved configuration interface of ElasticBeanstalkClient class. This is resolved and normalized from the {@link ElasticBeanstalkClientConfig | constructor configuration interface}. */ export interface ElasticBeanstalkClientResolvedConfig extends ElasticBeanstalkClientResolvedConfigType {} /** * <fullname>AWS Elastic Beanstalk</fullname> * * * <p>AWS Elastic Beanstalk makes it easy for you to create, deploy, and manage scalable, * fault-tolerant applications running on the Amazon Web Services cloud.</p> * <p>For more information about this product, go to the <a href="http://aws.amazon.com/elasticbeanstalk/">AWS Elastic Beanstalk</a> details page. The location of the * latest AWS Elastic Beanstalk WSDL is <a href="https://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl">https://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl</a>. * To install the Software Development Kits (SDKs), Integrated Development Environment (IDE) * Toolkits, and command line tools that enable you to access the API, go to <a href="http://aws.amazon.com/tools/">Tools for Amazon Web Services</a>.</p> * <p> * <b>Endpoints</b> * </p> * <p>For a list of region-specific endpoints that AWS Elastic Beanstalk supports, go to * <a href="https://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region">Regions and Endpoints</a> in the <i>Amazon Web Services * Glossary</i>.</p> */ export class ElasticBeanstalkClient extends __Client< __HttpHandlerOptions, ServiceInputTypes, ServiceOutputTypes, ElasticBeanstalkClientResolvedConfig > { /** * The resolved configuration of ElasticBeanstalkClient class. This is resolved and normalized from the {@link ElasticBeanstalkClientConfig | constructor configuration interface}. */ readonly config: ElasticBeanstalkClientResolvedConfig; constructor(configuration: ElasticBeanstalkClientConfig) { const _config_0 = __getRuntimeConfig(configuration); const _config_1 = resolveRegionConfig(_config_0); const _config_2 = resolveEndpointsConfig(_config_1); const _config_3 = resolveRetryConfig(_config_2); const _config_4 = resolveHostHeaderConfig(_config_3); const _config_5 = resolveAwsAuthConfig(_config_4); const _config_6 = resolveUserAgentConfig(_config_5); super(_config_6); this.config = _config_6; this.middlewareStack.use(getRetryPlugin(this.config)); this.middlewareStack.use(getContentLengthPlugin(this.config)); this.middlewareStack.use(getHostHeaderPlugin(this.config)); this.middlewareStack.use(getLoggerPlugin(this.config)); this.middlewareStack.use(getAwsAuthPlugin(this.config)); this.middlewareStack.use(getUserAgentPlugin(this.config)); } /** * Destroy underlying resources, like sockets. It's usually not necessary to do this. * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. * Otherwise, sockets might stay open for quite a long time before the server terminates them. */ destroy(): void { super.destroy(); } }
the_stack
/// <reference types="activex-interop" /> /// <reference types="activex-adodb" /> declare namespace ADOX { const enum ActionEnum { adAccessDeny = 3, adAccessGrant = 1, adAccessRevoke = 4, adAccessSet = 2, } const enum AllowNullsEnum { adIndexNullsAllow = 0, adIndexNullsDisallow = 1, adIndexNullsIgnore = 2, adIndexNullsIgnoreAny = 4, } const enum ColumnAttributesEnum { adColFixed = 1, adColNullable = 2, } const enum InheritTypeEnum { adInheritBoth = 3, adInheritContainers = 2, adInheritNone = 0, adInheritNoPropogate = 4, adInheritObjects = 1, } const enum KeyTypeEnum { adKeyForeign = 2, adKeyPrimary = 1, adKeyUnique = 3, } const enum ObjectTypeEnum { adPermObjColumn = 2, adPermObjDatabase = 3, adPermObjProcedure = 4, adPermObjProviderSpecific = -1, adPermObjTable = 1, adPermObjView = 5, } const enum RightsEnum { adRightCreate = 16384, adRightDelete = 65536, adRightDrop = 256, adRightExclusive = 512, adRightExecute = 536870912, adRightFull = 268435456, adRightInsert = 32768, adRightMaximumAllowed = 33554432, adRightNone = 0, adRightRead = -2147483648, adRightReadDesign = 1024, adRightReadPermissions = 131072, adRightReference = 8192, adRightUpdate = 1073741824, adRightWithGrant = 4096, adRightWriteDesign = 2048, adRightWriteOwner = 524288, adRightWritePermissions = 262144, } const enum RuleEnum { adRICascade = 1, adRINone = 0, adRISetDefault = 3, adRISetNull = 2, } const enum SortOrderEnum { adSortAscending = 1, adSortDescending = 2, } class Catalog { private constructor(); private 'ADOX.Catalog_typekey': Catalog; /** Can be set to a Connection object or a string. Returns the active Connection object, or `null` */ ActiveConnection: string | ADODB.Connection | null; /** * The **Create** method creates and opens a new ADO Connection to the data source specified in _ConnectString_. If successful, the new **Connection** object is assigned to the **ActiveConnection** property. * * An error will occur if the provider does not support creating new catalogs. * * @param ConnectString Connection string */ Create(ConnectString: string): void; /** * @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification */ GetObjectOwner(ObjectName: string, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, ObjectTypeId: any): string; GetObjectOwner(ObjectName: string, ObjectType: ObjectTypeEnum): string; readonly Groups: Groups; readonly Procedures: Procedures; /** * @param UserName Specifies the name of the **User** or **Group** to own the object * @param ObjectTypeId Specifies the GUID for a provider object type that is not defined by the OLE DB specification */ SetObjectOwner(ObjectName: string, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, UserName: string, ObjectTypeId: any): void; SetObjectOwner(ObjectName: string, ObjectType: ObjectTypeEnum, UserName: string): void; readonly Tables: Tables; readonly Users: Users; readonly Views: Views; } class Column { private constructor(); private 'ADOX.Column_typekey': Column; Attributes: ColumnAttributesEnum; DefinedSize: number; Name: string; NumericScale: number; ParentCatalog: Catalog; Precision: number; readonly Properties: ADODB.Properties; RelatedColumn: string; SortOrder: SortOrderEnum; Type: ADODB.DataTypeEnum; } interface Columns { /** * @param Type [Type=202] * @param DefinedSize [DefinedSize=0] */ Append(Item: Column | string, Type?: ADODB.DataTypeEnum, DefinedSize?: number): void; readonly Count: number; Delete(Item: string | number): void; Item(Item: string | number): Column; Refresh(): void; (Item: string | number): Column; } class Group { private constructor(); private 'ADOX.Group_typekey': Group; /** * @param Name Specifies the name of the object for which to set permissions. Pass `null` if you want to get the permissions for the object container. * @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification. */ GetPermissions(Name: string | null, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, ObjectTypeId: any): RightsEnum; GetPermissions(Name: string | null, ObjectType: ObjectTypeEnum): RightsEnum; Name: string; ParentCatalog: Catalog; readonly Properties: ADODB.Properties; /** * @param Rights A bitmask of one or more of the **RightsEnum** constants, that indicates the rights to set. * @param Inherit [Inherit=0] * @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification. */ SetPermissions(Name: string, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, Action: ActionEnum, Rights: RightsEnum, Inherit: InheritTypeEnum, ObjectTypeId: any): void; SetPermissions(Name: string, ObjectType: ObjectTypeEnum, Action: ActionEnum, Rights: RightsEnum, Inherit?: InheritTypeEnum): void; readonly Users: Users; } interface Groups { Append(Item: Group | string): void; readonly Count: number; Delete(Item: string | number): void; Item(Item: string | number): Group; Refresh(): void; (Item: string | number): Group; } class Index { private constructor(); private 'ADOX.Index_typekey': Index; Clustered: boolean; readonly Columns: Columns; IndexNulls: AllowNullsEnum; Name: string; PrimaryKey: boolean; readonly Properties: ADODB.Properties; Unique: boolean; } // tslint:disable-next-line:interface-name interface Indexes { Append(Item: Index | string, Columns?: string | SafeArray<string>): void; // is this actually two overloads, one with [Index] and one with [string,string | SafeArray<string>]? readonly Count: number; Delete(Item: string | number): void; Item(Item: string | number): Index; Refresh(): void; (Item: string | number): Index; } class Key { private constructor(); private 'ADOX.Key_typekey': Key; readonly Columns: Columns; DeleteRule: RuleEnum; Name: string; RelatedTable: string; Type: KeyTypeEnum; UpdateRule: RuleEnum; } interface Keys { /** * @param Type [Type=1] * @param RelatedTable [RelatedTable=''] * @param RelatedColumn [RelatedColumn=''] */ Append(Item: Key | string, Type?: KeyTypeEnum, Column?: string | SafeArray<string>, RelatedTable?: string, RelatedColumn?: string): void; readonly Count: number; Delete(Item: string | number): void; Item(Item: string | number): Key; Refresh(): void; (Item: string | number): Key; } class Procedure { private constructor(); private 'ADOX.Procedure_typekey': Procedure; Command: ADODB.Command; readonly DateCreated: VarDate | null; readonly DateModified: VarDate | null; readonly Name: string; } interface Procedures { Append(Name: string, Command: ADODB.Command): void; readonly Count: number; Delete(Item: string | number): void; Item(Item: string | number): Procedure; Refresh(): void; (Item: string | number): Procedure; } class Table { private constructor(); private 'ADOX.Table_typekey': Table; readonly Columns: Columns; readonly DateCreated: VarDate; readonly DateModified: VarDate; readonly Indexes: Indexes; readonly Keys: Keys; Name: string; ParentCatalog: Catalog; readonly Properties: ADODB.Properties; readonly Type: string; } interface Tables { Append(Item: Table | string): void; readonly Count: number; Delete(Item: string | number): void; Item(Item: string | number): Table; Refresh(): void; (Item: string | number): Table; } class User { private constructor(); private 'ADOX.User_typekey': User; ChangePassword(OldPassword: string, NewPassword: string): void; /** * @param Name Specifies the name of the object for which to set permissions. Pass `null` if you want to get the permissions for the object container. * @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification. */ GetPermissions(Name: string | null, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, ObjectTypeId: any): RightsEnum; GetPermissions(Name: string | null, ObjectType: ObjectTypeEnum): RightsEnum; readonly Groups: Groups; Name: string; ParentCatalog: Catalog; readonly Properties: ADODB.Properties; /** * @param Rights A bitmask of one or more of the **RightsEnum** constants, that indicates the rights to set. * @param Inherit [Inherit=0] * @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification. */ SetPermissions(Name: string, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, Action: ActionEnum, Rights: RightsEnum, Inherit: InheritTypeEnum, ObjectTypeId: any): void; SetPermissions(Name: string, ObjectType: ObjectTypeEnum, Action: ActionEnum, Rights: RightsEnum, Inherit?: InheritTypeEnum): void; } interface Users { /** @param Password [Password=''] */ Append(Item: User | string, Password?: string): void; readonly Count: number; Delete(Item: string | number): void; Item(Item: string | number): User; Refresh(): void; (Item: string | number): User; } class View { private constructor(); private 'ADOX.View_typekey': View; Command: ADODB.Command; readonly DateCreated: VarDate; readonly DateModified: VarDate; readonly Name: string; } interface Views { Append(Name: string, Command: ADODB.Command): void; readonly Count: number; Delete(Item: string | number): void; Item(Item: string | number): View; Refresh(): void; (Item: string | number): View; } } interface ActiveXObjectNameMap { 'ADOX.Catalog': ADOX.Catalog; 'ADOX.Column': ADOX.Column; 'ADOX.Group': ADOX.Group; 'ADOX.Index': ADOX.Index; 'ADOX.Key': ADOX.Key; 'ADOX.Table': ADOX.Table; 'ADOX.User': ADOX.User; }
the_stack
const fakeDB = require('fake-indexeddb'); const fakeDBIndex = require('fake-indexeddb/lib/FDBIndex'); const fakeDBKeyRange = require('fake-indexeddb/lib/FDBKeyRange'); const fakeDBDataBase = require('fake-indexeddb/lib/FDBDatabase'); const fakeObjectStore = require('fake-indexeddb/lib/FDBObjectStore'); const fakeDBTransaction = require('fake-indexeddb/lib/FDBTransaction'); const fakeIDBCursor = require('fake-indexeddb/lib/FDBCursor'); const fakeIDBRequest = require('fake-indexeddb/lib/FDBRequest'); import { dateFormat2Day, ONE_DAY_TIME_SPAN, M_BYTE, sizeOf } from '../src/lib/utils'; import LogManager from '../src/log-manager'; import LoganInstance from '../src/index'; import { ResultMsg, LogSuccHandler } from '../src/interface'; const NodeIndex = require('../src/node-index'); const DBName = 'testLogan'; const ReportUrl = 'testUrl'; const PublicK = '-----BEGIN PUBLIC KEY-----\n' + 'MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgG2m5VVtZ4mHml3FB9foDRpDW7Pw\n' + 'Foa+1eYN777rNmIdnmezQqHWIRVcnTRVjrgGt2ndP2cYT7MgmWpvr8IjgN0PZ6ng\n' + 'MmKYGpapMqkxsnS/6Q8UZO4PQNlnsK2hSPoIDeJcHxDvo6Nelg+mRHEpD6K+1FIq\n' + 'zvdwVPCcgK7UbZElAgMBAAE=\n' + '-----END PUBLIC KEY-----'; function setDBInWindow (): void { // @ts-ignore window.indexedDB = fakeDB; // @ts-ignore window.IDBIndex = fakeDBIndex; // @ts-ignore window.IDBKeyRange = fakeDBKeyRange; // @ts-ignore window.IDBDatabase = fakeDBDataBase; // @ts-ignore window.IDBObjectStore = fakeObjectStore; // @ts-ignore window.IDBTransaction = fakeDBTransaction; // @ts-ignore window.IDBCursor = fakeIDBCursor; // @ts-ignore window.IDBRequest = fakeIDBRequest; } // Ready for faked IndexedDB environment, before IDBM is imported. setDBInWindow(); import IDBM from 'idb-managed'; import { ReportResult } from '../build/interface'; const errorH = (): void => { /* Noop */ }; const succH = (): void => { /* Noop */ }; function clearDBFromWindow (): void { // @ts-ignore window.indexedDB = null; } function mockXHR (status: number, responseText: string, statusText: string): void { (window as any).XMLHttpRequest = class { status = 200; responseText = ''; statusText = ''; readyState = 4; open (): void { /* Noop */ } onreadystatechange (): void { /* Noop */ } setRequestHeader (): void { /* Noop */ } send (): void { setTimeout(() => { this.readyState = 4; this.status = status; this.responseText = responseText; this.statusText = statusText; this.onreadystatechange(); }, 1000); } }; } describe('Logan API Tests', () => { afterEach(async () => { await IDBM.deleteDB(DBName); LogManager.resetQuota(); }); test('log', async (done) => { LoganInstance.initConfig({ reportUrl: ReportUrl, publicKey: PublicK, dbName: DBName, errorHandler: errorH, succHandler: succH }); LoganInstance.log('aaa', 1); setTimeout(() => { expect(succH).toBeCalled; expect(errorH).not.toBeCalled; done(); }, 1000); }); test('logWithEncryption', async (done) => { LoganInstance.initConfig({ reportUrl: ReportUrl, publicKey: PublicK, dbName: DBName, errorHandler: errorH, succHandler: succH }); LoganInstance.logWithEncryption('aaa', 1); setTimeout(() => { expect(succH).toBeCalled; expect(errorH).not.toBeCalled; done(); }, 1000); }); test('customLog', async (done) => { const customLogContent = JSON.stringify({ content: 'aaa', type: 100 }); let expectLogContent: string, expectEncryptVersion: number; const succHandler: LogSuccHandler = (logConfig): void => { expectLogContent = logConfig.logContent; expectEncryptVersion = logConfig.encryptVersion; }; LoganInstance.initConfig({ reportUrl: ReportUrl, publicKey: PublicK, dbName: DBName, errorHandler: errorH, succHandler: succHandler }); LoganInstance.customLog({ logContent: customLogContent, encryptVersion: 1 }); setTimeout(async () => { expect(errorH).not.toBeCalled; expect(expectLogContent).toBe(customLogContent); expect(expectEncryptVersion).toBe(1); const logDetails = await IDBM.getItemsInRangeFromDB(DBName, { tableName: 'logan_detail_table' }); expect(logDetails.length).toBe(1); done(); }, 1000); }); test('log with large size', async (done) => { LoganInstance.initConfig({ reportUrl: ReportUrl, publicKey: PublicK, dbName: DBName }); const logNum = 40; for (let i = 0; i < logNum; i++) { let plaintext = ''; // 200,000B for (let j = 0; j < 25000; j++) { plaintext += Math.random() .toString(36) .substr(2, 8); } const logString = 'log' + i + ':' + plaintext; LoganInstance.log(logString, 1); } setTimeout(async () => { expect.assertions(2); const dayResult = await IDBM.getItemsInRangeFromDB(DBName, { tableName: 'log_day_table' }); expect(dayResult[0].reportPagesInfo.pageSizes.length).toBe(9); expect(dayResult[0].totalSize).toBeLessThanOrEqual(7 * M_BYTE); done(); }, 2000); }); test('log with special char', async (done) => { LoganInstance.initConfig({ reportUrl: ReportUrl, publicKey: PublicK, dbName: DBName }); const specialString = String.fromCharCode(200) + String.fromCharCode(3000); expect(sizeOf(specialString)).toBe(5); LoganInstance.log(specialString, 1); LoganInstance.logWithEncryption(specialString, 1); setTimeout(async () => { const logItems = await IDBM.getItemsInRangeFromDB(DBName, { tableName: 'logan_detail_table' }); expect(logItems.length).toBe(2); done(); }, 1000); }); test('report', async (done) => { LoganInstance.initConfig({ reportUrl: ReportUrl, publicKey: PublicK, dbName: DBName }); expect.assertions(2); const today = dateFormat2Day(new Date()); const yesterday = dateFormat2Day( new Date(+new Date() - ONE_DAY_TIME_SPAN) ); mockXHR(200, JSON.stringify({ code: 200 }), ''); LoganInstance.log('aaa', 1); setTimeout(async () => { const reportResult = await LoganInstance.report({ deviceId: 'aaa', fromDayString: yesterday, toDayString: today }); expect(reportResult[today].msg).toBe( LoganInstance.ResultMsg.REPORT_LOG_SUCC ); expect(reportResult[yesterday].msg).toBe( LoganInstance.ResultMsg.NO_LOG ); done(); }, 1000); }); test('customReport', async (done) => { LoganInstance.initConfig({ publicKey: PublicK, dbName: DBName }); const today = dateFormat2Day(new Date()); mockXHR(200, JSON.stringify({ code: 200 }), ''); LoganInstance.log('aaa', 1); setTimeout(async () => { const reportResult = await LoganInstance.report({ fromDayString: today, toDayString: today, xhrOptsFormatter: () => { return { reportUrl: ReportUrl }; } }); expect.assertions(1); expect(reportResult[today].msg).toBe( LoganInstance.ResultMsg.REPORT_LOG_SUCC ); done(); }, 1000); }); }); describe('Logan Param Invalid Tests', () => { test('logType is not set', async () => { expect.assertions(1); LoganInstance.initConfig({ reportUrl: ReportUrl, dbName: DBName, errorHandler: (e: Error) => { expect(e.message).toBe('logType needs to be set'); } }); // @ts-ignore LoganInstance.log('aaa'); }); test('publicKey is not set', async () => { LoganInstance.initConfig({ reportUrl: ReportUrl, dbName: DBName, errorHandler: (e: Error) => { expect(e.message).toBe('publicKey needs to be set before logWithEncryption'); expect.assertions(1); } }); LoganInstance.logWithEncryption('aaa', 1); }); test('reportConfig is not valid', async () => { expect.assertions(3); const fromDay = dateFormat2Day( new Date(+new Date() - ONE_DAY_TIME_SPAN * 2) ); const toDay = dateFormat2Day(new Date()); // @ts-ignore LoganInstance.report({}).catch(e => { expect(e.message).toBe('fromDayString is not valid, needs to be YYYY-MM-DD format'); }); // @ts-ignore LoganInstance.report({ deviceId: 'aaa', fromDayString: toDay, toDayString: fromDay }).catch(e => { expect(e.message).toBe( 'fromDayString needs to be no bigger than toDayString' ); }); // @ts-ignore LoganInstance.report({ deviceId: 'aaa', fromDayString: fromDay, toDayString: `${+new Date()}` }).catch(e => { expect(e.message).toContain('toDayString is not valid'); }); }); }); describe('Logan Exception Tests', () => { beforeEach(() => { LoganInstance.initConfig({ reportUrl: ReportUrl, publicKey: PublicK, dbName: DBName }); }); afterEach(async () => { await IDBM.deleteDB(DBName); LogManager.resetQuota(); }); test('report fail if xhr status is not 200', async (done) => { const today = dateFormat2Day(new Date()); mockXHR(100, '', ''); LoganInstance.log('aaa', 1); setTimeout(async () => { const reportResult = await LoganInstance.report({ deviceId: 'aaa', fromDayString: today, toDayString: today }); expect.assertions(2); expect(reportResult[today].msg).toBe( LoganInstance.ResultMsg.REPORT_LOG_FAIL ); expect(reportResult[today].desc).toBe( 'Request failed, status: 100, responseText: ' ); done(); }, 1000); }); test('report fail if server code is not 200', async (done) => { const today = dateFormat2Day(new Date()); mockXHR(200, JSON.stringify({ code: 400 }), ''); LoganInstance.log('aaa', 1); setTimeout(async () => { const reportResult = await LoganInstance.report({ deviceId: 'aaa', fromDayString: today, toDayString: today }); expect.assertions(1); expect(reportResult[today].msg).toBe( LoganInstance.ResultMsg.REPORT_LOG_FAIL ); done(); }, 1000); }); test('report with custom response', async (done) => { const today = dateFormat2Day(new Date()); LoganInstance.log('aaa', 1); const report = async (): Promise<ReportResult> => { return await LoganInstance.report({ deviceId: 'aaa', fromDayString: today, toDayString: today, xhrOptsFormatter: () => { return { responseDealer: (xhrResponseText: any): any => { const responseOb = JSON.parse(xhrResponseText); if (responseOb.code === 10000) { return { resultMsg: ResultMsg.REPORT_LOG_SUCC }; } else { return { resultMsg: ResultMsg.REPORT_LOG_FAIL, desc: `responseOb.code:${responseOb.code}` }; } } }; } }); }; setTimeout(async () => { mockXHR(200, JSON.stringify({ code: 10000 }), ''); const reportResult1 = await report(); expect(reportResult1[today].msg).toBe( LoganInstance.ResultMsg.REPORT_LOG_SUCC ); mockXHR(200, JSON.stringify({ code: 10001 }), ''); const reportResult2 = await report(); expect(reportResult2[today].msg).toBe( LoganInstance.ResultMsg.REPORT_LOG_FAIL ); expect.assertions(2); done(); }, 1000); }); test('When IndexedDB is not supported', async (done) => { clearDBFromWindow(); LoganInstance.initConfig({ reportUrl: ReportUrl, publicKey: PublicK, dbName: DBName, errorHandler: (e: Error) => { expect(e.message).toBe(ResultMsg.DB_NOT_SUPPORT); } }); LoganInstance.log('aaa', 1); setTimeout(() => { expect.assertions(1); setDBInWindow(); done(); }, 1000); }); test('When exceeds log limit', async (done) => { const LOG_TRY_TIMES = 4; const errorArr: Error[] = []; clearDBFromWindow(); LoganInstance.initConfig({ logTryTimes: LOG_TRY_TIMES, reportUrl: ReportUrl, publicKey: PublicK, dbName: DBName, errorHandler: (e: Error) => { errorArr.push(e); } }); for (let i = 0; i < LOG_TRY_TIMES + 1; i++) { LoganInstance.log('aaa', 1); } setTimeout(async () => { setDBInWindow(); const logItems = await IDBM.getItemsInRangeFromDB(DBName, { tableName: 'logan_detail_table' }); expect.assertions(4); expect(logItems.length).toBe(0); expect(errorArr[0].message).toBe(ResultMsg.DB_NOT_SUPPORT); // 测试save-log内部对tryTime的限制判断 expect(errorArr[LOG_TRY_TIMES].message).toBe( ResultMsg.EXCEED_TRY_TIMES ); LoganInstance.log('bbb', 1); // 测试index中logAsync对tryTime的限制判断 expect(errorArr[LOG_TRY_TIMES + 1].message).toBe( ResultMsg.EXCEED_TRY_TIMES ); done(); }, 2000); }); }); describe('Test node-index', () => { test('node-index contains all property of logan-web', () => { for (const property in LoganInstance) { expect(NodeIndex[property]).toBeDefined(); if (typeof (LoganInstance as any)[property] === 'function') { expect(() => { NodeIndex[property](); }).not.toThrow(); } } }); });
the_stack
import { AccessToken, DbResult, GuidString, OpenMode } from "@itwin/core-bentley"; import { IModelError, IModelVersion } from "@itwin/core-common"; import { TestUsers, TestUtility } from "@itwin/oidc-signin-tool"; import { assert } from "chai"; import { BriefcaseManager, ChangedElementsDb, IModelHost, IModelJsFs, ProcessChangesetOptions, SnapshotDb } from "@itwin/core-backend"; import { ChangedElementsManager } from "@itwin/core-backend/lib/cjs/ChangedElementsManager"; import { HubWrappers } from "@itwin/core-backend/lib/cjs/test/IModelTestUtils"; import { HubUtility } from "../HubUtility"; describe("ChangedElements", () => { let accessToken: AccessToken; let testITwinId: GuidString; let testIModelId: GuidString; before(async () => { accessToken = await TestUtility.getAccessToken(TestUsers.regular); testITwinId = await HubUtility.getTestITwinId(accessToken); testIModelId = await HubUtility.getTestIModelId(accessToken, HubUtility.testIModelNames.readOnly); }); it("Create ChangedElements Cache and process changesets", async () => { const cacheFilePath = BriefcaseManager.getChangeCachePathName(testIModelId); if (IModelJsFs.existsSync(cacheFilePath)) IModelJsFs.removeSync(cacheFilePath); const iModel = await HubWrappers.downloadAndOpenCheckpoint({ accessToken, iTwinId: testITwinId, iModelId: testIModelId, asOf: IModelVersion.first().toJSON() }); const changesets = await IModelHost.hubAccess.queryChangesets({ accessToken, iModelId: testIModelId }); assert.exists(iModel); const filePath = ChangedElementsManager.getChangedElementsPathName(iModel.iModelId); if (IModelJsFs.existsSync(filePath)) IModelJsFs.removeSync(filePath); let cache = ChangedElementsDb.createDb(iModel, filePath); assert.isDefined(cache); const startChangesetId = changesets[0].id; const endChangesetId = changesets[changesets.length - 1].id; // Check that the changesets have not been processed yet assert.isFalse(cache.isProcessed(startChangesetId)); assert.isFalse(cache.isProcessed(endChangesetId)); // Try getting changed elements, should fail because we haven't processed the changesets assert.throws(() => cache.getChangedElements(startChangesetId, endChangesetId), IModelError); // Process changesets with "Items" presentation rules const options: ProcessChangesetOptions = { rulesetId: "Items", startChangesetId, endChangesetId, wantParents: true, wantPropertyChecksums: true, }; const result = await cache.processChangesets(accessToken, iModel, options); assert.equal(result, DbResult.BE_SQLITE_OK); // Check that the changesets should have been processed now assert.isTrue(cache.isProcessed(startChangesetId)); assert.isTrue(cache.isProcessed(endChangesetId)); // Try getting changed elements, it should work this time let changes = cache.getChangedElements(startChangesetId, endChangesetId); assert.isTrue(changes !== undefined); assert.isTrue(changes!.elements.length !== 0); assert.isTrue(changes!.modelIds !== undefined); assert.isTrue(changes!.parentIds !== undefined); assert.isTrue(changes!.parentClassIds !== undefined); assert.isTrue(changes!.elements.length === changes!.classIds.length); assert.isTrue(changes!.elements.length === changes!.opcodes.length); assert.isTrue(changes!.elements.length === changes!.type.length); assert.isTrue(changes!.elements.length === changes!.modelIds!.length); assert.isTrue(changes!.elements.length === changes!.parentIds!.length); assert.isTrue(changes!.elements.length === changes!.parentClassIds!.length); // Try getting changed models const models = cache.getChangedModels(startChangesetId, endChangesetId); assert.isTrue(models !== undefined); assert.isTrue(models!.modelIds.length !== 0); assert.isTrue(models!.modelIds.length === models!.bboxes.length); // Clean and close cache.closeDb(); cache.cleanCaches(); // Destroy the cache // Open the db using the manager and try to get changed elements again to test the cached processed elements cache = ChangedElementsDb.openDb(filePath); assert.isTrue(cache !== undefined); // Check that the changesets should still be in the cache assert.isTrue(cache.isProcessed(startChangesetId)); assert.isTrue(cache.isProcessed(endChangesetId)); // Try getting changed elements again changes = cache.getChangedElements(startChangesetId, endChangesetId); assert.isTrue(changes !== undefined); assert.isTrue(changes!.elements.length !== 0); assert.isTrue(changes!.properties !== undefined); assert.isTrue(changes!.modelIds !== undefined); assert.isTrue(changes!.parentIds !== undefined); assert.isTrue(changes!.parentClassIds !== undefined); // Ensure format is returned correctly assert.isTrue(changes!.elements.length === changes!.classIds.length); assert.isTrue(changes!.elements.length === changes!.opcodes.length); assert.isTrue(changes!.elements.length === changes!.type.length); assert.isTrue(changes!.elements.length === changes!.properties!.length); assert.isTrue(changes!.elements.length === changes!.oldChecksums!.length); assert.isTrue(changes!.elements.length === changes!.newChecksums!.length); assert.isTrue(changes!.elements.length === changes!.modelIds!.length); assert.isTrue(changes!.elements.length === changes!.parentIds!.length); assert.isTrue(changes!.elements.length === changes!.parentClassIds!.length); // If model Ids are returned, check that they correspond to the right length if (changes!.modelIds) assert.isTrue(changes!.elements.length === changes!.modelIds.length); // Ensure we can clean hidden property caches without erroring out cache.closeDb(); cache.cleanCaches(); // Test the ChangedElementsManager // Check that the changesets should still be in the cache assert.isTrue(ChangedElementsManager.isProcessed(iModel.iModelId, startChangesetId)); assert.isTrue(ChangedElementsManager.isProcessed(iModel.iModelId, endChangesetId)); // Check that we can get elements changes = ChangedElementsManager.getChangedElements(iModel.iModelId, startChangesetId, endChangesetId); assert.isTrue(changes !== undefined); assert.isTrue(changes!.elements.length !== 0); assert.isTrue(changes!.elements.length === changes!.classIds.length); assert.isTrue(changes!.elements.length === changes!.opcodes.length); assert.isTrue(changes!.elements.length === changes!.type.length); assert.isTrue(changes!.elements.length === changes!.modelIds!.length); assert.isTrue(changes!.elements.length === changes!.properties!.length); assert.isTrue(changes!.elements.length === changes!.oldChecksums!.length); assert.isTrue(changes!.elements.length === changes!.newChecksums!.length); assert.isTrue(changes!.elements.length === changes!.parentIds!.length); assert.isTrue(changes!.elements.length === changes!.parentClassIds!.length); if (changes!.modelIds) assert.isTrue(changes!.elements.length === changes!.modelIds.length); // Test change data full return type and ensure format is correct const changeData = ChangedElementsManager.getChangeData(iModel.iModelId, startChangesetId, endChangesetId); assert.isTrue(changeData !== undefined); assert.isTrue(changeData!.changedElements !== undefined); assert.isTrue(changeData!.changedModels !== undefined); assert.isTrue(changeData!.changedElements.elements.length === changeData!.changedElements.classIds.length); assert.isTrue(changeData!.changedElements.elements.length === changeData!.changedElements.opcodes.length); assert.isTrue(changeData!.changedElements.elements.length === changeData!.changedElements.type.length); assert.isTrue(changeData?.changedElements.elements.length === changeData!.changedElements.properties!.length); assert.isTrue(changeData?.changedElements.elements.length === changeData!.changedElements.oldChecksums!.length); assert.isTrue(changeData?.changedElements.elements.length === changeData!.changedElements.newChecksums!.length); assert.isTrue(changeData?.changedElements.elements.length === changeData!.changedElements.modelIds!.length); assert.isTrue(changeData?.changedElements.elements.length === changeData!.changedElements.parentIds!.length); assert.isTrue(changeData?.changedElements.elements.length === changeData!.changedElements.parentClassIds!.length); assert.isTrue(changeData!.changedModels.modelIds.length === changeData!.changedModels.bboxes.length); ChangedElementsManager.cleanUp(); }); it("Create ChangedElements Cache and process changesets while rolling Db", async () => { const cacheFilePath: string = BriefcaseManager.getChangeCachePathName(testIModelId); if (IModelJsFs.existsSync(cacheFilePath)) IModelJsFs.removeSync(cacheFilePath); const iModel = await HubWrappers.downloadAndOpenCheckpoint({ accessToken, iTwinId: testITwinId, iModelId: testIModelId, asOf: IModelVersion.first().toJSON() }); const changesets = await IModelHost.hubAccess.queryChangesets({ accessToken, iModelId: testIModelId }); assert.exists(iModel); const filePath = ChangedElementsManager.getChangedElementsPathName(iModel.iModelId); if (IModelJsFs.existsSync(filePath)) IModelJsFs.removeSync(filePath); const cache = ChangedElementsDb.createDb(iModel, filePath); assert.isDefined(cache); // Process single const changesetId = changesets[0].id; // Check that the changesets have not been processed yet assert.isFalse(cache.isProcessed(changesetId)); // Try getting changed elements, should fail because we haven't processed the changesets assert.throws(() => cache.getChangedElements(changesetId, changesetId), IModelError); // Process changesets with "Items" presentation rules const options: ProcessChangesetOptions = { rulesetId: "Items", startChangesetId: changesetId, endChangesetId: changesetId, wantParents: true, wantPropertyChecksums: true, wantRelationshipCaching: true, }; // Get file path before processing and rolling since it requires closing the iModelDb const iModelFilepath = iModel.pathName; const result = await cache.processChangesetsAndRoll(accessToken, iModel, options); const newIModel = SnapshotDb.openDgnDb({ path: iModelFilepath }, OpenMode.Readonly); // Ensure that the iModel got rolled as part of the processing operation assert.equal(newIModel.getCurrentChangeset().id, changesetId); assert.equal(result, DbResult.BE_SQLITE_OK); // Check that the changesets should have been processed now assert.isTrue(cache.isProcessed(changesetId)); // Try getting changed elements, it should work this time const changes = cache.getChangedElements(changesetId, changesetId); assert.isTrue(changes !== undefined); assert.isTrue(changes!.elements.length !== 0); assert.isTrue(changes!.modelIds !== undefined); assert.isTrue(changes!.parentIds !== undefined); assert.isTrue(changes!.parentClassIds !== undefined); assert.isTrue(changes!.elements.length === changes!.classIds.length); assert.isTrue(changes!.elements.length === changes!.opcodes.length); assert.isTrue(changes!.elements.length === changes!.type.length); assert.isTrue(changes!.elements.length === changes!.modelIds!.length); assert.isTrue(changes!.elements.length === changes!.parentIds!.length); assert.isTrue(changes!.elements.length === changes!.parentClassIds!.length); // Try getting changed models const models = cache.getChangedModels(changesetId, changesetId); assert.isTrue(models !== undefined); assert.isTrue(models!.modelIds.length !== 0); assert.isTrue(models!.modelIds.length === models!.bboxes.length); // Destroy the cache cache.closeDb(); cache.cleanCaches(); ChangedElementsManager.cleanUp(); newIModel.closeIModel(); }); it("Create ChangedElements Cache and process changesets while rolling Db without caching", async () => { const cacheFilePath: string = BriefcaseManager.getChangeCachePathName(testIModelId); if (IModelJsFs.existsSync(cacheFilePath)) IModelJsFs.removeSync(cacheFilePath); const iModel = await HubWrappers.downloadAndOpenCheckpoint({ accessToken, iTwinId: testITwinId, iModelId: testIModelId, asOf: IModelVersion.first().toJSON() }); const changesets = await IModelHost.hubAccess.queryChangesets({ accessToken, iModelId: testIModelId }); assert.exists(iModel); const filePath = ChangedElementsManager.getChangedElementsPathName(iModel.iModelId); if (IModelJsFs.existsSync(filePath)) IModelJsFs.removeSync(filePath); const cache = ChangedElementsDb.createDb(iModel, filePath); assert.isDefined(cache); // Process single const changesetId = changesets[0].id; // Check that the changesets have not been processed yet assert.isFalse(cache.isProcessed(changesetId)); // Try getting changed elements, should fail because we haven't processed the changesets assert.throws(() => cache.getChangedElements(changesetId, changesetId), IModelError); // Process changesets with "Items" presentation rules const options: ProcessChangesetOptions = { rulesetId: "Items", startChangesetId: changesetId, endChangesetId: changesetId, wantParents: true, wantPropertyChecksums: true, wantRelationshipCaching: false, }; // Get file path before processing and rolling since it requires closing the iModelDb const iModelFilepath = iModel.pathName; const result = await cache.processChangesetsAndRoll(accessToken, iModel, options); const newIModel = SnapshotDb.openDgnDb({ path: iModelFilepath }, OpenMode.Readonly); // Ensure that the iModel got rolled as part of the processing operation assert.equal(newIModel.getCurrentChangeset().id, changesetId); assert.equal(result, DbResult.BE_SQLITE_OK); // Check that the changesets should have been processed now assert.isTrue(cache.isProcessed(changesetId)); // Try getting changed elements, it should work this time const changes = cache.getChangedElements(changesetId, changesetId); assert.isTrue(changes !== undefined); assert.isTrue(changes!.elements.length !== 0); assert.isTrue(changes!.modelIds !== undefined); assert.isTrue(changes!.parentIds !== undefined); assert.isTrue(changes!.parentClassIds !== undefined); assert.isTrue(changes!.elements.length === changes!.classIds.length); assert.isTrue(changes!.elements.length === changes!.opcodes.length); assert.isTrue(changes!.elements.length === changes!.type.length); assert.isTrue(changes!.elements.length === changes!.modelIds!.length); assert.isTrue(changes!.elements.length === changes!.parentIds!.length); assert.isTrue(changes!.elements.length === changes!.parentClassIds!.length); // Try getting changed models const models = cache.getChangedModels(changesetId, changesetId); assert.isTrue(models !== undefined); assert.isTrue(models!.modelIds.length !== 0); assert.isTrue(models!.modelIds.length === models!.bboxes.length); // Destroy the cache cache.closeDb(); cache.cleanCaches(); ChangedElementsManager.cleanUp(); newIModel.closeIModel(); }); });
the_stack
import * as React from "react"; import * as sui from "./sui"; import * as data from "./data"; import { fireClickOnEnter } from "./util"; export interface ICarouselProps extends React.Props<Carousel> { // Percentage of child width to bleed over either edge of the page bleedPercent: number; selectedIndex?: number; tickId?: string; // if set, collect usage analytics } export interface ICarouselState { leftDisabled?: boolean; rightDisabled?: boolean; } const OUT_OF_BOUND_MARGIN = 300; const DRAG_THRESHOLD = 5; enum DraggingDirection { None = 0, X = 1, Y = 2 } export class Carousel extends data.Component<ICarouselProps, ICarouselState> { private dragSurface: HTMLDivElement; private container: HTMLDivElement; private arrows: HTMLSpanElement[] = []; private isDragging = false; private definitelyDragging = DraggingDirection.None; private childWidth: number; private containerWidth: number; private arrowWidth: number; private actualPageLength: number; private currentOffset = 0; private index = 0; private dragStartX: number; private dragStartY: number; private dragStartOffset: number; private dragOffset: number; private animation: AnimationState; private animationId: number; private childrenElements: HTMLDivElement[] = []; constructor(props: ICarouselProps) { super(props); this.state = { } this.childrenElements = []; this.arrows = []; this.onLeftArrowClick = this.onLeftArrowClick.bind(this); this.onRightArrowClick = this.onRightArrowClick.bind(this); } UNSAFE_componentWillReceiveProps(nextProps: ICarouselProps) { if (nextProps.selectedIndex != undefined) { this.setIndex(nextProps.selectedIndex); } } private handleContainerRef = (c: HTMLDivElement) => { this.container = c; } private handleDragSurfaceRef = (c: HTMLDivElement) => { this.dragSurface = c; } private handleArrowRefs = (c: HTMLSpanElement) => { this.arrows.push(c); } private handleChildRefs = (c: HTMLDivElement) => { if (c) this.childrenElements.push(c) } public renderCore() { const { rightDisabled, leftDisabled } = this.state; const isRTL = pxt.Util.isUserLanguageRtl(); return <div className="ui carouselouter"> {!leftDisabled && <span role="button" className={"carouselarrow left aligned"} tabIndex={0} title={lf("See previous")} aria-label={lf("See previous")} onClick={this.onLeftArrowClick} onKeyDown={fireClickOnEnter} ref={this.handleArrowRefs}> <sui.Icon icon={"circle angle " + (!isRTL ? "left" : "right")} /> </span>} <div className="carouselcontainer" ref={this.handleContainerRef}> <div className="carouselbody" ref={this.handleDragSurfaceRef}> { React.Children.map(this.props.children, (child, index) => child ? <div className={`carouselitem ${this.props.selectedIndex == index ? 'selected' : ''}`} ref={this.handleChildRefs}> {React.cloneElement(child as any, { tabIndex: this.isVisible(index) ? 0 : -1 })} </div> : undefined) } </div> </div> {!rightDisabled && <span role="button" className={"carouselarrow right aligned"} tabIndex={0} title={lf("See more")} aria-label={lf("See more")} onClick={this.onRightArrowClick} onKeyDown={fireClickOnEnter} ref={this.handleArrowRefs}> <sui.Icon icon={"circle angle " + (!pxt.Util.isUserLanguageRtl() ? "right" : "left")} /> </span>} </div> } public onLeftArrowClick() { this.onArrowClick(true); } public onRightArrowClick() { this.onArrowClick(false); } private onArrowClick(left: boolean) { const prevIndex = this.index; const prevScroll = this.container.scrollLeft; this.setIndex(left ? this.index - this.actualPageLength : this.index + this.actualPageLength); const { tickId } = this.props; if (tickId) pxt.tickEvent("carousel.arrow.click", { tickId, index: this.index, left: left ? -1 : 1 }, { interactiveConsent: true }) if (left) { // Focus right most const prevElement = this.index + this.actualPageLength < prevIndex ? this.index + this.actualPageLength : prevIndex - 1; if (this.childrenElements[prevElement]) (this.childrenElements[prevElement].firstChild as HTMLElement).focus(); } else { // Focus left most const nextElement = this.index > prevIndex + this.actualPageLength ? this.index : prevIndex + this.actualPageLength; if (this.childrenElements[nextElement]) (this.childrenElements[nextElement].firstChild as HTMLElement).focus(); } // Undo any scrolling caused by focus() this.container.scrollLeft = prevScroll; } public componentDidMount() { this.initDragSurface(); this.updateDimensions(); window.addEventListener("resize", this.updateDimensions); } public componentWillUnmount() { window.removeEventListener("resize", this.updateDimensions); } public componentDidUpdate() { this.updateDimensions(); } public updateDimensions = () => { if (this.container) { let shouldReposition = false; this.containerWidth = this.container.getBoundingClientRect().width; this.getArrowWidth(); if (this.childrenElements.length) { const newWidth = this.childrenElements[0].getBoundingClientRect().width; if (newWidth !== this.childWidth) { this.childWidth = newWidth; shouldReposition = true; } this.actualPageLength = Math.floor(this.containerWidth / this.childWidth) } this.dragSurface.style.width = this.totalLength() + "px"; this.updateArrows(); if (this.index >= this.maxIndex()) { shouldReposition = true; this.index = this.maxIndex(); } if (shouldReposition) { this.setPosition(this.indexToOffset(this.index)); } } } private initDragSurface() { let down = (event: MouseEvent | TouchEvent | PointerEvent) => { this.definitelyDragging = DraggingDirection.None; this.dragStart(getX(event), getY(event)); }; let up = (event: MouseEvent | TouchEvent | PointerEvent) => { if (this.isDragging) { this.dragEnd(); if (this.definitelyDragging) { event.preventDefault(); event.stopPropagation(); } } }; let leave = (event: MouseEvent | TouchEvent | PointerEvent) => { if (this.isDragging) { this.dragEnd(); } }; let move = (event: MouseEvent | TouchEvent | PointerEvent) => { if (this.isDragging) { let x = getX(event); if (!this.definitelyDragging) { // lock direction let y = getY(event); if (Math.abs(x - this.dragStartX) > DRAG_THRESHOLD) { this.definitelyDragging = DraggingDirection.X; } else if (Math.abs(y - this.dragStartY) > DRAG_THRESHOLD) { this.definitelyDragging = DraggingDirection.Y; } } if (this.definitelyDragging == DraggingDirection.X) { event.stopPropagation(); event.preventDefault(); window.requestAnimationFrame(() => { this.dragMove(x); }); } } }; this.dragSurface.addEventListener("click", event => { if (this.definitelyDragging) { event.stopPropagation(); event.preventDefault(); } }); if ((window as any).PointerEvent) { this.dragSurface.addEventListener("pointerdown", down); this.dragSurface.addEventListener("pointerup", up); this.dragSurface.addEventListener("pointerleave", leave); this.dragSurface.addEventListener("pointermove", move); } else { this.dragSurface.addEventListener("mousedown", down); this.dragSurface.addEventListener("mouseup", up); this.dragSurface.addEventListener("mouseleave", leave); this.dragSurface.addEventListener("mousemove", move); if (pxt.BrowserUtils.isTouchEnabled()) { this.dragSurface.addEventListener("touchstart", down); this.dragSurface.addEventListener("touchend", up); this.dragSurface.addEventListener("touchcancel", leave); this.dragSurface.addEventListener("touchmove", move); } } } private dragStart(startX: number, startY: number) { this.isDragging = true; this.dragStartX = startX; this.dragStartY = startY; this.dragStartOffset = this.currentOffset; if (this.animationId) { window.cancelAnimationFrame(this.animationId); this.animationId = 0; } } private dragEnd() { this.isDragging = false; this.calculateIndex(); } private dragMove(x: number) { this.dragOffset = x - this.dragStartX; const newOffset = pxt.Util.isUserLanguageRtl() ? this.dragStartOffset + this.dragOffset : this.dragStartOffset - this.dragOffset; this.setPosition(newOffset); } private setPosition(offset: number) { if (this.dragSurface) { offset = Math.min(Math.max(offset, -OUT_OF_BOUND_MARGIN), this.maxScrollOffset()); this.currentOffset = offset; if (pxt.Util.isUserLanguageRtl()) { this.dragSurface.style.marginRight = -offset + "px"; } else { this.dragSurface.style.marginLeft = -offset + "px"; } } } private calculateIndex() { if (this.dragSurface) { const bucketIndex = Math.round(Math.max(this.currentOffset, 0) / this.childWidth); let index: number; if (this.currentOffset > this.dragStartOffset) { index = bucketIndex; } else { index = bucketIndex - 1; } this.setIndex(index, 200); } } private setIndex(index: number, millis?: number) { const newIndex = Math.max(Math.min(index, this.maxIndex()), 0); if (!millis) { millis = Math.abs(newIndex - this.index) * 100; } this.index = newIndex; this.updateArrows(); this.animation = new AnimationState(this.currentOffset, this.indexToOffset(this.index), millis); if (!this.animationId) { this.animationId = window.requestAnimationFrame(this.easeTowardsIndex.bind(this)); } } private isVisible(index: number) { return index >= this.index && index < this.index + (this.actualPageLength || 4); } private easeTowardsIndex(time: number) { if (this.dragSurface) { this.setPosition(this.animation.getPosition(time)); if (this.animation.isComplete) { this.animation = undefined; this.animationId = 0; } else { this.animationId = window.requestAnimationFrame(this.easeTowardsIndex.bind(this)); } } } private indexToOffset(index: number) { if (index <= 0) { return 0; } if (index === this.maxIndex()) { return this.totalLength() - this.containerWidth - OUT_OF_BOUND_MARGIN + this.arrowWidth * 2 } return index * this.childWidth - this.childWidth * this.props.bleedPercent / 100; } private totalLength() { return React.Children.count(this.props.children) * this.childWidth + OUT_OF_BOUND_MARGIN; } private getArrowWidth() { if (this.arrows.length) { this.arrowWidth = 0; this.arrows.forEach(a => { if (a) { this.arrowWidth = Math.max(a.getBoundingClientRect().width, this.arrowWidth) } }); } } private maxScrollOffset() { return Math.max(this.totalLength() - this.actualPageLength * this.childWidth + OUT_OF_BOUND_MARGIN, 0); } private maxIndex() { return Math.max(this.childrenElements.length - this.actualPageLength, 0); } private updateArrows() { const { rightDisabled, leftDisabled } = this.state || {} as any; const newRightDisabled = this.index === this.maxIndex(); const newLeftDisabled = this.index === 0; if (newRightDisabled !== rightDisabled || newLeftDisabled !== leftDisabled) { this.setState({ leftDisabled: newLeftDisabled, rightDisabled: newRightDisabled }); } } } class AnimationState { private slope: number; private startTime: number; public isComplete = false; constructor(private start: number, private end: number, private millis: number) { this.slope = (end - start) / millis; } getPosition(time: number) { if (this.isComplete) return this.end; if (this.startTime === undefined) { this.startTime = time; return this.start; } const diff = time - this.startTime; if (diff > this.millis) { this.isComplete = true; return this.end; } return this.start + Math.floor(this.slope * diff); } } function getX(event: MouseEvent | TouchEvent | PointerEvent) { if ("screenX" in event) { return (event as MouseEvent).screenX; } else { return (event as TouchEvent).changedTouches[0].screenX } } function getY(event: MouseEvent | TouchEvent | PointerEvent) { if ("screenY" in event) { return (event as MouseEvent).screenY; } else { return (event as TouchEvent).changedTouches[0].screenY } }
the_stack
import {range} from 'd3-array' import {Scale, NumericColumnData} from '../types' import {useLazyMemo} from './useLazyMemo' import {isDefined} from './isDefined' import {minBy} from './extrema' export const useHoverPointIndices = ( mode: 'x' | 'y' | 'xy', mouseX: number, mouseY: number, xColumnData: NumericColumnData, yColumnData: NumericColumnData, groupColData: NumericColumnData, xScale: Scale<number, number>, yScale: Scale<number, number>, width: number, height: number ): number[] => { const isActive = mouseX !== undefined && mouseX !== null && mouseX >= 0 && mouseX < width && mouseY !== undefined && mouseY !== null && mouseY >= 0 && mouseY < height const xColData = xColumnData ? xColumnData : [] const yColData = yColumnData ? yColumnData : [] const index = useLazyMemo( () => buildIndex(xColData, yColData, xScale, yScale, width, height), [xColData, yColData, xScale, yScale, width, height], isActive ) if (!isActive) { return null } let hoverLineIndices if (mode === 'x') { hoverLineIndices = lookupIndex1D( index.xBins, mouseX, xScale.invert(mouseX), xColData, groupColData, width ) } else if (mode === 'y') { hoverLineIndices = lookupIndex1D( index.yBins, mouseY, yScale.invert(mouseY), yColData, groupColData, height ) } else { hoverLineIndices = lookupIndex2D( index.xyBins, mouseX, mouseY, xScale.invert(mouseX), yScale.invert(mouseY), xColData, yColData, width, height ) } return hoverLineIndices } const INDEX_BIN_WIDTH = 30 type IndexTable = { xBins: number[][] yBins: number[][] xyBins: number[][][] // :-] } /* When a user hovers over a line graph, we need to show the points on each line closest to the mouse position. Since we don't want to look through the entire table to find the closest points on every hover event, we build an index on the first hover event that makes subsequent lookups fast. The index works by dividing the graph into discrete bins, each of them with a side length of `INDEX_BIN_WIDTH` pixels. In each bin we store the indices of rows in the original user-supplied table whose corresponding point lies within that bin. Then on every hover event, we can use some quick math to decide which bin the current hover corresponds to. Then we perform a linear search within each bin to find the point on each line closest to the mouse position. This limits the amount of work we have to do, since we only need to scan through a single bin, rather than through the entire table. See `lookupIndex2D` and `lookupIndex1D` for more info. */ const buildIndex = ( xColData: NumericColumnData, yColData: NumericColumnData, xScale: Scale<number, number>, yScale: Scale<number, number>, width: number, height: number ): IndexTable => { const xBinCount = Math.ceil(width / INDEX_BIN_WIDTH) + 1 const yBinCount = Math.ceil(height / INDEX_BIN_WIDTH) + 1 const indexTable = { xBins: range(xBinCount).map(_ => []), yBins: range(yBinCount).map(_ => []), xyBins: range(xBinCount).map(_ => range(yBinCount).map(_ => [])), } for (let i = 0; i < xColData.length; i++) { const x = xScale(xColData[i]) const y = yScale(yColData[i]) if (!isDefined(x) || !isDefined(y)) { continue } const xBinIndex = getBinIndex(x, width) const yBinIndex = getBinIndex(y, height) if ( xBinIndex < 0 || xBinIndex >= xBinCount || yBinIndex < 0 || yBinIndex >= yBinCount ) { continue } indexTable.xBins[xBinIndex].push(i) indexTable.yBins[yBinIndex].push(i) indexTable.xyBins[xBinIndex][yBinIndex].push(i) } return indexTable } const getBinIndex = (x: number, length: number): number => { const binCount = Math.ceil(length / INDEX_BIN_WIDTH) const binIndex = Math.floor((x / length) * binCount) return binIndex } /* This function finds the single point in a line plot closest to an (x, y) position using a precomputed `IndexTable`. The `IndexTable` partitions the plot into a discrete collection of rectangles called "bins". ----------------------------- | | | | | | | | | | | | | | | ----------------------------- | | | | | | | | | | | | | | | ----------------------------- | | | | | | | | | | | | | | | ----------------------------- | | | | | | | | | | | | | | | ----------------------------- | | | | | | | | | | | | | | | ----------------------------- Each bin stores references to the points contained within the bin in the visualization. Each point reference is the index of a row in the original user-supplied table that contains the data of the point. When the user hovers over the plot, we can lookup the bin corresponding to the (x, y) position of their mouse in constant time. In the following picture, that bin is marked with an `x`: ----------------------------- | | | | | | | | | | | | | | | ----------------------------- | | | | | | | | | | | | | | | ----------------------------- | | | | | | | | | |x| | | | | ----------------------------- | | | | | | | | | | | | | | | ----------------------------- | | | | | | | | | | | | | | | ----------------------------- We search through points in that bin to find the point closet to the exact (x, y) position of the mouse. If we find such a point, we return it immediately (as an index reference). However, there may be no points in the bin, in which case we need to expand our selection to nearby bins. We do so by searching the bins that border the initial bin: ----------------------------- | | | | | | | | | | | | | | | ----------------------------- | | | | | | | | |x|x|x| | | | ----------------------------- | | | | | | | | |x| |x| | | | ----------------------------- | | | | | | | | |x|x|x| | | | ----------------------------- | | | | | | | | | | | | | | | ----------------------------- If we still don't find a point, we expand the search again: ----------------------------- | | | | | | | |x|x|x|x|x| | | ----------------------------- | | | | | | | |x| | | |x| | | ----------------------------- | | | | | | | |x| | | |x| | | ----------------------------- | | | | | | | |x| | | |x| | | ----------------------------- | | | | | | | |x|x|x|x|x| | | ----------------------------- Expansion will stop at the bins that border the plot. So the next iteration would only expand horizontally, but not vertically: ----------------------------- | | | | | | |x|x|x|x|x|x|x| | ----------------------------- | | | | | | |x| | | | | |x| | ----------------------------- | | | | | | |x| | | | | |x| | ----------------------------- | | | | | | |x| | | | | |x| | ----------------------------- | | | | | | |x|x|x|x|x|x|x| | ----------------------------- When there is no where left to expand, we stop the search. */ const lookupIndex2D = ( bins: number[][][], mouseX: number, mouseY: number, dataX: number, dataY: number, xColData: NumericColumnData, yColData: NumericColumnData, width: number, height: number ): number[] => { const xBinCount = bins.length const yBinCount = bins[0].length let i0 = Math.max(0, getBinIndex(mouseX, width)) let i1 = Math.min(xBinCount - 1, getBinIndex(mouseX, width)) let j0 = Math.max(0, getBinIndex(mouseY, height)) let j1 = Math.min(yBinCount - 1, getBinIndex(mouseY, height)) let closestRowIndices = bins[i0][j0] let hasSearchedEverything = i0 === 0 && i1 === xBinCount - 1 && j0 === 0 && j1 === yBinCount - 1 while (closestRowIndices.length === 0 && !hasSearchedEverything) { i0 = Math.max(0, i0 - 1) i1 = Math.min(xBinCount - 1, i1 + 1) j0 = Math.max(0, j0 - 1) j1 = Math.min(yBinCount - 1, j1 + 1) closestRowIndices = collectClosestRowIndices(i0, i1, j0, j1, bins) hasSearchedEverything = i0 === 0 && i1 === xBinCount - 1 && j0 === 0 && j1 === yBinCount - 1 } if (closestRowIndices.length === 0) { return [] } const nearestIndex = minBy( rowIndex => sqDist(dataX, dataY, xColData[rowIndex], yColData[rowIndex]), closestRowIndices ) return [nearestIndex] } const collectClosestRowIndices = (i0, i1, j0, j1, bins): number[] => { const closestRowIndices = [] let x = i0 let y = j0 while (x <= i1) { bins[x][y].forEach((index: number) => closestRowIndices.push(index)) x++ } x-- y++ while (y <= j1) { bins[x][y].forEach((index: number) => closestRowIndices.push(index)) y++ } y-- x-- while (x >= i0) { bins[x][y].forEach((index: number) => closestRowIndices.push(index)) x-- } x++ y-- while (y >= j0) { bins[x][y].forEach((index: number) => closestRowIndices.push(index)) y-- } return closestRowIndices } const sqDist = (x0: number, y0: number, x1: number, y1: number): number => { return (x1 - x0) ** 2 + (y1 - y0) ** 2 } interface NearestIndexByGroup { [groupKey: string]: {i: number; distance: number} } /* This function is the one-dimensional analogue of `lookupIndex2D`; see `lookupIndex2D` function for more info. */ const lookupIndex1D = ( bins: number[][], mouseCoord: number, dataCoord: number, colData: NumericColumnData, groupColData: NumericColumnData, length: number ): number[] => { const initialBinIndex = getBinIndex(mouseCoord, length) const maxBinIndex = bins.length - 1 let leftBinIndex = Math.max(0, initialBinIndex - 1) let rightBinIndex = Math.min(initialBinIndex, maxBinIndex) let leftRowIndices = bins[leftBinIndex] let rightRowIndices = bins[rightBinIndex] // If no points are within the current left and right bins, expand the search // outward to the next nearest bins while ( !leftRowIndices.length && !rightRowIndices.length && (leftBinIndex !== 0 || rightBinIndex !== maxBinIndex) ) { leftBinIndex = Math.max(0, leftBinIndex - 1) rightBinIndex = Math.min(rightBinIndex + 1, maxBinIndex) leftRowIndices = bins[leftBinIndex] rightRowIndices = bins[rightBinIndex] } const nearestIndexByGroup: NearestIndexByGroup = {} collectNearestIndices( nearestIndexByGroup, leftRowIndices, dataCoord, colData, groupColData ) collectNearestIndices( nearestIndexByGroup, rightRowIndices, dataCoord, colData, groupColData ) const nearestRows = Object.values(nearestIndexByGroup) if (!nearestRows.length) { return [] } const nearestDistance = nearestRows.reduce( (acc, row) => Math.min(acc, row.distance), Infinity ) return nearestRows.filter(d => d.distance === nearestDistance).map(d => d.i) } const collectNearestIndices = ( acc: NearestIndexByGroup, rowIndices: number[], dataCoord: number, colData: NumericColumnData, groupColData: NumericColumnData ): void => { for (const i of rowIndices) { const group = groupColData[i] const distance = Math.floor(Math.abs(dataCoord - colData[i])) if (!acc[group] || distance < acc[group].distance) { acc[group] = {i, distance} } } }
the_stack
import {assert} from '../utils/assert'; import {getAccessorArrayTypeAndLength} from '../gltf-utils/gltf-utils'; import {BufferView} from '../types/gltf-json-schema'; import {BufferView as BufferViewPostprocessed} from '../types/gltf-postprocessed-schema'; // This is a post processor for loaded glTF files // The goal is to make the loaded data easier to use in WebGL applications // // Functions: // * Resolve indexed arrays structure of glTF into a linked tree. // * Translate stringified enum keys and values into WebGL constants. // * Load images (optional) // ENUM LOOKUP const COMPONENTS = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16 }; const BYTES = { 5120: 1, // BYTE 5121: 1, // UNSIGNED_BYTE 5122: 2, // SHORT 5123: 2, // UNSIGNED_SHORT 5125: 4, // UNSIGNED_INT 5126: 4 // FLOAT }; const GL_SAMPLER = { // Sampler parameters TEXTURE_MAG_FILTER: 0x2800, TEXTURE_MIN_FILTER: 0x2801, TEXTURE_WRAP_S: 0x2802, TEXTURE_WRAP_T: 0x2803, // Sampler default values REPEAT: 0x2901, LINEAR: 0x2601, NEAREST_MIPMAP_LINEAR: 0x2702 }; const SAMPLER_PARAMETER_GLTF_TO_GL = { magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER, minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER, wrapS: GL_SAMPLER.TEXTURE_WRAP_S, wrapT: GL_SAMPLER.TEXTURE_WRAP_T }; // When undefined, a sampler with repeat wrapping and auto filtering should be used. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#texture const DEFAULT_SAMPLER = { [GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR, [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR, [GL_SAMPLER.TEXTURE_WRAP_S]: GL_SAMPLER.REPEAT, [GL_SAMPLER.TEXTURE_WRAP_T]: GL_SAMPLER.REPEAT }; function getBytesFromComponentType(componentType) { return BYTES[componentType]; } function getSizeFromAccessorType(type) { return COMPONENTS[type]; } class GLTFPostProcessor { baseUri: string = ''; json: Record<string, any> = {}; buffers: [] = []; images: [] = []; postProcess(gltf, options = {}) { const {json, buffers = [], images = [], baseUri = ''} = gltf; assert(json); this.baseUri = baseUri; this.json = json; this.buffers = buffers; this.images = images; this._resolveTree(this.json, options); return this.json; } // Convert indexed glTF structure into tree structure // cross-link index resolution, enum lookup, convenience calculations // eslint-disable-next-line complexity _resolveTree(json, options = {}) { if (json.bufferViews) { json.bufferViews = json.bufferViews.map((bufView, i) => this._resolveBufferView(bufView, i)); } if (json.images) { json.images = json.images.map((image, i) => this._resolveImage(image, i)); } if (json.samplers) { json.samplers = json.samplers.map((sampler, i) => this._resolveSampler(sampler, i)); } if (json.textures) { json.textures = json.textures.map((texture, i) => this._resolveTexture(texture, i)); } if (json.accessors) { json.accessors = json.accessors.map((accessor, i) => this._resolveAccessor(accessor, i)); } if (json.materials) { json.materials = json.materials.map((material, i) => this._resolveMaterial(material, i)); } if (json.meshes) { json.meshes = json.meshes.map((mesh, i) => this._resolveMesh(mesh, i)); } if (json.nodes) { json.nodes = json.nodes.map((node, i) => this._resolveNode(node, i)); } if (json.skins) { json.skins = json.skins.map((skin, i) => this._resolveSkin(skin, i)); } if (json.scenes) { json.scenes = json.scenes.map((scene, i) => this._resolveScene(scene, i)); } if (json.scene !== undefined) { json.scene = json.scenes[this.json.scene]; } } getScene(index) { return this._get('scenes', index); } getNode(index) { return this._get('nodes', index); } getSkin(index) { return this._get('skins', index); } getMesh(index) { return this._get('meshes', index); } getMaterial(index) { return this._get('materials', index); } getAccessor(index) { return this._get('accessors', index); } getCamera(index) { return null; // TODO: fix this } getTexture(index) { return this._get('textures', index); } getSampler(index) { return this._get('samplers', index); } getImage(index) { return this._get('images', index); } getBufferView(index) { return this._get('bufferViews', index); } getBuffer(index) { return this._get('buffers', index); } _get(array, index) { // check if already resolved if (typeof index === 'object') { return index; } const object = this.json[array] && this.json[array][index]; if (!object) { console.warn(`glTF file error: Could not find ${array}[${index}]`); // eslint-disable-line } return object; } // PARSING HELPERS _resolveScene(scene, index) { // scene = {...scene}; scene.id = scene.id || `scene-${index}`; scene.nodes = (scene.nodes || []).map((node) => this.getNode(node)); return scene; } _resolveNode(node, index) { // node = {...node}; node.id = node.id || `node-${index}`; if (node.children) { node.children = node.children.map((child) => this.getNode(child)); } if (node.mesh !== undefined) { node.mesh = this.getMesh(node.mesh); } else if (node.meshes !== undefined && node.meshes.length) { node.mesh = node.meshes.reduce( (accum, meshIndex) => { const mesh = this.getMesh(meshIndex); accum.id = mesh.id; accum.primitives = accum.primitives.concat(mesh.primitives); return accum; }, {primitives: []} ); } if (node.camera !== undefined) { node.camera = this.getCamera(node.camera); } if (node.skin !== undefined) { node.skin = this.getSkin(node.skin); } return node; } _resolveSkin(skin, index) { // skin = {...skin}; skin.id = skin.id || `skin-${index}`; skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices); return skin; } _resolveMesh(mesh, index) { // mesh = {...mesh}; mesh.id = mesh.id || `mesh-${index}`; if (mesh.primitives) { mesh.primitives = mesh.primitives.map((primitive) => { primitive = {...primitive}; const attributes = primitive.attributes; primitive.attributes = {}; for (const attribute in attributes) { primitive.attributes[attribute] = this.getAccessor(attributes[attribute]); } if (primitive.indices !== undefined) { primitive.indices = this.getAccessor(primitive.indices); } if (primitive.material !== undefined) { primitive.material = this.getMaterial(primitive.material); } return primitive; }); } return mesh; } _resolveMaterial(material, index) { // material = {...material}; material.id = material.id || `material-${index}`; if (material.normalTexture) { material.normalTexture = {...material.normalTexture}; material.normalTexture.texture = this.getTexture(material.normalTexture.index); } if (material.occlusionTexture) { material.occlustionTexture = {...material.occlustionTexture}; material.occlusionTexture.texture = this.getTexture(material.occlusionTexture.index); } if (material.emissiveTexture) { material.emmisiveTexture = {...material.emmisiveTexture}; material.emissiveTexture.texture = this.getTexture(material.emissiveTexture.index); } if (!material.emissiveFactor) { material.emissiveFactor = material.emmisiveTexture ? [1, 1, 1] : [0, 0, 0]; } if (material.pbrMetallicRoughness) { material.pbrMetallicRoughness = {...material.pbrMetallicRoughness}; const mr = material.pbrMetallicRoughness; if (mr.baseColorTexture) { mr.baseColorTexture = {...mr.baseColorTexture}; mr.baseColorTexture.texture = this.getTexture(mr.baseColorTexture.index); } if (mr.metallicRoughnessTexture) { mr.metallicRoughnessTexture = {...mr.metallicRoughnessTexture}; mr.metallicRoughnessTexture.texture = this.getTexture(mr.metallicRoughnessTexture.index); } } return material; } _resolveAccessor(accessor, index) { // accessor = {...accessor}; accessor.id = accessor.id || `accessor-${index}`; if (accessor.bufferView !== undefined) { // Draco encoded meshes don't have bufferView accessor.bufferView = this.getBufferView(accessor.bufferView); } // Look up enums accessor.bytesPerComponent = getBytesFromComponentType(accessor.componentType); accessor.components = getSizeFromAccessorType(accessor.type); accessor.bytesPerElement = accessor.bytesPerComponent * accessor.components; // Create TypedArray for the accessor // Note: The canonical way to instantiate is to ignore this array and create // WebGLBuffer's using the bufferViews. if (accessor.bufferView) { const buffer = accessor.bufferView.buffer; const {ArrayType, byteLength} = getAccessorArrayTypeAndLength(accessor, accessor.bufferView); const byteOffset = (accessor.bufferView.byteOffset || 0) + (accessor.byteOffset || 0) + buffer.byteOffset; let cutBuffer = buffer.arrayBuffer.slice(byteOffset, byteOffset + byteLength); if (accessor.bufferView.byteStride) { cutBuffer = this._getValueFromInterleavedBuffer( buffer, byteOffset, accessor.bufferView.byteStride, accessor.bytesPerElement, accessor.count ); } accessor.value = new ArrayType(cutBuffer); } return accessor; } /** * Take values of particular accessor from interleaved buffer * various parts of the buffer * @param buffer * @param byteOffset * @param byteStride * @param bytesPerElement * @param count * @returns */ _getValueFromInterleavedBuffer(buffer, byteOffset, byteStride, bytesPerElement, count) { const result = new Uint8Array(count * bytesPerElement); for (let i = 0; i < count; i++) { const elementOffset = byteOffset + i * byteStride; result.set( new Uint8Array(buffer.arrayBuffer.slice(elementOffset, elementOffset + bytesPerElement)), i * bytesPerElement ); } return result.buffer; } _resolveTexture(texture, index) { // texture = {...texture}; texture.id = texture.id || `texture-${index}`; texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER; texture.source = this.getImage(texture.source); return texture; } _resolveSampler(sampler, index) { // sampler = {...sampler}; sampler.id = sampler.id || `sampler-${index}`; // Map textual parameters to GL parameter values sampler.parameters = {}; for (const key in sampler) { const glEnum = this._enumSamplerParameter(key); if (glEnum !== undefined) { sampler.parameters[glEnum] = sampler[key]; } } return sampler; } _enumSamplerParameter(key) { return SAMPLER_PARAMETER_GLTF_TO_GL[key]; } _resolveImage(image, index) { // image = {...image}; image.id = image.id || `image-${index}`; if (image.bufferView !== undefined) { image.bufferView = this.getBufferView(image.bufferView); } // Check if image has been preloaded by the GLTFLoader // If so, link it into the JSON and drop the URI const preloadedImage = this.images[index]; if (preloadedImage) { image.image = preloadedImage; } return image; } _resolveBufferView(bufferView: BufferView, index: number): BufferViewPostprocessed { // bufferView = {...bufferView}; const bufferIndex = bufferView.buffer; const result: BufferViewPostprocessed = { id: `bufferView-${index}`, ...bufferView, buffer: this.buffers[bufferIndex] }; // @ts-expect-error const arrayBuffer = this.buffers[bufferIndex].arrayBuffer; // @ts-expect-error let byteOffset = this.buffers[bufferIndex].byteOffset || 0; if ('byteOffset' in bufferView) { byteOffset += bufferView.byteOffset; } result.data = new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength); return result; } _resolveCamera(camera, index) { camera.id = camera.id || `camera-${index}`; // TODO - create 4x4 matrices if (camera.perspective) { // camera.matrix = createPerspectiveMatrix(camera.perspective); } if (camera.orthographic) { // camera.matrix = createOrthographicMatrix(camera.orthographic); } return camera; } } export function postProcessGLTF(gltf, options?) { return new GLTFPostProcessor().postProcess(gltf, options); }
the_stack
import * as Common from '../../core/common/common.js'; import networkWaterfallColumnStyles from './networkWaterfallColumn.css.js'; import type * as SDK from '../../core/sdk/sdk.js'; import * as PerfUI from '../../ui/legacy/components/perf_ui/perf_ui.js'; import * as UI from '../../ui/legacy/legacy.js'; import * as ThemeSupport from '../../ui/legacy/theme_support/theme_support.js'; import type {NetworkNode} from './NetworkDataGridNode.js'; import {RequestTimeRangeNameToColor} from './NetworkOverview.js'; import type {Label, NetworkTimeCalculator} from './NetworkTimeCalculator.js'; import type {RequestTimeRange} from './RequestTimingView.js'; import {RequestTimeRangeNames, RequestTimingView} from './RequestTimingView.js'; const BAR_SPACING = 1; export class NetworkWaterfallColumn extends UI.Widget.VBox { private canvas: HTMLCanvasElement; private canvasPosition: DOMRect; private readonly leftPadding: number; private readonly fontSize: number; private rightPadding: number; private scrollTop: number; private headerHeight: number; private calculator: NetworkTimeCalculator; private rawRowHeight: number; private rowHeight: number; private offsetWidth: number; private offsetHeight: number; private startTime: number; private endTime: number; private readonly popoverHelper: UI.PopoverHelper.PopoverHelper; private nodes: NetworkNode[]; private hoveredNode: NetworkNode|null; private eventDividers: Map<string, number[]>; private updateRequestID!: number|undefined; private readonly styleForTimeRangeName: Map<RequestTimeRangeNames, _LayerStyle>; private readonly styleForWaitingResourceType: Map<Common.ResourceType.ResourceType, _LayerStyle>; private readonly styleForDownloadingResourceType: Map<Common.ResourceType.ResourceType, _LayerStyle>; private readonly wiskerStyle: _LayerStyle; private readonly hoverDetailsStyle: _LayerStyle; private readonly pathForStyle: Map<_LayerStyle, Path2D>; private textLayers: _TextLayer[]; constructor(calculator: NetworkTimeCalculator) { // TODO(allada) Make this a shadowDOM when the NetworkWaterfallColumn gets moved into NetworkLogViewColumns. super(false); this.canvas = (this.contentElement.createChild('canvas') as HTMLCanvasElement); this.canvas.tabIndex = -1; this.setDefaultFocusedElement(this.canvas); this.canvasPosition = this.canvas.getBoundingClientRect(); this.leftPadding = 5; this.fontSize = 10; this.rightPadding = 0; this.scrollTop = 0; this.headerHeight = 0; this.calculator = calculator; // this.rawRowHeight captures model height (41 or 21px), // this.rowHeight is computed height of the row in CSS pixels, can be 20.8 for zoomed-in content. this.rawRowHeight = 0; this.rowHeight = 0; this.offsetWidth = 0; this.offsetHeight = 0; this.startTime = this.calculator.minimumBoundary(); this.endTime = this.calculator.maximumBoundary(); this.popoverHelper = new UI.PopoverHelper.PopoverHelper(this.element, this.getPopoverRequest.bind(this)); this.popoverHelper.setHasPadding(true); this.popoverHelper.setTimeout(300, 300); this.nodes = []; this.hoveredNode = null; this.eventDividers = new Map(); this.element.addEventListener('mousemove', this.onMouseMove.bind(this), true); this.element.addEventListener('mouseleave', _event => this.setHoveredNode(null, false), true); this.element.addEventListener('click', this.onClick.bind(this), true); this.styleForTimeRangeName = NetworkWaterfallColumn.buildRequestTimeRangeStyle(); const resourceStyleTuple = NetworkWaterfallColumn.buildResourceTypeStyle(); this.styleForWaitingResourceType = resourceStyleTuple[0]; this.styleForDownloadingResourceType = resourceStyleTuple[1]; const baseLineColor = ThemeSupport.ThemeSupport.instance().patchColorText('#a5a5a5', ThemeSupport.ThemeSupport.ColorUsage.Foreground); this.wiskerStyle = {borderColor: baseLineColor, lineWidth: 1, fillStyle: undefined}; this.hoverDetailsStyle = {fillStyle: baseLineColor, lineWidth: 1, borderColor: baseLineColor}; this.pathForStyle = new Map(); this.textLayers = []; } private static buildRequestTimeRangeStyle(): Map<RequestTimeRangeNames, _LayerStyle> { const types = RequestTimeRangeNames; const styleMap = new Map<RequestTimeRangeNames, _LayerStyle>(); styleMap.set(types.Connecting, {fillStyle: RequestTimeRangeNameToColor[types.Connecting]}); styleMap.set(types.SSL, {fillStyle: RequestTimeRangeNameToColor[types.SSL]}); styleMap.set(types.DNS, {fillStyle: RequestTimeRangeNameToColor[types.DNS]}); styleMap.set(types.Proxy, {fillStyle: RequestTimeRangeNameToColor[types.Proxy]}); styleMap.set(types.Blocking, {fillStyle: RequestTimeRangeNameToColor[types.Blocking]}); styleMap.set(types.Push, {fillStyle: RequestTimeRangeNameToColor[types.Push]}); styleMap.set( types.Queueing, {fillStyle: RequestTimeRangeNameToColor[types.Queueing], lineWidth: 2, borderColor: 'lightgrey'}); // This ensures we always show at least 2 px for a request. styleMap.set(types.Receiving, { fillStyle: RequestTimeRangeNameToColor[types.Receiving], lineWidth: 2, borderColor: '#03A9F4', }); styleMap.set(types.Waiting, {fillStyle: RequestTimeRangeNameToColor[types.Waiting]}); styleMap.set(types.ReceivingPush, {fillStyle: RequestTimeRangeNameToColor[types.ReceivingPush]}); styleMap.set(types.ServiceWorker, {fillStyle: RequestTimeRangeNameToColor[types.ServiceWorker]}); styleMap.set( types.ServiceWorkerPreparation, {fillStyle: RequestTimeRangeNameToColor[types.ServiceWorkerPreparation]}); styleMap.set(types.ServiceWorkerRespondWith, { fillStyle: RequestTimeRangeNameToColor[types.ServiceWorkerRespondWith], }); return styleMap; } private static buildResourceTypeStyle(): Map<Common.ResourceType.ResourceType, _LayerStyle>[] { const baseResourceTypeColors = new Map([ ['document', 'hsl(215, 100%, 80%)'], ['font', 'hsl(8, 100%, 80%)'], ['media', 'hsl(90, 50%, 80%)'], ['image', 'hsl(90, 50%, 80%)'], ['script', 'hsl(31, 100%, 80%)'], ['stylesheet', 'hsl(272, 64%, 80%)'], ['texttrack', 'hsl(8, 100%, 80%)'], ['websocket', 'hsl(0, 0%, 95%)'], ['xhr', 'hsl(53, 100%, 80%)'], ['fetch', 'hsl(53, 100%, 80%)'], ['other', 'hsl(0, 0%, 95%)'], ]); const waitingStyleMap = new Map<Common.ResourceType.ResourceType, _LayerStyle>(); const downloadingStyleMap = new Map<Common.ResourceType.ResourceType, _LayerStyle>(); for (const resourceType of Object.values(Common.ResourceType.resourceTypes)) { let color = baseResourceTypeColors.get(resourceType.name()); if (!color) { color = baseResourceTypeColors.get('other'); } const borderColor = toBorderColor((color as string)); waitingStyleMap.set( // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // @ts-expect-error resourceType, {fillStyle: toWaitingColor((color as string)), lineWidth: 1, borderColor: borderColor}); // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // @ts-expect-error downloadingStyleMap.set(resourceType, {fillStyle: color, lineWidth: 1, borderColor: borderColor}); } return [waitingStyleMap, downloadingStyleMap]; function toBorderColor(color: string): string|null { const parsedColor = Common.Color.Color.parse(color); if (!parsedColor) { return ''; } const hsla = parsedColor.hsla(); hsla[1] /= 2; hsla[2] -= Math.min(hsla[2], 0.2); return parsedColor.asString(null); } function toWaitingColor(color: string): string|null { const parsedColor = Common.Color.Color.parse(color); if (!parsedColor) { return ''; } const hsla = parsedColor.hsla(); hsla[2] *= 1.1; return parsedColor.asString(null); } } private resetPaths(): void { this.pathForStyle.clear(); this.pathForStyle.set(this.wiskerStyle, new Path2D()); this.styleForTimeRangeName.forEach(style => this.pathForStyle.set(style, new Path2D())); this.styleForWaitingResourceType.forEach(style => this.pathForStyle.set(style, new Path2D())); this.styleForDownloadingResourceType.forEach(style => this.pathForStyle.set(style, new Path2D())); this.pathForStyle.set(this.hoverDetailsStyle, new Path2D()); } willHide(): void { this.popoverHelper.hidePopover(); } wasShown(): void { this.update(); this.registerCSSFiles([networkWaterfallColumnStyles]); } private onMouseMove(event: MouseEvent): void { this.setHoveredNode(this.getNodeFromPoint(event.offsetX, event.offsetY), event.shiftKey); } private onClick(event: MouseEvent): void { const handled = this.setSelectedNode(this.getNodeFromPoint(event.offsetX, event.offsetY)); if (handled) { event.consume(true); } } private getPopoverRequest(event: MouseEvent): UI.PopoverHelper.PopoverRequest|null { if (!this.hoveredNode) { return null; } const request = this.hoveredNode.request(); if (!request) { return null; } const useTimingBars = !Common.Settings.Settings.instance().moduleSetting('networkColorCodeResourceTypes').get() && !this.calculator.startAtZero; let range; let start; let end; if (useTimingBars) { range = RequestTimingView.calculateRequestTimeRanges(request, 0) .find(data => data.name === RequestTimeRangeNames.Total); start = this.timeToPosition((range as RequestTimeRange).start); end = this.timeToPosition((range as RequestTimeRange).end); } else { range = this.getSimplifiedBarRange(request, 0); start = range.start; end = range.end; } if (end - start < 50) { const halfWidth = (end - start) / 2; start = start + halfWidth - 25; end = end - halfWidth + 25; } if (event.clientX < this.canvasPosition.left + start || event.clientX > this.canvasPosition.left + end) { return null; } const rowIndex = this.nodes.findIndex(node => node.hovered()); const barHeight = this.getBarHeight((range as RequestTimeRange).name); const y = this.headerHeight + (this.rowHeight * rowIndex - this.scrollTop) + ((this.rowHeight - barHeight) / 2); if (event.clientY < this.canvasPosition.top + y || event.clientY > this.canvasPosition.top + y + barHeight) { return null; } const anchorBox = this.element.boxInWindow(); anchorBox.x += start; anchorBox.y += y; anchorBox.width = end - start; anchorBox.height = barHeight; return { box: anchorBox, show: (popover: UI.GlassPane.GlassPane): Promise<true> => { const content = RequestTimingView.createTimingTable((request as SDK.NetworkRequest.NetworkRequest), this.calculator); popover.contentElement.appendChild(content); return Promise.resolve(true); }, hide: undefined, }; } private setHoveredNode(node: NetworkNode|null, highlightInitiatorChain: boolean): void { if (this.hoveredNode) { this.hoveredNode.setHovered(false, false); } this.hoveredNode = node; if (this.hoveredNode) { this.hoveredNode.setHovered(true, highlightInitiatorChain); } } private setSelectedNode(node: NetworkNode|null): boolean { if (node && node.dataGrid) { node.select(); node.dataGrid.element.focus(); return true; } return false; } setRowHeight(height: number): void { this.rawRowHeight = height; this.updateRowHeight(); } private updateRowHeight(): void { this.rowHeight = Math.round(this.rawRowHeight * window.devicePixelRatio) / window.devicePixelRatio; } setHeaderHeight(height: number): void { this.headerHeight = height; } setRightPadding(padding: number): void { this.rightPadding = padding; this.calculateCanvasSize(); } setCalculator(calculator: NetworkTimeCalculator): void { this.calculator = calculator; } getNodeFromPoint(x: number, y: number): NetworkNode|null { if (y <= this.headerHeight) { return null; } return this.nodes[Math.floor((this.scrollTop + y - this.headerHeight) / this.rowHeight)]; } scheduleDraw(): void { if (this.updateRequestID) { return; } this.updateRequestID = this.element.window().requestAnimationFrame(() => this.update()); } update(scrollTop?: number, eventDividers?: Map<string, number[]>, nodes?: NetworkNode[]): void { if (scrollTop !== undefined && this.scrollTop !== scrollTop) { this.popoverHelper.hidePopover(); this.scrollTop = scrollTop; } if (nodes) { this.nodes = nodes; this.calculateCanvasSize(); } if (eventDividers !== undefined) { this.eventDividers = eventDividers; } if (this.updateRequestID) { this.element.window().cancelAnimationFrame(this.updateRequestID); delete this.updateRequestID; } this.startTime = this.calculator.minimumBoundary(); this.endTime = this.calculator.maximumBoundary(); this.resetCanvas(); this.resetPaths(); this.textLayers = []; this.draw(); } private resetCanvas(): void { const ratio = window.devicePixelRatio; this.canvas.width = this.offsetWidth * ratio; this.canvas.height = this.offsetHeight * ratio; this.canvas.style.width = this.offsetWidth + 'px'; this.canvas.style.height = this.offsetHeight + 'px'; } onResize(): void { super.onResize(); this.updateRowHeight(); this.calculateCanvasSize(); this.scheduleDraw(); } private calculateCanvasSize(): void { this.offsetWidth = this.contentElement.offsetWidth - this.rightPadding; this.offsetHeight = this.contentElement.offsetHeight; this.calculator.setDisplayWidth(this.offsetWidth); this.canvasPosition = this.canvas.getBoundingClientRect(); } private timeToPosition(time: number): number { const availableWidth = this.offsetWidth - this.leftPadding; const timeToPixel = availableWidth / (this.endTime - this.startTime); return Math.floor(this.leftPadding + (time - this.startTime) * timeToPixel); } private didDrawForTest(): void { } private draw(): void { const useTimingBars = !Common.Settings.Settings.instance().moduleSetting('networkColorCodeResourceTypes').get() && !this.calculator.startAtZero; const nodes = this.nodes; const context = (this.canvas.getContext('2d') as CanvasRenderingContext2D | null); if (!context) { return; } context.save(); context.scale(window.devicePixelRatio, window.devicePixelRatio); context.translate(0, this.headerHeight); context.rect(0, 0, this.offsetWidth, this.offsetHeight); context.clip(); const firstRequestIndex = Math.floor(this.scrollTop / this.rowHeight); const lastRequestIndex = Math.min(nodes.length, firstRequestIndex + Math.ceil(this.offsetHeight / this.rowHeight)); for (let i = firstRequestIndex; i < lastRequestIndex; i++) { const rowOffset = this.rowHeight * i; const node = nodes[i]; this.decorateRow(context, node, rowOffset - this.scrollTop); let drawNodes: NetworkNode[] = []; if (node.hasChildren() && !node.expanded) { drawNodes = (node.flatChildren() as NetworkNode[]); } drawNodes.push(node); for (const drawNode of drawNodes) { if (useTimingBars) { this.buildTimingBarLayers(drawNode, rowOffset - this.scrollTop); } else { this.buildSimplifiedBarLayers(context, drawNode, rowOffset - this.scrollTop); } } } this.drawLayers(context, useTimingBars); context.save(); context.fillStyle = ThemeSupport.ThemeSupport.instance().patchColorText('#888', ThemeSupport.ThemeSupport.ColorUsage.Foreground); for (const textData of this.textLayers) { context.fillText(textData.text, textData.x, textData.y); } context.restore(); this.drawEventDividers(context); context.restore(); const freeZoneAtLeft = 75; const freeZoneAtRight = 18; const dividersData = PerfUI.TimelineGrid.TimelineGrid.calculateGridOffsets(this.calculator); PerfUI.TimelineGrid.TimelineGrid.drawCanvasGrid(context, dividersData); PerfUI.TimelineGrid.TimelineGrid.drawCanvasHeaders( context, dividersData, time => this.calculator.formatValue(time, dividersData.precision), this.fontSize, this.headerHeight, freeZoneAtLeft); context.save(); context.scale(window.devicePixelRatio, window.devicePixelRatio); context.clearRect(this.offsetWidth - freeZoneAtRight, 0, freeZoneAtRight, this.headerHeight); context.restore(); this.didDrawForTest(); } private drawLayers(context: CanvasRenderingContext2D, useTimingBars: boolean): void { for (const entry of this.pathForStyle) { const style = (entry[0] as _LayerStyle); const path = (entry[1] as Path2D); context.save(); context.beginPath(); if (style.lineWidth) { context.lineWidth = style.lineWidth; if (style.borderColor) { context.strokeStyle = style.borderColor; } context.stroke(path); } if (style.fillStyle) { context.fillStyle = useTimingBars ? ThemeSupport.ThemeSupport.instance().getComputedValue(style.fillStyle) : style.fillStyle; context.fill(path); } context.restore(); } } private drawEventDividers(context: CanvasRenderingContext2D): void { context.save(); context.lineWidth = 1; for (const color of this.eventDividers.keys()) { context.strokeStyle = color; for (const time of this.eventDividers.get(color) || []) { context.beginPath(); const x = this.timeToPosition(time); context.moveTo(x, 0); context.lineTo(x, this.offsetHeight); } context.stroke(); } context.restore(); } private getBarHeight(type?: RequestTimeRangeNames): number { const types = RequestTimeRangeNames; switch (type) { case types.Connecting: case types.SSL: case types.DNS: case types.Proxy: case types.Blocking: case types.Push: case types.Queueing: return 7; default: return 13; } } private getSimplifiedBarRange(request: SDK.NetworkRequest.NetworkRequest, borderOffset: number): { start: number, mid: number, end: number, } { const drawWidth = this.offsetWidth - this.leftPadding; const percentages = this.calculator.computeBarGraphPercentages(request); return { start: this.leftPadding + Math.floor((percentages.start / 100) * drawWidth) + borderOffset, mid: this.leftPadding + Math.floor((percentages.middle / 100) * drawWidth) + borderOffset, end: this.leftPadding + Math.floor((percentages.end / 100) * drawWidth) + borderOffset, }; } private buildSimplifiedBarLayers(context: CanvasRenderingContext2D, node: NetworkNode, y: number): void { const request = node.request(); if (!request) { return; } const borderWidth = 1; const borderOffset = borderWidth % 2 === 0 ? 0 : 0.5; const ranges = this.getSimplifiedBarRange(request, borderOffset); const height = this.getBarHeight(); y += Math.floor(this.rowHeight / 2 - height / 2 + borderWidth) - borderWidth / 2; const waitingStyle = (this.styleForWaitingResourceType.get(request.resourceType()) as _LayerStyle); const waitingPath = (this.pathForStyle.get(waitingStyle) as Path2D); waitingPath.rect(ranges.start, y, ranges.mid - ranges.start, height - borderWidth); const barWidth = Math.max(2, ranges.end - ranges.mid); const downloadingStyle = (this.styleForDownloadingResourceType.get(request.resourceType()) as _LayerStyle); const downloadingPath = (this.pathForStyle.get(downloadingStyle) as Path2D); downloadingPath.rect(ranges.mid, y, barWidth, height - borderWidth); let labels: Label|null = null; if (node.hovered()) { labels = this.calculator.computeBarGraphLabels(request); const barDotLineLength = 10; const leftLabelWidth = context.measureText(labels.left).width; const rightLabelWidth = context.measureText(labels.right).width; const hoverLinePath = (this.pathForStyle.get(this.hoverDetailsStyle) as Path2D); if (leftLabelWidth < ranges.mid - ranges.start) { const midBarX = ranges.start + (ranges.mid - ranges.start - leftLabelWidth) / 2; this.textLayers.push({text: labels.left, x: midBarX, y: y + this.fontSize}); } else if (barDotLineLength + leftLabelWidth + this.leftPadding < ranges.start) { this.textLayers.push( {text: labels.left, x: ranges.start - leftLabelWidth - barDotLineLength - 1, y: y + this.fontSize}); hoverLinePath.moveTo(ranges.start - barDotLineLength, y + Math.floor(height / 2)); hoverLinePath.arc(ranges.start, y + Math.floor(height / 2), 2, 0, 2 * Math.PI); hoverLinePath.moveTo(ranges.start - barDotLineLength, y + Math.floor(height / 2)); hoverLinePath.lineTo(ranges.start, y + Math.floor(height / 2)); } const endX = ranges.mid + barWidth + borderOffset; if (rightLabelWidth < endX - ranges.mid) { const midBarX = ranges.mid + (endX - ranges.mid - rightLabelWidth) / 2; this.textLayers.push({text: labels.right, x: midBarX, y: y + this.fontSize}); } else if (endX + barDotLineLength + rightLabelWidth < this.offsetWidth - this.leftPadding) { this.textLayers.push({text: labels.right, x: endX + barDotLineLength + 1, y: y + this.fontSize}); hoverLinePath.moveTo(endX, y + Math.floor(height / 2)); hoverLinePath.arc(endX, y + Math.floor(height / 2), 2, 0, 2 * Math.PI); hoverLinePath.moveTo(endX, y + Math.floor(height / 2)); hoverLinePath.lineTo(endX + barDotLineLength, y + Math.floor(height / 2)); } } if (!this.calculator.startAtZero) { const queueingRange = (RequestTimingView.calculateRequestTimeRanges(request, 0) .find(data => data.name === RequestTimeRangeNames.Total) as RequestTimeRange); const leftLabelWidth = labels ? context.measureText(labels.left).width : 0; const leftTextPlacedInBar = leftLabelWidth < ranges.mid - ranges.start; const wiskerTextPadding = 13; const textOffset = (labels && !leftTextPlacedInBar) ? leftLabelWidth + wiskerTextPadding : 0; const queueingStart = this.timeToPosition(queueingRange.start); if (ranges.start - textOffset > queueingStart) { const wiskerPath = (this.pathForStyle.get(this.wiskerStyle) as Path2D); wiskerPath.moveTo(queueingStart, y + Math.floor(height / 2)); wiskerPath.lineTo(ranges.start - textOffset, y + Math.floor(height / 2)); // TODO(allada) This needs to be floored. const wiskerHeight = height / 2; wiskerPath.moveTo(queueingStart + borderOffset, y + wiskerHeight / 2); wiskerPath.lineTo(queueingStart + borderOffset, y + height - wiskerHeight / 2 - 1); } } } private buildTimingBarLayers(node: NetworkNode, y: number): void { const request = node.request(); if (!request) { return; } const ranges = RequestTimingView.calculateRequestTimeRanges(request, 0); let index = 0; for (const range of ranges) { if (range.name === RequestTimeRangeNames.Total || range.name === RequestTimeRangeNames.Sending || range.end - range.start === 0) { continue; } const style = (this.styleForTimeRangeName.get(range.name) as _LayerStyle); const path = (this.pathForStyle.get(style) as Path2D); const lineWidth = style.lineWidth || 0; const height = this.getBarHeight(range.name); const middleBarY = y + Math.floor(this.rowHeight / 2 - height / 2) + lineWidth / 2; const start = this.timeToPosition(range.start); const end = this.timeToPosition(range.end); path.rect(start + (index * BAR_SPACING), middleBarY, end - start, height - lineWidth); index++; } } private decorateRow(context: CanvasRenderingContext2D, node: NetworkNode, y: number): void { const nodeBgColorId = node.backgroundColor(); context.save(); context.beginPath(); context.fillStyle = ThemeSupport.ThemeSupport.instance().getComputedValue(nodeBgColorId); context.rect(0, y, this.offsetWidth, this.rowHeight); context.fill(); context.restore(); } } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/naming-convention export interface _TextLayer { x: number; y: number; text: string; } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/naming-convention export interface _LayerStyle { fillStyle?: string; lineWidth?: number; borderColor?: string; }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/interactionsMappers"; import * as Parameters from "../models/parameters"; import { CustomerInsightsManagementClientContext } from "../customerInsightsManagementClientContext"; /** Class representing a Interactions. */ export class Interactions { private readonly client: CustomerInsightsManagementClientContext; /** * Create a Interactions. * @param {CustomerInsightsManagementClientContext} client Reference to the service client. */ constructor(client: CustomerInsightsManagementClientContext) { this.client = client; } /** * Creates an interaction or updates an existing interaction within a hub. * @param resourceGroupName The name of the resource group. * @param hubName The name of the hub. * @param interactionName The name of the interaction. * @param parameters Parameters supplied to the CreateOrUpdate Interaction operation. * @param [options] The optional parameters * @returns Promise<Models.InteractionsCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, hubName: string, interactionName: string, parameters: Models.InteractionResourceFormat, options?: msRest.RequestOptionsBase): Promise<Models.InteractionsCreateOrUpdateResponse> { return this.beginCreateOrUpdate(resourceGroupName,hubName,interactionName,parameters,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.InteractionsCreateOrUpdateResponse>; } /** * Gets information about the specified interaction. * @param resourceGroupName The name of the resource group. * @param hubName The name of the hub. * @param interactionName The name of the interaction. * @param [options] The optional parameters * @returns Promise<Models.InteractionsGetResponse> */ get(resourceGroupName: string, hubName: string, interactionName: string, options?: Models.InteractionsGetOptionalParams): Promise<Models.InteractionsGetResponse>; /** * @param resourceGroupName The name of the resource group. * @param hubName The name of the hub. * @param interactionName The name of the interaction. * @param callback The callback */ get(resourceGroupName: string, hubName: string, interactionName: string, callback: msRest.ServiceCallback<Models.InteractionResourceFormat>): void; /** * @param resourceGroupName The name of the resource group. * @param hubName The name of the hub. * @param interactionName The name of the interaction. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, hubName: string, interactionName: string, options: Models.InteractionsGetOptionalParams, callback: msRest.ServiceCallback<Models.InteractionResourceFormat>): void; get(resourceGroupName: string, hubName: string, interactionName: string, options?: Models.InteractionsGetOptionalParams | msRest.ServiceCallback<Models.InteractionResourceFormat>, callback?: msRest.ServiceCallback<Models.InteractionResourceFormat>): Promise<Models.InteractionsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, hubName, interactionName, options }, getOperationSpec, callback) as Promise<Models.InteractionsGetResponse>; } /** * Gets all interactions in the hub. * @param resourceGroupName The name of the resource group. * @param hubName The name of the hub. * @param [options] The optional parameters * @returns Promise<Models.InteractionsListByHubResponse> */ listByHub(resourceGroupName: string, hubName: string, options?: Models.InteractionsListByHubOptionalParams): Promise<Models.InteractionsListByHubResponse>; /** * @param resourceGroupName The name of the resource group. * @param hubName The name of the hub. * @param callback The callback */ listByHub(resourceGroupName: string, hubName: string, callback: msRest.ServiceCallback<Models.InteractionListResult>): void; /** * @param resourceGroupName The name of the resource group. * @param hubName The name of the hub. * @param options The optional parameters * @param callback The callback */ listByHub(resourceGroupName: string, hubName: string, options: Models.InteractionsListByHubOptionalParams, callback: msRest.ServiceCallback<Models.InteractionListResult>): void; listByHub(resourceGroupName: string, hubName: string, options?: Models.InteractionsListByHubOptionalParams | msRest.ServiceCallback<Models.InteractionListResult>, callback?: msRest.ServiceCallback<Models.InteractionListResult>): Promise<Models.InteractionsListByHubResponse> { return this.client.sendOperationRequest( { resourceGroupName, hubName, options }, listByHubOperationSpec, callback) as Promise<Models.InteractionsListByHubResponse>; } /** * Suggests relationships to create relationship links. * @param resourceGroupName The name of the resource group. * @param hubName The name of the hub. * @param interactionName The name of the interaction. * @param [options] The optional parameters * @returns Promise<Models.InteractionsSuggestRelationshipLinksResponse> */ suggestRelationshipLinks(resourceGroupName: string, hubName: string, interactionName: string, options?: msRest.RequestOptionsBase): Promise<Models.InteractionsSuggestRelationshipLinksResponse>; /** * @param resourceGroupName The name of the resource group. * @param hubName The name of the hub. * @param interactionName The name of the interaction. * @param callback The callback */ suggestRelationshipLinks(resourceGroupName: string, hubName: string, interactionName: string, callback: msRest.ServiceCallback<Models.SuggestRelationshipLinksResponse>): void; /** * @param resourceGroupName The name of the resource group. * @param hubName The name of the hub. * @param interactionName The name of the interaction. * @param options The optional parameters * @param callback The callback */ suggestRelationshipLinks(resourceGroupName: string, hubName: string, interactionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SuggestRelationshipLinksResponse>): void; suggestRelationshipLinks(resourceGroupName: string, hubName: string, interactionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SuggestRelationshipLinksResponse>, callback?: msRest.ServiceCallback<Models.SuggestRelationshipLinksResponse>): Promise<Models.InteractionsSuggestRelationshipLinksResponse> { return this.client.sendOperationRequest( { resourceGroupName, hubName, interactionName, options }, suggestRelationshipLinksOperationSpec, callback) as Promise<Models.InteractionsSuggestRelationshipLinksResponse>; } /** * Creates an interaction or updates an existing interaction within a hub. * @param resourceGroupName The name of the resource group. * @param hubName The name of the hub. * @param interactionName The name of the interaction. * @param parameters Parameters supplied to the CreateOrUpdate Interaction operation. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(resourceGroupName: string, hubName: string, interactionName: string, parameters: Models.InteractionResourceFormat, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, hubName, interactionName, parameters, options }, beginCreateOrUpdateOperationSpec, options); } /** * Gets all interactions in the hub. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.InteractionsListByHubNextResponse> */ listByHubNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.InteractionsListByHubNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByHubNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.InteractionListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByHubNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.InteractionListResult>): void; listByHubNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.InteractionListResult>, callback?: msRest.ServiceCallback<Models.InteractionListResult>): Promise<Models.InteractionsListByHubNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByHubNextOperationSpec, callback) as Promise<Models.InteractionsListByHubNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/interactions/{interactionName}", urlParameters: [ Parameters.resourceGroupName, Parameters.hubName1, Parameters.interactionName1, Parameters.subscriptionId ], queryParameters: [ Parameters.localeCode, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.InteractionResourceFormat }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByHubOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/interactions", urlParameters: [ Parameters.resourceGroupName, Parameters.hubName1, Parameters.subscriptionId ], queryParameters: [ Parameters.localeCode, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.InteractionListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const suggestRelationshipLinksOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/interactions/{interactionName}/suggestRelationshipLinks", urlParameters: [ Parameters.resourceGroupName, Parameters.hubName1, Parameters.interactionName1, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SuggestRelationshipLinksResponse }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/interactions/{interactionName}", urlParameters: [ Parameters.resourceGroupName, Parameters.hubName1, Parameters.interactionName0, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.InteractionResourceFormat, required: true } }, responses: { 200: { bodyMapper: Mappers.InteractionResourceFormat }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByHubNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.InteractionListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import R from 'ramda'; import yn from 'yn'; import pMapSeries from 'p-map-series'; import * as path from 'path'; import fs from 'fs-extra'; import { Consumer, loadConsumer } from '../../../consumer'; import ComponentsList from '../../../consumer/component/components-list'; import loader from '../../../cli/loader'; import HooksManager from '../../../hooks'; import { BEFORE_EXPORT, BEFORE_EXPORTS, BEFORE_LOADING_COMPONENTS } from '../../../cli/loader/loader-messages'; import { BitId, BitIds } from '../../../bit-id'; import IdExportedAlready from './exceptions/id-exported-already'; import logger from '../../../logger/logger'; import { Analytics } from '../../../analytics/analytics'; import EjectComponents from '../../../consumer/component-ops/eject-components'; import { EjectResults } from '../../../consumer/component-ops/eject-components'; import hasWildcard from '../../../utils/string/has-wildcard'; import { exportMany } from '../../../scope/component-ops/export-scope-components'; import { NodeModuleLinker } from '../../../links'; import BitMap from '../../../consumer/bit-map/bit-map'; import GeneralError from '../../../error/general-error'; import { COMPONENT_ORIGINS, PRE_EXPORT_HOOK, POST_EXPORT_HOOK, DEFAULT_BINDINGS_PREFIX } from '../../../constants'; import ManyComponentsWriter from '../../../consumer/component-ops/many-components-writer'; import * as packageJsonUtils from '../../../consumer/component/package-json-utils'; import { forkComponentsPrompt } from '../../../prompts'; const HooksManagerInstance = HooksManager.getInstance(); export default (async function exportAction(params: { ids: string[]; remote: string | null | undefined; eject: boolean; includeDependencies: boolean; setCurrentScope: boolean; allVersions: boolean; includeNonStaged: boolean; codemod: boolean; force: boolean; }) { HooksManagerInstance.triggerHook(PRE_EXPORT_HOOK, params); const { updatedIds, nonExistOnBitMap, missingScope, exported } = await exportComponents(params); let ejectResults; if (params.eject) ejectResults = await ejectExportedComponents(updatedIds); const exportResults = { componentsIds: exported, nonExistOnBitMap, missingScope, ejectResults }; HooksManagerInstance.triggerHook(POST_EXPORT_HOOK, exportResults); return exportResults; }); async function exportComponents({ ids, remote, includeDependencies, setCurrentScope, includeNonStaged, codemod, allVersions, force }: { ids: string[]; remote: string | null | undefined; includeDependencies: boolean; setCurrentScope: boolean; includeNonStaged: boolean; codemod: boolean; allVersions: boolean; force: boolean; }): Promise<{ updatedIds: BitId[]; nonExistOnBitMap: BitId[]; missingScope: BitId[]; exported: BitId[] }> { const consumer: Consumer = await loadConsumer(); const { idsToExport, missingScope, idsWithFutureScope } = await getComponentsToExport( ids, consumer, remote, includeNonStaged, force ); if (R.isEmpty(idsToExport)) return { updatedIds: [], nonExistOnBitMap: [], missingScope, exported: [] }; if (codemod) _throwForModified(consumer, idsToExport); const { exported, updatedLocally } = await exportMany({ scope: consumer.scope, ids: idsToExport, remoteName: remote, includeDependencies, changeLocallyAlthoughRemoteIsDifferent: setCurrentScope, codemod, allVersions, idsWithFutureScope }); const { updatedIds, nonExistOnBitMap } = _updateIdsOnBitMap(consumer.bitMap, updatedLocally); await linkComponents(updatedIds, consumer); Analytics.setExtraData('num_components', exported.length); if (codemod) { await reImportComponents(consumer, updatedIds); await cleanOldComponents(consumer, BitIds.fromArray(updatedIds), idsToExport); } // it is important to have consumer.onDestroy() before running the eject operation, we want the // export and eject operations to function independently. we don't want to lose the changes to // .bitmap file done by the export action in case the eject action has failed. await consumer.onDestroy(); return { updatedIds, nonExistOnBitMap, missingScope, exported }; } function _updateIdsOnBitMap(bitMap: BitMap, componentsIds: BitIds): { updatedIds: BitId[]; nonExistOnBitMap: BitIds } { const updatedIds = []; const nonExistOnBitMap = new BitIds(); componentsIds.forEach(componentsId => { const resultId = bitMap.updateComponentId(componentsId, true); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! if (resultId.hasVersion()) updatedIds.push(resultId); else nonExistOnBitMap.push(resultId); }); return { updatedIds, nonExistOnBitMap }; } async function getComponentsToExport( ids: string[], consumer: Consumer, remote: string | null | undefined, includeNonStaged: boolean, force: boolean ): Promise<{ idsToExport: BitIds; missingScope: BitId[]; idsWithFutureScope: BitIds }> { const componentsList = new ComponentsList(consumer); const idsHaveWildcard = hasWildcard(ids); const filterNonScopeIfNeeded = ( bitIds: BitIds ): { idsToExport: BitIds; missingScope: BitId[]; idsWithFutureScope: BitIds } => { const idsWithFutureScope = getIdsWithFutureScope(bitIds, consumer, remote); if (remote) return { idsToExport: bitIds, missingScope: [], idsWithFutureScope }; const [idsToExport, missingScope] = R.partition(id => { const idWithFutureScope = idsWithFutureScope.searchWithoutScopeAndVersion(id); if (!idWithFutureScope) throw new Error(`idsWithFutureScope is missing ${id.toString()}`); return idWithFutureScope.hasScope(); }, bitIds); return { idsToExport: BitIds.fromArray(idsToExport), missingScope, idsWithFutureScope }; }; const promptForFork = async (bitIds: BitIds | BitId[]) => { if (force || !remote) return; const idsToFork = bitIds.filter(id => id.scope && id.scope !== remote); if (!idsToFork.length) return; const forkPromptResult = await forkComponentsPrompt(idsToFork, remote)(); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! if (!yn(forkPromptResult.shouldFork)) { throw new GeneralError('the operation has been canceled'); } }; if (!ids.length || idsHaveWildcard) { loader.start(BEFORE_LOADING_COMPONENTS); const exportPendingComponents: BitIds = includeNonStaged ? await componentsList.listNonNewComponentsIds() : await componentsList.listExportPendingComponentsIds(); const componentsToExport = idsHaveWildcard ? ComponentsList.filterComponentsByWildcard(exportPendingComponents, ids) : exportPendingComponents; await promptForFork(componentsToExport); const loaderMsg = componentsToExport.length > 1 ? BEFORE_EXPORTS : BEFORE_EXPORT; loader.start(loaderMsg); return filterNonScopeIfNeeded(componentsToExport); } loader.start(BEFORE_EXPORT); // show single export const parsedIds = await Promise.all(ids.map(id => getParsedId(consumer, id))); const statuses = await consumer.getManyComponentsStatuses(parsedIds); statuses.forEach(({ id, status }) => { if (status.nested) { throw new GeneralError( `unable to export "${id.toString()}", the component is not fully available. please use "bit import" first` ); } // don't allow to re-export an exported component unless it's being exported to another scope if (remote && !status.staged && id.scope === remote) { throw new IdExportedAlready(id.toString(), remote); } }); await promptForFork(parsedIds); return filterNonScopeIfNeeded(BitIds.fromArray(parsedIds)); } function getIdsWithFutureScope(ids: BitIds, consumer: Consumer, remote?: string | null): BitIds { const workspaceDefaultScope = consumer.config.defaultScope; let workspaceDefaultOwner = consumer.config.defaultOwner; // For backward computability don't treat the default binding prefix as real owner if (workspaceDefaultOwner === DEFAULT_BINDINGS_PREFIX) { workspaceDefaultOwner = undefined; } const idsArray = ids.map(id => { if (remote) return id.changeScope(remote); if (id.hasScope()) return id; const overrides = consumer.config.getComponentConfig(id); const componentDefaultScope = overrides ? overrides.defaultScope : null; // TODO: handle separation of owner from default scope on component // TODO: handle owner of component let finalScope = componentDefaultScope || workspaceDefaultScope; if (workspaceDefaultScope && workspaceDefaultOwner && !componentDefaultScope) { finalScope = `${workspaceDefaultOwner}.${workspaceDefaultScope}`; } return id.changeScope(finalScope); }); return BitIds.fromArray(idsArray); } async function getParsedId(consumer: Consumer, id: string): Promise<BitId> { // reason why not calling `consumer.getParsedId()` first is because a component might not be on // .bitmap and only in the scope. we support this case and enable to export const parsedId: BitId = await consumer.scope.getParsedId(id); if (parsedId.hasScope()) return parsedId; // parsing id from the scope, doesn't provide the scope-name in case it's missing, in this case // get the id including the scope from the consumer. try { return consumer.getParsedId(id); } catch (err) { // not in the consumer, just return the one parsed without the scope name return parsedId; } } async function linkComponents(ids: BitId[], consumer: Consumer): Promise<void> { // we don't have much of a choice here, we have to load all the exported components in order to link them // some of the components might be authored, some might be imported. // when a component has dists, we need the consumer-component object to retrieve the dists info. const components = await Promise.all(ids.map(id => consumer.loadComponentFromModel(id))); const nodeModuleLinker = new NodeModuleLinker(components, consumer, consumer.bitMap); await nodeModuleLinker.link(); } async function ejectExportedComponents(componentsIds): Promise<EjectResults> { const consumer: Consumer = await loadConsumer(undefined, true); let ejectResults: EjectResults; try { const ejectComponents = new EjectComponents(consumer, componentsIds); ejectResults = await ejectComponents.eject(); } catch (err) { const ejectErr = `The components ${componentsIds.map(c => c.toString()).join(', ')} were exported successfully. However, the eject operation has failed due to an error: ${err.msg || err}`; logger.error(ejectErr, err); throw new Error(ejectErr); } // run the consumer.onDestroy() again, to write the changes done by the eject action to .bitmap await consumer.onDestroy(); return ejectResults; } async function reImportComponents(consumer: Consumer, ids: BitId[]) { await pMapSeries(ids, id => reImportComponent(consumer, id)); } async function reImportComponent(consumer: Consumer, id: BitId) { const componentWithDependencies = await consumer.loadComponentWithDependenciesFromModel(id); const componentMap = consumer.bitMap.getComponent(id); const rootDir = componentMap.rootDir; const shouldWritePackageJson = async (): Promise<boolean> => { if (!rootDir) return false; const packageJsonPath = path.join(consumer.getPath(), rootDir, 'package.json'); return fs.pathExists(packageJsonPath); }; const shouldInstallNpmPackages = (): boolean => { return componentMap.origin !== COMPONENT_ORIGINS.AUTHORED; }; const writePackageJson = await shouldWritePackageJson(); const shouldDependenciesSaveAsComponents = await consumer.shouldDependenciesSavedAsComponents([id]); componentWithDependencies.component.dependenciesSavedAsComponents = shouldDependenciesSaveAsComponents[0].saveDependenciesAsComponents; const manyComponentsWriter = new ManyComponentsWriter({ consumer, componentsWithDependencies: [componentWithDependencies], installNpmPackages: shouldInstallNpmPackages(), override: true, writePackageJson }); await manyComponentsWriter.writeAll(); } /** * remove the components with the old scope from package.json and from node_modules */ async function cleanOldComponents(consumer: Consumer, updatedIds: BitIds, idsToExport: BitIds) { const idsToClean = idsToExport.filter(id => updatedIds.hasWithoutScopeAndVersion(id)); await packageJsonUtils.removeComponentsFromWorkspacesAndDependencies(consumer, BitIds.fromArray(idsToClean)); } async function _throwForModified(consumer: Consumer, ids: BitIds) { const statuses = await consumer.getManyComponentsStatuses(ids); statuses.forEach(({ id, status }) => { if (status.modified) { throw new GeneralError( `unable to perform rewire on "${id.toString()}" because it is modified, please tag or discard your changes before re-trying` ); } }); }
the_stack
process.env.AWS_ACCESS_KEY_ID = 'testing'; process.env.AWS_SECRET_ACCESS_KEY = 'testing'; import 'mocha'; import { AwsInstrumentation, NormalizedRequest, NormalizedResponse } from '../src'; import { ReadableSpan, Span } from '@opentelemetry/sdk-trace-base'; import { context, SpanStatusCode, trace } from '@opentelemetry/api'; import { MessagingDestinationKindValues, MessagingOperationValues, SemanticAttributes, } from '@opentelemetry/semantic-conventions'; import { AttributeNames } from '../src/enums'; import expect from 'expect'; import * as fs from 'fs'; import { getTestSpans } from 'opentelemetry-instrumentation-testing-utils'; const region = 'us-east-1'; const instrumentation = new AwsInstrumentation(); instrumentation.enable(); import { PutObjectCommand, PutObjectCommandOutput, S3, S3Client } from '@aws-sdk/client-s3'; import { SQS } from '@aws-sdk/client-sqs'; instrumentation.disable(); import nock from 'nock'; describe('instrumentation-aws-sdk-v3', () => { const s3Client = new S3({ region }); beforeEach(() => { instrumentation.enable(); }); afterEach(() => { instrumentation.disable(); }); describe('functional', () => { it('promise await', async () => { nock(`https://ot-demo-test.s3.${region}.amazonaws.com/`) .put('/aws-ot-s3-test-object.txt?x-id=PutObject') .reply(200, fs.readFileSync('./test/mock-responses/s3-put-object.xml', 'utf8')); const params = { Bucket: 'ot-demo-test', Key: 'aws-ot-s3-test-object.txt' }; const awsRes = await s3Client.putObject(params); expect(getTestSpans().length).toBe(1); const [span] = getTestSpans(); expect(span.attributes[SemanticAttributes.RPC_SYSTEM]).toEqual('aws-api'); expect(span.attributes[SemanticAttributes.RPC_METHOD]).toEqual('PutObject'); expect(span.attributes[SemanticAttributes.RPC_SERVICE]).toEqual('S3'); expect(span.attributes[AttributeNames.AWS_REGION]).toEqual(region); expect(span.name).toEqual('S3.PutObject'); }); it('callback interface', (done) => { nock(`https://ot-demo-test.s3.${region}.amazonaws.com/`) .put('/aws-ot-s3-test-object.txt?x-id=PutObject') .reply(200, fs.readFileSync('./test/mock-responses/s3-put-object.xml', 'utf8')); const params = { Bucket: 'ot-demo-test', Key: 'aws-ot-s3-test-object.txt' }; s3Client.putObject(params, (err: any, data?: PutObjectCommandOutput) => { expect(getTestSpans().length).toBe(1); const [span] = getTestSpans(); expect(span.attributes[SemanticAttributes.RPC_SYSTEM]).toEqual('aws-api'); expect(span.attributes[SemanticAttributes.RPC_METHOD]).toEqual('PutObject'); expect(span.attributes[SemanticAttributes.RPC_SERVICE]).toEqual('S3'); expect(span.attributes[AttributeNames.AWS_REGION]).toEqual(region); expect(span.name).toEqual('S3.PutObject'); done(); }); }); it('use the sdk client style to perform operation', async () => { nock(`https://ot-demo-test.s3.${region}.amazonaws.com/`) .put('/aws-ot-s3-test-object.txt?x-id=PutObject') .reply(200, fs.readFileSync('./test/mock-responses/s3-put-object.xml', 'utf8')); const params = { Bucket: 'ot-demo-test', Key: 'aws-ot-s3-test-object.txt' }; const client = new S3Client({ region }); await client.send(new PutObjectCommand(params)); expect(getTestSpans().length).toBe(1); const [span] = getTestSpans(); expect(span.attributes[SemanticAttributes.RPC_SYSTEM]).toEqual('aws-api'); expect(span.attributes[SemanticAttributes.RPC_METHOD]).toEqual('PutObject'); expect(span.attributes[SemanticAttributes.RPC_SERVICE]).toEqual('S3'); expect(span.attributes[AttributeNames.AWS_REGION]).toEqual(region); expect(span.name).toEqual('S3.PutObject'); }); it('aws error', async () => { nock(`https://invalid-bucket-name.s3.${region}.amazonaws.com/`) .put('/aws-ot-s3-test-object.txt?x-id=PutObject') .reply(403, fs.readFileSync('./test/mock-responses/invalid-bucket.xml', 'utf8')); const params = { Bucket: 'invalid-bucket-name', Key: 'aws-ot-s3-test-object.txt' }; try { await s3Client.putObject(params); } catch { expect(getTestSpans().length).toBe(1); const [span] = getTestSpans(); // expect error attributes expect(span.status.code).toEqual(SpanStatusCode.ERROR); expect(span.status.message).toEqual('Access Denied'); expect(span.events.length).toBe(1); expect(span.events[0].name).toEqual('exception'); expect(span.attributes[SemanticAttributes.RPC_SYSTEM]).toEqual('aws-api'); expect(span.attributes[SemanticAttributes.RPC_METHOD]).toEqual('PutObject'); expect(span.attributes[SemanticAttributes.RPC_SERVICE]).toEqual('S3'); expect(span.attributes[AttributeNames.AWS_REGION]).toEqual(region); expect(span.attributes[AttributeNames.AWS_REQUEST_ID]).toEqual('MS95GTS7KXQ34X2S'); expect(span.name).toEqual('S3.PutObject'); } }); }); describe('instrumentation config', () => { describe('hooks', () => { it('verify request and response hooks are called with right params', async () => { instrumentation.disable(); instrumentation.setConfig({ preRequestHook: (span: Span, request: NormalizedRequest) => { span.setAttribute('attribute.from.request.hook', request.commandInput.Bucket); }, responseHook: (span: Span, response: NormalizedResponse) => { span.setAttribute('attribute.from.response.hook', 'data from response hook'); }, suppressInternalInstrumentation: true, }); instrumentation.enable(); nock(`https://ot-demo-test.s3.${region}.amazonaws.com/`) .put('/aws-ot-s3-test-object.txt?x-id=PutObject') .reply(200, fs.readFileSync('./test/mock-responses/s3-put-object.xml', 'utf8')); const params = { Bucket: 'ot-demo-test', Key: 'aws-ot-s3-test-object.txt' }; const awsRes = await s3Client.putObject(params); expect(getTestSpans().length).toBe(1); const [span] = getTestSpans(); expect(span.attributes['attribute.from.request.hook']).toEqual(params.Bucket); expect(span.attributes['attribute.from.response.hook']).toEqual('data from response hook'); }); it('handle throw in request and response hooks', async () => { instrumentation.disable(); instrumentation.setConfig({ preRequestHook: (span: Span, request: NormalizedRequest) => { span.setAttribute('attribute.from.request.hook', request.commandInput.Bucket); throw new Error('error from request hook in unittests'); }, responseHook: (span: Span, response: NormalizedResponse) => { throw new Error('error from response hook in unittests'); }, suppressInternalInstrumentation: true, }); instrumentation.enable(); nock(`https://ot-demo-test.s3.${region}.amazonaws.com/`) .put('/aws-ot-s3-test-object.txt?x-id=PutObject') .reply(200, fs.readFileSync('./test/mock-responses/s3-put-object.xml', 'utf8')); const params = { Bucket: 'ot-demo-test', Key: 'aws-ot-s3-test-object.txt' }; const awsRes = await s3Client.putObject(params); expect(getTestSpans().length).toBe(1); const [span] = getTestSpans(); expect(span.attributes['attribute.from.request.hook']).toEqual(params.Bucket); }); }); describe('moduleVersionAttributeName', () => { it('setting moduleVersionAttributeName is adding module version', async () => { instrumentation.disable(); instrumentation.setConfig({ moduleVersionAttributeName: 'module.version', suppressInternalInstrumentation: true, }); instrumentation.enable(); nock(`https://ot-demo-test.s3.${region}.amazonaws.com/`) .put('/aws-ot-s3-test-object.txt?x-id=PutObject') .reply(200, fs.readFileSync('./test/mock-responses/s3-put-object.xml', 'utf8')); const params = { Bucket: 'ot-demo-test', Key: 'aws-ot-s3-test-object.txt' }; const awsRes = await s3Client.putObject(params); expect(getTestSpans().length).toBe(1); const [span] = getTestSpans(); expect(span.attributes['module.version']).toMatch(/3.\d{1,4}\.\d{1,5}.*/); }); }); }); describe('custom service behavior', () => { describe('SQS', () => { const sqsClient = new SQS({ region }); it('sqs send add messaging attributes', async () => { nock(`https://sqs.${region}.amazonaws.com/`) .post('/') .reply(200, fs.readFileSync('./test/mock-responses/sqs-send.xml', 'utf8')); const params = { QueueUrl: 'https://sqs.us-east-1.amazonaws.com/731241200085/otel-demo-aws-sdk', MessageBody: 'payload example from v3 without batch', }; const awsRes = await sqsClient.sendMessage(params); expect(getTestSpans().length).toBe(1); const [span] = getTestSpans(); // make sure we have the general aws attributes: expect(span.attributes[SemanticAttributes.RPC_SYSTEM]).toEqual('aws-api'); expect(span.attributes[SemanticAttributes.RPC_METHOD]).toEqual('SendMessage'); expect(span.attributes[SemanticAttributes.RPC_SERVICE]).toEqual('SQS'); expect(span.attributes[AttributeNames.AWS_REGION]).toEqual(region); // custom messaging attributes expect(span.attributes[SemanticAttributes.MESSAGING_SYSTEM]).toEqual('aws.sqs'); expect(span.attributes[SemanticAttributes.MESSAGING_DESTINATION_KIND]).toEqual( MessagingDestinationKindValues.QUEUE ); expect(span.attributes[SemanticAttributes.MESSAGING_DESTINATION]).toEqual('otel-demo-aws-sdk'); expect(span.attributes[SemanticAttributes.MESSAGING_URL]).toEqual(params.QueueUrl); }); it('sqs receive add messaging attributes and context', (done) => { nock(`https://sqs.${region}.amazonaws.com/`) .post('/') .reply(200, fs.readFileSync('./test/mock-responses/sqs-receive.xml', 'utf8')); const params = { QueueUrl: 'https://sqs.us-east-1.amazonaws.com/731241200085/otel-demo-aws-sdk', MaxNumberOfMessages: 3, }; sqsClient.receiveMessage(params).then((res) => { expect(getTestSpans().length).toBe(1); const [span] = getTestSpans(); // make sure we have the general aws attributes: expect(span.attributes[SemanticAttributes.RPC_SYSTEM]).toEqual('aws-api'); expect(span.attributes[SemanticAttributes.RPC_METHOD]).toEqual('ReceiveMessage'); expect(span.attributes[SemanticAttributes.RPC_SERVICE]).toEqual('SQS'); expect(span.attributes[AttributeNames.AWS_REGION]).toEqual(region); const receiveCallbackSpan = trace.getSpan(context.active()); expect(receiveCallbackSpan).toBeDefined(); const attributes = (receiveCallbackSpan as unknown as ReadableSpan).attributes; expect(attributes[SemanticAttributes.MESSAGING_OPERATION]).toMatch( MessagingOperationValues.RECEIVE ); done(); }); }); }); }); });
the_stack
import { ScrollBar } from './scrollbar'; import { Chart } from '../../chart/chart'; import { RectOption, CircleOption } from '../utils/helper'; import { PathOption, Rect, SvgRenderer } from '@syncfusion/ej2-svg-base'; import { IScrollbarThemeStyle } from '../../chart/index'; // eslint-disable-next-line jsdoc/require-param /** * Create scrollbar svg. * * @returns {void} */ export function createScrollSvg(scrollbar: ScrollBar, renderer: SvgRenderer): void { const rect: Rect = scrollbar.axis.rect; const isHorizontalAxis: boolean = scrollbar.axis.orientation === 'Horizontal'; let enablePadding: boolean = false; let markerHeight: number = 0; let yMin: number | string; for (const tempSeries of scrollbar.axis.series) { if (tempSeries.marker.visible && tempSeries.marker.height > markerHeight) { markerHeight = tempSeries.marker.height; } } for (const tempSeries of scrollbar.axis.series) { if (tempSeries.visible) { // To avoid the console error, when the visibility of the series is false. yMin = tempSeries.yMin.toString(); enablePadding = (tempSeries.yData).some((yData: number | string) => { return yData === yMin; }); } if (enablePadding) { break; } } scrollbar.svgObject = renderer.createSvg({ id: scrollbar.component.element.id + '_' + 'scrollBar_svg' + scrollbar.axis.name, width: scrollbar.isVertical ? scrollbar.height : scrollbar.width, height: scrollbar.isVertical ? scrollbar.width : scrollbar.height, style: 'position: absolute;top: ' + ((scrollbar.axis.opposedPosition && isHorizontalAxis ? -16 : (enablePadding ? markerHeight : 0)) + rect.y) + 'px;left: ' + (((scrollbar.axis.opposedPosition && !isHorizontalAxis ? 16 : 0) + rect.x) - (scrollbar.isVertical ? scrollbar.height : 0)) + 'px;cursor:auto;' }); scrollbar.elements.push(scrollbar.svgObject); } /** * Scrollbar elements renderer */ export class ScrollElements { /** @private */ public thumbRectX: number; /** @private */ public thumbRectWidth: number; /** @private */ public leftCircleEle: Element; /** @private */ public rightCircleEle: Element; /** @private */ public leftArrowEle: Element; /** @private */ public rightArrowEle: Element; /** @private */ public gripCircle: Element; /** @private */ public slider: Element; /** @private */ public chartId: string; /** * Constructor for scroll elements * * @param scrollObj * @param chart */ constructor(chart: Chart) { this.chartId = chart.element.id + '_'; } /** * Render scrollbar elements. * * @returns {void} * @private */ public renderElements(scroll: ScrollBar, renderer: SvgRenderer): Element { const scrollGroup: Element = renderer.createGroup({ id: this.chartId + 'scrollBar_' + scroll.axis.name, transform: 'translate(' + ((scroll.isVertical && scroll.axis.isInversed) ? scroll.height : scroll.axis.isInversed ? scroll.width : '0') + ',' + (scroll.isVertical && scroll.axis.isInversed ? '0' : scroll.axis.isInversed ? scroll.height : scroll.isVertical ? scroll.width : '0') + ') rotate(' + (scroll.isVertical && scroll.axis.isInversed ? '90' : scroll.isVertical ? '270' : scroll.axis.isInversed ? '180' : '0') + ')' }); const backRectGroup: Element = renderer.createGroup({ id: this.chartId + 'scrollBar_backRect_' + scroll.axis.name }); const thumbGroup: Element = renderer.createGroup({ id: this.chartId + 'scrollBar_thumb_' + scroll.axis.name, transform: 'translate(0,0)' }); this.backRect(scroll, renderer, backRectGroup); this.thumb(scroll, renderer, thumbGroup); this.renderCircle(scroll, renderer, thumbGroup); this.arrows(scroll, renderer, thumbGroup); this.thumbGrip(scroll, renderer, thumbGroup); scrollGroup.appendChild(backRectGroup); scrollGroup.appendChild(thumbGroup); return scrollGroup; } /** * Method to render back rectangle of scrollbar * * @param scroll * @param renderer * @param parent * @param renderer * @param parent */ private backRect(scroll: ScrollBar, renderer: SvgRenderer, parent: Element): void { const style: IScrollbarThemeStyle = scroll.scrollbarThemeStyle; const backRectEle: Element = renderer.drawRectangle(new RectOption( this.chartId + 'scrollBarBackRect_' + scroll.axis.name, style.backRect, { width: 1, color: style.backRect }, 1, new Rect( 0, 0, scroll.width, scroll.height ), 0, 0) ) as HTMLElement; parent.appendChild(backRectEle); } /** * Method to render arrows * * @param scroll * @param renderer * @param parent * @param renderer * @param parent */ private arrows(scroll: ScrollBar, renderer: SvgRenderer, parent: Element): void { const style: IScrollbarThemeStyle = scroll.scrollbarThemeStyle; const option: PathOption = new PathOption( this.chartId + 'scrollBar_leftArrow_' + scroll.axis.name, style.arrow, 1, style.arrow, 1, '', '' ); this.leftArrowEle = renderer.drawPath(option); option.id = this.chartId + 'scrollBar_rightArrow_' + scroll.axis.name; this.rightArrowEle = renderer.drawPath(option); this.setArrowDirection(this.thumbRectX, this.thumbRectWidth, scroll.height); parent.appendChild(this.leftArrowEle); parent.appendChild(this.rightArrowEle); } /** * Methods to set the arrow width * * @param thumbRectX * @param thumbRectWidth * @param height */ public setArrowDirection(thumbRectX: number, thumbRectWidth: number, height: number): void { const circleRadius: number = 8; const leftDirection: string = 'M ' + ((thumbRectX - circleRadius / 2) + 1) + ' ' + (height / 2) + ' ' + 'L ' + (thumbRectX - circleRadius / 2 + 6) + ' ' + 11 + ' ' + 'L ' + (thumbRectX - circleRadius / 2 + 6) + ' ' + 5 + ' Z'; const rightDirection: string = 'M ' + ((thumbRectX + thumbRectWidth + circleRadius / 2) - 0.5) + ' ' + (height / 2) + ' ' + 'L ' + (thumbRectX + thumbRectWidth + circleRadius / 2 - 6) + ' ' + 11.5 + ' ' + 'L ' + (thumbRectX + thumbRectWidth + circleRadius / 2 - 6) + ' ' + 4.5 + ' Z'; this.leftArrowEle.setAttribute('d', leftDirection); this.rightArrowEle.setAttribute('d', rightDirection); } /** * Method to render thumb * * @param scroll * @param renderer * @param parent */ public thumb(scroll: ScrollBar, renderer: SvgRenderer, parent: Element): void { scroll.startX = this.thumbRectX; const style: IScrollbarThemeStyle = scroll.scrollbarThemeStyle; this.slider = renderer.drawRectangle(new RectOption( this.chartId + 'scrollBarThumb_' + scroll.axis.name, style.thumb, { width: 1, color: '' }, 1, new Rect( this.thumbRectX, 0, this.thumbRectWidth, scroll.height ) )); parent.appendChild(this.slider); } /** * Method to render circles * * @param scroll * @param renderer * @param parent */ private renderCircle(scroll: ScrollBar, renderer: SvgRenderer, parent: Element): void { const style: IScrollbarThemeStyle = scroll.scrollbarThemeStyle; const option: CircleOption = new CircleOption( this.chartId + 'scrollBar_leftCircle_' + scroll.axis.name, style.circle, { width: 1, color: style.circle }, 1, this.thumbRectX, scroll.height / 2, 8 ); const scrollShadowEle: string = '<filter x="-25.0%" y="-20.0%" width="150.0%" height="150.0%" filterUnits="objectBoundingBox"' + 'id="scrollbar_shadow"><feOffset dx="0" dy="1" in="SourceAlpha" result="shadowOffsetOuter1"></feOffset>' + '<feGaussianBlur stdDeviation="1.5" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>' + '<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>' + '<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.16 0" type="matrix" in="shadowBlurOuter1">' + '</feColorMatrix></filter>'; const defElement: Element = renderer.createDefs(); const shadowGroup: Element = renderer.createGroup({ id: this.chartId + scroll.axis.name + '_thumb_shadow' }); defElement.innerHTML = scrollShadowEle; shadowGroup.innerHTML = '<use fill="black" fill-opacity="1" filter="url(#scrollbar_shadow)" xlink:href="#' + this.chartId + 'scrollBar_leftCircle_' + scroll.axis.name + '"></use><use fill="black" fill-opacity="1" filter="url(#scrollbar_shadow)" xlink:href="#' + this.chartId + 'scrollBar_rightCircle_' + scroll.axis.name + '"></use>'; this.leftCircleEle = renderer.drawCircle(option); option.id = this.chartId + 'scrollBar_rightCircle_' + scroll.axis.name; option.cx = this.thumbRectX + this.thumbRectWidth; this.rightCircleEle = renderer.drawCircle(option); parent.appendChild(defElement); parent.appendChild(this.leftCircleEle); parent.appendChild(this.rightCircleEle); parent.appendChild(shadowGroup); } /** * Method to render grip elements * * @param scroll * @param renderer * @param parent */ private thumbGrip(scroll: ScrollBar, renderer: SvgRenderer, parent: Element): void { let sidePadding: number = 0; let topPadding: number = 0; const gripWidth: number = 14; const gripCircleDiameter: number = 2; const padding: number = gripWidth / 2 - gripCircleDiameter; const style: IScrollbarThemeStyle = scroll.scrollbarThemeStyle; const option: CircleOption = new CircleOption( this.chartId + 'scrollBar_gripCircle0' + '_' + scroll.axis.name, style.grip, { width: 1, color: style.grip }, 1, 0, 0, 1 ); this.gripCircle = renderer.createGroup({ id: this.chartId + 'scrollBar_gripCircle_' + scroll.axis.name, transform: 'translate(' + ((this.thumbRectX + this.thumbRectWidth / 2) + ((scroll.isVertical ? 1 : -1) * padding)) + ',' + (scroll.isVertical ? '10' : '5') + ') rotate(' + (scroll.isVertical ? '180' : '0') + ')' }); for (let i: number = 1; i <= 6; i++) { option.id = this.chartId + 'scrollBar_gripCircle' + i + '_' + scroll.axis.name; option.cx = sidePadding; option.cy = topPadding; this.gripCircle.appendChild( renderer.drawCircle(option ) ); sidePadding = i === 3 ? 0 : (sidePadding + 5); topPadding = i >= 3 ? 5 : 0; } parent.appendChild(this.gripCircle); } }
the_stack
import { Live2DCubismFramework as cubismphysicsinternal } from './cubismphysicsinternal'; import { Live2DCubismFramework as cubismmodel } from '../model/cubismmodel'; import { Live2DCubismFramework as cubismvector2 } from '../math/cubismvector2'; import { Live2DCubismFramework as cubismmath } from '../math/cubismmath'; import { Live2DCubismFramework as cubismphysicsjson } from './cubismphysicsjson'; import CubismPhysicsJson = cubismphysicsjson.CubismPhysicsJson; import CubismMath = cubismmath.CubismMath; import CubismPhysicsRig = cubismphysicsinternal.CubismPhysicsRig; import CubismPhysicsSubRig = cubismphysicsinternal.CubismPhysicsSubRig; import CubismPhysicsInput = cubismphysicsinternal.CubismPhysicsInput; import CubismPhysicsOutput = cubismphysicsinternal.CubismPhysicsOutput; import CubismPhysicsParticle = cubismphysicsinternal.CubismPhysicsParticle; import CubismPhysicsSource = cubismphysicsinternal.CubismPhysicsSource; import CubismPhysicsTargetType = cubismphysicsinternal.CubismPhysicsTargetType; import CubismPhysicsNormalization = cubismphysicsinternal.CubismPhysicsNormalization; import CubismVector2 = cubismvector2.CubismVector2; import CubismModel = cubismmodel.CubismModel; export namespace Live2DCubismFramework { // physics types tags. const PhysicsTypeTagX = 'X'; const PhysicsTypeTagY = 'Y'; const PhysicsTypeTagAngle = 'Angle'; // Constant of air resistance. const AirResistance = 5.0; // Constant of maximum weight of input and output ratio. const MaximumWeight = 100.0; // Constant of threshold of movement. const MovementThreshold = 0.001; /** * 物理演算クラス */ export class CubismPhysics { /** * インスタンスの作成 * @param buffer physics3.jsonが読み込まれているバッファ * @param size バッファのサイズ * @return 作成されたインスタンス */ public static create(buffer: ArrayBuffer, size: number): CubismPhysics { const ret: CubismPhysics = new CubismPhysics(); ret.parse(buffer, size); ret._physicsRig.gravity.y = 0; return ret; } /** * インスタンスを破棄する * @param physics 破棄するインスタンス */ public static delete(physics: CubismPhysics): void { if (physics != null) { physics.release(); physics = null; } } /** * 物理演算の評価 * @param model 物理演算の結果を適用するモデル * @param deltaTimeSeconds デルタ時間[秒] */ public evaluate(model: CubismModel, deltaTimeSeconds: number): void { let totalAngle: { angle: number }; let weight: number; let radAngle: number; let outputValue: number; const totalTranslation: CubismVector2 = new CubismVector2(); let currentSetting: CubismPhysicsSubRig; let currentInput: CubismPhysicsInput[]; let currentOutput: CubismPhysicsOutput[]; let currentParticles: CubismPhysicsParticle[]; let parameterValue: Float32Array; let parameterMaximumValue: Float32Array; let parameterMinimumValue: Float32Array; let parameterDefaultValue: Float32Array; parameterValue = model.getModel().parameters.values; parameterMaximumValue = model.getModel().parameters.maximumValues; parameterMinimumValue = model.getModel().parameters.minimumValues; parameterDefaultValue = model.getModel().parameters.defaultValues; for ( let settingIndex = 0; settingIndex < this._physicsRig.subRigCount; ++settingIndex ) { totalAngle = { angle: 0.0 }; totalTranslation.x = 0.0; totalTranslation.y = 0.0; currentSetting = this._physicsRig.settings.at(settingIndex); currentInput = this._physicsRig.inputs.get( currentSetting.baseInputIndex ); currentOutput = this._physicsRig.outputs.get( currentSetting.baseOutputIndex ); currentParticles = this._physicsRig.particles.get( currentSetting.baseParticleIndex ); // Load input parameters for (let i = 0; i < currentSetting.inputCount; ++i) { weight = currentInput[i].weight / MaximumWeight; if (currentInput[i].sourceParameterIndex == -1) { currentInput[i].sourceParameterIndex = model.getParameterIndex( currentInput[i].source.id ); } currentInput[i].getNormalizedParameterValue( totalTranslation, totalAngle, parameterValue[currentInput[i].sourceParameterIndex], parameterMinimumValue[currentInput[i].sourceParameterIndex], parameterMaximumValue[currentInput[i].sourceParameterIndex], parameterDefaultValue[currentInput[i].sourceParameterIndex], currentSetting.normalizationPosition, currentSetting.normalizationAngle, currentInput[0].reflect, weight ); } radAngle = CubismMath.degreesToRadian(-totalAngle.angle); totalTranslation.x = totalTranslation.x * CubismMath.cos(radAngle) - totalTranslation.y * CubismMath.sin(radAngle); totalTranslation.y = totalTranslation.x * CubismMath.sin(radAngle) + totalTranslation.y * CubismMath.cos(radAngle); // Calculate particles position. updateParticles( currentParticles, currentSetting.particleCount, totalTranslation, totalAngle.angle, this._options.wind, MovementThreshold * currentSetting.normalizationPosition.maximum, deltaTimeSeconds, AirResistance ); // Update output parameters. for (let i = 0; i < currentSetting.outputCount; ++i) { const particleIndex = currentOutput[i].vertexIndex; if ( particleIndex < 1 || particleIndex >= currentSetting.particleCount ) { break; } if (currentOutput[i].destinationParameterIndex == -1) { currentOutput[ i ].destinationParameterIndex = model.getParameterIndex( currentOutput[i].destination.id ); } const translation: CubismVector2 = new CubismVector2(); translation.x = currentParticles[particleIndex].position.x - currentParticles[particleIndex - 1].position.x; translation.y = currentParticles[particleIndex].position.y - currentParticles[particleIndex - 1].position.y; outputValue = currentOutput[i].getValue( translation, currentParticles, particleIndex, currentOutput[i].reflect, this._options.gravity ); const destinationParameterIndex: number = currentOutput[i].destinationParameterIndex; const outParameterValue: Float32Array = !Float32Array.prototype.slice && 'subarray' in Float32Array.prototype ? JSON.parse( JSON.stringify( parameterValue.subarray(destinationParameterIndex) ) ) // 値渡しするため、JSON.parse, JSON.stringify : parameterValue.slice(destinationParameterIndex); updateOutputParameterValue( outParameterValue, parameterMinimumValue[destinationParameterIndex], parameterMaximumValue[destinationParameterIndex], outputValue, currentOutput[i] ); // 値を反映 for ( let offset: number = destinationParameterIndex, outParamIndex = 0; offset < parameterValue.length; offset++, outParamIndex++ ) { parameterValue[offset] = outParameterValue[outParamIndex]; } } } } /** * オプションの設定 * @param options オプション */ public setOptions(options: Options): void { this._options = options; } /** * オプションの取得 * @return オプション */ public getOption(): Options { return this._options; } /** * コンストラクタ */ public constructor() { this._physicsRig = null; // set default options this._options = new Options(); this._options.gravity.y = -1.0; this._options.gravity.x = 0; this._options.wind.x = 0; this._options.wind.y = 0; } /** * デストラクタ相当の処理 */ public release(): void { this._physicsRig = void 0; this._physicsRig = null; } /** * physics3.jsonをパースする。 * @param physicsJson physics3.jsonが読み込まれているバッファ * @param size バッファのサイズ */ public parse(physicsJson: ArrayBuffer, size: number): void { this._physicsRig = new CubismPhysicsRig(); let json: CubismPhysicsJson = new CubismPhysicsJson(physicsJson, size); this._physicsRig.gravity = json.getGravity(); this._physicsRig.wind = json.getWind(); this._physicsRig.subRigCount = json.getSubRigCount(); this._physicsRig.settings.updateSize( this._physicsRig.subRigCount, CubismPhysicsSubRig, true ); this._physicsRig.inputs.updateSize( json.getTotalInputCount(), CubismPhysicsInput, true ); this._physicsRig.outputs.updateSize( json.getTotalOutputCount(), CubismPhysicsOutput, true ); this._physicsRig.particles.updateSize( json.getVertexCount(), CubismPhysicsParticle, true ); let inputIndex = 0, outputIndex = 0, particleIndex = 0; for (let i = 0; i < this._physicsRig.settings.getSize(); ++i) { this._physicsRig.settings.at( i ).normalizationPosition.minimum = json.getNormalizationPositionMinimumValue( i ); this._physicsRig.settings.at( i ).normalizationPosition.maximum = json.getNormalizationPositionMaximumValue( i ); this._physicsRig.settings.at( i ).normalizationPosition.defalut = json.getNormalizationPositionDefaultValue( i ); this._physicsRig.settings.at( i ).normalizationAngle.minimum = json.getNormalizationAngleMinimumValue( i ); this._physicsRig.settings.at( i ).normalizationAngle.maximum = json.getNormalizationAngleMaximumValue( i ); this._physicsRig.settings.at( i ).normalizationAngle.defalut = json.getNormalizationAngleDefaultValue( i ); // Input this._physicsRig.settings.at(i).inputCount = json.getInputCount(i); this._physicsRig.settings.at(i).baseInputIndex = inputIndex; for (let j = 0; j < this._physicsRig.settings.at(i).inputCount; ++j) { this._physicsRig.inputs.at(inputIndex + j).sourceParameterIndex = -1; this._physicsRig.inputs.at( inputIndex + j ).weight = json.getInputWeight(i, j); this._physicsRig.inputs.at( inputIndex + j ).reflect = json.getInputReflect(i, j); if (json.getInputType(i, j) == PhysicsTypeTagX) { this._physicsRig.inputs.at(inputIndex + j).type = CubismPhysicsSource.CubismPhysicsSource_X; this._physicsRig.inputs.at( inputIndex + j ).getNormalizedParameterValue = getInputTranslationXFromNormalizedParameterValue; } else if (json.getInputType(i, j) == PhysicsTypeTagY) { this._physicsRig.inputs.at(inputIndex + j).type = CubismPhysicsSource.CubismPhysicsSource_Y; this._physicsRig.inputs.at( inputIndex + j ).getNormalizedParameterValue = getInputTranslationYFromNormalizedParamterValue; } else if (json.getInputType(i, j) == PhysicsTypeTagAngle) { this._physicsRig.inputs.at(inputIndex + j).type = CubismPhysicsSource.CubismPhysicsSource_Angle; this._physicsRig.inputs.at( inputIndex + j ).getNormalizedParameterValue = getInputAngleFromNormalizedParameterValue; } this._physicsRig.inputs.at(inputIndex + j).source.targetType = CubismPhysicsTargetType.CubismPhysicsTargetType_Parameter; this._physicsRig.inputs.at( inputIndex + j ).source.id = json.getInputSourceId(i, j); } inputIndex += this._physicsRig.settings.at(i).inputCount; // Output this._physicsRig.settings.at(i).outputCount = json.getOutputCount(i); this._physicsRig.settings.at(i).baseOutputIndex = outputIndex; for (let j = 0; j < this._physicsRig.settings.at(i).outputCount; ++j) { this._physicsRig.outputs.at( outputIndex + j ).destinationParameterIndex = -1; this._physicsRig.outputs.at( outputIndex + j ).vertexIndex = json.getOutputVertexIndex(i, j); this._physicsRig.outputs.at( outputIndex + j ).angleScale = json.getOutputAngleScale(i, j); this._physicsRig.outputs.at( outputIndex + j ).weight = json.getOutputWeight(i, j); this._physicsRig.outputs.at(outputIndex + j).destination.targetType = CubismPhysicsTargetType.CubismPhysicsTargetType_Parameter; this._physicsRig.outputs.at( outputIndex + j ).destination.id = json.getOutputDestinationId(i, j); if (json.getOutputType(i, j) == PhysicsTypeTagX) { this._physicsRig.outputs.at(outputIndex + j).type = CubismPhysicsSource.CubismPhysicsSource_X; this._physicsRig.outputs.at( outputIndex + j ).getValue = getOutputTranslationX; this._physicsRig.outputs.at( outputIndex + j ).getScale = getOutputScaleTranslationX; } else if (json.getOutputType(i, j) == PhysicsTypeTagY) { this._physicsRig.outputs.at(outputIndex + j).type = CubismPhysicsSource.CubismPhysicsSource_Y; this._physicsRig.outputs.at( outputIndex + j ).getValue = getOutputTranslationY; this._physicsRig.outputs.at( outputIndex + j ).getScale = getOutputScaleTranslationY; } else if (json.getOutputType(i, j) == PhysicsTypeTagAngle) { this._physicsRig.outputs.at(outputIndex + j).type = CubismPhysicsSource.CubismPhysicsSource_Angle; this._physicsRig.outputs.at( outputIndex + j ).getValue = getOutputAngle; this._physicsRig.outputs.at( outputIndex + j ).getScale = getOutputScaleAngle; } this._physicsRig.outputs.at( outputIndex + j ).reflect = json.getOutputReflect(i, j); } outputIndex += this._physicsRig.settings.at(i).outputCount; // Particle this._physicsRig.settings.at(i).particleCount = json.getParticleCount( i ); this._physicsRig.settings.at(i).baseParticleIndex = particleIndex; for ( let j = 0; j < this._physicsRig.settings.at(i).particleCount; ++j ) { this._physicsRig.particles.at( particleIndex + j ).mobility = json.getParticleMobility(i, j); this._physicsRig.particles.at( particleIndex + j ).delay = json.getParticleDelay(i, j); this._physicsRig.particles.at( particleIndex + j ).acceleration = json.getParticleAcceleration(i, j); this._physicsRig.particles.at( particleIndex + j ).radius = json.getParticleRadius(i, j); this._physicsRig.particles.at( particleIndex + j ).position = json.getParticlePosition(i, j); } particleIndex += this._physicsRig.settings.at(i).particleCount; } this.initialize(); json.release(); json = void 0; json = null; } /** * 初期化する */ public initialize(): void { let strand: CubismPhysicsParticle[]; let currentSetting: CubismPhysicsSubRig; let radius: CubismVector2; for ( let settingIndex = 0; settingIndex < this._physicsRig.subRigCount; ++settingIndex ) { currentSetting = this._physicsRig.settings.at(settingIndex); strand = this._physicsRig.particles.get( currentSetting.baseParticleIndex ); // Initialize the top of particle. strand[0].initialPosition = new CubismVector2(0.0, 0.0); strand[0].lastPosition = new CubismVector2( strand[0].initialPosition.x, strand[0].initialPosition.y ); strand[0].lastGravity = new CubismVector2(0.0, -1.0); strand[0].lastGravity.y *= -1.0; strand[0].velocity = new CubismVector2(0.0, 0.0); strand[0].force = new CubismVector2(0.0, 0.0); // Initialize paritcles. for (let i = 1; i < currentSetting.particleCount; ++i) { radius = new CubismVector2(0.0, 0.0); radius.y = strand[i].radius; strand[i].initialPosition = new CubismVector2( strand[i - 1].initialPosition.x + radius.x, strand[i - 1].initialPosition.y + radius.y ); strand[i].position = new CubismVector2( strand[i].initialPosition.x, strand[i].initialPosition.y ); strand[i].lastPosition = new CubismVector2( strand[i].initialPosition.x, strand[i].initialPosition.y ); strand[i].lastGravity = new CubismVector2(0.0, -1.0); strand[i].lastGravity.y *= -1.0; strand[i].velocity = new CubismVector2(0.0, 0.0); strand[i].force = new CubismVector2(0.0, 0.0); } } } _physicsRig: CubismPhysicsRig; // 物理演算のデータ _options: Options; // オプション } /** * 物理演算のオプション */ export class Options { constructor() { this.gravity = new CubismVector2(0, 0); this.wind = new CubismVector2(0, 0); } gravity: CubismVector2; // 重力方向 wind: CubismVector2; // 風の方向 } /** * Gets sign. * * @param value Evaluation target value. * * @return Sign of value. */ function sign(value: number): number { let ret = 0; if (value > 0.0) { ret = 1; } else if (value < 0.0) { ret = -1; } return ret; } function getInputTranslationXFromNormalizedParameterValue( targetTranslation: CubismVector2, targetAngle: { angle: number }, value: number, parameterMinimumValue: number, parameterMaximumValue: number, parameterDefaultValue: number, normalizationPosition: CubismPhysicsNormalization, normalizationAngle: CubismPhysicsNormalization, isInverted: boolean, weight: number ): void { targetTranslation.x += normalizeParameterValue( value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationPosition.minimum, normalizationPosition.maximum, normalizationPosition.defalut, isInverted ) * weight; } function getInputTranslationYFromNormalizedParamterValue( targetTranslation: CubismVector2, targetAngle: { angle: number }, value: number, parameterMinimumValue: number, parameterMaximumValue: number, parameterDefaultValue: number, normalizationPosition: CubismPhysicsNormalization, normalizationAngle: CubismPhysicsNormalization, isInverted: boolean, weight: number ): void { targetTranslation.y += normalizeParameterValue( value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationPosition.minimum, normalizationPosition.maximum, normalizationPosition.defalut, isInverted ) * weight; } function getInputAngleFromNormalizedParameterValue( targetTranslation: CubismVector2, targetAngle: { angle: number }, value: number, parameterMinimumValue: number, parameterMaximumValue: number, parameterDefaultValue: number, normalizaitionPosition: CubismPhysicsNormalization, normalizationAngle: CubismPhysicsNormalization, isInverted: boolean, weight: number ): void { targetAngle.angle += normalizeParameterValue( value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationAngle.minimum, normalizationAngle.maximum, normalizationAngle.defalut, isInverted ) * weight; } function getOutputTranslationX( translation: CubismVector2, particles: CubismPhysicsParticle[], particleIndex: number, isInverted: boolean, parentGravity: CubismVector2 ): number { let outputValue: number = translation.x; if (isInverted) { outputValue *= -1.0; } return outputValue; } function getOutputTranslationY( translation: CubismVector2, particles: CubismPhysicsParticle[], particleIndex: number, isInverted: boolean, parentGravity: CubismVector2 ): number { let outputValue: number = translation.y; if (isInverted) { outputValue *= -1.0; } return outputValue; } function getOutputAngle( translation: CubismVector2, particles: CubismPhysicsParticle[], particleIndex: number, isInverted: boolean, parentGravity: CubismVector2 ): number { let outputValue: number; if (particleIndex >= 2) { parentGravity = particles[particleIndex - 1].position.substract( particles[particleIndex - 2].position ); } else { parentGravity = parentGravity.multiplyByScaler(-1.0); } outputValue = CubismMath.directionToRadian(parentGravity, translation); if (isInverted) { outputValue *= -1.0; } return outputValue; } function getRangeValue(min: number, max: number): number { const maxValue: number = CubismMath.max(min, max); const minValue: number = CubismMath.min(min, max); return CubismMath.abs(maxValue - minValue); } function getDefaultValue(min: number, max: number): number { const minValue: number = CubismMath.min(min, max); return minValue + getRangeValue(min, max) / 2.0; } function getOutputScaleTranslationX( translationScale: CubismVector2, angleScale: number ): number { return JSON.parse(JSON.stringify(translationScale.x)); } function getOutputScaleTranslationY( translationScale: CubismVector2, angleScale: number ): number { return JSON.parse(JSON.stringify(translationScale.y)); } function getOutputScaleAngle( translationScale: CubismVector2, angleScale: number ): number { return JSON.parse(JSON.stringify(angleScale)); } /** * Updates particles. * * @param strand Target array of particle. * @param strandCount Count of particle. * @param totalTranslation Total translation value. * @param totalAngle Total angle. * @param windDirection Direction of Wind. * @param thresholdValue Threshold of movement. * @param deltaTimeSeconds Delta time. * @param airResistance Air resistance. */ function updateParticles( strand: CubismPhysicsParticle[], strandCount: number, totalTranslation: CubismVector2, totalAngle: number, windDirection: CubismVector2, thresholdValue: number, deltaTimeSeconds: number, airResistance: number ) { let totalRadian: number; let delay: number; let radian: number; let currentGravity: CubismVector2; let direction: CubismVector2 = new CubismVector2(0.0, 0.0); let velocity: CubismVector2 = new CubismVector2(0.0, 0.0); let force: CubismVector2 = new CubismVector2(0.0, 0.0); let newDirection: CubismVector2 = new CubismVector2(0.0, 0.0); strand[0].position = new CubismVector2( totalTranslation.x, totalTranslation.y ); totalRadian = CubismMath.degreesToRadian(totalAngle); currentGravity = CubismMath.radianToDirection(totalRadian); currentGravity.normalize(); for (let i = 1; i < strandCount; ++i) { strand[i].force = currentGravity .multiplyByScaler(strand[i].acceleration) .add(windDirection); strand[i].lastPosition = new CubismVector2( strand[i].position.x, strand[i].position.y ); delay = strand[i].delay * deltaTimeSeconds * 30.0; direction = strand[i].position.substract(strand[i - 1].position); radian = CubismMath.directionToRadian(strand[i].lastGravity, currentGravity) / airResistance; direction.x = CubismMath.cos(radian) * direction.x - direction.y * CubismMath.sin(radian); direction.y = CubismMath.sin(radian) * direction.x + direction.y * CubismMath.cos(radian); strand[i].position = strand[i - 1].position.add(direction); velocity = strand[i].velocity.multiplyByScaler(delay); force = strand[i].force.multiplyByScaler(delay).multiplyByScaler(delay); strand[i].position = strand[i].position.add(velocity).add(force); newDirection = strand[i].position.substract(strand[i - 1].position); newDirection.normalize(); strand[i].position = strand[i - 1].position.add( newDirection.multiplyByScaler(strand[i].radius) ); if (CubismMath.abs(strand[i].position.x) < thresholdValue) { strand[i].position.x = 0.0; } if (delay != 0.0) { strand[i].velocity = strand[i].position.substract( strand[i].lastPosition ); strand[i].velocity = strand[i].velocity.divisionByScalar(delay); strand[i].velocity = strand[i].velocity.multiplyByScaler( strand[i].mobility ); } strand[i].force = new CubismVector2(0.0, 0.0); strand[i].lastGravity = new CubismVector2( currentGravity.x, currentGravity.y ); } } /** * Updates output parameter value. * @param parameterValue Target parameter value. * @param parameterValueMinimum Minimum of parameter value. * @param parameterValueMaximum Maximum of parameter value. * @param translation Translation value. */ function updateOutputParameterValue( parameterValue: Float32Array, parameterValueMinimum: number, parameterValueMaximum: number, translation: number, output: CubismPhysicsOutput ): void { let outputScale: number; let value: number; let weight: number; outputScale = output.getScale(output.translationScale, output.angleScale); value = translation * outputScale; if (value < parameterValueMinimum) { if (value < output.valueBelowMinimum) { output.valueBelowMinimum = value; } value = parameterValueMinimum; } else if (value > parameterValueMaximum) { if (value > output.valueExceededMaximum) { output.valueExceededMaximum = value; } value = parameterValueMaximum; } weight = output.weight / MaximumWeight; if (weight >= 1.0) { parameterValue[0] = value; } else { value = parameterValue[0] * (1.0 - weight) + value * weight; parameterValue[0] = value; } } function normalizeParameterValue( value: number, parameterMinimum: number, parameterMaximum: number, parameterDefault: number, normalizedMinimum: number, normalizedMaximum: number, normalizedDefault: number, isInverted: boolean ) { let result = 0.0; const maxValue: number = CubismMath.max(parameterMaximum, parameterMinimum); if (maxValue < value) { value = maxValue; } const minValue: number = CubismMath.min(parameterMaximum, parameterMinimum); if (minValue > value) { value = minValue; } const minNormValue: number = CubismMath.min( normalizedMinimum, normalizedMaximum ); const maxNormValue: number = CubismMath.max( normalizedMinimum, normalizedMaximum ); const middleNormValue: number = normalizedDefault; const middleValue: number = getDefaultValue(minValue, maxValue); const paramValue: number = value - middleValue; switch (sign(paramValue)) { case 1: { const nLength: number = maxNormValue - middleNormValue; const pLength: number = maxValue - middleValue; if (pLength != 0.0) { result = paramValue * (nLength / pLength); result += middleNormValue; } break; } case -1: { const nLength: number = minNormValue - middleNormValue; const pLength: number = minValue - middleValue; if (pLength != 0.0) { result = paramValue * (nLength / pLength); result += middleNormValue; } break; } case 0: { result = middleNormValue; break; } default: { break; } } return isInverted ? result : result * -1.0; } }
the_stack
import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants'; import { computeBufferSize } from '../helpers/compute-buffer-size'; import { copyFromChannel } from '../helpers/copy-from-channel'; import { copyToChannel } from '../helpers/copy-to-channel'; import { createAudioWorkletProcessor } from '../helpers/create-audio-worklet-processor'; import { createNestedArrays } from '../helpers/create-nested-arrays'; import { IAudioWorkletProcessor } from '../interfaces'; import { ReadOnlyMap } from '../read-only-map'; import { TNativeAudioNode, TNativeAudioParam, TNativeAudioWorkletNode, TNativeAudioWorkletNodeFakerFactoryFactory, TNativeChannelMergerNode, TNativeChannelSplitterNode, TNativeConstantSourceNode, TNativeGainNode } from '../types'; export const createNativeAudioWorkletNodeFakerFactory: TNativeAudioWorkletNodeFakerFactoryFactory = ( connectMultipleOutputs, createIndexSizeError, createInvalidStateError, createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeConstantSourceNode, createNativeGainNode, createNativeScriptProcessorNode, createNotSupportedError, disconnectMultipleOutputs, exposeCurrentFrameAndCurrentTime, getActiveAudioWorkletNodeInputs, monitorConnections ) => { return (nativeContext, baseLatency, processorConstructor, options) => { if (options.numberOfInputs === 0 && options.numberOfOutputs === 0) { throw createNotSupportedError(); } const outputChannelCount = Array.isArray(options.outputChannelCount) ? options.outputChannelCount : Array.from(options.outputChannelCount); // @todo Check if any of the channelCount values is greater than the implementation's maximum number of channels. if (outputChannelCount.some((channelCount) => channelCount < 1)) { throw createNotSupportedError(); } if (outputChannelCount.length !== options.numberOfOutputs) { throw createIndexSizeError(); } // Bug #61: This is not part of the standard but required for the faker to work. if (options.channelCountMode !== 'explicit') { throw createNotSupportedError(); } const numberOfInputChannels = options.channelCount * options.numberOfInputs; const numberOfOutputChannels = outputChannelCount.reduce((sum, value) => sum + value, 0); const numberOfParameters = processorConstructor.parameterDescriptors === undefined ? 0 : processorConstructor.parameterDescriptors.length; // Bug #61: This is not part of the standard but required for the faker to work. if (numberOfInputChannels + numberOfParameters > 6 || numberOfOutputChannels > 6) { throw createNotSupportedError(); } const messageChannel = new MessageChannel(); const gainNodes: TNativeGainNode[] = []; const inputChannelSplitterNodes: TNativeChannelSplitterNode[] = []; for (let i = 0; i < options.numberOfInputs; i += 1) { gainNodes.push( createNativeGainNode(nativeContext, { channelCount: options.channelCount, channelCountMode: options.channelCountMode, channelInterpretation: options.channelInterpretation, gain: 1 }) ); inputChannelSplitterNodes.push( createNativeChannelSplitterNode(nativeContext, { channelCount: options.channelCount, channelCountMode: 'explicit', channelInterpretation: 'discrete', numberOfOutputs: options.channelCount }) ); } const constantSourceNodes: TNativeConstantSourceNode[] = []; if (processorConstructor.parameterDescriptors !== undefined) { for (const { defaultValue, maxValue, minValue, name } of processorConstructor.parameterDescriptors) { const constantSourceNode = createNativeConstantSourceNode(nativeContext, { channelCount: 1, channelCountMode: 'explicit', channelInterpretation: 'discrete', offset: options.parameterData[name] !== undefined ? options.parameterData[name] : defaultValue === undefined ? 0 : defaultValue }); Object.defineProperties(constantSourceNode.offset, { defaultValue: { get: () => (defaultValue === undefined ? 0 : defaultValue) }, maxValue: { get: () => (maxValue === undefined ? MOST_POSITIVE_SINGLE_FLOAT : maxValue) }, minValue: { get: () => (minValue === undefined ? MOST_NEGATIVE_SINGLE_FLOAT : minValue) } }); constantSourceNodes.push(constantSourceNode); } } const inputChannelMergerNode = createNativeChannelMergerNode(nativeContext, { channelCount: 1, channelCountMode: 'explicit', channelInterpretation: 'speakers', numberOfInputs: Math.max(1, numberOfInputChannels + numberOfParameters) }); const bufferSize = computeBufferSize(baseLatency, nativeContext.sampleRate); const scriptProcessorNode = createNativeScriptProcessorNode( nativeContext, bufferSize, numberOfInputChannels + numberOfParameters, // Bug #87: Only Firefox will fire an AudioProcessingEvent if there is no connected output. Math.max(1, numberOfOutputChannels) ); const outputChannelSplitterNode = createNativeChannelSplitterNode(nativeContext, { channelCount: Math.max(1, numberOfOutputChannels), channelCountMode: 'explicit', channelInterpretation: 'discrete', numberOfOutputs: Math.max(1, numberOfOutputChannels) }); const outputChannelMergerNodes: TNativeChannelMergerNode[] = []; for (let i = 0; i < options.numberOfOutputs; i += 1) { outputChannelMergerNodes.push( createNativeChannelMergerNode(nativeContext, { channelCount: 1, channelCountMode: 'explicit', channelInterpretation: 'speakers', numberOfInputs: outputChannelCount[i] }) ); } for (let i = 0; i < options.numberOfInputs; i += 1) { gainNodes[i].connect(inputChannelSplitterNodes[i]); for (let j = 0; j < options.channelCount; j += 1) { inputChannelSplitterNodes[i].connect(inputChannelMergerNode, j, i * options.channelCount + j); } } const parameterMap = new ReadOnlyMap( processorConstructor.parameterDescriptors === undefined ? [] : processorConstructor.parameterDescriptors.map(({ name }, index) => { const constantSourceNode = constantSourceNodes[index]; constantSourceNode.connect(inputChannelMergerNode, 0, numberOfInputChannels + index); constantSourceNode.start(0); return <[string, TNativeAudioParam]>[name, constantSourceNode.offset]; }) ); inputChannelMergerNode.connect(scriptProcessorNode); let channelInterpretation = options.channelInterpretation; let onprocessorerror: TNativeAudioWorkletNode['onprocessorerror'] = null; // Bug #87: Expose at least one output to make this node connectable. const outputAudioNodes = options.numberOfOutputs === 0 ? [scriptProcessorNode] : outputChannelMergerNodes; const nativeAudioWorkletNodeFaker = { get bufferSize(): number { return bufferSize; }, get channelCount(): number { return options.channelCount; }, set channelCount(_) { // Bug #61: This is not part of the standard but required for the faker to work. throw createInvalidStateError(); }, get channelCountMode(): TNativeAudioWorkletNode['channelCountMode'] { return options.channelCountMode; }, set channelCountMode(_) { // Bug #61: This is not part of the standard but required for the faker to work. throw createInvalidStateError(); }, get channelInterpretation(): TNativeAudioWorkletNode['channelInterpretation'] { return channelInterpretation; }, set channelInterpretation(value) { for (const gainNode of gainNodes) { gainNode.channelInterpretation = value; } channelInterpretation = value; }, get context(): TNativeAudioWorkletNode['context'] { return scriptProcessorNode.context; }, get inputs(): TNativeAudioNode[] { return gainNodes; }, get numberOfInputs(): number { return options.numberOfInputs; }, get numberOfOutputs(): number { return options.numberOfOutputs; }, get onprocessorerror(): TNativeAudioWorkletNode['onprocessorerror'] { return onprocessorerror; }, set onprocessorerror(value) { if (typeof onprocessorerror === 'function') { nativeAudioWorkletNodeFaker.removeEventListener('processorerror', onprocessorerror); } onprocessorerror = typeof value === 'function' ? value : null; if (typeof onprocessorerror === 'function') { nativeAudioWorkletNodeFaker.addEventListener('processorerror', onprocessorerror); } }, get parameters(): TNativeAudioWorkletNode['parameters'] { return parameterMap; }, get port(): TNativeAudioWorkletNode['port'] { return messageChannel.port2; }, addEventListener(...args: any[]): void { return scriptProcessorNode.addEventListener(args[0], args[1], args[2]); }, connect: <TNativeAudioNode['connect']>connectMultipleOutputs.bind(null, outputAudioNodes), disconnect: <TNativeAudioNode['disconnect']>disconnectMultipleOutputs.bind(null, outputAudioNodes), dispatchEvent(...args: any[]): boolean { return scriptProcessorNode.dispatchEvent(args[0]); }, removeEventListener(...args: any[]): void { return scriptProcessorNode.removeEventListener(args[0], args[1], args[2]); } }; const patchedEventListeners: Map<EventListenerOrEventListenerObject, NonNullable<MessagePort['onmessage']>> = new Map(); messageChannel.port1.addEventListener = ((addEventListener) => { return (...args: [string, EventListenerOrEventListenerObject, (boolean | AddEventListenerOptions)?]): void => { if (args[0] === 'message') { const unpatchedEventListener = typeof args[1] === 'function' ? args[1] : typeof args[1] === 'object' && args[1] !== null && typeof args[1].handleEvent === 'function' ? args[1].handleEvent : null; if (unpatchedEventListener !== null) { const patchedEventListener = patchedEventListeners.get(args[1]); if (patchedEventListener !== undefined) { args[1] = <EventListenerOrEventListenerObject>patchedEventListener; } else { args[1] = (event: Event) => { exposeCurrentFrameAndCurrentTime(nativeContext.currentTime, nativeContext.sampleRate, () => unpatchedEventListener(event) ); }; patchedEventListeners.set(unpatchedEventListener, args[1]); } } } return addEventListener.call(messageChannel.port1, args[0], args[1], args[2]); }; })(messageChannel.port1.addEventListener); messageChannel.port1.removeEventListener = ((removeEventListener) => { return (...args: any[]): void => { if (args[0] === 'message') { const patchedEventListener = patchedEventListeners.get(args[1]); if (patchedEventListener !== undefined) { patchedEventListeners.delete(args[1]); args[1] = patchedEventListener; } } return removeEventListener.call(messageChannel.port1, args[0], args[1], args[2]); }; })(messageChannel.port1.removeEventListener); let onmessage: MessagePort['onmessage'] = null; Object.defineProperty(messageChannel.port1, 'onmessage', { get: () => onmessage, set: (value) => { if (typeof onmessage === 'function') { messageChannel.port1.removeEventListener('message', onmessage); } onmessage = typeof value === 'function' ? value : null; if (typeof onmessage === 'function') { messageChannel.port1.addEventListener('message', onmessage); messageChannel.port1.start(); } } }); processorConstructor.prototype.port = messageChannel.port1; let audioWorkletProcessor: null | IAudioWorkletProcessor = null; const audioWorkletProcessorPromise = createAudioWorkletProcessor( nativeContext, nativeAudioWorkletNodeFaker, processorConstructor, options ); audioWorkletProcessorPromise.then((dWrkltPrcssr) => (audioWorkletProcessor = dWrkltPrcssr)); const inputs = createNestedArrays(options.numberOfInputs, options.channelCount); const outputs = createNestedArrays(options.numberOfOutputs, outputChannelCount); const parameters: { [name: string]: Float32Array } = processorConstructor.parameterDescriptors === undefined ? [] : processorConstructor.parameterDescriptors.reduce( (prmtrs, { name }) => ({ ...prmtrs, [name]: new Float32Array(128) }), {} ); let isActive = true; const disconnectOutputsGraph = () => { if (options.numberOfOutputs > 0) { scriptProcessorNode.disconnect(outputChannelSplitterNode); } for (let i = 0, outputChannelSplitterNodeOutput = 0; i < options.numberOfOutputs; i += 1) { const outputChannelMergerNode = outputChannelMergerNodes[i]; for (let j = 0; j < outputChannelCount[i]; j += 1) { outputChannelSplitterNode.disconnect(outputChannelMergerNode, outputChannelSplitterNodeOutput + j, j); } outputChannelSplitterNodeOutput += outputChannelCount[i]; } }; const activeInputIndexes = new Map<number, number>(); // tslint:disable-next-line:deprecation scriptProcessorNode.onaudioprocess = ({ inputBuffer, outputBuffer }: AudioProcessingEvent) => { if (audioWorkletProcessor !== null) { const activeInputs = getActiveAudioWorkletNodeInputs(nativeAudioWorkletNodeFaker); for (let i = 0; i < bufferSize; i += 128) { for (let j = 0; j < options.numberOfInputs; j += 1) { for (let k = 0; k < options.channelCount; k += 1) { copyFromChannel(inputBuffer, inputs[j], k, k, i); } } if (processorConstructor.parameterDescriptors !== undefined) { processorConstructor.parameterDescriptors.forEach(({ name }, index) => { copyFromChannel(inputBuffer, parameters, name, numberOfInputChannels + index, i); }); } for (let j = 0; j < options.numberOfInputs; j += 1) { for (let k = 0; k < outputChannelCount[j]; k += 1) { // The byteLength will be 0 when the ArrayBuffer was transferred. if (outputs[j][k].byteLength === 0) { outputs[j][k] = new Float32Array(128); } } } try { const potentiallyEmptyInputs = inputs.map((input, index) => { const activeInput = activeInputs[index]; if (activeInput.size > 0) { activeInputIndexes.set(index, bufferSize / 128); return input; } const count = activeInputIndexes.get(index); if (count === undefined) { return []; } if (input.every((channelData) => channelData.every((sample) => sample === 0))) { if (count === 1) { activeInputIndexes.delete(index); } else { activeInputIndexes.set(index, count - 1); } } return input; }); const activeSourceFlag = exposeCurrentFrameAndCurrentTime( nativeContext.currentTime + i / nativeContext.sampleRate, nativeContext.sampleRate, () => (<IAudioWorkletProcessor>audioWorkletProcessor).process(potentiallyEmptyInputs, outputs, parameters) ); isActive = activeSourceFlag; for (let j = 0, outputChannelSplitterNodeOutput = 0; j < options.numberOfOutputs; j += 1) { for (let k = 0; k < outputChannelCount[j]; k += 1) { copyToChannel(outputBuffer, outputs[j], k, outputChannelSplitterNodeOutput + k, i); } outputChannelSplitterNodeOutput += outputChannelCount[j]; } } catch (error) { isActive = false; nativeAudioWorkletNodeFaker.dispatchEvent( new ErrorEvent('processorerror', { colno: error.colno, filename: error.filename, lineno: error.lineno, message: error.message }) ); } if (!isActive) { for (let j = 0; j < options.numberOfInputs; j += 1) { gainNodes[j].disconnect(inputChannelSplitterNodes[j]); for (let k = 0; k < options.channelCount; k += 1) { inputChannelSplitterNodes[i].disconnect(inputChannelMergerNode, k, j * options.channelCount + k); } } if (processorConstructor.parameterDescriptors !== undefined) { const length = processorConstructor.parameterDescriptors.length; for (let j = 0; j < length; j += 1) { const constantSourceNode = constantSourceNodes[j]; constantSourceNode.disconnect(inputChannelMergerNode, 0, numberOfInputChannels + j); constantSourceNode.stop(); } } inputChannelMergerNode.disconnect(scriptProcessorNode); scriptProcessorNode.onaudioprocess = null; // tslint:disable-line:deprecation if (isConnected) { disconnectOutputsGraph(); } else { disconnectFakeGraph(); } break; } } } }; let isConnected = false; // Bug #87: Only Firefox will fire an AudioProcessingEvent if there is no connected output. const nativeGainNode = createNativeGainNode(nativeContext, { channelCount: 1, channelCountMode: 'explicit', channelInterpretation: 'discrete', gain: 0 }); const connectFakeGraph = () => scriptProcessorNode.connect(nativeGainNode).connect(nativeContext.destination); const disconnectFakeGraph = () => { scriptProcessorNode.disconnect(nativeGainNode); nativeGainNode.disconnect(); }; const whenConnected = () => { if (isActive) { disconnectFakeGraph(); if (options.numberOfOutputs > 0) { scriptProcessorNode.connect(outputChannelSplitterNode); } for (let i = 0, outputChannelSplitterNodeOutput = 0; i < options.numberOfOutputs; i += 1) { const outputChannelMergerNode = outputChannelMergerNodes[i]; for (let j = 0; j < outputChannelCount[i]; j += 1) { outputChannelSplitterNode.connect(outputChannelMergerNode, outputChannelSplitterNodeOutput + j, j); } outputChannelSplitterNodeOutput += outputChannelCount[i]; } } isConnected = true; }; const whenDisconnected = () => { if (isActive) { connectFakeGraph(); disconnectOutputsGraph(); } isConnected = false; }; connectFakeGraph(); return monitorConnections(nativeAudioWorkletNodeFaker, whenConnected, whenDisconnected); }; };
the_stack
import { Server, WebSocket } from "mock-socket"; import { StateTransitionError, TransportState } from "../../../../src/api"; import { LoggerFactory } from "../../../../src/core"; import { Transport } from "../../../../src/platform/web"; import { EmitterSpy, makeEmitterSpy } from "../../../support/api/emitter-spy"; import { soon } from "../../../support/api/utils"; /** * Transport Unit Tests * * The approach here is to traverse all of the possible paths through * the finite state machine (FSM) which the transport implements. * We consider the FSM as a directed acyclic graph (even though it is cyclic) * by considering all paths through the FSM from "Disconnected" which arrive * back a "Disconnected" as comprising the entire acyclic graph. */ describe("Web Transport", () => { const connectionTimeout = 5; // seconds // The mock WebSocket implements a 4 ms delay implemented via setTimeout on connect // (so the callbacks can get setup before being called), close and send. So we need // to wait 5 ms before we can expect the onopen callback, for example, to be called. const serverDelay = 5; // milliseconds const server = "wss://localhost:8080"; const log = new LoggerFactory(); const logger = log.getLogger("sip.Transport"); const sendMessage = "just some bits"; const onConnectMock = jasmine.createSpy("onConnect"); const onDisconnectMock = jasmine.createSpy("onDisconnect"); const onMessageMock = jasmine.createSpy("onMessage"); let mockServer: Server; let mockServerWebSocket: WebSocket | undefined; let mockServerReceivedMessage: string | undefined; let transport: Transport; let transportStateSpy: EmitterSpy<TransportState>; let connectPromise: Promise<void> | undefined; let disconnectPromise: Promise<void> | undefined; let sendPromise: Promise<void> | undefined; beforeEach(() => { jasmine.clock().install(); initServer(); transport = new Transport(logger, { connectionTimeout, server }); transportStateSpy = makeEmitterSpy(transport.stateChange, logger); transport.onConnect = onConnectMock; transport.onDisconnect = onDisconnectMock; transport.onMessage = onMessageMock; }); afterEach(() => { transport.dispose(); mockServer.stop(); jasmine.clock().uninstall(); }); describe("Construct Transport", () => { // Construct the transport. constructTransport(); // The transport should now be in the Disconnected state, so traverse the FSM. traverseTransportStateMachine(); }); function initServer(): void { if (mockServer) { mockServer.close(); mockServerWebSocket = undefined; } mockServer = new Server(server, { selectProtocol: (protocols: Array<string>): string => "sip" }); mockServer.on("connection", (socket) => { logger.log("Mock WebSocket Server: incoming connection"); mockServerWebSocket = socket; socket.on("message", (receivedMessage) => { if (typeof receivedMessage !== "string") { throw new Error("Mock WebSocket Server received message not of type string."); } logger.log(`Mock WebSocket Server: received message "${receivedMessage}"`); mockServerReceivedMessage = receivedMessage; }); socket.on("close", () => { logger.log("Mock WebSocket Server: server closed"); }); }); } function resetAll(): void { resetMockServer(); resetPromises(); resetSpies(); } function resetMockServer(): void { mockServerReceivedMessage = undefined; } function resetPromises(): void { connectPromise = undefined; disconnectPromise = undefined; sendPromise = undefined; } function resetSpies(): void { onConnectMock.calls.reset(); onDisconnectMock.calls.reset(); onMessageMock.calls.reset(); transportStateSpy.calls.reset(); } function constructTransport(): void { it("protocol MUST be WSS", () => { expect(transport.protocol).toBe("WSS"); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); expect(onMessageMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); } /** * Run the suite of transport tests at each "node" of the transport FSM (see api/transport.ts). * * Traverses the entire transport FSM via the following state paths... * * 0. Disconnected * * 1. Disconnected -> Connecting * 1a. Disconnected -> Connecting -> Disconnected (network disconnected) -> TERMINAL * * 2. Disconnected -> Connecting -> Disconnecting * 2a. Disconnected -> Connecting -> Disconnecting -> Disconnected (network disconnected) -> TERMINAL * 2b. Disconnected -> Connecting -> Disconnecting -> Disconnected -> TERMINAL * * 3. Disconnected -> Connecting -> Connected * 3a. Disconnected -> Connecting -> Connected -> Disconnected (network) -> TERMINAL * * 4. Disconnected -> Connecting -> Connected -> Disconnecting * 4a. Disconnected -> Connecting -> Connected -> Disconnecting -> Disconnected (network disconnected) -> TERMINAL * 4b. Disconnected -> Connecting -> Connected -> Disconnecting -> Disconnected -> TERMINAL * * Traversal stops upon reaching the Disconnected state (which is where it starts), * but may continue on recursively for some number of cycles - two (2) by default * so that returning to initial state is tested. * * @param cycles - The number of times to cycle through the FSM. * @param cyclesCompleted - The number of cycles completed. */ function traverseTransportStateMachine(cycles = 2, cyclesCompleted = 0): void { if (cyclesCompleted === cycles) { return; } // 0. Disconnected describe(`Traverse FSM (${cyclesCompleted + 1} of ${cycles})`, () => { // The transport state is now Disconnected, run the test suite transportSuiteIn(TransportState.Disconnected); // 1. Disconnected -> Connecting describe(".connect in Disconnected state to Connecting state", () => { // Connect to network by calling connect() but not waiting for promise to resolve connectIn(TransportState.Disconnected); // The transport state is now Connecting, run the test suite transportSuiteIn(TransportState.Connecting); // 1a. Disconnected -> Connecting -> Disconnected (network disconnected) describe("Server close in Connecting state to Disconnected state", () => { // Disconnect network serverCloseIn(TransportState.Connecting); // TERMINAL: The transport state is now back to Disconnected, so we are at a terminal and may recurse... traverseTransportStateMachine(cycles, cyclesCompleted + 1); }); // 2. Disconnected -> Connecting -> Disconnecting describe(".disconnect in Connecting state to Disconnecting state", () => { // Disconnect from the network by calling disconnect() but not waiting for promise to resolve disconnectIn(TransportState.Connecting); // The transport state is now Disconnecting, run the test suite transportSuiteIn(TransportState.Disconnecting); // 2a. Disconnected -> Connecting -> Disconnecting -> Disconnected (network disconnected) describe("Server close in Disconnecting state to Disconnecting state", () => { // Disconnect network serverCloseIn(TransportState.Disconnecting); // TERMINAL: The transport state is now back to Disconnected, so we are at a terminal and may recurse... traverseTransportStateMachine(cycles, cyclesCompleted + 1); }); }); // 2b. Disconnected -> Connecting -> Disconnecting -> Disconnected describe(".disconnect in Connecting state to Disconnecting state resolves to Disconnected state", () => { // Disconnect from the network by calling disconnect() but not waiting for promise to resolve disconnectAcceptedCompletesIn(TransportState.Connecting); // TERMINAL: The transport state is now back to Disconnected, so we are at a terminal and may recurse... traverseTransportStateMachine(cycles, cyclesCompleted + 1); }); }); // 3. Disconnected -> Connecting -> Connected describe(".connect in Disconnected state resolves to Connected state", () => { // Connect to network by calling connect() and waiting for promise to resolve connectAcceptedCompletesIn(TransportState.Disconnected); // The transport state is now Connected, run the test suite transportSuiteIn(TransportState.Connected); // 3a. Disconnected -> Connecting -> Connected -> Disconnected (network disconnected) describe("Server close in Connected state to Disconnected state", () => { // Disconnect network serverCloseIn(TransportState.Connected); // TERMINAL: The transport state is now back to Disconnected, so we are at a terminal and may recurse... traverseTransportStateMachine(cycles, cyclesCompleted + 1); }); // 4. Disconnected -> Connecting -> Connected -> Disconnecting describe(".disconnect in Connected state to Disconnecting state", () => { // Disconnect from the network by calling disconnect() but not waiting for promise to resolve disconnectIn(TransportState.Connected); // The transport state is now Disconnecting, run the test suite transportSuiteIn(TransportState.Disconnecting); // 4a. Disconnected -> Connecting -> Connected -> Disconnecting -> Disconnected (network disconnected) describe("Server close in Disconnecting state to Disconnected state", () => { // Disconnect network serverCloseIn(TransportState.Disconnecting); // TERMINAL: The transport state is now back to Disconnected, so we are at a terminal and may recurse... traverseTransportStateMachine(cycles, cyclesCompleted + 1); }); }); // 4b. Disconnected -> Connecting -> Connected -> Disconnecting -> Disconnected describe(".disconnect in Connected state to Disconnecting state resolves to Disconnected state", () => { // Disconnect from the network by calling disconnect() but not waiting for promise to resolve disconnectAcceptedCompletesIn(TransportState.Connected); // TERMINAL: The transport state is now back to Disconnected, so we are at a terminal and may recurse... traverseTransportStateMachine(cycles, cyclesCompleted + 1); }); }); }); } function transportSuiteIn(state: TransportState): void { it(`assert transport state is ${state}`, () => { expect(transport.state).toBe(state); }); sendSuiteIn(state); disconnectSuiteIn(state); connectSuiteIn(state); describe(`callbacks fail calling .connect`, () => { function assertLoopDetected(error: Error): void { if (error instanceof StateTransitionError) { return; } throw error; } beforeEach(() => { onConnectMock.and.callFake(() => transport.connect().catch((error: Error) => assertLoopDetected(error))); onDisconnectMock.and.callFake(() => transport.connect().catch((error: Error) => assertLoopDetected(error))); onMessageMock.and.callFake(() => transport.connect().catch((error: Error) => assertLoopDetected(error))); }); afterEach(() => { onConnectMock.and.stub(); onDisconnectMock.and.stub(); onMessageMock.and.stub(); }); // Running the entire suite of tests is not necessary // connectSuiteIn(state); // disconnectSuiteIn(state); // This subset tests what we are looking to test describe(`.connect accepted in ${state} state completes`, () => { connectAcceptedCompletesIn(state); }); describe(`.disconnect accepted in ${state} state completes`, () => { disconnectAcceptedCompletesIn(state); }); }); describe(`callbacks fail calling .disconnect`, () => { function assertLoopDetected(error: Error): void { if (error instanceof StateTransitionError) { return; } throw error; } beforeEach(() => { onConnectMock.and.callFake(() => transport.disconnect().catch((error: Error) => assertLoopDetected(error))); onDisconnectMock.and.callFake(() => transport.disconnect().catch((error: Error) => assertLoopDetected(error))); onMessageMock.and.callFake(() => transport.disconnect().catch((error: Error) => assertLoopDetected(error))); }); afterEach(() => { onConnectMock.and.stub(); onDisconnectMock.and.stub(); onMessageMock.and.stub(); }); // Running the entire suite of tests is not necessary // connectSuiteIn(state); // disconnectSuiteIn(state); // This subset tests what we are looking to test describe(`.connect accepted in ${state} state completes`, () => { connectAcceptedCompletesIn(state); }); describe(`.disconnect accepted in ${state} state completes`, () => { disconnectAcceptedCompletesIn(state); }); }); } function connectIn(state: TransportState): void { let connectError: Error | undefined; beforeEach(() => { resetAll(); connectPromise = transport.connect().catch((error: Error) => { connectError = error; }); }); switch (state) { case TransportState.Connecting: it("state MUST be 'Connecting'", () => { expect(transport.state).toBe(TransportState.Connecting); }); it("state MUST not transition", () => { expect(transportStateSpy).not.toHaveBeenCalled(); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Connected: it("state MUST be 'Connected'", () => { expect(transport.state).toBe(TransportState.Connected); }); it("state MUST not transition", () => { expect(transportStateSpy).not.toHaveBeenCalled(); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be true", () => { expect(transport.isConnected()).toBe(true); }); break; case TransportState.Disconnecting: it("state MUST be 'Connecting'", () => { expect(transport.state).toBe(TransportState.Connecting); }); it("state MUST transition to 'Connecting'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnected: it("state MUST be 'Connecting'", () => { expect(transport.state).toBe(TransportState.Connecting); }); it("state MUST transition to 'Connecting'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; default: throw new Error("Unknown state."); } } function connectDisconnectIn(state: TransportState): void { let connectError: Error | undefined; let disconnectError: Error | undefined; beforeEach(() => { resetAll(); connectPromise = transport.connect().catch((error: Error) => { connectError = error; }); disconnectPromise = transport.disconnect().catch((error: Error) => { disconnectError = error; }); }); switch (state) { case TransportState.Connecting: it("state MUST be 'Disconnecting'", () => { expect(transport.state).toBe(TransportState.Disconnecting); }); it("state MUST transition to 'Disconnecting'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnecting]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Connected: it("state MUST be 'Disconnecting'", () => { expect(transport.state).toBe(TransportState.Disconnecting); }); it("state MUST transition to 'Disconnecting'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnecting]); }); it("callback 'onDisconnect' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(1); }); it("'onDisconnect' MUST NOT have Error", () => { expect(onDisconnectMock.calls.argsFor(0).length).toEqual(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnecting: it("state MUST be 'Disconnecting'", () => { expect(transport.state).toBe(TransportState.Disconnecting); }); it("state MUST transition to 'Connecting', 'Disconnecting'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Disconnecting]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnected: it("state MUST be 'Disconnecting'", () => { expect(transport.state).toBe(TransportState.Disconnecting); }); it("state MUST transition to 'Connecting', 'Disconnecting'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Disconnecting]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; default: throw new Error("Unknown state."); } } function connectDisconnectCompletesIn(state: TransportState): void { let connectError: Error | undefined; let disconnectError: Error | undefined; beforeEach(async () => { resetAll(); connectPromise = transport.connect().catch((error: Error) => { connectError = error; }); disconnectPromise = transport.disconnect().catch((error: Error) => { disconnectError = error; }); await soon(serverDelay); }); switch (state) { case TransportState.Connecting: it("connect error MUST be thrown", () => { expect(connectError).toEqual(jasmine.any(Error)); expect(disconnectError).toEqual(undefined); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Connected: it("error MUST NOT be thrown", () => { expect(connectError).toEqual(undefined); expect(disconnectError).toEqual(undefined); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("callback 'onDisconnect' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(1); }); it("'onDisconnect' MUST NOT have Error", () => { expect(onDisconnectMock.calls.argsFor(0).length).toEqual(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnecting: it("connect error MUST be thrown", () => { expect(connectError).toEqual(jasmine.any(Error)); expect(disconnectError).toEqual(undefined); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnected: it("connect error MUST be thrown", () => { expect(connectError).toEqual(jasmine.any(Error)); expect(disconnectError).toEqual(undefined); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; default: throw new Error("Unknown state."); } } function connectRejectedCompletesIn(state: TransportState): void { let connectError: Error | undefined; beforeEach(async () => { resetAll(); // Server rejects connection // eslint-disable-next-line @typescript-eslint/no-explicit-any (mockServer.options as any) = { selectProtocol: (protocols: Array<string>): string => "invalid" }; connectPromise = transport.connect().catch((error: Error) => { connectError = error; }); await soon(serverDelay); }); switch (state) { case TransportState.Connecting: it("connect error MUST be thrown", () => { expect(connectError).toEqual(jasmine.any(Error)); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST transition to 'Disconnected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnected]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Connected: it("error MUST NOT be thrown", () => { expect(connectError).toEqual(undefined); }); it("state MUST be 'Connected'", () => { expect(transport.state).toBe(TransportState.Connected); }); it("state MUST not transition", () => { expect(transportStateSpy).not.toHaveBeenCalled(); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be true", () => { expect(transport.isConnected()).toBe(true); }); break; case TransportState.Disconnecting: it("error MUST be thrown", () => { expect(connectError).toEqual(jasmine.any(Error)); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST transition to 'Connecting', 'Disconnected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Disconnected]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnected: it("error MUST be thrown", () => { expect(connectError).toEqual(jasmine.any(Error)); }); it("state MUST be Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST transition to 'Connecting', 'Disconnected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Disconnected]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; default: throw new Error("Unknown state."); } } function connectTimeoutCompletesIn(state: TransportState): void { let openBlocked: boolean; let connectError: Error | undefined; beforeEach(async () => { openBlocked = false; resetAll(); // HACK: prevent the transport from processing the WebSocket.onopen callback // eslint-disable-next-line @typescript-eslint/no-explicit-any (transport as any).onWebSocketOpen = (ev: Event, ws: WebSocket): void => { openBlocked = true; return; }; connectPromise = transport.connect().catch((error: Error) => { connectError = error; }); await soon(serverDelay); await soon(connectionTimeout * 1000); }); switch (state) { case TransportState.Connecting: it("assert open blocked (hack for test working)", () => { expect(openBlocked).toEqual(true); }); it("connect error MUST be thrown", () => { expect(connectError).toEqual(jasmine.any(Error)); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST transition to 'Disconnected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnected]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Connected: it("assert open not blocked (hack for test working)", () => { expect(openBlocked).toEqual(false); }); it("error MUST NOT be thrown", () => { expect(connectError).toEqual(undefined); }); it("state MUST be 'Connected'", () => { expect(transport.state).toBe(TransportState.Connected); }); it("state MUST not transition", () => { expect(transportStateSpy).not.toHaveBeenCalled(); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be true", () => { expect(transport.isConnected()).toBe(true); }); break; case TransportState.Disconnecting: it("assert open blocked (hack for test working)", () => { expect(openBlocked).toEqual(true); }); it("error MUST be thrown", () => { expect(connectError).toEqual(jasmine.any(Error)); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST transition to 'Connecting', 'Disconnected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Disconnected]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnected: it("assert open blocked (hack for test working)", () => { expect(openBlocked).toEqual(true); }); it("error MUST be thrown", () => { expect(connectError).toEqual(jasmine.any(Error)); }); it("state MUST be Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST transition to 'Connecting', 'Disconnected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Disconnected]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; default: throw new Error("Unknown state."); } } function connectAcceptedCompletesIn(state: TransportState): void { let connectError: Error | undefined; beforeEach(async () => { resetAll(); connectPromise = transport.connect().catch((error: Error) => { connectError = error; }); await soon(serverDelay); }); switch (state) { case TransportState.Connecting: it("error MUST NOT be thrown", () => { expect(connectError).toEqual(undefined); }); it("state MUST be 'Connected'", () => { expect(transport.state).toBe(TransportState.Connected); }); it("state MUST transition to 'Connected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connected]); }); it("callback 'onConnect' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(1); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be true", () => { expect(transport.isConnected()).toBe(true); }); break; case TransportState.Connected: it("error MUST NOT be thrown", () => { expect(connectError).toEqual(undefined); }); it("state MUST be 'Connected'", () => { expect(transport.state).toBe(TransportState.Connected); }); it("state MUST not transition", () => { expect(transportStateSpy).not.toHaveBeenCalled(); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be true", () => { expect(transport.isConnected()).toBe(true); }); break; case TransportState.Disconnecting: it("error MUST NOT be thrown", () => { expect(connectError).toEqual(undefined); }); it("state MUST be 'Connected'", () => { expect(transport.state).toBe(TransportState.Connected); }); it("state MUST transition to 'Connecting', 'Connected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Connected]); }); it("callback 'onConnect' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(1); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be true", () => { expect(transport.isConnected()).toBe(true); }); break; case TransportState.Disconnected: it("error MUST NOT be thrown", () => { expect(connectError).toEqual(undefined); }); it("state MUST be 'Connected'", () => { expect(transport.state).toBe(TransportState.Connected); }); it("state MUST transition to 'Connecting', 'Connected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Connected]); }); it("callback 'onConnect' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(1); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be true", () => { expect(transport.isConnected()).toBe(true); }); break; default: throw new Error("Unknown state."); } } function connectSuiteIn(state: TransportState): void { describe(`.connect in ${state} state`, () => { connectIn(state); }); describe(`.connect .disconnect in ${state} state`, () => { connectDisconnectIn(state); }); describe(`.connect .disconnect in ${state} state completes`, () => { connectDisconnectCompletesIn(state); }); describe(`.connect rejected in ${state} state completes`, () => { connectRejectedCompletesIn(state); }); describe(`.connect timeout in ${state} state completes`, () => { connectTimeoutCompletesIn(state); }); describe(`.connect accepted in ${state} state completes`, () => { connectAcceptedCompletesIn(state); }); } function disconnectIn(state: TransportState): void { let disconnectError: Error | undefined; beforeEach(() => { resetAll(); disconnectPromise = transport.disconnect().catch((error: Error) => { disconnectError = error; }); }); switch (state) { case TransportState.Connecting: it("state MUST be 'Disconnecting'", () => { expect(transport.state).toBe(TransportState.Disconnecting); }); it("state MUST transition to 'Disconnecting'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnecting]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Connected: it("state MUST be 'Disconnecting'", () => { expect(transport.state).toBe(TransportState.Disconnecting); }); it("state MUST transition to 'Disconnecting'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnecting]); }); it("callback 'onDisconnect' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(1); }); it("'onDisconnect' MUST NOT have Error", () => { expect(onDisconnectMock.calls.argsFor(0).length).toEqual(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnecting: it("state MUST be 'Disconnecting'", () => { expect(transport.state).toBe(TransportState.Disconnecting); }); it("state MUST not transition", () => { expect(transportStateSpy).not.toHaveBeenCalled(); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnected: it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST not transition", () => { expect(transportStateSpy).not.toHaveBeenCalled(); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; default: throw new Error("Unknown state."); } } function disconnectConnectIn(state: TransportState): void { let connectError: Error | undefined; let disconnectError: Error | undefined; beforeEach(() => { resetAll(); disconnectPromise = transport.disconnect().catch((error: Error) => { disconnectError = error; }); connectPromise = transport.connect().catch((error: Error) => { connectError = error; }); }); switch (state) { case TransportState.Connecting: it("state MUST be 'Connecting'", () => { expect(transport.state).toBe(TransportState.Connecting); }); it("state MUST transition to 'Disconnecting', 'Connecting'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Connecting]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Connected: it("state MUST be 'Connecting'", () => { expect(transport.state).toBe(TransportState.Connecting); }); it("state MUST transition to 'Disconnecting', 'Connecting'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Connecting]); }); it("callback 'onDisconnect' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(1); }); it("'onDisconnect' MUST NOT have Error", () => { expect(onDisconnectMock.calls.argsFor(0).length).toEqual(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnecting: it("state MUST be 'Connecting'", () => { expect(transport.state).toBe(TransportState.Connecting); }); it("state MUST transition to 'Connecting'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnected: it("state MUST be 'Connecting'", () => { expect(transport.state).toBe(TransportState.Connecting); }); it("state MUST transition to 'Connecting'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; default: throw new Error("Unknown state."); } } function disconnectConnectCompletesIn(state: TransportState): void { let connectError: Error | undefined; let disconnectError: Error | undefined; beforeEach(async () => { resetAll(); disconnectPromise = transport.disconnect().catch((error: Error) => { disconnectError = error; }); connectPromise = transport.connect().catch((error: Error) => { connectError = error; }); await soon(serverDelay); }); switch (state) { case TransportState.Connecting: it("disconnect error MUST be thrown", () => { expect(connectError).toEqual(undefined); expect(disconnectError).toEqual(jasmine.any(Error)); }); it("state MUST be 'Connected'", () => { expect(transport.state).toBe(TransportState.Connected); }); it("state MUST transition to 'Disconnecting', 'Connecting', 'Connected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(3); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Connecting]); expect(transportStateSpy.calls.argsFor(2)).toEqual([TransportState.Connected]); }); it("callback 'onConnect' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(1); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be true", () => { expect(transport.isConnected()).toBe(true); }); break; case TransportState.Connected: it("disconnect error MUST be thrown", () => { expect(connectError).toEqual(undefined); expect(disconnectError).toEqual(jasmine.any(Error)); }); it("state MUST be 'Connected'", () => { expect(transport.state).toBe(TransportState.Connected); }); it("state MUST transition to 'Disconnecting', 'Connecting', 'Connected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(3); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Connecting]); expect(transportStateSpy.calls.argsFor(2)).toEqual([TransportState.Connected]); }); it("callback 'onDisconnect' 'onConnected' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(1); expect(onDisconnectMock).toHaveBeenCalledTimes(1); }); it("'onDisconnect' MUST NOT have Error", () => { expect(onDisconnectMock.calls.argsFor(0).length).toEqual(0); }); it("isConnected MUST be true", () => { expect(transport.isConnected()).toBe(true); }); break; case TransportState.Disconnecting: it("disconnect error MUST be thrown", () => { expect(connectError).toEqual(undefined); expect(disconnectError).toEqual(jasmine.any(Error)); }); it("state MUST be 'Connected'", () => { expect(transport.state).toBe(TransportState.Connected); }); it("state MUST transition to 'Connecting', 'Connected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Connected]); }); it("callback 'onConnect' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(1); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be true", () => { expect(transport.isConnected()).toBe(true); }); break; case TransportState.Disconnected: it("error MUST NOT be thrown", () => { expect(connectError).toEqual(undefined); expect(disconnectError).toEqual(undefined); }); it("state MUST be 'Connected'", () => { expect(transport.state).toBe(TransportState.Connected); }); it("state MUST transition to 'Connecting', 'Connected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Connecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Connected]); }); it("callback 'onConnect' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(1); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be true", () => { expect(transport.isConnected()).toBe(true); }); break; default: throw new Error("Unknown state."); } } function disconnectAcceptedCompletesIn(state: TransportState): void { let disconnectError: Error | undefined; beforeEach(async () => { resetAll(); disconnectPromise = transport.disconnect().catch((error: Error) => { disconnectError = error; }); await soon(serverDelay); }); switch (state) { case TransportState.Connecting: it("error MUST NOT be thrown", () => { expect(disconnectError).toEqual(undefined); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST transition to 'Disconnecting', 'Disconnected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Disconnected]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Connected: it("error MUST NOT be thrown", () => { expect(disconnectError).toEqual(undefined); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST transition to 'Disconnecting', 'Disconnected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(2); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnecting]); expect(transportStateSpy.calls.argsFor(1)).toEqual([TransportState.Disconnected]); }); it("callback 'onDisconnect' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(1); }); it("'onDisconnect' MUST NOT have Error", () => { expect(onDisconnectMock.calls.argsFor(0).length).toEqual(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnecting: it("error MUST NOT be thrown", () => { expect(disconnectError).toEqual(undefined); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST transition to 'Disconnected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnected]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnected: it("error MUST NOT be thrown", () => { expect(disconnectError).toEqual(undefined); }); it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST not transition", () => { expect(transportStateSpy).not.toHaveBeenCalled(); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; default: throw new Error("Unknown state."); } } function disconnectSuiteIn(state: TransportState): void { describe(`.disconnect in ${state} state`, () => { disconnectIn(state); }); describe(`.disconnect .connect in ${state} state`, () => { disconnectConnectIn(state); }); describe(`.disconnect .connect in ${state} state completes`, () => { disconnectConnectCompletesIn(state); }); describe(`.disconnect accepted in ${state} state completes`, () => { disconnectAcceptedCompletesIn(state); }); } function sendIn(state: TransportState): void { let sendError: Error | undefined; beforeEach(() => { resetAll(); sendPromise = transport.send(sendMessage).catch((error: Error) => { sendError = error; }); }); switch (state) { case TransportState.Connecting: it("state MUST be 'Connecting'", () => { expect(transport.state).toBe(TransportState.Connecting); }); break; case TransportState.Connected: it("state MUST be 'Connected'", () => { expect(transport.state).toBe(TransportState.Connected); }); break; case TransportState.Disconnecting: it("state MUST be 'Disconnecting'", () => { expect(transport.state).toBe(TransportState.Disconnecting); }); break; case TransportState.Disconnected: it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); break; default: throw new Error("Unknown state."); } } function sendCompletesIn(state: TransportState): void { let sendError: Error | undefined; beforeEach(async () => { resetAll(); sendPromise = transport.send(sendMessage).catch((error: Error) => { sendError = error; }); await soon(serverDelay); }); if (state === TransportState.Connected) { it("Error MUST NOT be thrown", () => { expect(sendError).toEqual(undefined); }); it("Message sent should match message received", () => { expect(mockServerReceivedMessage).toEqual(sendMessage); }); } else { it("Error MUST be thrown", () => { expect(sendError).toEqual(jasmine.any(Error)); }); } } function sendServerCompletesIn(state: TransportState): void { beforeEach(async () => { resetAll(); if (mockServerWebSocket) { mockServerWebSocket.send(sendMessage); } await soon(serverDelay); }); if (state === TransportState.Connected) { it("Message sent should match message received", () => { expect(onMessageMock).toHaveBeenCalledTimes(1); expect(onMessageMock.calls.argsFor(0)).toEqual([sendMessage]); }); } else { it("Message callback MUST NOT have been called", () => { expect(onMessageMock).toHaveBeenCalledTimes(0); }); } } function sendSuiteIn(state: TransportState): void { describe(`.send in ${state} state`, () => { sendIn(state); }); describe(`.send in ${state} state completes`, () => { sendCompletesIn(state); }); describe(`.onMessage in ${state} state`, () => { sendServerCompletesIn(state); }); } function serverCloseIn(state: TransportState): void { beforeEach(() => { resetAll(); initServer(); // closes and restarts mock server }); switch (state) { case TransportState.Connecting: it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST transition to 'Disconnected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnected]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); expect(onMessageMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Connected: it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST transition to 'Disconnected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnected]); }); it("callback 'onDisconnect' MUST have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(1); expect(onMessageMock).toHaveBeenCalledTimes(0); }); it("'onDisconnect' MUST have Error", () => { expect(onDisconnectMock.calls.argsFor(0)).toEqual([jasmine.any(Error)]); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnecting: it("state MUST be 'Disconnected'", () => { expect(transport.state).toBe(TransportState.Disconnected); }); it("state MUST transition to 'Disconnected'", () => { expect(transportStateSpy).toHaveBeenCalledTimes(1); expect(transportStateSpy.calls.argsFor(0)).toEqual([TransportState.Disconnected]); }); it("callbacks MUST NOT have been called", () => { expect(onConnectMock).toHaveBeenCalledTimes(0); expect(onDisconnectMock).toHaveBeenCalledTimes(0); expect(onMessageMock).toHaveBeenCalledTimes(0); }); it("isConnected MUST be false", () => { expect(transport.isConnected()).toBe(false); }); break; case TransportState.Disconnected: // should not be able to get here it(`assert prior state was not Disconnected`, () => { expect(state).not.toBe(TransportState.Disconnected); }); break; default: throw new Error("Unknown state."); } } });
the_stack
namespace egret { /** * @class egret.GlowFilter * @classdesc * 使用 GlowFilter 类可以对显示对象应用发光效果。在投影滤镜的 distance 和 angle 属性设置为 0 时,发光滤镜与投影滤镜极为相似。 * @extends egret.Filter * @version Egret 3.1.4 * @platform Web,Native */ export class GlowFilter extends Filter { /** * @private */ public $red:number; /** * @private */ public $green:number; /** * @private */ public $blue:number; /** * Initializes a new GlowFilter instance. * @method egret.GlowFilter#constructor * @param color {number} The color of the glow. Valid values are in the hexadecimal format 0xRRGGBB. The default value is 0xFF0000. * @param alpha {number} The alpha transparency value for the color. Valid values are 0 to 1. For example, .25 sets a transparency value of 25%. The default value is 1. * @param blurX {number} The amount of horizontal blur. Valid values are 0 to 255 (floating point). * @param blurY {number} The amount of vertical blur. Valid values are 0 to 255 (floating point). * @param strength {number} The strength of the imprint or spread. The higher the value, the more color is imprinted and the stronger the contrast between the glow and the background. Valid values are 0 to 255. * @param quality {number} The number of times to apply the filter. * @param inner {boolean} Specifies whether the glow is an inner glow. The value true indicates an inner glow. The default is false, an outer glow (a glow around the outer edges of the object). * @param knockout {number} Specifies whether the object has a knockout effect. A value of true makes the object's fill transparent and reveals the background color of the document. The default value is false (no knockout effect). * @version Egret 3.1.4 * @platform Web * @language en_US */ /** * 初始化 GlowFilter 对象 * @method egret.GlowFilter#constructor * @param color {number} 光晕颜色,采用十六进制格式 0xRRGGBB。默认值为 0xFF0000。 * @param alpha {number} 颜色的 Alpha 透明度值。有效值为 0 到 1。例如,0.25 设置透明度值为 25%。 * @param blurX {number} 水平模糊量。有效值为 0 到 255(浮点)。 * @param blurY {number} 垂直模糊量。有效值为 0 到 255(浮点)。 * @param strength {number} 印记或跨页的强度。该值越高,压印的颜色越深,而且发光与背景之间的对比度也越强。有效值为 0 到 255。 * @param quality {number} 应用滤镜的次数。暂未实现。 * @param inner {boolean} 指定发光是否为内侧发光。值 true 指定发光是内侧发光。值 false 指定发光是外侧发光(对象外缘周围的发光)。 * @param knockout {number} 指定对象是否具有挖空效果。值为 true 将使对象的填充变为透明,并显示文档的背景颜色。 * @version Egret 3.1.4 * @platform Web * @language zh_CN */ constructor(color:number = 0xFF0000, alpha:number = 1.0, blurX:number = 6.0, blurY:number = 6.0, strength:number = 2, quality:number = 1, inner:boolean = false, knockout:boolean = false) { super(); let self = this; self.type = "glow"; self.$color = color; self.$blue = color & 0x0000FF; self.$green = (color & 0x00ff00) >> 8; self.$red = color >> 16; self.$alpha = alpha; self.$blurX = blurX; self.$blurY = blurY; self.$strength = strength; self.$quality = quality; self.$inner = inner; self.$knockout = knockout; self.$uniforms.color = {x: this.$red / 255, y: this.$green / 255, z: this.$blue / 255, w: 1}; self.$uniforms.alpha = alpha; self.$uniforms.blurX = blurX; self.$uniforms.blurY = blurY; self.$uniforms.strength = strength; // this.$uniforms.quality = quality; self.$uniforms.inner = inner ? 1 : 0; self.$uniforms.knockout = knockout ? 0 : 1; self.$uniforms.dist = 0; self.$uniforms.angle = 0; self.$uniforms.hideObject = 0; self.onPropertyChange(); } /** * @private */ public $color:number; /** * The color of the glow. * @version Egret 3.1.4 * @platform Web * @language en_US */ /** * 光晕颜色。 * @version Egret 3.1.4 * @platform Web * @language zh_CN */ public get color():number { return this.$color; } public set color(value:number) { if(this.$color == value) { return; } this.$color = value; this.$blue = value & 0x0000FF; this.$green = (value & 0x00ff00) >> 8; this.$red = value >> 16; this.$uniforms.color.x = this.$red / 255; this.$uniforms.color.y = this.$green / 255; this.$uniforms.color.z = this.$blue / 255; } /** * @private */ public $alpha:number; /** * The alpha transparency value for the color. * @version Egret 3.1.4 * @platform Web * @language en_US */ /** * 颜色的 Alpha 透明度值。 * @version Egret 3.1.4 * @platform Web * @language zh_CN */ public get alpha():number { return this.$alpha; } public set alpha(value:number) { if(this.$alpha == value) { return; } this.$alpha = value; this.$uniforms.alpha = value; } /** * @private */ public $blurX:number; /** * The amount of horizontal blur. * @version Egret 3.1.4 * @platform Web * @language en_US */ /** * 水平模糊量。 * @version Egret 3.1.4 * @platform Web * @language zh_CN */ public get blurX():number { return this.$blurX; } public set blurX(value:number) { let self = this; if(self.$blurX == value) { return; } self.$blurX = value; self.$uniforms.blurX = value; self.onPropertyChange(); } /** * @private */ public $blurY:number; /** * The amount of vertical blur. * @version Egret 3.1.4 * @platform Web * @language en_US */ /** * 垂直模糊量。 * @version Egret 3.1.4 * @platform Web * @language zh_CN */ public get blurY():number { return this.$blurY; } public set blurY(value:number) { let self = this; if(self.$blurY == value) { return; } self.$blurY = value; self.$uniforms.blurY = value; self.onPropertyChange(); } /** * @private */ public $strength:number; /** * The strength of the imprint or spread. * @version Egret 3.1.4 * @platform Web * @language en_US */ /** * 印记或跨页的强度。 * @version Egret 3.1.4 * @platform Web * @language zh_CN */ public get strength():number { return this.$strength; } public set strength(value:number) { if(this.$strength == value) { return; } this.$strength = value; this.$uniforms.strength = value; } /** * @private */ public $quality:number; /** * The number of times to apply the filter. * @version Egret 3.1.4 * @platform Web * @language en_US */ /** * 应用滤镜的次数。 * @version Egret 3.1.4 * @platform Web * @language zh_CN */ public get quality():number { return this.$quality; } public set quality(value:number) { if(this.$quality == value) { return; } this.$quality = value; } /** * @private */ public $inner:boolean; /** * Specifies whether the glow is an inner glow. * @version Egret 3.1.4 * @platform Web * @language en_US */ /** * 指定发光是否为内侧发光。 * @version Egret 3.1.4 * @platform Web * @language zh_CN */ public get inner():boolean { return this.$inner; } public set inner(value:boolean) { if(this.$inner == value) { return; } this.$inner = value; this.$uniforms.inner = value ? 1 : 0; } /** * @private */ public $knockout:boolean; /** * Specifies whether the object has a knockout effect. * @version Egret 3.1.4 * @platform Web * @language en_US */ /** * 指定对象是否具有挖空效果。 * @version Egret 3.1.4 * @platform Web * @language zh_CN */ public get knockout():boolean { return this.$knockout; } public set knockout(value:boolean) { if(this.$knockout == value) { return; } this.$knockout = value; this.$uniforms.knockout = value ? 0 : 1; } /** * @private */ public $toJson():string { return '{"color": ' + this.$color + ', "red": ' + this.$red + ', "green": ' + this.$green + ', "blue": ' + this.$blue + ', "alpha": ' + this.$alpha + ', "blurX": ' + this.$blurX + ', "blurY": ' + this.blurY + ', "strength": ' + this.$strength + ', "quality": ' + this.$quality + ', "inner": ' + this.$inner + ', "knockout": ' + this.$knockout + '}'; } protected updatePadding():void { let self = this; self.paddingLeft = self.blurX; self.paddingRight = self.blurX; self.paddingTop = self.blurY; self.paddingBottom = self.blurY; } } }
the_stack
declare namespace adone { /** * Filesystem Automation Streaming Templates/Transforms */ namespace fast { // File is based on vinyl typings // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/vinyl/index.d.ts namespace I { interface FileConstructorOptions { /** * The current workring directory of the file. Default: process.cwd() */ cwd?: string; /** * Full path to the file */ path?: string; /** * Stores the path history */ history?: string[]; /** * The result of a fs.Stat call */ stat?: fs.I.Stats; /** * File contents */ contents?: null | Buffer | nodestd.stream.Readable; /** * Used for relative pathing. Typically where a glob starts. Default: options.cwd */ base?: string; symlink?: string; } interface FileCloneOptions { contents?: boolean; deep?: boolean; } interface FileConstructor { new(options: FileConstructorOptions & { contents: Buffer }): BufferFile; new(options: FileConstructorOptions & { contents: nodestd.stream.Readable }): StreamFile; new(options?: FileConstructorOptions): NullFile; prototype: File; } interface File { /** * Gets and sets the contents of the file */ contents: null | Buffer | nodestd.stream.Readable; /** * Gets and sets current working directory. Will always be normalized and have trailing separators removed. */ cwd: string; /** * Gets and sets base directory. Used for relative pathing (typically where a glob starts). */ base: string; /** * Gets and sets the absolute pathname string or `undefined`. Setting to a different value * appends the new path to `file.history`. If set to the same value as the current path, it * is ignored. All new values are normalized and have trailing separators removed. */ path: string; stat: fs.I.Stats; /** * Gets the result of `path.relative(file.base, file.path)`. Or sets a new relative path for file.base */ relative: string; /** * Gets and sets the dirname of `file.path`. Will always be normalized and have trailing * separators removed. */ dirname: string; /** * Gets and sets the basename of `file.path`. */ basename: string; /** * Gets and sets extname of `file.path`. */ extname: string; /** * Gets and sets stem (filename without suffix) of `file.path`. */ stem: string; /** * Array of `file.path` values the file has had, from `file.history[0]` (original) * through `file.history[file.history.length - 1]` (current). `file.history` and its elements * should normally be treated as read-only and only altered indirectly by setting `file.path`. */ readonly history: ReadonlyArray<string>; /** * Gets and sets the path where the file points to if it's a symbolic link. Will always * be normalized and have trailing separators removed. */ symlink: string; /** * Returns a new File object with all attributes cloned. */ clone(options: FileCloneOptions & { contents: true }): this; clone(options?: FileCloneOptions): File; isBuffer(): boolean; isStream(): boolean; isNull(): boolean; isDirectory(): boolean; isSymbolic(): boolean; } interface NullFile extends File { contents: null; } interface BufferFile extends File { contents: Buffer; // } interface StreamFile extends File { contents: nodestd.stream.Readable; } type DirectoryFile = File; type SymbolicFile = File; /* tslint:disable-next-line:no-empty-interface */ interface Stream<S, T = File> extends stream.core.Stream<S, T> { // } } export const File: I.FileConstructor; namespace I { type CoreStreamSource = stream.core.I.Source<any, File>; interface LocalStreamConstructorOptions { /** * Whether to read files. Default: true */ read?: boolean; /** * Read files as buffers. Default: true */ buffer?: boolean; /** * Read files as streams */ stream?: boolean; /** * Current working directory for files. Default: process.cwd() */ cwd?: string; } interface LocalStreamConstructor { new(source: CoreStreamSource | File[], options: LocalStreamConstructorOptions & { read: false }): LocalStream<NullFile>; new(source: CoreStreamSource | File[], options: LocalStreamConstructorOptions & { stream: true }): LocalStream<StreamFile>; new(source: CoreStreamSource | File[], options?: LocalStreamConstructorOptions): LocalStream<BufferFile>; prototype: LocalStream<File>; } interface LocalStreamDestOptions { /** * Mode that is used for writing */ mode?: number; /** * Flag that is used for writing */ flag?: fs.I.Flag; /** * Current working directory for files, dest is resolved using this cwd. Default: constuctor cwd or process.cwd() */ cwd?: string; /** * Whether to push written files into the stream */ produceFiles?: boolean; /** * Whether to inherit the source file's mode (access properties) */ originMode?: boolean; /** * Whether to inherit the source file's time properties (atime, mtime) */ originTimes?: boolean; /** * Whether to inherit the source file's uid and gid */ originOwner?: boolean; } interface LocalStream<T> extends Stream<File, T> { /** * Writes all files into the given directory * * @param directory directory where to write files */ dest(directory: string, options?: LocalStreamDestOptions): this; /** * Writes all files into the given directory using the given callback * * @param getDirectory callback that returns a directory for each file */ dest(getDirectory: (file: T) => string, options?: LocalStreamDestOptions): this; } } export const LocalStream: I.LocalStreamConstructor; namespace I { interface SrcOptions extends LocalStreamConstructorOptions { /** * Used for relative pathing of files. Typically where a glob starts. */ base?: string; /** * Whether to match dotted files (hidden). Default: true */ dot?: boolean; /** * Whether to lstat instead of stat when stating. Default: false */ links?: boolean; } } /** * @param globs Source file/files */ function src(globs: string | string[], options: I.SrcOptions & { read: false }): I.LocalStream<I.NullFile>; function src(globs: string | string[], options: I.SrcOptions & { stream: true }): I.LocalStream<I.StreamFile>; function src(globs: string | string[], options?: I.SrcOptions): I.LocalStream<I.BufferFile>; namespace I { type WatcherConstructorOptions = fs.I.Watcher.ConstructorOptions; interface WatchOptions extends WatcherConstructorOptions, LocalStreamConstructorOptions { /** * Used for relative pathing of files. Typically where a glob starts. */ base?: string; /** * Whether to match dotted files (hidden). Default: true */ dot?: boolean; /** * Whether to resume the stream on the next tick. Default: true */ resume?: boolean; } } /** * @param globs Source file/files */ function watch(globs: string | string[], options: I.WatchOptions & { read: false }): I.LocalStream<I.NullFile>; function watch(globs: string | string[], options: I.WatchOptions & { stream: true }): I.LocalStream<I.StreamFile>; function watch(globs: string | string[], options?: I.WatchOptions): I.LocalStream<I.BufferFile>; namespace I { interface LocalMapStream<T> extends Stream<File, T> { dest(options?: LocalStreamDestOptions): this; } interface Mapping { /** * Source file/files */ from: string; /** * Destination directory */ to: string; } interface MapOptions extends LocalStreamConstructorOptions { /** * Used for relative pathing of files. Typically where a glob starts. */ base?: string; /** * Whether to match dotted files (hidden). Default: true */ dot?: boolean; } type WatchMapOptions = MapOptions & WatcherConstructorOptions; type MapSource = Mapping | Mapping[]; } /** * The same as fast.src, but source and dest paths are defined in one place */ function map(mappings: I.MapSource, options: I.MapOptions & { read: false }): I.LocalMapStream<I.NullFile>; function map(mappings: I.MapSource, options: I.MapOptions & { stream: true }): I.LocalMapStream<I.StreamFile>; function map(mappings: I.MapSource, options?: I.MapOptions): I.LocalMapStream<I.BufferFile>; function watchMap(mappings: I.MapSource, options: I.WatchMapOptions & { read: false }): I.LocalMapStream<I.NullFile>; function watchMap(mappings: I.MapSource, options: I.WatchMapOptions & { stream: true }): I.LocalMapStream<I.StreamFile>; function watchMap(mappings: I.MapSource, options?: I.WatchMapOptions): I.LocalMapStream<I.BufferFile>; // plugins namespace I { namespace plugin.compressor { type Compressor = "gz" | "deflate" | "brotli" | "lzma" | "xz" | "snappy"; // TODO keyof adone.compressor ? } interface Stream<S, T> { /** * Compresses all files using the given compressor */ compress(this: {}, type: plugin.compressor.Compressor, options?: { /** * Whether to rename files, adds corresponding extname */ rename?: boolean, [key: string]: any }): this; /** * Decompresses all files using the given compressor */ decompress(type: plugin.compressor.Compressor, options?: object): this; } namespace plugin.archive { type Archiver = "tar" | "zip"; // TODO keyof adone.archive ? } interface Stream<S, T> { /** * Packs all files into one archive of the given type */ pack(type: plugin.archive.Archiver, options?: object): this; /** * Unpacks the incoming files using the given archive type */ unpack(type: plugin.archive.Archiver, options?: object): this; /** * transpiles files */ transpile(options: object): this; // TODO adone.js.transpiler options /** * Deletes lines from files */ deleteLines(filters: RegExp | RegExp[]): this; /** * sets new filename */ rename(filename: string): this; rename(handle: { dirname?: string, prefix?: string, basename?: string, extname?: string }): this; rename(handler: (handle: { dirname: string, basename: string, extname: string }) => void): this; /** * concats all files into one */ concat(file: string | { path: string }, options?: { newLine?: string }): this; // flatten(options?: { // newPath?: string, // includeParents?: number | [number, number], // subPath?: number | [number, number], // }): this; } namespace plugin.sourcemaps { interface WriteOptions<T> { /** * By default the source maps include the source code. Pass false to use the original files */ includeContent?: boolean; /** * By default a comment containing / referencing the source map is added. * Set this to false to disable the comment (e.g. if you want to load the source maps by header) */ addComment?: boolean; /** * Sets the charset for inline source maps */ charset?: fs.I.Encoding; /** * Set the location where the source files are hosted (use this when includeContent is set to false) */ sourceRoot?: string | ((file: T) => string); /** * Function that is called for every source and receives the default source path as a parameter and the original file */ mapSources?(path: string, file: T): string; mapSourcesAbsolute?: boolean; /** * This option allows to rename the map file. * It takes a function that is called for every map and receives the default map path as a parameter */ mapFile?(file: T): string; /** * Set the destination path */ destPath?: string; /** * Clone options */ clone?: FileCloneOptions; /** * Specify a prefix to be prepended onto the source map URL when writing external source maps. */ sourceMappingURLPrefix?: string | ((file: T) => string); /** * The output of the function must be the full URL to the source map (in function of the output file) */ sourceMappingURL?(file: T): string; } } interface Stream<S, T> { sourcemapsInit(options?: { /** * Whether to load existing sourcemaps */ loadMaps?: boolean, /** * Whether to generate initial sourcemaps instead of using empty sourcemap */ identityMap?: boolean, largeFile?: boolean }): this; /** * * * @param dest destination directory */ sourcemapsWrite(dest: string, options?: plugin.sourcemaps.WriteOptions<T>): this; sourcemapsWrite(options?: plugin.sourcemaps.WriteOptions<T>): this; } namespace plugin.wrap { interface Options { /** * Set to explicit false value to disable automatic JSON, JSON5 and YAML parsing */ parse?: boolean; escape?: RegExp; evaluate?: RegExp; imports?: object; interpolate?: RegExp; sourceURL?: string; variable?: string; } interface TemplateFunctionData<T> extends Options { file: T; contents: object; [custom: string]: any; } } interface Stream<S, T> { /** * Wraps contents */ wrap( template: { src: string } | string | ((data: plugin.wrap.TemplateFunctionData<T>) => string), data?: object | ((file: T) => object), options?: plugin.wrap.Options | ((file: T) => plugin.wrap.Options) ): this; /** * Replaces contents */ replace(search: string, replacement: string | ((search: string) => string)): this; replace(search: RegExp, replacement: string): this; replace(search: Array<string | RegExp>, replacement: Array<string | ((search: string) => string)>): this; /** * Static asset revisioning by appending content hash to filenames */ revisionHash(options?: { manifest: { path?: string, merge?: boolean transformer?: { parse(str: string): any; stringify(obj: any): string; } } }): this; /** * Rewrite occurrences of filenames which have been renamed by revisionHash */ revisionHashReplace(options?: { /** * Use canonical Uris when replacing filePaths, * i.e. when working with filepaths with non forward slash (/) path separators * we replace them with forward slash. * Default: true */ canonicalUris?: boolean, /** * Add the prefix string to each replacement */ prefix?: string, /** * Only substitute in new filenames in files of these types * Default: ['.js', '.css', '.html', '.hbs'] */ replaceExtensions?: string[], /** * Read JSON manifests written out by revisionHash */ manifest?: File[] | stream.core.Stream<any, File>, /** * Modify the name of the unreved files before using them */ modifyUnreved?(path: string): string, /** * Modify the name of the reved files before using them */ modifyReved?(path: string): string }): this; } namespace plugin.chmod { interface Access { /** * Whether to have read access */ read?: boolean; /** * Whether to have write access */ write?: boolean; /** * Whether to ahve execute access */ execute?: boolean; } interface Mode { /** * Owner properties */ owner?: Access; /** * Group properties */ group?: Access; /** * Others properties */ others?: Access; } } interface Stream<S, T> { /** * Changes file mode */ chmod(mode?: number | plugin.chmod.Mode, dirMode?: number | plugin.chmod.Mode): this; } namespace plugin.notify { interface Options<T> { notifier?: object; // TODO adone.notifier host?: string; appName?: string; port?: number; /** * Filter out files */ filter?(file: T): boolean; /** * Whether to emit an error when the stream emits an error. Default: false */ emitError?: boolean; /** * Whether to notify on the last file. Default: false */ onLast?: boolean; /** * Whether to debounce notifications. Accepts a number as timeout or debounce options * Default: undefined */ debounce?: number | util.I.DebounceOptions & { /** * debounce timeout */ timeout: number }; /** * Object passed to the lodash template, for additional properties passed to the template */ templateOptions?: object; /** * Whether to use console notifications (print a message to console) */ console?: boolean; /** * Whether to use GUI notifications (notify-send/toaster/etc) */ gui?: boolean; /** * Notification title */ title?: string | ((file: T) => string); /** * Notification subtitle */ subtitle?: string | ((file: T) => string); open?: string | ((file: T) => string); /** * Notification message */ message?: string | ((file: T) => string); } interface OnErrorOptions<T> extends Options<T> { /** * Whether to end the stream when an error occurs */ endStream?: boolean; } type OptionsArg<T, O> = string | O | (() => O); } interface Stream<S, T> { /** * Notify about passing through files */ notify(options?: plugin.notify.OptionsArg<T, plugin.notify.Options<T>>): this; /** * Notify about errors */ notifyError(options?: plugin.notify.OptionsArg<T, plugin.notify.OnErrorOptions<T>>): this; } } namespace plugin { namespace notify { /** * Creates a callback that can be used as a reporter for errors */ function onError<T = any>(options?: I.plugin.notify.OptionsArg<T, I.plugin.notify.OnErrorOptions<T>>): (error: T) => void; } } } }
the_stack
import * as CanvasGauges from 'canvas-gauges'; import { WidgetContext } from '@home/models/widget-component.models'; import { attributesGaugeType, AttributeSourceProperty, ColorLevelSetting, DigitalGaugeSettings, digitalGaugeSettingsSchema, FixedLevelColors } from '@home/components/widget/lib/digital-gauge.models'; import * as tinycolor_ from 'tinycolor2'; import { isDefined, isDefinedAndNotNull } from '@core/utils'; import { prepareFontSettings } from '@home/components/widget/lib/settings.models'; import { CanvasDigitalGauge, CanvasDigitalGaugeOptions } from '@home/components/widget/lib/canvas-digital-gauge'; import { DatePipe } from '@angular/common'; import { DataKey, Datasource, DatasourceData, DatasourceType, JsonSettingsSchema, widgetType } from '@shared/models/widget.models'; import { IWidgetSubscription, WidgetSubscriptionOptions } from '@core/api/widget-api.models'; import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; import { EMPTY, Observable } from 'rxjs'; import GenericOptions = CanvasGauges.GenericOptions; const tinycolor = tinycolor_; const digitalGaugeSettingsSchemaValue = digitalGaugeSettingsSchema; // @dynamic export class TbCanvasDigitalGauge { static get settingsSchema(): JsonSettingsSchema { return digitalGaugeSettingsSchemaValue; } constructor(protected ctx: WidgetContext, canvasId: string) { const gaugeElement = $('#' + canvasId, ctx.$container)[0]; const settings: DigitalGaugeSettings = ctx.settings; this.localSettings = {}; this.localSettings.minValue = settings.minValue || 0; this.localSettings.maxValue = settings.maxValue || 100; this.localSettings.gaugeType = settings.gaugeType || 'arc'; this.localSettings.neonGlowBrightness = settings.neonGlowBrightness || 0; this.localSettings.dashThickness = settings.dashThickness || 0; this.localSettings.roundedLineCap = settings.roundedLineCap === true; const dataKey = ctx.data[0].dataKey; const keyColor = settings.defaultColor || dataKey.color; this.localSettings.unitTitle = ((settings.showUnitTitle === true) ? (settings.unitTitle && settings.unitTitle.length > 0 ? settings.unitTitle : dataKey.label) : ''); this.localSettings.showTimestamp = settings.showTimestamp === true; this.localSettings.timestampFormat = settings.timestampFormat && settings.timestampFormat.length ? settings.timestampFormat : 'yyyy-MM-dd HH:mm:ss'; this.localSettings.gaugeWidthScale = settings.gaugeWidthScale || 0.75; this.localSettings.gaugeColor = settings.gaugeColor || tinycolor(keyColor).setAlpha(0.2).toRgbString(); this.localSettings.useFixedLevelColor = settings.useFixedLevelColor || false; if (!settings.useFixedLevelColor) { if (!settings.levelColors || settings.levelColors.length === 0) { this.localSettings.levelColors = [keyColor]; } else { this.localSettings.levelColors = settings.levelColors.slice(); } } else { this.localSettings.levelColors = [keyColor]; this.localSettings.fixedLevelColors = settings.fixedLevelColors || []; } this.localSettings.showTicks = settings.showTicks || false; this.localSettings.ticks = []; this.localSettings.ticksValue = settings.ticksValue || []; this.localSettings.tickWidth = settings.tickWidth || 4; this.localSettings.colorTicks = settings.colorTicks || '#666'; this.localSettings.decimals = isDefined(dataKey.decimals) ? dataKey.decimals : (isDefinedAndNotNull(settings.decimals) ? settings.decimals : ctx.decimals); this.localSettings.units = dataKey.units && dataKey.units.length ? dataKey.units : (isDefined(settings.units) && settings.units.length > 0 ? settings.units : ctx.units); this.localSettings.hideValue = settings.showValue !== true; this.localSettings.hideMinMax = settings.showMinMax !== true; this.localSettings.donutStartAngle = isDefinedAndNotNull(settings.donutStartAngle) ? -TbCanvasDigitalGauge.toRadians(settings.donutStartAngle) : null; this.localSettings.title = ((settings.showTitle === true) ? (settings.title && settings.title.length > 0 ? settings.title : dataKey.label) : ''); if (!this.localSettings.unitTitle && this.localSettings.showTimestamp) { this.localSettings.unitTitle = ' '; } this.localSettings.titleFont = prepareFontSettings(settings.titleFont, { size: 12, style: 'normal', weight: '500', color: keyColor }); this.localSettings.valueFont = prepareFontSettings(settings.valueFont, { size: 18, style: 'normal', weight: '500', color: keyColor }); this.localSettings.minMaxFont = prepareFontSettings(settings.minMaxFont, { size: 10, style: 'normal', weight: '500', color: keyColor }); this.localSettings.labelFont = prepareFontSettings(settings.labelFont, { size: 8, style: 'normal', weight: '500', color: keyColor }); const gaugeData: CanvasDigitalGaugeOptions = { renderTo: gaugeElement, gaugeWidthScale: this.localSettings.gaugeWidthScale, gaugeColor: this.localSettings.gaugeColor, levelColors: this.localSettings.levelColors, colorTicks: this.localSettings.colorTicks, tickWidth: this.localSettings.tickWidth, ticks: this.localSettings.ticks, title: this.localSettings.title, fontTitleSize: this.localSettings.titleFont.size, fontTitleStyle: this.localSettings.titleFont.style, fontTitleWeight: this.localSettings.titleFont.weight, colorTitle: this.localSettings.titleFont.color, fontTitle: this.localSettings.titleFont.family, fontValueSize: this.localSettings.valueFont.size, fontValueStyle: this.localSettings.valueFont.style, fontValueWeight: this.localSettings.valueFont.weight, colorValue: this.localSettings.valueFont.color, fontValue: this.localSettings.valueFont.family, fontMinMaxSize: this.localSettings.minMaxFont.size, fontMinMaxStyle: this.localSettings.minMaxFont.style, fontMinMaxWeight: this.localSettings.minMaxFont.weight, colorMinMax: this.localSettings.minMaxFont.color, fontMinMax: this.localSettings.minMaxFont.family, fontLabelSize: this.localSettings.labelFont.size, fontLabelStyle: this.localSettings.labelFont.style, fontLabelWeight: this.localSettings.labelFont.weight, colorLabel: this.localSettings.labelFont.color, fontLabel: this.localSettings.labelFont.family, minValue: this.localSettings.minValue, maxValue: this.localSettings.maxValue, gaugeType: this.localSettings.gaugeType, dashThickness: this.localSettings.dashThickness, roundedLineCap: this.localSettings.roundedLineCap, symbol: this.localSettings.units, label: this.localSettings.unitTitle, showTimestamp: this.localSettings.showTimestamp, hideValue: this.localSettings.hideValue, hideMinMax: this.localSettings.hideMinMax, donutStartAngle: this.localSettings.donutStartAngle, valueDec: this.localSettings.decimals, neonGlowBrightness: this.localSettings.neonGlowBrightness, // animations animation: settings.animation !== false && !ctx.isMobile, animationDuration: isDefinedAndNotNull(settings.animationDuration) ? settings.animationDuration : 500, animationRule: settings.animationRule || 'linear', isMobile: ctx.isMobile }; this.gauge = new CanvasDigitalGauge(gaugeData).draw(); this.init(); } private localSettings: DigitalGaugeSettings; private levelColorsSourcesSubscription: IWidgetSubscription; private ticksSourcesSubscription: IWidgetSubscription; private gauge: CanvasDigitalGauge; static generateDatasource(ctx: WidgetContext, datasources: Datasource[], entityAlias: string, attribute: string, settings: any): Datasource[]{ const entityAliasId = ctx.aliasController.getEntityAliasId(entityAlias); if (!entityAliasId) { throw new Error('Not valid entity aliase name ' + entityAlias); } const datasource = datasources.find((datasourceIteration) => { return datasourceIteration.entityAliasId === entityAliasId; }); const dataKey: DataKey = { type: DataKeyType.attribute, name: attribute, label: attribute, settings: [settings], _hash: Math.random() }; if (datasource) { const findDataKey = datasource.dataKeys.find((dataKeyIteration) => { return dataKeyIteration.name === attribute; }); if (findDataKey) { findDataKey.settings.push(settings); } else { datasource.dataKeys.push(dataKey); } } else { const datasourceAttribute: Datasource = { type: DatasourceType.entity, name: entityAlias, aliasName: entityAlias, entityAliasId, dataKeys: [dataKey] }; datasources.push(datasourceAttribute); } return datasources; } private static toRadians(angle: number): number { return angle * (Math.PI / 180); } init() { let updateSetting = false; if (this.localSettings.useFixedLevelColor && this.localSettings.fixedLevelColors?.length > 0) { this.localSettings.levelColors = this.settingLevelColorsSubscribe(this.localSettings.fixedLevelColors); updateSetting = true; } if (this.localSettings.showTicks && this.localSettings.ticksValue?.length) { this.localSettings.ticks = this.settingTicksSubscribe(this.localSettings.ticksValue); updateSetting = true; } if (updateSetting) { this.updateSetting(); } } settingLevelColorsSubscribe(options: FixedLevelColors[]): ColorLevelSetting[] { let levelColorsDatasource: Datasource[] = []; const predefineLevelColors: ColorLevelSetting[] = []; predefineLevelColors.push({ value: this.localSettings.minValue, color: this.localSettings.gaugeColor }); function setLevelColor(levelSetting: AttributeSourceProperty, color: string) { if (levelSetting.valueSource === 'predefinedValue' && isFinite(levelSetting.value)) { predefineLevelColors.push({ value: levelSetting.value, color }); } else if (levelSetting.entityAlias && levelSetting.attribute) { try { levelColorsDatasource = TbCanvasDigitalGauge.generateDatasource(this.ctx, levelColorsDatasource, levelSetting.entityAlias, levelSetting.attribute, {color, index: predefineLevelColors.length}); } catch (e) { return; } predefineLevelColors.push(null); } } for (const levelColor of options) { if (levelColor.from) { setLevelColor.call(this, levelColor.from, levelColor.color); } if (levelColor.to) { setLevelColor.call(this, levelColor.to, levelColor.color); } } this.subscribeAttributes(levelColorsDatasource, 'levelColors').subscribe((subscription) => { this.levelColorsSourcesSubscription = subscription; }); return predefineLevelColors; } settingTicksSubscribe(options: AttributeSourceProperty[]): number[] { let ticksDatasource: Datasource[] = []; const predefineTicks: number[] = []; for (const tick of options) { if (tick.valueSource === 'predefinedValue' && isFinite(tick.value)) { predefineTicks.push(tick.value); } else if (tick.entityAlias && tick.attribute) { try { ticksDatasource = TbCanvasDigitalGauge .generateDatasource(this.ctx, ticksDatasource, tick.entityAlias, tick.attribute, predefineTicks.length); } catch (e) { continue; } predefineTicks.push(null); } } this.subscribeAttributes(ticksDatasource, 'ticks').subscribe((subscription) => { this.ticksSourcesSubscription = subscription; }); return predefineTicks; } subscribeAttributes(datasource: Datasource[], typeAttributes: attributesGaugeType): Observable<IWidgetSubscription> { if (!datasource.length) { return EMPTY; } const levelColorsSourcesSubscriptionOptions: WidgetSubscriptionOptions = { datasources: datasource, useDashboardTimewindow: false, type: widgetType.latest, callbacks: { onDataUpdated: (subscription) => { this.updateAttribute(subscription.data, typeAttributes); } } }; return this.ctx.subscriptionApi.createSubscription(levelColorsSourcesSubscriptionOptions, true); } updateAttribute(data: Array<DatasourceData>, typeAttributes: attributesGaugeType) { for (const keyData of data) { if (keyData && keyData.data && keyData.data[0]) { const attrValue = keyData.data[0][1]; if (isFinite(attrValue)) { for (const setting of keyData.dataKey.settings) { switch (typeAttributes) { case 'levelColors': this.localSettings.levelColors[setting.index] = { value: attrValue, color: setting.color }; break; case 'ticks': this.localSettings.ticks[setting] = attrValue; break; } } } } } this.updateSetting(); } updateSetting() { (this.gauge.options as CanvasDigitalGaugeOptions).ticks = this.localSettings.ticks; (this.gauge.options as CanvasDigitalGaugeOptions).levelColors = this.localSettings.levelColors; this.gauge.options = CanvasDigitalGauge.configure(this.gauge.options); this.gauge.update({} as CanvasDigitalGaugeOptions); } update() { if (this.ctx.data.length > 0) { const cellData = this.ctx.data[0]; if (cellData.data.length > 0) { const tvPair = cellData.data[cellData.data.length - 1]; let timestamp; if (this.localSettings.showTimestamp) { timestamp = tvPair[0]; const filter = this.ctx.$injector.get(DatePipe); (this.gauge.options as CanvasDigitalGaugeOptions).label = filter.transform(timestamp, this.localSettings.timestampFormat); } const value = tvPair[1]; if (value !== this.gauge.value) { if (!this.gauge.options.animation) { this.gauge._value = value; } this.gauge.value = value; } else if (this.localSettings.showTimestamp && this.gauge.timestamp !== timestamp) { this.gauge.timestamp = timestamp; } } } } mobileModeChanged() { const animation = this.ctx.settings.animation !== false && !this.ctx.isMobile; this.gauge.update({animation, isMobile: this.ctx.isMobile} as CanvasDigitalGaugeOptions); } resize() { this.gauge.update({width: this.ctx.width, height: this.ctx.height} as GenericOptions); } destroy() { this.gauge.destroy(); this.gauge = null; } }
the_stack
import { connectivityState as ConnectivityState, status as Status, Metadata, logVerbosity, experimental } from "@grpc/grpc-js"; import { isLocalitySubchannelAddress, LocalitySubchannelAddress } from "./load-balancer-priority"; import LoadBalancingConfig = experimental.LoadBalancingConfig; import LoadBalancer = experimental.LoadBalancer; import ChannelControlHelper = experimental.ChannelControlHelper; import getFirstUsableConfig = experimental.getFirstUsableConfig; import registerLoadBalancerType = experimental.registerLoadBalancerType; import ChildLoadBalancerHandler = experimental.ChildLoadBalancerHandler; import Picker = experimental.Picker; import PickResult = experimental.PickResult; import PickArgs = experimental.PickArgs; import QueuePicker = experimental.QueuePicker; import UnavailablePicker = experimental.UnavailablePicker; import SubchannelAddress = experimental.SubchannelAddress; import subchannelAddressToString = experimental.subchannelAddressToString; import validateLoadBalancingConfig = experimental.validateLoadBalancingConfig; const TRACER_NAME = 'weighted_target'; function trace(text: string): void { experimental.trace(logVerbosity.DEBUG, TRACER_NAME, text); } const TYPE_NAME = 'weighted_target'; const DEFAULT_RETENTION_INTERVAL_MS = 15 * 60 * 1000; export interface WeightedTarget { weight: number; child_policy: LoadBalancingConfig[]; } export class WeightedTargetLoadBalancingConfig implements LoadBalancingConfig { getLoadBalancerName(): string { return TYPE_NAME; } constructor(private targets: Map<string, WeightedTarget>) { } getTargets() { return this.targets; } toJsonObject(): object { const targetsField: {[key: string]: object} = {}; for (const [targetName, targetValue] of this.targets.entries()) { targetsField[targetName] = { weight: targetValue.weight, child_policy: targetValue.child_policy.map(policy => policy.toJsonObject()) }; } return { [TYPE_NAME]: { targets: targetsField } } } static createFromJson(obj: any): WeightedTargetLoadBalancingConfig { const targetsMap: Map<string, WeightedTarget> = new Map<string, WeightedTarget>(); if (!('targets' in obj && obj.targets !== null && typeof obj.targets === 'object')) { throw new Error('Weighted target config must have a targets map'); } for (const key of obj.targets) { const targetObj = obj.targets[key]; if (!('weight' in targetObj && typeof targetObj.weight === 'number')) { throw new Error(`Weighted target ${key} must have a numeric weight`); } if (!('child_policy' in targetObj && Array.isArray(targetObj.child_policy))) { throw new Error(`Weighted target ${key} must have a child_policy array`); } const validatedTarget: WeightedTarget = { weight: targetObj.weight, child_policy: targetObj.child_policy.map(validateLoadBalancingConfig) } targetsMap.set(key, validatedTarget); } return new WeightedTargetLoadBalancingConfig(targetsMap); } } /** * Represents a picker and a subinterval of a larger interval used for randomly * selecting an element of a list of these objects. */ interface WeightedPicker { picker: Picker; /** * The exclusive end of the interval associated with this element. The start * of the interval is implicitly the rangeEnd of the previous element in the * list, or 0 for the first element in the list. */ rangeEnd: number; } class WeightedTargetPicker implements Picker { private rangeTotal: number; constructor(private readonly pickerList: WeightedPicker[]) { this.rangeTotal = pickerList[pickerList.length - 1].rangeEnd; } pick(pickArgs: PickArgs): PickResult { // num | 0 is equivalent to floor(num) const selection = (Math.random() * this.rangeTotal) | 0; /* Binary search for the element of the list such that * pickerList[index - 1].rangeEnd <= selection < pickerList[index].rangeEnd */ let mid = 0; let startIndex = 0; let endIndex = this.pickerList.length - 1; let index = 0; while (endIndex > startIndex) { mid = ((startIndex + endIndex) / 2) | 0; if (this.pickerList[mid].rangeEnd > selection) { endIndex = mid; } else if (this.pickerList[mid].rangeEnd < selection) { startIndex = mid + 1; } else { // + 1 here because the range is exclusive at the top end index = mid + 1; break; } } if (index === 0) { index = startIndex; } return this.pickerList[index].picker.pick(pickArgs); } } interface WeightedChild { updateAddressList(addressList: SubchannelAddress[], lbConfig: WeightedTarget, attributes: { [key: string]: unknown; }): void; exitIdle(): void; resetBackoff(): void; destroy(): void; deactivate(): void; maybeReactivate(): void; getConnectivityState(): ConnectivityState; getPicker(): Picker; getWeight(): number; } export class WeightedTargetLoadBalancer implements LoadBalancer { private WeightedChildImpl = class implements WeightedChild { private connectivityState: ConnectivityState = ConnectivityState.IDLE; private picker: Picker; private childBalancer: ChildLoadBalancerHandler; private deactivationTimer: NodeJS.Timer | null = null; private weight: number = 0; constructor(private parent: WeightedTargetLoadBalancer, private name: string) { this.childBalancer = new ChildLoadBalancerHandler(experimental.createChildChannelControlHelper(this.parent.channelControlHelper, { updateState: (connectivityState: ConnectivityState, picker: Picker) => { this.updateState(connectivityState, picker); }, })); this.picker = new QueuePicker(this.childBalancer); } private updateState(connectivityState: ConnectivityState, picker: Picker) { trace('Target ' + this.name + ' ' + ConnectivityState[this.connectivityState] + ' -> ' + ConnectivityState[connectivityState]); this.connectivityState = connectivityState; this.picker = picker; this.parent.updateState(); } updateAddressList(addressList: SubchannelAddress[], lbConfig: WeightedTarget, attributes: { [key: string]: unknown; }): void { this.weight = lbConfig.weight; const childConfig = getFirstUsableConfig(lbConfig.child_policy); if (childConfig !== null) { this.childBalancer.updateAddressList(addressList, childConfig, attributes); } } exitIdle(): void { this.childBalancer.exitIdle(); } resetBackoff(): void { this.childBalancer.resetBackoff(); } destroy(): void { this.childBalancer.destroy(); if (this.deactivationTimer !== null) { clearTimeout(this.deactivationTimer); } } deactivate(): void { if (this.deactivationTimer === null) { this.deactivationTimer = setTimeout(() => { this.parent.targets.delete(this.name); this.deactivationTimer = null; }, DEFAULT_RETENTION_INTERVAL_MS); } } maybeReactivate(): void { if (this.deactivationTimer !== null) { clearTimeout(this.deactivationTimer); this.deactivationTimer = null; } } getConnectivityState(): ConnectivityState { return this.connectivityState; } getPicker(): Picker { return this.picker; } getWeight(): number { return this.weight; } } // end of WeightedChildImpl /** * Map of target names to target children. Includes current targets and * previous targets with deactivation timers that have not yet triggered. */ private targets: Map<string, WeightedChild> = new Map<string, WeightedChild>(); /** * List of current target names. */ private targetList: string[] = []; constructor(private channelControlHelper: ChannelControlHelper) {} private updateState() { const pickerList: WeightedPicker[] = []; let end = 0; let connectingCount = 0; let idleCount = 0; let transientFailureCount = 0; for (const targetName of this.targetList) { const target = this.targets.get(targetName); if (target === undefined) { continue; } switch (target.getConnectivityState()) { case ConnectivityState.READY: end += target.getWeight(); pickerList.push({ picker: target.getPicker(), rangeEnd: end }); break; case ConnectivityState.CONNECTING: connectingCount += 1; break; case ConnectivityState.IDLE: idleCount += 1; break; case ConnectivityState.TRANSIENT_FAILURE: transientFailureCount += 1; break; default: // Ignore the other possiblity, SHUTDOWN } } let connectivityState: ConnectivityState; if (pickerList.length > 0) { connectivityState = ConnectivityState.READY; } else if (connectingCount > 0) { connectivityState = ConnectivityState.CONNECTING; } else if (idleCount > 0) { connectivityState = ConnectivityState.IDLE; } else { connectivityState = ConnectivityState.TRANSIENT_FAILURE; } let picker: Picker; switch (connectivityState) { case ConnectivityState.READY: picker = new WeightedTargetPicker(pickerList); break; case ConnectivityState.CONNECTING: case ConnectivityState.IDLE: picker = new QueuePicker(this); break; default: picker = new UnavailablePicker({ code: Status.UNAVAILABLE, details: 'weighted_target: all children report state TRANSIENT_FAILURE', metadata: new Metadata() }); } trace( 'Transitioning to ' + ConnectivityState[connectivityState] ); this.channelControlHelper.updateState(connectivityState, picker); } updateAddressList(addressList: SubchannelAddress[], lbConfig: LoadBalancingConfig, attributes: { [key: string]: unknown; }): void { if (!(lbConfig instanceof WeightedTargetLoadBalancingConfig)) { // Reject a config of the wrong type trace('Discarding address list update with unrecognized config ' + JSON.stringify(lbConfig.toJsonObject(), undefined, 2)); return; } /* For each address, the first element of its localityPath array determines * which child it belongs to. So we bucket those addresses by that first * element, and pass along the rest of the localityPath for that child * to use. */ const childAddressMap = new Map<string, LocalitySubchannelAddress[]>(); for (const address of addressList) { if (!isLocalitySubchannelAddress(address)) { // Reject address that cannot be associated with targets return; } if (address.localityPath.length < 1) { // Reject address that cannot be associated with targets return; } const childName = address.localityPath[0]; const childAddress: LocalitySubchannelAddress = { ...address, localityPath: address.localityPath.slice(1), }; let childAddressList = childAddressMap.get(childName); if (childAddressList === undefined) { childAddressList = []; childAddressMap.set(childName, childAddressList); } childAddressList.push(childAddress); } this.targetList = Array.from(lbConfig.getTargets().keys()); for (const [targetName, targetConfig] of lbConfig.getTargets()) { let target = this.targets.get(targetName); if (target === undefined) { target = new this.WeightedChildImpl(this, targetName); this.targets.set(targetName, target); } else { target.maybeReactivate(); } const targetAddresses = childAddressMap.get(targetName) ?? []; trace('Assigning target ' + targetName + ' address list ' + targetAddresses.map(address => '(' + subchannelAddressToString(address) + ' path=' + address.localityPath + ')')); target.updateAddressList(targetAddresses, targetConfig, attributes); } // Deactivate targets that are not in the new config for (const [targetName, target] of this.targets) { if (this.targetList.indexOf(targetName) < 0) { trace('Deactivating target ' + targetName); target.deactivate(); } } this.updateState(); } exitIdle(): void { for (const targetName of this.targetList) { this.targets.get(targetName)?.exitIdle(); } } resetBackoff(): void { for (const targetName of this.targetList) { this.targets.get(targetName)?.resetBackoff(); } } destroy(): void { for (const target of this.targets.values()) { target.destroy(); } this.targets.clear(); } getTypeName(): string { return TYPE_NAME; } } export function setup() { registerLoadBalancerType(TYPE_NAME, WeightedTargetLoadBalancer, WeightedTargetLoadBalancingConfig); }
the_stack
import * as ui from "../../ui"; import * as csx from '../../base/csx'; import * as React from "react"; import { cast, server } from "../../../socket/socketClient"; import * as docCache from "../model/docCache"; import * as types from "../../../common/types"; import * as cursorHistory from "../../cursorHistory"; import * as search from "../search/monacoSearch"; import * as semanticView from "../addons/semanticView"; import * as monacoUtils from "../monacoUtils"; import * as gitStatus from "../addons/gitStatus"; import * as liveAnalysis from "../addons/liveAnalysis"; import * as quickFix from "../addons/quickFix"; import * as linter from "../addons/linter"; import * as docblockr from "../addons/dockblockr"; import * as doctor from "../addons/doctor"; import * as testedMonaco from "../addons/testedMonaco"; import * as utils from '../../../common/utils'; import * as autoCloseTag from '../addons/autoCloseTag'; // Any other style modifications require('./codeEditor.css'); /** * The monokai theme * Reference : https://github.com/Microsoft/vscode/blob/d296b8e5b28925ea2df109baa2487c1d26f6ff3c/src/vs/editor/common/standalone/themes.ts */ import IThemeRule = monaco.editor.IThemeRule; export const monokai: IThemeRule[] = [ { token: '', foreground: 'f8f8f2' }, { token: 'comment', foreground: '75715e' }, { token: 'string', foreground: 'e6db74' }, { token: 'support.property-value.string.value.json', foreground: 'e6db74' }, { token: 'constant.numeric', foreground: 'ae81ff' }, { token: 'constant.language', foreground: 'ae81ff' }, { token: 'constant.character', foreground: 'ae81ff' }, { token: 'constant.other', foreground: 'ae81ff' }, { token: 'keyword', foreground: 'f92672' }, { token: 'support.property-value.keyword.json', foreground: 'f92672' }, { token: 'storage', foreground: 'aae354' }, { token: 'storage.type', foreground: '66d9ef', fontStyle: 'italic' }, { token: 'entity.name.class', foreground: 'a6e22e' }, { token: 'entity.other', foreground: 'a6e22e' }, { token: 'entity.name.function', foreground: 'a6e22e' }, { token: 'entity.name.tag', foreground: 'f92672' }, { token: 'entity.other.attribute-name', foreground: 'a6e22e' }, { token: 'variable', foreground: 'f8f8f2' }, { token: 'variable.parameter', foreground: 'fd971f', fontStyle: 'italic' }, { token: 'support.function', foreground: '66d9ef' }, { token: 'support.constant', foreground: '66d9ef' }, { token: 'support.type', foreground: '66d9ef' }, { token: 'support.class', foreground: '66d9ef', fontStyle: 'italic' }, /** We use qualifier for `const`, `var`, `private` etc. */ { token: 'qualifier', foreground: '00d0ff' }, /* `def` does not exist. We like to use it for variable definitions */ { token: 'def', foreground: 'fd971f' }, /** variable-2 doesn't exist. We use it for identifiers in type positions */ { token: 'variable-2', foreground: '9effff' }, ]; monaco.editor.defineTheme('monokai', { base: 'vs-dark', inherit: true, rules: monokai }); /** * We extend the monaco editor */ declare global { module monaco { module editor { interface ICommonCodeEditor { /** keep `filePath` */ filePath?: string; } } } } interface Props { onFocusChange?: (focused: boolean) => any; readOnly?: boolean; filePath: string; /** This is the only property we allow changing dynamically. Helps with rendering the same file path for different previews */ preview?: ts.TextSpan; } export class CodeEditor extends ui.BaseComponent<Props, { isFocused?: boolean, loading?: boolean }>{ constructor(props) { super(props); this.state = { isFocused: false, loading: true, }; } editor: monaco.editor.ICodeEditor; refs: { [string: string]: any; codeEditor: HTMLDivElement; } /** Ready after the doc is loaded */ ready = false; afterReadyQueue: { (): void }[] = []; /** If already ready it execs ... otherwise waits */ afterReady = (cb: () => void) => { if (this.ready) cb(); else { this.afterReadyQueue.push(cb); } } componentDidMount() { var mountNode = this.refs.codeEditor; const { filePath } = this.props; this.editor = monaco.editor.create(mountNode, { value: '...', theme: 'monokai', folding: true, autoClosingBrackets: true, wrappingColumn: 0, readOnly: false, // Never readonly ... even for readonly editors. Otherwise monaco doesn't highlight active line :) scrollBeyondLastLine: false, // Don't scroll by mouse where you can't scroll by keyboard :) formatOnType: true, contextmenu: false, // Disable context menu till we have it actually useful /** Move snippet suggestions to the bottom */ snippetSuggestions: 'bottom', /** Since everything else in our UI is Square */ roundedSelection: false, /** For git status, find results, errors */ overviewRulerLanes: 3, /** Don't reserve too much space for line numbers */ lineNumbersMinChars: 4, /** We need the glyph margin to show live analysis stuff */ glyphMargin: true, /** * Change the default font. * The default is `consolas` , `courier new`. * This means that if user does not have consolas they get *aweful* courier new. * Don't want that. * Also the default change by OS. * I prefer consistency so going with custom font everywhere */ fontFamily: 'consolas, menlo, monospace', /** Also make the font a bit bigger */ fontSize: 16, }, []); this.editor.filePath = filePath; // Utility to load editor options const loadEditorOptions = (editorOptions: types.EditorOptions) => { // Feels consistent with https://code.visualstudio.com/Docs/customization/userandworkspace this.editor.getModel().updateOptions({ insertSpaces: editorOptions.convertTabsToSpaces, tabSize: editorOptions.tabSize }); } this.disposible.add(cast.editorOptionsChanged.on((res) => { if (res.filePath === this.props.filePath) { loadEditorOptions(res.editorOptions); } })); // load up the doc docCache.getLinkedDoc(this.props.filePath, this.editor).then(({ doc, editorOptions }) => { // Load editor options loadEditorOptions(editorOptions); if (this.props.preview) { this.gotoPreview(this.props.preview); } // linter // NOTE: done here because it depends on model :) this.disposible.add(linter.setup(this.editor)); /** Tested */ if (!this.props.readOnly) { this.disposible.add(testedMonaco.setup(this.editor)); } /** Auto close tag */ const ext = utils.getExt(this.props.filePath); if (ext === 'tsx') { this.disposible.add(autoCloseTag.setup(this.editor)); } // Mark as ready and do anything that was waiting for ready to occur 🌹 this.afterReadyQueue.forEach(cb => cb()); this.ready = true; this.setState({ loading: false }); }) this.disposible.add(this.editor.onDidFocusEditor(this.focusChanged.bind(this, true))); this.disposible.add(this.editor.onDidBlurEditor(this.focusChanged.bind(this, false))); // cursor history if (!this.props.readOnly) { this.disposible.add(this.editor.onDidChangeCursorPosition(this.handleCursorActivity)); } // live analysis this.disposible.add(liveAnalysis.setup(this.editor)); // quick fix if (!this.props.readOnly) { this.disposible.add(quickFix.setup(this.editor)); } // Git status this.disposible.add(gitStatus.setup(this.editor)); // Docblockr this.disposible.add(docblockr.setup(this.editor)); } componentWillUnmount() { super.componentWillUnmount(); docCache.removeLinkedDoc(this.props.filePath, this.editor); this.editor.dispose(); this.editor = null; } firstFocus = true; focus = () => { if (!this.ready && this.firstFocus) { this.firstFocus = false; this.afterReadyQueue.push(() => { this.resize(); this.focus(); }); } else if (this.editor) { this.editor.focus(); } } resize = () => { if (this.editor) { const before = this.editor.getDomNode().scrollHeight; this.refresh(); const after = this.editor.getDomNode().scrollHeight; const worthRestoringScrollPosition = (after !== before) && (after != 0); /** Restore last scroll position on refresh after a blur */ if (this.lastScrollPosition != undefined && worthRestoringScrollPosition) { setTimeout(() => { this.editor.setScrollTop(this.lastScrollPosition); // console.log(this.props.filePath, before, after, worthRestoringScrollPosition, this.lastScrollPosition); // DEBUG this.lastScrollPosition = undefined; }) } } } lastScrollPosition: number | undefined = undefined; willBlur() { this.lastScrollPosition = this.editor.getScrollTop(); // console.log('Storing:', this.props.filePath, this.lastScrollPosition); // DEBUG } gotoPosition = (position: EditorPosition) => { this.afterReady(() => { this.lastScrollPosition = undefined; // Don't even think about restoring scroll position /** e.g. if the tab is already active we don't call `focus` from `gotoPosition` ... however it might not have focus */ if (!this.editor.isFocused()) { this.editor.focus() } /** SetTimeout because if editor comes out of hidden state we goto position too fast and then the scroll position is off */ setTimeout(() => monacoUtils.gotoPosition({ editor: this.editor, position })); }); } private refresh = () => { this.editor.layout(); } focusChanged = (focused) => { this.setState({ isFocused: focused }); this.props.onFocusChange && this.props.onFocusChange(focused); } getValue() { this.editor.getValue(); } /** * used to seed the initial search if coming out of hidden */ getSelectionSearchString(): string | undefined { let selection = this.editor.getSelection(); if (selection.startLineNumber === selection.endLineNumber) { if (selection.isEmpty()) { let wordAtPosition = this.editor.getModel().getWordAtPosition(selection.getStartPosition()); if (wordAtPosition) { return wordAtPosition.word; } } else { return this.editor.getModel().getValueInRange(selection); } } return undefined; } search = (options: FindOptions) => { search.commands.search(this.editor, options); } hideSearch = () => { search.commands.hideSearch(this.editor); } findNext = (options: FindOptions) => { search.commands.findNext(this.editor, options); } findPrevious = (options: FindOptions) => { search.commands.findPrevious(this.editor, options); } replaceNext = (newText: string) => { search.commands.replaceNext(this.editor, newText); } replacePrevious = (newText: string) => { search.commands.replacePrevious(this.editor, newText); } replaceAll = (newText: string) => { search.commands.replaceAll(this.editor, newText); } handleCursorActivity = () => { let cursor = this.editor.getSelection(); cursorHistory.addEntry({ line: cursor.startLineNumber - 1, ch: cursor.startColumn - 1, }); }; render() { var className = 'ReactCodeEditor'; if (this.state.isFocused) { className += ' ReactCodeEditor--focused'; } const loadingStyle = { position: 'absolute', top: '45%', left: '45%', zIndex: 1, color: '#999', border: '5px solid #999', borderRadius: '5px', fontSize: '2rem', padding: '5px', transition: '.2s opacity', opacity: this.state.loading ? 1 : 0, pointerEvents: 'none', }; return ( <div className={className} style={csx.extend(csx.horizontal, csx.flex, { position: 'relative', maxWidth: '100%' })}> {!this.props.readOnly && <doctor.Doctor cm={this.editor} filePath={this.props.filePath} />} <div style={loadingStyle as any}>LOADING</div> <div ref="codeEditor" style={{ display: 'flex', flexDirection: 'column', flex: 1, overflow: 'hidden' }} /> {!this.props.readOnly && <semanticView.SemanticView editor={this.editor} filePath={this.props.filePath} />} </div> ); } componentWillReceiveProps(nextProps: Props) { // If next props are getting a preview then old props had them too (based on how we use preview) if (nextProps.preview && nextProps.preview.start !== this.props.preview.start) { this.gotoPreview(nextProps.preview); } } gotoPreview(preview: ts.TextSpan) { // Re-layout as for preview style editors monaco seems to render faster than CSS 🌹 this.editor.layout(); let pos = this.editor.getModel().getPositionAt(preview.start); this.editor.revealLineInCenterIfOutsideViewport(pos.lineNumber); this.editor.setPosition(pos); } }
the_stack
//============================================================== // START Enums and Input Objects //============================================================== export enum BreastTypeEnum { FAKE = "FAKE", NA = "NA", NATURAL = "NATURAL", } export enum CriterionModifier { EQUALS = "EQUALS", EXCLUDES = "EXCLUDES", GREATER_THAN = "GREATER_THAN", INCLUDES = "INCLUDES", INCLUDES_ALL = "INCLUDES_ALL", IS_NULL = "IS_NULL", LESS_THAN = "LESS_THAN", NOT_EQUALS = "NOT_EQUALS", NOT_NULL = "NOT_NULL", } export enum DateAccuracyEnum { DAY = "DAY", MONTH = "MONTH", YEAR = "YEAR", } export enum EthnicityEnum { ASIAN = "ASIAN", BLACK = "BLACK", CAUCASIAN = "CAUCASIAN", INDIAN = "INDIAN", LATIN = "LATIN", MIDDLE_EASTERN = "MIDDLE_EASTERN", MIXED = "MIXED", OTHER = "OTHER", } export enum EthnicityFilterEnum { ASIAN = "ASIAN", BLACK = "BLACK", CAUCASIAN = "CAUCASIAN", INDIAN = "INDIAN", LATIN = "LATIN", MIDDLE_EASTERN = "MIDDLE_EASTERN", MIXED = "MIXED", OTHER = "OTHER", UNKNOWN = "UNKNOWN", } export enum EyeColorEnum { BLUE = "BLUE", BROWN = "BROWN", GREEN = "GREEN", GREY = "GREY", HAZEL = "HAZEL", RED = "RED", } export enum FingerprintAlgorithm { MD5 = "MD5", OSHASH = "OSHASH", PHASH = "PHASH", } export enum GenderEnum { FEMALE = "FEMALE", INTERSEX = "INTERSEX", MALE = "MALE", TRANSGENDER_FEMALE = "TRANSGENDER_FEMALE", TRANSGENDER_MALE = "TRANSGENDER_MALE", } export enum GenderFilterEnum { FEMALE = "FEMALE", INTERSEX = "INTERSEX", MALE = "MALE", TRANSGENDER_FEMALE = "TRANSGENDER_FEMALE", TRANSGENDER_MALE = "TRANSGENDER_MALE", UNKNOWN = "UNKNOWN", } export enum HairColorEnum { AUBURN = "AUBURN", BALD = "BALD", BLACK = "BLACK", BLONDE = "BLONDE", BRUNETTE = "BRUNETTE", GREY = "GREY", OTHER = "OTHER", RED = "RED", VARIOUS = "VARIOUS", } export enum OperationEnum { CREATE = "CREATE", DESTROY = "DESTROY", MERGE = "MERGE", MODIFY = "MODIFY", } export enum RoleEnum { ADMIN = "ADMIN", EDIT = "EDIT", INVITE = "INVITE", MANAGE_INVITES = "MANAGE_INVITES", MODIFY = "MODIFY", READ = "READ", VOTE = "VOTE", } export enum SortDirectionEnum { ASC = "ASC", DESC = "DESC", } export enum TagGroupEnum { ACTION = "ACTION", PEOPLE = "PEOPLE", SCENE = "SCENE", } export enum TargetTypeEnum { PERFORMER = "PERFORMER", SCENE = "SCENE", STUDIO = "STUDIO", TAG = "TAG", } export enum VoteStatusEnum { ACCEPTED = "ACCEPTED", IMMEDIATE_ACCEPTED = "IMMEDIATE_ACCEPTED", IMMEDIATE_REJECTED = "IMMEDIATE_REJECTED", PENDING = "PENDING", REJECTED = "REJECTED", } export interface ActivateNewUserInput { name: string; email: string; activation_key: string; password: string; } export interface ApplyEditInput { id: string; } export interface BodyModificationCriterionInput { location?: string | null; description?: string | null; modifier: CriterionModifier; } export interface BodyModificationInput { location: string; description?: string | null; } export interface BreastTypeCriterionInput { value?: BreastTypeEnum | null; modifier: CriterionModifier; } export interface CancelEditInput { id: string; } export interface DateCriterionInput { value: any; modifier: CriterionModifier; } export interface EditCommentInput { id: string; comment: string; } export interface EditFilterType { user_id?: string | null; status?: VoteStatusEnum | null; operation?: OperationEnum | null; vote_count?: IntCriterionInput | null; applied?: boolean | null; target_type?: TargetTypeEnum | null; target_id?: string | null; } export interface EditInput { id?: string | null; operation: OperationEnum; edit_id?: string | null; merge_source_ids?: string[] | null; comment?: string | null; } export interface EyeColorCriterionInput { value?: EyeColorEnum | null; modifier: CriterionModifier; } export interface FingerprintEditInput { hash: string; algorithm: FingerprintAlgorithm; duration: number; submissions: number; created: any; updated: any; } export interface FuzzyDateInput { date: any; accuracy: DateAccuracyEnum; } export interface GrantInviteInput { user_id: string; amount: number; } export interface HairColorCriterionInput { value?: HairColorEnum | null; modifier: CriterionModifier; } export interface IDCriterionInput { value: string[]; modifier: CriterionModifier; } export interface ImageCreateInput { url?: string | null; file?: any | null; } export interface IntCriterionInput { value: number; modifier: CriterionModifier; } export interface MeasurementsInput { cup_size?: string | null; band_size?: number | null; waist?: number | null; hip?: number | null; } export interface MultiIDCriterionInput { value?: string[] | null; modifier: CriterionModifier; } export interface NewUserInput { email: string; invite_key?: string | null; } export interface PerformerAppearanceInput { performer_id: string; as?: string | null; } export interface PerformerEditDetailsInput { name?: string | null; disambiguation?: string | null; aliases?: string[] | null; gender?: GenderEnum | null; urls?: URLInput[] | null; birthdate?: FuzzyDateInput | null; ethnicity?: EthnicityEnum | null; country?: string | null; eye_color?: EyeColorEnum | null; hair_color?: HairColorEnum | null; height?: number | null; measurements?: MeasurementsInput | null; breast_type?: BreastTypeEnum | null; career_start_year?: number | null; career_end_year?: number | null; tattoos?: BodyModificationInput[] | null; piercings?: BodyModificationInput[] | null; image_ids?: string[] | null; } export interface PerformerEditInput { edit: EditInput; details?: PerformerEditDetailsInput | null; options?: PerformerEditOptionsInput | null; } export interface PerformerEditOptionsInput { set_modify_aliases?: boolean | null; set_merge_aliases?: boolean | null; } export interface PerformerFilterType { names?: string | null; name?: string | null; alias?: string | null; disambiguation?: StringCriterionInput | null; gender?: GenderFilterEnum | null; url?: string | null; birthdate?: DateCriterionInput | null; birth_year?: IntCriterionInput | null; age?: IntCriterionInput | null; ethnicity?: EthnicityFilterEnum | null; country?: StringCriterionInput | null; eye_color?: EyeColorCriterionInput | null; hair_color?: HairColorCriterionInput | null; height?: IntCriterionInput | null; cup_size?: StringCriterionInput | null; band_size?: IntCriterionInput | null; waist_size?: IntCriterionInput | null; hip_size?: IntCriterionInput | null; breast_type?: BreastTypeCriterionInput | null; career_start_year?: IntCriterionInput | null; career_end_year?: IntCriterionInput | null; tattoos?: BodyModificationCriterionInput | null; piercings?: BodyModificationCriterionInput | null; } export interface QuerySpec { page?: number | null; per_page?: number | null; sort?: string | null; direction?: SortDirectionEnum | null; } export interface ResetPasswordInput { email: string; } export interface RevokeInviteInput { user_id: string; amount: number; } export interface RoleCriterionInput { value: RoleEnum[]; modifier: CriterionModifier; } export interface SceneCreateInput { title?: string | null; details?: string | null; urls?: URLInput[] | null; date?: any | null; studio_id?: string | null; performers?: PerformerAppearanceInput[] | null; tag_ids?: string[] | null; image_ids?: string[] | null; fingerprints: FingerprintEditInput[]; duration?: number | null; director?: string | null; } export interface SceneDestroyInput { id: string; } export interface SceneEditDetailsInput { title?: string | null; details?: string | null; urls?: URLInput[] | null; date?: any | null; studio_id?: string | null; performers?: PerformerAppearanceInput[] | null; tag_ids?: string[] | null; image_ids?: string[] | null; fingerprints?: FingerprintEditInput[] | null; duration?: number | null; director?: string | null; } export interface SceneEditInput { edit: EditInput; details?: SceneEditDetailsInput | null; duration?: number | null; } export interface SceneFilterType { text?: string | null; title?: string | null; url?: string | null; date?: DateCriterionInput | null; studios?: MultiIDCriterionInput | null; parentStudio?: string | null; tags?: MultiIDCriterionInput | null; performers?: MultiIDCriterionInput | null; alias?: StringCriterionInput | null; fingerprints?: MultiIDCriterionInput | null; } export interface SceneUpdateInput { id: string; title?: string | null; details?: string | null; urls?: URLInput[] | null; date?: any | null; studio_id?: string | null; performers?: PerformerAppearanceInput[] | null; tag_ids?: string[] | null; image_ids?: string[] | null; fingerprints?: FingerprintEditInput[] | null; duration?: number | null; director?: string | null; } export interface StringCriterionInput { value: string; modifier: CriterionModifier; } export interface StudioCreateInput { name: string; urls?: URLInput[] | null; parent_id?: string | null; image_ids?: string[] | null; } export interface StudioDestroyInput { id: string; } export interface StudioEditDetailsInput { name?: string | null; urls?: URLInput[] | null; parent_id?: string | null; image_ids?: string[] | null; } export interface StudioEditInput { edit: EditInput; details?: StudioEditDetailsInput | null; } export interface StudioFilterType { name?: string | null; names?: string | null; url?: string | null; parent?: IDCriterionInput | null; has_parent?: boolean | null; } export interface StudioUpdateInput { id: string; name?: string | null; urls?: URLInput[] | null; parent_id?: string | null; image_ids?: string[] | null; } export interface TagCategoryCreateInput { name: string; group: TagGroupEnum; description?: string | null; } export interface TagCategoryDestroyInput { id: string; } export interface TagCategoryUpdateInput { id: string; name?: string | null; group?: TagGroupEnum | null; description?: string | null; } export interface TagEditDetailsInput { name?: string | null; description?: string | null; aliases?: string[] | null; category_id?: string | null; } export interface TagEditInput { edit: EditInput; details?: TagEditDetailsInput | null; } export interface TagFilterType { text?: string | null; names?: string | null; name?: string | null; category_id?: string | null; } export interface URLInput { url: string; type: string; } export interface UserChangePasswordInput { existing_password?: string | null; new_password: string; reset_key?: string | null; } export interface UserCreateInput { name: string; password: string; roles: RoleEnum[]; email: string; invited_by_id?: string | null; } export interface UserDestroyInput { id: string; } export interface UserFilterType { name?: string | null; email?: string | null; roles?: RoleCriterionInput | null; apiKey?: string | null; successful_edits?: IntCriterionInput | null; unsuccessful_edits?: IntCriterionInput | null; successful_votes?: IntCriterionInput | null; unsuccessful_votes?: IntCriterionInput | null; api_calls?: IntCriterionInput | null; invited_by?: string | null; } export interface UserUpdateInput { id: string; name?: string | null; password?: string | null; roles?: RoleEnum[] | null; email?: string | null; } //============================================================== // END Enums and Input Objects //==============================================================
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PollerLike, PollOperationState } from "@azure/core-lro"; import { VirtualMachine, VirtualMachinesListByLocationOptionalParams, VirtualMachinesListOptionalParams, VirtualMachinesListAllOptionalParams, VirtualMachineSize, VirtualMachinesListAvailableSizesOptionalParams, VirtualMachineCaptureParameters, VirtualMachinesCaptureOptionalParams, VirtualMachinesCaptureResponse, VirtualMachinesCreateOrUpdateOptionalParams, VirtualMachinesCreateOrUpdateResponse, VirtualMachineUpdate, VirtualMachinesUpdateOptionalParams, VirtualMachinesUpdateResponse, VirtualMachinesDeleteOptionalParams, VirtualMachinesGetOptionalParams, VirtualMachinesGetResponse, VirtualMachinesInstanceViewOptionalParams, VirtualMachinesInstanceViewResponse, VirtualMachinesConvertToManagedDisksOptionalParams, VirtualMachinesDeallocateOptionalParams, VirtualMachinesGeneralizeOptionalParams, VirtualMachinesPowerOffOptionalParams, VirtualMachinesReapplyOptionalParams, VirtualMachinesRestartOptionalParams, VirtualMachinesStartOptionalParams, VirtualMachinesRedeployOptionalParams, VirtualMachinesReimageOptionalParams, VirtualMachinesRetrieveBootDiagnosticsDataOptionalParams, VirtualMachinesRetrieveBootDiagnosticsDataResponse, VirtualMachinesPerformMaintenanceOptionalParams, VirtualMachinesSimulateEvictionOptionalParams, VirtualMachinesAssessPatchesOptionalParams, VirtualMachinesAssessPatchesResponse, VirtualMachineInstallPatchesParameters, VirtualMachinesInstallPatchesOptionalParams, VirtualMachinesInstallPatchesResponse, RunCommandInput, VirtualMachinesRunCommandOptionalParams, VirtualMachinesRunCommandResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a VirtualMachines. */ export interface VirtualMachines { /** * Gets all the virtual machines under the specified subscription for the specified location. * @param location The location for which virtual machines under the subscription are queried. * @param options The options parameters. */ listByLocation( location: string, options?: VirtualMachinesListByLocationOptionalParams ): PagedAsyncIterableIterator<VirtualMachine>; /** * Lists all of the virtual machines in the specified resource group. Use the nextLink property in the * response to get the next page of virtual machines. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ list( resourceGroupName: string, options?: VirtualMachinesListOptionalParams ): PagedAsyncIterableIterator<VirtualMachine>; /** * Lists all of the virtual machines in the specified subscription. Use the nextLink property in the * response to get the next page of virtual machines. * @param options The options parameters. */ listAll( options?: VirtualMachinesListAllOptionalParams ): PagedAsyncIterableIterator<VirtualMachine>; /** * Lists all available virtual machine sizes to which the specified virtual machine can be resized. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ listAvailableSizes( resourceGroupName: string, vmName: string, options?: VirtualMachinesListAvailableSizesOptionalParams ): PagedAsyncIterableIterator<VirtualMachineSize>; /** * Captures the VM by copying virtual hard disks of the VM and outputs a template that can be used to * create similar VMs. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param parameters Parameters supplied to the Capture Virtual Machine operation. * @param options The options parameters. */ beginCapture( resourceGroupName: string, vmName: string, parameters: VirtualMachineCaptureParameters, options?: VirtualMachinesCaptureOptionalParams ): Promise< PollerLike< PollOperationState<VirtualMachinesCaptureResponse>, VirtualMachinesCaptureResponse > >; /** * Captures the VM by copying virtual hard disks of the VM and outputs a template that can be used to * create similar VMs. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param parameters Parameters supplied to the Capture Virtual Machine operation. * @param options The options parameters. */ beginCaptureAndWait( resourceGroupName: string, vmName: string, parameters: VirtualMachineCaptureParameters, options?: VirtualMachinesCaptureOptionalParams ): Promise<VirtualMachinesCaptureResponse>; /** * The operation to create or update a virtual machine. Please note some properties can be set only * during virtual machine creation. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param parameters Parameters supplied to the Create Virtual Machine operation. * @param options The options parameters. */ beginCreateOrUpdate( resourceGroupName: string, vmName: string, parameters: VirtualMachine, options?: VirtualMachinesCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<VirtualMachinesCreateOrUpdateResponse>, VirtualMachinesCreateOrUpdateResponse > >; /** * The operation to create or update a virtual machine. Please note some properties can be set only * during virtual machine creation. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param parameters Parameters supplied to the Create Virtual Machine operation. * @param options The options parameters. */ beginCreateOrUpdateAndWait( resourceGroupName: string, vmName: string, parameters: VirtualMachine, options?: VirtualMachinesCreateOrUpdateOptionalParams ): Promise<VirtualMachinesCreateOrUpdateResponse>; /** * The operation to update a virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param parameters Parameters supplied to the Update Virtual Machine operation. * @param options The options parameters. */ beginUpdate( resourceGroupName: string, vmName: string, parameters: VirtualMachineUpdate, options?: VirtualMachinesUpdateOptionalParams ): Promise< PollerLike< PollOperationState<VirtualMachinesUpdateResponse>, VirtualMachinesUpdateResponse > >; /** * The operation to update a virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param parameters Parameters supplied to the Update Virtual Machine operation. * @param options The options parameters. */ beginUpdateAndWait( resourceGroupName: string, vmName: string, parameters: VirtualMachineUpdate, options?: VirtualMachinesUpdateOptionalParams ): Promise<VirtualMachinesUpdateResponse>; /** * The operation to delete a virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginDelete( resourceGroupName: string, vmName: string, options?: VirtualMachinesDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * The operation to delete a virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginDeleteAndWait( resourceGroupName: string, vmName: string, options?: VirtualMachinesDeleteOptionalParams ): Promise<void>; /** * Retrieves information about the model view or the instance view of a virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ get( resourceGroupName: string, vmName: string, options?: VirtualMachinesGetOptionalParams ): Promise<VirtualMachinesGetResponse>; /** * Retrieves information about the run-time state of a virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ instanceView( resourceGroupName: string, vmName: string, options?: VirtualMachinesInstanceViewOptionalParams ): Promise<VirtualMachinesInstanceViewResponse>; /** * Converts virtual machine disks from blob-based to managed disks. Virtual machine must be * stop-deallocated before invoking this operation. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginConvertToManagedDisks( resourceGroupName: string, vmName: string, options?: VirtualMachinesConvertToManagedDisksOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Converts virtual machine disks from blob-based to managed disks. Virtual machine must be * stop-deallocated before invoking this operation. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginConvertToManagedDisksAndWait( resourceGroupName: string, vmName: string, options?: VirtualMachinesConvertToManagedDisksOptionalParams ): Promise<void>; /** * Shuts down the virtual machine and releases the compute resources. You are not billed for the * compute resources that this virtual machine uses. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginDeallocate( resourceGroupName: string, vmName: string, options?: VirtualMachinesDeallocateOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Shuts down the virtual machine and releases the compute resources. You are not billed for the * compute resources that this virtual machine uses. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginDeallocateAndWait( resourceGroupName: string, vmName: string, options?: VirtualMachinesDeallocateOptionalParams ): Promise<void>; /** * Sets the OS state of the virtual machine to generalized. It is recommended to sysprep the virtual * machine before performing this operation. <br>For Windows, please refer to [Create a managed image * of a generalized VM in * Azure](https://docs.microsoft.com/azure/virtual-machines/windows/capture-image-resource).<br>For * Linux, please refer to [How to create an image of a virtual machine or * VHD](https://docs.microsoft.com/azure/virtual-machines/linux/capture-image). * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ generalize( resourceGroupName: string, vmName: string, options?: VirtualMachinesGeneralizeOptionalParams ): Promise<void>; /** * The operation to power off (stop) a virtual machine. The virtual machine can be restarted with the * same provisioned resources. You are still charged for this virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginPowerOff( resourceGroupName: string, vmName: string, options?: VirtualMachinesPowerOffOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * The operation to power off (stop) a virtual machine. The virtual machine can be restarted with the * same provisioned resources. You are still charged for this virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginPowerOffAndWait( resourceGroupName: string, vmName: string, options?: VirtualMachinesPowerOffOptionalParams ): Promise<void>; /** * The operation to reapply a virtual machine's state. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginReapply( resourceGroupName: string, vmName: string, options?: VirtualMachinesReapplyOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * The operation to reapply a virtual machine's state. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginReapplyAndWait( resourceGroupName: string, vmName: string, options?: VirtualMachinesReapplyOptionalParams ): Promise<void>; /** * The operation to restart a virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginRestart( resourceGroupName: string, vmName: string, options?: VirtualMachinesRestartOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * The operation to restart a virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginRestartAndWait( resourceGroupName: string, vmName: string, options?: VirtualMachinesRestartOptionalParams ): Promise<void>; /** * The operation to start a virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginStart( resourceGroupName: string, vmName: string, options?: VirtualMachinesStartOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * The operation to start a virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginStartAndWait( resourceGroupName: string, vmName: string, options?: VirtualMachinesStartOptionalParams ): Promise<void>; /** * Shuts down the virtual machine, moves it to a new node, and powers it back on. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginRedeploy( resourceGroupName: string, vmName: string, options?: VirtualMachinesRedeployOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Shuts down the virtual machine, moves it to a new node, and powers it back on. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginRedeployAndWait( resourceGroupName: string, vmName: string, options?: VirtualMachinesRedeployOptionalParams ): Promise<void>; /** * Reimages the virtual machine which has an ephemeral OS disk back to its initial state. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginReimage( resourceGroupName: string, vmName: string, options?: VirtualMachinesReimageOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Reimages the virtual machine which has an ephemeral OS disk back to its initial state. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginReimageAndWait( resourceGroupName: string, vmName: string, options?: VirtualMachinesReimageOptionalParams ): Promise<void>; /** * The operation to retrieve SAS URIs for a virtual machine's boot diagnostic logs. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ retrieveBootDiagnosticsData( resourceGroupName: string, vmName: string, options?: VirtualMachinesRetrieveBootDiagnosticsDataOptionalParams ): Promise<VirtualMachinesRetrieveBootDiagnosticsDataResponse>; /** * The operation to perform maintenance on a virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginPerformMaintenance( resourceGroupName: string, vmName: string, options?: VirtualMachinesPerformMaintenanceOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * The operation to perform maintenance on a virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginPerformMaintenanceAndWait( resourceGroupName: string, vmName: string, options?: VirtualMachinesPerformMaintenanceOptionalParams ): Promise<void>; /** * The operation to simulate the eviction of spot virtual machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ simulateEviction( resourceGroupName: string, vmName: string, options?: VirtualMachinesSimulateEvictionOptionalParams ): Promise<void>; /** * Assess patches on the VM. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginAssessPatches( resourceGroupName: string, vmName: string, options?: VirtualMachinesAssessPatchesOptionalParams ): Promise< PollerLike< PollOperationState<VirtualMachinesAssessPatchesResponse>, VirtualMachinesAssessPatchesResponse > >; /** * Assess patches on the VM. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param options The options parameters. */ beginAssessPatchesAndWait( resourceGroupName: string, vmName: string, options?: VirtualMachinesAssessPatchesOptionalParams ): Promise<VirtualMachinesAssessPatchesResponse>; /** * Installs patches on the VM. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param installPatchesInput Input for InstallPatches as directly received by the API * @param options The options parameters. */ beginInstallPatches( resourceGroupName: string, vmName: string, installPatchesInput: VirtualMachineInstallPatchesParameters, options?: VirtualMachinesInstallPatchesOptionalParams ): Promise< PollerLike< PollOperationState<VirtualMachinesInstallPatchesResponse>, VirtualMachinesInstallPatchesResponse > >; /** * Installs patches on the VM. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param installPatchesInput Input for InstallPatches as directly received by the API * @param options The options parameters. */ beginInstallPatchesAndWait( resourceGroupName: string, vmName: string, installPatchesInput: VirtualMachineInstallPatchesParameters, options?: VirtualMachinesInstallPatchesOptionalParams ): Promise<VirtualMachinesInstallPatchesResponse>; /** * Run command on the VM. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param parameters Parameters supplied to the Run command operation. * @param options The options parameters. */ beginRunCommand( resourceGroupName: string, vmName: string, parameters: RunCommandInput, options?: VirtualMachinesRunCommandOptionalParams ): Promise< PollerLike< PollOperationState<VirtualMachinesRunCommandResponse>, VirtualMachinesRunCommandResponse > >; /** * Run command on the VM. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine. * @param parameters Parameters supplied to the Run command operation. * @param options The options parameters. */ beginRunCommandAndWait( resourceGroupName: string, vmName: string, parameters: RunCommandInput, options?: VirtualMachinesRunCommandOptionalParams ): Promise<VirtualMachinesRunCommandResponse>; }
the_stack
* Variable: DEFAULT_HOTSPOT * * Defines the portion of the cell which is to be used as a connectable * region. Default is 0.3. Possible values are 0 < x <= 1. */ export const DEFAULT_HOTSPOT = 0.3; /** * Variable: MIN_HOTSPOT_SIZE * * Defines the minimum size in pixels of the portion of the cell which is * to be used as a connectable region. Default is 8. */ export const MIN_HOTSPOT_SIZE = 8; /** * Variable: MAX_HOTSPOT_SIZE * * Defines the maximum size in pixels of the portion of the cell which is * to be used as a connectable region. Use 0 for no maximum. Default is 0. */ export const MAX_HOTSPOT_SIZE = 0; /** * Variable: RENDERING_HINT_EXACT * * Defines the exact rendering hint. */ export const RENDERING_HINT_EXACT = 'exact'; /** * Variable: RENDERING_HINT_FASTER * * Defines the faster rendering hint. */ export const RENDERING_HINT_FASTER = 'faster'; /** * Variable: RENDERING_HINT_FASTEST * * Defines the fastest rendering hint. */ export const RENDERING_HINT_FASTEST = 'fastest'; /** * Variable: DIALECT_SVG * * Defines the SVG display dialect name. */ export const DIALECT_SVG = 'svg'; /** * Variable: DIALECT_MIXEDHTML * * Defines the mixed HTML display dialect name. */ export const DIALECT_MIXEDHTML = 'mixedHtml'; /** * Variable: DIALECT_PREFERHTML * * Defines the preferred HTML display dialect name. */ export const DIALECT_PREFERHTML = 'preferHtml'; /** * Variable: DIALECT_STRICTHTML * * Defines the strict HTML display dialect. */ export const DIALECT_STRICTHTML = 'strictHtml'; /** * Variable: NS_SVG * * Defines the SVG namespace. */ export const NS_SVG = 'http://www.w3.org/2000/svg'; /** * Variable: NS_XLINK * * Defines the XLink namespace. */ export const NS_XLINK = 'http://www.w3.org/1999/xlink'; /** * Variable: SHADOWCOLOR * * Defines the color to be used to draw shadows in shapes and windows. * Default is gray. */ export const SHADOWCOLOR = 'gray'; /** * Variable: VML_SHADOWCOLOR * * Used for shadow color in filters where transparency is not supported * (Microsoft Internet Explorer). Default is gray. */ export const VML_SHADOWCOLOR = 'gray'; /** * Variable: SHADOW_OFFSET_X * * Specifies the x-offset of the shadow. Default is 2. */ export const SHADOW_OFFSET_X = 2; /** * Variable: SHADOW_OFFSET_Y * * Specifies the y-offset of the shadow. Default is 3. */ export const SHADOW_OFFSET_Y = 3; /** * Variable: SHADOW_OPACITY * * Defines the opacity for shadows. Default is 1. */ export const SHADOW_OPACITY = 1; /** * Variable: NODETYPE_ELEMENT * * DOM node of type ELEMENT. */ export const NODETYPE_ELEMENT = 1; /** * Variable: NODETYPE_ATTRIBUTE * * DOM node of type ATTRIBUTE. */ export const NODETYPE_ATTRIBUTE = 2; /** * Variable: NODETYPE_TEXT * * DOM node of type TEXT. */ export const NODETYPE_TEXT = 3; /** * Variable: NODETYPE_CDATA * * DOM node of type CDATA. */ export const NODETYPE_CDATA = 4; /** * Variable: NODETYPE_ENTITY_REFERENCE * * DOM node of type ENTITY_REFERENCE. */ export const NODETYPE_ENTITY_REFERENCE = 5; /** * Variable: NODETYPE_ENTITY * * DOM node of type ENTITY. */ export const NODETYPE_ENTITY = 6; /** * Variable: NODETYPE_PROCESSING_INSTRUCTION * * DOM node of type PROCESSING_INSTRUCTION. */ export const NODETYPE_PROCESSING_INSTRUCTION = 7; /** * Variable: NODETYPE_COMMENT * * DOM node of type COMMENT. */ export const NODETYPE_COMMENT = 8; /** * Variable: NODETYPE_DOCUMENT * * DOM node of type DOCUMENT. */ export const NODETYPE_DOCUMENT = 9; /** * Variable: NODETYPE_DOCUMENTTYPE * * DOM node of type DOCUMENTTYPE. */ export const NODETYPE_DOCUMENTTYPE = 10; /** * Variable: NODETYPE_DOCUMENT_FRAGMENT * * DOM node of type DOCUMENT_FRAGMENT. */ export const NODETYPE_DOCUMENT_FRAGMENT = 11; /** * Variable: NODETYPE_NOTATION * * DOM node of type NOTATION. */ export const NODETYPE_NOTATION = 12; /** * Variable: TOOLTIP_VERTICAL_OFFSET * * Defines the vertical offset for the tooltip. * Default is 16. */ export const TOOLTIP_VERTICAL_OFFSET = 16; /** * Variable: DEFAULT_VALID_COLOR * * Specifies the default valid color. Default is #0000FF. */ export const DEFAULT_VALID_COLOR = '#00FF00'; /** * Variable: DEFAULT_INVALID_COLOR * * Specifies the default invalid color. Default is #FF0000. */ export const DEFAULT_INVALID_COLOR = '#FF0000'; /** * Variable: OUTLINE_HIGHLIGHT_COLOR * * Specifies the default highlight color for shape outlines. * Default is #0000FF. This is used in <mxEdgeHandler>. */ export const OUTLINE_HIGHLIGHT_COLOR = '#00FF00'; /** * Variable: OUTLINE_HIGHLIGHT_COLOR * * Defines the strokewidth to be used for shape outlines. * Default is 5. This is used in <mxEdgeHandler>. */ export const OUTLINE_HIGHLIGHT_STROKEWIDTH = 5; /** * Variable: HIGHLIGHT_STROKEWIDTH * * Defines the strokewidth to be used for the highlights. * Default is 3. */ export const HIGHLIGHT_STROKEWIDTH = 3; /** * Variable: CONSTRAINT_HIGHLIGHT_SIZE * * Size of the constraint highlight (in px). Default is 2. */ export const HIGHLIGHT_SIZE = 2; /** * Variable: HIGHLIGHT_OPACITY * * Opacity (in %) used for the highlights (including outline). * Default is 100. */ export const HIGHLIGHT_OPACITY = 100; /** * Variable: CURSOR_MOVABLE_VERTEX * * Defines the cursor for a movable vertex. Default is 'move'. */ export const CURSOR_MOVABLE_VERTEX = 'move'; /** * Variable: CURSOR_MOVABLE_EDGE * * Defines the cursor for a movable edge. Default is 'move'. */ export const CURSOR_MOVABLE_EDGE = 'move'; /** * Variable: CURSOR_LABEL_HANDLE * * Defines the cursor for a movable label. Default is 'default'. */ export const CURSOR_LABEL_HANDLE = 'default'; /** * Variable: CURSOR_TERMINAL_HANDLE * * Defines the cursor for a terminal handle. Default is 'pointer'. */ export const CURSOR_TERMINAL_HANDLE = 'pointer'; /** * Variable: CURSOR_BEND_HANDLE * * Defines the cursor for a movable bend. Default is 'crosshair'. */ export const CURSOR_BEND_HANDLE = 'crosshair'; /** * Variable: CURSOR_VIRTUAL_BEND_HANDLE * * Defines the cursor for a movable bend. Default is 'crosshair'. */ export const CURSOR_VIRTUAL_BEND_HANDLE = 'crosshair'; /** * Variable: CURSOR_CONNECT * * Defines the cursor for a connectable state. Default is 'pointer'. */ export const CURSOR_CONNECT = 'pointer'; /** * Variable: HIGHLIGHT_COLOR * * Defines the color to be used for the cell highlighting. * Use 'none' for no color. Default is #00FF00. */ export const HIGHLIGHT_COLOR = '#00FF00'; /** * Variable: TARGET_HIGHLIGHT_COLOR * * Defines the color to be used for highlighting a target cell for a new * or changed connection. Note that this may be either a source or * target terminal in the graph. Use 'none' for no color. * Default is #0000FF. */ export const CONNECT_TARGET_COLOR = '#0000FF'; /** * Variable: INVALID_CONNECT_TARGET_COLOR * * Defines the color to be used for highlighting a invalid target cells * for a new or changed connections. Note that this may be either a source * or target terminal in the graph. Use 'none' for no color. Default is * #FF0000. */ export const INVALID_CONNECT_TARGET_COLOR = '#FF0000'; /** * Variable: DROP_TARGET_COLOR * * Defines the color to be used for the highlighting target parent cells * (for drag and drop). Use 'none' for no color. Default is #0000FF. */ export const DROP_TARGET_COLOR = '#0000FF'; /** * Variable: VALID_COLOR * * Defines the color to be used for the coloring valid connection * previews. Use 'none' for no color. Default is #FF0000. */ export const VALID_COLOR = '#00FF00'; /** * Variable: INVALID_COLOR * * Defines the color to be used for the coloring invalid connection * previews. Use 'none' for no color. Default is #FF0000. */ export const INVALID_COLOR = '#FF0000'; /** * Variable: EDGE_SELECTION_COLOR * * Defines the color to be used for the selection border of edges. Use * 'none' for no color. Default is #00FF00. */ export const EDGE_SELECTION_COLOR = '#00FF00'; /** * Variable: VERTEX_SELECTION_COLOR * * Defines the color to be used for the selection border of vertices. Use * 'none' for no color. Default is #00FF00. */ export const VERTEX_SELECTION_COLOR = '#00FF00'; /** * Variable: VERTEX_SELECTION_STROKEWIDTH * * Defines the strokewidth to be used for vertex selections. * Default is 1. */ export const VERTEX_SELECTION_STROKEWIDTH = 1; /** * Variable: EDGE_SELECTION_STROKEWIDTH * * Defines the strokewidth to be used for edge selections. * Default is 1. */ export const EDGE_SELECTION_STROKEWIDTH = 1; /** * Variable: SELECTION_DASHED * * Defines the dashed state to be used for the vertex selection * border. Default is true. */ export const VERTEX_SELECTION_DASHED = true; /** * Variable: SELECTION_DASHED * * Defines the dashed state to be used for the edge selection * border. Default is true. */ export const EDGE_SELECTION_DASHED = true; /** * Variable: GUIDE_COLOR * * Defines the color to be used for the guidelines in mxGraphHandler. * Default is #FF0000. */ export const GUIDE_COLOR = '#FF0000'; /** * Variable: GUIDE_STROKEWIDTH * * Defines the strokewidth to be used for the guidelines in mxGraphHandler. * Default is 1. */ export const GUIDE_STROKEWIDTH = 1; /** * Variable: OUTLINE_COLOR * * Defines the color to be used for the outline rectangle * border. Use 'none' for no color. Default is #0099FF. */ export const OUTLINE_COLOR = '#0099FF'; /** * Variable: OUTLINE_STROKEWIDTH * * Defines the strokewidth to be used for the outline rectangle * stroke width. Default is 3. */ export const OUTLINE_STROKEWIDTH = 3; /** * Variable: HANDLE_SIZE * * Defines the default size for handles. Default is 6. */ export const HANDLE_SIZE = 6; /** * Variable: LABEL_HANDLE_SIZE * * Defines the default size for label handles. Default is 4. */ export const LABEL_HANDLE_SIZE = 4; /** * Variable: HANDLE_FILLCOLOR * * Defines the color to be used for the handle fill color. Use 'none' for * no color. Default is #00FF00 (green). */ export const HANDLE_FILLCOLOR = '#00FF00'; /** * Variable: HANDLE_STROKECOLOR * * Defines the color to be used for the handle stroke color. Use 'none' for * no color. Default is black. */ export const HANDLE_STROKECOLOR = 'black'; /** * Variable: LABEL_HANDLE_FILLCOLOR * * Defines the color to be used for the label handle fill color. Use 'none' * for no color. Default is yellow. */ export const LABEL_HANDLE_FILLCOLOR = 'yellow'; /** * Variable: CONNECT_HANDLE_FILLCOLOR * * Defines the color to be used for the connect handle fill color. Use * 'none' for no color. Default is #0000FF (blue). */ export const CONNECT_HANDLE_FILLCOLOR = '#0000FF'; /** * Variable: LOCKED_HANDLE_FILLCOLOR * * Defines the color to be used for the locked handle fill color. Use * 'none' for no color. Default is #FF0000 (red). */ export const LOCKED_HANDLE_FILLCOLOR = '#FF0000'; /** * Variable: OUTLINE_HANDLE_FILLCOLOR * * Defines the color to be used for the outline sizer fill color. Use * 'none' for no color. Default is #00FFFF. */ export const OUTLINE_HANDLE_FILLCOLOR = '#00FFFF'; /** * Variable: OUTLINE_HANDLE_STROKECOLOR * * Defines the color to be used for the outline sizer stroke color. Use * 'none' for no color. Default is #0033FF. */ export const OUTLINE_HANDLE_STROKECOLOR = '#0033FF'; /** * Variable: DEFAULT_FONTFAMILY * * Defines the default family for all fonts. Default is Arial,Helvetica. */ export const DEFAULT_FONTFAMILY = 'Arial,Helvetica'; /** * Variable: DEFAULT_FONTSIZE * * Defines the default size (in px). Default is 11. */ export const DEFAULT_FONTSIZE = 11; /** * Variable: DEFAULT_TEXT_DIRECTION * * Defines the default value for the <STYLE_TEXT_DIRECTION> if no value is * defined for it in the style. Default value is an empty string which means * the default system setting is used and no direction is set. */ export const DEFAULT_TEXT_DIRECTION = ''; /** * Variable: LINE_HEIGHT * * Defines the default line height for text labels. Default is 1.2. */ export const LINE_HEIGHT = 1.2; /** * Variable: WORD_WRAP * * Defines the CSS value for the word-wrap property. Default is "normal". * Change this to "break-word" to allow long words to be able to be broken * and wrap onto the next line. */ export const WORD_WRAP = 'normal'; /** * Variable: ABSOLUTE_LINE_HEIGHT * * Specifies if absolute line heights should be used (px) in CSS. Default * is false. Set this to true for backwards compatibility. */ export const ABSOLUTE_LINE_HEIGHT = false; /** * Variable: DEFAULT_FONTSTYLE * * Defines the default style for all fonts. Default is 0. This can be set * to any combination of font styles as follows. * * (code) * mxConstants.DEFAULT_FONTSTYLE = mxConstants.FONT_BOLD | mxConstants.FONT_ITALIC; * (end) */ export const DEFAULT_FONTSTYLE = 0; /** * Variable: DEFAULT_STARTSIZE * * Defines the default start size for swimlanes. Default is 40. */ export const DEFAULT_STARTSIZE = 40; /** * Variable: DEFAULT_MARKERSIZE * * Defines the default size for all markers. Default is 6. */ export const DEFAULT_MARKERSIZE = 6; /** * Variable: DEFAULT_IMAGESIZE * * Defines the default width and height for images used in the * label shape. Default is 24. */ export const DEFAULT_IMAGESIZE = 24; /** * Variable: ENTITY_SEGMENT * * Defines the length of the horizontal segment of an Entity Relation. * This can be overridden using <'segment'> style. * Default is 30. */ export const ENTITY_SEGMENT = 30; /** * Variable: RECTANGLE_ROUNDING_FACTOR * * Defines the rounding factor for rounded rectangles in percent between * 0 and 1. Values should be smaller than 0.5. Default is 0.15. */ export const RECTANGLE_ROUNDING_FACTOR = 0.15; /** * Variable: LINE_ARCSIZE * * Defines the size of the arcs for rounded edges. Default is 20. */ export const LINE_ARCSIZE = 20; /** * Variable: ARROW_SPACING * * Defines the spacing between the arrow shape and its terminals. Default is 0. */ export const ARROW_SPACING = 0; /** * Variable: ARROW_WIDTH * * Defines the width of the arrow shape. Default is 30. */ export const ARROW_WIDTH = 30; /** * Variable: ARROW_SIZE * * Defines the size of the arrowhead in the arrow shape. Default is 30. */ export const ARROW_SIZE = 30; /** * Variable: PAGE_FORMAT_A4_PORTRAIT * * Defines the rectangle for the A4 portrait page format. The dimensions * of this page format are 826x1169 pixels. */ export const PAGE_FORMAT_A4_PORTRAIT = [0, 0, 827, 1169]; /** * Variable: PAGE_FORMAT_A4_PORTRAIT * * Defines the rectangle for the A4 portrait page format. The dimensions * of this page format are 826x1169 pixels. */ export const PAGE_FORMAT_A4_LANDSCAPE = [0, 0, 1169, 827]; /** * Variable: PAGE_FORMAT_LETTER_PORTRAIT * * Defines the rectangle for the Letter portrait page format. The * dimensions of this page format are 850x1100 pixels. */ export const PAGE_FORMAT_LETTER_PORTRAIT = [0, 0, 850, 1100]; /** * Variable: PAGE_FORMAT_LETTER_PORTRAIT * * Defines the rectangle for the Letter portrait page format. The dimensions * of this page format are 850x1100 pixels. */ export const PAGE_FORMAT_LETTER_LANDSCAPE = [0, 0, 1100, 850]; /** * Variable: NONE * * Defines the value for none. Default is "none". */ export const NONE = 'none'; /** * Variable: FONT_BOLD * * Constant for bold fonts. Default is 1. */ export const FONT_BOLD = 1; /** * Variable: FONT_ITALIC * * Constant for italic fonts. Default is 2. */ export const FONT_ITALIC = 2; /** * Variable: FONT_UNDERLINE * * Constant for underlined fonts. Default is 4. */ export const FONT_UNDERLINE = 4; /** * Variable: FONT_STRIKETHROUGH * * Constant for strikthrough fonts. Default is 8. */ export const FONT_STRIKETHROUGH = 8; /** * Variable: SHAPE_RECTANGLE * * Name under which <mxRectangleShape> is registered in <mxCellRenderer>. * Default is rectangle. */ export const SHAPE_RECTANGLE = 'rectangle'; /** * Variable: SHAPE_ELLIPSE * * Name under which <mxEllipse> is registered in <mxCellRenderer>. * Default is ellipse. */ export const SHAPE_ELLIPSE = 'ellipse'; /** * Variable: SHAPE_DOUBLE_ELLIPSE * * Name under which <mxDoubleEllipse> is registered in <mxCellRenderer>. * Default is doubleEllipse. */ export const SHAPE_DOUBLE_ELLIPSE = 'doubleEllipse'; /** * Variable: SHAPE_RHOMBUS * * Name under which <mxRhombus> is registered in <mxCellRenderer>. * Default is rhombus. */ export const SHAPE_RHOMBUS = 'rhombus'; /** * Variable: SHAPE_LINE * * Name under which <mxLine> is registered in <mxCellRenderer>. * Default is line. */ export const SHAPE_LINE = 'line'; /** * Variable: SHAPE_IMAGE * * Name under which <mxImageShape> is registered in <mxCellRenderer>. * Default is image. */ export const SHAPE_IMAGE = 'image'; /** * Variable: SHAPE_ARROW * * Name under which <mxArrow> is registered in <mxCellRenderer>. * Default is arrow. */ export const SHAPE_ARROW = 'arrow'; /** * Variable: SHAPE_ARROW_CONNECTOR * * Name under which <mxArrowConnector> is registered in <mxCellRenderer>. * Default is arrowConnector. */ export const SHAPE_ARROW_CONNECTOR = 'arrowConnector'; /** * Variable: SHAPE_LABEL * * Name under which <mxLabel> is registered in <mxCellRenderer>. * Default is label. */ export const SHAPE_LABEL = 'label'; /** * Variable: SHAPE_CYLINDER * * Name under which <mxCylinder> is registered in <mxCellRenderer>. * Default is cylinder. */ export const SHAPE_CYLINDER = 'cylinder'; /** * Variable: SHAPE_SWIMLANE * * Name under which <mxSwimlane> is registered in <mxCellRenderer>. * Default is swimlane. */ export const SHAPE_SWIMLANE = 'swimlane'; /** * Variable: SHAPE_CONNECTOR * * Name under which <mxConnector> is registered in <mxCellRenderer>. * Default is connector. */ export const SHAPE_CONNECTOR = 'connector'; /** * Variable: SHAPE_ACTOR * * Name under which <mxActor> is registered in <mxCellRenderer>. * Default is actor. */ export const SHAPE_ACTOR = 'actor'; /** * Variable: SHAPE_CLOUD * * Name under which <mxCloud> is registered in <mxCellRenderer>. * Default is cloud. */ export const SHAPE_CLOUD = 'cloud'; /** * Variable: SHAPE_TRIANGLE * * Name under which <mxTriangle> is registered in <mxCellRenderer>. * Default is triangle. */ export const SHAPE_TRIANGLE = 'triangle'; /** * Variable: SHAPE_HEXAGON * * Name under which <mxHexagon> is registered in <mxCellRenderer>. * Default is hexagon. */ export const SHAPE_HEXAGON = 'hexagon'; /** * Variable: ARROW_CLASSIC * * Constant for classic arrow markers. */ export const ARROW_CLASSIC = 'classic'; /** * Variable: ARROW_CLASSIC_THIN * * Constant for thin classic arrow markers. */ export const ARROW_CLASSIC_THIN = 'classicThin'; /** * Variable: ARROW_BLOCK * * Constant for block arrow markers. */ export const ARROW_BLOCK = 'block'; /** * Variable: ARROW_BLOCK_THIN * * Constant for thin block arrow markers. */ export const ARROW_BLOCK_THIN = 'blockThin'; /** * Variable: ARROW_OPEN * * Constant for open arrow markers. */ export const ARROW_OPEN = 'open'; /** * Variable: ARROW_OPEN_THIN * * Constant for thin open arrow markers. */ export const ARROW_OPEN_THIN = 'openThin'; /** * Variable: ARROW_OVAL * * Constant for oval arrow markers. */ export const ARROW_OVAL = 'oval'; /** * Variable: ARROW_DIAMOND * * Constant for diamond arrow markers. */ export const ARROW_DIAMOND = 'diamond'; /** * Variable: ARROW_DIAMOND_THIN * * Constant for thin diamond arrow markers. */ export const ARROW_DIAMOND_THIN = 'diamondThin'; /** * Variable: ALIGN_LEFT * * Constant for left horizontal alignment. Default is left. */ export const ALIGN_LEFT = 'left'; /** * Variable: ALIGN_CENTER * * Constant for center horizontal alignment. Default is center. */ export const ALIGN_CENTER = 'center'; /** * Variable: ALIGN_RIGHT * * Constant for right horizontal alignment. Default is right. */ export const ALIGN_RIGHT = 'right'; /** * Variable: ALIGN_TOP * * Constant for top vertical alignment. Default is top. */ export const ALIGN_TOP = 'top'; /** * Variable: ALIGN_MIDDLE * * Constant for middle vertical alignment. Default is middle. */ export const ALIGN_MIDDLE = 'middle'; /** * Variable: ALIGN_BOTTOM * * Constant for bottom vertical alignment. Default is bottom. */ export const ALIGN_BOTTOM = 'bottom'; /** * Variable: DIRECTION_NORTH * * Constant for direction north. Default is north. */ export const DIRECTION_NORTH = 'north'; /** * Variable: DIRECTION_SOUTH * * Constant for direction south. Default is south. */ export const DIRECTION_SOUTH = 'south'; /** * Variable: DIRECTION_EAST * * Constant for direction east. Default is east. */ export const DIRECTION_EAST = 'east'; /** * Variable: DIRECTION_WEST * * Constant for direction west. Default is west. */ export const DIRECTION_WEST = 'west'; /** * Variable: TEXT_DIRECTION_DEFAULT * * Constant for text direction default. Default is an empty string. Use * this value to use the default text direction of the operating system. */ export const TEXT_DIRECTION_DEFAULT = ''; /** * Variable: TEXT_DIRECTION_AUTO * * Constant for text direction automatic. Default is auto. Use this value * to find the direction for a given text with <mxText.getAutoDirection>. */ export const TEXT_DIRECTION_AUTO = 'auto'; /** * Variable: TEXT_DIRECTION_LTR * * Constant for text direction left to right. Default is ltr. Use this * value for left to right text direction. */ export const TEXT_DIRECTION_LTR = 'ltr'; /** * Variable: TEXT_DIRECTION_RTL * * Constant for text direction right to left. Default is rtl. Use this * value for right to left text direction. */ export const TEXT_DIRECTION_RTL = 'rtl'; /** * Variable: DIRECTION_MASK_NONE * * Constant for no direction. */ export const DIRECTION_MASK_NONE = 0; /** * Variable: DIRECTION_MASK_WEST * * Bitwise mask for west direction. */ export const DIRECTION_MASK_WEST = 1; /** * Variable: DIRECTION_MASK_NORTH * * Bitwise mask for north direction. */ export const DIRECTION_MASK_NORTH = 2; /** * Variable: DIRECTION_MASK_SOUTH * * Bitwise mask for south direction. */ export const DIRECTION_MASK_SOUTH = 4; /** * Variable: DIRECTION_MASK_EAST * * Bitwise mask for east direction. */ export const DIRECTION_MASK_EAST = 8; /** * Variable: DIRECTION_MASK_ALL * * Bitwise mask for all directions. */ export const DIRECTION_MASK_ALL = 15; /** * Variable: ELBOW_VERTICAL * * Constant for elbow vertical. Default is horizontal. */ export const ELBOW_VERTICAL = 'vertical'; /** * Variable: ELBOW_HORIZONTAL * * Constant for elbow horizontal. Default is horizontal. */ export const ELBOW_HORIZONTAL = 'horizontal'; /** * Variable: EDGESTYLE_ELBOW * * Name of the elbow edge style. Can be used as a string value * for the STYLE_EDGE style. */ export const EDGESTYLE_ELBOW = 'elbowEdgeStyle'; /** * Variable: EDGESTYLE_ENTITY_RELATION * * Name of the entity relation edge style. Can be used as a string value * for the STYLE_EDGE style. */ export const EDGESTYLE_ENTITY_RELATION = 'entityRelationEdgeStyle'; /** * Variable: EDGESTYLE_LOOP * * Name of the loop edge style. Can be used as a string value * for the STYLE_EDGE style. */ export const EDGESTYLE_LOOP = 'loopEdgeStyle'; /** * Variable: EDGESTYLE_SIDETOSIDE * * Name of the side to side edge style. Can be used as a string value * for the STYLE_EDGE style. */ export const EDGESTYLE_SIDETOSIDE = 'sideToSideEdgeStyle'; /** * Variable: EDGESTYLE_TOPTOBOTTOM * * Name of the top to bottom edge style. Can be used as a string value * for the STYLE_EDGE style. */ export const EDGESTYLE_TOPTOBOTTOM = 'topToBottomEdgeStyle'; /** * Variable: EDGESTYLE_ORTHOGONAL * * Name of the generic orthogonal edge style. Can be used as a string value * for the STYLE_EDGE style. */ export const EDGESTYLE_ORTHOGONAL = 'orthogonalEdgeStyle'; /** * Variable: EDGESTYLE_SEGMENT * * Name of the generic segment edge style. Can be used as a string value * for the STYLE_EDGE style. */ export const EDGESTYLE_SEGMENT = 'segmentEdgeStyle'; /** * Variable: PERIMETER_ELLIPSE * * Name of the ellipse perimeter. Can be used as a string value * for the STYLE_PERIMETER style. */ export const PERIMETER_ELLIPSE = 'ellipsePerimeter'; /** * Variable: PERIMETER_RECTANGLE * * Name of the rectangle perimeter. Can be used as a string value * for the STYLE_PERIMETER style. */ export const PERIMETER_RECTANGLE = 'rectanglePerimeter'; /** * Variable: PERIMETER_RHOMBUS * * Name of the rhombus perimeter. Can be used as a string value * for the STYLE_PERIMETER style. */ export const PERIMETER_RHOMBUS = 'rhombusPerimeter'; /** * Variable: PERIMETER_HEXAGON * * Name of the hexagon perimeter. Can be used as a string value * for the STYLE_PERIMETER style. */ export const PERIMETER_HEXAGON = 'hexagonPerimeter'; /** * Variable: PERIMETER_TRIANGLE * * Name of the triangle perimeter. Can be used as a string value * for the STYLE_PERIMETER style. */ export const PERIMETER_TRIANGLE = 'trianglePerimeter';
the_stack
import delay from 'delay' import { mockProcessExit, mockProcessStderr, mockProcessStdout } from 'jest-mock-process' import { Listr } from '@root/index' describe('show subtasks', () => { let mockExit: jest.SpyInstance<never, [number?]> // eslint-disable-next-line @typescript-eslint/ban-types let mockStdout: jest.SpyInstance<boolean, [string, string?, Function?]> // eslint-disable-next-line @typescript-eslint/ban-types let mockStderr: jest.SpyInstance<boolean, [string, string?, Function?]> process.stdout.isTTY = true beforeEach(async () => { mockExit = mockProcessExit() mockStdout = mockProcessStdout() mockStderr = mockProcessStderr() }) afterEach(async () => { mockExit.mockRestore() mockStdout.mockRestore() mockStderr.mockRestore() jest.clearAllMocks() }) // JQYWVb3x1scokQK2IzhwA4F0qxWbYzXR it('should create a set of subtasks', async () => { await new Listr( [ { title: 'This task will execute.', task: (ctx, task): Listr => task.newListr([ { title: 'This is a subtask.', task: async (): Promise<void> => { await delay(30) } }, { title: 'This is a subtask.', task: async (): Promise<void> => { await delay(30) } } ]) } ], { concurrent: false, rendererOptions: { lazy: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('JQYWVb3x1scokQK2IzhwA4F0qxWbYzXR-out') expect(mockStderr.mock.calls).toMatchSnapshot('JQYWVb3x1scokQK2IzhwA4F0qxWbYzXR-err') expect(mockExit.mock.calls).toMatchSnapshot('JQYWVb3x1scokQK2IzhwA4F0qxWbYzXR-exit') }) // 3ygUxrTkCDLDfDrXzF1ocWR6626jaL0k it('should be able to change concurrency setting in subtask, second subtask should finish first', async () => { await new Listr( [ { title: 'This task will execute.', task: (ctx, task): Listr => task.newListr( [ { title: 'This is a subtask.', task: async (): Promise<void> => { await delay(30) } }, { title: 'This is an another subtask.', task: async (): Promise<void> => { await delay(20) } } ], { concurrent: true } ) } ], { concurrent: false, rendererOptions: { lazy: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('3ygUxrTkCDLDfDrXzF1ocWR6626jaL0k-out') expect(mockStderr.mock.calls).toMatchSnapshot('3ygUxrTkCDLDfDrXzF1ocWR6626jaL0k-err') expect(mockExit.mock.calls).toMatchSnapshot('3ygUxrTkCDLDfDrXzF1ocWR6626jaL0k-exit') }) // 8TNRrm8bI9ndz4jrhYC492luGNhtMTmZ it('should be able to change collapse settings', async () => { await new Listr( [ { title: 'This task will execute.', task: (ctx, task): Listr => task.newListr([ { title: 'This is a subtask.', task: async (): Promise<void> => { await delay(30) } }, { title: 'This is an another subtask.', task: async (): Promise<void> => { await delay(20) } } ]) }, { title: 'This task will execute.', task: (ctx, task): Listr => task.newListr( [ { title: 'This is a subtask.', task: async (): Promise<void> => { await delay(30) } }, { title: 'This is an another subtask.', task: async (): Promise<void> => { await delay(20) } } ], { rendererOptions: { collapse: false } } ) } ], { concurrent: false, rendererOptions: { lazy: true, collapse: true } } ).run() expect(mockStdout.mock.calls).toMatchSnapshot('8TNRrm8bI9ndz4jrhYC492luGNhtMTmZ-out') expect(mockStderr.mock.calls).toMatchSnapshot('8TNRrm8bI9ndz4jrhYC492luGNhtMTmZ-err') expect(mockExit.mock.calls).toMatchSnapshot('8TNRrm8bI9ndz4jrhYC492luGNhtMTmZ-exit') }) // 12ttDlnth5pr1YuJEnfXm3I2CzRbcFlY it('should be able to change exit on error', async () => { try { await new Listr( [ { title: 'This task will execute and not quit on errors.', task: (ctx, task): Listr => task.newListr( [ { title: 'This is a subtask.', task: async (): Promise<void> => { throw new Error('I have failed [0]') } }, { title: 'This is an another subtask.', task: async (): Promise<void> => { throw new Error('I have failed [1]') } }, { title: 'This is yet an another subtask.', task: async (ctx, task): Promise<void> => { task.title = 'I have succeeded.' } } ], { exitOnError: false } ) }, { title: 'This task will execute.', task: (): void => { throw new Error('exit') } } ], { concurrent: false, exitOnError: true, rendererOptions: { lazy: true } } ).run() } catch (e: any) { expect(e).toBeTruthy() } expect(mockStdout.mock.calls).toMatchSnapshot('12ttDlnth5pr1YuJEnfXm3I2CzRbcFlY-out') expect(mockStderr.mock.calls).toMatchSnapshot('12ttDlnth5pr1YuJEnfXm3I2CzRbcFlY-err') expect(mockExit.mock.calls).toMatchSnapshot('12ttDlnth5pr1YuJEnfXm3I2CzRbcFlY-exit') }) // 9VMxFnaAKNjetcT1a9gLgN0dnasB7BRc it('should be able to render subtasks with no title with correct indentation', async () => { try { await new Listr( [ { title: 'This task will execute.', task: (ctx, task): void => { task.output = 'output' task.output = 'some more output' task.output = 'even more output' }, options: { bottomBar: Infinity, persistentOutput: true } }, { title: 'This task will execute a task without titles.', task: (ctx, task): Listr => task.newListr( [ { task: async (): Promise<void> => { await delay(10) } }, { task: async (): Promise<void> => { await delay(10) } }, { task: async (): Promise<void> => { await delay(10) } } ], { exitOnError: false } ) } ], { concurrent: false, exitOnError: true, rendererOptions: { lazy: true } } ).run() } catch (e: any) { expect(e).toBeTruthy() } expect(mockStdout.mock.calls).toMatchSnapshot('9VMxFnaAKNjetcT1a9gLgN0dnasB7BRc-out') expect(mockStderr.mock.calls).toMatchSnapshot('9VMxFnaAKNjetcT1a9gLgN0dnasB7BRc-err') expect(mockExit.mock.calls).toMatchSnapshot('9VMxFnaAKNjetcT1a9gLgN0dnasB7BRc-exit') }) // oGL7rWlMEOEDNqOOFgj2R9ilvahlLAuR it.each([ [ true, false ] ])('should output the task error in parent task with collapseErrors: %s and show subtasks: false', async (cases) => { try { await new Listr( [ { title: 'This task will execute.', task: (ctx, task): Listr => task.newListr([ { title: 'This is a subtask.', task: async (): Promise<void> => { await delay(3) throw new Error('bye') } }, { title: 'This is a subtask.', task: async (): Promise<void> => { await delay(3) } } ]) } ], { concurrent: true, exitOnError: true, rendererOptions: { lazy: true, showSubtasks: false, collapseErrors: cases } } ).run() } catch (e: any) { expect(e).toBeTruthy() } expect(mockStdout.mock.calls).toMatchSnapshot('oGL7rWlMEOEDNqOOFgj2R9ilvahlLAuR-out') expect(mockStderr.mock.calls).toMatchSnapshot('oGL7rWlMEOEDNqOOFgj2R9ilvahlLAuR-err') expect(mockExit.mock.calls).toMatchSnapshot('oGL7rWlMEOEDNqOOFgj2R9ilvahlLAuR-exit') }) // bcaTpU40igebiNC4Koho5ObSuJxhYPsJ it.each([ true, false ])('should output the task error in parent task with: collapseErrors: %s showsubtasks: true', async (cases) => { try { await new Listr( [ { title: 'This task will execute.', task: (_, task): Listr => task.newListr([ { title: 'This is a subtask.', task: async (): Promise<void> => { await delay(3) throw new Error('bye') } }, { title: 'This is a subtask.', task: async (): Promise<void> => { await delay(3) } } ]) } ], { concurrent: true, exitOnError: true, rendererOptions: { lazy: true, showSubtasks: true, collapseErrors: cases } } ).run() } catch (e: any) { expect(e).toBeTruthy() } expect(mockStdout.mock.calls).toMatchSnapshot('bcaTpU40igebiNC4Koho5ObSuJxhYPsJ-out') expect(mockStderr.mock.calls).toMatchSnapshot('bcaTpU40igebiNC4Koho5ObSuJxhYPsJ-err') expect(mockExit.mock.calls).toMatchSnapshot('bcaTpU40igebiNC4Koho5ObSuJxhYPsJ-exit') }) })
the_stack
export type ColorSpecification = string; export type FormattedSpecification = string; export type ResolvedImageSpecification = string; export type PromoteIdSpecification = {[_: string]: string} | string; export type FilterSpecification = ['has', string] | ['!has', string] | ['==', string, string | number | boolean] | ['!=', string, string | number | boolean] | ['>', string, string | number | boolean] | ['>=', string, string | number | boolean] | ['<', string, string | number | boolean] | ['<=', string, string | number | boolean] | Array<string | FilterSpecification>; // Can't type in, !in, all, any, none -- https://github.com/facebook/flow/issues/2443 export type TransitionSpecification = { duration?: number, delay?: number }; // Note: doesn't capture interpolatable vs. non-interpolatable types. export type CameraFunctionSpecification<T> = { type: 'exponential', stops: Array<[number, T]> } | { type: 'interval', stops: Array<[number, T]> }; export type SourceFunctionSpecification<T> = { type: 'exponential', stops: Array<[number, T]>, property: string, default?: T } | { type: 'interval', stops: Array<[number, T]>, property: string, default?: T } | { type: 'categorical', stops: Array<[string | number | boolean, T]>, property: string, default?: T } | { type: 'identity', property: string, default?: T }; export type CompositeFunctionSpecification<T> = { type: 'exponential', stops: Array<[{zoom: number, value: number}, T]>, property: string, default?: T } | { type: 'interval', stops: Array<[{zoom: number, value: number}, T]>, property: string, default?: T } | { type: 'categorical', stops: Array<[{zoom: number, value: string | number | boolean}, T]>, property: string, default?: T }; export type ExpressionSpecification = Array<unknown>; export type PropertyValueSpecification<T> = T | CameraFunctionSpecification<T> | ExpressionSpecification; export type DataDrivenPropertyValueSpecification<T> = T | CameraFunctionSpecification<T> | SourceFunctionSpecification<T> | CompositeFunctionSpecification<T> | ExpressionSpecification; export type StyleSpecification = { "version": 8, "name"?: string, "metadata"?: unknown, "center"?: Array<number>, "zoom"?: number, "bearing"?: number, "pitch"?: number, "light"?: LightSpecification, "sources": {[_: string]: SourceSpecification}, "sprite"?: string, "glyphs"?: string, "transition"?: TransitionSpecification, "layers": Array<LayerSpecification> }; export type LightSpecification = { "anchor"?: PropertyValueSpecification<"map" | "viewport">, "position"?: PropertyValueSpecification<[number, number, number]>, "color"?: PropertyValueSpecification<ColorSpecification>, "intensity"?: PropertyValueSpecification<number> }; export type VectorSourceSpecification = { "type": "vector", "url"?: string, "tiles"?: Array<string>, "bounds"?: [number, number, number, number], "scheme"?: "xyz" | "tms", "minzoom"?: number, "maxzoom"?: number, "attribution"?: string, "promoteId"?: PromoteIdSpecification, "volatile"?: boolean }; export type RasterSourceSpecification = { "type": "raster", "url"?: string, "tiles"?: Array<string>, "bounds"?: [number, number, number, number], "minzoom"?: number, "maxzoom"?: number, "tileSize"?: number, "scheme"?: "xyz" | "tms", "attribution"?: string, "volatile"?: boolean }; export type RasterDEMSourceSpecification = { "type": "raster-dem", "url"?: string, "tiles"?: Array<string>, "bounds"?: [number, number, number, number], "minzoom"?: number, "maxzoom"?: number, "tileSize"?: number, "attribution"?: string, "encoding"?: "terrarium" | "mapbox", "volatile"?: boolean }; export type GeoJSONSourceSpecification = { "type": "geojson", "data"?: unknown, "maxzoom"?: number, "attribution"?: string, "buffer"?: number, "filter"?: unknown, "tolerance"?: number, "cluster"?: boolean, "clusterRadius"?: number, "clusterMaxZoom"?: number, "clusterMinPoints"?: number, "clusterProperties"?: unknown, "lineMetrics"?: boolean, "generateId"?: boolean, "promoteId"?: PromoteIdSpecification }; export type VideoSourceSpecification = { "type": "video", "urls": Array<string>, "coordinates": [[number, number], [number, number], [number, number], [number, number]] }; export type ImageSourceSpecification = { "type": "image", "url": string, "coordinates": [[number, number], [number, number], [number, number], [number, number]] }; export type SourceSpecification = | VectorSourceSpecification | RasterSourceSpecification | RasterDEMSourceSpecification | GeoJSONSourceSpecification | VideoSourceSpecification | ImageSourceSpecification export type FillLayerSpecification = { "id": string, "type": "fill", "metadata"?: unknown, "source": string, "source-layer"?: string, "minzoom"?: number, "maxzoom"?: number, "filter"?: FilterSpecification, "layout"?: { "fill-sort-key"?: DataDrivenPropertyValueSpecification<number>, "visibility"?: "visible" | "none" }, "paint"?: { "fill-antialias"?: PropertyValueSpecification<boolean>, "fill-opacity"?: DataDrivenPropertyValueSpecification<number>, "fill-color"?: DataDrivenPropertyValueSpecification<ColorSpecification>, "fill-outline-color"?: DataDrivenPropertyValueSpecification<ColorSpecification>, "fill-translate"?: PropertyValueSpecification<[number, number]>, "fill-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, "fill-pattern"?: DataDrivenPropertyValueSpecification<ResolvedImageSpecification> } }; export type LineLayerSpecification = { "id": string, "type": "line", "metadata"?: unknown, "source": string, "source-layer"?: string, "minzoom"?: number, "maxzoom"?: number, "filter"?: FilterSpecification, "layout"?: { "line-cap"?: PropertyValueSpecification<"butt" | "round" | "square">, "line-join"?: DataDrivenPropertyValueSpecification<"bevel" | "round" | "miter">, "line-miter-limit"?: PropertyValueSpecification<number>, "line-round-limit"?: PropertyValueSpecification<number>, "line-sort-key"?: DataDrivenPropertyValueSpecification<number>, "visibility"?: "visible" | "none" }, "paint"?: { "line-opacity"?: DataDrivenPropertyValueSpecification<number>, "line-color"?: DataDrivenPropertyValueSpecification<ColorSpecification>, "line-translate"?: PropertyValueSpecification<[number, number]>, "line-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, "line-width"?: DataDrivenPropertyValueSpecification<number>, "line-gap-width"?: DataDrivenPropertyValueSpecification<number>, "line-offset"?: DataDrivenPropertyValueSpecification<number>, "line-blur"?: DataDrivenPropertyValueSpecification<number>, "line-dasharray"?: PropertyValueSpecification<Array<number>>, "line-pattern"?: DataDrivenPropertyValueSpecification<ResolvedImageSpecification>, "line-gradient"?: ExpressionSpecification } }; export type SymbolLayerSpecification = { "id": string, "type": "symbol", "metadata"?: unknown, "source": string, "source-layer"?: string, "minzoom"?: number, "maxzoom"?: number, "filter"?: FilterSpecification, "layout"?: { "symbol-placement"?: PropertyValueSpecification<"point" | "line" | "line-center">, "symbol-spacing"?: PropertyValueSpecification<number>, "symbol-avoid-edges"?: PropertyValueSpecification<boolean>, "symbol-sort-key"?: DataDrivenPropertyValueSpecification<number>, "symbol-z-order"?: PropertyValueSpecification<"auto" | "viewport-y" | "source">, "icon-allow-overlap"?: PropertyValueSpecification<boolean>, "icon-ignore-placement"?: PropertyValueSpecification<boolean>, "icon-optional"?: PropertyValueSpecification<boolean>, "icon-rotation-alignment"?: PropertyValueSpecification<"map" | "viewport" | "auto">, "icon-size"?: DataDrivenPropertyValueSpecification<number>, "icon-text-fit"?: PropertyValueSpecification<"none" | "width" | "height" | "both">, "icon-text-fit-padding"?: PropertyValueSpecification<[number, number, number, number]>, "icon-image"?: DataDrivenPropertyValueSpecification<ResolvedImageSpecification>, "icon-rotate"?: DataDrivenPropertyValueSpecification<number>, "icon-padding"?: PropertyValueSpecification<number>, "icon-keep-upright"?: PropertyValueSpecification<boolean>, "icon-offset"?: DataDrivenPropertyValueSpecification<[number, number]>, "icon-anchor"?: DataDrivenPropertyValueSpecification<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">, "icon-pitch-alignment"?: PropertyValueSpecification<"map" | "viewport" | "auto">, "text-pitch-alignment"?: PropertyValueSpecification<"map" | "viewport" | "auto">, "text-rotation-alignment"?: PropertyValueSpecification<"map" | "viewport" | "auto">, "text-field"?: DataDrivenPropertyValueSpecification<FormattedSpecification>, "text-font"?: DataDrivenPropertyValueSpecification<Array<string>>, "text-size"?: DataDrivenPropertyValueSpecification<number>, "text-max-width"?: DataDrivenPropertyValueSpecification<number>, "text-line-height"?: PropertyValueSpecification<number>, "text-letter-spacing"?: DataDrivenPropertyValueSpecification<number>, "text-justify"?: DataDrivenPropertyValueSpecification<"auto" | "left" | "center" | "right">, "text-radial-offset"?: DataDrivenPropertyValueSpecification<number>, "text-variable-anchor"?: PropertyValueSpecification<Array<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">>, "text-anchor"?: DataDrivenPropertyValueSpecification<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">, "text-max-angle"?: PropertyValueSpecification<number>, "text-writing-mode"?: PropertyValueSpecification<Array<"horizontal" | "vertical">>, "text-rotate"?: DataDrivenPropertyValueSpecification<number>, "text-padding"?: PropertyValueSpecification<number>, "text-keep-upright"?: PropertyValueSpecification<boolean>, "text-transform"?: DataDrivenPropertyValueSpecification<"none" | "uppercase" | "lowercase">, "text-offset"?: DataDrivenPropertyValueSpecification<[number, number]>, "text-allow-overlap"?: PropertyValueSpecification<boolean>, "text-ignore-placement"?: PropertyValueSpecification<boolean>, "text-optional"?: PropertyValueSpecification<boolean>, "visibility"?: "visible" | "none" }, "paint"?: { "icon-opacity"?: DataDrivenPropertyValueSpecification<number>, "icon-color"?: DataDrivenPropertyValueSpecification<ColorSpecification>, "icon-halo-color"?: DataDrivenPropertyValueSpecification<ColorSpecification>, "icon-halo-width"?: DataDrivenPropertyValueSpecification<number>, "icon-halo-blur"?: DataDrivenPropertyValueSpecification<number>, "icon-translate"?: PropertyValueSpecification<[number, number]>, "icon-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, "text-opacity"?: DataDrivenPropertyValueSpecification<number>, "text-color"?: DataDrivenPropertyValueSpecification<ColorSpecification>, "text-halo-color"?: DataDrivenPropertyValueSpecification<ColorSpecification>, "text-halo-width"?: DataDrivenPropertyValueSpecification<number>, "text-halo-blur"?: DataDrivenPropertyValueSpecification<number>, "text-translate"?: PropertyValueSpecification<[number, number]>, "text-translate-anchor"?: PropertyValueSpecification<"map" | "viewport"> } }; export type CircleLayerSpecification = { "id": string, "type": "circle", "metadata"?: unknown, "source": string, "source-layer"?: string, "minzoom"?: number, "maxzoom"?: number, "filter"?: FilterSpecification, "layout"?: { "circle-sort-key"?: DataDrivenPropertyValueSpecification<number>, "visibility"?: "visible" | "none" }, "paint"?: { "circle-radius"?: DataDrivenPropertyValueSpecification<number>, "circle-color"?: DataDrivenPropertyValueSpecification<ColorSpecification>, "circle-blur"?: DataDrivenPropertyValueSpecification<number>, "circle-opacity"?: DataDrivenPropertyValueSpecification<number>, "circle-translate"?: PropertyValueSpecification<[number, number]>, "circle-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, "circle-pitch-scale"?: PropertyValueSpecification<"map" | "viewport">, "circle-pitch-alignment"?: PropertyValueSpecification<"map" | "viewport">, "circle-stroke-width"?: DataDrivenPropertyValueSpecification<number>, "circle-stroke-color"?: DataDrivenPropertyValueSpecification<ColorSpecification>, "circle-stroke-opacity"?: DataDrivenPropertyValueSpecification<number> } }; export type HeatmapLayerSpecification = { "id": string, "type": "heatmap", "metadata"?: unknown, "source": string, "source-layer"?: string, "minzoom"?: number, "maxzoom"?: number, "filter"?: FilterSpecification, "layout"?: { "visibility"?: "visible" | "none" }, "paint"?: { "heatmap-radius"?: DataDrivenPropertyValueSpecification<number>, "heatmap-weight"?: DataDrivenPropertyValueSpecification<number>, "heatmap-intensity"?: PropertyValueSpecification<number>, "heatmap-color"?: ExpressionSpecification, "heatmap-opacity"?: PropertyValueSpecification<number> } }; export type FillExtrusionLayerSpecification = { "id": string, "type": "fill-extrusion", "metadata"?: unknown, "source": string, "source-layer"?: string, "minzoom"?: number, "maxzoom"?: number, "filter"?: FilterSpecification, "layout"?: { "visibility"?: "visible" | "none" }, "paint"?: { "fill-extrusion-opacity"?: PropertyValueSpecification<number>, "fill-extrusion-color"?: DataDrivenPropertyValueSpecification<ColorSpecification>, "fill-extrusion-translate"?: PropertyValueSpecification<[number, number]>, "fill-extrusion-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, "fill-extrusion-pattern"?: DataDrivenPropertyValueSpecification<ResolvedImageSpecification>, "fill-extrusion-height"?: DataDrivenPropertyValueSpecification<number>, "fill-extrusion-base"?: DataDrivenPropertyValueSpecification<number>, "fill-extrusion-vertical-gradient"?: PropertyValueSpecification<boolean> } }; export type RasterLayerSpecification = { "id": string, "type": "raster", "metadata"?: unknown, "source": string, "source-layer"?: string, "minzoom"?: number, "maxzoom"?: number, "filter"?: FilterSpecification, "layout"?: { "visibility"?: "visible" | "none" }, "paint"?: { "raster-opacity"?: PropertyValueSpecification<number>, "raster-hue-rotate"?: PropertyValueSpecification<number>, "raster-brightness-min"?: PropertyValueSpecification<number>, "raster-brightness-max"?: PropertyValueSpecification<number>, "raster-saturation"?: PropertyValueSpecification<number>, "raster-contrast"?: PropertyValueSpecification<number>, "raster-resampling"?: PropertyValueSpecification<"linear" | "nearest">, "raster-fade-duration"?: PropertyValueSpecification<number> } }; export type HillshadeLayerSpecification = { "id": string, "type": "hillshade", "metadata"?: unknown, "source": string, "source-layer"?: string, "minzoom"?: number, "maxzoom"?: number, "filter"?: FilterSpecification, "layout"?: { "visibility"?: "visible" | "none" }, "paint"?: { "hillshade-illumination-direction"?: PropertyValueSpecification<number>, "hillshade-illumination-anchor"?: PropertyValueSpecification<"map" | "viewport">, "hillshade-exaggeration"?: PropertyValueSpecification<number>, "hillshade-shadow-color"?: PropertyValueSpecification<ColorSpecification>, "hillshade-highlight-color"?: PropertyValueSpecification<ColorSpecification>, "hillshade-accent-color"?: PropertyValueSpecification<ColorSpecification> } }; export type BackgroundLayerSpecification = { "id": string, "type": "background", "metadata"?: unknown, "minzoom"?: number, "maxzoom"?: number, "layout"?: { "visibility"?: "visible" | "none" }, "paint"?: { "background-color"?: PropertyValueSpecification<ColorSpecification>, "background-pattern"?: PropertyValueSpecification<ResolvedImageSpecification>, "background-opacity"?: PropertyValueSpecification<number> } }; export type LayerSpecification = | FillLayerSpecification | LineLayerSpecification | SymbolLayerSpecification | CircleLayerSpecification | HeatmapLayerSpecification | FillExtrusionLayerSpecification | RasterLayerSpecification | HillshadeLayerSpecification | BackgroundLayerSpecification;
the_stack
import { includes, isUndefined, isNull, isArray, isObject, isBoolean, defaults, each, extend, find, has, initial, last, clone, reduce, keys, isEmpty, forEach, } from 'lodash'; export function RestangularConfigurer(object, configuration) { object.configuration = configuration; /** * Those are HTTP safe methods for which there is no need to pass any data with the request. */ const safeMethods = ['get', 'head', 'options', 'trace', 'getlist']; configuration.isSafe = function (operation) { return includes(safeMethods, operation.toLowerCase()); }; const absolutePattern = /^https?:\/\//i; configuration.isAbsoluteUrl = function (string) { return isUndefined(configuration.absoluteUrl) || isNull(configuration.absoluteUrl) ? string && absolutePattern.test(string) : configuration.absoluteUrl; }; configuration.absoluteUrl = isUndefined(configuration.absoluteUrl) ? true : configuration.absoluteUrl; object.setSelfLinkAbsoluteUrl = function (value) { configuration.absoluteUrl = value; }; /** * This is the BaseURL to be used with Restangular */ configuration.baseUrl = isUndefined(configuration.baseUrl) ? '' : configuration.baseUrl; object.setBaseUrl = function (newBaseUrl) { configuration.baseUrl = /\/$/.test(newBaseUrl) ? newBaseUrl.substring(0, newBaseUrl.length - 1) : newBaseUrl; return this; }; /** * Sets the extra fields to keep from the parents */ configuration.extraFields = configuration.extraFields || []; object.setExtraFields = function (newExtraFields) { configuration.extraFields = newExtraFields; return this; }; /** * Some default $http parameter to be used in EVERY call **/ configuration.defaultHttpFields = configuration.defaultHttpFields || {}; object.setDefaultHttpFields = function (values) { configuration.defaultHttpFields = values; return this; }; /** * Always return plain data, no restangularized object **/ configuration.plainByDefault = configuration.plainByDefault || false; object.setPlainByDefault = function (value) { configuration.plainByDefault = value === true ? true : false; return this; }; configuration.withHttpValues = function (httpLocalConfig, obj) { return defaults(obj, httpLocalConfig, configuration.defaultHttpFields); }; configuration.encodeIds = isUndefined(configuration.encodeIds) ? true : configuration.encodeIds; object.setEncodeIds = function (encode) { configuration.encodeIds = encode; }; configuration.defaultRequestParams = configuration.defaultRequestParams || { get: {}, post: {}, put: {}, remove: {}, common: {} }; object.setDefaultRequestParams = function (param1, param2) { let methods = []; const params = param2 || param1; if (!isUndefined(param2)) { if (isArray(param1)) { methods = param1; } else { methods.push(param1); } } else { methods.push('common'); } each(methods, function (method) { configuration.defaultRequestParams[method] = params; }); return this; }; object.requestParams = configuration.defaultRequestParams; configuration.defaultHeaders = configuration.defaultHeaders || {}; object.setDefaultHeaders = function (headers) { configuration.defaultHeaders = headers; object.defaultHeaders = configuration.defaultHeaders; return this; }; object.defaultHeaders = configuration.defaultHeaders; /** * Method overriders response Method **/ configuration.defaultResponseMethod = configuration.defaultResponseMethod || 'promise'; object.setDefaultResponseMethod = function (method) { configuration.defaultResponseMethod = method; object.defaultResponseMethod = configuration.defaultResponseMethod; return this; }; object.defaultResponseMethod = configuration.defaultResponseMethod; /** * Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override **/ configuration.methodOverriders = configuration.methodOverriders || []; object.setMethodOverriders = function (values) { const overriders = extend([], values); if (configuration.isOverridenMethod('delete', overriders)) { overriders.push('remove'); } configuration.methodOverriders = overriders; return this; }; configuration.jsonp = isUndefined(configuration.jsonp) ? false : configuration.jsonp; object.setJsonp = function (active) { configuration.jsonp = active; }; configuration.isOverridenMethod = function (method, values) { const search = values || configuration.methodOverriders; return !isUndefined(find(search, function (one: string) { return one.toLowerCase() === method.toLowerCase(); })); }; /** * Sets the URL creator type. For now, only Path is created. In the future we'll have queryParams **/ configuration.urlCreator = configuration.urlCreator || 'path'; object.setUrlCreator = function (name) { if (!has(configuration.urlCreatorFactory, name)) { throw new Error('URL Path selected isn\'t valid'); } configuration.urlCreator = name; return this; }; /** * You can set the restangular fields here. The 3 required fields for Restangular are: * * id: Id of the element * route: name of the route of this element * parentResource: the reference to the parent resource * * All of this fields except for id, are handled (and created) by Restangular. By default, * the field values will be id, route and parentResource respectively */ configuration.restangularFields = configuration.restangularFields || { id: 'id', route: 'route', parentResource: 'parentResource', restangularCollection: 'restangularCollection', cannonicalId: '__cannonicalId', etag: 'restangularEtag', selfLink: 'href', get: 'get', getList: 'getList', put: 'put', post: 'post', remove: 'remove', head: 'head', trace: 'trace', options: 'options', patch: 'patch', getRestangularUrl: 'getRestangularUrl', getRequestedUrl: 'getRequestedUrl', putElement: 'putElement', addRestangularMethod: 'addRestangularMethod', getParentList: 'getParentList', clone: 'clone', ids: 'ids', httpConfig: '_$httpConfig', reqParams: 'reqParams', one: 'one', all: 'all', several: 'several', oneUrl: 'oneUrl', allUrl: 'allUrl', customPUT: 'customPUT', customPATCH: 'customPATCH', customPOST: 'customPOST', customDELETE: 'customDELETE', customGET: 'customGET', customGETLIST: 'customGETLIST', customOperation: 'customOperation', doPUT: 'doPUT', doPATCH: 'doPATCH', doPOST: 'doPOST', doDELETE: 'doDELETE', doGET: 'doGET', doGETLIST: 'doGETLIST', fromServer: 'fromServer', withConfig: 'withConfig', withHttpConfig: 'withHttpConfig', singleOne: 'singleOne', plain: 'plain', save: 'save', restangularized: 'restangularized' }; object.setRestangularFields = function (resFields) { configuration.restangularFields = extend({}, configuration.restangularFields, resFields); return this; }; configuration.isRestangularized = function (obj) { return !!obj[configuration.restangularFields.restangularized]; }; configuration.setFieldToElem = function (field, elem, value) { const properties = field.split('.'); let idValue = elem; each(initial(properties), function (prop: any) { idValue[prop] = {}; idValue = idValue[prop]; }); const index: any = last(properties); idValue[index] = value; return this; }; configuration.getFieldFromElem = function (field, elem) { const properties = field.split('.'); let idValue: any = elem; each(properties, function (prop) { if (idValue) { idValue = idValue[prop]; } }); return clone(idValue); }; configuration.setIdToElem = function (elem, id /*, route */) { configuration.setFieldToElem(configuration.restangularFields.id, elem, id); return this; }; configuration.getIdFromElem = function (elem) { return configuration.getFieldFromElem(configuration.restangularFields.id, elem); }; configuration.isValidId = function (elemId) { return '' !== elemId && !isUndefined(elemId) && !isNull(elemId); }; configuration.setUrlToElem = function (elem, url /*, route */) { configuration.setFieldToElem(configuration.restangularFields.selfLink, elem, url); return this; }; configuration.getUrlFromElem = function (elem) { return configuration.getFieldFromElem(configuration.restangularFields.selfLink, elem); }; configuration.useCannonicalId = isUndefined(configuration.useCannonicalId) ? false : configuration.useCannonicalId; object.setUseCannonicalId = function (value) { configuration.useCannonicalId = value; return this; }; configuration.getCannonicalIdFromElem = function (elem) { const cannonicalId = elem[configuration.restangularFields.cannonicalId]; const actualId = configuration.isValidId(cannonicalId) ? cannonicalId : configuration.getIdFromElem(elem); return actualId; }; /** * Sets the Response parser. This is used in case your response isn't directly the data. * For example if you have a response like {meta: {'meta'}, data: {name: 'Gonto'}} * you can extract this data which is the one that needs wrapping * * The ResponseExtractor is a function that receives the response and the method executed. */ configuration.responseInterceptors = configuration.responseInterceptors ? [...configuration.responseInterceptors] : []; configuration.defaultResponseInterceptor = function (data /*, operation, what, url, response, subject */) { return data || {}; }; configuration.responseExtractor = function (data, operation, what, url, response, subject) { const interceptors = clone(configuration.responseInterceptors); interceptors.push(configuration.defaultResponseInterceptor); let theData = data; each(interceptors, function (interceptor: any) { theData = interceptor(theData, operation, what, url, response, subject); }); return theData; }; object.addResponseInterceptor = function (extractor) { configuration.responseInterceptors.push(extractor); return this; }; configuration.errorInterceptors = configuration.errorInterceptors ? [...configuration.errorInterceptors] : []; object.addErrorInterceptor = function (interceptor) { configuration.errorInterceptors = [interceptor, ...configuration.errorInterceptors]; return this; }; object.setResponseInterceptor = object.addResponseInterceptor; object.setResponseExtractor = object.addResponseInterceptor; object.setErrorInterceptor = object.addErrorInterceptor; /** * Response interceptor is called just before resolving promises. */ /** * Request interceptor is called before sending an object to the server. */ configuration.requestInterceptors = configuration.requestInterceptors ? [...configuration.requestInterceptors] : []; configuration.defaultInterceptor = function (element, operation, path, url, headers, params, httpConfig) { return { element: element, headers: headers, params: params, httpConfig: httpConfig }; }; configuration.fullRequestInterceptor = function (element, operation, path, url, headers, params, httpConfig) { const interceptors = clone(configuration.requestInterceptors); const defaultRequest = configuration.defaultInterceptor(element, operation, path, url, headers, params, httpConfig); return reduce(interceptors, function (request: any, interceptor: any) { const returnInterceptor: any = interceptor( request.element, operation, path, url, request.headers, request.params, request.httpConfig ); return extend(request, returnInterceptor); }, defaultRequest); }; object.addRequestInterceptor = function (interceptor) { configuration.requestInterceptors.push(function (elem, operation, path, url, headers, params, httpConfig) { return { headers: headers, params: params, element: interceptor(elem, operation, path, url), httpConfig: httpConfig }; }); return this; }; object.setRequestInterceptor = object.addRequestInterceptor; object.addFullRequestInterceptor = function (interceptor) { configuration.requestInterceptors.push(interceptor); return this; }; object.setFullRequestInterceptor = object.addFullRequestInterceptor; configuration.onBeforeElemRestangularized = configuration.onBeforeElemRestangularized || function (elem) { return elem; }; object.setOnBeforeElemRestangularized = function (post) { configuration.onBeforeElemRestangularized = post; return this; }; object.setRestangularizePromiseInterceptor = function (interceptor) { configuration.restangularizePromiseInterceptor = interceptor; return this; }; /** * This method is called after an element has been "Restangularized". * * It receives the element, a boolean indicating if it's an element or a collection * and the name of the model * */ configuration.onElemRestangularized = configuration.onElemRestangularized || function (elem) { return elem; }; object.setOnElemRestangularized = function (post) { configuration.onElemRestangularized = post; return this; }; configuration.shouldSaveParent = configuration.shouldSaveParent || function () { return true; }; object.setParentless = function (values) { if (isArray(values)) { configuration.shouldSaveParent = function (route) { return !includes(values, route); }; } else if (isBoolean(values)) { configuration.shouldSaveParent = function () { return !values; }; } return this; }; /** * This lets you set a suffix to every request. * * For example, if your api requires that for JSon requests you do /users/123.json, you can set that * in here. * * * By default, the suffix is null */ configuration.suffix = isUndefined(configuration.suffix) ? null : configuration.suffix; object.setRequestSuffix = function (newSuffix) { configuration.suffix = newSuffix; return this; }; /** * Add element transformers for certain routes. */ configuration.transformers = configuration.transformers || {}; object.addElementTransformer = function (type, secondArg, thirdArg) { let isCollection = null; let transformer = null; if (arguments.length === 2) { transformer = secondArg; } else { transformer = thirdArg; isCollection = secondArg; } let typeTransformers = configuration.transformers[type]; if (!typeTransformers) { typeTransformers = configuration.transformers[type] = []; } typeTransformers.push(function (coll, elem) { if (isNull(isCollection) || (coll === isCollection)) { return transformer(elem); } return elem; }); return object; }; object.extendCollection = function (route, fn) { return object.addElementTransformer(route, true, fn); }; object.extendModel = function (route, fn) { return object.addElementTransformer(route, false, fn); }; configuration.transformElem = function (elem, isCollection, route, Restangular, force) { if (!force && !configuration.transformLocalElements && !elem[configuration.restangularFields.fromServer]) { return elem; } const typeTransformers = configuration.transformers[route]; let changedElem = elem; if (typeTransformers) { each(typeTransformers, function (transformer: (isCollection: boolean, changedElem: any) => any) { changedElem = transformer(isCollection, changedElem); }); } return configuration.onElemRestangularized(changedElem, isCollection, route, Restangular); }; configuration.transformLocalElements = isUndefined(configuration.transformLocalElements) ? false : configuration.transformLocalElements; object.setTransformOnlyServerElements = function (active) { configuration.transformLocalElements = !active; }; configuration.fullResponse = isUndefined(configuration.fullResponse) ? false : configuration.fullResponse; object.setFullResponse = function (full) { configuration.fullResponse = full; return this; }; // Internal values and functions configuration.urlCreatorFactory = {}; /** * Base URL Creator. Base prototype for everything related to it **/ const BaseCreator = function () { }; BaseCreator.prototype.setConfig = function (config) { this.config = config; return this; }; BaseCreator.prototype.parentsArray = function (current) { const parents = []; while (current) { parents.push(current); current = current[this.config.restangularFields.parentResource]; } return parents.reverse(); }; function RestangularResource(config, $http, url, configurer) { const resource = {}; each(keys(configurer), function (key) { const value = configurer[key]; // Add default parameters value.params = extend({}, value.params, config.defaultRequestParams[value.method.toLowerCase()]); // We don't want the ? if no params are there if (isEmpty(value.params)) { delete value.params; } if (config.isSafe(value.method)) { resource[key] = function () { const resultConfig = extend(value, { url: url }); return $http.createRequest(resultConfig); }; } else { resource[key] = function (data) { const resultConfig = extend(value, { url: url, data: data }); return $http.createRequest(resultConfig); }; } }); return resource; } BaseCreator.prototype.resource = function (current, $http, localHttpConfig, callHeaders, callParams, what, etag, operation) { const params = defaults(callParams || {}, this.config.defaultRequestParams.common); const headers = defaults(callHeaders || {}, this.config.defaultHeaders); if (etag) { if (!configuration.isSafe(operation)) { headers['If-Match'] = etag; } else { headers['If-None-Match'] = etag; } } let url = this.base(current); if (what) { let add = ''; if (!/\/$/.test(url)) { add += '/'; } add += what; url += add; } if (this.config.suffix && url.indexOf(this.config.suffix, url.length - this.config.suffix.length) === -1 && !this.config.getUrlFromElem(current)) { url += this.config.suffix; } current[this.config.restangularFields.httpConfig] = undefined; return RestangularResource(this.config, $http, url, { getList: this.config.withHttpValues(localHttpConfig, { method: 'GET', params: params, headers: headers }), get: this.config.withHttpValues(localHttpConfig, { method: 'GET', params: params, headers: headers }), jsonp: this.config.withHttpValues(localHttpConfig, { method: 'jsonp', params: params, headers: headers }), put: this.config.withHttpValues(localHttpConfig, { method: 'PUT', params: params, headers: headers }), post: this.config.withHttpValues(localHttpConfig, { method: 'POST', params: params, headers: headers }), remove: this.config.withHttpValues(localHttpConfig, { method: 'DELETE', params: params, headers: headers }), head: this.config.withHttpValues(localHttpConfig, { method: 'HEAD', params: params, headers: headers }), trace: this.config.withHttpValues(localHttpConfig, { method: 'TRACE', params: params, headers: headers }), options: this.config.withHttpValues(localHttpConfig, { method: 'OPTIONS', params: params, headers: headers }), patch: this.config.withHttpValues(localHttpConfig, { method: 'PATCH', params: params, headers: headers }) }); }; /** * This is the Path URL creator. It uses Path to show Hierarchy in the Rest API. * This means that if you have an Account that then has a set of Buildings, a URL to a building * would be /accounts/123/buildings/456 **/ const Path = function () { }; Path.prototype = new BaseCreator(); Path.prototype.normalizeUrl = function (url) { const parts = /((?:http[s]?:)?\/\/)?(.*)?/.exec(url); parts[2] = parts[2].replace(/[\\\/]+/g, '/'); return (typeof parts[1] !== 'undefined') ? parts[1] + parts[2] : parts[2]; }; Path.prototype.base = function (current) { const __this = this; return reduce(this.parentsArray(current), function (acum: any, elem: any) { let elemUrl; const elemSelfLink = __this.config.getUrlFromElem(elem); if (elemSelfLink) { if (__this.config.isAbsoluteUrl(elemSelfLink)) { return elemSelfLink; } else { elemUrl = elemSelfLink; } } else { elemUrl = elem[__this.config.restangularFields.route]; if (elem[__this.config.restangularFields.restangularCollection]) { const ids = elem[__this.config.restangularFields.ids]; if (ids) { elemUrl += '/' + ids.join(','); } } else { let elemId: any; if (__this.config.useCannonicalId) { elemId = __this.config.getCannonicalIdFromElem(elem); } else { elemId = __this.config.getIdFromElem(elem); } if (configuration.isValidId(elemId) && !elem.singleOne) { elemUrl += '/' + (__this.config.encodeIds ? encodeURIComponent(elemId) : elemId); } } } acum = acum.replace(/\/$/, '') + '/' + elemUrl; return __this.normalizeUrl(acum); }, this.config.baseUrl); }; Path.prototype.fetchUrl = function (current, what) { let baseUrl = this.base(current); if (what) { baseUrl += '/' + what; } return baseUrl; }; Path.prototype.fetchRequestedUrl = function (current, what) { const url = this.fetchUrl(current, what); const params = current[configuration.restangularFields.reqParams]; // From here on and until the end of fetchRequestedUrl, // the code has been kindly borrowed from angular.js // The reason for such code bloating is coherence: // If the user were to use this for cache management, the // serialization of parameters would need to be identical // to the one done by angular for cache keys to match. function sortedKeys(obj) { const resultKeys = []; for (const key in obj) { if (obj.hasOwnProperty(key)) { resultKeys.push(key); } } return resultKeys.sort(); } function forEachSorted(obj, iterator?, context?) { const sortedKeysArray = sortedKeys(obj); for (let i = 0; i < sortedKeysArray.length; i++) { iterator.call(context, obj[sortedKeysArray[i]], sortedKeysArray[i]); } return sortedKeysArray; } function encodeUriQuery(val, pctEncodeSpaces?) { return encodeURIComponent(val) .replace(/%40/gi, '@') .replace(/%3A/gi, ':') .replace(/%24/g, '$') .replace(/%2C/gi, ',') .replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); } if (!params) { return url + (this.config.suffix || ''); } const parts = []; forEachSorted(params, function (value, key) { if (value === null || value === undefined) { return; } if (!isArray(value)) { value = [value]; } forEach(value, function (v) { if (isObject(v)) { v = JSON.stringify(v); } parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(v)); }); }); return url + (this.config.suffix || '') + ((url.indexOf('?') === -1) ? '?' : '&') + parts.join('&'); }; configuration.urlCreatorFactory.path = Path; }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [appconfig](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsappconfig.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Appconfig extends PolicyStatement { public servicePrefix = 'appconfig'; /** * Statement provider for service [appconfig](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsappconfig.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to create an application * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_CreateApplication.html */ public toCreateApplication() { return this.to('CreateApplication'); } /** * Grants permission to create a configuration profile * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_CreateConfigurationProfile.html */ public toCreateConfigurationProfile() { return this.to('CreateConfigurationProfile'); } /** * Grants permission to create a deployment strategy * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_CreateDeploymentStrategy.html */ public toCreateDeploymentStrategy() { return this.to('CreateDeploymentStrategy'); } /** * Grants permission to create an environment * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_CreateEnvironment.html */ public toCreateEnvironment() { return this.to('CreateEnvironment'); } /** * Grants permission to create a hosted configuration version * * Access Level: Write * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_CreateHostedConfigurationVersion.html */ public toCreateHostedConfigurationVersion() { return this.to('CreateHostedConfigurationVersion'); } /** * Grants permission to delete an application * * Access Level: Write * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_DeleteApplication.html */ public toDeleteApplication() { return this.to('DeleteApplication'); } /** * Grants permission to delete a configuration profile * * Access Level: Write * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_DeleteConfigurationProfile.html */ public toDeleteConfigurationProfile() { return this.to('DeleteConfigurationProfile'); } /** * Grants permission to delete a deployment strategy * * Access Level: Write * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_DeleteDeploymentStrategy.html */ public toDeleteDeploymentStrategy() { return this.to('DeleteDeploymentStrategy'); } /** * Grants permission to delete an environment * * Access Level: Write * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_DeleteEnvironment.html */ public toDeleteEnvironment() { return this.to('DeleteEnvironment'); } /** * Grants permission to delete a hosted configuration version * * Access Level: Write * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_DeleteHostedConfigurationVersion.html */ public toDeleteHostedConfigurationVersion() { return this.to('DeleteHostedConfigurationVersion'); } /** * Grants permission to view details about an application * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_GetApplication.html */ public toGetApplication() { return this.to('GetApplication'); } /** * Grants permission to view details about a configuration * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_GetConfiguration.html */ public toGetConfiguration() { return this.to('GetConfiguration'); } /** * Grants permission to view details about a configuration profile * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_GetConfigurationProfile.html */ public toGetConfigurationProfile() { return this.to('GetConfigurationProfile'); } /** * Grants permission to view details about a deployment * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_GetDeployment.html */ public toGetDeployment() { return this.to('GetDeployment'); } /** * Grants permission to view details about a deployment strategy * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_GetDeploymentStrategy.html */ public toGetDeploymentStrategy() { return this.to('GetDeploymentStrategy'); } /** * Grants permission to view details about an environment * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_GetEnvironment.html */ public toGetEnvironment() { return this.to('GetEnvironment'); } /** * Grants permission to view details about a hosted configuration version * * Access Level: Read * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_GetHostedConfigurationVersion.html */ public toGetHostedConfigurationVersion() { return this.to('GetHostedConfigurationVersion'); } /** * Grants permission to list the applications in your account * * Access Level: List * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_ListApplications.html */ public toListApplications() { return this.to('ListApplications'); } /** * Grants permission to list the configuration profiles for an application * * Access Level: List * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_ListConfigurationProfiles.html */ public toListConfigurationProfiles() { return this.to('ListConfigurationProfiles'); } /** * Grants permission to list the deployment strategies for your account * * Access Level: List * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_ListDeploymentStrategies.html */ public toListDeploymentStrategies() { return this.to('ListDeploymentStrategies'); } /** * Grants permission to list the deployments for an environment * * Access Level: List * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_ListDeployments.html */ public toListDeployments() { return this.to('ListDeployments'); } /** * Grants permission to list the environments for an application * * Access Level: List * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_ListEnvironments.html */ public toListEnvironments() { return this.to('ListEnvironments'); } /** * Grants permission to list the hosted configuration versions for a configuration profile * * Access Level: List * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_ListHostedConfigurationVersions.html */ public toListHostedConfigurationVersions() { return this.to('ListHostedConfigurationVersions'); } /** * Grants permission to view a list of resource tags for a specified resource * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to initiate a deployment * * Access Level: Write * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_StartDeployment.html */ public toStartDeployment() { return this.to('StartDeployment'); } /** * Grants permission to stop a deployment * * Access Level: Write * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_StopDeployment.html */ public toStopDeployment() { return this.to('StopDeployment'); } /** * Grants permission to tag an appconfig resource. * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to untag an appconfig resource. * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to modify an application * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_UpdateApplication.html */ public toUpdateApplication() { return this.to('UpdateApplication'); } /** * Grants permission to modify a configuration profile * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_UpdateConfigurationProfile.html */ public toUpdateConfigurationProfile() { return this.to('UpdateConfigurationProfile'); } /** * Grants permission to modify a deployment strategy * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_UpdateDeploymentStrategy.html */ public toUpdateDeploymentStrategy() { return this.to('UpdateDeploymentStrategy'); } /** * Grants permission to modify an environment * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_UpdateEnvironment.html */ public toUpdateEnvironment() { return this.to('UpdateEnvironment'); } /** * Grants permission to validate a configuration * * Access Level: Write * * https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_ValidateConfiguration.html */ public toValidateConfiguration() { return this.to('ValidateConfiguration'); } protected accessLevelList: AccessLevelList = { "Write": [ "CreateApplication", "CreateConfigurationProfile", "CreateDeploymentStrategy", "CreateEnvironment", "CreateHostedConfigurationVersion", "DeleteApplication", "DeleteConfigurationProfile", "DeleteDeploymentStrategy", "DeleteEnvironment", "DeleteHostedConfigurationVersion", "StartDeployment", "StopDeployment", "UpdateApplication", "UpdateConfigurationProfile", "UpdateDeploymentStrategy", "UpdateEnvironment", "ValidateConfiguration" ], "Read": [ "GetApplication", "GetConfiguration", "GetConfigurationProfile", "GetDeployment", "GetDeploymentStrategy", "GetEnvironment", "GetHostedConfigurationVersion", "ListTagsForResource" ], "List": [ "ListApplications", "ListConfigurationProfiles", "ListDeploymentStrategies", "ListDeployments", "ListEnvironments", "ListHostedConfigurationVersions" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type application to the statement * * https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-application.html * * @param applicationId - Identifier for the applicationId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onApplication(applicationId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appconfig:${Region}:${Account}:application/${ApplicationId}'; arn = arn.replace('${ApplicationId}', applicationId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type environment to the statement * * https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-environment.html * * @param applicationId - Identifier for the applicationId. * @param environmentId - Identifier for the environmentId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onEnvironment(applicationId: string, environmentId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appconfig:${Region}:${Account}:application/${ApplicationId}/environment/${EnvironmentId}'; arn = arn.replace('${ApplicationId}', applicationId); arn = arn.replace('${EnvironmentId}', environmentId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type configurationprofile to the statement * * https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html * * @param applicationId - Identifier for the applicationId. * @param configurationProfileId - Identifier for the configurationProfileId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onConfigurationprofile(applicationId: string, configurationProfileId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appconfig:${Region}:${Account}:application/${ApplicationId}/configurationprofile/${ConfigurationProfileId}'; arn = arn.replace('${ApplicationId}', applicationId); arn = arn.replace('${ConfigurationProfileId}', configurationProfileId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type deploymentstrategy to the statement * * https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-deployment-strategy.html * * @param deploymentStrategyId - Identifier for the deploymentStrategyId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onDeploymentstrategy(deploymentStrategyId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appconfig:${Region}:${Account}:deploymentstrategy/${DeploymentStrategyId}'; arn = arn.replace('${DeploymentStrategyId}', deploymentStrategyId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type deployment to the statement * * https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-deploying.html * * @param applicationId - Identifier for the applicationId. * @param environmentId - Identifier for the environmentId. * @param deploymentNumber - Identifier for the deploymentNumber. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onDeployment(applicationId: string, environmentId: string, deploymentNumber: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appconfig:${Region}:${Account}:application/${ApplicationId}/environment/${EnvironmentId}/deployment/${DeploymentNumber}'; arn = arn.replace('${ApplicationId}', applicationId); arn = arn.replace('${EnvironmentId}', environmentId); arn = arn.replace('${DeploymentNumber}', deploymentNumber); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type hostedconfigurationversion to the statement * * https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html * * @param applicationId - Identifier for the applicationId. * @param configurationProfileId - Identifier for the configurationProfileId. * @param versionNumber - Identifier for the versionNumber. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onHostedconfigurationversion(applicationId: string, configurationProfileId: string, versionNumber: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appconfig:${Region}:${Account}:application/${ApplicationId}/configurationprofile/${ConfigurationProfileId}/hostedconfigurationversion/${VersionNumber}'; arn = arn.replace('${ApplicationId}', applicationId); arn = arn.replace('${ConfigurationProfileId}', configurationProfileId); arn = arn.replace('${VersionNumber}', versionNumber); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import assert = require("assert") //import fs = require("fs") //import path = require("path") //import _=require("underscore") // //import def = require("raml-definition-system") // //import ll=require("../lowLevelAST") import high = require("../highLevelImpl") import hl=require("../highLevelAST") // //import t3 = require("../artifacts/raml10parser") // import util = require("./test-utils") import tools = require("./testTools") import wrapper10=require("../artifacts/raml10parserapi") import _=require("underscore") describe('Runtime example tests', function() { this.timeout(15000); it('Should return JSON string example as JSON', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e1.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog2"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isJSONString(), true); var jsonExample = example.asJSON(); assert.deepEqual(jsonExample,{ "name": "Dog", "age": 33 }) }); it('Should return JSON string example as String', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e1.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog2"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isJSONString(), true); var jsonString = example.asString(); var jsonExample = JSON.parse(jsonString); assert.deepEqual(jsonExample,{ "name": "Dog", "age": 33 }) }); it('Should return JSON string example original', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e1.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog2"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isJSONString(), true); var jsonString = example.original(); var jsonExample = JSON.parse(jsonString); assert.deepEqual(jsonExample,{ "name": "Dog", "age": 33 }) }); it('Should return YAML string example as JSON', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e1.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isJSONString(), false); assert.equal(example.isYAML(), true); var jsonExample = example.asJSON(); assert.deepEqual(jsonExample,{ "name": "Dog", "age": 33 }) }); it('Should return YAML string example as String', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e1.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isJSONString(), false); assert.equal(example.isYAML(), true); var jsonString = example.asString(); var jsonExample = JSON.parse(jsonString); assert.deepEqual(jsonExample,{ "name": "Dog", "age": 33 }) }); it('Should return YAML string example original', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e1.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isJSONString(), false); assert.equal(example.isYAML(), true); var jsonExample = example.original(); assert.deepEqual(jsonExample,{ "name": "Dog", "age": 33 }) }); it('Should return expand and return proper string 1', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e1.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="ManWithDog"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isEmpty(), true); var jsonString = example.expandAsString(); var jsonExample = JSON.parse(jsonString); assert.deepEqual(jsonExample,{"name":"Pavel","d":{"name":"Dog","age":33}}) }); it('Should return expand and return proper JSON 1', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e1.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="ManWithDog"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isEmpty(), true); var jsonExample = example.expandAsJSON(); assert.deepEqual(jsonExample,{"name":"Pavel","d":{"name":"Dog","age":33}}) }); it('Should return JSON string example as JSON, include', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e2.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog2"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isJSONString(), true); var jsonExample = example.asJSON(); assert.deepEqual(jsonExample,{ "name": "Dog", "age": 33 }) }); it('Should return JSON string example as String, include', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e2.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog2"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isJSONString(), true); var jsonString = example.asString(); var jsonExample = JSON.parse(jsonString); assert.deepEqual(jsonExample,{ "name": "Dog", "age": 33 }) }); it('Should return JSON string example original, include', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e2.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog2"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isJSONString(), true); var jsonString = example.original(); var jsonExample = JSON.parse(jsonString); assert.deepEqual(jsonExample,{ "name": "Dog", "age": 33 }) }); it('Should return YAML string example as JSON, include', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e2.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isJSONString(), false); assert.equal(example.isYAML(), true); var jsonExample = example.asJSON(); assert.deepEqual(jsonExample,{ "name": "Dog", "age": 33 }) }); it('Should return YAML string example as String, include', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e2.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isJSONString(), false); assert.equal(example.isYAML(), true); var jsonString = example.asString(); var jsonExample = JSON.parse(jsonString); assert.deepEqual(jsonExample,{ "name": "Dog", "age": 33 }) }); it('Should return YAML string example original, include', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e2.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isJSONString(), false); assert.equal(example.isYAML(), true); var jsonExample = example.original(); assert.deepEqual(jsonExample,{ "name": "Dog", "age": 33 }) }); it('Should return expand and return proper string 1, include', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e2.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="ManWithDog"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isEmpty(), true); var jsonString = example.expandAsString(); var jsonExample = JSON.parse(jsonString); assert.deepEqual(jsonExample,{"name":"Pavel","d":{"name":"Dog","age":33}}) }); it('Should return expand and return proper JSON 1, include', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e2.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="ManWithDog"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isEmpty(), true); var jsonExample = example.expandAsJSON(); assert.deepEqual(jsonExample,{"name":"Pavel","d":{"name":"Dog","age":33}}) }); it('Should return XML string example as String', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e3.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Dog"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isXMLString(), true); var xmlString = example.asString(); assert(xmlString.indexOf(">") != -1) }); it('User defined 1', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e4.raml')); var resource = tools.collectionItem(api.resources(), 0); var method = tools.collectionItem(resource.methods(), 0); var body = tools.collectionItem(method.body(), 0); var runtimeType = body.runtimeType(); assert.equal(runtimeType.hasGenuineUserDefinedTypeInHierarchy(), true); assert.equal(runtimeType.genuineUserDefinedTypeInHierarchy().nameId(), "application/json"); }); it('User defined 2', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e5.raml')); var resource = tools.collectionItem(api.resources(), 0); var method = tools.collectionItem(resource.methods(), 0); var body = tools.collectionItem(method.body(), 0); var runtimeType = body.runtimeType(); assert.equal(runtimeType.hasGenuineUserDefinedTypeInHierarchy(), true); assert.equal(runtimeType.genuineUserDefinedTypeInHierarchy().nameId(), "Dog"); }); it('Should return expand and return proper JSON 3', function () { var api = util.loadApiWrapper1(util.data('exampleGen/e6.raml')); var types : wrapper10.TypeDeclaration[] = <any>tools.toArray(api.types()); var type=_.find(types,x=>x.name()=="Employee"); assert(type != null); var runtimeType = type.runtimeType(); assert(runtimeType != null); var example : hl.IExpandableExample = tools.collectionItem(runtimeType.examples(), 0); assert.equal(example.isEmpty(), true); var jsonExample = example.expandAsJSON(); assert.deepEqual(jsonExample,{"name":"Christian","dep":{"name":"OCTO"}}) }); });
the_stack
import Builder from '../../src/Builder'; import TypeScriptRenderer from '../../src/renderers/TypeScript'; import ArrayDefinition from '../../src/definitions/Array'; import BoolDefinition from '../../src/definitions/Bool'; import EnumDefinition from '../../src/definitions/Enum'; import InstanceDefinition from '../../src/definitions/Instance'; import KeyDefinition from '../../src/definitions/Key'; import NumberDefinition from '../../src/definitions/Number'; import ObjectDefinition from '../../src/definitions/Object'; import ReferenceDefinition from '../../src/definitions/Reference'; import StringDefinition from '../../src/definitions/String'; import UnionDefinition from '../../src/definitions/Union'; import ShapeDefinition from '../../src/definitions/Shape'; import Schematic from '../../src/Schematic'; import { options } from '../mocks'; describe('TypeScriptRenderer', () => { let renderer: TypeScriptRenderer; beforeEach(() => { renderer = new TypeScriptRenderer( { ...options, renderers: ['typescript'], }, new Builder(), new Schematic( '/foo.json', { name: 'Foo', attributes: { id: 'number' }, }, options, ), ); renderer.beforeParse(); }); describe('beforeParse()', () => { it('does not change suffix if not inferring', () => { renderer.beforeParse(); expect(renderer.suffix).toBe('Interface'); }); it('does not change suffix if no prop types', () => { renderer.options.inferPropTypesShape = true; renderer.beforeParse(); expect(renderer.suffix).toBe('Interface'); }); it('changes suffix if inferring prop types', () => { renderer.options.inferPropTypesShape = true; renderer.options.renderers.push('prop-types'); renderer.beforeParse(); expect(renderer.suffix).toBe('Shape'); }); it('doesnt set suffix', () => { renderer.suffix = ''; // Reset renderer.options.suffix = false; renderer.beforeParse(); expect(renderer.suffix).toBe(''); }); }); describe('renderArray()', () => { it('renders nullable', () => { expect( renderer.renderArray( new ArrayDefinition(options, 'foo', { nullable: true, valueType: 'string', }), 0, ), ).toBe('Array<string> | null'); }); it('renders non-nullable', () => { expect( renderer.renderArray( new ArrayDefinition(options, 'foo', { nullable: false, valueType: { type: 'string', nullable: false, }, }), 0, ), ).toBe('Array<string>'); }); it('handles non-primitive', () => { expect( renderer.renderArray( new ArrayDefinition(options, 'foo', { valueType: { type: 'object', valueType: 'string', }, }), 0, ), ).toBe('Array<{ [key: string]: string }>'); }); it('handles instance ofs', () => { expect( renderer.renderArray( new ArrayDefinition(options, 'foo', { valueType: { type: 'instance', contract: 'FooBar', }, }), 0, ), ).toBe('Array<FooBar>'); }); it('defaults value to any', () => { const def = new ArrayDefinition(options, 'foo', { valueType: 'string', }); // @ts-expect-error delete def.valueType; expect(renderer.renderArray(def, 0)).toBe('Array<any>'); }); }); describe('renderBool()', () => { it('renders nullable', () => { expect( renderer.renderBool( new BoolDefinition(options, 'foo', { nullable: true, }), ), ).toBe('boolean | null'); }); it('renders non-nullable', () => { expect( renderer.renderBool( new BoolDefinition(options, 'foo', { nullable: false, }), ), ).toBe('boolean'); }); }); describe('renderEnum()', () => { it('renders', () => { expect( renderer.renderEnum( new EnumDefinition(options, 'bar', { valueType: 'number', values: [1, 23, 164], }), 0, ), ).toBe('FooBarEnum'); }); it('renders a union', () => { renderer.options.enums = false; expect( renderer.renderEnum( new EnumDefinition(options, 'bar', { valueType: 'number', values: [1, 23, 164], }), 0, ), ).toBe('1 | 23 | 164'); }); }); describe('renderInstance()', () => { it('renders nullable', () => { expect( renderer.renderInstance( new InstanceDefinition(options, 'foo', { nullable: true, contract: 'FooBar', }), ), ).toBe('FooBar | null'); }); it('renders non-nullable', () => { expect( renderer.renderInstance( new InstanceDefinition(options, 'foo', { nullable: false, contract: 'FooBar', }), ), ).toBe('FooBar'); }); }); describe('renderKey()', () => { it('renders nullable', () => { expect( renderer.renderKey( new KeyDefinition(options, 'foo', { nullable: true, }), ), ).toBe('Key | null'); expect(Array.from(renderer.builder.header)).toEqual(['export type Key = string | number;']); }); it('renders non-nullable', () => { expect( renderer.renderKey( new KeyDefinition(options, 'foo', { nullable: false, }), ), ).toBe('Key'); expect(Array.from(renderer.builder.header)).toEqual(['export type Key = string | number;']); }); }); describe('renderNumber()', () => { it('renders nullable', () => { expect( renderer.renderNumber( new NumberDefinition(options, 'foo', { nullable: true, }), ), ).toBe('number | null'); }); it('renders non-nullable', () => { expect( renderer.renderNumber( new NumberDefinition(options, 'foo', { nullable: false, }), ), ).toBe('number'); }); }); describe('renderObject()', () => { it('renders nullable', () => { expect( renderer.renderObject( new ObjectDefinition(options, 'foo', { nullable: true, valueType: 'number', }), 0, ), ).toBe('{ [key: string]: number } | null'); }); it('renders non-nullable', () => { expect( renderer.renderObject( new ObjectDefinition(options, 'foo', { nullable: false, valueType: 'number', }), 0, ), ).toBe('{ [key: string]: number }'); }); it('handles key type', () => { expect( renderer.renderObject( new ObjectDefinition(options, 'foo', { keyType: 'number', valueType: { type: 'array', valueType: 'string', }, }), 0, ), ).toBe('{ [key: number]: Array<string> }'); }); it('defaults key to string', () => { const def = new ObjectDefinition(options, 'foo', { keyType: 'number', valueType: 'string', }); // @ts-expect-error delete def.keyType; expect(renderer.renderObject(def, 0)).toBe('{ [key: string]: string }'); }); it('defaults value to any', () => { const def = new ObjectDefinition(options, 'foo', { keyType: 'number', valueType: 'string', }); // @ts-expect-error delete def.valueType; expect(renderer.renderObject(def, 0)).toBe('{ [key: number]: any }'); }); }); describe('renderReference()', () => { it('renders nullable', () => { expect( renderer.renderReference( new ReferenceDefinition(options, 'foo', { nullable: true, self: true, }), ), ).toBe('FooInterface | null'); }); it('renders non-nullable', () => { expect( renderer.renderReference( new ReferenceDefinition(options, 'foo', { nullable: false, self: true, }), ), ).toBe('FooInterface'); }); it('renders with no suffix', () => { renderer.suffix = ''; expect( renderer.renderReference( new ReferenceDefinition(options, 'foo', { nullable: false, self: true, }), ), ).toBe('Foo'); }); }); describe('renderSchema()', () => { it('renders with generics', () => { renderer.options.schemaGenerics = true; expect( renderer.renderSchema('QuxSchema', [], { resourceName: 'quxs', }), ).toBe("export const quxSchema = new Schema<QuxInterface>('quxs');"); }); it('renders with generics and no suffix', () => { renderer.options.schemaGenerics = true; renderer.suffix = ''; expect( renderer.renderSchema('QuxSchema', [], { resourceName: 'quxs', }), ).toBe("export const quxSchema = new Schema<Qux>('quxs');"); }); }); describe('renderShape()', () => { it('defaults to object if no attributes', () => { const def = new ShapeDefinition(options, 'foo', { attributes: { foo: 'string' }, }); // @ts-expect-error delete def.attributes; expect(renderer.renderShape(def, 0)).toBe('{ [key: string]: any }'); }); }); describe('renderString()', () => { it('renders nullable', () => { expect( renderer.renderString( new StringDefinition(options, 'foo', { nullable: true, }), ), ).toBe('string | null'); }); it('renders non-nullable', () => { expect( renderer.renderString( new StringDefinition(options, 'foo', { nullable: false, }), ), ).toBe('string'); }); }); describe('renderUnion()', () => { const valueTypes = [ 'string', { type: 'bool' }, { type: 'array', valueType: 'number', }, ]; it('renders nullable', () => { expect( renderer.renderUnion( new UnionDefinition(options, 'foo', { nullable: true, valueTypes, }), 0, ), ).toBe('string | boolean | Array<number> | null'); }); it('renders non-nullable', () => { expect( renderer.renderUnion( new UnionDefinition(options, 'foo', { nullable: false, valueTypes, }), 0, ), ).toBe('string | boolean | Array<number>'); }); it('handles nested unions', () => { expect( renderer.renderUnion( new UnionDefinition(options, 'foo', { valueTypes: [ ...valueTypes, { type: 'union', valueTypes: [ { type: 'instance', contract: 'FooBar', }, ], }, ], }), 0, ), ).toBe('string | boolean | Array<number> | FooBar'); }); }); describe('wrapNullable()', () => { it('renders nullable', () => { // @ts-expect-error expect(renderer.wrapNullable({ isNullable: () => true }, 'foo')).toBe('foo | null'); }); it('renders non-nullable', () => { // @ts-expect-error expect(renderer.wrapNullable({ isNullable: () => false }, 'foo')).toBe('foo'); }); }); });
the_stack
import { entitySchemaValidator } from './entitySchemaValidator'; describe('entitySchemaValidator', () => { const validator = entitySchemaValidator(); let entity: any; beforeEach(() => { entity = { apiVersion: 'backstage.io/v1alpha1', kind: 'Component', metadata: { uid: 'e01199ab-08cc-44c2-8e19-5c29ded82521', etag: 'lsndfkjsndfkjnsdfkjnsd==', name: 'test', namespace: 'ns', title: 'My Component, Yay', description: 'Yeah this is probably the best component so far', labels: { 'backstage.io/custom': 'ValueStuff', }, annotations: { 'example.com/bindings': 'are-secret', }, tags: ['java', 'data'], links: [ { url: 'https://example.com', title: 'Website', icon: 'website', }, ], }, spec: { type: 'service', lifecycle: 'production', owner: 'me', }, relations: [ { type: 't', target: { kind: 'k', namespace: 'ns', name: 'n' } }, ], status: { items: [ { type: 't', level: 'error', message: 'm', error: { name: 'n', message: 'm', code: '1', stack: 's' }, }, ], }, }; }); it('happy path: accepts valid data', () => { expect(() => validator(entity)).not.toThrow(); }); // // apiVersion and kind // it('rejects wrong root type', () => { expect(() => validator(7)).toThrow(/object/); }); it('rejects missing apiVersion', () => { delete entity.apiVersion; expect(() => validator(entity)).toThrow(/apiVersion/); }); it('rejects bad apiVersion type', () => { entity.apiVersion = 7; expect(() => validator(entity)).toThrow(/apiVersion/); }); it('rejects empty apiVersion', () => { entity.apiVersion = ''; expect(() => validator(entity)).toThrow(/apiVersion/); }); it('rejects missing kind', () => { delete entity.kind; expect(() => validator(entity)).toThrow(/kind/); }); it('rejects bad kind type', () => { entity.kind = 7; expect(() => validator(entity)).toThrow(/kind/); }); it('rejects empty kind', () => { entity.kind = ''; expect(() => validator(entity)).toThrow(/kind/); }); // // metadata // it('rejects missing metadata', () => { delete entity.metadata; expect(() => validator(entity)).toThrow(/metadata/); }); it('rejects bad metadata type', () => { entity.metadata = 7; expect(() => validator(entity)).toThrow(/metadata/); }); it('accepts missing uid', () => { delete entity.metadata.uid; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad uid type', () => { entity.metadata.uid = 7; expect(() => validator(entity)).toThrow(/uid/); }); it('rejects empty uid', () => { entity.metadata.uid = ''; expect(() => validator(entity)).toThrow(/uid/); }); it('accepts missing etag', () => { delete entity.metadata.etag; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad etag type', () => { entity.metadata.etag = 7; expect(() => validator(entity)).toThrow(/etag/); }); it('rejects empty etag', () => { entity.metadata.etag = ''; expect(() => validator(entity)).toThrow(/etag/); }); it('rejects missing name', () => { delete entity.metadata.name; expect(() => validator(entity)).toThrow(/name/); }); it('rejects bad name type', () => { entity.metadata.name = 7; expect(() => validator(entity)).toThrow(/name/); }); it('accepts missing namespace', () => { delete entity.metadata.namespace; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad namespace type', () => { entity.metadata.namespace = 7; expect(() => validator(entity)).toThrow(/namespace/); }); it('accepts missing title', () => { delete entity.metadata.title; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad title type', () => { entity.metadata.title = 7; expect(() => validator(entity)).toThrow(/title/); }); it('rejects empty title', () => { entity.metadata.title = ''; expect(() => validator(entity)).toThrow(/title/); }); it('accepts missing description', () => { delete entity.metadata.description; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad description type', () => { entity.metadata.description = 7; expect(() => validator(entity)).toThrow(/description/); }); it('accepts missing labels', () => { delete entity.metadata.labels; expect(() => validator(entity)).not.toThrow(); }); it('accepts empty labels', () => { entity.metadata.labels = {}; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad labels type', () => { entity.metadata.labels = 7; expect(() => validator(entity)).toThrow(/labels/); }); it('accepts missing annotations', () => { delete entity.metadata.annotations; expect(() => validator(entity)).not.toThrow(); }); it('accepts empty annotations object', () => { entity.metadata.annotations = {}; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad annotations type', () => { entity.metadata.annotations = 7; expect(() => validator(entity)).toThrow(/annotations/); }); it('rejects bad tags type', () => { entity.metadata.tags = 7; expect(() => validator(entity)).toThrow(/tags/); }); it('accepts empty tags', () => { entity.metadata.tags = []; expect(() => validator(entity)).not.toThrow(); }); it('rejects empty tag', () => { entity.metadata.tags[0] = ''; expect(() => validator(entity)).toThrow(/tags/); }); it('rejects bad tag type', () => { entity.metadata.tags[0] = 7; expect(() => validator(entity)).toThrow(/tags/); }); it('accepts missing links', () => { delete entity.metadata.links; expect(() => validator(entity)).not.toThrow(); }); it('accepts empty links', () => { entity.metadata.links = []; expect(() => validator(entity)).not.toThrow(); }); it('rejects empty links.url', () => { entity.metadata.links[0].url = ''; expect(() => validator(entity)).toThrow(/links/); }); it('rejects missing links.url', () => { delete entity.metadata.links[0].url; expect(() => validator(entity)).toThrow(/links/); }); it('rejects bad links.url type', () => { entity.metadata.links[0].url = 7; expect(() => validator(entity)).toThrow(/links/); }); it('rejects empty links.title', () => { entity.metadata.links[0].title = ''; expect(() => validator(entity)).toThrow(/links/); }); it('accepts missing links.title', () => { delete entity.metadata.links[0].title; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad links.title type', () => { entity.metadata.links[0].title = 7; expect(() => validator(entity)).toThrow(/links/); }); it('rejects empty links.icon', () => { entity.metadata.links[0].icon = ''; expect(() => validator(entity)).toThrow(/links/); }); it('accepts missing links.icon', () => { delete entity.metadata.links[0].icon; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad links.icon type', () => { entity.metadata.links[0].icon = 7; expect(() => validator(entity)).toThrow(/links/); }); it('accepts unknown metadata field', () => { entity.metadata.unknown = 7; expect(() => validator(entity)).not.toThrow(); }); // // spec // it('accepts missing spec', () => { delete entity.spec; expect(() => validator(entity)).not.toThrow(); }); it('rejects non-object spec', () => { entity.spec = 7; expect(() => validator(entity)).toThrow(/spec/); }); it('accepts unknown spec field', () => { entity.spec.unknown = 7; expect(() => validator(entity)).not.toThrow(); }); // // Relations // it('accepts missing relations', () => { delete entity.relations; expect(() => validator(entity)).not.toThrow(); }); it('accepts empty relations', () => { entity.relations = []; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad relations type', () => { entity.relations = 7; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects missing relations.type', () => { delete entity.relations[0].type; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects empty relations.type', () => { entity.relations[0].type = ''; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects wrong relations.type type', () => { entity.relations[0].type = 7; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects missing relations.target', () => { delete entity.relations[0].target; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects empty relations.target', () => { entity.relations[0].target = ''; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects wrong relations.target type', () => { entity.relations[0].target = 7; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects missing relations.target.kind', () => { delete entity.relations[0].target.kind; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects empty relations.target.kind', () => { entity.relations[0].target.kind = ''; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects wrong relations.target.kind type', () => { entity.relations[0].target.kind = 7; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects missing relations.target.namespace', () => { delete entity.relations[0].target.namespace; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects empty relations.target.namespace', () => { entity.relations[0].target.namespace = ''; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects wrong relations.target.namespace type', () => { entity.relations[0].target.namespace = 7; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects missing relations.target.name', () => { delete entity.relations[0].target.name; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects empty relations.target.name', () => { entity.relations[0].target.name = ''; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects wrong relations.target.name type', () => { entity.relations[0].target.name = 7; expect(() => validator(entity)).toThrow(/relations/); }); it('rejects unknown relation field', () => { entity.relations[0].unknown = 7; expect(() => validator(entity)).toThrow(/unknown/); }); // // Status // it('accepts missing status', () => { delete entity.status; expect(() => validator(entity)).not.toThrow(); }); it('accepts empty status', () => { entity.status = {}; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad status type', () => { entity.status = 7; expect(() => validator(entity)).toThrow(/status/); }); it('accepts missing status.items', () => { delete entity.status.items; expect(() => validator(entity)).not.toThrow(); }); it('accepts empty status.items', () => { entity.status.items = []; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad status.items type', () => { entity.status.items = 7; expect(() => validator(entity)).toThrow(/status/); }); it('rejects bad status.items item type', () => { entity.status.items[0] = 7; expect(() => validator(entity)).toThrow(/status/); }); it('rejects missing status.items.type', () => { delete entity.status.items[0].type; expect(() => validator(entity)).toThrow(/status/); }); it('rejects empty status.items.type', () => { entity.status.items[0].type = ''; expect(() => validator(entity)).toThrow(/status/); }); it('rejects bad status.items.type type', () => { entity.status.items[0].type = 7; expect(() => validator(entity)).toThrow(/status/); }); it('rejects missing status.items.level', () => { delete entity.status.items[0].level; expect(() => validator(entity)).toThrow(/status/); }); it('rejects empty status.items.level', () => { entity.status.items[0].level = ''; expect(() => validator(entity)).toThrow(/status/); }); it('rejects bad status.items.level type', () => { entity.status.items[0].level = 7; expect(() => validator(entity)).toThrow(/status/); }); it('rejects bad status.items.level enum', () => { entity.status.items[0].level = 'unknown'; expect(() => validator(entity)).toThrow(/status/); }); it('rejects missing status.items.message', () => { delete entity.status.items[0].message; expect(() => validator(entity)).toThrow(/status/); }); it('accepts empty status.items.message', () => { entity.status.items[0].message = ''; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad status.items.message type', () => { entity.status.items[0].message = 7; expect(() => validator(entity)).toThrow(/status/); }); it('accepts missing status.items.error', () => { delete entity.status.items[0].error; expect(() => validator(entity)).not.toThrow(); }); it('rejects missing status.items.error.name', () => { delete entity.status.items[0].error.name; expect(() => validator(entity)).toThrow(/name/); }); it('rejects empty status.items.error.name', () => { entity.status.items[0].error.name = ''; expect(() => validator(entity)).toThrow(/name/); }); it('rejects bad status.items.error.name type', () => { entity.status.items[0].error.name = 7; expect(() => validator(entity)).toThrow(/name/); }); it('rejects missing status.items.error.message', () => { delete entity.status.items[0].error.message; expect(() => validator(entity)).toThrow(/message/); }); it('accepts empty status.items.error.message', () => { entity.status.items[0].error.message = ''; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad status.items.error.message type', () => { entity.status.items[0].error.message = 7; expect(() => validator(entity)).toThrow(/message/); }); it('accepts missing status.items.error.code', () => { delete entity.status.items[0].error.code; expect(() => validator(entity)).not.toThrow(); }); it('accepts empty status.items.error.code', () => { entity.status.items[0].error.code = ''; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad status.items.error.code type', () => { entity.status.items[0].error.code = 7; expect(() => validator(entity)).toThrow(/code/); }); it('accepts missing status.items.error.stack', () => { delete entity.status.items[0].error.stack; expect(() => validator(entity)).not.toThrow(); }); it('accepts empty status.items.error.stack', () => { entity.status.items[0].error.stack = ''; expect(() => validator(entity)).not.toThrow(); }); it('rejects bad status.items.error.stack type', () => { entity.status.items[0].error.stack = 7; expect(() => validator(entity)).toThrow(/stack/); }); it('accepts unknown status.items field', () => { entity.status.items[0].unknown = 7; expect(() => validator(entity)).not.toThrow(); }); it('accepts unknown status.items.error field', () => { entity.status.items[0].error.unknown = 7; expect(() => validator(entity)).not.toThrow(); }); });
the_stack
import { LoanMasterNodeRegTestContainer } from './loan_container' import BigNumber from 'bignumber.js' import { Testing } from '@defichain/jellyfish-testing' import { GenesisKeys } from '@defichain/testcontainers' describe('Loan updateLoanScheme', () => { const container = new LoanMasterNodeRegTestContainer() const testing = Testing.create(container) beforeAll(async () => { await testing.container.start() await testing.container.waitForWalletCoinbaseMaturity() // Default scheme await testing.container.call('createloanscheme', [100, new BigNumber(1.5), 'default']) await testing.generate(1) }) beforeEach(async () => { await testing.container.call('createloanscheme', [200, new BigNumber(2.5), 'scheme1']) await testing.generate(1) }) afterEach(async () => { const data = await testing.container.call('listloanschemes') const result = data.filter((d: { default: boolean }) => !d.default) for (let i = 0; i < result.length; i += 1) { // Delete all schemes except default scheme await testing.container.call('destroyloanscheme', [result[i].id]) await testing.generate(1) } }) afterAll(async () => { await testing.container.stop() }) it('should updateLoanScheme', async () => { const loanSchemeId = await testing.rpc.loan.updateLoanScheme({ minColRatio: 300, interestRate: new BigNumber(3.5), id: 'scheme1' }) expect(typeof loanSchemeId).toStrictEqual('string') expect(loanSchemeId.length).toStrictEqual(64) await testing.generate(1) const data = await testing.container.call('listloanschemes') const result = data.filter((d: { id: string }) => d.id === 'scheme1') expect(result.length).toStrictEqual(1) expect(result[0]).toStrictEqual( { default: false, id: 'scheme1', interestrate: 3.5, mincolratio: 300 } ) }) it('should not updateLoanScheme if minColRatio is less than 100', async () => { const promise = testing.rpc.loan.updateLoanScheme({ minColRatio: 99, interestRate: new BigNumber(3.5), id: 'scheme1' }) await expect(promise).rejects.toThrow('RpcApiError: \'Test LoanSchemeTx execution failed:\nminimum collateral ratio cannot be less than 100\', code: -32600, method: updateloanscheme') }) it('should not updateLoanScheme if interestRate is less than 0.01', async () => { const promise = testing.rpc.loan.updateLoanScheme({ minColRatio: 300, interestRate: new BigNumber(0.00999), id: 'scheme1' }) await expect(promise).rejects.toThrow('RpcApiError: \'Test LoanSchemeTx execution failed:\ninterest rate cannot be less than 0.01\', code: -32600, method: updateloanscheme') }) it('should not updateLoanScheme if same minColRatio and interestRate were created before', async () => { const promise = testing.rpc.loan.updateLoanScheme({ minColRatio: 100, interestRate: new BigNumber(1.5), id: 'scheme1' }) await expect(promise).rejects.toThrow('RpcApiError: \'Test LoanSchemeTx execution failed:\nLoan scheme default with same interestrate and mincolratio already exists\', code: -32600, method: updateloanscheme') }) it('should not updateLoanScheme if id does not exist', async () => { const promise = testing.rpc.loan.updateLoanScheme({ minColRatio: 300, interestRate: new BigNumber(3.5), id: 'scheme2' }) await expect(promise).rejects.toThrow('RpcApiError: \'Test LoanSchemeTx execution failed:\nCannot find existing loan scheme with id scheme2\', code: -32600, method: updateloanscheme') }) it('should not updateLoanScheme if id is an empty string', async () => { const promise = testing.rpc.loan.updateLoanScheme({ minColRatio: 300, interestRate: new BigNumber(3.5), id: '' }) await expect(promise).rejects.toThrow('RpcApiError: \'Test LoanSchemeTx execution failed:\nid cannot be empty or more than 8 chars long\', code: -32600, method: updateloanscheme') }) it('should not updateLoanScheme if id is more than 8 chars long', async () => { const promise = testing.rpc.loan.updateLoanScheme({ minColRatio: 300, interestRate: new BigNumber(3.5), id: 'x'.repeat(9) }) await expect(promise).rejects.toThrow('RpcApiError: \'Test LoanSchemeTx execution failed:\nid cannot be empty or more than 8 chars long\', code: -32600, method: updateloanscheme') }) it('should updateLoanScheme with utxos', async () => { const { txid, vout } = await testing.container.fundAddress(GenesisKeys[0].owner.address, 10) const loanSchemeId = await testing.rpc.loan.updateLoanScheme({ minColRatio: 300, interestRate: new BigNumber(3.5), id: 'scheme1' }, [{ txid, vout }]) expect(typeof loanSchemeId).toStrictEqual('string') expect(loanSchemeId.length).toStrictEqual(64) await testing.generate(1) const rawtx = await testing.container.call('getrawtransaction', [loanSchemeId, true]) expect(rawtx.vin[0].txid).toStrictEqual(txid) expect(rawtx.vin[0].vout).toStrictEqual(vout) const data = await testing.container.call('listloanschemes') const result = data.filter((d: { id: string }) => d.id === 'scheme1') expect(result.length).toStrictEqual(1) expect(result[0]).toStrictEqual( { default: false, id: 'scheme1', interestrate: 3.5, mincolratio: 300 } ) }) it('should not updateLoanScheme with utxos not from foundation member', async () => { const utxo = await testing.container.fundAddress(await testing.generateAddress(), 10) const promise = testing.rpc.loan.updateLoanScheme({ minColRatio: 300, interestRate: new BigNumber(3.5), id: 'scheme1' }, [utxo]) await expect(promise).rejects.toThrow('RpcApiError: \'Test LoanSchemeTx execution failed:\ntx not from foundation member!\', code: -32600, method: updateloanscheme') }) }) describe('Loan updateLoanScheme with activateAfterBlock at block 120', () => { const container = new LoanMasterNodeRegTestContainer() const testing = Testing.create(container) beforeAll(async () => { await testing.container.start() await testing.container.waitForWalletCoinbaseMaturity() }) afterAll(async () => { await testing.container.stop() }) it('should updateLoanScheme', async () => { // Default scheme await testing.container.call('createloanscheme', [100, new BigNumber(1.5), 'default']) await testing.generate(1) await testing.container.call('createloanscheme', [200, new BigNumber(2.5), 'scheme1']) await testing.generate(1) // Wait for block 110 await testing.container.waitForBlockHeight(110) // To update at block 120 const loanSchemeId = await testing.rpc.loan.updateLoanScheme({ minColRatio: 300, interestRate: new BigNumber(3.5), id: 'scheme1', activateAfterBlock: 120 }) expect(typeof loanSchemeId).toStrictEqual('string') expect(loanSchemeId.length).toStrictEqual(64) await testing.generate(1) // Shouldn't update at block 111 { const data = await testing.container.call('listloanschemes') const result = data.filter((d: { id: string }) => d.id === 'scheme1') expect(result.length).toStrictEqual(1) expect(result[0]).toStrictEqual( { default: false, id: 'scheme1', interestrate: 2.5, mincolratio: 200 } ) } // Wait for block 120 await testing.container.waitForBlockHeight(120) // Should update at block 120 { const data = await testing.container.call('listloanschemes') const result = data.filter((d: { id: string }) => d.id === 'scheme1') expect(result.length).toStrictEqual(1) expect(result[0]).toStrictEqual( { default: false, id: 'scheme1', interestrate: 3.5, mincolratio: 300 } ) } }) }) describe('Loan updateLoanScheme with activateAfterBlock less than current block', () => { const container = new LoanMasterNodeRegTestContainer() const testing = Testing.create(container) beforeAll(async () => { await testing.container.start() await testing.container.waitForWalletCoinbaseMaturity() }) afterAll(async () => { await testing.container.stop() }) it('should not updateLoanScheme', async () => { await testing.container.call('createloanscheme', [200, new BigNumber(2.5), 'scheme1']) await testing.generate(1) await testing.container.waitForBlockHeight(110) // Attempt to updateLoanScheme at block 109 const promise = testing.rpc.loan.updateLoanScheme({ minColRatio: 300, interestRate: new BigNumber(3.5), id: 'scheme1', activateAfterBlock: 109 }) await expect(promise).rejects.toThrow('RpcApiError: \'Test LoanSchemeTx execution failed:\nUpdate height below current block height, set future height\', code: -32600, method: updateloanscheme') }) }) describe('Loan updateLoanScheme with same minColRatio and interestRate pending loan scheme created before', () => { const container = new LoanMasterNodeRegTestContainer() const testing = Testing.create(container) beforeAll(async () => { await testing.container.start() await testing.container.waitForWalletCoinbaseMaturity() }) afterAll(async () => { await testing.container.stop() }) it('should not updateLoanScheme', async () => { // Wait for block 100 await testing.container.waitForBlockHeight(100) await testing.container.call('createloanscheme', [300, new BigNumber(3.5), 'scheme2']) await testing.generate(1) // To update scheme on later block await testing.rpc.loan.updateLoanScheme({ minColRatio: 400, interestRate: new BigNumber(4.5), id: 'scheme2', activateAfterBlock: 110 }) await testing.generate(1) // Attempt to update same minColRatio and interestRate as the pending scheme const promise = testing.rpc.loan.updateLoanScheme({ minColRatio: 400, interestRate: new BigNumber(4.5), id: 'scheme1' }) await expect(promise).rejects.toThrow('RpcApiError: \'Test LoanSchemeTx execution failed:\nLoan scheme scheme2 with same interestrate and mincolratio pending on block 110\', code: -32600, method: updateloanscheme') }) })
the_stack
import { css, jsx } from '@emotion/core'; import React, { useMemo, useCallback, useState, useEffect, useRef } from 'react'; import { useRecoilValue } from 'recoil'; import { v4 as uuidv4 } from 'uuid'; import { ConversationActivityTrafficItem, Activity, UserSettings } from '@botframework-composer/types'; import { Stack } from 'office-ui-fabric-react/lib/Stack'; import { CommandBar, ICommandBarStyles } from 'office-ui-fabric-react/lib/CommandBar'; import { DetailsList, DetailsListLayoutMode, IColumn, SelectionMode, Selection, IObjectWithKey, IDetailsRowProps, DetailsRow, IDetailsListStyles, IDetailsRowStyles, IDetailsHeaderStyles, } from 'office-ui-fabric-react/lib/DetailsList'; import formatMessage from 'format-message'; import get from 'lodash/get'; import { IScrollablePaneStyles, ScrollablePane } from 'office-ui-fabric-react/lib/ScrollablePane'; import { Sticky, StickyPositionType } from 'office-ui-fabric-react/lib/Sticky'; import { TooltipHost } from 'office-ui-fabric-react/lib/Tooltip'; import { CommunicationColors, FluentTheme } from '@uifabric/fluent-theme'; import { Link } from 'office-ui-fabric-react/lib/Link'; import { IButtonStyles } from 'office-ui-fabric-react/lib/Button'; import { DebugPanelTabHeaderProps } from '../types'; import { currentProjectIdState, dispatcherState, userSettingsState, watchedVariablesState, webChatTrafficState, } from '../../../../../recoilModel'; import { WatchVariablePicker } from '../../WatchVariablePicker/WatchVariablePicker'; import TelemetryClient from '../../../../../telemetry/TelemetryClient'; import { WatchTabObjectValue } from './WatchTabObjectValue'; const toolbarHeight = 24; const unavailbleValue = css` font-family: ${FluentTheme.fonts.small.fontFamily}; font-size: ${FluentTheme.fonts.small.fontSize}; font-style: italic; height: 16px; line-height: 16px; display: inline-block; padding: 8px 0; `; const primitiveValue = (userSettings: UserSettings) => css` font-family: ${userSettings.codeEditor.fontSettings.fontFamily}; font-size: ${userSettings.codeEditor.fontSettings.fontSize}; color: ${CommunicationColors.shade10}; height: 16px; line-height: 16px; display: inline-block; padding: 8px 0; `; const emptyState = css` font-family: ${FluentTheme.fonts.small.fontFamily}; font-size: ${FluentTheme.fonts.small.fontSize}; line-height: ${FluentTheme.fonts.small.lineHeight}; padding-left: 16px; `; const watchTableStyles: Partial<IDetailsListStyles> = { root: { maxHeight: `calc(100% - ${toolbarHeight}px)`, }, contentWrapper: { overflowY: 'auto' as any, // fill remaining space after table header row height: 'calc(100% - 60px)', }, }; const rowStyles = (): Partial<IDetailsRowStyles> => ({ cell: { minHeight: 32, padding: '0 6px' }, checkCell: { height: 32, minHeight: 32, selectors: { '& > div[role="checkbox"]': { height: 32, }, }, }, root: { minHeight: 32 }, }); const commandBarStyles: Partial<ICommandBarStyles> = { root: { height: toolbarHeight, padding: 0 } }; const detailsHeaderStyles: Partial<IDetailsHeaderStyles> = { root: { paddingTop: 0, }, }; const scrollingContainerStyles: Partial<IScrollablePaneStyles> = { contentContainer: { padding: '0 16px', }, }; const addButtonStyles: Partial<IButtonStyles> = { root: { paddingLeft: 0, }, icon: { marginLeft: 0, }, }; const NameColumnKey = 'watchTabNameColumn'; const ValueColumnKey = 'watchTabValueColumn'; const watchTableLayout: DetailsListLayoutMode = DetailsListLayoutMode.justified; // Returns the specified property from the bot state trace if it exists. // Ex. getValueFromBotTraceMemory('user.address.city', trace) export const getValueFromBotTraceMemory = ( valuePath: string, botTrace: Activity ): { value: any; propertyIsAvailable: boolean } => { const pathSegments = valuePath.split('.'); if (pathSegments.length === 1) { // this is the root level of a memory scope return { propertyIsAvailable: true, value: get(botTrace?.value, valuePath, undefined), }; } pathSegments.pop(); const parentValuePath = pathSegments.join('.'); const parentPropertyValue = get(botTrace?.value, parentValuePath, undefined); return { // if the parent key to the desired property is an object then the property is available propertyIsAvailable: parentPropertyValue !== null && typeof parentPropertyValue === 'object', value: get(botTrace?.value, valuePath, undefined), }; }; export const WatchTabContent: React.FC<DebugPanelTabHeaderProps> = ({ isActive }) => { const currentProjectId = useRecoilValue(currentProjectIdState); const rawWebChatTraffic = useRecoilValue(webChatTrafficState(currentProjectId)); const watchedVariables = useRecoilValue(watchedVariablesState(currentProjectId)); const { setWatchedVariables } = useRecoilValue(dispatcherState); const [uncommittedWatchedVariables, setUncommittedWatchedVariables] = useState<Record<string, string>>({}); const [selectedVariables, setSelectedVariables] = useState<IObjectWithKey[]>(); const userSettings = useRecoilValue(userSettingsState); const watchedVariablesSelection = useRef( new Selection({ onSelectionChanged: () => { setSelectedVariables(watchedVariablesSelection.current.getSelection()); }, selectionMode: SelectionMode.multiple, }) ); // reset state when switching to a new project useEffect(() => { setUncommittedWatchedVariables({}); }, [currentProjectId]); const mostRecentBotState = useMemo(() => { const botStateTraffic = rawWebChatTraffic.filter( (t) => t.trafficType === 'activity' && t.activity.type === 'trace' && t.activity.name === 'BotState' ) as ConversationActivityTrafficItem[]; if (botStateTraffic.length) { return botStateTraffic[botStateTraffic.length - 1]; } }, [rawWebChatTraffic]); const onRenderVariableName = useCallback( (item: { key: string; value: string }, index: number | undefined, column: IColumn | undefined) => { return <WatchVariablePicker key={item.key} path={item.value} variableId={item.key} />; }, [] ); const onRenderVariableValue = useCallback( (item: { key: string; value: string }, index: number | undefined, column: IColumn | undefined) => { if (mostRecentBotState) { const variable = watchedVariables[item.key]; if (variable === undefined) { // the variable has not been committed yet return null; } // try to determine the value and render it accordingly const { propertyIsAvailable, value } = getValueFromBotTraceMemory(variable, mostRecentBotState?.activity); if (propertyIsAvailable) { if (value !== null && typeof value === 'object') { // render monaco view return <WatchTabObjectValue value={value} />; } else if (value === undefined) { return <span css={primitiveValue(userSettings)}>{formatMessage('undefined')}</span>; } else { // render primitive view return ( <span css={primitiveValue(userSettings)}>{typeof value === 'string' ? `"${value}"` : String(value)}</span> ); } } else { // the value is not available return <span css={unavailbleValue}>{formatMessage('not available')}</span>; } } else { // no bot trace available - render "not available" for committed variables, and nothing for uncommitted variables return watchedVariables[item.key] !== undefined ? ( <span css={unavailbleValue}>{formatMessage('not available')}</span> ) : null; } }, [mostRecentBotState, userSettings, watchedVariables] ); // TODO: update to office-ui-fabric-react@7.170.x to gain access to "flexGrow" column property to distribute proprotional column widths // (name column takes up 1/3 of space and value column takes up the remaining 2/3) const watchTableColumns: IColumn[] = useMemo( () => [ { key: NameColumnKey, name: 'Name', fieldName: 'name', minWidth: 100, maxWidth: 600, isResizable: true, onRender: onRenderVariableName, }, { key: ValueColumnKey, name: 'Value', fieldName: 'value', minWidth: 100, maxWidth: undefined, isResizable: true, onRender: onRenderVariableValue, }, ], [onRenderVariableName, onRenderVariableValue] ); // we need to refresh the details list when we get a new bot state, add a new row, or submit a variable to watch const refreshedWatchedVariables = useMemo(() => { // merge any committed variables into the uncommitted list so that state // is saved when the user collapses the panel or switches to another tab return Object.entries(uncommittedWatchedVariables).map(([key, value]) => { return { key, value: watchedVariables[key] ?? value, }; }); }, [mostRecentBotState, uncommittedWatchedVariables, watchedVariables]); const renderRow = useCallback((props?: IDetailsRowProps) => { return props ? <DetailsRow {...props} styles={rowStyles()} /> : null; }, []); const onClickAdd = useCallback(() => { setUncommittedWatchedVariables({ ...uncommittedWatchedVariables, [uuidv4()]: '', }); }, [uncommittedWatchedVariables]); const onClickRemove = useCallback(() => { const updatedUncommitted = { ...uncommittedWatchedVariables }; const updatedCommitted = { ...watchedVariables }; if (selectedVariables?.length) { selectedVariables.map((item: IObjectWithKey) => { delete updatedUncommitted[item.key as string]; if (updatedCommitted[item.key as string]) { // track only when we remove a property that is actually being watched TelemetryClient.track('StateWatchPropertyRemoved', { property: updatedCommitted[item.key as string] }); } delete updatedCommitted[item.key as string]; }); } setWatchedVariables(currentProjectId, updatedCommitted); setUncommittedWatchedVariables(updatedUncommitted); }, [currentProjectId, selectedVariables, setWatchedVariables, setUncommittedWatchedVariables]); const removeIsDisabled = useMemo(() => { return !selectedVariables?.length; }, [selectedVariables]); const onRenderDetailsHeader = (props, defaultRender) => { return ( <Sticky isScrollSynced stickyPosition={StickyPositionType.Header}> {defaultRender({ ...props, onRenderColumnHeaderTooltip: (tooltipHostProps) => <TooltipHost {...tooltipHostProps} />, styles: detailsHeaderStyles, })} </Sticky> ); }; if (!isActive) { return null; } return ( <Stack verticalFill> <CommandBar css={{ height: `${toolbarHeight}px`, padding: '8px 16px 16px 16px', alignItems: 'center', }} items={[ { key: 'addProperty', text: formatMessage('Add property'), iconProps: { iconName: 'Add' }, onClick: onClickAdd, buttonStyles: addButtonStyles, }, { disabled: removeIsDisabled, key: 'removeProperty', text: formatMessage('Remove from list'), iconProps: { iconName: 'Cancel' }, onClick: onClickRemove, }, ]} styles={commandBarStyles} /> <Stack.Item css={{ height: `calc(100% - 55px)`, position: 'relative', }} > <ScrollablePane styles={scrollingContainerStyles}> {refreshedWatchedVariables.length ? ( <DetailsList columns={watchTableColumns} items={refreshedWatchedVariables} layoutMode={watchTableLayout} selection={watchedVariablesSelection.current} selectionMode={SelectionMode.multiple} styles={watchTableStyles} onRenderDetailsHeader={onRenderDetailsHeader} onRenderRow={renderRow} /> ) : ( <span css={emptyState}> {formatMessage.rich( 'Add properties to watch while testing your bot in the Web Chat pane. <a>Learn more.</a>', { a: ({ children }) => ( <Link key="watch-table-empty-state-link" href="https://aka.ms/bfcomposer-2-watch" target="_blank"> {children} </Link> ), } )} </span> )} </ScrollablePane> </Stack.Item> </Stack> ); };
the_stack
import React, { CSSProperties, forwardRef, useLayoutEffect, useMemo, useState, useCallback, MutableRefObject, useEffect, useRef, } from 'react'; import ReactEcharts from 'echarts-for-react'; import * as Echarts from 'echarts/core'; import { EChartsOption, ComposeOption, ECharts } from 'echarts'; import { LinesSeriesOption, MapSeriesOption, // 系列类型的定义后缀都为 SeriesOption CustomSeriesOption, } from 'echarts/charts'; import { TooltipComponentOption, // 组件类型的定义后缀都为 ComponentOption GridComponentOption, } from 'echarts/components'; import { merge } from 'lodash'; import { getMapSeries } from './baseSeries'; import { CHINA_GEO_VALUE, GEO_SOURCE_URL, INITIAL_GEO_CODE, INITIAL_LINE_COLOR, INITIAL_MAP_NAME, INITIAL_POINT_COLOR, mapGeoDivisions, } from './constant'; import EChartsReact from 'echarts-for-react'; import geoJson from './assets/geoSource.json'; import useStyle from '../../hooks/useStyle'; import './index.less'; let echarts = window.echarts as typeof Echarts; if (!echarts) { echarts = Echarts; } // 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型 type ECOption = ComposeOption<MapSeriesOption | CustomSeriesOption | TooltipComponentOption | GridComponentOption>; export interface MapDivisions { value: string; label: string; children: MapDivisions[]; } interface MapChartProps { /** 地图行政区划 code */ geoCode?: string; /** 显示地名 */ showLabel?: boolean; /** 地名字体大小 */ labelSize?: number; /** 是否禁用图表交互 */ mapSilent?: boolean; /** 允许下钻 */ enableDrill?: boolean; /** 控制缩放比例 */ zoom?: number; /** 本地地图 Json(如果传了就用本地的) */ mapJson?: any; /** 图表配置 */ config?: ECOption; /** 下钻后的图表配置 */ drilledConfig?: ECOption; /** 点数据 */ pointData?: { name: string; value: number[] }[]; /** 飞线数据 */ lineData?: { coords: number[][]; }[]; style?: CSSProperties; /** 返回按钮样式 */ returnBtnStyle?: CSSProperties; /** 返回按钮文本 */ returnBtnText?: string; onEvents?: Record<string, (params?: any) => void>; } const MapChart = forwardRef<EChartsReact, MapChartProps>( ( { geoCode = INITIAL_GEO_CODE, showLabel = false, mapSilent = false, enableDrill = false, labelSize = 16, zoom = 1.2, mapJson, pointData = [], lineData = [], style, returnBtnStyle, returnBtnText, onEvents, config, drilledConfig, }, ref ) => { const _echartsRef = useRef<ReactEcharts>(null); const echartsRef = (ref as MutableRefObject<ReactEcharts>) ?? _echartsRef; // 是否已经第一次注册地图 const [isRegistered, setIsRegistered] = useState<boolean>(false); const [refreshing, setRefreshing] = useState<boolean>(false); const [mapInfoList, setMapInfoList] = useState<{ name: string; code: string; json: any }[]>([]); const { style: modifiedStyle } = useStyle(style); const mapName = useMemo(() => getMapName(geoCode), [geoCode]); const isDrilled = useMemo(() => mapInfoList.length > 1, [mapInfoList]); const option = useMemo(() => { const { name: selectedName } = mapInfoList[mapInfoList.length - 1] || {}; const newName = selectedName || mapName; const mapSeries = getMapSeries(newName, zoom); const modifiedSeries = mapSeries.map((item, idx) => { const name = `${newName}${idx || ''}`; if (idx < 3) { return { ...item, map: name, }; } return { ...item, map: name, label: { show: showLabel, fontSize: labelSize, color: '#fff', }, silent: mapSilent, zoom, }; }) as MapSeriesOption[]; return merge( { series: modifiedSeries.concat([ { type: 'effectScatter', coordinateSystem: 'geo', symbolSize: 14, rippleEffect: { brushType: 'fill', }, itemStyle: { color: INITIAL_POINT_COLOR, }, symbol: 'circle', data: pointData, z: 3, tooltip: { show: true, }, }, { type: 'lines', zlevel: 2, effect: { show: true, period: 2, // 箭头指向速度,值越小速度越快 trailLength: 0.5, // 特效尾迹长度[0,1]值越大,尾迹越长重 symbol: 'arrow', // 箭头图标 symbolSize: 7, // 图标大小 }, lineStyle: { normal: { color: INITIAL_LINE_COLOR, width: 1, // 线条宽度 opacity: 0.1, // 尾迹线条透明度 curveness: 0.3, // 尾迹线条曲直度 }, }, data: lineData, } as LinesSeriesOption, ] as MapSeriesOption[]), geo: { aspectScale: 0.75, roam: false, silent: true, top: 100, itemStyle: { borderColor: '#697899', borderWidth: 1, areaColor: '#103682', shadowColor: 'RGBA(75, 192, 255, 0.6)', shadowOffsetX: 6, shadowOffsetY: 5, shadowBlur: 20, }, map: newName, zoom, }, } as EChartsOption, isDrilled && drilledConfig ? drilledConfig : config ); // eslint-disable-next-line react-hooks/exhaustive-deps }, [config, labelSize, lineData, mapName, mapInfoList, mapSilent, pointData, showLabel, zoom]); useLayoutEffect(() => { (async () => { // 使用本地 mapJson if (mapJson) { await registerCustomMap(mapName, geoCode, mapJson); setIsRegistered(true); setMapInfoList([{ name: mapName, code: geoCode, json: mapJson }]); return; } const newMapJson = await registerCustomMap(mapName, geoCode); if (!newMapJson) { return; } setMapInfoList([{ name: mapName, code: geoCode, json: newMapJson }]); setIsRegistered(true); })(); }, [geoCode, mapJson, mapName]); /** 重置地图 */ const handleResetMap = useCallback(() => { if (!isRegistered) { return; } const mapInstance = (echartsRef as MutableRefObject<ReactEcharts>).current?.getEchartsInstance() as ECharts; if (!mapInstance) return; const { name: parentName, code: parentCode, json: parentJson } = mapInfoList[mapInfoList.length - 2]; registerCustomMap(mapName, parentCode, parentJson); setMapInfoList(mapInfoList.slice(0, -1)); }, [isRegistered, echartsRef, mapInfoList, mapName]); /** 绑定地图下钻事件 */ const bindDrillEvent = useCallback(() => { const mapInstance = (echartsRef as MutableRefObject<ReactEcharts>).current?.getEchartsInstance() as ECharts; if (!isRegistered || !enableDrill) { return; } if (!mapInstance) return; mapInstance.on('click', function (e: any) { (async () => { const { code, json: currentMapJson } = mapInfoList[mapInfoList.length - 1]; if (!currentMapJson) { return; } const newName = e.data?.location ?? e.name; const currentFeature = currentMapJson.features.find((item: any) => item.properties.name === newName); const { adcode = '' } = currentFeature?.properties || {}; // 如果跟上次选择的地区相同则返回 if (`${adcode}` === code) { return; } // 注册子地区地图 const result = await registerCustomMap(newName, `${adcode}`); if (!result) { return; } setMapInfoList(mapInfoList.concat({ name: newName, code: `${adcode}`, json: result })); })(); }); }, [echartsRef, enableDrill, isRegistered, mapInfoList]); useEffect(() => { // 强制触发重新加载 setRefreshing(true); requestAnimationFrame(() => { setRefreshing(false); /** 点击地图下钻 */ bindDrillEvent(); }); }, [bindDrillEvent, mapInfoList]); return ( <div style={modifiedStyle}> {isDrilled && ( <div className="td-lego-map-return-btn" style={returnBtnStyle} onClick={handleResetMap}> {returnBtnText ?? '< 返回上级'} </div> )} {isRegistered && !refreshing && ( <ReactEcharts ref={echartsRef} echarts={echarts} option={option} style={{ width: modifiedStyle.width, height: modifiedStyle.height }} onEvents={onEvents} /> )} </div> ); } ); export default MapChart; /** 获得地图名称 */ export const getMapName = (geoCode?: string) => { if (!geoCode) { return 'china'; } const getGeoList = () => { const codeList: string[] = []; let preStr = ''; for (let i = 0; i < geoCode.length; i += 2) { const codeStr = geoCode?.slice(i, i + 2); if (codeStr === '00') { break; } codeList.push(`${preStr}${codeStr}`); preStr += codeStr; } return codeList; }; const geoNames = getGeoList(); let currentGeoArr = mapGeoDivisions; let currenName = INITIAL_MAP_NAME; if (!geoNames || geoNames[0] === CHINA_GEO_VALUE) { return currenName; } for (let i = 0; i < geoNames.length; i++) { const newGeoObj = currentGeoArr.find(item => item.value === geoNames[i]); if (!newGeoObj) { return currenName; } currentGeoArr = newGeoObj.children || []; // 如果是市辖区,名称还是上一级的名称 currenName = newGeoObj.label === '市辖区' ? currenName : newGeoObj.label; } return currenName; }; /** 注册指定名字地图 */ const registerCustomMap = async (name: string, geoCode?: string, currentMapJson?: any) => { if (!name || !geoCode) { return; } /** 注册多层 layer 以得到层叠样式 */ const registerMapJson = async (name: string, mapJson: any) => { for (let i = 0; i < 4; i++) { echarts.registerMap(`${name}${i || ''}`, mapJson); } }; if (currentMapJson) { registerMapJson(name, currentMapJson); return; } try { const response = await fetch(`${GEO_SOURCE_URL}${geoJson[geoCode]}`); if (response.status !== 200) { throw new Error(`请求失败:${response.statusText}`); } const mapJson = await response.json(); registerMapJson(name, mapJson); return mapJson; } catch (err) { console.error(err); return null; } };
the_stack
import { ChatReplayData, RestartConversationStatus } from '@bfemulator/app-shared'; import cloneDeep from 'clone-deep'; import { Activity } from 'botframework-schema'; import { replayScenarios } from '../../mocks/conversationQueueMocks'; import { ConversationQueue, WebChatEvents } from './restartConversationQueue'; describe('Restart Conversation Queue', () => { let scenarios; beforeEach(() => { scenarios = cloneDeep(replayScenarios); }); it('should validate if it is in Replay conversational flow', () => { const { activitiesToBePosted, incomingActivities, postActivitiesSlots } = scenarios[2]; const queue: ConversationQueue = new ConversationQueue( activitiesToBePosted, { incomingActivities, postActivitiesSlots, }, '123', activitiesToBePosted[activitiesToBePosted.length - 1], jest.fn() ); expect(queue.validateIfReplayFlow(RestartConversationStatus.Started, WebChatEvents.incomingActivity)).toBeTruthy(); expect(queue.validateIfReplayFlow(RestartConversationStatus.Rejected, WebChatEvents.incomingActivity)).toBeFalsy(); expect(queue.validateIfReplayFlow(undefined, WebChatEvents.incomingActivity)).toBeFalsy(); expect(queue.validateIfReplayFlow(RestartConversationStatus.Started, WebChatEvents.postActivity)).toBeFalsy(); expect(queue.validateIfReplayFlow(RestartConversationStatus.Started, 'WEBCHAT/SEND_TYPING')).toBeFalsy(); }); it('should give the correct activity to be posted next if available in scenario[0]', () => { const activities: any = scenarios[0].activitiesToBePosted; const chatReplayData: ChatReplayData = { incomingActivities: scenarios[0].incomingActivities, postActivitiesSlots: scenarios[0].postActivitiesSlots, }; const queue: ConversationQueue = new ConversationQueue(activities, chatReplayData, '123', activities[1], jest.fn()); expect(queue.getNextActivityForPost()).toBeUndefined(); expect(queue.replayComplete).toBeFalsy(); queue.handleIncomingActivity(chatReplayData.incomingActivities[0] as Activity); const postActivity: Activity = queue.getNextActivityForPost(); expect(postActivity.channelData.matchIndexes).toEqual([1, 2]); const botResponsesForActivity: Activity[] = scenarios[0].botResponsesForActivity; queue.handleIncomingActivity(botResponsesForActivity[1]); expect(queue.getNextActivityForPost()).toBeUndefined(); queue.handleIncomingActivity(botResponsesForActivity[2]); expect(queue.getNextActivityForPost()).toBeUndefined(); const err = queue.handleIncomingActivity(botResponsesForActivity[3]); expect(err).toBeUndefined(); expect(queue.getNextActivityForPost()).toBeDefined(); }); it('should throw error if activities arrive in the wrong order on replay in scenario[0]', () => { const activities: any = scenarios[0].activitiesToBePosted; const chatReplayData: ChatReplayData = { incomingActivities: scenarios[0].incomingActivities, postActivitiesSlots: scenarios[0].postActivitiesSlots, }; const queue: ConversationQueue = new ConversationQueue(activities, chatReplayData, '123', activities[1], jest.fn()); // Conversation Update queue.handleIncomingActivity(chatReplayData.incomingActivities[0] as Activity); const botResponsesForActivity: Activity[] = scenarios[0].botResponsesForActivity; queue.handleIncomingActivity(botResponsesForActivity[1]); expect(queue.getNextActivityForPost()).toBeUndefined(); // The original conversation had 2 bot responses for the activity before an echoback const err = queue.handleIncomingActivity(botResponsesForActivity[3]); expect(err).toBeDefined(); expect(queue.replayComplete).toBeFalsy(); }); it('should replay scenario1 without errors and should set replay to complete - Scenario[1]', () => { const { activitiesToBePosted, incomingActivities, postActivitiesSlots, botResponsesForActivity } = scenarios[1]; const queue: ConversationQueue = new ConversationQueue( activitiesToBePosted, { incomingActivities, postActivitiesSlots, }, '123', activitiesToBePosted[activitiesToBePosted.length - 1], jest.fn() ); // Conversation Update let err; err = queue.handleIncomingActivity(incomingActivities[0]); expect(err).toBeUndefined(); expect(queue.getNextActivityForPost()).toBeUndefined(); queue.handleIncomingActivity(incomingActivities[1]); let activity = queue.getNextActivityForPost(); expect(activity).toBeDefined(); err = queue.handleIncomingActivity(botResponsesForActivity[2]); err = queue.handleIncomingActivity(botResponsesForActivity[3]); expect(err).toBeUndefined(); err = queue.handleIncomingActivity(botResponsesForActivity[4]); err = queue.handleIncomingActivity(botResponsesForActivity[5]); expect(err).toBeUndefined(); activity = queue.getNextActivityForPost(); expect(activity).toBeDefined(); err = queue.handleIncomingActivity(botResponsesForActivity[6]); err = queue.handleIncomingActivity(botResponsesForActivity[7]); expect(err).toBeUndefined(); err = queue.handleIncomingActivity(botResponsesForActivity[8]); expect(err).toBeUndefined(); expect(queue.replayComplete).toBeTruthy(); }); it('should handle multiple events sent before we get completion for the first one - Scenario[2]', () => { const { activitiesToBePosted, incomingActivities, postActivitiesSlots, botResponsesForActivity } = scenarios[2]; const queue: ConversationQueue = new ConversationQueue( activitiesToBePosted, { incomingActivities, postActivitiesSlots, }, '123', activitiesToBePosted[activitiesToBePosted.length - 1], jest.fn() ); let err; queue.handleIncomingActivity(botResponsesForActivity[0]); const postActivity2: Activity = queue.getNextActivityForPost(); expect(postActivity2).toBeDefined(); expect(postActivity2.channelData.matchIndexes).toEqual([1, 4, 7, 8]); err = queue.handleIncomingActivity(botResponsesForActivity[1]); expect(err).toBeUndefined(); const postActivity3: Activity = queue.getNextActivityForPost(); expect(postActivity3.channelData.matchIndexes).toEqual([2, 3, 5]); queue.handleIncomingActivity(botResponsesForActivity[2]); queue.handleIncomingActivity(botResponsesForActivity[3]); queue.handleIncomingActivity(botResponsesForActivity[4]); queue.handleIncomingActivity(botResponsesForActivity[5]); //Act3 completed err = queue.handleIncomingActivity(botResponsesForActivity[6]); expect(err).toBeUndefined(); expect(queue.getNextActivityForPost()).toBeUndefined(); queue.handleIncomingActivity(botResponsesForActivity[7]); err = queue.handleIncomingActivity(botResponsesForActivity[8]); expect(err).toBeUndefined(); expect(queue.getNextActivityForPost()).toBeUndefined(); expect(queue.replayComplete).toBeFalsy(); }); it('should set replay complete once the last action that the user set for restart was fired - Scenario[2]', () => { const { activitiesToBePosted, incomingActivities, postActivitiesSlots, botResponsesForActivity } = scenarios[2]; const queue: ConversationQueue = new ConversationQueue( activitiesToBePosted, { incomingActivities, postActivitiesSlots, }, '123', activitiesToBePosted[activitiesToBePosted.length - 2], jest.fn() ); queue.handleIncomingActivity(botResponsesForActivity[0]); queue.getNextActivityForPost(); queue.handleIncomingActivity(botResponsesForActivity[1]); queue.getNextActivityForPost(); queue.handleIncomingActivity(botResponsesForActivity[2]); // We have asked the queue to stop after posting 2 activities expect(queue.replayComplete).toBeTruthy(); }); it('should set replay complete after 3 actions have been posted - Scenario[2]', () => { const { activitiesToBePosted, incomingActivities, postActivitiesSlots, botResponsesForActivity } = scenarios[2]; const queue: ConversationQueue = new ConversationQueue( activitiesToBePosted, { incomingActivities, postActivitiesSlots, }, '123', activitiesToBePosted[activitiesToBePosted.length - 1], jest.fn() ); queue.handleIncomingActivity(botResponsesForActivity[0]); queue.handleIncomingActivity(botResponsesForActivity[1]); queue.handleIncomingActivity(botResponsesForActivity[2]); queue.handleIncomingActivity(botResponsesForActivity[3]); queue.handleIncomingActivity(botResponsesForActivity[4]); queue.handleIncomingActivity(botResponsesForActivity[5]); queue.handleIncomingActivity(botResponsesForActivity[6]); queue.handleIncomingActivity(botResponsesForActivity[7]); expect(queue.replayComplete).toBeFalsy(); queue.handleIncomingActivity(botResponsesForActivity[8]); queue.handleIncomingActivity(botResponsesForActivity[9]); const postActivity = queue.getNextActivityForPost(); expect(postActivity).toBeDefined(); queue.handleIncomingActivity(botResponsesForActivity[10]); expect(queue.replayComplete).toBeTruthy(); }); it('should set replay complete after progressive responses arrive - Scenario[3]', () => { const { activitiesToBePosted, incomingActivities, postActivitiesSlots, botResponsesForActivity } = scenarios[3]; const queue: ConversationQueue = new ConversationQueue( activitiesToBePosted, { incomingActivities, postActivitiesSlots, }, '123', activitiesToBePosted[activitiesToBePosted.length - 1], jest.fn() ); queue.handleIncomingActivity(botResponsesForActivity[0]); queue.handleIncomingActivity(botResponsesForActivity[1]); queue.handleIncomingActivity(botResponsesForActivity[2]); queue.handleIncomingActivity(botResponsesForActivity[3]); queue.handleIncomingActivity(botResponsesForActivity[4]); queue.handleIncomingActivity(botResponsesForActivity[5]); queue.handleIncomingActivity(botResponsesForActivity[6]); queue.handleIncomingActivity(botResponsesForActivity[7]); queue.handleIncomingActivity(botResponsesForActivity[8]); queue.handleIncomingActivity(botResponsesForActivity[9]); queue.handleIncomingActivity(botResponsesForActivity[10]); queue.handleIncomingActivity(botResponsesForActivity[11]); queue.handleIncomingActivity(botResponsesForActivity[12]); let err = queue.handleIncomingActivity(botResponsesForActivity[13]); // Progressive response for Act2 arrived at the correct spot expect(err).toBeUndefined(); err = queue.handleIncomingActivity(botResponsesForActivity[14]); // Another Progressive response for Act2 arrived at the correct spot expect(err).toBeUndefined(); }); });
the_stack
import { BigNumber } from 'bignumber.js'; import { buf2hex, b58cdecode, textDecode, textEncode } from './utility'; import { prefix, forgeMappings } from './constants'; interface Operation { kind: string; level?: number; nonce?: string; pkh?: string; hash?: string; secret?: string; source?: string; period?: number; proposal?: string; ballot?: string; fee?: string; counter?: string; gas_limit?: string; storage_limit?: string; parameters?: Micheline; balance?: string; delegate?: string; amount?: string; destination?: string; public_key?: string; script?: { code: Micheline; storage: Micheline }; } interface OperationObject { branch?: string; contents?: Operation[]; protocol?: string; signature?: string; } interface ForgedBytes { opbytes: string; opOb: OperationObject; counter: number; } type Micheline = | { entrypoint: string; value: | { prim: string; args?: MichelineArray; annots?: string[]; } | { bytes: string } | { int: string } | { string: string } | { address: string } | { contract: string } | { key: string } | { key_hash: string } | { signature: string } | MichelineArray; } | { prim: string; args?: MichelineArray; annots?: string[]; } | { bytes: string } | { int: string } | { string: string } | { address: string } | { contract: string } | { key: string } | { key_hash: string } | { signature: string } | MichelineArray; type MichelineArray = Array<Micheline>; /** * @description Convert bytes from Int32 * @param {number} num Number to convert to bytes * @returns {Object} The converted number */ export const toBytesInt32 = (num: number): any => { // @ts-ignore num = parseInt(num, 10); const arr = new Uint8Array([ (num & 0xff000000) >> 24, (num & 0x00ff0000) >> 16, (num & 0x0000ff00) >> 8, num & 0x000000ff, ]); return arr.buffer; }; /** * @description Convert hex from Int32 * @param {number} num Number to convert to hex * @returns {string} The converted number */ export const toBytesInt32Hex = (num: number): string => { const forgedBuffer = new Uint8Array(toBytesInt32(num)); return buf2hex(forgedBuffer); }; /** * @description Convert bytes from Int16 * @param {number} num Number to convert to bytes * @returns {Object} The converted number */ export const toBytesInt16 = (num: number): any => { // @ts-ignore num = parseInt(num, 10); const arr = new Uint8Array([(num & 0xff00) >> 8, num & 0x00ff]); return arr.buffer; }; /** * @description Convert hex from Int16 * @param {number} num Number to convert to hex * @returns {string} The converted number */ export const toBytesInt16Hex = (num: number): string => { const forgedBuffer = new Uint8Array(toBytesInt16(num)); return buf2hex(forgedBuffer); }; /** * @description Forge boolean * @param {boolean} boolArg Boolean value to convert * @returns {string} The converted boolean */ export const bool = (boolArg: boolean): string => (boolArg ? 'ff' : '00'); /** * @description Forge script bytes * @param {Object} scriptArg Script to forge * @param {string} scriptArg.code Script code * @param {string} scriptArg.storage Script storage * @returns {string} Forged script bytes */ export const script = (scriptArg: { code: Micheline; storage: Micheline; }): string => { const t1 = encodeRawBytes(scriptArg.code).toLowerCase(); const t2 = encodeRawBytes(scriptArg.storage).toLowerCase(); return ( toBytesInt32Hex(t1.length / 2) + t1 + toBytesInt32Hex(t2.length / 2) + t2 ); }; /** * @description Forge parameter bytes * @param {string} parameter Script to forge * @returns {string} Forged parameter bytes */ export const parameters = (parameter: any): string => { const fp: string[] = []; const isDefaultParameter = parameter.entrypoint === 'default'; fp.push(isDefaultParameter ? '00' : 'FF'); if (!isDefaultParameter) { const parameterBytes = encodeRawBytes(parameter.value).toLowerCase(); if (forgeMappings.entrypointMappingReverse[parameter.entrypoint]) { fp.push(forgeMappings.entrypointMappingReverse[parameter.entrypoint]); } else { const stringBytes = encodeRawBytes({ string: parameter.entrypoint, }).toLowerCase(); fp.push('FF'); fp.push(stringBytes.slice(8)); } fp.push((parameterBytes.length / 2).toString(16).padStart(8, '0')); fp.push(parameterBytes); } return fp.join(''); }; /** * @description Forge public key hash bytes * @param {string} pkh Public key hash to forge * @returns {string} Forged public key hash bytes */ export const publicKeyHash = (pkh: string): string => { const t = parseInt(pkh.substr(2, 1), 10); const fpkh = [`0${t - 1}`]; const forgedBuffer = new Uint8Array( b58cdecode(pkh, prefix[pkh.substring(0, 3)]), ); fpkh.push(buf2hex(forgedBuffer)); return fpkh.join(''); }; /** * @description Forge address bytes * @param {string} addressArg Address to forge * @returns {string} Forged address bytes */ export const address = (addressArg: string): string => { const fa: string[] = []; if (addressArg.substring(0, 1) === 'K') { fa.push('01'); const forgedBuffer = new Uint8Array(b58cdecode(addressArg, prefix.KT)); fa.push(buf2hex(forgedBuffer)); fa.push('00'); } else { fa.push('00'); fa.push(publicKeyHash(addressArg)); } return fa.join(''); }; /** * @description Forge zarith bytes * @param {number} n Zarith to forge * @returns {string} Forged zarith bytes */ export const zarith = (n: string): string => { const fn: string[] = []; let nn = new BigNumber(n, 10); if (nn.isNaN()) { throw new TypeError(`Error forging zarith ${n}`); } // eslint-disable-next-line no-constant-condition while (true) { if (nn.lt(128)) { if (nn.lt(16)) fn.push('0'); fn.push(nn.toString(16)); break; } else { let b = nn.mod(128); nn = nn.minus(b); nn = nn.dividedBy(128); b = b.plus(128); fn.push(b.toString(16)); } } return fn.join(''); }; /** * @description Forge public key bytes * @param {number} pk Public key to forge * @returns {string} Forged public key bytes */ export const publicKey = (pk: string): string => { const fpk: string[] = []; const keyPrefix = pk.substring(0, 2); if (keyPrefix === 'ed') { fpk.push('00'); } if (keyPrefix === 'sp') { fpk.push('01'); } if (keyPrefix === 'p2') { fpk.push('02'); } const forgedBuffer = new Uint8Array( b58cdecode(pk, prefix[pk.substring(0, 4)]), ); fpk.push(buf2hex(forgedBuffer)); return fpk.join(''); }; /** * @description Forge operation bytes * @param {Object} op Operation to forge * @returns {string} Forged operation bytes */ export const operation = (op: Operation): string => { const fop: string[] = []; const forgedBuffer = new Uint8Array([ forgeMappings.forgeOpTags['009'][op.kind], ]); fop.push(buf2hex(forgedBuffer)); if (op.kind === 'endorsement') { fop.push(endorsement(op)); } else if (op.kind === 'seed_nonce_revelation') { fop.push(seedNonceRevelation(op)); } else if (op.kind === 'double_endorsement_evidence') { fop.push(doubleEndorsementEvidence()); } else if (op.kind === 'double_baking_evidence') { fop.push(doubleBakingEvidence()); } else if (op.kind === 'activate_account') { fop.push(activateAccount(op)); } else if (op.kind === 'proposals') { fop.push(proposals()); } else if (op.kind === 'ballot') { fop.push(ballot(op)); } else if (op.kind === 'reveal') { fop.push(reveal(op)); } else if (op.kind === 'transaction') { fop.push(transaction(op)); } else if (op.kind === 'origination') { fop.push(origination(op)); } else if (op.kind === 'delegation') { fop.push(delegation(op)); } return fop.join(''); }; /** * @description Forge endorsement operation bytes * @param {Object} op Operation to forge * @returns {string} Forged operation bytes */ export const endorsement = (op: Operation): string => { if (!op.level) { throw new Error('Endorsement operation malformed. Missing level.'); } const levelBuffer = new Uint8Array(toBytesInt32(op.level)); return buf2hex(levelBuffer); }; /** * @description Forge seed_nonce_revelation operation bytes * @param {Object} op Operation to forge * @returns {string} Forged operation bytes */ export const seedNonceRevelation = (op: Operation): string => { const fop: string[] = []; if (!op.level || !op.nonce) { throw new Error( 'SeedNonceRevelation operation malformed. Missing level or nonce.', ); } const levelBuffer = new Uint8Array(toBytesInt32(op.level)); fop.push(buf2hex(levelBuffer)); fop.push(op.nonce); return fop.join(''); }; // eslint-disable-next-line jsdoc/require-returns-check /** * @description Forge double_endorsement_evidence operation bytes * @returns {string} Forged operation bytes */ export const doubleEndorsementEvidence = (): string => { throw new Error('Double endorse forging is not complete'); }; // eslint-disable-next-line jsdoc/require-returns-check /** * @description Forge double_baking_evidence operation bytes * @returns {string} Forged operation bytes */ export const doubleBakingEvidence = (): string => { throw new Error('Double bake forging is not complete'); }; /** * @description Forge activate_account operation bytes * @param {Object} op Operation to forge * @returns {string} Forged operation bytes */ export const activateAccount = (op: Operation): string => { const fop: string[] = []; if (!op.pkh || !op.secret) { throw new Error( 'ActivateAccount operation malformed. Missing pkh or secret.', ); } const addressBuffer = new Uint8Array(b58cdecode(op.pkh, prefix.tz1)); fop.push(buf2hex(addressBuffer)); fop.push(op.secret); return fop.join(''); }; // eslint-disable-next-line jsdoc/require-returns-check /** * @description Forge proposals operation bytes * @returns {string} Forged operation bytes */ export const proposals = (): string => { throw new Error('Proposal forging is not complete'); }; /** * @description Forge ballot operation bytes * @param {Object} op Operation to forge * @returns {string} Forged operation bytes */ export const ballot = (op: Operation): string => { const fop: string[] = []; if (!op.source || !op.period || !op.proposal) { throw new Error( 'Ballot operation malformed. Missing source, period, or proposal.', ); } fop.push(publicKeyHash(op.source)); const periodBuffer = new Uint8Array(toBytesInt32(op.period)); fop.push(buf2hex(periodBuffer)); const forgedBuffer = new Uint8Array(b58cdecode(op.proposal, prefix.P)); fop.push(buf2hex(forgedBuffer)); let ballotBytes; if (op.ballot === 'yay' || op.ballot === 'yea') { ballotBytes = '00'; } else if (op.ballot === 'nay') { ballotBytes = '01'; } else { ballotBytes = '02'; } fop.push(ballotBytes); return fop.join(''); }; /** * @description Forge reveal operation bytes * @param {Object} op Operation to forge * @returns {string} Forged operation bytes */ export const reveal = (op: Operation): string => { if ( !op.source || !op.fee || !op.counter || !op.gas_limit || !op.storage_limit || !op.public_key ) { throw new Error( 'Reveal operation malformed. Missing source, fee, counter, gas_limit, storage_limit, or public_key.', ); } const fop: string[] = []; fop.push(publicKeyHash(op.source)); fop.push(zarith(op.fee)); fop.push(zarith(op.counter)); fop.push(zarith(op.gas_limit)); fop.push(zarith(op.storage_limit)); fop.push(publicKey(op.public_key)); return fop.join(''); }; /** * @description Forge transaction operation bytes * @param {Object} op Operation to forge * @returns {string} Forged operation bytes */ export const transaction = (op: Operation): string => { if ( !op.source || !op.fee || !op.counter || !op.gas_limit || !op.storage_limit || !op.amount || !op.destination ) { throw new Error( 'Reveal operation malformed. Missing source, fee, counter, gas_limit, storage_limit, amount, or destination.', ); } const fop = []; fop.push(publicKeyHash(op.source)); fop.push(zarith(op.fee)); fop.push(zarith(op.counter)); fop.push(zarith(op.gas_limit)); fop.push(zarith(op.storage_limit)); fop.push(zarith(op.amount)); fop.push(address(op.destination)); if (op.parameters) { fop.push(parameters(op.parameters)); } else { fop.push(bool(false)); } return fop.join(''); }; /** * @description Forge origination operation bytes * @param {Object} op Operation to forge * @returns {string} Forged operation bytes */ export const origination = (op: Operation): string => { if ( !op.source || !op.fee || !op.counter || !op.gas_limit || !op.storage_limit || !op.balance || !op.script ) { throw new Error( 'Reveal operation malformed. Missing source, fee, counter, gas_limit, storage_limit, balance, or script.', ); } const fop: string[] = []; fop.push(publicKeyHash(op.source)); fop.push(zarith(op.fee)); fop.push(zarith(op.counter)); fop.push(zarith(op.gas_limit)); fop.push(zarith(op.storage_limit)); fop.push(zarith(op.balance)); if (op.delegate) { fop.push(bool(true)); fop.push(publicKeyHash(op.delegate)); } else { fop.push(bool(false)); } fop.push(script(op.script)); return fop.join(''); }; /** * @description Forge delegation operation bytes * @param {Object} op Operation to forge * @returns {string} Forged operation bytes */ export const delegation = (op: Operation): string => { if ( !op.source || !op.fee || !op.counter || !op.gas_limit || !op.storage_limit ) { throw new Error( 'Reveal operation malformed. Missing source, fee, counter, gas_limit or storage_limit.', ); } const fop: string[] = []; fop.push(publicKeyHash(op.source)); fop.push(zarith(op.fee)); fop.push(zarith(op.counter)); fop.push(zarith(op.gas_limit)); fop.push(zarith(op.storage_limit)); if (op.delegate) { fop.push(bool(true)); fop.push(publicKeyHash(op.delegate)); } else { fop.push(bool(false)); } return fop.join(''); }; /** * @description Forge operation bytes * @param {Object} opOb The operation object(s) * @param {number} counter The current counter for the account * @param {string} protocol The next protocol for the operation. Used to handle protocol upgrade events if necessary. * @returns {string} Forged operation bytes * @example * forge.forge({ * branch: head.hash, * contents: [{ * kind: 'transaction', * source: 'tz1fXdNLZ4jrkjtgJWMcfeNpFDK9mbCBsaV4', * fee: '50000', * counter: '31204', * gas_limit: '10200', * storage_limit: '0', * amount: '100000000', * destination: 'tz1RvhdZ5pcjD19vCCK9PgZpnmErTba3dsBs', * }], * }, 32847).then(({ opbytes, opOb }) => console.log(opbytes, opOb)); */ export const forge = async ( opOb: OperationObject, counter: number, // eslint-disable-next-line @typescript-eslint/no-unused-vars protocol: string, ): Promise<ForgedBytes> => { if (!opOb.contents) { throw new Error('No operation contents provided.'); } if (!opOb.branch) { throw new Error('No operation branch provided.'); } const forgedBuffer = new Uint8Array(b58cdecode(opOb.branch, prefix.b)); const forgedBytes = [buf2hex(forgedBuffer)]; opOb.contents.forEach((content: Operation): void => { forgedBytes.push(operation(content)); }); return { opbytes: forgedBytes.join(''), opOb, counter, }; }; /** * @description Decode raw bytes * @param {string} bytes The bytes to decode * @returns {Object} Decoded raw bytes */ export const decodeRawBytes = (bytes: string): Micheline => { bytes = bytes.toUpperCase(); let index = 0; const read = (len: number) => { const readBytes = bytes.slice(index, index + len); index += len; return readBytes; }; const rec = (): any => { const b = read(2); const prim = forgeMappings.primMapping[b]; if (prim instanceof Object) { const forgeOp = forgeMappings.opMapping[read(2)]; const args = [...Array(prim.len)]; const result: { prim: string; args?: (string | number | boolean)[]; annots?: string[]; } = { prim: forgeOp, args: args.map(() => rec()), annots: undefined, }; if (!prim.len) { delete result.args; } if (prim.annots) { const annotsLen = parseInt(read(8), 16) * 2; const stringHexLst = read(annotsLen).match(/[\dA-F]{2}/g); if (stringHexLst) { const stringBytes = new Uint8Array( stringHexLst.map((x) => parseInt(x, 16)), ); const stringResult = textDecode(stringBytes); result.annots = stringResult.split(' '); } } else { delete result.annots; } return result; } if (b === '0A') { const len = read(8); const intLen = parseInt(len, 16) * 2; const data = read(intLen); return { bytes: data }; } if (b === '01') { const len = read(8); const intLen = parseInt(len, 16) * 2; const data = read(intLen); const matchResult = data.match(/[\dA-F]{2}/g); if (matchResult instanceof Array) { const stringRaw = new Uint8Array( matchResult.map((x) => parseInt(x, 16)), ); return { string: textDecode(stringRaw) }; } throw new Error('Input bytes error'); } if (b === '00') { const firstBytes = parseInt(read(2), 16).toString(2).padStart(8, '0'); // const isPositive = firstBytes[1] === '0'; const validBytes = [firstBytes.slice(2)]; let checknext = firstBytes[0] === '1'; while (checknext) { const bytesCheck = parseInt(read(2), 16).toString(2).padStart(8, '0'); validBytes.push(bytesCheck.slice(1)); checknext = bytesCheck[0] === '1'; } const num = new BigNumber(validBytes.reverse().join(''), 2); return { int: num.toString() }; } if (b === '02') { const len = read(8); const intLen = parseInt(len, 16) * 2; // const data = read(intLen); const limit = index + intLen; const seqLst = []; while (limit > index) { seqLst.push(rec()); } return seqLst; } throw new Error(`Invalid raw bytes: Byte:${b} Index:${index}`); }; return rec(); }; /** * @description Encode raw bytes * @param {Object} input The value to encode * @returns {string} Encoded value as bytes */ export const encodeRawBytes = (input: Micheline): string => { const rec = (inputArg: Micheline): string => { const result: string[] = []; if (inputArg instanceof Array) { result.push('02'); const bytes = inputArg.map((x) => rec(x)).join(''); const len = bytes.length / 2; result.push(len.toString(16).padStart(8, '0')); result.push(bytes); } else if (inputArg instanceof Object) { if ('prim' in inputArg) { if (inputArg.prim === 'LAMBDA') { result.push('09'); result.push(forgeMappings.opMappingReverse[inputArg.prim]); if (inputArg.args) { const innerResult: string[] = []; inputArg.args.forEach((arg) => { innerResult.push(rec(arg)); }); const len = innerResult.join('').length / 2; result.push(len.toString(16).padStart(8, '0')); innerResult.forEach((x) => result.push(x)); } const annotsBytes = inputArg.annots ? inputArg.annots .map((x) => buf2hex(new Uint8Array(textEncode(x)))) .join('20') : ''; result.push((annotsBytes.length / 2).toString(16).padStart(8, '0')); if (annotsBytes) { result.push(annotsBytes); } } else { const argsLen = inputArg.args ? inputArg.args.length : 0; result.push( forgeMappings.primMappingReverse[argsLen][`${!!inputArg.annots}`], ); result.push(forgeMappings.opMappingReverse[inputArg.prim]); if (inputArg.args) { inputArg.args.forEach((arg: any) => result.push(rec(arg))); } if (inputArg.annots) { const annotsBytes = inputArg.annots .map((x: any) => { const forgedBuffer = new Uint8Array(textEncode(x)); return buf2hex(forgedBuffer); }) .join('20'); result.push((annotsBytes.length / 2).toString(16).padStart(8, '0')); result.push(annotsBytes); } } } else if ('bytes' in inputArg) { const len = inputArg.bytes.length / 2; result.push('0A'); result.push(len.toString(16).padStart(8, '0')); result.push(inputArg.bytes); } else if ('int' in inputArg) { const num = new BigNumber(inputArg.int, 10); const positiveMark = num.toString(2)[0] === '-' ? '1' : '0'; const binary = num.toString(2).replace('-', ''); const pad = // eslint-disable-next-line no-nested-ternary binary.length <= 6 ? 6 : (binary.length - 6) % 7 ? binary.length + 7 - ((binary.length - 6) % 7) : binary.length; const splitted = binary.padStart(pad, '0').match(/\d{6,7}/g) || []; const reversed = splitted.reverse(); reversed[0] = positiveMark + reversed[0]; const numHex = reversed .map((x: string, i: number) => parseInt((i === reversed.length - 1 ? '0' : '1') + x, 2) .toString(16) .padStart(2, '0'), ) .join(''); result.push('00'); result.push(numHex); } else if ('string' in inputArg) { const stringBytes = textEncode(inputArg.string); const stringHex = [].slice .call(stringBytes) .map((x: any) => x.toString(16).padStart(2, '0')) .join(''); const len = stringBytes.length; result.push('01'); result.push(len.toString(16).padStart(8, '0')); result.push(stringHex); } } return result.join(''); }; return rec(input).toUpperCase(); }; export default { address, decodeRawBytes, encodeRawBytes, forge, operation, endorsement, seedNonceRevelation, doubleEndorsementEvidence, doubleBakingEvidence, activateAccount, proposals, ballot, reveal, transaction, origination, delegation, parameters, publicKey, publicKeyHash, zarith, bool, script, toBytesInt32, toBytesInt32Hex, };
the_stack
import * as cdk from 'monocdk'; import { AutoBump, WritableGitHubRepo } from '../../lib'; import '@monocdk-experiment/assert/jest'; const Stack = cdk.Stack; const MOCK_REPO = new WritableGitHubRepo({ sshKeySecret: { secretArn: 'ssh-key-secret-arn' }, commitUsername: 'user', commitEmail: 'email@email', repository: 'owner/repo', tokenSecretArn: 'token-secret-arn', }); test('autoBump', () => { // GIVEN const stack = new Stack(new cdk.App(), 'TestStack'); // WHEN new AutoBump(stack, 'MyAutoBump', { repo: MOCK_REPO, }); // THEN // build project expect(stack).toHaveResource('AWS::CodeBuild::Project', { Triggers: { Webhook: false, }, Source: { Type: 'GITHUB', GitCloneDepth: 0, Location: 'https://github.com/owner/repo.git', ReportBuildStatus: false, BuildSpec: JSON.stringify({ version: '0.2', phases: { pre_build: { commands: [ 'git config --global user.email "email@email"', 'git config --global user.name "user"', ], }, build: { commands: [ 'export SKIP=false', '$SKIP || { aws secretsmanager get-secret-value --secret-id "ssh-key-secret-arn" --output=text --query=SecretString > ~/.ssh/id_rsa ; }', '$SKIP || { mkdir -p ~/.ssh ; }', '$SKIP || { chmod 0600 ~/.ssh/id_rsa ~/.ssh/config ; }', '$SKIP || { ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts ; }', '$SKIP || { ls .git && { echo ".git directory exists"; } || { echo ".git directory doesnot exist - cloning..." && git init . && git remote add origin git@github.com:owner/repo.git && git fetch && git reset --hard origin/master && git branch -M master && git clean -fqdx; } ; }', "$SKIP || { git describe --exact-match master && { echo 'Skip condition is met, skipping...' && export SKIP=true; } || { echo 'Skip condition is not met, continuing...' && export SKIP=false; } ; }", '$SKIP || { export GITHUB_TOKEN=$(aws secretsmanager get-secret-value --secret-id "token-secret-arn" --output=text --query=SecretString) ; }', '$SKIP || { git rev-parse --verify origin/bump/$VERSION && { git checkout bump/$VERSION && git merge master && /bin/sh ./bump.sh && export VERSION=$(git describe) && echo Finished running user commands; } || { git checkout master && git checkout -b temp && /bin/sh ./bump.sh && export VERSION=$(git describe) && echo Finished running user commands && git branch -M bump/$VERSION; } ; }', '$SKIP || { git merge-base --is-ancestor bump/$VERSION origin/master && { echo "Skipping: bump/$VERSION is an ancestor of origin/master"; export SKIP=true; } || { echo "Pushing: bump/$VERSION is ahead of origin/master"; export SKIP=false; } ; }', '$SKIP || { git remote add origin_ssh git@github.com:owner/repo.git ; }', '$SKIP || { git push --atomic --follow-tags origin_ssh bump/$VERSION:bump/$VERSION ; }', "$SKIP || { curl --fail -X POST -o pr.json --header \"Authorization: token $GITHUB_TOKEN\" --header \"Content-Type: application/json\" -d \"{\\\"title\\\":\\\"chore(release): $VERSION\\\",\\\"base\\\":\\\"master\\\",\\\"head\\\":\\\"bump/$VERSION\\\"}\" https://api.github.com/repos/owner/repo/pulls && export PR_NUMBER=$(node -p 'require(\"./pr.json\").number') ; }", '$SKIP || { curl --fail -X PATCH --header "Authorization: token $GITHUB_TOKEN" --header "Content-Type: application/json" -d "{\\"body\\":\\"See [CHANGELOG](https://github.com/owner/repo/blob/bump/$VERSION/CHANGELOG.md)\\"}" https://api.github.com/repos/owner/repo/pulls/$PR_NUMBER ; }', ], }, }, }, undefined, 2), }, }); }); test('autoBump with schedule', () => { const stack = new Stack(new cdk.App(), 'TestStack'); // WHEN new AutoBump(stack, 'MyAutoBump', { repo: MOCK_REPO, scheduleExpression: 'cron(0 12 * * ? *)', }); // default schedule expect(stack).toHaveResource('AWS::Events::Rule', { ScheduleExpression: 'cron(0 12 * * ? *)', }); }); test('autoBump with custom cloneDepth', () => { // GIVEN const stack = new Stack(new cdk.App(), 'TestStack'); // WHEN new AutoBump(stack, 'MyAutoBump', { repo: MOCK_REPO, cloneDepth: 10, }); // THEN // build project expect(stack).toHaveResource('AWS::CodeBuild::Project', { Triggers: { Webhook: false, }, Source: { Type: 'GITHUB', GitCloneDepth: 10, Location: 'https://github.com/owner/repo.git', ReportBuildStatus: false, BuildSpec: JSON.stringify({ version: '0.2', phases: { pre_build: { commands: [ 'git config --global user.email "email@email"', 'git config --global user.name "user"', ], }, build: { commands: [ 'export SKIP=false', '$SKIP || { aws secretsmanager get-secret-value --secret-id "ssh-key-secret-arn" --output=text --query=SecretString > ~/.ssh/id_rsa ; }', '$SKIP || { mkdir -p ~/.ssh ; }', '$SKIP || { chmod 0600 ~/.ssh/id_rsa ~/.ssh/config ; }', '$SKIP || { ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts ; }', '$SKIP || { ls .git && { echo ".git directory exists"; } || { echo ".git directory doesnot exist - cloning..." && git init . && git remote add origin git@github.com:owner/repo.git && git fetch && git reset --hard origin/master && git branch -M master && git clean -fqdx; } ; }', "$SKIP || { git describe --exact-match master && { echo 'Skip condition is met, skipping...' && export SKIP=true; } || { echo 'Skip condition is not met, continuing...' && export SKIP=false; } ; }", '$SKIP || { export GITHUB_TOKEN=$(aws secretsmanager get-secret-value --secret-id "token-secret-arn" --output=text --query=SecretString) ; }', '$SKIP || { git rev-parse --verify origin/bump/$VERSION && { git checkout bump/$VERSION && git merge master && /bin/sh ./bump.sh && export VERSION=$(git describe) && echo Finished running user commands; } || { git checkout master && git checkout -b temp && /bin/sh ./bump.sh && export VERSION=$(git describe) && echo Finished running user commands && git branch -M bump/$VERSION; } ; }', '$SKIP || { git merge-base --is-ancestor bump/$VERSION origin/master && { echo "Skipping: bump/$VERSION is an ancestor of origin/master"; export SKIP=true; } || { echo "Pushing: bump/$VERSION is ahead of origin/master"; export SKIP=false; } ; }', '$SKIP || { git remote add origin_ssh git@github.com:owner/repo.git ; }', '$SKIP || { git push --atomic --follow-tags origin_ssh bump/$VERSION:bump/$VERSION ; }', "$SKIP || { curl --fail -X POST -o pr.json --header \"Authorization: token $GITHUB_TOKEN\" --header \"Content-Type: application/json\" -d \"{\\\"title\\\":\\\"chore(release): $VERSION\\\",\\\"base\\\":\\\"master\\\",\\\"head\\\":\\\"bump/$VERSION\\\"}\" https://api.github.com/repos/owner/repo/pulls && export PR_NUMBER=$(node -p 'require(\"./pr.json\").number') ; }", '$SKIP || { curl --fail -X PATCH --header "Authorization: token $GITHUB_TOKEN" --header "Content-Type: application/json" -d "{\\"body\\":\\"See [CHANGELOG](https://github.com/owner/repo/blob/bump/$VERSION/CHANGELOG.md)\\"}" https://api.github.com/repos/owner/repo/pulls/$PR_NUMBER ; }', ], }, }, }, undefined, 2), }, }); }); test('autoBump with schedule disabled', () => { // GIVEN const stack = new Stack(new cdk.App(), 'TestStack'); // WHEN new AutoBump(stack, 'MyAutoBump', { repo: MOCK_REPO, scheduleExpression: 'disable', }); // THEN expect(stack).not.toHaveResource('AWS::Events::Rule', { ScheduleExpression: 'cron(0 12 * * ? *)', }); }); test('autoBump with push only', () => { // GIVEN const stack = new Stack(new cdk.App(), 'TestStack'); const repo = new WritableGitHubRepo({ sshKeySecret: { secretArn: 'ssh-key-secret-arn' }, commitUsername: 'user', commitEmail: 'email@email', repository: 'owner/repo', tokenSecretArn: 'token-secret-arn', }); // WHEN new AutoBump(stack, 'MyAutoBump', { repo, pushOnly: true, }); // THEN // build project expect(stack).toHaveResource('AWS::CodeBuild::Project', { Triggers: { Webhook: false, }, Source: { Type: 'GITHUB', GitCloneDepth: 0, Location: 'https://github.com/owner/repo.git', ReportBuildStatus: false, BuildSpec: JSON.stringify({ version: '0.2', phases: { pre_build: { commands: [ 'git config --global user.email "email@email"', 'git config --global user.name "user"', ], }, build: { commands: [ 'export SKIP=false', '$SKIP || { aws secretsmanager get-secret-value --secret-id "ssh-key-secret-arn" --output=text --query=SecretString > ~/.ssh/id_rsa ; }', '$SKIP || { mkdir -p ~/.ssh ; }', '$SKIP || { chmod 0600 ~/.ssh/id_rsa ~/.ssh/config ; }', '$SKIP || { ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts ; }', '$SKIP || { ls .git && { echo ".git directory exists"; } || { echo ".git directory doesnot exist - cloning..." && git init . && git remote add origin git@github.com:owner/repo.git && git fetch && git reset --hard origin/master && git branch -M master && git clean -fqdx; } ; }', "$SKIP || { git describe --exact-match master && { echo 'Skip condition is met, skipping...' && export SKIP=true; } || { echo 'Skip condition is not met, continuing...' && export SKIP=false; } ; }", '$SKIP || { git rev-parse --verify origin/bump/$VERSION && { git checkout bump/$VERSION && git merge master && /bin/sh ./bump.sh && export VERSION=$(git describe) && echo Finished running user commands; } || { git checkout master && git checkout -b temp && /bin/sh ./bump.sh && export VERSION=$(git describe) && echo Finished running user commands && git branch -M bump/$VERSION; } ; }', '$SKIP || { git merge-base --is-ancestor bump/$VERSION origin/master && { echo "Skipping: bump/$VERSION is an ancestor of origin/master"; export SKIP=true; } || { echo "Pushing: bump/$VERSION is ahead of origin/master"; export SKIP=false; } ; }', '$SKIP || { git remote add origin_ssh git@github.com:owner/repo.git ; }', '$SKIP || { git push --atomic --follow-tags origin_ssh bump/$VERSION:bump/$VERSION ; }', ], }, }, }, undefined, 2), }, }); }); test('autoBump with pull request with custom options', () => { // GIVEN const stack = new Stack(new cdk.App(), 'TestStack'); // WHEN new AutoBump(stack, 'MyAutoBump', { repo: MOCK_REPO, title: 'custom title', body: 'custom body', base: { name: 'release', }, }); // THEN // build project expect(stack).toHaveResource('AWS::CodeBuild::Project', { Triggers: { Webhook: false, }, Source: { Type: 'GITHUB', GitCloneDepth: 0, Location: 'https://github.com/owner/repo.git', ReportBuildStatus: false, BuildSpec: JSON.stringify({ version: '0.2', phases: { pre_build: { commands: [ 'git config --global user.email "email@email"', 'git config --global user.name "user"', ], }, build: { commands: [ 'export SKIP=false', '$SKIP || { aws secretsmanager get-secret-value --secret-id "ssh-key-secret-arn" --output=text --query=SecretString > ~/.ssh/id_rsa ; }', '$SKIP || { mkdir -p ~/.ssh ; }', '$SKIP || { chmod 0600 ~/.ssh/id_rsa ~/.ssh/config ; }', '$SKIP || { ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts ; }', '$SKIP || { ls .git && { echo ".git directory exists"; } || { echo ".git directory doesnot exist - cloning..." && git init . && git remote add origin git@github.com:owner/repo.git && git fetch && git reset --hard origin/release && git branch -M release && git clean -fqdx; } ; }', "$SKIP || { git describe --exact-match release && { echo 'Skip condition is met, skipping...' && export SKIP=true; } || { echo 'Skip condition is not met, continuing...' && export SKIP=false; } ; }", '$SKIP || { export GITHUB_TOKEN=$(aws secretsmanager get-secret-value --secret-id "token-secret-arn" --output=text --query=SecretString) ; }', '$SKIP || { git rev-parse --verify origin/bump/$VERSION && { git checkout bump/$VERSION && git merge release && /bin/sh ./bump.sh && export VERSION=$(git describe) && echo Finished running user commands; } || { git checkout release && git checkout -b temp && /bin/sh ./bump.sh && export VERSION=$(git describe) && echo Finished running user commands && git branch -M bump/$VERSION; } ; }', '$SKIP || { git merge-base --is-ancestor bump/$VERSION origin/release && { echo "Skipping: bump/$VERSION is an ancestor of origin/release"; export SKIP=true; } || { echo "Pushing: bump/$VERSION is ahead of origin/release"; export SKIP=false; } ; }', '$SKIP || { git remote add origin_ssh git@github.com:owner/repo.git ; }', '$SKIP || { git push --atomic --follow-tags origin_ssh bump/$VERSION:bump/$VERSION ; }', "$SKIP || { curl --fail -X POST -o pr.json --header \"Authorization: token $GITHUB_TOKEN\" --header \"Content-Type: application/json\" -d \"{\\\"title\\\":\\\"custom title\\\",\\\"base\\\":\\\"release\\\",\\\"head\\\":\\\"bump/$VERSION\\\"}\" https://api.github.com/repos/owner/repo/pulls && export PR_NUMBER=$(node -p 'require(\"./pr.json\").number') ; }", '$SKIP || { curl --fail -X PATCH --header "Authorization: token $GITHUB_TOKEN" --header "Content-Type: application/json" -d "{\\"body\\":\\"custom body\\"}" https://api.github.com/repos/owner/repo/pulls/$PR_NUMBER ; }', ], }, }, }, undefined, 2), }, }); }); test('autoBump with pull request fails when head=base', () => { // GIVEN const stack = new Stack(new cdk.App(), 'TestStack'); // WHEN expect(() => new AutoBump(stack, 'MyAutoBump', { repo: MOCK_REPO, base: { name: 'master', }, head: { name: 'master', }, })).toThrow(); });
the_stack
import React, { Fragment, Component } from 'react' import { connect } from 'dva' import _ from 'lodash' import queryString from 'query-string' import { emitter } from '~/utils/events' import BaseIframe from '~/components/Iframe' import TheStage from '../Stage' import './index.less' import { isKeyboardEvent } from '~/constant/keyboardEvent' import { Props, ConnectState, selectedComponentData, IPageConfig } from './interface' import { LeftWidth, HeaderHeight } from '~/routes/GuiEditor' import { getContainerData, getHetu } from '~/utils' export function getComponentProps(el: Element, pageConfig: IPageConfig): null | selectedComponentData { if (el && el.nodeType === 1) { // 判断是否为DOM节点, 必须同时有这两个key, 才是有效的组件节点 let dataPageConfigPath = el.getAttribute('data-pageconfig-path') let dataComponentType = el.getAttribute('data-component-type') let isValidComponentType = getHetu('isValidComponentType') if (!isValidComponentType(dataComponentType) || !dataPageConfigPath) { // 向父节点查找 return getComponentProps(el.parentNode as Element, pageConfig) } const dataProps = _.get(pageConfig, dataPageConfigPath) if (_.isPlainObject(dataProps)) { const reac = el.getBoundingClientRect() return { parentNode: el.parentNode, reac, dataPageConfigPath, // @ts-ignore dataComponentType, } } else { console.warn(`data-pageconfig-path:${dataPageConfigPath} is not valid`) } } return null } class TheContent extends Component<Props> { static displayName = 'TheContent' state = { width: '100%', height: '100%', } interval: NodeJS.Timeout iframe: HTMLIFrameElement $el: HTMLDivElement componentDidMount() { window.addEventListener('wheel', this.onWheel, { passive: false }) window.addEventListener('keydown', this.onKeyDown) window.addEventListener('resize', this.onResize) emitter.on('highlightComponent', this.highlightComponent) emitter.on('clickThroughByPageConfigPath', this.clickThroughByPageConfigPath) this.calculationSelectedComponentData() } componentWillUnmount() { emitter.off('highlightComponent', this.highlightComponent) emitter.off('clickThroughByPageConfigPath', this.clickThroughByPageConfigPath) window.removeEventListener('resize', this.onResize) window.removeEventListener('keydown', this.onKeyDown) window.removeEventListener('wheel', this.onWheel) clearInterval(this.interval) clearTimeout(this.timeoutHighlightComponent) clearInterval(this.intervalCalculationSelectedComponentData) this.calculationSelectedComponentData = () => { } } // 绑定触摸板事件 onWheel = (e: WheelEvent) => { // 向左或向右滑动时 阻止默认行为 if (e.deltaX < 0 || e.deltaX > 0) { e.preventDefault() } } // 绑定键盘事件 onKeyDown = (e: KeyboardEvent) => { const { dispatch, isLockIframe } = this.props if (e.metaKey && e.keyCode === 83) { // 如果按键是command + s 则阻止默认行为,避免触发网页的保存 e.preventDefault() } // TODO 根据不同的系统, 配置默认快捷键, 并允许用户配置快捷键 if (isKeyboardEvent(e, 'shift')) { // ctrl + shift || commond + shift dispatch({ type: 'guiEditor/setState', payload: { isLockIframe: !isLockIframe, }, }) } } onResize = _.debounce(() => { this.props.dispatch({ type: 'guiEditor/setState', payload: { hoverComponentData: null, selectedComponentData: null, }, }) }, 500) onIframeLoad = (e: React.SyntheticEvent<HTMLIFrameElement, Event>) => { const iframeDocument = _.get(this.iframe, 'contentWindow.document') // 每1秒去获取iframe的尺寸, 当修改元素, iframe 有延迟渲染时, 可以同步尺寸 this.interval = setInterval(() => { const width = iframeDocument.documentElement.scrollWidth || iframeDocument.body.scrollWidth const height = iframeDocument.documentElement.scrollHeight || iframeDocument.body.scrollHeight this.setState({ width, height, }) }, 1000) } onStageMouseMove = _.throttle((e) => { const { isIframeLoading, isDragging, pageConfig } = this.props if (isIframeLoading || isDragging) return false // 获取点击的坐标 const { clientX, clientY } = e if (!this.$el) return false const scrollTop = _.get(this.$el, 'parentNode.scrollTop') const scrollLeft = _.get(this.$el, 'parentNode.scrollLeft') const iframeDocument = _.get(this.iframe, 'contentWindow.document') if (_.isFunction(iframeDocument.elementFromPoint)) { const el = iframeDocument.elementFromPoint( clientX - LeftWidth + scrollLeft, clientY - HeaderHeight + scrollTop, ) const hoverComponentData = getComponentProps(el, pageConfig) if (hoverComponentData) { this.props.dispatch({ type: 'guiEditor/setState', payload: { hoverComponentData, }, }) } } }, 100) onStageMouseLeave = _.debounce((e) => { this.props.dispatch({ type: 'guiEditor/setState', payload: { hoverComponentData: null, }, }) }, 500) last_calculation_time: Date = new Date() intervalCalculationSelectedComponentData: any // 动态计算selectedComponentData的尺寸 calculationSelectedComponentData = () => { let _this = this // 两次执行的时间间隔 let gup = 1000 function calculate() { _this.last_calculation_time = new Date() const { dispatch, pageConfig } = _this.props const iframeDocument = _.get(_this.iframe, 'contentWindow.document') let dataPageConfigPath = _.get(_this.props, 'selectedComponentData.dataPageConfigPath') const el = iframeDocument.documentElement.querySelector(`[data-pageconfig-path='${dataPageConfigPath}']`) let hoverComponentData if (!el || (el && el.nodeType !== 1)) { // hoverComponentData = null hoverComponentData = null } else { hoverComponentData = getComponentProps(el, pageConfig) } dispatch({ type: 'guiEditor/setState', payload: { selectedComponentData: hoverComponentData } }) setTimeout(() => { _this.calculationSelectedComponentData() }, gup); } let diff = (new Date().getTime()) - this.last_calculation_time.getTime() if (diff < gup) { setTimeout(() => { _this.calculationSelectedComponentData() }, gup); } else { calculate() } } /** * 点击页面任意位置 */ onStageClick = (e: MouseEvent) => { const { pageConfig, hoverComponentData, selectedComponentData, containerData, isIframeLoading, isDragging, dispatch } = this.props let _this = this function _onStageClick() { _this.last_calculation_time = new Date() if (isIframeLoading || isDragging || !_.isPlainObject(hoverComponentData)) { return { containerData, selectedComponentData } } else { const { dataComponentType } = hoverComponentData const selectedButtons = getHetu(['editConfigMap', dataComponentType, 'selectedButtons']) let _containerData = getContainerData(pageConfig, hoverComponentData) dispatch({ type: 'guiEditor/setState', payload: { selectedComponentData: hoverComponentData, activeTab: 'base', containerData: _containerData, isInsertItemMode: selectedButtons.indexOf('add') !== -1 }, }) return { containerData: _containerData, selectedComponentData: hoverComponentData } } } return _onStageClick() } /** * 根据pageConfigPath获取DOM节点, 并高亮DOM节点 */ timeoutHighlightComponent: NodeJS.Timeout highlightComponent = (dataPageConfigPath: string, max: number = 100) => { this.last_calculation_time = new Date() if (max === 0) { console.error(`[data-pageconfig-path='${dataPageConfigPath}'] 对应的DOM节点不存在`) return } this.timeoutHighlightComponent && clearTimeout(this.timeoutHighlightComponent) const { dispatch, pageConfig } = this.props const iframeDocument = _.get(this.iframe, 'contentWindow.document') const el = iframeDocument.documentElement.querySelector(`[data-pageconfig-path='${dataPageConfigPath}']`) if (!el || (el && el.nodeType !== 1)) { // el节点可能没渲染出来, 等下一次事件循环再试 this.timeoutHighlightComponent = setTimeout(() => { this.highlightComponent(dataPageConfigPath, max - 1) }, 30); return } const hoverComponentData = getComponentProps(el, pageConfig) dispatch({ type: 'guiEditor/setState', payload: { activeTab: 'base', hoverComponentData, selectedComponentData: hoverComponentData } }) } /** * 通过pageConfigPath触发iframe内部元素点击事件 */ clickThroughByPageConfigPath = (dataPageConfigPath: string, max: number = 100) => { this.last_calculation_time = new Date() if (max === 0) { console.error(`[data-pageconfig-path='${dataPageConfigPath}'] 对应的DOM节点不存在`) return } const iframeDocument = _.get(this.iframe, 'contentWindow.document') const el = iframeDocument.documentElement.querySelector(`[data-pageconfig-path='${dataPageConfigPath}']`) if (!el || (el && el.nodeType !== 1)) { // el节点可能没渲染出来, 等下一次事件循环再试 setTimeout(() => { this.clickThroughByPageConfigPath(dataPageConfigPath, max - 1) }, 100); return } } getIframeUrl = () => { const { route, query } = queryString.parse(window.location.search) return route + (query ? '?' + query : '') } render() { const { width, height } = this.state const { isLockIframe } = this.props const stageStyle = { height: height + 'px', width: width + 'px' } let iframeSrc = this.getIframeUrl() return ( <div className='the-gui-content' style={stageStyle} ref={(el) => (this.$el = el)} > <BaseIframe getRef={(c) => (this.iframe = c)} src={iframeSrc} onLoad={this.onIframeLoad} onKeydown={this.onKeyDown} /> {isLockIframe && ( <TheStage style={stageStyle} onMouseMove={this.onStageMouseMove} onMouseLeave={this.onStageMouseLeave} onClick={this.onStageClick} /> )} </div> ) } } export default connect(({ guiEditor }: ConnectState) => ({ isIframeLoading: guiEditor.isIframeLoading, isInsertItemMode: guiEditor.isInsertItemMode, query: guiEditor.query, pageConfig: guiEditor.pageConfig, hoverComponentData: guiEditor.hoverComponentData, selectedComponentData: guiEditor.selectedComponentData, activeTab: guiEditor.activeTab, isLockIframe: guiEditor.isLockIframe, isDragging: guiEditor.isDragging, containerData: guiEditor.containerData }))(TheContent)
the_stack
import * as React from 'react'; import { LinearProgress } from '@material-ui/core'; import CloseIcon from '@material-ui/icons/Close'; import LaunchIcon from '@material-ui/icons/Launch'; import ErrorIcon from '@material-ui/icons/Error'; import UnknownIcon from '@material-ui/icons/Help'; import PendingIcon from '@material-ui/icons/Schedule'; import SkippedIcon from '@material-ui/icons/SkipNext'; import SuccessIcon from '@material-ui/icons/CheckCircle'; import CancelIcon from '@material-ui/icons/Cancel'; import StatusRunning from '../../icons/statusRunning'; import TerminatedIcon from '../../icons/statusTerminated'; import { DeployProgressState } from './DeploysProgress'; import DeployUtils from './DeployUtils'; import { KatibProgress } from './KatibProgress'; // From kubeflow/pipelines repo enum PipelineStatus { ERROR = 'Error', FAILED = 'Failed', PENDING = 'Pending', RUNNING = 'Running', SKIPPED = 'Skipped', SUCCEEDED = 'Succeeded', TERMINATING = 'Terminating', TERMINATED = 'Terminated', UNKNOWN = 'Unknown', } interface DeployProgress extends DeployProgressState { onRemove?: () => void; } export const DeployProgress: React.FunctionComponent<DeployProgress> = props => { const getSnapshotLink = (task: any) => { if (!task.result || !task.result.event) { return '#'; } const link = `${window.location.origin}/_/rok/buckets/${task.bucket}/files/${task.result.event.object}/versions/${task.result.event.version}`; return props.namespace ? `${link}?ns=${props.namespace}` : link; }; const getTaskLink = (task: any) => { const link = `${window.location.origin}/_/rok/buckets/${task.bucket}/tasks/${task.id}`; return props.namespace ? `${link}?ns=${props.namespace}` : link; }; const getUploadLink = (pipeline: any) => { // link: /_/pipeline/#/pipelines/details/<id> // id = uploadPipeline.pipeline.id if (!pipeline.pipeline || !pipeline.pipeline.pipelineid) { return '#'; } const link = `${window.location.origin}/_/pipeline/#/pipelines/details/${pipeline.pipeline.pipelineid}/version/${pipeline.pipeline.versionid}`; return props.namespace ? link.replace('#', `?ns=${props.namespace}#`) : link; }; const getRunLink = (run: any) => { // link: /_/pipeline/#/runs/details/<id> // id = runPipeline.id if (!run.id) { return '#'; } const link = `${window.location.origin}/_/pipeline/#/runs/details/${run.id}`; return props.namespace ? link.replace('#', `?ns=${props.namespace}#`) : link; }; const getRunText = (pipeline: any) => { switch (pipeline.status) { case null: case 'Running': return 'View'; case 'Terminating': case 'Failed': return pipeline.status as string; default: return 'Done'; } }; const getRunComponent = (pipeline: any) => { let title = 'Unknown status'; let IconComponent: any = UnknownIcon; let iconColor = '#5f6368'; switch (pipeline.status) { case PipelineStatus.ERROR: IconComponent = ErrorIcon; iconColor = DeployUtils.color.errorText; // title = 'Error'; break; case PipelineStatus.FAILED: IconComponent = ErrorIcon; iconColor = DeployUtils.color.errorText; // title = 'Failed'; break; case PipelineStatus.PENDING: IconComponent = PendingIcon; iconColor = DeployUtils.color.weak; // title = 'Pendig'; break; case PipelineStatus.RUNNING: IconComponent = StatusRunning; iconColor = DeployUtils.color.blue; // title = 'Running'; break; case PipelineStatus.TERMINATING: IconComponent = StatusRunning; iconColor = DeployUtils.color.blue; // title = 'Terminating'; break; case PipelineStatus.SKIPPED: IconComponent = SkippedIcon; // title = 'Skipped'; break; case PipelineStatus.SUCCEEDED: IconComponent = SuccessIcon; iconColor = DeployUtils.color.success; // title = 'Succeeded'; break; case PipelineStatus.TERMINATED: IconComponent = TerminatedIcon; iconColor = DeployUtils.color.terminated; // title = 'Terminated'; break; case PipelineStatus.UNKNOWN: break; default: console.error('pipeline status:', pipeline.status); } return ( <React.Fragment> {getRunText(pipeline)} <IconComponent style={{ color: iconColor, height: 18, width: 18 }} /> </React.Fragment> ); }; const getKatibKfpExperimentLink = (experimentId: string) => { // link: /_/pipeline/#/experiments/details/<ud> if (!experimentId) { return '#'; } const link = `${window.location.origin}/_/pipeline/#/experiments/details/${experimentId}`; return props.namespace ? link.replace('#', `?ns=${props.namespace}#`) : link; }; const getSnapshotTpl = () => { if (!props.task) { return ( <React.Fragment> Unknown status <UnknownIcon style={{ color: DeployUtils.color.terminated, height: 18, width: 18, }} /> </React.Fragment> ); } if (!['success', 'error', 'canceled'].includes(props.task.status)) { const progress = props.task.progress || 0; return ( <LinearProgress variant="determinate" color="primary" value={progress} /> ); } let getLink: (task: any) => string = () => '#'; let message = props.task.message; let IconComponent: any = UnknownIcon; let iconColor = DeployUtils.color.blue; switch (props.task.status) { case 'success': getLink = getSnapshotLink; message = 'Done'; IconComponent = LaunchIcon; break; case 'error': getLink = getTaskLink; IconComponent = ErrorIcon; iconColor = DeployUtils.color.errorText; break; case 'canceled': IconComponent = CancelIcon; getLink = getTaskLink; iconColor = DeployUtils.color.canceled; break; } return ( <React.Fragment> <a href={getLink(props.task)} target="_blank" rel="noopener noreferrer"> {message} <IconComponent style={{ color: iconColor, height: 18, width: 18 }} /> </a> </React.Fragment> ); }; let validationTpl; if (props.notebookValidation === true) { validationTpl = ( <React.Fragment> <SuccessIcon style={{ color: DeployUtils.color.success, height: 18, width: 18 }} /> </React.Fragment> ); } else if (props.notebookValidation === false) { validationTpl = ( <React.Fragment> <ErrorIcon style={{ color: DeployUtils.color.errorText, height: 18, width: 18 }} /> </React.Fragment> ); } else { validationTpl = <LinearProgress color="primary" />; } let compileTpl; if (props.compiledPath && props.compiledPath !== 'error') { compileTpl = ( <React.Fragment> <a onClick={_ => props.docManager.openOrReveal(props.compiledPath)}> Done <SuccessIcon style={{ color: DeployUtils.color.success, height: 18, width: 18 }} /> </a> </React.Fragment> ); } else if (props.compiledPath === 'error') { compileTpl = ( <React.Fragment> <ErrorIcon style={{ color: DeployUtils.color.errorText, height: 18, width: 18 }} /> </React.Fragment> ); } else { compileTpl = <LinearProgress color="primary" />; } let uploadTpl; if (props.pipeline) { uploadTpl = ( <React.Fragment> <a href={getUploadLink(props.pipeline)} target="_blank" rel="noopener noreferrer" > Done <LaunchIcon style={{ height: 18, width: 18 }} /> </a> </React.Fragment> ); } else if (props.pipeline === false) { uploadTpl = ( <React.Fragment> <ErrorIcon style={{ color: DeployUtils.color.errorText, height: 18, width: 18 }} /> </React.Fragment> ); } else { uploadTpl = <LinearProgress color="primary" />; } let runTpl; if (props.runPipeline) { runTpl = ( <React.Fragment> <a href={getRunLink(props.runPipeline)} target="_blank" rel="noopener noreferrer" > {getRunComponent(props.runPipeline)} </a> </React.Fragment> ); } else if (props.runPipeline == false) { runTpl = ( <React.Fragment> <ErrorIcon style={{ color: DeployUtils.color.errorText, height: 18, width: 18 }} /> </React.Fragment> ); } else { runTpl = <LinearProgress color="primary" />; } let katibKfpExpTpl; if (!props.katibKFPExperiment) { katibKfpExpTpl = <LinearProgress color="primary" />; } else if (props.katibKFPExperiment.id !== 'error') { katibKfpExpTpl = ( <React.Fragment> <a href={getKatibKfpExperimentLink(props.katibKFPExperiment.id)} target="_blank" rel="noopener noreferrer" > Done <LaunchIcon style={{ fontSize: '1rem' }} /> </a> </React.Fragment> ); } else { katibKfpExpTpl = ( <React.Fragment> <ErrorIcon style={{ color: DeployUtils.color.errorText, height: 18, width: 18 }} /> </React.Fragment> ); } return ( <div className="deploy-progress"> <div style={{ justifyContent: 'flex-end', textAlign: 'right', paddingRight: '4px', height: '1rem', }} > <CloseIcon style={{ fontSize: '1rem', cursor: 'pointer' }} onClick={_ => props.onRemove()} /> </div> {props.showValidationProgress ? ( <div className="deploy-progress-row"> <div className="deploy-progress-label">Validating notebook...</div> <div className="deploy-progress-value"> {validationTpl} {DeployUtils.getWarningBadge( 'Validation Warnings', props.validationWarnings, )} </div> </div> ) : null} {props.showSnapshotProgress ? ( <div className="deploy-progress-row"> <div className="deploy-progress-label">Taking snapshot...</div> <div className="deploy-progress-value"> {getSnapshotTpl()}{' '} {DeployUtils.getWarningBadge( 'Snapshot Warnings', props.snapshotWarnings, )} </div> </div> ) : null} {props.showCompileProgress ? ( <div className="deploy-progress-row"> <div className="deploy-progress-label">Compiling notebook...</div> <div className="deploy-progress-value"> {compileTpl} {DeployUtils.getWarningBadge( 'Compile Warnings', props.compileWarnings, )} </div> </div> ) : null} {props.showUploadProgress ? ( <div className="deploy-progress-row"> <div className="deploy-progress-label">Uploading pipeline...</div> <div className="deploy-progress-value"> {uploadTpl} {DeployUtils.getWarningBadge( 'Upload Warnings', props.uploadWarnings, )} </div> </div> ) : null} {props.showRunProgress ? ( <div className="deploy-progress-row"> <div className="deploy-progress-label">Running pipeline...</div> <div className="deploy-progress-value"> {runTpl} {DeployUtils.getWarningBadge('Run Warnings', props.runWarnings)} </div> </div> ) : null} {props.showKatibKFPExperiment ? ( <div className="deploy-progress-row"> <div className="deploy-progress-label"> Creating KFP experiment... </div> <div className="deploy-progress-value">{katibKfpExpTpl}</div> </div> ) : null} {props.showKatibProgress ? ( <KatibProgress experiment={props.katib} /> ) : null} </div> ); };
the_stack
import { Application, Contract, Organization, Key, Wallet, Vault as ProvideVault, BaselineResponse, Object, Mapping, Workflow, Workstep, } from "@provide/types"; import { Ident, identClientFactory, nchainClientFactory, vaultClientFactory, baselineClientFactory } from "provide-js"; import { Uuid, TokenStr } from "../models/common"; import { AuthParams } from "../models/auth-params"; import * as jwt from "jsonwebtoken"; import { AuthContext } from "./auth-context"; import { AccessToken } from "./access-token"; import { NatsClientFacade as NatsClient } from "./nats-listener"; import { Token as _Token } from "../models/token"; import { ServerUser as _User, User } from "../models/user"; export interface ProvideClient { readonly user: User; readonly userRefreshToken: TokenStr; natsClient: NatsClient | null; logout(): Promise<void>; getWorkgroups(): Promise<Application[]>; connectNatsClient(): Promise<void>; // eslint-disable-next-line no-unused-vars sendCreateProtocolMessage(message: Object): Promise<BaselineResponse>; // eslint-disable-next-line no-unused-vars sendUpdateProtocolMessage(baselineID: string, message: Object): Promise<BaselineResponse>; // eslint-disable-next-line no-unused-vars acceptWorkgroupInvitation(inviteToken: TokenStr, organizationId: Uuid): Promise<void>; // eslint-disable-next-line no-unused-vars getWorkgroupMappings(appId: string): Promise<Mapping[]>; // eslint-disable-next-line no-unused-vars getWorkflows(appId: string): Promise<Workflow[]>; // eslint-disable-next-line no-unused-vars createWorkflow(params: any): Promise<Workflow>; // eslint-disable-next-line no-unused-vars getWorksteps(workflowId: string): Promise<Workstep[]>; // eslint-disable-next-line no-unused-vars getWorkstepDetails(workflowId: string, workstepId: string): Promise<Workstep>; // eslint-disable-next-line no-unused-vars createWorkstep(workflowId: string, params: any): Promise<Workstep>; // eslint-disable-next-line no-unused-vars createWorkgroupMapping(params: any): Promise<Mapping>; } class ProvideClientImpl implements ProvideClient { private _user: User; private _userAuthContext: AuthContext; private _appAuthContext: AuthContext; private _orgAuthContext: AuthContext; private _NatsClient: NatsClient; private scheme = "https"; private host = "0.pgrok.provide.services:37517"; constructor(user: User, userAuthContext: AuthContext) { this._user = user; this._userAuthContext = userAuthContext; } get user(): User { return this._user; } get userRefreshToken(): TokenStr { return this._userAuthContext.refreshToken; } get natsClient(): NatsClient { return this._NatsClient; } logout(): Promise<void> { // TODO: Maybe must call deleteToken? this._user = null; this._userAuthContext = null; return Promise.resolve(); } async authorizeOrganization(organizationId: Uuid): Promise<void> { await this._userAuthContext.execute(async (accessToken) => { const identService = identClientFactory(accessToken); const params = { scope: "offline_access", organization_id: organizationId, }; await identService.createToken(params).then((token) => { const expiresIn = parseInt(token["expiresIn"]); const accessToken = new AccessToken(token.id, token.accessToken, expiresIn); this._orgAuthContext = new AuthContext(token.refreshToken, accessToken); }); }); } async authorizeApplication(workgroupAndApplicationId: Uuid): Promise<void> { await this._userAuthContext.execute((accessToken) => { const identService = identClientFactory(accessToken); const params = { scope: "offline_access", application_id: workgroupAndApplicationId, }; return identService.createToken(params).then((token) => { const expiresIn = parseInt(token["expiresIn"]); const accessToken = new AccessToken(token.id, token.accessToken, expiresIn); this._appAuthContext = new AuthContext(token.refreshToken, accessToken); }); }); } async getWorkgroups(): Promise<Application[]> { const retVal = await this._userAuthContext.get((accessToken) => { const identService = identClientFactory(accessToken); //TODO: Change to baselineSerive.fetchWorkgroups() return identService.fetchApplications({}); }); return retVal.results; } async getWorkgroupMappings(appId: string): Promise<Mapping[]> { var orgID = await this.getOrgID(); await this.authorizeOrganization(orgID); const retVal = await this._orgAuthContext.get(async (accessToken) => { const baselineService = baselineClientFactory(accessToken, this.scheme, this.host); return await baselineService.fetchMappings({ workgroup_id: appId }); }); return retVal["results"]; } async updateWorkgroupMapping(appId: string, mappingId: string, params: Object): Promise<void> { var orgID = await this.getOrgID(); await this.authorizeOrganization(orgID); await this._orgAuthContext.get(async (accessToken) => { const baselineService = baselineClientFactory(accessToken, this.scheme, this.host); return await baselineService.updateMapping(mappingId, params); }); } async createWorkgroupMapping(params: any): Promise<Mapping> { var orgID = await this.getOrgID(); await this.authorizeOrganization(orgID); const retval = await this._orgAuthContext.get(async (accessToken) => { const baselineService = baselineClientFactory(accessToken, this.scheme, this.host); return await baselineService.createMapping(params); }); return retval; } async sendCreateProtocolMessage(message: Object): Promise<BaselineResponse> { var orgID = await this.getOrgID(); await this.authorizeOrganization(orgID); const retVal = await this._orgAuthContext.get(async (accessToken) => { const baselineService = baselineClientFactory(accessToken, this.scheme, this.host); return await baselineService.createObject(message); }); return retVal; } async sendUpdateProtocolMessage(baselineID: string, message: Object): Promise<BaselineResponse> { var orgID = await this.getOrgID(); await this.authorizeOrganization(orgID); const retVal = await this._orgAuthContext.get(async (accessToken) => { const baselineService = baselineClientFactory(accessToken, this.scheme, this.host); return await baselineService.updateObject(baselineID, message); }); return retVal; } async getWorkflows(appId: string): Promise<Workflow[]> { var orgID = await this.getOrgID(); await this.authorizeOrganization(orgID); const retVal = await this._orgAuthContext.get(async (accessToken) => { const baselineService = baselineClientFactory(accessToken, this.scheme, this.host); return await baselineService.fetchWorkflows({ workgroup_id: appId, filter_instances: true }); }); return retVal["results"]; } async createWorkflow(params: any): Promise<Workflow> { var orgID = await this.getOrgID(); await this.authorizeOrganization(orgID); const retVal = await this._orgAuthContext.get(async (accessToken) => { const baselineService = baselineClientFactory(accessToken, this.scheme, this.host); return await baselineService.createWorkflow(params); }); return retVal; } async getWorksteps(workflowId: string): Promise<Workstep[]> { var orgID = await this.getOrgID(); await this.authorizeOrganization(orgID); const retVal = await this._orgAuthContext.get(async (accessToken) => { const baselineService = baselineClientFactory(accessToken, this.scheme, this.host); return await baselineService.fetchWorksteps(workflowId); }); return retVal["results"]; } async getWorkstepDetails(workflowId: string, workstepId: string): Promise<Workstep> { var orgID = await this.getOrgID(); await this.authorizeOrganization(orgID); const retVal = await this._orgAuthContext.get(async (accessToken) => { const baselineService = baselineClientFactory(accessToken, this.scheme, this.host); return await baselineService.fetchWorkstepDetails(workflowId, workstepId); }); return retVal; } async createWorkstep(workflowId: string, params: any): Promise<Workstep> { var orgID = await this.getOrgID(); await this.authorizeOrganization(orgID); const retVal = await this._orgAuthContext.get(async (accessToken) => { const baselineService = baselineClientFactory(accessToken, this.scheme, this.host); return await baselineService.createWorkstep(workflowId, params); }); return retVal; } async connectNatsClient(): Promise<void> { var orgID = await this.getOrgID(); await this.authorizeOrganization(orgID); await this._orgAuthContext.get(async (accessToken) => { this._NatsClient = new NatsClient(accessToken); return await this._NatsClient.connect(); }); return; } private async getOrgID(): Promise<string> { const organization = await this._userAuthContext.get(async (accessToken) => { const identService = identClientFactory(accessToken); return await identService.fetchOrganizations({}); }); return organization.results[0].id; } async createWallet(): Promise<Wallet> { this.guardNotNullAppAuthContext(); const retVal = await this._appAuthContext.get((accessToken) => { const nchainService = nchainClientFactory(accessToken); const params = { purpose: 44, }; return nchainService.createWallet(params); }); return retVal; } async getFirstOrCreateVault(organizationId: Uuid): Promise<ProvideVault> { const vaults = await this.getVaults(organizationId); if (vaults.length > 0) { return vaults[0]; } const newVault = await this.createVault(organizationId); return newVault; } async getVaults(organizationId: Uuid): Promise<ProvideVault[]> { this.guardNotNullOrgAuthContext(); const retVal = await this._orgAuthContext.get((accessToken) => { const vaultService = vaultClientFactory(accessToken); const params = { organization_id: organizationId, }; return vaultService.fetchVaults(params); }); return retVal.results; } async createVault(organizationId: Uuid): Promise<ProvideVault> { this.guardNotNullOrgAuthContext(); const retVal = await this._orgAuthContext.get((accessToken) => { const vaultService = vaultClientFactory(accessToken); const params = { name: `vault for organization: ${organizationId}`, description: `identity/signing keystore for organization: ${organizationId}`, }; return vaultService.createVault(params); }); return retVal; } async getFirstOrCreateVaultKey(vaultId: Uuid, spec: string, organizationId: Uuid): Promise<Key> { const keys = await this.getVaultKeys(vaultId, spec); if (keys.length > 0) { return keys[0]; } const newKey = await this.createVaultKey(vaultId, spec, organizationId); return newKey; } // TODO: Maybe it always only one. async getVaultKeys(vaultId: Uuid, spec: string): Promise<Key[]> { this.guardNotNullOrgAuthContext(); const retVal = await this._orgAuthContext.get((accessToken) => { const vaultService = vaultClientFactory(accessToken); const params = { spec: spec, }; return vaultService.fetchVaultKeys(vaultId, params); }); return retVal.results; } async createVaultKey(vaultId: Uuid, spec: string, organizationId: Uuid): Promise<Key> { this.guardNotNullOrgAuthContext(); const retVal = await this._orgAuthContext.get((accessToken) => { const vaultService = vaultClientFactory(accessToken); const params = { name: `${spec} key organization: ${organizationId}`, description: `${spec} key organization: ${organizationId}`, spec: spec, type: "asymmetric", usage: "sign/verify", }; return vaultService.createVaultKey(vaultId, params); }); return retVal; } async getContracts(contractType: string): Promise<Contract[]> { this.guardNotNullAppAuthContext(); const retVal = await this._appAuthContext.get((accessToken) => { const nchainService = nchainClientFactory(accessToken); const params = { type: contractType, }; return nchainService.fetchContracts(params); }); return retVal.results; } async getOrCreateApplicationOrganization( workgroupAndApplicationId: Uuid, organizationId: Uuid ): Promise<Organization> { const applicationOrganizations = await this.getApplicationOrganizations(workgroupAndApplicationId, organizationId); // NOTE: I don't know why, but we must find organizationId... see RegisterWorkgroupOrganization in \provide-cli\cmd\common\baseline.go let applicationOrganization = applicationOrganizations.find((x) => x.id === organizationId); if (applicationOrganization) { return applicationOrganization; } applicationOrganization = await this.createApplicationOrganization(workgroupAndApplicationId, organizationId); return applicationOrganization; } async createOrGetApplicationOrganization( workgroupAndApplicationId: Uuid, organizationId: Uuid ): Promise<Organization> { try { const applicationOrganization = await this.createApplicationOrganization( workgroupAndApplicationId, organizationId ); return applicationOrganization; } catch { const applicationOrganizations = await this.getApplicationOrganizations( workgroupAndApplicationId, organizationId ); let applicationOrganization = applicationOrganizations.find((x) => x.id === organizationId); if (applicationOrganization) { return applicationOrganization; } throw "Organization not associated with workgroup"; } } async createApplicationOrganization(workgroupAndApplicationId: Uuid, organizationId: Uuid): Promise<Organization> { this.guardNotNullAppAuthContext(); const retVal = await this._appAuthContext.get((accessToken) => { const identService = identClientFactory(accessToken); const params = { organization_id: organizationId, }; return identService.createApplicationOrganization(workgroupAndApplicationId, params); }); return retVal; } async getApplicationOrganizations(workgroupAndApplicationId: Uuid, organizationId: Uuid): Promise<Organization[]> { this.guardNotNullAppAuthContext(); const retVal = await this._appAuthContext.get((accessToken) => { const identService = identClientFactory(accessToken); const params = { organization_id: organizationId, }; return identService.fetchApplicationOrganizations(workgroupAndApplicationId, params); }); return retVal.results; } async acceptWorkgroupInvitation(inviteToken: TokenStr, organizationId: Uuid): Promise<void> { // TODO: requirePublicJWTVerifiers() from GO const inviteClaims = jwt.decode(inviteToken) as { [key: string]: any }; if (!inviteClaims) { throw "Can't parse invite token"; } const workgroupAndApplicationId = inviteClaims.baseline.workgroup_id as Uuid; await this.authorizeOrganization(organizationId); await this.authorizeApplication(workgroupAndApplicationId); // NOTE: I don't know for what, see: func authorizeApplicationContext() in \provide-cli\cmd\baseline\workgroups\workgroup_init.go await this.createWallet(); const vault = await this.getFirstOrCreateVault(organizationId); /* NOTE: START - Where used? I don't know */ // eslint-disable-next-line no-unused-vars const babyJubJubKey = await this.getFirstOrCreateVaultKey(vault.id, "babyJubJub", organizationId); // eslint-disable-next-line no-unused-vars const secp256k1Key = await this.getFirstOrCreateVaultKey(vault.id, "secp256k1", organizationId); // eslint-disable-next-line no-unused-vars const hdwalletKey = await this.getFirstOrCreateVaultKey(vault.id, "BIP39", organizationId); // eslint-disable-next-line no-unused-vars const rsa4096Key = await this.getFirstOrCreateVaultKey(vault.id, "RSA-4096", organizationId); /* NOTE: END */ // common.RegisterWorkgroupOrganization(common.ApplicationID) const contracts = await this.getContracts("organization-registry"); if (!contracts.length) { throw "Failed to initialize registry contract"; } // NOTE: It's look like instance of applicationOrganization not required // eslint-disable-next-line no-unused-vars // const applicationOrganization = await this.getOrCreateApplicationOrganization( // workgroupAndApplicationId, // organizationId // ); // eslint-disable-next-line no-unused-vars const applicationOrganization = await this.createOrGetApplicationOrganization( workgroupAndApplicationId, organizationId ); // token := common.RequireAPIToken() // baseline.CreateWorkgroup(token, map[string]interface{}{ // "token": jwt, // }) } private guardNotNullAppAuthContext() { if (!this._appAuthContext) { throw "No application authorization"; } } private guardNotNullOrgAuthContext() { if (!this._orgAuthContext) { throw "No organization authorization"; } } } export function authenticateStub(authParams: AuthParams): Promise<ProvideClient> { const user: User = { id: "asdfgasdfgsdfgsdfg", email: authParams.email, name: "User Name " + authParams.password, }; const userAccessToken = new AccessToken("id", "access_token", 86400); const userAuthContext = new AuthContext("refresh_token", userAccessToken); return Promise.resolve(new ProvideClientImpl(user, userAuthContext)); } export async function authenticate(authParams: AuthParams): Promise<ProvideClient> { const params = Object.assign( { scope: "offline_access", }, authParams ); const response = await Ident.authenticate(params); let tokenResponse = response.token as any as _Token; let userResponse = response.user as any as _User; const user: User = userResponse as User; const userAccessToken = new AccessToken(tokenResponse.id, tokenResponse.access_token, tokenResponse.expires_in); const userAuthContext = new AuthContext(tokenResponse.refresh_token, userAccessToken); return new ProvideClientImpl(user, userAuthContext); } // eslint-disable-next-line no-unused-vars export function restoreStub(refreshToken: TokenStr, user: User): Promise<ProvideClient> { const fakeauthParams = { email: "email", password: "password" }; return authenticateStub(fakeauthParams); } export async function restore(refreshToken: TokenStr, user: User): Promise<ProvideClient> { const userAuthContext = new AuthContext(refreshToken); await userAuthContext.refresh(); return new ProvideClientImpl(user, userAuthContext); }
the_stack
* @file index.ts * * The main LMLayerWorker class, the top-level class within the Web Worker. * The LMLayerWorker handles the keyboard/worker communication * protocol, delegating prediction requests to the language * model implementations. */ /// <reference path="../message.d.ts" /> /// <reference path="models/dummy-model.ts" /> /// <reference path="../node_modules/@keymanapp/models-wordbreakers/src/index.ts" /> /// <reference path="./model-compositor.ts" /> /** * Encapsulates all the state required for the LMLayer's worker thread. * * Implements the state pattern. There are three states: * * - `unconfigured` (initial state before configuration) * - `modelless` (state without model loaded) * - `ready` (state with model loaded, accepts prediction requests) * * Transitions are initiated by valid messages. Invalid * messages are errors, and do not lead to transitions. * * +-------------+ load +---------+ * config | |----------->| | * +-------> modelless + + ready +---+ * | |<-----------| | | * +-------------+ unload +----^----+ | predict * | | * +--------+ * * The model and the configuration are ONLY relevant in the `ready` state; * as such, they are NOT direct properties of the LMLayerWorker. */ class LMLayerWorker { /** * State pattern. This object handles onMessage(). * handleMessage() can transition to a different state, if * necessary. */ private state: LMLayerWorkerState; /** * By default, it's self.postMessage(), but can be overridden * so that this can be tested **outside of a Worker**. */ private _postMessage: PostMessage; /** * By default, it's self.importScripts(), but can be overridden * so that this can be tested **outside of a Worker**. * * To function properly, self.importScripts() must be bound to self * before being stored here, else it will fail. */ private _importScripts: ImportScripts; private self: any; private _platformCapabilities: Capabilities; private _hostURL: string; private _currentModelSource: ModelSourceSpec; constructor(options = { importScripts: null, postMessage: null }) { this._postMessage = options.postMessage || postMessage; this._importScripts = options.importScripts || importScripts; this.setupConfigState(); } public error(message: string, error?: any) { // error isn't a fan of being cloned across the worker boundary. this.cast('error', { log: message, error: (error && error.stack) ? error.stack : undefined }); } /** * A function that can be set as self.onmessage (the Worker * message handler). * NOTE! You must bind it to a specific instance, e.g.: * * // Do this! * self.onmessage = worker.onMessage.bind(worker); * * Incorrect: * * // Don't do this! * self.onmessage = worker.onMessage; * * See: .install(); */ onMessage(event: MessageEvent) { const {message} = event.data; // Ensure the message is tagged with a valid message tag. if (!message) { throw new Error(`Missing required 'message' property: ${event.data}`) } // If last load was for this exact model file, squash the message. // (Though not if we've had an unload since.) let im = event.data as IncomingMessage; if(im.message == 'load') { let data = im as LoadMessage; let duplicated = false; if(this._currentModelSource && data.source.type == this._currentModelSource.type) { if(data.source.type == 'file' && data.source.file == (this._currentModelSource as ModelFile).file) { duplicated = true; } else if(data.source.type == 'raw' && data.source.code == (this._currentModelSource as ModelEval).code) { duplicated = true; } } if(duplicated) { // Some JS implementations don't allow web workers access to the console. if(typeof console !== 'undefined') { console.warn("Duplicate model load message detected - squashing!"); } return; } else { this._currentModelSource = data.source; } } else if(im.message == 'unload') { this._currentModelSource = null; } // We got a message! Delegate to the current state. this.state.handleMessage(im); } /** * Sends back a message structured according to the protocol. * @param message A message type. * @param payload The message's payload. Can have any properties, except 'message'. */ private cast(message: OutgoingMessageKind, payload: Object) { // Chrome raises "TypeError: invalid invocation" if postMessage is called // with any non-default value for `this`, i.e., this won't work: // // this._postMessage({ foo: 'bar' }); // // Yank it postMessage() off of `this` so that it's called on the // "global" context, and everything works again. let postMessage = this._postMessage; postMessage({ message, ...payload }); } /** * Loads a model by executing the given source code, and * passing in the appropriate configuration. * * @param desc Type of the model to instantiate and its parameters. * @param capabilities Capabilities on offer from the keyboard. */ public loadModel(model: LexicalModel) { // TODO: pass _platformConfig to model so that it can self-configure to the platform, // returning a Configuration. /* Note that this function is typically called from within an `importScripts` call. * For meaningful error messages to be successfully logged, we must catch what we can here * and pass a message to outside the worker - otherwise a generic "Script error" occurs. */ try { let configuration = model.configure(this._platformCapabilities); // Handle deprecations. if(!configuration.leftContextCodePoints) { configuration.leftContextCodePoints = configuration.leftContextCodeUnits; } if(!configuration.rightContextCodePoints) { configuration.rightContextCodePoints = configuration.rightContextCodeUnits; } // Set reasonable defaults for the configuration. if (!configuration.leftContextCodePoints) { configuration.leftContextCodePoints = this._platformCapabilities.maxLeftContextCodePoints; } if (!configuration.rightContextCodePoints) { configuration.rightContextCodePoints = this._platformCapabilities.maxRightContextCodePoints || 0; } // Ensures that default casing rules exist for custom models that request casing rules but don't define them. if(model.languageUsesCasing && !model.applyCasing) { model.applyCasing = models.defaultApplyCasing; } let compositor = this.transitionToReadyState(model); // This test allows models to directly specify the property without it being auto-overridden by // this default. if(configuration.wordbreaksAfterSuggestions === undefined) { configuration.wordbreaksAfterSuggestions = (compositor.punctuation.insertAfterWord != ''); } this.cast('ready', { configuration }); } catch (err) { this.error("loadModel failed!", err); } } private loadModelFile(url: string) { // The self/global WebWorker method, allowing us to directly import another script file into WebWorker scope. // If built correctly, the model's script file will auto-register the model with loadModel() above. try { this._importScripts(url); } catch (err) { this.error("Error occurred when attempting to load dictionary", err); } } public unloadModel() { // Right now, this seems sufficient to clear out the old model. // The only existing reference to a loaded model is held by // transitionToReadyState's `handleMessage` closure. (The `model` var) this.transitionToLoadingState(); } /** * Sets the initial state, i.e., `unconfigured`. * This state only handles `config` messages, and will * transition to the `modelless` state once it receives * the config data from the host platform. */ private setupConfigState() { this.state = { name: 'unconfigured', handleMessage: (payload) => { // ... that message must have been 'config'! if (payload.message !== 'config') { throw new Error(`invalid message; expected 'config' but got ${payload.message}`); } this._platformCapabilities = payload.capabilities; this.transitionToLoadingState(); } } } /** * Sets the model-loading state, i.e., `modelless`. * This state only handles `load` messages, and will * transition to the `ready` state once it receives a model * description and capabilities. */ private transitionToLoadingState() { let _this = this; this.state = { name: 'modelless', handleMessage: (payload) => { // ...that message must have been 'load'! if (payload.message !== 'load') { throw new Error(`invalid message; expected 'load' but got ${payload.message}`); } // TODO: validate configuration? if(payload.source.type == 'file') { _this.loadModelFile(payload.source.file); } else { // Creates a closure capturing all top-level names that the model must be able to reference. // `eval` runs by scope rules; our virtualized worker needs a special scope for this to work. // // Reference: https://stackoverflow.com/a/40108685 // Note that we don't need `this`, but we do need the namespaces seen below. let code = payload.source.code; let evalInContext = function(LMLayerWorker, models, correction, wordBreakers) { eval(code); } evalInContext(_this, models, correction, wordBreakers); } } }; } /** * Sets the state to `ready`. This requires a * fully-instantiated model. The `ready` state only responds * to `predict` message, and is an accepting state. * * @param model The loaded language model. */ private transitionToReadyState(model: LexicalModel): ModelCompositor { let compositor = new ModelCompositor(model); this.state = { name: 'ready', handleMessage: (payload) => { switch(payload.message) { case 'predict': var {transform, context} = payload; var suggestions = compositor.predict(transform, context); // Now that the suggestions are ready, send them out! this.cast('suggestions', { token: payload.token, suggestions: suggestions }); break; case 'wordbreak': let brokenWord = models.wordbreak(model.wordbreaker || wordBreakers.default, payload.context); this.cast('currentword', { token: payload.token, word: brokenWord }); break; case 'unload': this.unloadModel(); break; case 'accept': var {suggestion, context, postTransform} = payload; var reversion = compositor.acceptSuggestion(suggestion, context, postTransform); this.cast('postaccept', { token: payload.token, reversion: reversion }); break; case 'revert': var {reversion, context} = payload; var suggestions: Suggestion[] = compositor.applyReversion(reversion, context); this.cast('postrevert', { token: payload.token, suggestions: suggestions }); break; case 'reset-context': var {context} = payload; compositor.resetContext(context); break; default: throw new Error(`invalid message; expected one of {'predict', 'wordbreak', 'accept', 'revert', 'reset-context', 'unload'} but got ${payload.message}`); } }, compositor: compositor }; return compositor; } /** * Creates a new instance of the LMLayerWorker, and installs all its * functions within the provided Worker global scope. * * In production, this is called within the Worker's scope as: * * LMLayerWorker.install(self); * * ...and this will setup onmessage and postMessage() appropriately. * * During testing, this method is useful to mock an entire global scope, * * var fakeScope = { postMessage: ... }; * LMLayerWorker.install(fakeScope); * // now we can spy on methods in fakeScope! * * @param scope A global scope to install upon. */ static install(scope: DedicatedWorkerGlobalScope): LMLayerWorker { let worker = new LMLayerWorker({ postMessage: scope.postMessage, importScripts: scope.importScripts.bind(scope) }); scope.onmessage = worker.onMessage.bind(worker); worker.self = scope; // Ensures that the worker instance is accessible for loaded model scripts. // Assists unit-testing. scope['LMLayerWorker'] = worker; scope['models'] = models; scope['correction'] = correction; scope['wordBreakers'] = wordBreakers; return worker; } } // Let LMLayerWorker be available both in the browser and in Node. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { module.exports = LMLayerWorker; module.exports['correction'] = correction; module.exports['models'] = models; module.exports['wordBreakers'] = wordBreakers; /// XXX: export the ModelCompositor for testing. module.exports['ModelCompositor'] = ModelCompositor; } else if (typeof self !== 'undefined' && 'postMessage' in self) { // Automatically install if we're in a Web Worker. LMLayerWorker.install(self as any); // really, 'as typeof globalThis', but we're currently getting TS errors from use of that. } else { //@ts-ignore window.LMLayerWorker = LMLayerWorker; }
the_stack
import * as net from 'net' import * as crypto from 'crypto' import * as childProcess from 'child_process' import * as path from 'path' import * as fs from 'fs' import * as os from 'os' import * as _ from 'lodash' import * as url from 'url' import * as qs from 'querystring' import { mapYcmCompletionsToLanguageServerCompletions, mapYcmDiagnosticToLanguageServerDiagnostic, crossPlatformBufferToString, logger, crossPlatformUri, mapYcmTypeToHover, mapYcmLocationToLocation, mapYcmDocToHover } from './utils' import { IPCMessageReader, IPCMessageWriter, createConnection, IConnection, TextDocumentSyncKind, TextDocuments, TextDocument, Diagnostic, DiagnosticSeverity, InitializeParams, InitializeResult, TextDocumentPositionParams, CompletionItem, CompletionItemKind, Position, Location, RemoteWindow, MessageActionItem } from 'vscode-languageserver' import YcmRequest from './ycmRequest' export default class Ycm { private port: number private hmacSecret: Buffer private process: childProcess.ChildProcess private workingDir: string private window: RemoteWindow private settings: Settings private constructor(settings: Settings) { this.settings = settings } private findUnusedPort(): Promise<number> { return new Promise<number>((resolve, reject) => { const server = net.createServer() server.listen(0, () => { resolve((server.address() as net.AddressInfo).port) server.close() }) server.on('error', (err) => reject(err)) }) } private readDefaultOptions() { return new Promise<any>((resolve, reject) => { fs.readFile(path.resolve(this.settings.ycmd.path, 'ycmd', 'default_settings.json'), {encoding: 'utf8'}, (err, data) => { if (err) { fs.readFile(this.settings.ycmd.path, {encoding: 'utf8'}, (err, data) => { if (err) reject(err) else resolve(JSON.parse(data)) }) } else { resolve(JSON.parse(data)) } }) }) } private generateRandomSecret(): Buffer { return crypto.randomBytes(16) } private processData([unusedPort, hmac, options]: [number, Buffer, any]): Promise<string> { this.port = unusedPort this.hmacSecret = hmac options.hmac_secret = this.hmacSecret.toString('base64') options.global_ycm_extra_conf = this.settings.ycmd.global_extra_config options.confirm_extra_conf = this.settings.ycmd.confirm_extra_conf options.extra_conf_globlist = [] options.rustSrcPath = '' const optionsFile = path.resolve(os.tmpdir(), `VSCodeYcmOptions-${Date.now()}`) logger(`processData: ${JSON.stringify(options)}`) return new Promise<string>((resolve, reject) => { fs.writeFile(optionsFile, JSON.stringify(options), {encoding: 'utf8'}, (err) => { if (err) reject(err) else resolve(optionsFile) }) }) } private _start(optionsFile): Promise<childProcess.ChildProcess> { return new Promise<childProcess.ChildProcess>((resolve, reject) => { let cmd = this.settings.ycmd.python let args = [ path.resolve(this.settings.ycmd.path, 'ycmd'), `--port=${this.port}`, `--options_file=${optionsFile}`, `--idle_suicide_seconds=600` ] if (process.platform === 'win32') { args = args.map(it => `"${it.replace(/"/g, '\\"')}"`) cmd = `"${cmd.replace(/"/g, '\\"')}"` args.unshift(cmd) args = ['/s', '/d', '/c', `"${args.join(' ')}"`] cmd = 'cmd.exe' } const options = { windowsVerbatimArguments: true, cwd: this.workingDir, env: process.env } logger('_start', args) const cp = childProcess.spawn(cmd, args, options) logger('_start', `process spawn success ${cp.pid}`) cp.stdout.on('data', (data: Buffer) => logger(`ycm stdout`, crossPlatformBufferToString(data))) cp.stderr.on('data', (data: Buffer) => logger(`ycm stderr`, crossPlatformBufferToString(data))) cp.on('error', (err) => { logger('_start error', err) }) cp.on('exit', (code) => { logger('_start exit', code) this.process = null switch (code) { case 3: reject(new Error('Unexpected error while loading the YCM core library.')) case 4: reject(new Error('YCM core library not detected; you need to compile YCM before using it. Follow the instructions in the documentation.')) case 5: reject(new Error('YCM core library compiled for Python 3 but loaded in Python 2. Set the Python Executable config to a Python 3 interpreter path.')) case 6: reject(new Error('YCM core library compiled for Python 2 but loaded in Python 3. Set the Python Executable config to a Python 2 interpreter path.')) case 7: reject(new Error('YCM core library too old; PLEASE RECOMPILE by running the install.py script. See the documentation for more details.')) } }) setTimeout(() => resolve(cp), 1000) }) } private static async start(workingDir: string, settings: Settings, window: RemoteWindow): Promise<Ycm> { try { const ycm = new Ycm(settings) ycm.workingDir = workingDir ycm.window = window const data = await Promise.all<any>([ycm.findUnusedPort(), ycm.generateRandomSecret(), ycm.readDefaultOptions()]) as [number, Buffer, any] logger('start', `unused port: ${data[0]}`) logger('start', `random secret: ${data[1].toString('hex')}`) logger('start', `default options: ${JSON.stringify(data[2])}`) const optionsFile = await ycm.processData(data) logger('start', `optionsFile: ${optionsFile}`) ycm.process = await ycm._start(optionsFile) logger('start', `ycm started: ${ycm.process.pid}`) return ycm } catch (err) { throw err } } private static Instance: Ycm private static Initializing = false public static async getInstance(workingDir: string, settings: Settings, window: RemoteWindow): Promise<Ycm> { if (Ycm.Initializing) return new Promise<Ycm>((resolve, reject) => { logger('getInstance', 'ycm is initializing, delay 200ms...') setTimeout(() => resolve(Ycm.getInstance(workingDir, settings, window)), 200) }) if (!Ycm.Instance || Ycm.Instance.workingDir !== workingDir || !_.isEqual(Ycm.Instance.settings, settings) || !Ycm.Instance.process) { logger('getInstance', `ycm is restarting`) if (!!Ycm.Instance) await Ycm.Instance.reset() try { Ycm.Initializing = true Ycm.Instance = await Ycm.start(workingDir, settings, window) } catch (err) { throw err } finally { Ycm.Initializing = false } } return Ycm.Instance } public static reset() { if (!!Ycm.Instance) { Ycm.Instance.reset() } } public async reset() { if (!!this.process) { try { const request = this.buildRequest(null) await request.request('shutdown') } catch (e) { logger('reset', e) } this.process = null this.port = null this.hmacSecret = null } } private buildRequest(currentDocument: string, position: Position = null, documents: TextDocuments = null, event: string = null) { return new YcmRequest(this.window, this.port, this.hmacSecret, this.workingDir, currentDocument, position, documents, event) } private runCompleterCommand(documentUri: string, position: Position, documents: TextDocuments, command: string) { return this.buildRequest(documentUri, position, documents, command).isCommand().request() } private eventNotification(documentUri: string, position: Position, documents: TextDocuments, event: string) { return this.buildRequest(documentUri, position, documents, event).request() } public async getReady(documentUri: string, documents: TextDocuments) { const response = await this.eventNotification(documentUri, null, documents, 'BufferVisit') logger(`getReady`, JSON.stringify(response)) } public async completion(documentUri: string, position: Position, documents: TextDocuments): Promise<CompletionItem[]> { const request = this.buildRequest(documentUri, position, documents) const response = await request.request('completions') const completions = response['completions'] as YcmCompletionItem[] const res = mapYcmCompletionsToLanguageServerCompletions(completions) logger(`completion`, `ycm responsed ${res.length} items`) return res } public async getType(documentUri: string, position: Position, documents: TextDocuments, imprecise: boolean = false) { const type = await this.runCompleterCommand(documentUri, position, documents, imprecise ? 'GetTypeImprecise' : 'GetType') as YcmGetTypeResponse logger('getType', JSON.stringify(type)) return mapYcmTypeToHover(type, documents.get(documentUri).languageId) } public async goTo(documentUri: string, position: Position, documents: TextDocuments) { const definition = await this.runCompleterCommand(documentUri, position, documents, 'GoTo') logger('goTo', JSON.stringify(definition)) return mapYcmLocationToLocation(definition as YcmLocation) } public async getExactMatchingCompletion(documentUri, position, documents) { let currDoc = documents.get(documentUri) let currDocString = currDoc.getText() let currOffset = currDoc.offsetAt(position) let nameStart = currOffset // get the current identifier while (currDocString[currOffset].match(/[A-Z|a-z|0-9|_]/)) currOffset++ while (currDocString[nameStart].match(/[A-Z|a-z|0-9|_]/)) nameStart-- let identifierName = currDocString.slice(nameStart + 1, currOffset) // find exact match for current identifier let completionArray = await this.completion(documentUri, currDoc.positionAt(currOffset - 1), documents) return completionArray.find(function (elem) { // if a file has compilation problems, ycmd will fall back to ID-based // completions, which have only `extra_menu_info: "[ID]"` as additional // info, so we filter those useless ones out by looking to see if they // have what we really want: the signature at the top of the // `documentation` info. return elem.insertText === identifierName && !!elem.documentation }) } public async getDocHover(documentUri, position, documents, imprecise = false) { const doc = await this.runCompleterCommand(documentUri, position, documents, imprecise ? 'GetDocImprecise' : 'GetDoc') logger('getDocHover', JSON.stringify(doc)) return mapYcmDocToHover(doc, documents.get(documentUri).languageId) } public async getDoc(documentUri: string, position: Position, documents: TextDocuments) { const doc = await this.runCompleterCommand(documentUri, position, documents, 'GetDoc') logger('getDoc', JSON.stringify(doc)) } public async getDetailedDiagnostic(documentUri: string, position: Position, documents: TextDocuments) { const request = this.buildRequest(documentUri, position, documents) const response = await request.request('detailed_diagnostic') } public async readyToParse(documentUri: string, documents: TextDocuments): Promise<Diagnostic[]> { try { const response = await this.eventNotification(documentUri, null, documents, 'FileReadyToParse') if (!_.isArray(response)) return [] logger(`readyToParse`, `ycm responsed ${response.length} items`) const issues = response as YcmDiagnosticItem[] const uri = crossPlatformUri(documentUri) const [reported_issues, header_issues] = _.partition(issues, it => it.location.filepath === uri) // If there are issues we come across in files other than the // one we're looking at, it's probably from an included header. // Since they may be the root source of errors in the file // we're looking at, instead of filtering them all out, let's // just pick the first one to display and hard-code it to // show up on the first line, since the language // server diagnostic interface doesn't appear to be able to // report errors in different files. if (header_issues.length > 0) { const issue = header_issues[0] const relative = path.relative(path.parse(uri).dir, path.parse(issue.location.filepath).dir) let location = issue.location.filepath if (relative.split(/[\/\\\\]/).length <= 1) { location = path.normalize(`./${relative}/${path.parse(issue.location.filepath).base}`) } reported_issues.unshift({ ...issue, text: `${issue.text} in included file ${location}:${issue.location.line_num}`, location: { ...issue.location, column_num: 1, line_num: 1, }, location_extent: { ...issue.location_extent, start: { ...issue.location_extent.start, line_num: 1, column_num: 1, }, end: { ...issue.location_extent.end, line_num: 1, column_num: 1000, } } }) } logger(`readyToParse->reported_issues`, JSON.stringify(reported_issues)) return mapYcmDiagnosticToLanguageServerDiagnostic(reported_issues).filter(it => !!it.range) } catch (err) { return [] } } public async fixIt(documentUri: string, position: Position, documents: TextDocuments) { const response = await this.runCompleterCommand(documentUri, position, documents, 'FixIt') const fixits = response.fixits as YcmFixIt[] const uri = crossPlatformUri(documentUri) fixits.forEach(it => { if (it.text.indexOf(uri) !== -1) it.text = it.text.replace(`${uri}:`, '') }) return fixits } public async currentIdentifierFinished(documentUri: string, documents: TextDocuments) { await this.eventNotification(documentUri, null, documents, 'CurrentIdentifierFinished') } public async insertLeave(documentUri: string, documents: TextDocuments) { await this.eventNotification(documentUri, null, documents, 'InsertLeave') } } export interface Settings { ycmd: { path: string global_extra_config: string python: string confirm_extra_conf: boolean debug: boolean enable_hover_type: boolean use_imprecise_get_type: boolean } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/operationalizationClustersMappers"; import * as Parameters from "../models/parameters"; import { MachineLearningComputeManagementClientContext } from "../machineLearningComputeManagementClientContext"; /** Class representing a OperationalizationClusters. */ export class OperationalizationClusters { private readonly client: MachineLearningComputeManagementClientContext; /** * Create a OperationalizationClusters. * @param {MachineLearningComputeManagementClientContext} client Reference to the service client. */ constructor(client: MachineLearningComputeManagementClientContext) { this.client = client; } /** * Create or update an operationalization cluster. * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param parameters Parameters supplied to create or update an Operationalization cluster. * @param [options] The optional parameters * @returns Promise<Models.OperationalizationClustersCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, clusterName: string, parameters: Models.OperationalizationCluster, options?: msRest.RequestOptionsBase): Promise<Models.OperationalizationClustersCreateOrUpdateResponse> { return this.beginCreateOrUpdate(resourceGroupName,clusterName,parameters,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.OperationalizationClustersCreateOrUpdateResponse>; } /** * Gets the operationalization cluster resource view. Note that the credentials are not returned by * this call. Call ListKeys to get them. * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param [options] The optional parameters * @returns Promise<Models.OperationalizationClustersGetResponse> */ get(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase): Promise<Models.OperationalizationClustersGetResponse>; /** * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param callback The callback */ get(resourceGroupName: string, clusterName: string, callback: msRest.ServiceCallback<Models.OperationalizationCluster>): void; /** * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, clusterName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationalizationCluster>): void; get(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationalizationCluster>, callback?: msRest.ServiceCallback<Models.OperationalizationCluster>): Promise<Models.OperationalizationClustersGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, clusterName, options }, getOperationSpec, callback) as Promise<Models.OperationalizationClustersGetResponse>; } /** * The PATCH operation can be used to update only the tags for a cluster. Use PUT operation to * update other properties. * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param parameters The parameters supplied to patch the cluster. * @param [options] The optional parameters * @returns Promise<Models.OperationalizationClustersUpdateResponse> */ update(resourceGroupName: string, clusterName: string, parameters: Models.OperationalizationClusterUpdateParameters, options?: msRest.RequestOptionsBase): Promise<Models.OperationalizationClustersUpdateResponse>; /** * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param parameters The parameters supplied to patch the cluster. * @param callback The callback */ update(resourceGroupName: string, clusterName: string, parameters: Models.OperationalizationClusterUpdateParameters, callback: msRest.ServiceCallback<Models.OperationalizationCluster>): void; /** * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param parameters The parameters supplied to patch the cluster. * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, clusterName: string, parameters: Models.OperationalizationClusterUpdateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationalizationCluster>): void; update(resourceGroupName: string, clusterName: string, parameters: Models.OperationalizationClusterUpdateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationalizationCluster>, callback?: msRest.ServiceCallback<Models.OperationalizationCluster>): Promise<Models.OperationalizationClustersUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, clusterName, parameters, options }, updateOperationSpec, callback) as Promise<Models.OperationalizationClustersUpdateResponse>; } /** * Deletes the specified cluster. * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param [options] The optional parameters * @returns Promise<Models.OperationalizationClustersDeleteResponse> */ deleteMethod(resourceGroupName: string, clusterName: string, options?: Models.OperationalizationClustersDeleteMethodOptionalParams): Promise<Models.OperationalizationClustersDeleteResponse> { return this.beginDeleteMethod(resourceGroupName,clusterName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.OperationalizationClustersDeleteResponse>; } /** * Gets the credentials for the specified cluster such as Storage, ACR and ACS credentials. This is * a long running operation because it fetches keys from dependencies. * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param [options] The optional parameters * @returns Promise<Models.OperationalizationClustersListKeysResponse> */ listKeys(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase): Promise<Models.OperationalizationClustersListKeysResponse>; /** * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param callback The callback */ listKeys(resourceGroupName: string, clusterName: string, callback: msRest.ServiceCallback<Models.OperationalizationClusterCredentials>): void; /** * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param options The optional parameters * @param callback The callback */ listKeys(resourceGroupName: string, clusterName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationalizationClusterCredentials>): void; listKeys(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationalizationClusterCredentials>, callback?: msRest.ServiceCallback<Models.OperationalizationClusterCredentials>): Promise<Models.OperationalizationClustersListKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, clusterName, options }, listKeysOperationSpec, callback) as Promise<Models.OperationalizationClustersListKeysResponse>; } /** * Checks if updates are available for system services in the cluster. * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param [options] The optional parameters * @returns Promise<Models.OperationalizationClustersCheckSystemServicesUpdatesAvailableResponse> */ checkSystemServicesUpdatesAvailable(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase): Promise<Models.OperationalizationClustersCheckSystemServicesUpdatesAvailableResponse>; /** * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param callback The callback */ checkSystemServicesUpdatesAvailable(resourceGroupName: string, clusterName: string, callback: msRest.ServiceCallback<Models.CheckSystemServicesUpdatesAvailableResponse>): void; /** * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param options The optional parameters * @param callback The callback */ checkSystemServicesUpdatesAvailable(resourceGroupName: string, clusterName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CheckSystemServicesUpdatesAvailableResponse>): void; checkSystemServicesUpdatesAvailable(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CheckSystemServicesUpdatesAvailableResponse>, callback?: msRest.ServiceCallback<Models.CheckSystemServicesUpdatesAvailableResponse>): Promise<Models.OperationalizationClustersCheckSystemServicesUpdatesAvailableResponse> { return this.client.sendOperationRequest( { resourceGroupName, clusterName, options }, checkSystemServicesUpdatesAvailableOperationSpec, callback) as Promise<Models.OperationalizationClustersCheckSystemServicesUpdatesAvailableResponse>; } /** * Updates system services in a cluster. * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param [options] The optional parameters * @returns Promise<Models.OperationalizationClustersUpdateSystemServicesResponse> */ updateSystemServices(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase): Promise<Models.OperationalizationClustersUpdateSystemServicesResponse> { return this.beginUpdateSystemServices(resourceGroupName,clusterName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.OperationalizationClustersUpdateSystemServicesResponse>; } /** * Gets the clusters in the specified resource group. * @param resourceGroupName Name of the resource group in which the cluster is located. * @param [options] The optional parameters * @returns Promise<Models.OperationalizationClustersListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: Models.OperationalizationClustersListByResourceGroupOptionalParams): Promise<Models.OperationalizationClustersListByResourceGroupResponse>; /** * @param resourceGroupName Name of the resource group in which the cluster is located. * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>): void; /** * @param resourceGroupName Name of the resource group in which the cluster is located. * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: Models.OperationalizationClustersListByResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>): void; listByResourceGroup(resourceGroupName: string, options?: Models.OperationalizationClustersListByResourceGroupOptionalParams | msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>, callback?: msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>): Promise<Models.OperationalizationClustersListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.OperationalizationClustersListByResourceGroupResponse>; } /** * Gets the operationalization clusters in the specified subscription. * @param [options] The optional parameters * @returns Promise<Models.OperationalizationClustersListBySubscriptionIdResponse> */ listBySubscriptionId(options?: Models.OperationalizationClustersListBySubscriptionIdOptionalParams): Promise<Models.OperationalizationClustersListBySubscriptionIdResponse>; /** * @param callback The callback */ listBySubscriptionId(callback: msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>): void; /** * @param options The optional parameters * @param callback The callback */ listBySubscriptionId(options: Models.OperationalizationClustersListBySubscriptionIdOptionalParams, callback: msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>): void; listBySubscriptionId(options?: Models.OperationalizationClustersListBySubscriptionIdOptionalParams | msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>, callback?: msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>): Promise<Models.OperationalizationClustersListBySubscriptionIdResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionIdOperationSpec, callback) as Promise<Models.OperationalizationClustersListBySubscriptionIdResponse>; } /** * Create or update an operationalization cluster. * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param parameters Parameters supplied to create or update an Operationalization cluster. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(resourceGroupName: string, clusterName: string, parameters: Models.OperationalizationCluster, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, clusterName, parameters, options }, beginCreateOrUpdateOperationSpec, options); } /** * Deletes the specified cluster. * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, clusterName: string, options?: Models.OperationalizationClustersBeginDeleteMethodOptionalParams): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, clusterName, options }, beginDeleteMethodOperationSpec, options); } /** * Updates system services in a cluster. * @param resourceGroupName Name of the resource group in which the cluster is located. * @param clusterName The name of the cluster. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginUpdateSystemServices(resourceGroupName: string, clusterName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, clusterName, options }, beginUpdateSystemServicesOperationSpec, options); } /** * Gets the clusters in the specified resource group. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.OperationalizationClustersListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: Models.OperationalizationClustersListByResourceGroupNextOptionalParams): Promise<Models.OperationalizationClustersListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, options: Models.OperationalizationClustersListByResourceGroupNextOptionalParams, callback: msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>): void; listByResourceGroupNext(nextPageLink: string, options?: Models.OperationalizationClustersListByResourceGroupNextOptionalParams | msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>, callback?: msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>): Promise<Models.OperationalizationClustersListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.OperationalizationClustersListByResourceGroupNextResponse>; } /** * Gets the operationalization clusters in the specified subscription. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.OperationalizationClustersListBySubscriptionIdNextResponse> */ listBySubscriptionIdNext(nextPageLink: string, options?: Models.OperationalizationClustersListBySubscriptionIdNextOptionalParams): Promise<Models.OperationalizationClustersListBySubscriptionIdNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listBySubscriptionIdNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listBySubscriptionIdNext(nextPageLink: string, options: Models.OperationalizationClustersListBySubscriptionIdNextOptionalParams, callback: msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>): void; listBySubscriptionIdNext(nextPageLink: string, options?: Models.OperationalizationClustersListBySubscriptionIdNextOptionalParams | msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>, callback?: msRest.ServiceCallback<Models.PaginatedOperationalizationClustersList>): Promise<Models.OperationalizationClustersListBySubscriptionIdNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listBySubscriptionIdNextOperationSpec, callback) as Promise<Models.OperationalizationClustersListBySubscriptionIdNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningCompute/operationalizationClusters/{clusterName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.OperationalizationCluster }, default: { bodyMapper: Mappers.ErrorResponseWrapper } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningCompute/operationalizationClusters/{clusterName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.OperationalizationClusterUpdateParameters, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationalizationCluster }, default: { bodyMapper: Mappers.ErrorResponseWrapper } }, serializer }; const listKeysOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningCompute/operationalizationClusters/{clusterName}/listKeys", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.OperationalizationClusterCredentials }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const checkSystemServicesUpdatesAvailableOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningCompute/operationalizationClusters/{clusterName}/checkSystemServicesUpdatesAvailable", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.CheckSystemServicesUpdatesAvailableResponse }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningCompute/operationalizationClusters", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion, Parameters.skiptoken ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PaginatedOperationalizationClustersList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listBySubscriptionIdOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.MachineLearningCompute/operationalizationClusters", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion, Parameters.skiptoken ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PaginatedOperationalizationClustersList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningCompute/operationalizationClusters/{clusterName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.OperationalizationCluster, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationalizationCluster }, 201: { bodyMapper: Mappers.OperationalizationCluster }, default: { bodyMapper: Mappers.ErrorResponseWrapper } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningCompute/operationalizationClusters/{clusterName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName ], queryParameters: [ Parameters.apiVersion, Parameters.deleteAll ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: { headersMapper: Mappers.OperationalizationClustersDeleteHeaders }, 204: { headersMapper: Mappers.OperationalizationClustersDeleteHeaders }, default: { bodyMapper: Mappers.ErrorResponseWrapper, headersMapper: Mappers.OperationalizationClustersDeleteHeaders } }, serializer }; const beginUpdateSystemServicesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningCompute/operationalizationClusters/{clusterName}/updateSystemServices", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.clusterName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.UpdateSystemServicesResponse, headersMapper: Mappers.OperationalizationClustersUpdateSystemServicesHeaders }, 202: { headersMapper: Mappers.OperationalizationClustersUpdateSystemServicesHeaders }, default: { bodyMapper: Mappers.CloudError, headersMapper: Mappers.OperationalizationClustersUpdateSystemServicesHeaders } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], queryParameters: [ Parameters.apiVersion, Parameters.skiptoken ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PaginatedOperationalizationClustersList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listBySubscriptionIdNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], queryParameters: [ Parameters.apiVersion, Parameters.skiptoken ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PaginatedOperationalizationClustersList }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import { EDITOR } from 'internal:constants'; import { IRigidBody2D } from '../../spec/i-rigid-body'; import { _decorator, Vec2, Component, error, Layers, IVec2Like } from '../../../core'; import { ERigidBody2DType } from '../physics-types'; import { ccclass } from '../../../core/data/class-decorator'; import { createRigidBody } from '../instance'; import { Joint2D } from './joints/joint-2d'; import { PhysicsGroup } from '../../../physics/framework/physics-enum'; const { property, type, menu } = _decorator; @ccclass('cc.RigidBody2D') @menu('Physics2D/RigidBody2D') export class RigidBody2D extends Component { /** * @en * Gets or sets the group of the rigid body. * @zh * 获取或设置分组。 */ @type(PhysicsGroup) public get group (): number { return this._group; } public set group (v: number) { this._group = v; } @property enabledContactListener = false; /** * @en * Is this a fast moving body that should be prevented from tunneling through * other moving bodies? * Note : * - All bodies are prevented from tunneling through kinematic and static bodies. This setting is only considered on dynamic bodies. * - You should use this flag sparingly since it increases processing time. * @zh * 这个刚体是否是一个快速移动的刚体,并且需要禁止穿过其他快速移动的刚体? * 需要注意的是 : * - 所有刚体都被禁止从 运动刚体 和 静态刚体 中穿过。此选项只关注于 动态刚体。 * - 应该尽量少的使用此选项,因为它会增加程序处理时间。 */ @property bullet = false; /** * @en * Rigidbody type : Static, Kinematic, Dynamic or Animated. * @zh * 刚体类型: Static, Kinematic, Dynamic or Animated. */ @type(ERigidBody2DType) get type (): ERigidBody2DType { return this._type; } set type (v: ERigidBody2DType) { this._type = v; if (this._body) { if (v === ERigidBody2DType.Animated) { this._body.setType(ERigidBody2DType.Kinematic); } else { this._body.setType(v); } } } /** * @en * Set this flag to false if this body should never fall asleep. * Note that this increases CPU usage. * @zh * 如果此刚体永远都不应该进入睡眠,那么设置这个属性为 false。 * 需要注意这将使 CPU 占用率提高。 */ @property get allowSleep (): boolean { return this._allowSleep; } set allowSleep (v: boolean) { this._allowSleep = v; if (this._body) { this._body.setAllowSleep(v); } } /** * @en * Scale the gravity applied to this body. * @zh * 缩放应用在此刚体上的重力值 */ @property get gravityScale (): number { return this._gravityScale; } set gravityScale (v: number) { this._gravityScale = v; if (this._body) { this._body.setGravityScale(v); } } /** * @en * Linear damping is use to reduce the linear velocity. * The damping parameter can be larger than 1, but the damping effect becomes sensitive to the * time step when the damping parameter is large. * @zh * Linear damping 用于衰减刚体的线性速度。衰减系数可以大于 1,但是当衰减系数比较大的时候,衰减的效果会变得比较敏感。 */ @property get linearDamping (): number { return this._linearDamping; } set linearDamping (v: number) { this._linearDamping = v; if (this._body) { this._body.setLinearDamping(v); } } /** * @en * Angular damping is use to reduce the angular velocity. The damping parameter * can be larger than 1 but the damping effect becomes sensitive to the * time step when the damping parameter is large. * @zh * Angular damping 用于衰减刚体的角速度。衰减系数可以大于 1,但是当衰减系数比较大的时候,衰减的效果会变得比较敏感。 */ @property get angularDamping (): number { return this._angularDamping; } set angularDamping (v: number) { this._angularDamping = v; if (this._body) { this._body.setAngularDamping(v); } } /** * @en * The linear velocity of the body's origin in world co-ordinates. * @zh * 刚体在世界坐标下的线性速度 */ @property get linearVelocity (): Vec2 { if (this._body) { this._body.getLinearVelocity(this._linearVelocity); } return this._linearVelocity; } set linearVelocity (v: Vec2) { this._linearVelocity = v; if (this._body) { this._body.setLinearVelocity(v); } } /** * @en * The angular velocity of the body. * @zh * 刚体的角速度 */ @property get angularVelocity (): number { if (this._body) { this._angularVelocity = this._body.getAngularVelocity(); } return this._angularVelocity; } set angularVelocity (v: number) { this._angularVelocity = v; if (this._body) { this._body.setAngularVelocity(v); } } /** * @en * Should this body be prevented from rotating? * @zh * 是否禁止此刚体进行旋转 */ @property get fixedRotation (): boolean { return this._fixedRotation; } set fixedRotation (v: boolean) { this._fixedRotation = v; if (this._body) { this._body.setFixedRotation(v); } } /** * @en * Whether to wake up this rigid body during initialization * @zh * 是否在初始化时唤醒此刚体 */ @property awakeOnLoad = true; // /** // * @en // * Set the active state of the body. An inactive body is not // * simulated and cannot be collided with or woken up. // * If body is active, all fixtures will be added to the // * broad-phase. // * If body is inactive, all fixtures will be removed from // * the broad-phase and all contacts will be destroyed. // * Fixtures on an inactive body are implicitly inactive and will // * not participate in collisions, ray-casts, or queries. // * Joints connected to an inactive body are implicitly inactive. // * @zh // * 设置刚体的激活状态。一个非激活状态下的刚体是不会被模拟和碰撞的,不管它是否处于睡眠状态下。 // * 如果刚体处于激活状态下,所有夹具会被添加到 粗测阶段(broad-phase)。 // * 如果刚体处于非激活状态下,所有夹具会被从 粗测阶段(broad-phase)中移除。 // * 在非激活状态下的夹具不会参与到碰撞,射线,或者查找中 // * 链接到非激活状态下刚体的关节也是非激活的。 // * @property {Boolean} active // * @default true // */ // get active () { // if (this._body) { // return this._body.isActive(); // } // return false; // } // set active (v) { // if (this._body) { // this._body.setActive(v); // } // } /// RigidBody methods /// /** * @en * Whether the rigid body is awake. * @zh * 获取刚体是否正在休眠 */ isAwake () { if (this._body) { return this._body.isAwake; } return false; } /** * @en * Wake up the rigid body. * @zh * 唤醒刚体。 */ wakeUp () { if (this._body) { this._body.wakeUp(); } } /** * @en * Dormancy of rigid body. * @zh * 休眠刚体。 */ sleep () { if (this._body) { this._body.sleep(); } } /** * @en * Get total mass of the body. * @zh * 获取刚体的质量。 */ getMass (): number { if (this._body) { return this._body.getMass(); } return 0; } /** * @en * Apply a force at a world point. If the force is not * applied at the center of mass, it will generate a torque and * affect the angular velocity. * @zh * 施加一个力到刚体上的一个点。如果力没有施加到刚体的质心上,还会产生一个扭矩并且影响到角速度。 * @param force - the world force vector. * @param point - the world position. * @param wake - also wake up the body. */ applyForce (force: Vec2, point: Vec2, wake: boolean) { if (this._body) { this._body.applyForce(force, point, wake); } } /** * @en * Apply a force to the center of mass. * @zh * 施加一个力到刚体上的质心上。 * @param force - the world force vector. * @param wake - also wake up the body. */ applyForceToCenter (force: Vec2, wake: boolean) { if (this._body) { this._body.applyForceToCenter(force, wake); } } /** * @en * Apply a torque. This affects the angular velocity. * @zh * 施加一个扭矩力,将影响刚体的角速度 * @param torque - about the z-axis (out of the screen), usually in N-m. * @param wake - also wake up the body */ applyTorque (torque: number, wake: boolean) { if (this._body) { this._body.applyTorque(torque, wake); } } /** * @en * Apply a impulse at a world point, this immediately modifies the velocity. * If the impulse is not applied at the center of mass, it will generate a torque and * affect the angular velocity. * @zh * 施加冲量到刚体上的一个点,将立即改变刚体的线性速度。 * 如果冲量施加到的点不是刚体的质心,那么将产生一个扭矩并影响刚体的角速度。 * @param impulse - the world impulse vector, usually in N-seconds or kg-m/s. * @param point - the world position * @param wake - alse wake up the body */ applyLinearImpulse (impulse: Vec2, point: Vec2, wake: boolean) { if (this._body) { this._body.applyLinearImpulse(impulse, point, wake); } } /** * @en * Apply a impulse at the center of mass, this immediately modifies the velocity. * @zh * 施加冲量到刚体上的质心点,将立即改变刚体的线性速度。 * @param impulse - the world impulse vector, usually in N-seconds or kg-m/s. * @param point - the world position * @param wake - alse wake up the body */ applyLinearImpulseToCenter (impulse: Vec2, wake: boolean) { if (this._body) { this._body.applyLinearImpulseToCenter(impulse, wake); } } /** * @en * Apply an angular impulse. * @zh * 施加一个角速度冲量。 * @param impulse - the angular impulse in units of kg*m*m/s * @param wake - also wake up the body */ applyAngularImpulse (impulse: number, wake: boolean) { if (this._body) { this._body.applyAngularImpulse(impulse, wake); } } /** * @en * Get the world linear velocity of a world point attached to this body. * @zh * 获取刚体上指定点的线性速度 * @param worldPoint - a point in world coordinates. * @param out - optional, the receiving point */ getLinearVelocityFromWorldPoint<Out extends IVec2Like> (worldPoint: IVec2Like, out: Out): Out { if (this._body) { return this._body.getLinearVelocityFromWorldPoint(worldPoint, out); } return out; } /** * @en * Converts a world coordinate point to the given rigid body coordinate. * @zh * 将一个给定的世界坐标系下的向量转换为刚体本地坐标系下的向量 * @param worldVector - a vector in world coordinates. * @param out - optional, the receiving vector */ getLocalVector<Out extends IVec2Like> (worldVector: IVec2Like, out: Out): Out { if (this._body) { return this._body.getLocalVector(worldVector, out); } return out; } /** * @en * Converts a given vector in this rigid body's local coordinate system to the world coordinate system * @zh * 将一个给定的刚体本地坐标系下的向量转换为世界坐标系下的向量 * @param localVector - a vector in world coordinates. * @param out - optional, the receiving vector */ getWorldVector<Out extends IVec2Like> (localVector: IVec2Like, out: Out): Out { if (this._body) { return this._body.getWorldVector(localVector, out); } return out; } /** * @en * Converts a given point in the world coordinate system to this rigid body's local coordinate system * @zh * 将一个给定的世界坐标系下的点转换为刚体本地坐标系下的点 * @param worldPoint - a point in world coordinates. * @param out - optional, the receiving point */ getLocalPoint<Out extends IVec2Like> (worldPoint: IVec2Like, out: Out): Out { if (this._body) { return this._body.getLocalPoint(worldPoint, out); } return out; } /** * @en * Converts a given point in this rigid body's local coordinate system to the world coordinate system * @zh * 将一个给定的刚体本地坐标系下的点转换为世界坐标系下的点 * @param localPoint - a point in local coordinates. * @param out - optional, the receiving point */ getWorldPoint<Out extends IVec2Like> (localPoint: IVec2Like, out: Out): Out { if (this._body) { return this._body.getWorldPoint(localPoint, out); } return out; } /** * @en * Get the local position of the center of mass. * @zh * 获取刚体本地坐标系下的质心 */ getLocalCenter<Out extends IVec2Like> (out: Out): Out { if (this._body) { return this._body.getLocalCenter(out); } return out; } /** * @en * Get the world position of the center of mass. * @zh * 获取刚体世界坐标系下的质心 */ getWorldCenter<Out extends IVec2Like> (out: Out): Out { if (this._body) { return this._body.getWorldCenter(out); } return out; } /** * @en * Get the rotational inertia of the body about the local origin. * @zh * 获取刚体本地坐标系下原点的旋转惯性 */ getInertia () { if (this._body) { this._body.getInertia(); } return 0; } /// COMPONENT LIFECYCLE /// protected onLoad () { if (!EDITOR) { this._body = createRigidBody(); this._body.initialize(this); } } protected onEnable () { if (this._body) { this._body.onEnable!(); } } protected onDisable () { if (this._body) { this._body.onDisable!(); } } protected onDestroy () { if (this._body) { this._body.onDestroy!(); } } private _body: IRigidBody2D | null = null; get impl () { return this._body; } @property private _group = PhysicsGroup.DEFAULT; @property private _type = ERigidBody2DType.Dynamic; @property private _allowSleep = true; @property private _gravityScale = 1; @property private _linearDamping = 0; @property private _angularDamping = 0; @property private _linearVelocity = new Vec2(); @property private _angularVelocity = 0; @property private _fixedRotation = false; }
the_stack
import ImageAssets from '../../assets/ImageAssets'; import { getAwardProps } from '../../awards/GameAwardsHelper'; import { AwardProperty } from '../../awards/GameAwardsTypes'; import CommonBackButton from '../../commons/CommonBackButton'; import { Constants, screenCenter, screenSize } from '../../commons/CommonConstants'; import { addLoadingScreen } from '../../effects/LoadingScreen'; import { putWorkerMessage } from '../../effects/WorkerMessage'; import GameInputManager from '../../input/GameInputManager'; import GameLayerManager from '../../layer/GameLayerManager'; import { Layer } from '../../layer/GameLayerTypes'; import SourceAcademyGame from '../../SourceAcademyGame'; import { createButton } from '../../utils/ButtonUtils'; import { limitNumber, mandatory } from '../../utils/GameUtils'; import { resizeUnderflow } from '../../utils/SpriteUtils'; import { calcTableFormatPos, Direction, HexColor } from '../../utils/StyleUtils'; import { createBitmapText } from '../../utils/TextUtils'; import { awardBannerTextStyle, awardNoAssetTitleStyle, AwardsHallConstants } from './AwardsHallConstants'; import { createAwardsHoverContainer } from './AwardsHallHelper'; /** * This scenes display all students awards (collectibles and achievements). */ class AwardsHall extends Phaser.Scene { public layerManager?: GameLayerManager; public inputManager?: GameInputManager; private backgroundTile: Phaser.GameObjects.TileSprite | undefined; private awardsContainer: Phaser.GameObjects.Container | undefined; private isScrollLeft: boolean; private isScrollRight: boolean; private scrollLim: number; private awardXSpace: number; constructor() { super('AwardsHall'); SourceAcademyGame.getInstance().setCurrentSceneRef(this); this.isScrollLeft = false; this.isScrollRight = false; this.scrollLim = 0; this.awardXSpace = 0; } public init() { this.layerManager = new GameLayerManager(this); this.inputManager = new GameInputManager(this); } public preload() { addLoadingScreen(this); } public async create() { // Calculate the maximum horizontal space required based // on maximum number of achievement/collectible const achievementLength = this.getUserStateManager().getAchievements().length; const collectibleLength = this.getUserStateManager().getCollectibles().length; this.awardXSpace = Math.ceil( Math.max(achievementLength, collectibleLength) / AwardsHallConstants.maxAwardsPerCol ) * AwardsHallConstants.award.xSpace; // Scroll limit is anything that exceed the screen size this.scrollLim = this.awardXSpace < screenSize.x ? 0 : this.awardXSpace - screenSize.x; this.renderBackground(); this.renderAwards(); putWorkerMessage(this, 'A', screenSize.x * 0.95, screenSize.y * 0.99); } public update() { if (!this.backgroundTile || !this.awardsContainer) return; // Scroll the awards hall if button is currently clicked/held down let newXPos = this.awardsContainer.x; if (this.isScrollRight) { newXPos -= AwardsHallConstants.scrollSpeed; } else if (this.isScrollLeft) { newXPos += AwardsHallConstants.scrollSpeed; } newXPos = limitNumber(newXPos, -this.scrollLim, 0); // To achieve seamless background, we need to scroll on .tilePosition for background this.backgroundTile.tilePositionX = -newXPos; this.awardsContainer.x = newXPos; } /** * Render background of this scene, as well as its * UI elements (arrows, backbutton, as well as the 'Collectible' and 'Achievement' banner). */ private renderBackground() { if (this.backgroundTile) this.backgroundTile.destroy(); this.backgroundTile = new Phaser.GameObjects.TileSprite( this, 0, 0, AwardsHallConstants.tileDim, AwardsHallConstants.tileDim, ImageAssets.awardsBackground.key ).setOrigin(0, 0.25); this.getLayerManager().addToLayer(Layer.Background, this.backgroundTile); // Add banners const banners = ['Achievements', 'Collectibles']; const bannerPos = calcTableFormatPos({ direction: Direction.Column, numOfItems: banners.length }); banners.forEach((banner, index) => { const bannerCont = this.createBanner(banner, bannerPos[index][1]); this.getLayerManager().addToLayer(Layer.UI, bannerCont); }); const leftArrow = createButton(this, { assetKey: ImageAssets.chapterSelectArrow.key, onDown: () => (this.isScrollLeft = true), onUp: () => (this.isScrollLeft = false), onOut: () => (this.isScrollLeft = false) }).setPosition(screenCenter.x - AwardsHallConstants.arrow.xOffset, screenCenter.y); const rightArrow = createButton(this, { assetKey: ImageAssets.chapterSelectArrow.key, onDown: () => (this.isScrollRight = true), onUp: () => (this.isScrollRight = false), onOut: () => (this.isScrollRight = false) }) .setPosition(screenCenter.x + AwardsHallConstants.arrow.xOffset, screenCenter.y) .setScale(-1, 1); const backButton = new CommonBackButton(this, () => { this.cleanUp(); this.scene.start('MainMenu'); }); this.getLayerManager().addToLayer(Layer.UI, leftArrow); this.getLayerManager().addToLayer(Layer.UI, rightArrow); this.getLayerManager().addToLayer(Layer.UI, backButton); } /** * Render all the awards that student has. */ private renderAwards() { if (this.awardsContainer) this.awardsContainer.destroy(); this.awardsContainer = new Phaser.GameObjects.Container(this, 0, 0); // Achievement const achievements = this.getAwards(this.getUserStateManager().getAchievements()); const achievementsPos = calcTableFormatPos({ direction: Direction.Column, numOfItems: achievements.length, numItemLimit: AwardsHallConstants.maxAwardsPerCol, redistributeLast: false, maxXSpace: this.awardXSpace, maxYSpace: AwardsHallConstants.award.ySpace }); // Achievement is positioned on the upper half of the screen this.awardsContainer.add( achievements.map((achievement, index) => this.createAward( achievement, achievementsPos[index][0], achievementsPos[index][1] + AwardsHallConstants.award.yStart - screenCenter.y ) ) ); // Collectible const collectibles = this.getAwards(this.getUserStateManager().getCollectibles()); const collectiblesPos = calcTableFormatPos({ direction: Direction.Column, numOfItems: collectibles.length, numItemLimit: AwardsHallConstants.maxAwardsPerCol, redistributeLast: false, maxXSpace: this.awardXSpace, maxYSpace: AwardsHallConstants.award.ySpace }); // Collectible is positioned on the lower half of the screen this.awardsContainer.add( collectibles.map((collectible, index) => this.createAward( collectible, collectiblesPos[index][0], collectiblesPos[index][1] + AwardsHallConstants.award.yStart ) ) ); this.getLayerManager().addToLayer(Layer.Objects, this.awardsContainer); } /** * Fetch awardProps based on the type string[] * @param keys */ private getAwards(keys: string[]) { const awardProps = getAwardProps(keys); return awardProps; } /** * Format the given award; giving it a pop up hover of its * description, resize it to the correct size, and position it * based on the given xPos and yPos. * * @param award awardProperty to be used * @param xPos x position of the award * @param yPos y position of the award */ private createAward(award: AwardProperty, xPos: number, yPos: number) { const awardCont = new Phaser.GameObjects.Container(this, xPos, yPos); let image; if (award.assetKey === Constants.nullInteractionId) { // No asset is associated with the award image = new Phaser.GameObjects.Rectangle( this, 0, 0, AwardsHallConstants.award.dim, AwardsHallConstants.award.dim, HexColor.darkBlue, 0.8 ); image.setInteractive(); const text = new Phaser.GameObjects.Text( this, 0, 0, award.title, awardNoAssetTitleStyle ).setOrigin(0.5, 0.5); awardCont.add([image, text]); } else { image = new Phaser.GameObjects.Sprite(this, 0, 0, award.assetKey).setOrigin(0.5); resizeUnderflow(image, AwardsHallConstants.award.dim, AwardsHallConstants.award.dim); image.setInteractive({ pixelPerfect: true, useHandCursor: true }); awardCont.add(image); } // Add black tint if award is not completed const blackTint = new Phaser.GameObjects.Rectangle( this, 0, 0, AwardsHallConstants.award.dim, AwardsHallConstants.award.dim, 0 ).setAlpha(award.completed ? 0 : 0.8); awardCont.add(blackTint); // Set up the pop up const hoverCont = createAwardsHoverContainer(this, award); image.addListener(Phaser.Input.Events.GAMEOBJECT_POINTER_OVER, () => hoverCont.setVisible(true) ); image.addListener(Phaser.Input.Events.GAMEOBJECT_POINTER_OUT, () => hoverCont.setVisible(false) ); image.addListener( Phaser.Input.Events.GAMEOBJECT_POINTER_MOVE, (pointer: Phaser.Input.Pointer) => { hoverCont.x = pointer.x + 10; hoverCont.y = pointer.y - 10; } ); this.getLayerManager().addToLayer(Layer.UI, hoverCont); return awardCont; } /** * Clean up of related managers */ private cleanUp() { this.getInputManager().clearListeners(); this.getLayerManager().clearAllLayers(); } /** * Format the given text with banner style. * * In-game, this is the achievement & collectible banner * that is positioned on the left hand side. * * @param text text to be put on the banner * @param yPos y position of the banner */ private createBanner(text: string, yPos: number) { const bannerContainer = new Phaser.GameObjects.Container(this, 0, yPos); const bannerBg = new Phaser.GameObjects.Sprite( this, AwardsHallConstants.banner.xOffset, 0, ImageAssets.awardsPage.key ); const bannerText = createBitmapText( this, text, AwardsHallConstants.bannerTextConfig, awardBannerTextStyle ); bannerContainer.add([bannerBg, bannerText]); return bannerContainer; } public getUserStateManager = () => SourceAcademyGame.getInstance().getUserStateManager(); public getInputManager = () => mandatory(this.inputManager); public getLayerManager = () => mandatory(this.layerManager); } export default AwardsHall;
the_stack
import * as React from "react"; import * as ReactDom from "react-dom"; import { Version, Environment, EnvironmentType } from "@microsoft/sp-core-library"; import { ThemeProvider, IReadonlyTheme, ThemeChangedEventArgs } from '@microsoft/sp-component-base'; import { BaseClientSideWebPart, IWebPartPropertiesMetadata } from "@microsoft/sp-webpart-base"; import { DisplayMode } from "@microsoft/sp-core-library"; import { isEqual } from '@microsoft/sp-lodash-subset'; import { IPropertyPaneConfiguration, PropertyPaneToggle, IPropertyPaneField, IPropertyPaneChoiceGroupOption, PropertyPaneChoiceGroup, PropertyPaneTextField, IPropertyPaneGroup, IPropertyPaneConditionalGroup, DynamicDataSharedDepth, PropertyPaneDynamicField, PropertyPaneDynamicFieldSet } from "@microsoft/sp-property-pane"; import * as update from 'immutability-helper'; import * as strings from "PeopleSearchWebPartStrings"; import { IPeopleSearchWebPartProps } from "./IPeopleSearchWebPartProps"; import { ISearchService, MockSearchService, SearchService } from "../../services/SearchService"; import { IPeopleSearchContainerProps, PeopleSearchContainer } from "./components/PeopleSearchContainer"; import ResultsLayoutOption from "../../models/ResultsLayoutOption"; import { TemplateService } from "../../services/TemplateService/TemplateService"; export default class PeopleSearchWebPart extends BaseClientSideWebPart<IPeopleSearchWebPartProps> { private _searchService: ISearchService; private _templateService: TemplateService; private _placeholder = null; private _themeProvider: ThemeProvider; private _themeVariant: IReadonlyTheme; private _initComplete = false; private _templatePropertyPaneOptions: IPropertyPaneField<any>[] = []; public async render(): Promise<void> { if (!this._initComplete) { return; } await this._initTemplate(); if (this.displayMode === DisplayMode.Edit) { const { Placeholder } = await import( /* webpackChunkName: 'search-property-pane' */ '@pnp/spfx-controls-react/lib/Placeholder' ); this._placeholder = Placeholder; } this.renderCompleted(); } protected get isRenderAsync(): boolean { return true; } protected renderCompleted(): void { super.renderCompleted(); let renderElement = null; if (this._isWebPartConfigured()) { const searchParameter: string | undefined = this.properties.searchParameter.tryGetValue(); this._searchService = update(this._searchService, { selectParameter: { $set: this.properties.selectParameter ? this.properties.selectParameter.split(',') : [] }, filterParameter: { $set: this.properties.filterParameter }, orderByParameter: { $set: this.properties.orderByParameter }, searchParameter: { $set: searchParameter }, pageSize: { $set: parseInt(this.properties.pageSize) } }); renderElement = React.createElement( PeopleSearchContainer, { webPartTitle: this.properties.webPartTitle, displayMode: this.displayMode, showBlank: this.properties.showBlank, showResultsCount: this.properties.showResultsCount, showPagination: this.properties.showPagination, searchService: this._searchService, templateService: this._templateService, templateParameters: this.properties.templateParameters, selectedLayout: this.properties.selectedLayout, themeVariant: this._themeVariant, serviceScope: this.context.serviceScope, updateWebPartTitle: (value: string) => { this.properties.webPartTitle = value; } } as IPeopleSearchContainerProps ); } else { if (this.displayMode === DisplayMode.Edit) { const placeholder: React.ReactElement<any> = React.createElement( this._placeholder, { iconName: strings.PlaceHolderEditLabel, iconText: strings.PlaceHolderIconText, description: strings.PlaceHolderDescription, buttonLabel: strings.PlaceHolderConfigureBtnLabel, onConfigure: this._setupWebPart.bind(this) } ); renderElement = placeholder; } else { renderElement = React.createElement('div', null); } } ReactDom.render(renderElement, this.domElement); } protected async onInit(): Promise<void> { this._initializeRequiredProperties(); this._initThemeVariant(); if (Environment.type === EnvironmentType.Local) { this._searchService = new MockSearchService(); } else { this._searchService = new SearchService(this.context.msGraphClientFactory); } this._templateService = new TemplateService(); this._initComplete = true; return super.onInit(); } protected onDispose(): void { ReactDom.unmountComponentAtNode(this.domElement); } protected get dataVersion(): Version { return Version.parse("1.0"); } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { const templateParametersGroup = this._getTemplateFieldsGroup(); let propertyPaneGroups: (IPropertyPaneGroup | IPropertyPaneConditionalGroup)[] = [ { groupName: strings.QuerySettingsGroupName, groupFields: this._getQueryFields() }, { primaryGroup: { groupName: strings.SearchQuerySettingsGroupName, groupFields: [ PropertyPaneTextField('searchParameter', { label: strings.SearchParameter }) ] }, secondaryGroup: { groupName: strings.SearchQuerySettingsGroupName, groupFields: [ PropertyPaneDynamicFieldSet({ label: strings.SearchParameter, fields: [ PropertyPaneDynamicField('searchParameter', { label: strings.SearchParameter }) ], sharedConfiguration: { depth: DynamicDataSharedDepth.Property } }) ] }, // Show the secondary group only if the web part has been // connected to a dynamic data source showSecondaryGroup: !!this.properties.searchParameter.tryGetSource() } as IPropertyPaneConditionalGroup, { groupName: strings.StylingSettingsGroupName, groupFields: this._getStylingFields(), } ]; if (templateParametersGroup) { propertyPaneGroups.push(templateParametersGroup); } return { pages: [ { groups: propertyPaneGroups, displayGroupsAsAccordion: false } ] }; } protected async onPropertyPaneFieldChanged(propertyPath: string) { if (propertyPath.localeCompare('selectedLayout') === 0) { await this._initTemplate(); this.context.propertyPane.refresh(); } } protected get propertiesMetadata(): IWebPartPropertiesMetadata { return { 'searchParameter': { dynamicPropertyType: 'string' } } as any as IWebPartPropertiesMetadata; } /** * Determines the group fields for query options inside the property pane */ private _getQueryFields(): IPropertyPaneField<any>[] { let stylingFields: IPropertyPaneField<any>[] = [ PropertyPaneTextField('selectParameter', { label: strings.SelectParameter, multiline: true }), PropertyPaneTextField('filterParameter', { label: strings.FilterParameter, multiline: true }), PropertyPaneTextField('orderByParameter', { label: strings.OrderByParameter, multiline: true }), PropertyPaneTextField('pageSize', { label: strings.PageSizeParameter, value: this.properties.pageSize.toString(), maxLength: 3, deferredValidationTime: 300, onGetErrorMessage: (value: string) => { return this._validateNumber(value); } }), ]; return stylingFields; } /** * Init the template according to the property pane current configuration * @returns the template content as a string */ private async _initTemplate(): Promise<void> { this._templatePropertyPaneOptions = this._templateService.getTemplateParameters(this.properties.selectedLayout, this.properties); } /** * Determines the group fields for styling options inside the property pane */ private _getStylingFields(): IPropertyPaneField<any>[] { const layoutOptions = [ { iconProps: { officeFabricIconFontName: 'People' }, text: strings.PeopleLayoutOption, key: ResultsLayoutOption.People }, { iconProps: { officeFabricIconFontName: 'Code' }, text: strings.DebugLayoutOption, key: ResultsLayoutOption.Debug } ] as IPropertyPaneChoiceGroupOption[]; let stylingFields: IPropertyPaneField<any>[] = [ // PropertyPaneToggle('showPagination', { // label: strings.ShowPaginationControl, // }), PropertyPaneToggle('showBlank', { label: strings.ShowBlankLabel, checked: this.properties.showBlank, }), PropertyPaneToggle('showResultsCount', { label: strings.ShowResultsCountLabel, checked: this.properties.showResultsCount, }), PropertyPaneChoiceGroup('selectedLayout', { label: strings.ResultsLayoutLabel, options: layoutOptions }), ]; return stylingFields; } /** * Gets template parameters fields */ private _getTemplateFieldsGroup(): IPropertyPaneGroup { let templateFieldsGroup: IPropertyPaneGroup = null; if (this._templatePropertyPaneOptions.length > 0) { templateFieldsGroup = { groupFields: this._templatePropertyPaneOptions, isCollapsed: false, groupName: strings.TemplateParameters.TemplateParametersGroupName }; } return templateFieldsGroup; } /** * Checks if all webpart properties have been configured */ private _isWebPartConfigured(): boolean { return true; } /** * Initializes the Web Part required properties if there are not present in the manifest (i.e. during an update scenario) */ private _initializeRequiredProperties() { this.properties.selectedLayout = (this.properties.selectedLayout !== undefined && this.properties.selectedLayout !== null) ? this.properties.selectedLayout : ResultsLayoutOption.People; this.properties.templateParameters = this.properties.templateParameters ? this.properties.templateParameters : {}; } /** * Initializes theme variant properties */ private _initThemeVariant(): void { // Consume the new ThemeProvider service this._themeProvider = this.context.serviceScope.consume(ThemeProvider.serviceKey); // If it exists, get the theme variant this._themeVariant = this._themeProvider.tryGetTheme(); // Register a handler to be notified if the theme variant changes this._themeProvider.themeChangedEvent.add(this, this._handleThemeChangedEvent.bind(this)); } /** * Update the current theme variant reference and re-render. * @param args The new theme */ private _handleThemeChangedEvent(args: ThemeChangedEventArgs): void { if (!isEqual(this._themeVariant, args.theme)) { this._themeVariant = args.theme; this.render(); } } /** * Opens the Web Part property pane */ private _setupWebPart() { this.context.propertyPane.open(); } private _validateNumber(value: string): string { let number = parseInt(value); if (isNaN(number)) { return strings.InvalidNumberIntervalMessage; } if (number < 1 || number > 999) { return strings.InvalidNumberIntervalMessage; } return ''; } }
the_stack
import { Component } from 'vue-property-decorator'; import { select } from 'd3-selection'; import Victor from 'victor'; import _ from 'lodash'; import $ from 'jquery'; import { Visualization, injectVisualizationTemplate, multiplyVisuals, Scale, AnyScale, getScale, drawAxis, DEFAULT_PLOT_MARGINS, LABEL_OFFSET_PX, PlotMargins, drawBrushBox, getBrushBox, isPointInBox, } from '@/components/visualization'; import template from './scatterplot.html'; import ColumnSelect from '@/components/column-select/column-select'; import { SELECTED_COLOR } from '@/common/constants'; import { isNumericalType } from '@/data/util'; import { fadeOut, getTransform } from '@/common/util'; import { VisualProperties } from '@/data/visuals'; import * as history from './history'; const DOMAIN_MARGIN = .1; interface ScatterplotSave { xColumn: number | null; yColumn: number | null; areXAxisTicksVisible: boolean; areYAxisTicksVisible: boolean; axisMargin: boolean; useDatasetRange: boolean; transparentBackground: boolean; } interface ScatterplotItemProps { index: number; x: number | string; y: number | string; visuals: VisualProperties; hasVisuals: boolean; selected: boolean; } const DEFAULT_ITEM_VISUALS: VisualProperties = { color: '#333', border: 'black', width: 1, size: 5, opacity: 1, }; const SELECTED_ITEM_VISUALS: VisualProperties = { color: 'white', border: SELECTED_COLOR, }; @Component({ template: injectVisualizationTemplate(template), components: { ColumnSelect, }, }) export default class Scatterplot extends Visualization { protected NODE_TYPE = 'scatterplot'; protected HAS_SETTINGS = true; // allow transparent background private xColumn: number | null = null; private yColumn: number | null = null; private margins: PlotMargins = { ...DEFAULT_PLOT_MARGINS, bottom: 20 }; private xScale!: Scale; private yScale!: Scale; private itemProps: ScatterplotItemProps[] = []; // When set, xScale ane yScale will be set to the dataset's domains private useDatasetRange = false; // Whether to have margin at the two sides of the axes. private axisMargin = true; private areXAxisTicksVisible = true; private areYAxisTicksVisible = true; // advanced settings private transparentBackground = false; public setXColumn(column: number) { this.xColumn = column; this.draw(); } public setYColumn(column: number) { this.yColumn = column; this.draw(); } public setTransitionDisabled(value: boolean) { this.isTransitionDisabled = value; } public applyColumns(columns: number[]) { if (columns.length === 0) { this.findDefaultColumns(); } else if (columns.length === 1) { this.xColumn = this.yColumn = columns[0]; } else { this.xColumn = columns[0]; this.yColumn = columns[1]; } this.draw(); } public setUseDatasetRange(value: boolean) { this.useDatasetRange = value; this.draw(); } public setXAxisTicksVisible(value: boolean) { this.areXAxisTicksVisible = value; this.draw(); } public setYAxisTicksVisible(value: boolean) { this.areYAxisTicksVisible = value; this.draw(); } public setAxisMargin(value: boolean) { this.axisMargin = value; this.draw(); } public setTransparentBackground(value: boolean) { this.backgroundColor = value ? 'none' : 'white'; } protected created() { this.serializationChain.push((): ScatterplotSave => ({ xColumn: this.xColumn, yColumn: this.yColumn, useDatasetRange: this.useDatasetRange, axisMargin: this.axisMargin, areXAxisTicksVisible: this.areXAxisTicksVisible, areYAxisTicksVisible: this.areYAxisTicksVisible, transparentBackground: this.transparentBackground, })); this.deserializationChain.push(nodeSave => { const save = nodeSave as ScatterplotSave; if (save.transparentBackground) { this.setTransparentBackground(true); } }); } protected draw() { if (!this.hasDataset()) { return; } if (this.xColumn === null || this.yColumn === null) { this.coverText = 'Please choose columns'; return; } this.coverText = ''; this.computeItemProps(); this.computeScales(); this.updateLeftMargin(); this.updateBottomMargin(); // Drawing must occur after scale computations. this.drawXAxis(); this.drawYAxis(); this.drawPoints(); } protected brushed(brushPoints: Point[], isBrushStop?: boolean) { if (isBrushStop) { this.computeBrushedItems(brushPoints); this.computeSelection(); this.computeItemProps(); this.drawPoints(); this.propagateSelection(); } drawBrushBox(this.$refs.brush as SVGElement, !isBrushStop ? brushPoints : []); } protected findDefaultColumns() { if (!this.hasDataset()) { return; } const dataset = this.getDataset(); const numericalColumns = dataset.getColumns().filter(column => isNumericalType(column.type)).slice(0, 2) .map(column => column.index); if (this.xColumn !== null) { this.xColumn = this.updateColumnOnDatasetChange(this.xColumn); } else { this.xColumn = numericalColumns.shift() || null; } if (this.yColumn !== null) { this.yColumn = this.updateColumnOnDatasetChange(this.yColumn); } else { this.yColumn = numericalColumns.shift() || null; } } private computeBrushedItems(brushPoints: Point[]) { if (brushPoints.length <= 1) { return; // ignore clicks } if (!this.isShiftPressed || !brushPoints.length) { this.selection.clear(); // reset selection if shift key is not down if (!brushPoints.length) { return; } } const box = getBrushBox(brushPoints); this.itemProps.forEach(props => { const point = { x: this.xScale(props.x), y: this.yScale(props.y) }; const clickToPointDistance = new Victor(point.x, point.y) .subtract(new Victor(brushPoints[0].x, brushPoints[0].y)).length(); if (isPointInBox(point, box) || clickToPointDistance <= (props.visuals.size as number) / 2) { this.selection.addItem(props.index); } }); } private computeItemProps() { const pkg = this.inputPortMap.in.getSubsetPackage(); const items = pkg.getItems(); this.itemProps = items.map(item => { const props: ScatterplotItemProps = { index: item.index, x: this.getDataset().getCellForScale(item, this.xColumn as number), y: this.getDataset().getCellForScale(item, this.yColumn as number), visuals: _.extend({}, DEFAULT_ITEM_VISUALS, item.visuals), hasVisuals: !_.isEmpty(item.visuals), selected: this.selection.hasItem(item.index), }; if (props.selected) { _.extend(props.visuals, SELECTED_ITEM_VISUALS); multiplyVisuals(props.visuals); } return props; }); } private drawPoints() { const useTransition = this.isTransitionFeasible(this.itemProps.length); const svgPoints = select(this.$refs.points as SVGGElement); let points = svgPoints.selectAll<SVGGraphicsElement, ScatterplotItemProps>('circle') .data(this.itemProps, d => d.index.toString()); if (useTransition) { fadeOut(points.exit()); } else { points.exit().remove(); } points = points.enter().append<SVGGraphicsElement>('circle') .attr('id', d => d.index.toString()) .merge(points) .attr('has-visuals', d => d.hasVisuals) .attr('is-selected', d => d.selected); const updatedPoints = useTransition ? points.transition() : points; updatedPoints .attr('cx', d => this.xScale(d.x)) .attr('cy', d => this.yScale(d.y)) .attr('r', d => (d.visuals.size as number / 2) + 'px') .style('fill', d => d.visuals.color as string) .style('stroke', d => d.visuals.border as string) .style('stroke-width', d => d.visuals.width + 'px') .style('opacity', d => d.visuals.opacity as number); this.moveSelectedPointsToFront(); } /** * Moves the selected points so that they appear above the other points to be clearly visible. * Elements that appear later in an SVG are rendered on the top. */ private moveSelectedPointsToFront() { const gPoints = this.$refs.points as SVGGElement; const $points = $(gPoints); $points.children('circle[has-visuals=true]').appendTo(gPoints); $points.children('circle[is-selected=true]').appendTo(gPoints); } private computeScales() { const items = this.inputPortMap.in.getSubsetPackage().getItemIndices(); const dataset = this.getDataset(); const xDomain = dataset.getDomain(this.xColumn as number, this.useDatasetRange ? undefined : items); const yDomain = dataset.getDomain(this.yColumn as number, this.useDatasetRange ? undefined : items); [this.xScale, this.yScale] = [ getScale(dataset.getColumnType(this.xColumn as number), xDomain, [this.margins.left, this.svgWidth - this.margins.right], { domainMargin: this.axisMargin ? DOMAIN_MARGIN : 0, }), getScale(dataset.getColumnType(this.yColumn as number), yDomain, [this.svgHeight - this.margins.bottom, this.margins.top], { domainMargin: this.axisMargin ? DOMAIN_MARGIN : 0, }), ]; } private drawXAxis() { drawAxis(this.$refs.xAxis as SVGElement, this.xScale, { classes: 'x', orient: 'bottom', ticks: !this.areXAxisTicksVisible ? 0 : undefined, transform: getTransform([0, this.svgHeight - this.margins.bottom]), label: { text: this.getDataset().getColumnName(this.xColumn as number), transform: getTransform([this.svgWidth - this.margins.right, -LABEL_OFFSET_PX]), }, }); } private drawYAxis() { drawAxis(this.$refs.yAxis as SVGElement, this.yScale, { classes: 'y', orient: 'left', ticks: !this.areYAxisTicksVisible ? 0 : undefined, transform: getTransform([this.margins.left, 0]), label: { text: this.getDataset().getColumnName(this.yColumn as number), transform: getTransform([LABEL_OFFSET_PX, this.margins.top], 1, 90), }, }); } /** * Determines the maximum length of the y axis ticks and sets the left margin accordingly. */ private updateLeftMargin() { this.drawYAxis(); this.updateMargins(() => { const maxTickWidth = _.max($(this.$refs.yAxis as SVGGElement) .find('.y > .tick > text') .map((index: number, element: SVGGraphicsElement) => element.getBBox().width)) || 0; this.margins.left = DEFAULT_PLOT_MARGINS.left + maxTickWidth; (this.xScale as AnyScale).range([this.margins.left, this.svgWidth - this.margins.right]); }); } /** * Determines the bottom margin depending on whether X axis ticks are shown. */ private updateBottomMargin() { this.drawXAxis(); this.updateMargins(() => { const maxTickHeight = _.max($(this.$refs.xAxis as SVGGElement) .find('.x > .tick > text') .map((index: number, element: SVGGraphicsElement) => element.getBBox().height)) || 0; this.margins.bottom = DEFAULT_PLOT_MARGINS.bottom + maxTickHeight; (this.yScale as AnyScale).range([this.svgHeight - this.margins.bottom, this.margins.top]); }); } private onSelectXColumn(column: number, prevColumn: number | null) { this.commitHistory(history.selectXColumnEvent(this, column, prevColumn)); this.setXColumn(column); } private onSelectYColumn(column: number, prevColumn: number | null) { this.commitHistory(history.selectYColumnEvent(this, column, prevColumn)); this.setYColumn(column); } private onToggleTransitionDisabled(value: boolean) { this.commitHistory(history.toggleTransitionDisabledEvent(this, value)); this.setTransitionDisabled(value); } private onToggleUseDatasetRange(value: boolean) { this.commitHistory(history.toggleUseDatasetRangeEvent(this, value)); this.setUseDatasetRange(value); } private onToggleXAxisTicksVisible(value: boolean) { this.commitHistory(history.toggleXAxisTicksVisibleEvent(this, value)); this.setXAxisTicksVisible(value); } private onToggleYAxisTicksVisible(value: boolean) { this.commitHistory(history.toggleYAxisTicksVisibleEvent(this, value)); this.setYAxisTicksVisible(value); } private onToggleAxisMargin(value: boolean) { this.commitHistory(history.toggleAxisMarginEvent(this, value)); this.setAxisMargin(value); } private onToggleTransparentBackground(value: boolean) { this.commitHistory(history.toggleTransparentBackgroundEvent(this, value)); this.setTransparentBackground(value); } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { TagContract, TagListByOperationOptionalParams, TagListByApiOptionalParams, TagListByProductOptionalParams, TagListByServiceOptionalParams, TagGetEntityStateByOperationOptionalParams, TagGetEntityStateByOperationResponse, TagGetByOperationOptionalParams, TagGetByOperationResponse, TagAssignToOperationOptionalParams, TagAssignToOperationResponse, TagDetachFromOperationOptionalParams, TagGetEntityStateByApiOptionalParams, TagGetEntityStateByApiResponse, TagGetByApiOptionalParams, TagGetByApiResponse, TagAssignToApiOptionalParams, TagAssignToApiResponse, TagDetachFromApiOptionalParams, TagGetEntityStateByProductOptionalParams, TagGetEntityStateByProductResponse, TagGetByProductOptionalParams, TagGetByProductResponse, TagAssignToProductOptionalParams, TagAssignToProductResponse, TagDetachFromProductOptionalParams, TagGetEntityStateOptionalParams, TagGetEntityStateResponse, TagGetOptionalParams, TagGetResponse, TagCreateUpdateParameters, TagCreateOrUpdateOptionalParams, TagCreateOrUpdateResponse, TagUpdateOptionalParams, TagUpdateResponse, TagDeleteOptionalParams } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a Tag. */ export interface Tag { /** * Lists all Tags associated with the Operation. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param operationId Operation identifier within an API. Must be unique in the current API Management * service instance. * @param options The options parameters. */ listByOperation( resourceGroupName: string, serviceName: string, apiId: string, operationId: string, options?: TagListByOperationOptionalParams ): PagedAsyncIterableIterator<TagContract>; /** * Lists all Tags associated with the API. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param options The options parameters. */ listByApi( resourceGroupName: string, serviceName: string, apiId: string, options?: TagListByApiOptionalParams ): PagedAsyncIterableIterator<TagContract>; /** * Lists all Tags associated with the Product. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param productId Product identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ listByProduct( resourceGroupName: string, serviceName: string, productId: string, options?: TagListByProductOptionalParams ): PagedAsyncIterableIterator<TagContract>; /** * Lists a collection of tags defined within a service instance. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ listByService( resourceGroupName: string, serviceName: string, options?: TagListByServiceOptionalParams ): PagedAsyncIterableIterator<TagContract>; /** * Gets the entity state version of the tag specified by its identifier. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param operationId Operation identifier within an API. Must be unique in the current API Management * service instance. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ getEntityStateByOperation( resourceGroupName: string, serviceName: string, apiId: string, operationId: string, tagId: string, options?: TagGetEntityStateByOperationOptionalParams ): Promise<TagGetEntityStateByOperationResponse>; /** * Get tag associated with the Operation. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param operationId Operation identifier within an API. Must be unique in the current API Management * service instance. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ getByOperation( resourceGroupName: string, serviceName: string, apiId: string, operationId: string, tagId: string, options?: TagGetByOperationOptionalParams ): Promise<TagGetByOperationResponse>; /** * Assign tag to the Operation. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param operationId Operation identifier within an API. Must be unique in the current API Management * service instance. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ assignToOperation( resourceGroupName: string, serviceName: string, apiId: string, operationId: string, tagId: string, options?: TagAssignToOperationOptionalParams ): Promise<TagAssignToOperationResponse>; /** * Detach the tag from the Operation. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param operationId Operation identifier within an API. Must be unique in the current API Management * service instance. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ detachFromOperation( resourceGroupName: string, serviceName: string, apiId: string, operationId: string, tagId: string, options?: TagDetachFromOperationOptionalParams ): Promise<void>; /** * Gets the entity state version of the tag specified by its identifier. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ getEntityStateByApi( resourceGroupName: string, serviceName: string, apiId: string, tagId: string, options?: TagGetEntityStateByApiOptionalParams ): Promise<TagGetEntityStateByApiResponse>; /** * Get tag associated with the API. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ getByApi( resourceGroupName: string, serviceName: string, apiId: string, tagId: string, options?: TagGetByApiOptionalParams ): Promise<TagGetByApiResponse>; /** * Assign tag to the Api. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ assignToApi( resourceGroupName: string, serviceName: string, apiId: string, tagId: string, options?: TagAssignToApiOptionalParams ): Promise<TagAssignToApiResponse>; /** * Detach the tag from the Api. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ detachFromApi( resourceGroupName: string, serviceName: string, apiId: string, tagId: string, options?: TagDetachFromApiOptionalParams ): Promise<void>; /** * Gets the entity state version of the tag specified by its identifier. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param productId Product identifier. Must be unique in the current API Management service instance. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ getEntityStateByProduct( resourceGroupName: string, serviceName: string, productId: string, tagId: string, options?: TagGetEntityStateByProductOptionalParams ): Promise<TagGetEntityStateByProductResponse>; /** * Get tag associated with the Product. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param productId Product identifier. Must be unique in the current API Management service instance. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ getByProduct( resourceGroupName: string, serviceName: string, productId: string, tagId: string, options?: TagGetByProductOptionalParams ): Promise<TagGetByProductResponse>; /** * Assign tag to the Product. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param productId Product identifier. Must be unique in the current API Management service instance. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ assignToProduct( resourceGroupName: string, serviceName: string, productId: string, tagId: string, options?: TagAssignToProductOptionalParams ): Promise<TagAssignToProductResponse>; /** * Detach the tag from the Product. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param productId Product identifier. Must be unique in the current API Management service instance. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ detachFromProduct( resourceGroupName: string, serviceName: string, productId: string, tagId: string, options?: TagDetachFromProductOptionalParams ): Promise<void>; /** * Gets the entity state version of the tag specified by its identifier. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ getEntityState( resourceGroupName: string, serviceName: string, tagId: string, options?: TagGetEntityStateOptionalParams ): Promise<TagGetEntityStateResponse>; /** * Gets the details of the tag specified by its identifier. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ get( resourceGroupName: string, serviceName: string, tagId: string, options?: TagGetOptionalParams ): Promise<TagGetResponse>; /** * Creates a tag. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param parameters Create parameters. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, serviceName: string, tagId: string, parameters: TagCreateUpdateParameters, options?: TagCreateOrUpdateOptionalParams ): Promise<TagCreateOrUpdateResponse>; /** * Updates the details of the tag specified by its identifier. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header * response of the GET request or it should be * for unconditional update. * @param parameters Update parameters. * @param options The options parameters. */ update( resourceGroupName: string, serviceName: string, tagId: string, ifMatch: string, parameters: TagCreateUpdateParameters, options?: TagUpdateOptionalParams ): Promise<TagUpdateResponse>; /** * Deletes specific tag of the API Management service instance. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param tagId Tag identifier. Must be unique in the current API Management service instance. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header * response of the GET request or it should be * for unconditional update. * @param options The options parameters. */ delete( resourceGroupName: string, serviceName: string, tagId: string, ifMatch: string, options?: TagDeleteOptionalParams ): Promise<void>; }
the_stack
import * as Immutable from "immutable"; import * as _ from "lodash"; import * as moment from "moment-timezone"; import Moment = moment.Moment; import { Duration, duration } from "./duration"; import { Index, index } from "./index"; import { period, Period } from "./period"; import { time } from "./time"; import { TimeRange, timerange } from "./timerange"; const UNITS = { n: { label: "nanoseconds", length: 1 / 1000000 }, u: { label: "microseconds", length: 1 / 1000 }, l: { label: "milliseconds", length: 1 }, s: { label: "seconds", length: 1000 }, m: { label: "minutes", length: 60 * 1000 }, h: { label: "hours", length: 60 * 60 * 1000 }, d: { label: "days", length: 60 * 60 * 24 * 1000 } }; /** * A value is valid if it isn't either undefined, null, or a NaN */ function isValid(v: number): boolean { return !(_.isUndefined(v) || _.isNaN(v) || _.isNull(v)); } /** * The last duration of time until now, represented as a `TimeRange` */ function untilNow(d: Duration): TimeRange { const t = new Date(); const begin = new Date(+t - +d); return new TimeRange(begin, t); } /** * Single zero left padding, for days and months. */ function leftPad(value: number): string { return `${value < 10 ? "0" : ""}${value}`; } const indexStringRegex = /^((([0-9]+)([smhdlun]))@)*(([0-9]+)([smhdlun]))(\+([0-9]+))*-([0-9]+)$/; /** * Returns a duration in milliseconds given a window period. * For example "30s" (30 seconds) should return 30000ms. Accepts * seconds (e.g. "30s"), minutes (e.g. "5m"), hours (e.g. "6h") and * days (e.g. "30d") as the period. */ function windowDuration(p: string): number { // window should be two parts, a number and a letter if it's a // range based index, e.g "1h". const parts = indexStringRegex.exec(p); if (parts && parts.length >= 3) { const num = parseInt(parts[1], 10); const unit = parts[2]; return num * UNITS[unit].length * 1000; } } export interface DecodedIndexString { decodedPeriod: Period; decodedDuration: Duration; decodedIndex: number; } /** * Decodes a period based index string. The result is a structure containing: * - decodedPeriod * - decodedDuration * - decodedIndex */ function decodeIndexString(indexString: string): DecodedIndexString { const parts = indexStringRegex.exec(indexString); const [g1, d, g2, g3, g4, frequency, g6, g7, g8, offset, i] = parts; const decodedPeriod = period(duration(frequency), offset ? time(parseInt(offset, 10)) : null); const decodedDuration = d ? duration(d) : decodedPeriod.frequency(); const decodedIndex = parseInt(i, 10); return { decodedPeriod, decodedDuration, decodedIndex }; } function isIndexString(indexString: string): boolean { return indexStringRegex.test(indexString); } /** * Helper function to get the window position relative * to Jan 1, 1970. */ function windowPositionFromDate(p: string, date: Date) { const d = this.windowDuration(p); let dd = moment.utc(date).valueOf(); return Math.floor((dd /= d)); } /** * Given an index string, return the `TimeRange` that represents. This is the * main parsing function as far as taking an index string and decoding it into * the timerange that it represents. For example, this is how the Index * constructor is able to take a string and represent a timerange. It is also * used when windowing to determine trigger times. */ function timeRangeFromIndexString(indexString: string, tz: string = "Etc/UTC"): TimeRange { const parts = indexString.split("-"); let beginTime: Moment; let endTime: Moment; switch (parts.length) { case 3: // A day, month and year e.g. 2014-10-24 if ( !_.isNaN(parseInt(parts[0], 10)) && !_.isNaN(parseInt(parts[1], 10)) && !_.isNaN(parseInt(parts[2], 10)) ) { const parsedYear = parseInt(parts[0], 10); const parsedMonth = parseInt(parts[1], 10); const parsedDay = parseInt(parts[2], 10); beginTime = moment.tz([parsedYear, parsedMonth - 1, parsedDay], tz); endTime = moment.tz([parsedYear, parsedMonth - 1, parsedDay], tz).endOf("day"); } break; case 2: if (isIndexString(indexString)) { // Period index string e.g. 1d-1234 const { decodedPeriod, decodedDuration, decodedIndex } = decodeIndexString( indexString ); const beginTimestamp = decodedIndex * +decodedPeriod.frequency(); const endTimestamp = beginTimestamp + +decodedDuration; beginTime = moment(beginTimestamp).tz(tz); endTime = moment(endTimestamp).tz(tz); } else if (!_.isNaN(parseInt(parts[0], 10)) && !_.isNaN(parseInt(parts[1], 10))) { // A month and year e.g 2015-09 const parsedYear = parseInt(parts[0], 10); const parsedMonth = parseInt(parts[1], 10); beginTime = moment.tz([parsedYear, parsedMonth - 1], tz); endTime = moment.tz([parsedYear, parsedMonth - 1], tz).endOf("month"); } break; // A year e.g. 2015 case 1: const year = parseInt(parts[0], 10); beginTime = moment.tz([year], tz); endTime = moment.tz([year], tz).endOf("year"); break; } if (beginTime && beginTime.isValid() && endTime && endTime.isValid()) { return timerange(beginTime, endTime); } else { return undefined; } } /** * Returns a nice string for an index string. If the index string is of * the form 1d-2345 then just that string is returned (there's not nice * way to put it), but if it represents a day, month, or year * (e.g. 2015-07) then a nice string like "July" will be returned. It's * also possible to pass in the format of the reply for these types of * strings. See moment's format naming conventions: * http://momentjs.com/docs/#/displaying/format/ */ function niceIndexString(indexString: string, format: string): string { let t; const parts = indexString.split("-"); switch (parts.length) { case 3: if ( !_.isNaN(parseInt(parts[0], 10)) && !_.isNaN(parseInt(parts[1], 10)) && !_.isNaN(parseInt(parts[2], 10)) ) { const parsedYear = parseInt(parts[0], 10); const parsedMonth = parseInt(parts[1], 10); const parsedDay = parseInt(parts[2], 10); t = moment.utc([parsedYear, parsedMonth - 1, parsedDay]); if (format) { return t.format(format); } else { return t.format("MMMM Do YYYY"); } } break; case 2: if (isIndexString(indexString)) { return indexString; } else if (!_.isNaN(parseInt(parts[0], 10)) && !_.isNaN(parseInt(parts[1], 10))) { const parsedYear = parseInt(parts[0], 10); const parsedMonth = parseInt(parts[1], 10); t = moment.utc([parsedYear, parsedMonth - 1]); if (format) { return t.format(format); } else { return t.format("MMMM"); } } break; case 1: const year = parts[0]; t = moment.utc([year]); if (format) { return t.format(format); } else { return t.format("YYYY"); } } return indexString; } /** * Returns true if the value is null, undefined or NaN */ function isMissing(val: any): boolean { return _.isNull(val) || _.isUndefined(val) || _.isNaN(val); } /** * Function to turn a constructor args into a timestamp */ function timestampFromArg(arg: number | string | Date | Moment): Date { if (_.isNumber(arg)) { return new Date(arg); } else if (_.isString(arg)) { return new Date(+arg); } else if (_.isDate(arg)) { return new Date(arg.getTime()); } else if (moment.isMoment(arg)) { return new Date(arg.valueOf()); } else { throw new Error( `Unable to get timestamp from ${arg}. Should be a number, date, or moment.` ); } } /** * Function to turn a constructor args into a `TimeRange` */ function timeRangeFromArg(arg: TimeRange | string | Date[]): TimeRange { if (arg instanceof TimeRange) { return arg; } else if (_.isString(arg)) { const [begin, end] = arg.split(","); return new TimeRange(+begin, +end); } else if (_.isArray(arg) && arg.length === 2) { const argArray = arg as Date[]; return new TimeRange(argArray[0], argArray[1]); } else { throw new Error(`Unable to parse timerange. Should be a TimeRange. Got ${arg}.`); } } /** * Function to turn a constructor of two args into an `Index`. * The second arg defines the timezone (local or UTC) */ function indexFromArgs(arg1: string | Index, arg2: string = "Etc/UTC"): Index { if (_.isString(arg1)) { return index(arg1, arg2); } else if (arg1 instanceof Index) { return arg1; } else { throw new Error(`Unable to get index from ${arg1}. Should be a string or Index.`); } } /** * Function to turn a constructor arg into an `Immutable.Map` * of data. */ function dataFromArg( arg: {} | Immutable.Map<string, any> | number | string ): Immutable.Map<string, any> { let data; if (_.isObject(arg)) { // Deeply convert the data to Immutable Map data = Immutable.fromJS(arg); } else if (data instanceof Immutable.Map) { // Copy reference to the data data = arg; } else if (_.isNumber(arg) || _.isString(arg)) { // Just add it to the value key of a new Map // e.g. new Event(t, 25); -> t, {value: 25} data = Immutable.Map({ value: arg }); } else { throw new Error(`Unable to interpret event data from ${arg}.`); } return data; } /** * Convert the `field spec` into a list if it is not already. */ function fieldAsArray(field: string | string[]): string[] { if (_.isArray(field)) { return field; } else if (_.isString(field)) { return field.split("."); } } export default { dataFromArg, fieldAsArray, indexFromArgs, isMissing, isValid, leftPad, isIndexString, decodeIndexString, niceIndexString, timeRangeFromArg, timeRangeFromIndexString, timestampFromArg, untilNow, windowDuration, windowPositionFromDate };
the_stack
import { needs, NodeEncryptionMaterial, NodeDecryptionMaterial, unwrapDataKey, wrapWithKeyObjectIfSupported, AwsEsdkKeyObject, NodeHash, } from '@aws-crypto/material-management' import { createCipheriv, createDecipheriv, createSign, createVerify, timingSafeEqual, } from 'crypto' import { HKDF } from '@aws-crypto/hkdf-node' import { kdfInfo, kdfCommitKeyInfo } from '@aws-crypto/serialize' import { AwsESDKSigner, AwsESDKVerify } from './types' export interface AwsEsdkJsCipherGCM { update(data: Buffer): Buffer final(): Buffer getAuthTag(): Buffer setAAD(aad: Buffer): this } export interface AwsEsdkJsDecipherGCM { update(data: Buffer): Buffer final(): Buffer setAuthTag(buffer: Buffer): this setAAD(aad: Buffer): this } type KDFIndex = Readonly<{ [K in NodeHash]: ReturnType<typeof HKDF> }> const kdfIndex: KDFIndex = Object.freeze({ sha256: HKDF('sha256' as NodeHash), sha384: HKDF('sha384' as NodeHash), sha512: HKDF('sha512' as NodeHash), }) export interface GetCipher { (iv: Uint8Array): AwsEsdkJsCipherGCM } export interface GetCipherInfo { (messageId: Uint8Array): { getCipher: GetCipher keyCommitment?: Uint8Array } } export interface GetSigner { (): AwsESDKSigner & { awsCryptoSign: () => Buffer } } export interface NodeEncryptionMaterialHelper { getCipherInfo: GetCipherInfo getSigner?: GetSigner dispose: () => void } export interface GetEncryptHelper { (material: NodeEncryptionMaterial): NodeEncryptionMaterialHelper } export const getEncryptHelper: GetEncryptHelper = ( material: NodeEncryptionMaterial ) => { /* Precondition: NodeEncryptionMaterial must have a valid data key. */ needs(material.hasValidKey(), 'Material has no unencrypted data key.') const { signatureHash } = material.suite /* Conditional types can not narrow the return type :( * Function overloads "works" but then I can not export * the function and have eslint be happy (Multiple exports of name) */ const getCipherInfo = curryCryptoStream(material, createCipheriv) return Object.freeze({ getCipherInfo, getSigner: signatureHash ? getSigner : undefined, dispose, }) function getSigner() { /* Precondition: The NodeEncryptionMaterial must have not been zeroed. * hasUnencryptedDataKey will check that the unencrypted data key has been set * *and* that it has not been zeroed. At this point it must have been set * because the KDF function operated on it. So at this point * we are protecting that someone has zeroed out the material * because the Encrypt process has been complete. */ needs( material.hasUnencryptedDataKey, 'Unencrypted data key has been zeroed.' ) if (!signatureHash) throw new Error('Material does not support signature.') const { signatureKey } = material if (!signatureKey) throw new Error('Material does not support signature.') const { privateKey } = signatureKey if (typeof privateKey !== 'string') throw new Error('Material does not support signature.') const signer = Object.assign( createSign(signatureHash), // don't export the private key if we don't have to { awsCryptoSign: () => signer.sign(privateKey) } ) return signer } function dispose() { material.zeroUnencryptedDataKey() } } export interface GetDecipher { (iv: Uint8Array): AwsEsdkJsDecipherGCM } export interface GetDecipherInfo { (messageId: Uint8Array, commitKey?: Uint8Array): GetDecipher } export interface GetVerify { (): AwsESDKVerify & { awsCryptoVerify: (signature: Buffer) => boolean } } export interface NodeDecryptionMaterialHelper { getDecipherInfo: GetDecipherInfo getVerify?: GetVerify dispose: () => void } export interface GetDecryptionHelper { (material: NodeDecryptionMaterial): NodeDecryptionMaterialHelper } export const getDecryptionHelper: GetDecryptionHelper = ( material: NodeDecryptionMaterial ) => { /* Precondition: NodeDecryptionMaterial must have a valid data key. */ needs(material.hasValidKey(), 'Material has no unencrypted data key.') const { signatureHash } = material.suite /* Conditional types can not narrow the return type :( * Function overloads "works" but then I can not export * the function and have eslint be happy (Multiple exports of name) */ const getDecipherInfo = curryCryptoStream(material, createDecipheriv) return Object.freeze({ getDecipherInfo, getVerify: signatureHash ? getVerify : undefined, dispose, }) function getVerify() { if (!signatureHash) throw new Error('Material does not support signature.') const { verificationKey } = material if (!verificationKey) throw new Error('Material does not support signature.') const verify = Object.assign( createVerify(signatureHash), // explicitly bind the public key for this material { awsCryptoVerify: (signature: Buffer) => // As typescript gets better typing // We should consider either generics or // 2 different verificationKeys for Node and WebCrypto verify.verify(verificationKey.publicKey as string, signature), } ) return verify } function dispose() { material.zeroUnencryptedDataKey() } } type CreateCryptoIvStream< Material extends NodeEncryptionMaterial | NodeDecryptionMaterial > = Material extends NodeEncryptionMaterial ? typeof createCipheriv : typeof createDecipheriv type CryptoStream< Material extends NodeEncryptionMaterial | NodeDecryptionMaterial > = Material extends NodeEncryptionMaterial ? AwsEsdkJsCipherGCM : AwsEsdkJsDecipherGCM type CreateCryptoStream< Material extends NodeEncryptionMaterial | NodeDecryptionMaterial > = (iv: Uint8Array) => CryptoStream<Material> type CurryHelper< Material extends NodeEncryptionMaterial | NodeDecryptionMaterial > = Material extends NodeEncryptionMaterial ? { getCipher: CreateCryptoStream<Material> keyCommitment: Uint8Array } : Material extends NodeDecryptionMaterial ? CreateCryptoStream<Material> : never export function curryCryptoStream< Material extends NodeEncryptionMaterial | NodeDecryptionMaterial >(material: Material, createCryptoIvStream: CreateCryptoIvStream<Material>) { const { encryption: cipherName, ivLength } = material.suite const isEncrypt = material instanceof NodeEncryptionMaterial /* Precondition: material must be either NodeEncryptionMaterial or NodeDecryptionMaterial. * */ needs( isEncrypt ? createCipheriv === createCryptoIvStream : material instanceof NodeDecryptionMaterial ? createDecipheriv === createCryptoIvStream : false, 'Unsupported cryptographic material.' ) return (messageId: Uint8Array, commitKey?: Uint8Array) => { const { derivedKey, keyCommitment } = nodeKdf( material, messageId, commitKey ) return ( isEncrypt ? { getCipher: createCryptoStream, keyCommitment } : createCryptoStream ) as CurryHelper<Material> function createCryptoStream(iv: Uint8Array): CryptoStream<Material> { /* Precondition: The length of the IV must match the NodeAlgorithmSuite specification. */ needs( iv.byteLength === ivLength, 'Iv length does not match algorithm suite specification' ) /* Precondition: The material must have not been zeroed. * hasUnencryptedDataKey will check that the unencrypted data key has been set * *and* that it has not been zeroed. At this point it must have been set * because the KDF function operated on it. So at this point * we are protecting that someone has zeroed out the material * because the Encrypt process has been complete. */ needs( material.hasUnencryptedDataKey, 'Unencrypted data key has been zeroed.' ) /* createDecipheriv is incorrectly typed in @types/node. It should take key: CipherKey, not key: BinaryLike. * Also, the check above ensures * that _createCryptoStream is not false. * But TypeScript does not believe me. * For any complicated code, * you should defer to the checker, * but here I'm going to assert * it is simple enough. */ return createCryptoIvStream( cipherName, derivedKey as any, iv ) as unknown as CryptoStream<Material> } } } export function nodeKdf( material: NodeEncryptionMaterial | NodeDecryptionMaterial, nonce: Uint8Array, commitKey?: Uint8Array ): { derivedKey: Uint8Array | AwsEsdkKeyObject keyCommitment?: Uint8Array } { const dataKey = material.getUnencryptedDataKey() const { kdf, kdfHash, keyLengthBytes, commitmentLength, saltLengthBytes, commitment, id: suiteId, } = material.suite /* Check for early return (Postcondition): No Node.js KDF, just return the unencrypted data key. */ if (!kdf && !kdfHash) { /* Postcondition: Non-KDF algorithm suites *must* not have a commitment. */ needs(!commitKey, 'Commitment not supported.') return { derivedKey: dataKey } } /* Precondition: Valid HKDF values must exist for Node.js. */ needs( kdf === 'HKDF' && kdfHash && kdfIndex[kdfHash] && nonce instanceof Uint8Array, 'Invalid HKDF values.' ) /* The unwrap is done once we *know* that a KDF is required. * If we unwrapped before everything will work, * but we may be creating new copies of the unencrypted data key (export). */ const { buffer: dkBuffer, byteOffset: dkByteOffset, byteLength: dkByteLength, } = unwrapDataKey(dataKey) if (commitment === 'NONE') { /* Postcondition: Non-committing Node algorithm suites *must* not have a commitment. */ needs(!commitKey, 'Commitment not supported.') const toExtract = Buffer.from(dkBuffer, dkByteOffset, dkByteLength) const { buffer, byteOffset, byteLength } = kdfInfo(suiteId, nonce) const infoBuff = Buffer.from(buffer, byteOffset, byteLength) const derivedBytes = kdfIndex[kdfHash as NodeHash](toExtract)( keyLengthBytes, infoBuff ) const derivedKey = wrapWithKeyObjectIfSupported(derivedBytes) return { derivedKey } } /* Precondition UNTESTED: Committing suites must define expected values. */ needs( commitment === 'KEY' && commitmentLength && saltLengthBytes, 'Malformed suite data.' ) /* Precondition: For committing algorithms, the nonce *must* be 256 bit. * i.e. It must target a V2 message format. */ needs( nonce.byteLength === saltLengthBytes, 'Nonce is not the correct length for committed algorithm suite.' ) const toExtract = Buffer.from(dkBuffer, dkByteOffset, dkByteLength) const expand = kdfIndex[kdfHash as NodeHash](toExtract, nonce) const { keyLabel, commitLabel } = kdfCommitKeyInfo(material.suite) const keyCommitment = expand(commitmentLength / 8, commitLabel) const isDecrypt = material instanceof NodeDecryptionMaterial /* Precondition: If material is NodeDecryptionMaterial the key commitments *must* match. * This is also the preferred location to check, * because then the decryption key is never even derived. */ needs( (isDecrypt && commitKey && timingSafeEqual(keyCommitment, commitKey)) || (!isDecrypt && !commitKey), isDecrypt ? 'Commitment does not match.' : 'Invalid arguments.' ) const derivedBytes = expand(keyLengthBytes, keyLabel) const derivedKey = wrapWithKeyObjectIfSupported(derivedBytes) return { derivedKey, keyCommitment } }
the_stack
import "mocha"; import * as expect from "expect"; import { DefaultZxSpectrumStateManager, loadWaModule, SilentAudioRenderer, } from "../helpers"; import { setEngineDependencies } from "../../../src/renderer/machines/core/vm-engine-dependencies"; import { ZxSpectrum48Core } from "../../../src/renderer/machines/zx-spectrum/ZxSpectrum48Core"; import { SpectrumMachineStateBase } from "../../../src/renderer/machines/zx-spectrum/ZxSpectrumCoreBase"; import { EmulationMode, ExecuteCycleOptions, } from "../../../src/core/abstractions/vm-core-types"; import { MemoryHelper } from "../../../src/renderer/machines/wa-interop/memory-helpers"; import { COLORIZATION_BUFFER, PIXEL_RENDERING_BUFFER, } from "../../../src/renderer/machines/wa-interop/memory-map"; let machine: ZxSpectrum48Core; // --- Set up the virual machine engine service with the setEngineDependencies({ waModuleLoader: (n) => loadWaModule(n), sampleRateGetter: () => 48000, audioRendererFactory: () => new SilentAudioRenderer(), spectrumStateManager: new DefaultZxSpectrumStateManager(), }); describe("ZX Spectrum 48 - Screen", () => { before(async () => { machine = new ZxSpectrum48Core({ baseClockFrequency: 3_276_800, tactsInFrame: 16384, firmware: [new Uint8Array(32768)], }); await machine.setupMachine(); }); beforeEach(async () => { await machine.setupMachine(); }); it("ULA frame tact is OK", () => { const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s.tactsInFrame).toBe(69888); }); it("Flash toggle rate is OK", () => { const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s.flashFrames).toBe(25); }); it("Setting border value does not change invisible area", () => { machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x10, 0x00, // LD BC,$0010 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0xfb, // EI 0x76, // HALT ]); fillPixelBuffer(0xff); machine.executeFrame(new ExecuteCycleOptions(EmulationMode.UntilHalt)); const s = machine.getMachineState(); expect(s._pc).toBe(0x800e); expect(s.tacts).toBe(451); expect(s.frameCompleted).toBe(false); const mh = new MemoryHelper(machine.api, PIXEL_RENDERING_BUFFER); let sum = 0x00; for (let row = 0; row < s.screenHeight; row++) { for (let col = 0; col < s.screenWidth; col++) { sum += mh.readByte(row * s.screenWidth + col); } } expect(sum).toBe(0xff * s.screenHeight * s.screenWidth); }); it("Setting border value changes border area #1", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x8d, 0x00, // LD BC,$008C 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0x76, // HALT ]); fillPixelBuffer(0xff); machine.executeFrame(new ExecuteCycleOptions(EmulationMode.UntilHalt)); const s = machine.getMachineState() as SpectrumMachineStateBase; console.log(s.executionCompletionReason); console.log(s.tacts); expect(s._pc).toBe(0x800d); expect(s.tacts).toBe(3697); expect(s.frameCompleted).toBe(false); expect(s.borderColor).toBe(0x05); const mh = new MemoryHelper(machine.api, PIXEL_RENDERING_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let col = 0; col < 220; col++) { const pixel = mh.readByte(col); sum += pixel; } expect(sum).toBe(0x05 * 220); // --- Remaining line should be 0xff sum = 0; for (let col = 220; col < s.screenWidth; col++) { const pixel = mh.readByte(col); sum += pixel; } expect(sum).toBe(0xff * (s.screenWidth - 220)); // --- Remaining screen part should be 0xff sum = 0x00; for (let row = 1; row < s.screenHeight; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0xff * s.screenWidth * (s.screenHeight - 1)); }); it("Setting border value changes border area #2", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x26, 0x02, // LD BC,$0226 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0x76, // HALT ]); fillPixelBuffer(0xff); machine.executeFrame(new ExecuteCycleOptions(EmulationMode.UntilHalt)); const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s._pc).toBe(0x800d); expect(s.tacts).toBe(14331); expect(s.frameCompleted).toBe(false); expect(s.borderColor).toBe(0x05); const mh = new MemoryHelper(machine.api, PIXEL_RENDERING_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let row = 0; row < 47; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * 47); // --- Remaining line should be 0xff sum = 0; for (let col = 220; col < s.screenWidth; col++) { const pixel = mh.readByte(48 * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0xff * (s.screenWidth - 220)); // --- Remaining screen part should be 0xff sum = 0x00; const lastLine = s.lastDisplayLine + s.borderBottomLines; for (let row = 48; row < lastLine; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0xff * s.screenWidth * (lastLine - 48)); }); it("Setting border value changes border area #3", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x29, 0x02, // LD BC,$0229 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0xfb, // EI 0x76, // HALT ]); fillPixelBuffer(0xff); machine.executeFrame(new ExecuteCycleOptions(EmulationMode.UntilHalt)); const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s._pc).toBe(0x800e); expect(s.tacts).toBe(14413); expect(s.frameCompleted).toBe(false); expect(s.borderColor).toBe(0x05); const mh = new MemoryHelper(machine.api, PIXEL_RENDERING_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let row = 0; row < 47; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * 47); // --- The left border of row 48 should be set to 0x05 sum = 0; for (let col = 0; col < 48; col++) { const pixel = mh.readByte(48 * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * 48); // --- The first 112 pixels of the first display row (48) should be set to 0 sum = 0; for (let col = 48; col < 148; col++) { const pixel = mh.readByte(48 * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x00); // --- Remaining screen part should be 0xff sum = 0x00; const lastLine = s.lastDisplayLine + s.borderBottomLines; for (let row = 49; row < lastLine; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0xff * s.screenWidth * (lastLine - 49)); }); it("Border + empty pixels", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x75, 0x0a, // LD BC,$0A75 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0x76, // HALT ]); fillPixelBuffer(0xff); machine.executeFrame(new ExecuteCycleOptions(EmulationMode.UntilHalt)); const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s._pc).toBe(0x800d); expect(s.tacts).toBe(69633); expect(s.frameCompleted).toBe(false); expect(s.borderColor).toBe(0x05); const mh = new MemoryHelper(machine.api, PIXEL_RENDERING_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let row = 0; row < 48; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * 48); // --- The left border of row 48 should be set to 0x05 sum = 0; for (let col = 0; col < 48; col++) { const pixel = mh.readByte(48 * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * 48); // --- Display rows should have a border value of 0x05 and a pixel value of 0x00 for (let row = 48; row < 48 + 192; row++) { sum = 0x00; for (let col = 0; col < s.borderLeftPixels; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * s.borderLeftPixels); sum = 0x00; for ( let col = s.borderLeftPixels; col < s.screenWidth - s.borderRightPixels; col++ ) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x00); sum = 0x00; for ( let col = s.screenWidth - s.borderRightPixels; col < s.screenWidth; col++ ) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * s.borderRightPixels); } sum = 0; for (let row = 48 + 192; row < s.screenHeight; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * (s.screenHeight - 192 - 48)); }); it("Rendering with pattern #1", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x75, 0x0a, // LD BC,$0A75 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0x76, // HALT ]); fillPixelBuffer(0xff); let mh = new MemoryHelper(machine.api, 0); for (let addr = 0x4000; addr < 0x5800; addr++) { machine.writeMemory(addr, addr & 0x0100 ? 0xaa : 0x55); } for (let addr = 0x5800; addr < 0x5b00; addr++) { machine.writeMemory(addr, 0x51); } machine.executeFrame(new ExecuteCycleOptions(EmulationMode.UntilHalt)); const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s._pc).toBe(0x800d); expect(s.tacts).toBe(69633); expect(s.frameCompleted).toBe(false); expect(s.borderColor).toBe(0x05); mh = new MemoryHelper(machine.api, PIXEL_RENDERING_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let row = 0; row < 48; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * 48); // --- The left border of row 48 should be set to 0x05 sum = 0; for (let col = 0; col < 48; col++) { const pixel = mh.readByte(48 * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * 48); // --- Display rows should have a border value of 0x05 and a pixel value of 0x00 for (let row = 48; row < 48 + 192; row++) { sum = 0x00; for (let col = 0; col < s.borderLeftPixels; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * s.borderLeftPixels); sum = 0x00; let expectedSum = 0x00; for ( let col = s.borderLeftPixels; col < s.screenWidth - s.borderRightPixels; col++ ) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; expectedSum += (row + col) % 2 ? 0x09 : 0x0a; } expect(sum).toBe(expectedSum); sum = 0x00; for ( let col = s.screenWidth - s.borderRightPixels; col < s.screenWidth; col++ ) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * s.borderRightPixels); } sum = 0; for (let row = 48 + 192; row < s.screenHeight; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * (s.screenHeight - 192 - 48)); }); it("Rendering until frame ends", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x75, 0x0a, // LD BC,$0A75 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0x76, // HALT ]); fillPixelBuffer(0xff); let mh = new MemoryHelper(machine.api, 0); for (let addr = 0x4000; addr < 0x5800; addr++) { machine.writeMemory(addr, addr & 0x0100 ? 0xaa : 0x55); } for (let addr = 0x5800; addr < 0x5b00; addr++) { machine.writeMemory(addr, 0x51); } machine.executeFrame(new ExecuteCycleOptions(EmulationMode.UntilFrameEnds)); const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s._pc).toBe(0x800d); expect(s.frameCompleted).toBe(true); expect(s.borderColor).toBe(0x05); mh = new MemoryHelper(machine.api, PIXEL_RENDERING_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let row = 0; row < 48; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * 48); // --- The left border of row 48 should be set to 0x05 sum = 0; for (let col = 0; col < 48; col++) { const pixel = mh.readByte(48 * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * 48); // --- Display rows should have a border value of 0x05 and a pixel value of 0x00 for (let row = 48; row < 48 + 192; row++) { sum = 0x00; for (let col = 0; col < s.borderLeftPixels; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * s.borderLeftPixels); sum = 0x00; let expectedSum = 0x00; for ( let col = s.borderLeftPixels; col < s.screenWidth - s.borderRightPixels; col++ ) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; expectedSum += (row + col) % 2 ? 0x09 : 0x0a; } expect(sum).toBe(expectedSum); sum = 0x00; for ( let col = s.screenWidth - s.borderRightPixels; col < s.screenWidth; col++ ) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * s.borderRightPixels); } sum = 0; for (let row = 48 + 192; row < s.screenHeight; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * (s.screenHeight - 192 - 48)); }); it("Colorize border + empty pixels", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x75, 0x0a, // LD BC,$0A75 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0x76, // HALT ]); fillPixelBuffer(0xff); machine.executeFrame(new ExecuteCycleOptions(EmulationMode.UntilHalt)); machine.api.colorize(); const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s._pc).toBe(0x800d); expect(s.tacts).toBe(69633); expect(s.frameCompleted).toBe(false); expect(s.borderColor).toBe(0x05); const mh = new MemoryHelper(machine.api, COLORIZATION_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let row = 0; row < 48; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readUint32((row * s.screenWidth + col) * 4); if (pixel === 0xffaaaa00 - 0x100000000) { sum++; } } } }); }); /** * * @param data Pixel buffer data */ function fillPixelBuffer(data: number): void { const s = machine.getMachineState() as SpectrumMachineStateBase; const mh = new MemoryHelper(machine.api, PIXEL_RENDERING_BUFFER); const visibleLines = s.screenHeight - s.nonVisibleBorderTopLines - s.nonVisibleBorderTopLines; const visibleColumns = (s.screenLineTime - s.nonVisibleBorderRightTime) * 2; const pixels = visibleLines * visibleColumns; for (let i = 0; i < pixels; i++) { mh.writeByte(i, data); } }
the_stack
import * as React from 'react'; export interface AppProps { /** * Called when the quit menu item is called, right before the entire app quits. */ onShouldQuit?: () => void; } /** * The app is the container for the entire program and holds Windows and Menus. */ export class App extends React.Component<AppProps> { } export interface AreaBaseProps extends GridChildrenProps, Label, Stretchy { /** * The fill color for the component. */ fill?: string; /** * The opacity of the fill (between 0 and 1). Gets multiplied with the fill colors alpha value. */ fillOpacity?: number; /** * The stroke (line) color for the component. */ stroke?: string; strokeLinecap?: 'flat' | 'round' | 'bevel'; strokeLinejoin?: 'miter' | 'round' | 'bevel'; /** * How far to extend the stroke at a sharp corner when using `strokeLinejoin='miter'` * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit * for a more detailed explanation. */ strokeMiterlimit?: number; /** * The opacity of the stroke (between 0 and 1). Gets multiplied with the stroke colors alpha value. */ strokeOpacity?: number; strokeWidth?: number; /** * List of transformations to apply to the component (are quite similar to SVG transformations). Example for multiple transformations: `transform="translate(100, 100) rotate(90)"`. * * All x and y coordinates specified in a transformation are relative _to the component itself_, meaning that `translate(-50%, 0)` will translate the component by 50% of it's own width to left. */ transform?: string; } export interface AreaRectangleProps extends AreaBaseProps { /** * The height of the rectangle. */ height: number | string; /** * The width of the rectangle. */ width: number | string; /** * The x coordinate of the rectangles top left corner. */ x: number | string; /** * The y coordinate of the rectangles top left corner. */ y: number | string; } /** * A rectangle to be displayed in an Area component. */ export class AreaRectangle extends React.Component<AreaRectangleProps> { } export interface AreaLineProps extends AreaBaseProps { /** * The x coordinate of the line's start point. */ x1: number | string; /** * The x coordinate of the line's end point. */ x2: number | string; /** * The y coordinate of the line's start point. */ y1: number | string; /** * The y coordinate of the line's end point. */ y2: number | string; } export class AreaLine extends React.Component<AreaLineProps> { } export interface AreaCircleProps extends AreaBaseProps { /** * The circle's radius. Percentage values use the Area's width. */ r: number | string; /** * The x coordinate of the center of the cirle. */ x: number | string; /** * The y coordinate of the center of the cirle. */ y: number | string; } export class AreaCircle extends React.Component<AreaCircleProps> { } export interface AreaBezierProps extends AreaBaseProps { /** * The x coordinate of the curve's control point at the start. */ cx1: number | string; /** * The x coordinate of the curve's control point at the end. */ cx2: number | string; /** * The y coordinate of the curve's control point at the start. */ cy1: number | string; /** * The y coordinate of the curve's control point at the end. */ cy2: number | string; /** * The x coordinate of the curve's start point. */ x1: number | string; /** * The x coordinate of the curve's end point. */ x2: number | string; /** * The y coordinate of the curve's start point. */ y1: number | string; /** * The y coordinate of the curve's end point. */ y2: number | string; } export class AreaBezier extends React.Component<AreaBezierProps> { } export interface AreaPathProps extends AreaBaseProps { /** * A string describing the path (uses SVG's path syntax, explanation @see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths). * * A warning is displayed whan an unimplemented shaped are used (Quadratic Beziers and Arcs). */ d: string; /** * Sets the methods how to determine wheter to fill a path. Explanation @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule. */ fillMode: 'nonzero' | 'evenodd'; } export class AreaPath extends React.Component<AreaPathProps> { } export interface AreaTextProps extends StyledTextProps, AreaBaseProps { } export class AreaText extends React.Component<AreaTextProps> { } export interface AreaGroupProps extends AreaBaseProps { /** * Specify `width` and `height` to be able to use percentage values in transforms. */ width?: number | string; /** * Specify `width` and `height` to be able to use percentage values in transforms. */ height?: number | string; } export class AreaGroup extends React.Component<AreaGroupProps> { } export interface MouseEvent { button: number; height: number; width: number; x: number; y: number; } export interface KeyboardEvent { extKey: number; key: string; modifierKey: number; modifiers: number; } export interface AreaProps extends AreaBaseProps { /** * Called when releasing a key. Return `true` to signal that this event got handled (always returning true will disable any menu accelerators). */ onKeyDown?: (event: KeyboardEvent) => boolean; /** * Called when pressing a key. Return `true` to signal that this event got handled (always returning true will disable any menu accelerators). */ onKeyUp?: (event: KeyboardEvent) => boolean; /** * Whether the area can be seen. */ onMouseDown?: (event: MouseEvent) => void; /** * Called when the mouse enters the area. */ onMouseEnter?: () => void; /** * Called when the mouse leaves the area. */ onMouseLeave?: () => void; /** * Called when the mouse is moved over the area */ onMouseMove?: (event: { buttons: ReadonlyArray<string>; height: number; width: number; x: number; y: number; }) => void; /** * **Not working at the moment.** * * Called when releasing a mouse button over the area. */ onMouseUp?: (event: MouseEvent) => void; /** * Whether the area can be seen. */ visible?: boolean; } /** * A component onto which area components like rectangles or circles can be drawn. * * Some props can be applied to all area components (including Area itself and children) * @see https://proton-native.js.org/#/area_props. */ export class Area extends React.Component<AreaProps> { /** * A Bezier curve to be displayed in an Area component. */ static Bezier: typeof AreaBezier; /** * A circle to be displayed in an Area component. */ static Circle: typeof AreaCircle; /** * A component to apply props to all it's children in an Area component. * * To be able to use percentage values in transforms, the props `width` and `height` need to be specified (they have no graphical effect). */ static Group: typeof AreaGroup; /** * A straigt line to be displayed in an Area component. */ static Line: typeof AreaLine; /** * A component describing a path to be displayed in an Area component. * * To be able to use percentage values in transforms, the props `width` and `height` need to be specified (they have no graphical effect). */ static Path: typeof AreaPath; /** * A rectangle to be displayed in an Area component. */ static Rectangle: typeof AreaRectangle; /** * A (possibly styled) text to be displayed in an Area component. Nested `Area.Text` components inheirit the parent's style. */ static Text: typeof AreaText; } export interface BoxProps extends GridChildrenProps, Label, Stretchy { /** * Whether the Box is enabled. */ enabled?: boolean; /** * Whether there is extra space between the children in the Box. */ padded?: boolean; /** * Whether the Box arranges its children vertically or horizontally. */ vertical?: boolean; /** * Whether the Box and its children can be seen. */ visible?: boolean; } export class Box extends React.Component<BoxProps> { } export interface ButtonProps extends GridChildrenProps, Label, Stretchy { /** * The text to display in the button. */ children?: string; /** * Whether the button can be clicked. */ enabled?: boolean; /** * Called when the button is clicked. */ onClick?: () => void; /** * Whether the button can be seen. */ visible?: boolean; } /** * A container for multiple components that are ordered vertically or horizontally. Similar to React Native's `View`. */ export class Button extends React.Component<ButtonProps> { } export interface CheckboxProps extends GridChildrenProps, Label, Stretchy { /** * Whether the checkbox is checked or not. */ checked?: boolean; /** * The text to display next to the check box. */ children?: string; /** * Whether the checkbox can be used. */ enabled?: boolean; /** * Called when the checkbox is clicked. The current checkbox state is passed as an argument. */ onToggle?: (checked: boolean) => void; /** * Whether the checkbox can be seen. */ visible?: boolean; } export class Checkbox extends React.Component<CheckboxProps> { } export interface ColorButtonProps extends GridChildrenProps, Label, Stretchy { /** * The initial color for the ColorButton. Can be passed as standard color seen in CSS (a color name, hex, rgb, rgba, hsl, hsla). */ color?: string; /** * Called when the color is changed for the ColorButton. The current color is passed as an object of RGBA. */ onChange?: (color: { r: number, g: number, b: number, a: number }) => void; } /** * A button that allows the user to choose a color. */ export class ColorButton extends React.Component<ColorButtonProps> { } export interface FormProps extends GridChildrenProps, Stretchy { /** * Whether the Form is enabled. */ enabled?: boolean; /** * Whether there is padding between the components */ padded?: boolean; /** * Whether the Form can be seen. */ visible?: boolean; } /** * A container where there is a label on the left and a component on the right. * * Each form component has a single prop, `label` which sets the label to its left. It is required. */ export class Form extends React.Component<FormProps> { } export interface GridChildrenProps { /** * Whether the component is aligned with the other components in the column/row. */ align?: { h: boolean; v: boolean; }; /** * What column the component resides in. */ column?: number; /** * Whether the component can expand in the direction. */ expand?: { h: boolean; v: boolean; }; /** * What row the component resides in. */ row?: number; /** * How many rows/columns the component takes off. */ span?: { x: number; y: number; }; } export interface GridProps { /** * Whether the Grid is enabled. */ enabled?: boolean; /** * Whether there is padding between the components */ padded?: boolean; /** * Whether the Grid can be seen. */ visible?: boolean; } /** * A grid where components can be placed in rows and columns. */ export class Grid extends React.Component<GridProps> { } export interface GroupProps extends GridChildrenProps, Label, Stretchy { /** * Group can only have one child. To have more than one child, use boxes. */ children?: JSX.Element; /** * Whether the Group is enabled. */ enabled?: boolean; /** * Whether there is a margin inside the group. */ margined?: boolean; /** * The name of the group. */ title?: string; /** * Whether the Grid can be seen. */ visible?: boolean; } /** * A named group of components. * * **Note:** Group can only have one child. To have more than one child, use boxes */ export class Group extends React.Component<GroupProps> { } export interface Label { /** * Label for Form and Tab children */ label?: string; } export interface MenuProps { /** * The name of the menu. */ label?: string; } export interface MenuItemProps { /** * The text to display for the menu item. */ children?: string; /** * If the type is `Check`, then set whether it is checked or not. */ checked?: boolean; /** * How the menu item is displayed. * * - `Check` - a checkable option in the menu. * - `Quit` - a Quit button. This accepts no text. * - `About` - an About button. This accepts no text. * - `Preferences` - a Preferences button. This accepts no text. * - `Separator` - a Separator between menu items. This accepts no text. * - `Item` - a normal menu button. This is the default. */ type?: 'Check' | 'Quit' | 'About' | 'Preferences' | 'Separator' | 'Item'; /** * Called when the menu item is clicked. If the type is `Check`, then it passes whether it is checked as an argument. */ onClick?: (checked: boolean) => void; } /** * A single item in a Menu. */ export class MenuItem extends React.Component<MenuItemProps> { } /** * The top bar on a window that can have multiple options. * * The menu must come outside and before the Window for it to take effect. It is made up of Menu.Items. Menus can be embedded inside eachother to make sub-menus. */ export class Menu extends React.Component<MenuProps> { /** * A single item in a Menu. */ static Item: typeof MenuItem; } export interface PickerProps extends GridChildrenProps, Label, Stretchy { /** * Whether the user can enter their own custom text in addition to the drop down menu. */ editable?: boolean; /** * Whether the Picker is enabled. */ enabled?: boolean; /** * When an *editable* Picker is changed. The current text is passed as an argument. */ onChange?: (text: string) => void; /** * When a *non-editable* Picker is changed. The current selection is passed as an argument. */ onSelect?: (selection: number) => void; /** * What element is selected if the picker *is not* editable. */ selected?: number; /** * What text is selected/typed if the picker *is* editable. */ text?: string; /** * Whether the Picker can be seen. */ visible?: boolean; } export interface PickerItemProps { children: string; } export class PickerItem extends React.Component<PickerItemProps> { } /** * A drop down menu where the user can pick different values. */ export class Picker extends React.Component<PickerProps> { static Item: typeof PickerItem; } export interface ProgressBarProps extends GridChildrenProps, Label, Stretchy { /** * Whether the ProgressBar is enabled. */ enabled?: boolean; /** * The current value of the ProgressBar (0-100). A value of -1 indicates an indeterminate progressbar. */ value?: number; /** * Whether the ProgressBar can be seen. */ visible?: boolean; } /** * A bar that shows the progress in a certain task, 0-100. */ export class ProgressBar extends React.Component<ProgressBarProps> { } export interface RadioButtonsItemProps { children: string; } export class RadioButtonsItem extends React.Component<RadioButtonsItemProps> { } export interface RadioButtonsProps extends GridChildrenProps, Label, Stretchy { /** * Whether the RadioButtons can be used. */ enabled?: boolean; /** * Called when a RadioButton is selected. The number selected is passed as an argument. */ onSelect?: (selected: number) => void; /** * What RadioButton is selected, zero-indexed. -1 means nothing is selected. */ selected?: number; /** * Whether the RadioButtons can be seen. */ visible?: boolean; } /** * A choice between multiple options. * * Every child must be a RadioButtons.Item, that requires a string child that is the label to display to the right of the RadioButton. */ export class RadioButtons extends React.Component<RadioButtonsProps> { static Item: typeof RadioButtonsItem; } export interface SeparatorProps extends GridChildrenProps, Label, Stretchy { /** * Whether the Separator is enabled. */ enabled?: boolean; /** * Whether the line is vertical or horizontal. */ vertical?: boolean; /** * Whether the Separator can be seen. */ visible?: boolean; } /** * A line to separate two components, commonly used in a Box. */ export class Separator extends React.Component<SeparatorProps> { } export interface SliderProps extends GridChildrenProps, Label, Stretchy { /** * Whether the Slider is enabled. */ enabled?: boolean; /** * The minimum value for the slider. */ min?: number; /** * The maximum value for the slider. */ max?: number; /** * Called when the value of the slider is changed. The current value is passed as an argument. */ onChange?: (value: number) => void; /** * The current value of the Slider (0-100). */ value?: number; /** * Whether the Slider can be seen. */ visible?: boolean; } /** * A bar that can be dragged by the user from 0-100. */ export class Slider extends React.Component<SliderProps> { } export interface SpinBoxProps extends GridChildrenProps, Label, Stretchy { /** * Whether the Spinbox is enabled. */ enabled?: boolean; /** * When the Spinbox value is changed. The current value is passed as a parameter. */ onChange?: (value: number) => void; /** * What the value of the Spinbox is set to. */ value?: number; /** * Whether the Spinbox can be seen. */ visible?: boolean; } /** * A location for the user to choose a number. */ export class SpinBox extends React.Component<SpinBoxProps> { } export interface Stretchy { /** * Whether the component should stretch to fill the available space. Defaults to true. * * Excluded on: * - Tabs * - Grid children * - Combobox/RadioButton Items * - MenuBar */ stretchy?: boolean; } export interface StyledTextProps { style?: { /** * The background color, specified as a CSS color string. */ backgroundColor?: string; /** * The text color, specified as a CSS color string. */ color?: string; /** * The font family (only if available on the system). */ fontFamily?: string; /** * The font size (in pt). */ fontSize?: number; /** * Whether an italic font should be used. */ fontStyle?: 'normal' | 'oblique' | 'italic'; /** * Whether a bold font should be used (and the amount). */ fontWeight?: 'minimum' | 'thin' | 'ultraLight' | 'light' | 'book' | 'normal' | 'medium' | 'semiBold' | 'bold' | 'ultraBold' | 'heavy' | 'ultraHeavy' | 'maximum' | number; /** * Wheter the text should be aligned to the left, center or right. * * **Works only on a top level text component, not it's children!** */ textAlign?: 'left' | 'center' | 'right'; /** * How wide or narrow the characters should be. */ textStretch?: 'ultraCondensed' | 'extraCondensed' | 'condensed' | 'semiCondensed' | 'normal' | 'semiExpanded' | 'expanded' | 'extraExpanded' | 'ultraExpanded'; /** * The text underline style. */ textUnderline?: 'none' | 'single' | 'double' | 'suggestion'; /** * The text underline color. * * A color string | 'spelling' | 'grammar' | 'auxiliary' */ textUnderlineColor?: 'spelling' | 'grammar' | 'auxiliary' | string; }; /** * The x coordinate of the text's top left corner. (Only in a top level text component.) */ x?: number | string; /** * The y coordinate of the text's top left corner. (Only in a top level text component.) */ y?: number | string; } export class StyledText extends React.Component<StyledTextProps> { } export interface TabProps extends GridChildrenProps { /** * Whether the Tab is enabled. */ enabled?: boolean; /** * Whether the Tab can be seen. */ visible?: boolean; } /** * A component with different named tabs containing other components. * * Each child is required to have a label prop that is displayed at the top and names the tab. */ export class Tab extends React.Component<TabProps> { } export interface TextProps extends GridChildrenProps, Label, Stretchy { /** * The text to display. */ children?: string; } /** * Displays some text. */ export class Text extends React.Component<TextProps> { } export interface TextInputProps extends GridChildrenProps, Label, Stretchy { /** * The default text in the TextInput. */ children?: string; /** * Whether the TextInput can be used. */ enabled?: boolean; /** * Whether multiple lines can be inputted into the TextInput. */ multiline?: boolean; /** * Called when the TextInput text is changed. The new text is passed as an argument. */ onChange?: (text: string) => void; /** * Whether the TextInput can be written to by the user. */ readOnly?: boolean; /** * Whether characters are hidden in the TextInput. Commonly used for passwords. */ secure?: boolean; /** * Whether the TextInput can be seen. */ visible?: boolean; } /** * A place for the user to type in a string. */ export class TextInput extends React.Component<TextInputProps> { } export interface WindowProps { /** * Whether the window will have a border on the inside. */ borderless?: boolean; /** * Window can only have one child. To have more than one child, use boxes. */ children?: JSX.Element; /** * Whether the window is closed. If set to closed, then the window will be closed. */ closed?: boolean; /** * Whether the window will be fullscreen on start. */ fullscreen?: boolean; /** * Whether the window is the last window. If set to `true`, then the program will quit once the window is closed. */ lastWindow?: boolean; /** * Whether all children will have a margin around them and the outer edge of the window. */ margined?: boolean; /** * Whether a menubar will be shown on the top of the window. */ menuBar?: boolean; /** * Called when the window is closed. */ onClose?: () => void; /** * Called when the window size is changed by the user. The new size is passed as an argument, in an object. */ onContentSizeChange?: (size: { h: number, y: number }) => void; /** * How big the window is when the application is first started. */ size?: { h: number, w: number }; /** * The title of the window. Will be shown at the top left ribbon. */ title?: string; } /** * The window is the basis where all other components reside. * * **Note:** Window can only have one child. To have more than one child, use boxes. */ export class Window extends React.Component<WindowProps> { } /** * Renders the input component */ export function render(element: JSX.Element): void; /** * A method to display an alert. * @param type What type the dialog is. The current types are: * - Message - a simple message * - Error - an error message * - Open - open a file * - Save - save a file * @param options Options for the title and descript. */ export function Dialog( type: 'Message' | 'Error', options?: { title: string, description?: string } | { title?: string, description: string } ): void; /** * A dialog to save or open a file. Returns chosen file path. * @param type What type the dialog is. The current types are: * - Open - open a file * - Save - save a file */ export function Dialog(type: 'Open' | 'Save'): string;
the_stack
import prelude = require("prelude-ls"); var five: number = prelude.id(5); //=> 5 var emptyObj: Object = prelude.id({}); //=> {} var expectBool: boolean = prelude.isType("Undefined", void 8); //=> true prelude.isType("Boolean", true); //=> true prelude.isType("Number", 1); //=> true prelude.isType("String", "hi"); //=> true prelude.isType("Object", {}); //=> true prelude.isType("Array", []); //=> true var numberArray: Array<number> = prelude.replicate(4, 3); //=> [3, 3, 3, 3] var strArray: Array<string> = prelude.replicate(4, "a"); //=> ["a", "a", "a", "a"] prelude.replicate(0, "a"); //=> [] // List var eachRes: Array<Array<string>> = prelude.each(x => x.push("boom"), [["a"], ["b"], ["c"]]); //=> [["a", "boom"], ["b", "boom"], ["c", "boom"]] var mapRes: Array<string> = prelude.map(x => x.toString(), [1, 2, 3, 4, 5]) //=> ["1", "2", "3", "4", "5"] prelude.map(x => x.toUpperCase(), ["ha", "ma"]); //=> ["HA", "MA"] prelude.map(x => x.num, [{num: 3}, {num: 1}]); //=> [3, 1] var compactRes: Array<any> = prelude.compact([0, 1, false, true, "", "ha"]) //=> [1, true, "ha"] var filterRes: Array<number> = prelude.filter(x => x < 3, [1, 2, 3, 4, 5]); //=> [1, 2] prelude.filter(prelude.even, [3, 4, 0]); //=> [4, 0] var rejectRes: Array<number> = prelude.reject(prelude.odd, [1, 2, 3, 4, 5]); //=> [2, 4] var partitionRes: Array<Array<number>> = prelude.partition(x => x > 60, [49, 58, 76, 43, 88, 77, 90]); //=> [[76, 88, 77, 90], [49, 58, 43]] var findRes: number = prelude.find(prelude.odd, [2, 4, 6, 7, 8, 9, 10]); //=> 7 var headRes: number = prelude.head([1, 2, 3, 4, 5]); //=> 1 var tailRes: Array<number> = prelude.tail([1, 2, 3, 4, 5]); //=> [2, 3, 4, 5] var lastRes: number = prelude.last([1, 2, 3, 4, 5]); //=> 5 var initialRes: Array<number> = prelude.initial([1, 2, 3, 4, 5]); //=> [1, 2, 3, 4] var emptyRes: boolean = prelude.empty([]); //=> true var reverseRes: Array<number> = prelude.reverse([1, 2, 3]); //=> [3, 2, 1] var uniqueRes: Array<number> = prelude.unique([1, 1, 1, 3, 3, 6, 7, 8]); //=> [1, 3, 6, 7, 8] var uniqueByRes: Array<string> = prelude.uniqueBy(x => x.length, ["and", "here", "are", "some", "words"]); //=> ["and", "here", "words"] var foldRes: number = prelude.fold(x => y => x + y, 0, [1, 2, 3, 4, 5]); //=> 15 var fold1Res: number = prelude.fold1(x => y => x + y, [1, 2, 3]); //=> 6 var foldrRes: number = prelude.foldr(x => y => x - y, 9, [1, 2, 3, 4]); //=> 7 var foldrStrRes: string = prelude.foldr(x => y => x + y, "e", ["a", "b", "c", "d"]); //=> "abcde" var foldr1Res: number = prelude.foldr1(x => y => x - y, [1, 2, 3, 4, 9]); //=> 7 var unfoldrRes: Array<number> = prelude.unfoldr(x => x === 0 ? null : [x, x - 1], 10); //=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] var concatRes: Array<number> = prelude.concat([[1], [2, 3], [4]]); //=> [1, 2, 3, 4] var concatMapRes: Array<any> = prelude.concatMap(x => ["hoge", x, x + 2], [1, 2, 3]); //=> ["hoge", 1, 3, "hoge", 2, 4, "hoge", 3, 5] var flattenRes: Array<number> = prelude.flatten([1, [[2], 3], [4, [[5]]]]); //=> [1, 2, 3, 4, 5] var differenceRes: Array<number> = prelude.difference([1, 2, 3], [1]); //=> [2, 3] prelude.difference([1, 2, 3, 4, 5], [5, 2, 10], [9]); //=> [1, 3, 4] prelude.intersection([2, 3], [9, 8], [12, 1], [99]); //=> [] var intersectionRes: Array<number> = prelude.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1], [-1, 0, 1, 2]); //=> [1, 2] prelude.intersection([1, 2, 3], [2, 1, 3], [3, 1, 2]); //=> [1, 2, 3] var unionRes: Array<number> = prelude.union([1, 5, 7], [3, 5], []); //=> [1, 5, 7, 3] var countByRes: Object = prelude.countBy(prelude.floor, [4.2, 6.1, 6.4]); //=> {4: 1, 6: 2} prelude.countBy(x => x.length, ["one", "two", "three"]); //=> {3: 2, 5: 1} var groupByRes: Object = prelude.groupBy(prelude.floor, [4.2, 6.1, 6.4]); //=> {4: [4.2], 6: [6.1, 6.4]} prelude.groupBy(x => x.length, ["one", "two", "three"]); //=> {3: ["one", "two"], 5: ["three"]} var andListRes: boolean = prelude.andList([true, 2 + 2 == 4]); //=> true prelude.andList([true, true, false]); //=> false prelude.andList([]); //=> true var orListRes: boolean = prelude.orList([false, false, true, false]); //=> true prelude.orList([]); //=> false var anyRes: boolean = prelude.any(prelude.even, [3, 5, 7, 8, 9]); //=> true prelude.any(prelude.even, []); //=> false var allRes: boolean = prelude.all(prelude.isType("String"), ["ha", "ma", "la"]); //=> true prelude.all(prelude.isType("String"), []); //=> true var sortRes: Array<number> = prelude.sort([3, 1, 5, 2, 4, 6]); //=> [1, 2, 3, 4, 5, 6] var f = (x: string) => (y: string) => x.length > y.length ? 1 : x.length < y.length ? -1 : 0; var sortWithRes: Array<string> = prelude.sortWith(f, ["three", "one", "two"]); //=> ["one", "two", "three"] var sortByRes: Array<string> = prelude.sortBy(x => x.length, ["there", "hey", "a", "ha"]); //=> ["a", "ha", "hey", "there"] var table: Array<{ id: number; name: string; }> = [{ id: 1, name: "george" }, { id: 2, name: "mike" }, { id: 3, name: "donald" }]; prelude.sortBy(x => x.name, table); //=> [{"id": 3, "name": "donald"}, // {"id": 1, "name": "george"}, // {"id": 2, "name": "mike"}] var sumRes: number = prelude.sum([1, 2, 3, 4, 5]); //=> 15 prelude.sum([]); //=> 0 var productRes: number = prelude.product([1, 2, 3]); //=> 6 prelude.product([]); //=> 1 var meanRes: number = prelude.mean([1, 2, 3, 4, 5]); //=> 3 var maximumRes: number = prelude.maximum([4, 1, 9, 3]); //=> 9 var minimumRes: string = prelude.minimum(["c", "e", "a", "d", "b"]); //=> "a" var maximumByRes: string = prelude.maximumBy(x => x.length, ["hi", "there", "I", "am", "looooong"]); //=> "looooong" var scanRes: Array<number> = prelude.scan(x => y => x + y, 0, [1, 2, 3]); //=> [0, 1, 3, 6] var scan1Res: Array<number> = prelude.scan1(x => y => x + y, [1, 2, 3]); //=> [1, 3, 6] var scanrRes: Array<number> = prelude.scanr(x => y => x + y, 0, [1, 2, 3]); //=> [6, 5, 3, 0] var scanr1Res: Array<number> = prelude.scanr1(x => y => x + y, [1, 2, 3]); //=> [6, 5, 3] var sliceRes: Array<number> = prelude.slice(2, 4, [1, 2, 3, 4, 5]); //=> [3, 4] var takeRes: Array<number> = prelude.take(2, [1, 2, 3, 4, 5]); //=> [1, 2] var dropRes: Array<number> = prelude.drop(2, [1, 2, 3, 4, 5]); //=> [3, 4, 5] var splitAtRes: Array<Array<number>> = prelude.splitAt(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [3, 4, 5]] var takeWhileRes: Array<number> = prelude.takeWhile(prelude.odd, [1, 3, 5, 4, 8, 7, 9]); //=> [1, 3, 5] var dropWhileRes: Array<number> = prelude.dropWhile(prelude.even, [2, 4, 5, 6]); //=> [5, 6] var spanRes: Array<Array<number>> = prelude.span(prelude.even, [2, 4, 5, 6]); //=> [[2, 4], [5, 6]] var breakListRes: Array<Array<number>> = prelude.breakList(x => x == 3, [1, 2, 3, 4, 5]); //=> [[1, 2], [3, 4, 5]] var zipRes: Array<Array<number>> = prelude.zip([1, 2, 3], [4, 5, 6]); //=> [[1, 4], [2, 5], [3, 6]] var zipWithRes: Array<number> = prelude.zipWith(x => y => x + y, [1, 2, 3], [4, 5, 6]); //=> [5, 7, 9] var zipAllRes: Array<Array<number>> = prelude.zipAll([1, 2, 3], [4, 5, 6], [7, 8, 9]); //=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]] var zipAllWithRes: Array<number> = prelude.zipAllWith((a, b, c) => a + b + c, [1, 2, 3], [3, 2, 1], [1, 1, 1]); //=> [5, 5, 5] var atRes: number = prelude.at(2, [1, 2, 3, 4]); //=> 3 prelude.at(-3, [1, 2, 3, 4]); //=> 2 var elemIndexRes: number = prelude.elemIndex("a", ["c", "a", "b", "a"]); //=> 1 var elemIndicesRes: Array<number> = prelude.elemIndices("a", ["c", "a", "b", "a"]); //=> [1, 3] var findIndexRes: number = prelude.findIndex(prelude.even, [1, 2, 3, 4]); //=> 1 var findIndicesRes: Array<number> = prelude.findIndices(prelude.even, [1, 2, 3, 4]); //=> [1, 3] // Obj var keysRes: Array<string> = prelude.keys({a: 2, b: 3, c: 9}); //=> ["a", "b", "c"] var valuesRes: Array<number> = prelude.values({a: 2, b: 3, c: 9}); //=> [2, 3, 9] var pairsToObjRes: Object = prelude.pairsToObj<string | number>([["a", "b"], ["c", "d"], ["e", 1]]); //=> {a: "b", c: "d", e: 1} var objToPairsRes: Array<Array<string | number>> = prelude.objToPairs({a: "b", c: "d", e: 1}); //=> [["a", "b"], ["c", "d"], ["e", 1]] var listsToObjRes: Object = prelude.listsToObj(["a", "b", "c"], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} var objToListsRes = prelude.objToLists({a: 1, b: 2, c: 3}); //=> [["a", "b", "c"], [1, 2, 3]] var objEmptyRes: boolean = prelude.Obj.empty({}); //=> true var count = 4; prelude.Obj.each(x => count += x, {a: 1, b: 2, c: 3}); count; //=> 10 prelude.Obj.map(x => x + 2, {a: 2, b: 3, c: 4}); //=> {a: 4, b: 5, c: 6} prelude.Obj.compact({a: 0, b: 1, c: false, d: "", e: "ha"}); //=> {b: 1, e: "ha"} prelude.Obj.filter(prelude.even, {a: 3, b: 4, c: 0}); //=> {b: 4, c: 0} prelude.Obj.reject(x => x == 2, {a: 1, b: 2}); //=> {a: 1} prelude.Obj.partition(x => x == 2, {a: 1, b: 2, c: 3}); //=> [{b: 2}, {a: 1, c: 3}] prelude.Obj.find(prelude.even, {a: 1, b: 2, c: 3, d: 4}); //=> 2 // Str prelude.split("|", "1|2|3"); //=> ["1", "2", "3"] prelude.join("|", ["1", "2", "3"]); //=> "1|2|3" prelude.lines("one\ntwo\nthree"); //=> ["one", "two", "three"] prelude.unlines(["one", "two", "three"]); //=> "one\ntwo\nthree" prelude.words("hello, what is that?"); //=> ["hello,", "what", "is", "that?"] prelude.unwords(["one", "two", "three"]); //=> "one two three" prelude.chars("hello"); //=> ["h", "e", "l", "l", "o"] prelude.unchars(["t", "h", "e", "r", "e"]); //=> "there" prelude.unchars(["ma", "ma"]); //=> "mama" prelude.repeat(4, "a"); //=> "aaaa" prelude.repeat(2, "ha"); //=> "haha" prelude.capitalize("hi there"); //=> "Hi there" prelude.camelize("hi-there"); //=> "hiThere" prelude.camelize("hi_there"); //=> "hiThere" prelude.dasherize("hiThere"); //=> "hi-there" prelude.dasherize("FooBar"); //=> "foo-bar" prelude.dasherize("innerHTML"); //=> "inner-HTML" prelude.empty(""); //=> true prelude.reverse("goat"); //=> "taog" prelude.slice(2, 4, "hello"); //=> "ll" prelude.take(4, "hello"); //=> "hell" prelude.drop(1, "goat"); //=> "oat" prelude.splitAt(4, "hello"); //=> ["hell", "o"] prelude.takeWhile(x => !prelude.empty(prelude.elemIndices(x, ["a", "b", "c", "d"])), "cabdek"); //=> "cabd" prelude.dropWhile(x => x === "m", "mmmmmhmm"); //=> "hmm" prelude.span(x => x === "m", "mmmmmhmm"); //=> ["mmmmm", "hmm"] prelude.Str.breakStr(x => x === "h", "mmmmmhmm"); //=> ["mmmmm", "hmm"] // Func var applyRes: number = prelude.apply((x, y) => x + y, [2, 3]); //=> 5 var add = (x: number, y: number) => x + y; var addCurried = prelude.curry(add); var addFour = addCurried(4); addFour(2); //=> 6 var flipRes: (x: number) => (y: number) => number = prelude.flip<number, number, number>(x => y => Math.pow(x, y)); var fixRes: number = prelude.fix( (fib: (n: number) => number) => (n: number) => n <= 1 ? 1 : fib(n - 1) + fib(n - 2) )(9); //=> 55 var sameLength: (x: string, y: string) => boolean = prelude.over<string, number, boolean>((x, y) => x == y, x => x.length); sameLength('hi', 'me'); //=> true sameLength('one', 'boom'); //=> false // Num prelude.max(3, 1); //=> 3 var maxRes: string = prelude.max("a", "c"); //=> "c" var minRes: number = prelude.min(3, 1); //=> 1 prelude.min("a", "c"); //=> "a" var negateRes: number = prelude.negate(3); //=> -3 prelude.negate(-2); //=> 2 var absRes: number = prelude.abs(-2); //=> 2 prelude.abs(2); //=> 2 var signumRes: number = prelude.signum(-5); //=> -1 prelude.signum(0); //=> 0 prelude.signum(9); //=> 1 var quotRes: number = prelude.quot(-20, 3); //=> -6 var remRes: number = prelude.rem(-20, 3); //=> -2 var divRes: number = prelude.div(-20, 3); //=> -7 var modRes: number = prelude.mod(-20, 3); //=> 1 var recipRes: number = prelude.recip(4); //=> 0.25 var piRes: number = prelude.pi; //=> 3.141592653589793 var tauRes: number = prelude.tau; //=> 6.283185307179586 var expRes: number = prelude.exp(1); //=> 2.718281828459045 var sqrtRes: number = prelude.sqrt(4); //=> 2 var lnRes: number = prelude.ln(10); //=> 2.302585092994046 var powRes: number = prelude.pow(-2, 2); //=> 4 var sinRes: number = prelude.sin(prelude.pi / 2); //=> 1 var cosRes: number = prelude.cos(prelude.pi); //=> -1 var aTanRes: number = prelude.tan(prelude.pi / 4); //=> 1 var asinRes: number = prelude.asin(0); //=> 0 var acosRes: number = prelude.acos(1); //=> 0 prelude.atan(0); //=> 0 var atanRes: number = prelude.atan2(1, 0); //=> 1.5707963267948966 var truncateRes: number = prelude.truncate(-1.5); //=> -1 prelude.truncate(1.5); //=> 1 var roundRes: number = prelude.round(0.6); //=> 1 prelude.round(0.5); //=> 1 prelude.round(0.4); //=> 0 var ceilingRes: number = prelude.ceiling(0.1); //=> 1 var floorRes: number = prelude.floor(0.9); //=> 0 var isItNanRes: boolean = prelude.isItNaN(prelude.sqrt(-1)); //=> true var evenRes: boolean = prelude.even(4); //=> true prelude.even(0); //=> true var oddRes: boolean = prelude.odd(3); //=> true var gcdRes: number = prelude.gcd(12, 18); //=> 6 var lcmRes: number = prelude.lcm(12, 18); //=> 36
the_stack
import { toolkit } from '@docgeni/toolkit'; import { DocgeniContext } from '../docgeni.interface'; import { ChannelItem, ComponentDocItem, DocItem, HomeDocMeta, Locale, NavigationItem } from '../interfaces'; import { ascendingSortByOrder, buildNavsMapForLocales, DOCS_ENTRY_FILE_NAMES, getDocTitle, isEntryDoc } from '../utils'; import { DocSourceFile } from './doc-file'; import * as path from 'path'; import { resolve } from '../fs'; export class NavsBuilder { private localeNavsMap: Record<string, NavigationItem[]> = {}; /* The navs that generate by docs dir insertion location */ private docsNavInsertIndex: number; private get config() { return this.docgeni.config; } private rootNavs: NavigationItem[]; private localesDocsNavsMap: Record< string, { navs: NavigationItem[]; docItems: DocItem[]; homeMeta?: HomeDocMeta; } > = {}; constructor(private docgeni: DocgeniContext) {} public async run() { this.setRootNavs(); this.localeNavsMap = buildNavsMapForLocales(this.config.locales, this.rootNavs); await this.build(); await this.emit(); } public async emit() { const localeNavsMap: Record<string, NavigationItem[]> = JSON.parse(JSON.stringify(this.localeNavsMap)); const localeDocItemsMap: Record<string, DocItem[]> = {}; for (const locale of this.docgeni.config.locales) { const navsForLocale = this.getLocaleDocsNavs(locale.key); const docItems = this.getLocaleDocsItems(locale.key); localeDocItemsMap[locale.key] = docItems; let componentDocItems: ComponentDocItem[] = []; localeNavsMap[locale.key].splice(this.docsNavInsertIndex, 0, ...navsForLocale); this.docgeni.librariesBuilder.libraries.forEach(libraryBuilder => { componentDocItems = componentDocItems.concat(libraryBuilder.generateLocaleNavs(locale.key, localeNavsMap[locale.key])); }); await this.docgeni.host.writeFile( `${this.docgeni.paths.absSiteAssetsContentPath}/navigations-${locale.key}.json`, JSON.stringify( { navs: localeNavsMap[locale.key], docs: docItems.concat(componentDocItems), homeMeta: this.localesDocsNavsMap[locale.key].homeMeta }, null, 2 ) ); } await this.docgeni.host.writeFile( `${this.docgeni.paths.absSiteContentPath}/navigations.json`, JSON.stringify(localeNavsMap, null, 2) ); this.docgeni.hooks.navsEmitSucceed.call(this, localeDocItemsMap); } private getLocaleDocsNavs(locale: string) { return (this.localesDocsNavsMap[locale] && this.localesDocsNavsMap[locale].navs) || []; } private getLocaleDocsItems(locale: string) { return (this.localesDocsNavsMap[locale] && this.localesDocsNavsMap[locale].docItems) || []; } private async setRootNavs() { let navs = this.config.navs; let docsNavInsertIndex = navs.indexOf(null); if (docsNavInsertIndex >= 0) { navs = this.config.navs.filter(item => { return !!item; }); } else { docsNavInsertIndex = navs.length; } this.docsNavInsertIndex = docsNavInsertIndex; this.rootNavs = navs as NavigationItem[]; } public async build() { const localeKeys = this.config.locales.map(locale => { return locale.key; }); const localesDocsDataMap: Record< string, { navs: NavigationItem[]; docItems: DocItem[]; homeMeta?: HomeDocMeta; } > = {}; for (const locale of this.config.locales) { const isDefaultLocale = locale.key === this.config.defaultLocale; const localeDocsPath = await this.getLocaleDocsPath(locale); localesDocsDataMap[locale.key] = { navs: [], docItems: [] }; if (await this.docgeni.host.pathExists(localeDocsPath)) { const docItems: DocItem[] = []; const { navs, homeMeta } = await this.buildDocDirNavs( localeDocsPath, locale.key, docItems, undefined, isDefaultLocale ? localeKeys : [] ); localesDocsDataMap[locale.key] = { navs, docItems, homeMeta }; if (this.docgeni.config.mode === 'full') { docItems.forEach(docItem => { if (docItem.channelPath) { docItem.path = docItem.path.replace(docItem.channelPath + '/', ''); } }); } } } this.localesDocsNavsMap = localesDocsDataMap; } private async buildDocDirNavs( dirPath: string, locale: string, docItems: DocItem[], parentItem?: NavigationItem, excludeDirs?: string[] ) { const dirsAndFiles = await this.docgeni.host.getDirsAndFiles(dirPath, { exclude: excludeDirs }); let navs: Array<NavigationItem> = []; let homeMeta: HomeDocMeta; for (const dirname of dirsAndFiles) { const absDocPath = resolve(dirPath, dirname); if (await this.docgeni.host.isDirectory(absDocPath)) { const entryFile = this.tryGetEntryFile(absDocPath); const currentPath = this.getCurrentRoutePath(dirname, entryFile); const fullRoutePath = this.getFullRoutePath(currentPath, parentItem); const navItem: NavigationItem = { id: fullRoutePath, path: fullRoutePath, channelPath: parentItem ? parentItem.channelPath : fullRoutePath, title: getDocTitle(entryFile && entryFile.meta.title, dirname), subtitle: entryFile && entryFile.meta.subtitle, hidden: entryFile && entryFile.meta.hidden, items: [], order: entryFile && toolkit.utils.isNumber(entryFile.meta.order) ? entryFile.meta.order : Number.MAX_SAFE_INTEGER }; // hide it when hidden is true if (!navItem.hidden) { navs.push(navItem); } const { navs: subNavs } = await this.buildDocDirNavs(absDocPath, locale, docItems, navItem, excludeDirs); navItem.items = subNavs; } else { if (path.extname(absDocPath) !== '.md') { continue; } const docFile = this.docgeni.docsBuilder.getDoc(absDocPath); if (!docFile) { throw new Error(`Can't find doc file for ${absDocPath}`); } const isEntry = isEntryDoc(docFile.name); const isHome = isEntry && !parentItem; if (isHome && this.docgeni.config.mode === 'full') { homeMeta = docFile.meta; homeMeta.contentPath = docFile.getRelativeOutputPath(); continue; } if (isEntry && toolkit.utils.isEmpty(docFile.output)) { continue; } const currentPath = this.getCurrentRoutePath(isEntry ? '' : toolkit.strings.paramCase(docFile.name), docFile); const fullRoutePath = this.getFullRoutePath(currentPath, parentItem, isEntry); const docItem: NavigationItem = { id: docFile.name, path: fullRoutePath, channelPath: parentItem ? parentItem.channelPath : '', title: getDocTitle(docFile.meta.title, docFile.name), subtitle: docFile.meta.subtitle, order: toolkit.utils.isNumber(docFile.meta.order) ? docFile.meta.order : Number.MAX_SAFE_INTEGER, hidden: docFile.meta.hidden, toc: toolkit.utils.isUndefinedOrNull(docFile.meta.toc) ? this.docgeni.config.toc : docFile.meta.toc, headings: docFile.headings }; docItem.contentPath = docFile.getRelativeOutputPath(); docItem.originPath = docFile.relative; // hide it when hidden is true if (!docItem.hidden) { navs.push(docItem); docItems.push(docItem); } } } navs = ascendingSortByOrder(navs); return { navs, homeMeta }; } private tryGetEntryFile(dirPath: string) { const fullPath = DOCS_ENTRY_FILE_NAMES.map(name => { return resolve(dirPath, `${name}.md`); }).find(path => { return this.docgeni.docsBuilder.getDoc(path); }); if (fullPath) { return this.docgeni.docsBuilder.getDoc(fullPath); } else { return undefined; } } private getFullRoutePath(currentPath: string, parentNav?: NavigationItem, isEntry?: boolean): string { if (parentNav && parentNav.path) { if (isEntry && currentPath === parentNav.path) { return ''; } if (!currentPath || isEntry) { return parentNav.path; } else { return `${parentNav.path}/${currentPath.toLowerCase()}`; } } else { return currentPath; } } private getCurrentRoutePath(dirname: string, file?: DocSourceFile) { let currentPath = dirname; if (file && !toolkit.utils.isUndefinedOrNull(file.meta.path)) { currentPath = file.meta.path; } return currentPath; } private async getLocaleDocsPath(locale: Locale) { const isDefaultLocale = locale.key === this.config.defaultLocale; if (isDefaultLocale) { const dir = resolve(this.docgeni.paths.absDocsPath, locale.key); if (await this.docgeni.host.pathExists(dir)) { return dir; } } return isDefaultLocale ? this.docgeni.paths.absDocsPath : resolve(this.docgeni.paths.absDocsPath, locale.key); } }
the_stack
import _ from 'lodash' import K8sFunctions, {StringStringArrayMap, GetItemsFunction} from '../k8s/k8sFunctions' import {Cluster, PodDetails, PodContainerDetails, ServiceDetails} from "../k8s/k8sObjectTypes" import { K8sClient } from '../k8s/k8sClient' import ActionContext from './actionContext' import {Choice} from './actionSpec' import Context from "../context/contextStore" import IstioFunctions from '../k8s/istioFunctions' import KubectlClient from '../k8s/kubectlClient' export interface ItemSelection { title: string namespace: string cluster: string item: any [key: string]: any } export interface PodSelection extends ItemSelection { podName: string containerName: string podContainerDetails?: PodDetails|PodContainerDetails podIP?: string hostIP?: string nodeName?: string k8sClient: K8sClient } export default class ChoiceManager { static clearSelectionsDelay = 300000 static items: StringStringArrayMap = {} static useNamespace: boolean = true static showChoiceSubItems: boolean = true static cacheKey: string|undefined = undefined static pendingChoicesCounter = 0 static clearItemsTimer: any = undefined static cacheLoadTimer: any = undefined static cacheLoadInterval = 300000 static cachedEnvoyProxies: any = {} static cachedServices: any = {} static startClearItemsTimer() { if(this.clearItemsTimer) { clearTimeout(this.clearItemsTimer) } this.clearItemsTimer = setTimeout(this.clear.bind(this), this.clearSelectionsDelay) } static startAsyncCacheLoader() { if(this.cacheLoadTimer) { clearInterval(this.cacheLoadTimer) } this.loadPreCachedItems() this.cacheLoadTimer = setInterval(this.loadPreCachedItems.bind(this), this.cacheLoadInterval) } static async loadPreCachedItems() { const clusters = Context.clusters for(const cluster of clusters) { //this.cachedEnvoyProxies[cluster.name] = await IstioFunctions.getAllEnvoyProxies(cluster.k8sClient) this.cachedServices[cluster.name] = await K8sFunctions.getClusterServices(cluster.k8sClient) } } static clearPreCache() { this.cachedEnvoyProxies = {} this.cachedServices = {} } static clear() { this.items = {} this.useNamespace = true this.showChoiceSubItems = true this.cacheKey = undefined this.clearItemsTimer = undefined this.pendingChoicesCounter = 0 } static createChoices(items, namespace, cluster, ...fields) { const choices: Choice[] = [] items && items.forEach(item => { const choiceItem: any[] = [] const choiceData: any = {} if(fields.length > 0) { fields.forEach(field => { choiceItem.push(item[field]) choiceData[field] = item[field] }) choiceData['title'] = choiceData['name'] || choiceItem[0] } else { const itemName = item.name || item choiceItem.push(itemName) choiceData['title'] = choiceData['name'] = itemName } let itemNS = namespace if(!itemNS) { itemNS = item.namespace ? (item.namespace.name || item.namespace) : "" } if(itemNS) { choiceItem.push("Namespace: " + itemNS) } choiceItem.push("Cluster: " + cluster) choiceData.cluster = cluster choiceData.namespace = itemNS choiceData.item = item choices.push({displayItem: choiceItem, data: choiceData}) }) return choices } private static async _createAndStoreItems(cache: boolean, cacheKey: string|undefined, actionContext: ActionContext, getItems: GetItemsFunction, useNamespace: boolean = true, ...fields) { const clusters = actionContext.getClusters() this.useNamespace = useNamespace const isCached = this.cacheKey === cacheKey if(cache) { if(!cacheKey || !isCached) { this.cacheKey = cacheKey this.items = {} } else { Object.keys(this.items).forEach(c => { const cluster = clusters.filter(cluster => cluster.name === c)[0] if(!cluster) { delete this.items[c] } else if(useNamespace) { if(cluster.namespaces.length > 0) { Object.keys(this.items[c]).forEach(ns => { if(cluster.namespaces.filter(namespace => namespace.name === ns).length === 0) { delete this.items[c][ns] } }) } } }) } } else { this.cacheKey = undefined this.items = {} } const operationId = Context.operationCounter let choices: any[] = [] for(const cluster of clusters) { if(!this.items[cluster.name]) { this.items[cluster.name] = {} } let namespaces = cluster.namespaces if(useNamespace) { if(namespaces.length === 0) { namespaces = await K8sFunctions.getClusterNamespaces(cluster.k8sClient) } for(const namespace of namespaces) { if(operationId !== Context.operationCounter) { return [] } let isNewNamespace = false if(!this.items[cluster.name][namespace.name]) { this.items[cluster.name][namespace.name] = [] isNewNamespace = true } let items = this.items[cluster.name][namespace.name] if(!cache || !isCached || isNewNamespace) { items = this.items[cluster.name][namespace.name] = await getItems(cluster.name, namespace.name, cluster.k8sClient) } choices = choices.concat(this.createChoices(items, namespace.name, cluster.name, ...fields)) } } else { const clusterItems = this.items[cluster.name] if(!cache || Object.values(clusterItems).length === 0) { const items = await getItems(cluster.name, undefined, cluster.k8sClient) items.forEach(item => { const namespace = item.namespace ? (item.namespace.name || item.namespace) : "" if(!clusterItems[namespace]) { clusterItems[namespace] = [] } clusterItems[namespace].push(item) }) } Object.keys(clusterItems).forEach(ns => { choices = choices.concat(this.createChoices(clusterItems[ns], undefined, cluster.name, ...fields)) }) } } choices = choices.sort((c1, c2) => { let result = c1.displayItem[0].localeCompare(c2.displayItem[0]) if(result === 0 && c1.displayItem.length > 1) { result = c1.displayItem[1].localeCompare(c2.displayItem[1]) } return result }) return choices } static async storeItems(actionContext: ActionContext, getItems: GetItemsFunction, useNamespace: boolean = true, ...fields) { return this._createAndStoreItems(false, undefined, actionContext, getItems, useNamespace, ...fields) } static async storeCachedItems(cacheKey: string, actionContext: ActionContext, getItems: GetItemsFunction, useNamespace: boolean = true, ...fields) { return this._createAndStoreItems(true, cacheKey, actionContext, getItems, useNamespace, ...fields) } static async _prepareChoices(cache: boolean, cacheKey: string|undefined, actionContext: ActionContext, k8sFunction: GetItemsFunction, name: string, min: number, max: number, useNamespace: boolean = true, ...fields) { const operationId = Context.operationCounter ++this.pendingChoicesCounter if(Context.doubleSelections) { Context.doubleSelections = false Context.selections = [] } let previousSelections: any[] = cache && this.cacheKey === cacheKey ? actionContext.getSelections() : [] this.cacheKey !== cacheKey && (Context.selections = []) const choices: any[] = await ChoiceManager._createAndStoreItems(cache, cacheKey, actionContext, k8sFunction, useNamespace, ...fields) if(min === choices.length) { Context.selections = choices actionContext.onSkipChoices && actionContext.onSkipChoices() } else { let howMany = "" if(min === max && max > 0) { howMany = " " + max + " " } else { howMany = min > 0 ? " at least " + min : "" howMany += max > 0 && min > 0 ? ", and " : "" howMany += max > 0 ? " up to " + max + " " : "" } //show dialog only if no other operation has been performed by the user in the meantime if(operationId === Context.operationCounter) { actionContext.onActionInitChoices && actionContext.onActionInitChoices("Choose" + howMany + name, choices, min, max, ChoiceManager.showChoiceSubItems, previousSelections) } else if(--this.pendingChoicesCounter === 0) { actionContext.onCancelActionChoice && actionContext.onCancelActionChoice() } } } static async prepareChoices(actionContext: ActionContext, k8sFunction: GetItemsFunction, name: string, min: number, max: number, useNamespace: boolean = true, ...fields) { return this._prepareChoices(false, undefined, actionContext, k8sFunction, name, min, max, useNamespace, ...fields) } static async prepareCachedChoices(actionContext: ActionContext, k8sFunction: GetItemsFunction, name: string, min: number, max: number, useNamespace: boolean = true, ...fields) { return this._prepareChoices(true, name, actionContext, k8sFunction, name, min, max, useNamespace, ...fields) } static onActionChoiceCompleted() { this.startClearItemsTimer() } static getSelections(actionContext: ActionContext) : ItemSelection[] { return actionContext.getSelections().map(selection => selection.data) } static getDoubleSelections(actionContext: ActionContext) : ItemSelection[][] { return actionContext.getSelections().map(selection => selection.data) } static async chooseClusters(min: number = 2, max: number = 3, actionContext: ActionContext) { const clusters = actionContext.getClusters() const getCluster = async (cluster) => [Context.cluster(cluster)] if(clusters.length > max) { ChoiceManager.showChoiceSubItems = false await ChoiceManager.prepareChoices(actionContext, getCluster, "Clusters", min, max, false, "name") ChoiceManager.showChoiceSubItems = true } else { Context.selections = await ChoiceManager.storeItems(actionContext, getCluster, false, "name") actionContext.onSkipChoices && actionContext.onSkipChoices() } } static getSelectedClusters(actionContext: ActionContext) : Cluster[] { return this.getSelections(actionContext).map(s => s.item) as Cluster[] } static async chooseCRDs(min: number = 1, max: number = 5, actionContext: ActionContext) { ChoiceManager.prepareCachedChoices(actionContext, async (cluster, namespace,k8sClient) => { return K8sFunctions.getClusterCRDs(k8sClient) }, "CRDs", min, max, false, "name") } static async _chooseNamespaces(clusters: Cluster[], unique: boolean, min: number, max: number, actionContext: ActionContext) { const clusterNames = clusters.map(c => c.name) const clustersMissingNamespaces = clusters.filter(c => c.namespaces.length === 0) let namespaces = actionContext.getNamespaces().filter(ns => clusterNames.includes(ns.cluster.name)) for(const cluster of clustersMissingNamespaces) { const clusterNamespaces = await K8sFunctions.getClusterNamespaces(cluster.k8sClient) namespaces = namespaces.concat(clusterNamespaces.map(ns => { ns.cluster = cluster return ns })) } let namespaceNames: string[] = [] const uniqueFilter = ns => { if(namespaceNames.includes(ns.name)) { return false } else { namespaceNames.push(ns.name) return true } } if(unique) { namespaces = namespaces.filter(uniqueFilter) } if(namespaces.length < min) { namespaces = [] namespaceNames = [] //reset for use by uniqueFilter for(const cluster of clusters) { let clusterNamespaces = await K8sFunctions.getClusterNamespaces(cluster.k8sClient) if(unique) { clusterNamespaces = clusterNamespaces.filter(uniqueFilter) } namespaces = namespaces.concat(clusterNamespaces.map(ns => { ns.cluster = cluster return ns })) } } if(namespaces.length < min || namespaces.length > max) { ChoiceManager.showChoiceSubItems = !unique await ChoiceManager.prepareCachedChoices(actionContext, async (clusterName, namespace, k8sClient) => namespaces.filter(ns => ns.cluster.name === clusterName), "Namespaces", min, max, false, "name") ChoiceManager.showChoiceSubItems = true } else { Context.selections = await ChoiceManager.storeCachedItems("namespaces", actionContext, async (cluster, namespace, k8sClient) => namespaces.filter(ns => ns.cluster.name === cluster), false, "name") actionContext.onSkipChoices && actionContext.onSkipChoices() } } static async chooseNamespaces(unique: boolean, min: number, max: number, actionContext: ActionContext) { return ChoiceManager._chooseNamespaces(actionContext.getClusters(), unique, min, max, actionContext) } static async chooseNamespacesWithIstio(unique: boolean = false, min: number = 1, max: number = 5, actionContext: ActionContext) { const clusters = actionContext.getClusters().filter(c => c.hasIstio) return ChoiceManager._chooseNamespaces(clusters, unique, min, max, actionContext) } static async choosePods(min: number, max: number, chooseContainers: boolean, loadDetails: boolean, actionContext: ActionContext) { const clusterPods = {} ChoiceManager.prepareCachedChoices(actionContext, async (cluster, namespace, k8sClient) => { if(!clusterPods[cluster]) { clusterPods[cluster] = k8sClient.cluster.hasKubectl ? await KubectlClient.getPodsAndContainers(k8sClient.cluster) : await K8sFunctions.getAllClusterPods(k8sClient) } let pods : any[] = clusterPods[cluster] namespace && namespace.length > 0 && (pods = pods.filter(pod => pod.namespace === namespace)) if(chooseContainers) { pods = _.flatMap(pods, pod => pod.containers.map(c => { return { ...pod, name: (c.name ? c.name : c)+"@"+pod.name, } })) } return pods }, chooseContainers ? "Container@Pod" : "Pod(s)", min, max, true, "name" ) } static async chooseServicePods(serviceName: string, serviceNamespace: string, min: number = 1, max: number = 1, chooseContainers: boolean = false, loadDetails: boolean = false, actionContext: ActionContext) { ChoiceManager.prepareCachedChoices(actionContext, async (cluster, namespace, k8sClient) => { let podsAndContainers = await K8sFunctions.getPodsAndContainersForServiceName(serviceName, serviceNamespace, k8sClient, true) let pods = podsAndContainers.pods as any[] if(chooseContainers) { pods = _.flatMap(pods, pod => pod.containers.map(c => { return { ...pod, name: (c.name ? c.name : c)+"@"+pod.name, } })) } return pods }, chooseContainers ? "Container@Pod" : "Pod(s)", min, max, false, "name" ) } static async getPodSelections(actionContext: ActionContext, loadDetails: boolean = true, loadContainers: boolean = false) { const selections = actionContext.getSelections() const podSelections : PodSelection[] = [] for(const selection of selections) { const podInfo = selection.data.item const clusters = actionContext.getClusters() const k8sClient = clusters.filter(c => c.name === selection.data.cluster) .map(cluster => cluster.k8sClient)[0] const title = selection.data.name || selection.data.title const podAndContainerName = loadContainers ? title.split("@") : undefined const containerName = loadContainers ? podAndContainerName[0] : undefined const podName = loadContainers ? podAndContainerName[1] : title const podContainerDetails = loadDetails ? loadContainers ? await K8sFunctions.getContainerDetails(selection.data.namespace, podName, containerName, k8sClient) : await K8sFunctions.getPodDetails(selection.data.namespace, podName, k8sClient) : undefined selection.data.podName = podName selection.data.containerName = containerName if(podContainerDetails) { selection.data.podContainerDetails = podContainerDetails selection.data.item = podContainerDetails } selection.data.k8sClient = k8sClient const podSelection: PodSelection = { title, cluster: selection.data.cluster, namespace: selection.data.namespace, podName, containerName, podContainerDetails, item: selection.data.item, podIP: podInfo.podIP, hostIP: podInfo.hostIP, nodeName: podInfo.nodeName, k8sClient } podSelections.push(podSelection) } return podSelections } static async getClusterServices(cluster, namespace, k8sClient) { if(ChoiceManager.cachedServices[cluster]) { return (namespace && namespace.length > 0) ? ChoiceManager.cachedServices[cluster].filter(s => s.namespace === namespace) : ChoiceManager.cachedServices[cluster] } else { return (namespace && namespace.length > 0) ? await K8sFunctions.getServices(namespace, k8sClient) : await K8sFunctions.getClusterServices(k8sClient) } } static async chooseService(min, max, actionContext) { ChoiceManager.prepareCachedChoices(actionContext, ChoiceManager.getClusterServices, "Services", min, max, true, "name") } static async getServiceSelections(actionContext: ActionContext) { const selections = actionContext.getSelections() const serviceSelections : ItemSelection[] = [] for(const selection of selections) { const cluster = actionContext.getClusters().filter(c => c.name === selection.data.cluster)[0] const serviceDetails = await K8sFunctions.getServiceDetails(selection.data.name, selection.data.namespace, cluster.k8sClient) serviceDetails && serviceSelections.push({ title: serviceDetails.name+"."+serviceDetails.namespace, name: serviceDetails.name, namespace: serviceDetails.namespace, cluster: cluster.name, item: serviceDetails as any, }) } return serviceSelections } static async chooseClusterService(targetCluster: string, min, max, actionContext) { ChoiceManager.prepareCachedChoices(actionContext, async (cluster, namespace, k8sClient) => { return cluster === targetCluster ? await ChoiceManager.getClusterServices(cluster, namespace, k8sClient) : [] }, "Services", min, max, true, "name") } static async chooseServiceContainer(serviceName: string, serviceNamespace: string, serviceCluster: string, actionContext: ActionContext) { ChoiceManager.prepareCachedChoices(actionContext, async (cluster, namespace, k8sClient) => { if(cluster === serviceCluster) { let podsAndContainers = await K8sFunctions.getPodsAndContainersForServiceName(serviceName, serviceNamespace, k8sClient, true) return podsAndContainers.containers as any[] } else { return [] } }, "Container(s)", 1, 1, false, "name" ) } static async chooseServiceAndContainer(action, actionContext: ActionContext) { await ChoiceManager.doubleChoices(action, actionContext, await ChoiceManager.chooseService.bind(ChoiceManager, 1, 1, actionContext), await ChoiceManager.getServiceSelections.bind(ChoiceManager, actionContext), async serviceSelection => { const service = serviceSelection.data[0].item await ChoiceManager.chooseServiceContainer(service.name, service.namespace, serviceSelection.data[0].cluster, actionContext) }, await ChoiceManager.getSelections.bind(ChoiceManager, actionContext) ) } static async chooseServiceAndIngressPod(action, actionContext: ActionContext, maxService: number = 2, maxIngressPods: number = 2) { await ChoiceManager.doubleChoices(action, actionContext, await ChoiceManager.chooseService.bind(ChoiceManager, 1, maxService, actionContext), await ChoiceManager.getServiceSelections.bind(ChoiceManager, actionContext), async serviceSelection => { await ChoiceManager.chooseClusterIngressGatewayPods(serviceSelection.data[0].cluster, 1, maxIngressPods, actionContext) }, await ChoiceManager.getPodSelections.bind(ChoiceManager, actionContext, false, false) ) } static async doubleChoices(action, actionContext, choose1, getSelections1, choose2, getSelections2) { let selections: any[] = [] const choice2SelectionHandler = async (...args) => { selections.push({data: await getSelections2()}) Context.selections = selections Context.doubleSelections = true action.act(actionContext) } const choice1SelectionHandler = async (...args) => { selections.push({data: await getSelections1()}) actionContext.onSkipChoices = choice2SelectionHandler actionContext.onActionInitChoices = actionContext.onActionInitChoicesUnbound.bind(actionContext, choice2SelectionHandler) await choose2(selections[0]) } actionContext.onSkipChoices = choice1SelectionHandler actionContext.onActionInitChoices = actionContext.onActionInitChoicesUnbound.bind(actionContext, choice1SelectionHandler) await choose1() } static async chooseEnvoyProxy(min: number = 1, max: number = 1, actionContext: ActionContext) { const clusterEnvoyProxies = {} ChoiceManager.prepareCachedChoices(actionContext, async (cluster, namespace, k8sClient) => { let proxies: any[] = [] if(this.cachedEnvoyProxies[cluster]) { proxies = this.cachedEnvoyProxies[cluster] } else { if(!clusterEnvoyProxies[cluster]) { clusterEnvoyProxies[cluster] = await IstioFunctions.getAllEnvoyProxies(k8sClient) } proxies = clusterEnvoyProxies[cluster] } if(namespace && namespace.length > 0) { proxies = proxies.filter(p => p.namespace === namespace) } return proxies }, "Envoy Proxies", min, max, true, "title") } static getSelectedEnvoyProxies(actionContext: ActionContext) { const selections = ChoiceManager.getSelections(actionContext) return selections.map(s => { s.item.cluster = s.cluster return s.item }) } static async chooseClusterIngressGatewayPods(targetCluster: string, min: number = 1, max: number = 1, actionContext: ActionContext) { ChoiceManager.prepareCachedChoices(actionContext, async (cluster, namespace, k8sClient) => { return cluster === targetCluster ? await IstioFunctions.getIngressGatewayPodsList(k8sClient) : [] }, "IngressGateway Pods", min, max, false, "name") } static async chooseIngressGatewayPods(min: number = 1, max: number = 1, actionContext: ActionContext) { ChoiceManager.prepareCachedChoices(actionContext, async (cluster, namespace, k8sClient) => { return await IstioFunctions.getIngressGatewayPodsList(k8sClient) }, "IngressGateway Pods", min, max, false, "name") } static async choosePilotPods(min: number = 1, max: number = 1, actionContext: ActionContext) { ChoiceManager.prepareCachedChoices(actionContext, async (cluster, namespace, k8sClient) => { return await IstioFunctions.getPilotPods(k8sClient) }, "Pilot Pods", min, max, false, "name") } static async chooseIstioCRDs(min: number = 1, max: number = 10, actionContext: ActionContext) { await ChoiceManager.prepareCachedChoices(actionContext, async (cluster, namespace,k8sClient) => { return k8sClient.istio ? k8sClient.istio.crds : [] }, "Istio CRDs", 1, 10, false) } }
the_stack
import { DataType } from "../../entities/dataType"; import { GlobalFunction, GlobalTag } from "../../entities/globals"; import { Parameter } from "../../entities/parameter"; import { Signature } from "../../entities/signature"; import { equalsIgnoreCase } from "../textUtil"; import CFDocsService from "./cfDocsService"; import { CFMLEngine, CFMLEngineName } from "./cfmlEngine"; import { multiSigGlobalFunctions } from "./multiSignatures"; import * as htmlEntities from "html-entities"; const entities = new htmlEntities.AllHtmlEntities(); export interface Param { name: string; type: string; required: boolean; description?: string; default?: string; values?: string[]; } export interface EngineCompatibilityDetail { minimum_version?: string; deprecated?: string; removed?: string; notes?: string; docs?: string; } export interface EngineInfo { [name: string]: EngineCompatibilityDetail; } export interface Example { title: string; description: string; code: string; result: string; runnable?: boolean; } /** * Resolves a string value of data type to an enumeration member * @param type The data type string to resolve */ function getParamDataType(type: string): DataType { switch (type) { case "any": return DataType.Any; case "array": return DataType.Array; case "binary": return DataType.Binary; case "boolean": return DataType.Boolean; case "component": return DataType.Component; case "date": return DataType.Date; case "function": return DataType.Function; case "guid": return DataType.GUID; case "numeric": return DataType.Numeric; case "query": return DataType.Query; case "string": return DataType.String; case "struct": return DataType.Struct; case "uuid": return DataType.UUID; case "variablename": return DataType.VariableName; case "xml": return DataType.XML; default: // console.log("Unknown param type: " + type); return DataType.Any; } } /** * Resolves a string value of data type to an enumeration member * @param type The data type string to resolve */ function getReturnDataType(type: string): DataType { switch (type) { case "any": return DataType.Any; case "array": return DataType.Array; case "binary": return DataType.Binary; case "boolean": return DataType.Boolean; case "date": return DataType.Date; case "function": return DataType.Function; case "guid": return DataType.GUID; case "numeric": return DataType.Numeric; case "query": return DataType.Query; case "string": return DataType.String; case "struct": return DataType.Struct; case "uuid": return DataType.UUID; case "variablename": return DataType.VariableName; case "void": return DataType.Void; case "xml": return DataType.XML; default: return DataType.Any; // DataType.Void? } } export class CFDocsDefinitionInfo { private static allFunctionNames: string[]; private static allTagNames: string[]; public name: string; public type: string; public syntax: string; public member?: string; public script?: string; public returns?: string; public related?: string[]; public description?: string; public discouraged?: string; public params?: Param[]; public engines?: EngineInfo; public links?: string[]; public examples?: Example[]; constructor( name: string, type: string, syntax: string, member: string, script: string, returns: string, related: string[], description: string, discouraged: string, params: Param[], engines: EngineInfo, links: string[], examples: Example[] ) { this.name = name; this.type = type; this.syntax = syntax; this.member = member; this.script = script; this.returns = returns; this.related = related; this.description = description; this.discouraged = discouraged; this.params = params; this.engines = engines; this.links = links; this.examples = examples; } /** * Returns whether this object is a function */ public isFunction(): boolean { return (equalsIgnoreCase(this.type, "function")); } /** * Returns whether this object is a tag */ public isTag(): boolean { return (equalsIgnoreCase(this.type, "tag")); } /** * Returns a GlobalFunction object based on this object */ public toGlobalFunction(): GlobalFunction { let signatures: Signature[] = []; if (multiSigGlobalFunctions.has(this.name)) { let thisMultiSigs: string[][] = multiSigGlobalFunctions.get(this.name); thisMultiSigs.forEach((thisMultiSig: string[]) => { let parameters: Parameter[] = []; thisMultiSig.forEach((multiSigParam: string) => { let paramFound = false; for (const param of this.params) { let multiSigParamParsed: string = multiSigParam.split("=")[0]; if (param.name === multiSigParamParsed) { let parameter: Parameter = { name: multiSigParam, dataType: getParamDataType(param.type.toLowerCase()), required: param.required, description: param.description, default: param.default, enumeratedValues: param.values }; parameters.push(parameter); paramFound = true; break; } } if (!paramFound) { let parameter: Parameter = { name: multiSigParam, dataType: DataType.Any, required: false, description: "" }; parameters.push(parameter); } }); let signatureInfo: Signature = { parameters: parameters }; signatures.push(signatureInfo); }); } else { let parameters: Parameter[] = this.params.map((param: Param) => { return { name: param.name, dataType: getParamDataType(param.type.toLowerCase()), required: param.required, description: entities.decode(param.description), default: param.default, enumeratedValues: param.values }; }); let signatureInfo: Signature = { parameters: parameters }; signatures.push(signatureInfo); } return { name: this.name, syntax: this.syntax, description: (this.description ? entities.decode(this.description) : ""), returntype: getReturnDataType(this.returns.toLowerCase()), signatures: signatures }; } /** * Returns a GlobalTag object based on this object */ public toGlobalTag(): GlobalTag { let parameters: Parameter[] = this.params.map((param: Param) => { return { name: param.name, dataType: getParamDataType(param.type.toLowerCase()), required: param.required, description: entities.decode(param.description), default: param.default, enumeratedValues: param.values }; }); let signatureInfo: Signature = { parameters: parameters }; let signatures: Signature[] = []; signatures.push(signatureInfo); return { name: this.name, syntax: this.syntax, scriptSyntax: this.script, description: entities.decode(this.description), signatures: signatures, hasBody: true }; } /** * Checks if this definition is compatible with given engine * @param engine The CFML engine with which to check compatibility */ public isCompatible(engine: CFMLEngine): boolean { const engineVendor: CFMLEngineName = engine.getName(); if (engineVendor === CFMLEngineName.Unknown || !this.engines) { return true; } const engineCompat: EngineCompatibilityDetail = this.engines[engineVendor]; if (!engineCompat) { return false; } const engineVersion: string = engine.getVersion(); if (!engineVersion) { return true; } if (engineCompat.minimum_version) { const minEngine: CFMLEngine = new CFMLEngine(engineVendor, engineCompat.minimum_version); if (engine.isOlder(minEngine)) { return false; } } if (engineCompat.removed) { const maxEngine: CFMLEngine = new CFMLEngine(engineVendor, engineCompat.removed); if (engine.isNewerOrEquals(maxEngine)) { return false; } } return true; } /** * Gets all function names documented by CFDocs. Once retrieved, they are statically stored. */ public static async getAllFunctionNames(): Promise<string[]> { if (!CFDocsDefinitionInfo.allFunctionNames) { CFDocsDefinitionInfo.allFunctionNames = await CFDocsService.getAllFunctionNames(); } return CFDocsDefinitionInfo.allFunctionNames; } /** * Gets all tag names documented by CFDocs. Once retrieved, they are statically stored. */ public static async getAllTagNames(): Promise<string[]> { if (!CFDocsDefinitionInfo.allTagNames) { CFDocsDefinitionInfo.allTagNames = await CFDocsService.getAllTagNames(); } return CFDocsDefinitionInfo.allTagNames; } /** * Returns whether the given identifier is the name of a function documented in CFDocs * @param name The identifier to check for */ public static async isFunctionName(name: string): Promise<boolean> { let allFunctionNames: string[] = await CFDocsDefinitionInfo.getAllFunctionNames(); return allFunctionNames.includes(name.toLowerCase()); } /** * Returns whether the given identifier is the name of a tag documented in CFDocs * @param name The identifier to check for */ public static async isTagName(name: string): Promise<boolean> { let allTagNames: string[] = await CFDocsDefinitionInfo.getAllTagNames(); return allTagNames.includes(name.toLowerCase()); } /** * Returns whether the given identifier is the name of a function or tag documented in CFDocs * @param name The identifier to check for */ public static async isIdentifier(name: string): Promise<boolean> { return (CFDocsDefinitionInfo.isFunctionName(name) || CFDocsDefinitionInfo.isTagName(name)); } }
the_stack
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { OrganisationService, CatalogService, ShopEventBus, UserEventBus } from './../shared/services/index'; import { ModalComponent, ModalResult, ModalAction } from './../shared/modal/index'; import { ManagerInfoVO, ManagerVO, ShopVO, RoleVO, ProductSupplierCatalogVO, Pair, SearchResultVO } from './../shared/model/index'; import { FormValidationEvent, Futures, Future } from './../shared/event/index'; import { Config } from './../../environments/environment'; import { LogUtil } from './../shared/log/index'; @Component({ selector: 'cw-organisation-managers', templateUrl: 'organisation-managers.component.html', }) export class OrganisationManagerComponent implements OnInit, OnDestroy { private static MANAGERS:string = 'managers'; private static MANAGER:string = 'manager'; public viewMode:string = OrganisationManagerComponent.MANAGERS; public managers:SearchResultVO<ManagerInfoVO>; public managerFilter:string; private delayedFilteringManager:Future; private delayedFilteringManagerMs:number = Config.UI_INPUT_DELAY; public selectedManager:ManagerInfoVO; public managerEdit:ManagerVO; public shops:Array<ShopVO> = []; public roles:Array<RoleVO> = []; public suppliers:Array<ProductSupplierCatalogVO> = []; @ViewChild('deleteConfirmationModalDialog') private deleteConfirmationModalDialog:ModalComponent; @ViewChild('disableConfirmationModalDialog') private disableConfirmationModalDialog:ModalComponent; @ViewChild('resetConfirmationModalDialog') private resetConfirmationModalDialog:ModalComponent; public deleteValue:String; private shopAllSub:any; public loading:boolean = false; public changed:boolean = false; public validForSave:boolean = false; constructor(private _organisationService:OrganisationService, private _catalogService:CatalogService) { LogUtil.debug('OrganisationManagerComponent constructed'); this.shopAllSub = ShopEventBus.getShopEventBus().shopsUpdated$.subscribe(shopsevt => { this.shops = shopsevt; }); this.managers = this.newSearchResultInstance(); } newManagerInstance():ManagerVO { return { managerId: 0, login: null, email: null, firstName: null, lastName: null, enabled: false, companyName1: null, companyName2: null, companyDepartment: null, managerShops: [], managerRoles: [], managerSupplierCatalogs: [], managerCategoryCatalogs: [] }; } newSearchResultInstance():SearchResultVO<ManagerInfoVO> { return { searchContext: { parameters: { filter: [] }, start: 0, size: Config.UI_TABLE_PAGE_SIZE, sortBy: null, sortDesc: false }, items: [], total: 0 }; } ngOnInit() { LogUtil.debug('OrganisationManagerComponent ngOnInit'); this.onRefreshHandler(); let that = this; this.delayedFilteringManager = Futures.perpetual(function() { that.getAllManagers(); }, this.delayedFilteringManagerMs); } ngOnDestroy() { LogUtil.debug('OrganisationManagerComponent ngOnDestroy'); if (this.shopAllSub) { this.shopAllSub.unsubscribe(); } } onManagerFilterChange(event:any) { this.managers.searchContext.start = 0; // changing filter means we need to start from first page this.delayedFilteringManager.delay(); } onRefreshHandler() { LogUtil.debug('OrganisationManagerComponent refresh handler'); if (UserEventBus.getUserEventBus().current() != null) { if (this.roles == null || this.roles.length == 0) { this.getAllRoles(); } else { this.getAllManagers(); } } } onPageSelected(page:number) { LogUtil.debug('LocationsComponent onPageSelected', page); this.managers.searchContext.start = page; this.delayedFilteringManager.delay(); } onSortSelected(sort:Pair<string, boolean>) { LogUtil.debug('LocationsComponent ononSortSelected', sort); if (sort == null) { this.managers.searchContext.sortBy = null; this.managers.searchContext.sortDesc = false; } else { this.managers.searchContext.sortBy = sort.first; this.managers.searchContext.sortDesc = sort.second; } this.delayedFilteringManager.delay(); } onManagerSelected(data:ManagerVO) { LogUtil.debug('OrganisationManagerComponent onManagerSelected', data); this.selectedManager = data; } onManagerChanged(event:FormValidationEvent<ManagerVO>) { LogUtil.debug('OrganisationManagerComponent onManagerChanged', event); this.changed = true; this.validForSave = event.valid; this.managerEdit = event.source; } onBackToList() { LogUtil.debug('OrganisationManagerComponent onBackToList handler'); if (this.viewMode === OrganisationManagerComponent.MANAGER) { this.managerEdit = null; this.viewMode = OrganisationManagerComponent.MANAGERS; } } onRowNew() { LogUtil.debug('OrganisationManagerComponent onRowNew handler'); this.changed = false; this.validForSave = false; if (this.viewMode === OrganisationManagerComponent.MANAGERS) { this.managerEdit = this.newManagerInstance(); this.viewMode = OrganisationManagerComponent.MANAGER; } } onRowDelete(row:any) { LogUtil.debug('OrganisationManagerComponent onRowDelete handler', row); this.deleteValue = row.email; this.deleteConfirmationModalDialog.show(); } onRowDeleteSelected() { if (this.selectedManager != null) { this.onRowDelete(this.selectedManager); } } onRowEditManager(row:ManagerInfoVO) { LogUtil.debug('OrganisationManagerComponent onRowEditManager handler', row); this.loading = true; this._organisationService.getManagerById(row.managerId).subscribe( manager => { LogUtil.debug('OrganisationManagerComponent get manager by email', manager); this.managerEdit = manager; this.changed = false; this.validForSave = false; this.viewMode = OrganisationManagerComponent.MANAGER; this.loading = false; }); } onRowEditSelected() { if (this.selectedManager != null) { this.onRowEditManager(this.selectedManager); } } onSaveHandler() { if (this.validForSave && this.changed) { if (this.managerEdit != null) { LogUtil.debug('OrganisationManagerComponent Save handler manager', this.managerEdit); this.loading = true; this._organisationService.saveManager(this.managerEdit).subscribe( rez => { this.changed = false; this.selectedManager = rez; this.validForSave = false; this.managerEdit = null; this.loading = false; this.getAllManagers(); } ); } } } onDiscardEventHandler() { LogUtil.debug('OrganisationManagerComponent discard handler'); if (this.viewMode === OrganisationManagerComponent.MANAGER) { if (this.selectedManager != null) { this.onRowEditSelected(); } else { this.onRowNew(); } } } onDeleteConfirmationResult(modalresult: ModalResult) { LogUtil.debug('OrganisationManagerComponent onDeleteConfirmationResult modal result is ', modalresult); if (ModalAction.POSITIVE === modalresult.action) { if (this.selectedManager != null) { LogUtil.debug('OrganisationManagerComponent onDeleteConfirmationResult', this.selectedManager); this.loading = true; this._organisationService.removeManager(this.selectedManager.managerId).subscribe(res => { LogUtil.debug('OrganisationManagerComponent removeManager', this.selectedManager); this.selectedManager = null; this.managerEdit = null; this.loading = false; this.viewMode = OrganisationManagerComponent.MANAGERS; this.getAllManagers(); }); } } } onRowEnableSelected() { if (this.selectedManager != null) { this.deleteValue = this.selectedManager.email; this.disableConfirmationModalDialog.show(); } } onDisableConfirmationResult(modalresult: ModalResult) { LogUtil.debug('OrganisationManagerComponent onDisableConfirmationResult modal result is ', modalresult); if (ModalAction.POSITIVE === modalresult.action) { if (this.selectedManager != null) { this.loading = true; this._organisationService.updateDisabledFlag(this.selectedManager.managerId, this.selectedManager.enabled).subscribe( done => { LogUtil.debug('OrganisationManagerComponent updateDisabledFlag', done); this.selectedManager.enabled = !this.selectedManager.enabled; this.changed = false; this.validForSave = false; this.loading = false; }); } } } onRowResetSelected() { if (this.selectedManager != null) { this.deleteValue = this.selectedManager.email; this.resetConfirmationModalDialog.show(); } } onResetConfirmationResult(modalresult: ModalResult) { LogUtil.debug('OrganisationManagerComponent onResetConfirmationResult modal result is ', modalresult); if (ModalAction.POSITIVE === modalresult.action) { if (this.selectedManager != null) { this.loading = true; this._organisationService.resetPassword(this.selectedManager.managerId).subscribe( done => { LogUtil.debug('OrganisationManagerComponent resetPassword', done); this.changed = false; this.validForSave = false; this.loading = false; }); } } } onClearFilter() { this.managerFilter = ''; this.getAllManagers(); } private getAllManagers() { LogUtil.debug('OrganisationManagerComponent getAllManagers'); this.loading = true; this.managers.searchContext.parameters.filter = [ this.managerFilter ]; this.managers.searchContext.size = Config.UI_TABLE_PAGE_SIZE; this._organisationService.getFilteredManagers(this.managers.searchContext).subscribe( allmanagers => { LogUtil.debug('OrganisationManagerComponent getAllManagers', allmanagers); this.managers = allmanagers; this.selectedManager = null; this.managerEdit = null; this.viewMode = OrganisationManagerComponent.MANAGERS; this.changed = false; this.validForSave = false; this.loading = false; }); } private getAllRoles() { this.loading = true; this._organisationService.getAllRoles().subscribe( allroles => { LogUtil.debug('OrganisationManagerComponent getAllRoles', allroles); this.roles = allroles; this._catalogService.getAllProductSuppliersCatalogs().subscribe(allsup => { LogUtil.debug('OrganisationManagerComponent getAllProductSuppliersCatalogs', allsup); this.suppliers = allsup; this.loading = false; this.getAllManagers(); }); }); } }
the_stack
import { expect } from "chai"; import { Tenant } from "../../../emulator/auth/state"; import { expectStatusCode, registerTenant } from "./helpers"; import { describeAuthEmulator, PROJECT_ID } from "./setup"; describeAuthEmulator("tenant management", ({ authApi }) => { describe("createTenant", () => { it("should create tenants", async () => { await authApi() .post("/identitytoolkit.googleapis.com/v2/projects/project-id/tenants") .set("Authorization", "Bearer owner") .send({ allowPasswordSignup: true, disableAuth: false, displayName: "display", enableAnonymousUser: true, enableEmailLinkSignin: true, mfaConfig: { enabledProviders: ["PROVIDER_UNSPECIFIED", "PHONE_SMS"], state: "ENABLED", }, }) .then((res) => { expectStatusCode(200, res); expect(res.body.allowPasswordSignup).to.be.true; expect(res.body.disableAuth).to.be.false; expect(res.body.displayName).to.eql("display"); expect(res.body.enableAnonymousUser).to.be.true; expect(res.body.enableEmailLinkSignin).to.be.true; expect(res.body.mfaConfig).to.eql({ enabledProviders: ["PROVIDER_UNSPECIFIED", "PHONE_SMS"], state: "ENABLED", }); // Should have a non-empty tenantId and matching resource name expect(res.body).to.have.property("tenantId"); expect(res.body.tenantId).to.not.eql(""); expect(res.body).to.have.property("name"); expect(res.body.name).to.eql(`projects/project-id/tenants/${res.body.tenantId}`); }); }); it("should create a tenant with default disabled settings", async () => { await authApi() .post("/identitytoolkit.googleapis.com/v2/projects/project-id/tenants") .set("Authorization", "Bearer owner") .send({}) .then((res) => { expectStatusCode(200, res); expect(res.body.allowPasswordSignup).to.be.false; expect(res.body.disableAuth).to.be.false; expect(res.body.enableAnonymousUser).to.be.false; expect(res.body.enableEmailLinkSignin).to.be.false; expect(res.body.mfaConfig).to.eql({ state: "DISABLED", enabledProviders: [], }); }); }); }); describe("getTenants", () => { it("should get tenants", async () => { const projectId = "project-id"; const tenant = await registerTenant(authApi(), projectId, {}); await authApi() .get(`/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants/${tenant.tenantId}`) .set("Authorization", "Bearer owner") .then((res) => { expectStatusCode(200, res); expect(res.body).to.eql(tenant); }); }); it("should create tenants with default enabled settings if they do not exist", async () => { // No projects exist initially const projectId = "project-id"; await authApi() .get(`/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants`) .set("Authorization", "Bearer owner") .then((res) => { expectStatusCode(200, res); expect(res.body.tenants).to.have.length(0); }); // Get should implicitly create a tenant that does not exist const tenantId = "tenant-id"; const createdTenant: Tenant = { tenantId, name: `projects/${projectId}/tenants/${tenantId}`, allowPasswordSignup: true, disableAuth: false, enableAnonymousUser: true, enableEmailLinkSignin: true, mfaConfig: { enabledProviders: ["PHONE_SMS"], state: "ENABLED", }, }; await authApi() .get(`/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants/${tenantId}`) .set("Authorization", "Bearer owner") .then((res) => { expectStatusCode(200, res); expect(res.body).to.eql(createdTenant); }); // The newly created tenant should be returned await authApi() .get(`/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants`) .set("Authorization", "Bearer owner") .then((res) => { expectStatusCode(200, res); expect(res.body.tenants).to.have.length(1); expect(res.body.tenants[0].tenantId).to.eql(tenantId); }); }); }); describe("deleteTenants", () => { it("should delete tenants", async () => { const projectId = "project-id"; const tenant = await registerTenant(authApi(), projectId, {}); await authApi() .delete( `/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants/${tenant.tenantId}` ) .set("Authorization", "Bearer owner") .then((res) => { expectStatusCode(200, res); }); }); it("should delete tenants if request body is passed", async () => { const projectId = "project-id"; const tenant = await registerTenant(authApi(), projectId, {}); await authApi() .delete( `/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants/${tenant.tenantId}` ) .set("Authorization", "Bearer owner") // Sets content-type and sends "{}" in request payload. This is very // uncommon for HTTP DELETE requests, but clients like the Node.js Admin // SDK do it anyway. We want the emulator to tolerate this. .send({}) .then((res) => { expectStatusCode(200, res); }); }); }); describe("listTenants", () => { it("should list tenants", async () => { const projectId = "project-id"; const tenant1 = await registerTenant(authApi(), projectId, {}); const tenant2 = await registerTenant(authApi(), projectId, {}); await authApi() .get(`/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants`) .set("Authorization", "Bearer owner") .then((res) => { expectStatusCode(200, res); expect(res.body.tenants).to.have.length(2); expect(res.body.tenants.map((tenant: Tenant) => tenant.tenantId)).to.have.members([ tenant1.tenantId, tenant2.tenantId, ]); expect(res.body).not.to.have.property("nextPageToken"); }); }); it("should allow specifying pageSize and pageToken", async () => { const projectId = "project-id"; const tenant1 = await registerTenant(authApi(), projectId, {}); const tenant2 = await registerTenant(authApi(), projectId, {}); const tenantIds = [tenant1.tenantId, tenant2.tenantId].sort(); const nextPageToken = await authApi() .get(`/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants`) .set("Authorization", "Bearer owner") .query({ pageSize: 1 }) .then((res) => { expectStatusCode(200, res); expect(res.body.tenants).to.have.length(1); expect(res.body.tenants[0].tenantId).to.eql(tenantIds[0]); expect(res.body).to.have.property("nextPageToken").which.is.a("string"); return res.body.nextPageToken; }); await authApi() .get(`/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants`) .set("Authorization", "Bearer owner") .query({ pageToken: nextPageToken }) .then((res) => { expectStatusCode(200, res); expect(res.body.tenants).to.have.length(1); expect(res.body.tenants[0].tenantId).to.eql(tenantIds[1]); expect(res.body).not.to.have.property("nextPageToken"); }); }); it("should always return a page token even if page is full", async () => { const projectId = "project-id"; const tenant1 = await registerTenant(authApi(), projectId, {}); const tenant2 = await registerTenant(authApi(), projectId, {}); const tenantIds = [tenant1.tenantId, tenant2.tenantId].sort(); const nextPageToken = await authApi() .get(`/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants`) .set("Authorization", "Bearer owner") .query({ pageSize: 2 }) .then((res) => { expectStatusCode(200, res); expect(res.body.tenants).to.have.length(2); expect(res.body.tenants[0].tenantId).to.eql(tenantIds[0]); expect(res.body.tenants[1].tenantId).to.eql(tenantIds[1]); expect(res.body).to.have.property("nextPageToken").which.is.a("string"); return res.body.nextPageToken; }); await authApi() .get(`/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants`) .set("Authorization", "Bearer owner") .query({ pageToken: nextPageToken }) .then((res) => { expectStatusCode(200, res); expect(res.body.tenants || []).to.have.length(0); expect(res.body).not.to.have.property("nextPageToken"); }); }); }); describe("updateTenants", () => { it("updates tenant config", async () => { const projectId = "project-id"; const tenant = await registerTenant(authApi(), projectId, {}); const updateMask = "allowPasswordSignup,disableAuth,displayName,enableAnonymousUser,enableEmailLinkSignin,mfaConfig"; await authApi() .patch( `/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants/${tenant.tenantId}` ) .set("Authorization", "Bearer owner") .query({ updateMask }) .send({ allowPasswordSignup: true, disableAuth: false, displayName: "display", enableAnonymousUser: true, enableEmailLinkSignin: true, mfaConfig: { enabledProviders: ["PROVIDER_UNSPECIFIED", "PHONE_SMS"], state: "ENABLED", }, }) .then((res) => { expectStatusCode(200, res); expect(res.body.allowPasswordSignup).to.be.true; expect(res.body.disableAuth).to.be.false; expect(res.body.displayName).to.eql("display"); expect(res.body.enableAnonymousUser).to.be.true; expect(res.body.enableEmailLinkSignin).to.be.true; expect(res.body.mfaConfig).to.eql({ enabledProviders: ["PROVIDER_UNSPECIFIED", "PHONE_SMS"], state: "ENABLED", }); }); }); it("does not update if the field does not exist on the update tenant", async () => { const projectId = "project-id"; const tenant = await registerTenant(authApi(), projectId, {}); const updateMask = "displayName"; await authApi() .patch( `/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants/${tenant.tenantId}` ) .set("Authorization", "Bearer owner") .query({ updateMask }) .send({}) .then((res) => { expectStatusCode(200, res); expect(res.body).not.to.have.property("displayName"); }); }); it("does not update if indexing a primitive field or array on the update tenant", async () => { const projectId = "project-id"; const tenant = await registerTenant(authApi(), projectId, { displayName: "display", mfaConfig: { enabledProviders: ["PROVIDER_UNSPECIFIED", "PHONE_SMS"], }, }); const updateMask = "displayName.0,mfaConfig.enabledProviders.nonexistentField"; await authApi() .patch( `/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants/${tenant.tenantId}` ) .set("Authorization", "Bearer owner") .query({ updateMask }) .send({ displayName: "unused", mfaConfig: { enabledProviders: ["PROVIDER_UNSPECIFIED"], }, }) .then((res) => { expectStatusCode(200, res); expect(res.body.displayName).to.eql("display"); expect(res.body.mfaConfig.enabledProviders).to.eql(["PROVIDER_UNSPECIFIED", "PHONE_SMS"]); }); }); it("performs a full update if the update mask is empty", async () => { const projectId = "project-id"; const tenant = await registerTenant(authApi(), projectId, {}); await authApi() .patch( `/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants/${tenant.tenantId}` ) .set("Authorization", "Bearer owner") .send({ allowPasswordSignup: true, disableAuth: false, displayName: "display", enableAnonymousUser: true, enableEmailLinkSignin: true, mfaConfig: { enabledProviders: ["PROVIDER_UNSPECIFIED", "PHONE_SMS"], state: "ENABLED", }, }) .then((res) => { expectStatusCode(200, res); expect(res.body.allowPasswordSignup).to.be.true; expect(res.body.disableAuth).to.be.false; expect(res.body.displayName).to.eql("display"); expect(res.body.enableAnonymousUser).to.be.true; expect(res.body.enableEmailLinkSignin).to.be.true; expect(res.body.mfaConfig).to.eql({ enabledProviders: ["PROVIDER_UNSPECIFIED", "PHONE_SMS"], state: "ENABLED", }); }); }); it("performs a full update with production defaults if the update mask is empty", async () => { const projectId = "project-id"; const tenant = await registerTenant(authApi(), projectId, {}); await authApi() .patch( `/identitytoolkit.googleapis.com/v2/projects/${projectId}/tenants/${tenant.tenantId}` ) .set("Authorization", "Bearer owner") .send({}) .then((res) => { expectStatusCode(200, res); expect(res.body.allowPasswordSignup).to.be.false; expect(res.body.disableAuth).to.be.false; expect(res.body.enableAnonymousUser).to.be.false; expect(res.body.enableEmailLinkSignin).to.be.false; expect(res.body.mfaConfig).to.eql({ enabledProviders: [], state: "DISABLED", }); }); }); }); });
the_stack
import {Platform} from 'react-native'; import {WebsocketEvents} from '@constants'; import {getConfig} from '@mm-redux/selectors/entities/general'; import Store from '@store/store'; const MAX_WEBSOCKET_FAILS = 7; const MIN_WEBSOCKET_RETRY_TIME = 3000; // 3 sec const MAX_WEBSOCKET_RETRY_TIME = 300000; // 5 mins class WebSocketClient { conn?: WebSocket; connectionUrl: string; connectionTimeout: any; connectionId: string | null; token: string|null; // responseSequence is the number to track a response sent // via the websocket. A response will always have the same sequence number // as the request. responseSequence: number; // serverSequence is the incrementing sequence number from the // server-sent event stream. serverSequence: number; connectFailCount: number; eventCallback?: Function; firstConnectCallback?: Function; missedEventsCallback?: Function; reconnectCallback?: Function; errorCallback?: Function; closeCallback?: Function; connectingCallback?: Function; stop: boolean; constructor() { this.connectionUrl = ''; this.connectionId = ''; this.token = null; this.responseSequence = 1; this.serverSequence = 0; this.connectFailCount = 0; this.stop = false; } initialize(token: string|null, opts = {}) { const defaults = { forceConnection: true, connectionUrl: this.connectionUrl, }; const {connectionUrl, forceConnection, ...additionalOptions} = Object.assign({}, defaults, opts); if (forceConnection) { this.stop = false; } return new Promise((resolve, reject) => { if (this.conn) { resolve(null); return; } if (connectionUrl == null) { console.log('websocket must have connection url'); //eslint-disable-line no-console reject(new Error('websocket must have connection url')); return; } if (this.connectingCallback) { this.connectingCallback(); } const regex = /^(?:https?|wss?):(?:\/\/)?[^/]*/; const captured = (regex).exec(connectionUrl); let origin; if (captured) { origin = captured[0]; if (Platform.OS === 'android') { // this is done cause for android having the port 80 or 443 will fail the connection // the websocket will append them const split = origin.split(':'); const port = split[2]; if (port === '80' || port === '443') { origin = `${split[0]}:${split[1]}`; } } } else { // If we're unable to set the origin header, the websocket won't connect, but the URL is likely malformed anyway const errorMessage = 'websocket failed to parse origin from ' + connectionUrl; console.warn(errorMessage); // eslint-disable-line no-console reject(new Error(errorMessage)); return; } let url = connectionUrl; const config = getConfig(Store.redux?.getState()); const reliableWebSockets = config?.EnableReliableWebSockets === 'true'; if (reliableWebSockets) { // Add connection id, and last_sequence_number to the query param. // We cannot also send it as part of the auth_challenge, because the session cookie is already sent with the request. url = `${connectionUrl}?connection_id=${this.connectionId}&sequence_number=${this.serverSequence}`; } if (this.connectFailCount === 0) { console.log('websocket connecting to ' + url); //eslint-disable-line no-console } this.conn = new WebSocket(url, [], {headers: {origin}, ...(additionalOptions || {})}); this.connectionUrl = connectionUrl; this.token = token; this.conn!.onopen = () => { // No need to reset sequence number here. if (!reliableWebSockets) { this.serverSequence = 0; } if (token) { // we check for the platform as a workaround until we fix on the server that further authentications // are ignored this.sendMessage('authentication_challenge', {token}); } if (this.connectFailCount > 0) { console.log('websocket re-established connection'); //eslint-disable-line no-console if (!reliableWebSockets && this.reconnectCallback) { this.reconnectCallback(); } else if (reliableWebSockets && this.serverSequence && this.missedEventsCallback) { this.missedEventsCallback(); } } else if (this.firstConnectCallback) { this.firstConnectCallback(); } this.connectFailCount = 0; resolve(null); }; this.conn!.onclose = () => { this.conn = undefined; this.responseSequence = 1; if (this.connectFailCount === 0) { console.log('websocket closed'); //eslint-disable-line no-console } this.connectFailCount++; if (this.closeCallback) { this.closeCallback(this.connectFailCount); } let retryTime = MIN_WEBSOCKET_RETRY_TIME; // If we've failed a bunch of connections then start backing off if (this.connectFailCount > MAX_WEBSOCKET_FAILS) { retryTime = MIN_WEBSOCKET_RETRY_TIME * this.connectFailCount; if (retryTime > MAX_WEBSOCKET_RETRY_TIME) { retryTime = MAX_WEBSOCKET_RETRY_TIME; } } if (this.connectionTimeout) { clearTimeout(this.connectionTimeout); } this.connectionTimeout = setTimeout( () => { if (this.stop) { clearTimeout(this.connectionTimeout); return; } this.initialize(token, opts); }, retryTime, ); }; this.conn!.onerror = (evt: any) => { if (this.connectFailCount <= 1) { console.log('websocket error'); //eslint-disable-line no-console console.log(evt); //eslint-disable-line no-console } if (this.errorCallback) { this.errorCallback(evt); } }; this.conn!.onmessage = (evt: any) => { const msg = JSON.parse(evt.data); // This indicates a reply to a websocket request. // We ignore sequence number validation of message responses // and only focus on the purely server side event stream. if (msg.seq_reply) { if (msg.error) { console.warn(msg); //eslint-disable-line no-console } } else if (this.eventCallback) { if (reliableWebSockets) { // We check the hello packet, which is always the first packet in a stream. if (msg.event === WebsocketEvents.HELLO && this.reconnectCallback) { //eslint-disable-next-line no-console console.log('got connection id ', msg.data.connection_id); // If we already have a connectionId present, and server sends a different one, // that means it's either a long timeout, or server restart, or sequence number is not found. // Then we do the sync calls, and reset sequence number to 0. if (this.connectionId !== '' && this.connectionId !== msg.data.connection_id) { //eslint-disable-next-line no-console console.log('long timeout, or server restart, or sequence number is not found.'); this.reconnectCallback(); this.serverSequence = 0; } // If it's a fresh connection, we have to set the connectionId regardless. // And if it's an existing connection, setting it again is harmless, and keeps the code simple. this.connectionId = msg.data.connection_id; } // Now we check for sequence number, and if it does not match, // we just disconnect and reconnect. if (msg.seq !== this.serverSequence) { // eslint-disable-next-line no-console console.log('missed websocket event, act_seq=' + msg.seq + ' exp_seq=' + this.serverSequence); // We are not calling this.close() because we need to auto-restart. this.connectFailCount = 0; this.responseSequence = 1; this.conn?.close(); // Will auto-reconnect after MIN_WEBSOCKET_RETRY_TIME. return; } } else if (msg.seq !== this.serverSequence && this.reconnectCallback) { // eslint-disable-next-line no-console console.log('missed websocket event, act_seq=' + msg.seq + ' exp_seq=' + this.serverSequence); this.reconnectCallback(); } this.serverSequence = msg.seq + 1; this.eventCallback(msg); } }; }); } setConnectingCallback(callback: Function) { this.connectingCallback = callback; } setEventCallback(callback: Function) { this.eventCallback = callback; } setFirstConnectCallback(callback: Function) { this.firstConnectCallback = callback; } setMissedEventsCallback(callback: Function) { this.missedEventsCallback = callback; } setReconnectCallback(callback: Function) { this.reconnectCallback = callback; } setErrorCallback(callback: Function) { this.errorCallback = callback; } setCloseCallback(callback: Function) { this.closeCallback = callback; } close(stop = false) { this.stop = stop; this.connectFailCount = 0; this.responseSequence = 1; if (this.conn && this.conn.readyState === WebSocket.OPEN) { this.conn.close(); } } sendMessage(action: string, data: any) { const msg = { action, seq: this.responseSequence++, data, }; if (this.conn && this.conn.readyState === WebSocket.OPEN) { this.conn.send(JSON.stringify(msg)); } else if (!this.conn || this.conn.readyState === WebSocket.CLOSED) { this.conn = undefined; this.initialize(this.token); } } userTyping(channelId: string, parentId: string) { this.sendMessage('user_typing', { channel_id: channelId, parent_id: parentId, }); } getStatuses() { this.sendMessage('get_statuses', null); } getStatusesByIds(userIds: string[]) { this.sendMessage('get_statuses_by_ids', { user_ids: userIds, }); } } export default new WebSocketClient();
the_stack
import { fakeAsync, flush, tick } from '@angular/core/testing'; import { NgExpressEngineInstance } from '../engine-decorator/ng-express-engine-decorator'; import { OptimizedSsrEngine, SsrCallbackFn } from './optimized-ssr-engine'; import { RenderingStrategy, SsrOptimizationOptions, } from './ssr-optimization-options'; const defaultRenderTime = 100; /** * Helper class to easily create and test engine wrapper against mocked engine. * * Mocked engine will return sample rendering after 100 milliseconds. * * Usage: * 1. Instantiate the class with desired options * 2. Call request() to run request through engine * 3. Examine renders property for the renders */ class TestEngineRunner { /** Accumulates html output for engine runs */ renders: string[] = []; /** Accumulates response parameters for engine runs */ responseParams: object[] = []; renderCount = 0; optimizedSsrEngine: OptimizedSsrEngine; engineInstance: NgExpressEngineInstance; constructor(options: SsrOptimizationOptions, renderTime?: number) { // mocked engine instance that will render test output in 100 milliseconds const engineInstanceMock = ( filePath: string, _: any, callback: SsrCallbackFn ) => { setTimeout(() => { callback(undefined, `${filePath}-${this.renderCount++}`); }, renderTime ?? defaultRenderTime); }; this.optimizedSsrEngine = new OptimizedSsrEngine( engineInstanceMock, options ); this.engineInstance = this.optimizedSsrEngine.engineInstance; } /** Run request against the engine. The result will be stored in rendering property. */ request(url: string, params?: { httpHeaders?: { [key: string]: string } }) { const response: { [key: string]: string } = {}; const headers = new Headers(params?.httpHeaders ?? {}); const optionsMock = { req: <Partial<Request>>{ originalUrl: url, headers, get: (header: string): string | null => headers.get(header), }, res: <Partial<Response>>{ set: (key: string, value: any) => (response[key] = value), }, }; this.engineInstance(url, optionsMock, (_, html) => { this.renders.push(html ?? ''); this.responseParams.push(response); }); return this; } } const getCurrentConcurrency = ( engineRunner: TestEngineRunner ): { currentConcurrency: number } => { return { currentConcurrency: engineRunner.optimizedSsrEngine['currentConcurrency'], }; }; describe('OptimizedSsrEngine', () => { describe('timeout option', () => { it('should fallback to CSR if rendering exceeds timeout', fakeAsync(() => { const engineRunner = new TestEngineRunner({ timeout: 50 }).request('a'); tick(200); expect(engineRunner.renders).toEqual(['']); })); it('should return timed out render in the followup request', fakeAsync(() => { const engineRunner = new TestEngineRunner({ timeout: 50 }).request('a'); tick(200); expect(engineRunner.renders).toEqual(['']); engineRunner.request('a'); expect(engineRunner.renders[1]).toEqual('a-0'); })); it('should return render if rendering meets timeout', fakeAsync(() => { const engineRunner = new TestEngineRunner({ timeout: 150 }).request('a'); tick(200); expect(engineRunner.renders).toEqual(['a-0']); })); it('should fallback instantly if is set to 0', () => { const engineRunner = new TestEngineRunner({ timeout: 0 }).request('a'); expect(engineRunner.renders).toEqual(['']); }); it('should return timed out render in the followup request, also when timeout is set to 0', fakeAsync(() => { const engineRunner = new TestEngineRunner({ timeout: 0 }).request('a'); expect(engineRunner.renders).toEqual(['']); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); tick(200); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 0, }); engineRunner.request('a'); expect(engineRunner.renders[1]).toEqual('a-0'); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 0, }); })); }); describe('no-store cache control header', () => { it('should be applied for a fallback', () => { const engineRunner = new TestEngineRunner({ timeout: 0 }).request('a'); expect(engineRunner.renders).toEqual(['']); expect(engineRunner.responseParams).toEqual([ { 'Cache-Control': 'no-store' }, ]); }); it('should not be applied for a render within time limit', fakeAsync(() => { const engineRunner = new TestEngineRunner({ timeout: 200 }).request('a'); tick(200); expect(engineRunner.renders).toEqual(['a-0']); expect(engineRunner.responseParams).toEqual([{}]); })); it('should not be applied for a render served with next response', fakeAsync(() => { const engineRunner = new TestEngineRunner({ timeout: 50 }).request('a'); tick(200); engineRunner.request('a'); expect(engineRunner.renders).toEqual(['', 'a-0']); expect(engineRunner.responseParams).toEqual([ { 'Cache-Control': 'no-store' }, {}, ]); })); }); describe('cache option', () => { it('should not cache requests if disabled', fakeAsync(() => { const engineRunner = new TestEngineRunner({ cache: false, timeout: 200, }).request('a'); tick(200); engineRunner.request('a'); tick(200); engineRunner.request('a'); tick(200); expect(engineRunner.renders).toEqual(['a-0', 'a-1', 'a-2']); })); it('should cache requests if enabled', fakeAsync(() => { const engineRunner = new TestEngineRunner({ cache: true, timeout: 200, }).request('a'); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); tick(200); engineRunner.request('a'); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 0, }); tick(200); engineRunner.request('a'); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 0, }); tick(200); expect(engineRunner.renders).toEqual(['a-0', 'a-0', 'a-0']); })); }); describe('concurrency option', () => { it('should limit concurrency and fallback to csr', fakeAsync(() => { const engineRunner = new TestEngineRunner({ concurrency: 3, timeout: 200, }) .request('a') .request('b') .request('c') .request('d') .request('e'); tick(200); expect(engineRunner.renders).toEqual([ '', // CSR fallback for 'd' '', // CSR fallback for 'e' 'a-0', 'b-1', 'c-2', ]); })); it('should reinvigorate limit after emptying the queue', fakeAsync(() => { const engineRunner = new TestEngineRunner({ concurrency: 2, timeout: 200, }).request('a'); tick(60); engineRunner.request('b').request('c'); tick(60); engineRunner.request('d').request('e'); tick(200); engineRunner.request('f').request('g'); tick(200); expect(engineRunner.renders).toEqual([ '', // CSR fallback for 'c' 'a-0', '', // CSR fallback for 'e' 'b-1', 'd-2', 'f-3', 'g-4', ]); })); }); describe('ttl option', () => { it('should invalidate expired renders', fakeAsync(() => { let currentDate = 100; spyOn(Date, 'now').and.callFake(() => currentDate); const engineRunner = new TestEngineRunner({ cache: true, ttl: 300, timeout: 200, }).request('a'); tick(200); currentDate += 200; engineRunner.request('a'); tick(200); currentDate += 200; engineRunner.request('a'); tick(200); expect(engineRunner.renders).toEqual(['a-0', 'a-0', 'a-1']); })); }); describe('renderKeyResolver option', () => { it('should use custom render key resolver', fakeAsync(() => { const engineRunner = new TestEngineRunner({ renderKeyResolver: (req) => req.originalUrl.substr(0, 2), timeout: 200, cache: true, }).request('ala'); tick(200); engineRunner.request('ale'); tick(200); engineRunner.request('ela'); tick(200); engineRunner.request('alu'); tick(200); engineRunner.request('elu'); tick(200); expect(engineRunner.renders).toEqual([ 'ala-0', 'ala-0', 'ela-1', 'ala-0', 'ela-1', ]); })); }); describe('renderingStrategyResolver option', () => { describe('ALWAYS_SSR', () => { it('should ignore timeout', fakeAsync(() => { const engineRunner = new TestEngineRunner({ renderingStrategyResolver: () => RenderingStrategy.ALWAYS_SSR, timeout: 50, cache: true, }).request('a'); tick(200); expect(engineRunner.renders).toEqual(['a-0']); })); it('should ignore timeout also when it is set to 0', fakeAsync(() => { const engineRunner = new TestEngineRunner({ renderingStrategyResolver: () => RenderingStrategy.ALWAYS_SSR, timeout: 0, cache: true, }).request('a'); tick(200); expect(engineRunner.renders).toEqual(['a-0']); })); it('should render each request separately, even if there is already a pending render for the same rendering key', fakeAsync(() => { const engineRunner = new TestEngineRunner({ renderingStrategyResolver: () => RenderingStrategy.ALWAYS_SSR, timeout: 200, }); spyOn( engineRunner.optimizedSsrEngine as any, 'expressEngine' // 'expressEngine' is a protected property ).and.callThrough(); engineRunner.request('a'); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); tick(1); engineRunner.request('a'); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 2, }); expect(engineRunner.renders).toEqual([]); tick(100); expect(engineRunner.renders).toEqual(['a-0', 'a-1']); expect( engineRunner.optimizedSsrEngine['expressEngine'] ).toHaveBeenCalledTimes(2); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 0, }); })); }); describe('ALWAYS_CSR', () => { it('should return CSR instantly', fakeAsync(() => { const engineRunner = new TestEngineRunner({ renderingStrategyResolver: () => RenderingStrategy.ALWAYS_CSR, timeout: 200, cache: true, }).request('a'); tick(200); engineRunner.request('a'); tick(200); expect(engineRunner.renders).toEqual(['', '']); })); it('should not start the actual render in the background', fakeAsync(() => { const engineRunner = new TestEngineRunner({ renderingStrategyResolver: () => RenderingStrategy.ALWAYS_CSR, timeout: 200, cache: true, }); spyOn( engineRunner.optimizedSsrEngine as any, 'expressEngine' // 'expressEngine' is a protected property ).and.callThrough(); engineRunner.request('a'); expect(engineRunner.renders).toEqual(['']); expect( engineRunner.optimizedSsrEngine['expressEngine'] ).not.toHaveBeenCalled(); })); }); describe('DEFAULT', () => { it('should obey the timeout', fakeAsync(() => { const engineRunner = new TestEngineRunner({ renderingStrategyResolver: () => RenderingStrategy.DEFAULT, timeout: 50, }).request('a'); tick(200); engineRunner.request('a'); expect(engineRunner.renders).toEqual(['', 'a-0']); })); it('should fallback to CSR when there is already pending a render for the same rendering key', fakeAsync(() => { const engineRunner = new TestEngineRunner({ renderingStrategyResolver: () => RenderingStrategy.DEFAULT, timeout: 200, }).request('a'); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); tick(1); engineRunner.request('a'); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); expect(engineRunner.renders).toEqual(['']); // immediate fallback to CSR for the 2nd request for the same key tick(100); expect(engineRunner.renders).toEqual(['', 'a-0']); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 0, }); })); }); describe('custom resolver function', () => { it('should return different strategies for different types of request', fakeAsync(() => { const engineRunner = new TestEngineRunner({ renderingStrategyResolver: (req) => req.get('User-Agent')?.match(/bot|crawl|slurp|spider|mediapartners/) ? RenderingStrategy.ALWAYS_SSR : RenderingStrategy.DEFAULT, timeout: 50, }); engineRunner.request('a'); engineRunner.request('a', { httpHeaders: { 'User-Agent': 'bot' } }); tick(200); expect(engineRunner.renders).toEqual(['', 'a-1']); })); }); }); describe('forcedSsrTimeout option', () => { it('should fallback to CSR when forcedSsrTimeout timeout is exceeded for ALWAYS_SSR rendering strategy, and return the timed out render in the followup request', fakeAsync(() => { const engineRunner = new TestEngineRunner({ renderingStrategyResolver: () => RenderingStrategy.ALWAYS_SSR, timeout: 50, forcedSsrTimeout: 80, }).request('a'); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); tick(60); expect(engineRunner.renders).toEqual([]); tick(50); expect(engineRunner.renders).toEqual(['']); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 0, }); engineRunner.request('a'); expect(engineRunner.renders).toEqual(['', 'a-0']); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 0, }); })); it('should not affect DEFAULT rendering strategy', fakeAsync(() => { const engineRunner = new TestEngineRunner({ timeout: 50, forcedSsrTimeout: 80, }).request('a'); tick(60); expect(engineRunner.renders).toEqual(['']); tick(50); engineRunner.request('a'); expect(engineRunner.renders).toEqual(['', 'a-0']); })); }); describe('maxRenderTime option', () => { const fiveMinutes = 300000; it('should not kick-in for the non-hanging (normal) renders', fakeAsync(() => { const renderTime = 10; const requestUrl = 'a'; const engineRunner = new TestEngineRunner({}, renderTime).request( requestUrl ); spyOn<any>(engineRunner.optimizedSsrEngine, 'log').and.callThrough(); tick(renderTime + 1); expect(engineRunner.renderCount).toEqual(1); expect(engineRunner.optimizedSsrEngine['log']).not.toHaveBeenCalledWith( `Rendering of ${requestUrl} was not able to complete. This might cause memory leaks!`, false ); })); it('should use the default value of 5 minutes for hanging renders', fakeAsync(() => { const requestUrl = 'a'; const renderTime = fiveMinutes + 100; const engineRunner = new TestEngineRunner({}, renderTime).request( requestUrl ); spyOn<any>(engineRunner.optimizedSsrEngine, 'log').and.callThrough(); tick(fiveMinutes); expect(engineRunner.renderCount).toEqual(0); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `Rendering of ${requestUrl} was not able to complete. This might cause memory leaks!`, false ); tick(101); expect(engineRunner.renderCount).toEqual(1); })); it('should use the provided value instead of the default one', fakeAsync(() => { const requestUrl = 'a'; const renderTime = 200; const maxRenderTime = renderTime - 50; // shorter than the predicted render time const engineRunner = new TestEngineRunner( { maxRenderTime }, renderTime ).request(requestUrl); spyOn<any>(engineRunner.optimizedSsrEngine, 'log').and.callThrough(); tick(maxRenderTime); expect(engineRunner.renderCount).toEqual(0); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `Rendering of ${requestUrl} was not able to complete. This might cause memory leaks!`, false ); tick(50); expect(engineRunner.renderCount).toEqual(1); })); it('should release the concurrency slot for the hanging render', fakeAsync(() => { const hangingRequest = 'a'; const csrRequest = 'b'; const ssrRequest = 'c'; const renderTime = 200; const maxRenderTime = renderTime - 50; // shorter than the predicted render time const engineRunner = new TestEngineRunner( { concurrency: 1, maxRenderTime }, renderTime ); spyOn<any>(engineRunner.optimizedSsrEngine, 'log').and.callThrough(); // issue two requests engineRunner.request(hangingRequest); engineRunner.request(csrRequest); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); tick(1); // while the concurrency slot is busy rendering the first hanging request, the second request gets the CSR version expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `CSR fallback: Concurrency limit exceeded (1)` ); expect(engineRunner.renderCount).toEqual(0); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); tick(maxRenderTime); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `Rendering of ${hangingRequest} was not able to complete. This might cause memory leaks!`, false ); expect(engineRunner.renderCount).toEqual(0); // even though the hanging request is still rendering, we've freed up a slot for a new request engineRunner.request(ssrRequest); tick(1); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `Rendering started (${ssrRequest})` ); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); flush(); })); it('should not cache the result of the hanging render, even when it succeeds after `maxRenderTime`', fakeAsync(() => { const requestUrl = 'a'; const renderTime = fiveMinutes + 100; const engineRunner = new TestEngineRunner( { timeout: 200, cache: true, }, renderTime ).request(requestUrl); spyOn<any>(engineRunner.optimizedSsrEngine, 'log').and.callThrough(); expect(engineRunner.renders).toEqual([]); tick(fiveMinutes + 101); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `Rendering of ${requestUrl} completed after the specified maxRenderTime, therefore it was ignored.` ); expect(engineRunner.renders).toEqual(['']); engineRunner.request(requestUrl); expect(engineRunner.renders).toEqual(['']); // if the result was cached, the 2nd request would get immediately 'a-0' flush(); })); }); describe('reuseCurrentRendering', () => { const requestUrl = 'a'; const differentUrl = 'b'; const getRenderCallbacksCount = ( engineRunner: TestEngineRunner, renderingKey: string ): { renderCallbacksCount: number } => { return { renderCallbacksCount: engineRunner.optimizedSsrEngine['renderCallbacks'].get(renderingKey) ?.length ?? 0, }; }; describe('when disabled', () => { it('should fallback to CSR for parallel subsequent requests for the same rendering key', fakeAsync(() => { const timeout = 300; const engineRunner = new TestEngineRunner({ timeout }, 400); spyOn<any>(engineRunner.optimizedSsrEngine, 'log').and.callThrough(); engineRunner.request(requestUrl); expect(getRenderCallbacksCount(engineRunner, requestUrl)).toEqual({ renderCallbacksCount: 0, }); tick(200); engineRunner.request(requestUrl); expect(getRenderCallbacksCount(engineRunner, requestUrl)).toEqual({ renderCallbacksCount: 0, }); tick(100); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `CSR fallback: rendering in progress (${requestUrl})` ); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `SSR rendering exceeded timeout ${timeout}, fallbacking to CSR for ${requestUrl}`, false ); expect(engineRunner.renders).toEqual(['', '']); flush(); })); }); describe('when enabled', () => { describe('multiple subsequent requests for the same rendering key should reuse the same render', () => { it('and the first request should timeout', fakeAsync(() => { const timeout = 300; const engineRunner = new TestEngineRunner( { timeout, reuseCurrentRendering: true }, 400 ); spyOn<any>(engineRunner.optimizedSsrEngine, 'log').and.callThrough(); engineRunner.request(requestUrl); tick(200); engineRunner.request(requestUrl); tick(100); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `SSR rendering exceeded timeout ${timeout}, fallbacking to CSR for ${requestUrl}`, false ); tick(100); expect(engineRunner.renderCount).toEqual(1); expect(engineRunner.renders).toEqual(['', `${requestUrl}-0`]); flush(); })); it('and honour the timeout option', fakeAsync(() => { const timeout = 300; const engineRunner = new TestEngineRunner( { timeout, reuseCurrentRendering: true }, 1000 ); const logSpy = spyOn<any>( engineRunner.optimizedSsrEngine, 'log' ).and.callThrough(); engineRunner.request(requestUrl); tick(200); engineRunner.request(requestUrl); //1st times out tick(100); // 2nd request times out tick(200); let renderExceedMessageCount = 0; logSpy.calls.allArgs().forEach((args: unknown[]) => { args.forEach((message: unknown) => { if ( message === `SSR rendering exceeded timeout ${timeout}, fallbacking to CSR for ${requestUrl}` ) { renderExceedMessageCount++; } }); }); expect(renderExceedMessageCount).toBe(2); expect(engineRunner.renderCount).toEqual(0); expect(engineRunner.renders).toEqual(['', '']); flush(); })); it('also when the rendering strategy is ALWAYS_SSR', fakeAsync(() => { const timeout = 300; const engineRunner = new TestEngineRunner( { timeout, reuseCurrentRendering: true, renderingStrategyResolver: () => RenderingStrategy.ALWAYS_SSR, }, 400 ); engineRunner.request(requestUrl); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); expect(getRenderCallbacksCount(engineRunner, requestUrl)).toEqual({ renderCallbacksCount: 1, }); tick(200); engineRunner.request(requestUrl); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); expect(getRenderCallbacksCount(engineRunner, requestUrl)).toEqual({ renderCallbacksCount: 2, }); tick(200); expect(engineRunner.renderCount).toEqual(1); expect(engineRunner.renders).toEqual([ `${requestUrl}-0`, `${requestUrl}-0`, ]); flush(); })); it('and take up only one concurrent slot', fakeAsync(() => { const timeout = 300; const engineRunner = new TestEngineRunner( { timeout, reuseCurrentRendering: true, concurrency: 2 }, 400 ); spyOn<any>(engineRunner.optimizedSsrEngine, 'log').and.callThrough(); // start 1st request engineRunner.request(requestUrl); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); expect(getRenderCallbacksCount(engineRunner, requestUrl)).toEqual({ renderCallbacksCount: 1, }); // start 2nd request tick(200); engineRunner.request(requestUrl); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); expect(getRenderCallbacksCount(engineRunner, requestUrl)).toEqual({ renderCallbacksCount: 2, }); // start 3rd request engineRunner.request(requestUrl); expect(getRenderCallbacksCount(engineRunner, requestUrl)).toEqual({ renderCallbacksCount: 3, }); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); // 1st request timeout tick(100); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `SSR rendering exceeded timeout ${timeout}, fallbacking to CSR for ${requestUrl}`, false ); expect(engineRunner.renders).toEqual(['']); // the first request fallback to CSR due to timeout expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); // the render still continues in the background // eventually the render succeeds and 2 remaining requests get the same response: tick(100); expect(engineRunner.renderCount).toEqual(1); expect(engineRunner.renders).toEqual([ '', // CSR fallback of the 1st request due to it timed out `${requestUrl}-0`, `${requestUrl}-0`, ]); expect(getRenderCallbacksCount(engineRunner, requestUrl)).toEqual({ renderCallbacksCount: 0, }); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 0, }); flush(); })); it('and concurrency limit should NOT fallback to CSR, when the request is for a pending render', fakeAsync(() => { const engineRunner = new TestEngineRunner({ reuseCurrentRendering: true, timeout: 200, concurrency: 1, }); spyOn<any>(engineRunner.optimizedSsrEngine, 'log').and.callThrough(); engineRunner.request('a'); engineRunner.request('a'); tick(200); expect( engineRunner.optimizedSsrEngine['log'] ).not.toHaveBeenCalledWith( `CSR fallback: Concurrency limit exceeded (1)` ); expect(engineRunner.renders).toEqual(['a-0', 'a-0']); })); it('combined with a different request should take up two concurrency slots', fakeAsync(() => { const timeout = 300; const engineRunner = new TestEngineRunner( { timeout, reuseCurrentRendering: true, concurrency: 2 }, 200 ); engineRunner .request(requestUrl) .request(requestUrl) .request(requestUrl) .request(requestUrl) .request(requestUrl); tick(20); expect(getRenderCallbacksCount(engineRunner, requestUrl)).toEqual({ renderCallbacksCount: 5, }); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); engineRunner.request(differentUrl); tick(20); expect(getRenderCallbacksCount(engineRunner, differentUrl)).toEqual({ renderCallbacksCount: 1, }); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 2, }); tick(250); expect(engineRunner.renders).toEqual([ 'a-0', 'a-0', 'a-0', 'a-0', 'a-0', 'b-1', ]); expect(getRenderCallbacksCount(engineRunner, requestUrl)).toEqual({ renderCallbacksCount: 0, }); expect(getRenderCallbacksCount(engineRunner, differentUrl)).toEqual({ renderCallbacksCount: 0, }); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 0, }); flush(); })); }); describe('combined with maxRenderTime option', () => { it('should free up only one concurrent slot when the render is hanging for many waiting requests', fakeAsync(() => { const hangingRequest = 'a'; const ssrRequest = 'b'; const renderTime = 200; const maxRenderTime = renderTime - 50; // shorter than the predicted render time const engineRunner = new TestEngineRunner( { concurrency: 2, maxRenderTime, reuseCurrentRendering: true }, renderTime ); spyOn<any>(engineRunner.optimizedSsrEngine, 'log').and.callThrough(); engineRunner.request(hangingRequest); engineRunner.request(hangingRequest); engineRunner.request(hangingRequest); tick(1); expect(engineRunner.renderCount).toEqual(0); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); expect(getRenderCallbacksCount(engineRunner, hangingRequest)).toEqual( { renderCallbacksCount: 3, } ); tick(maxRenderTime); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `Rendering of ${hangingRequest} was not able to complete. This might cause memory leaks!`, false ); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 0, }); expect(getRenderCallbacksCount(engineRunner, hangingRequest)).toEqual( { renderCallbacksCount: 0, } ); // even though the hanging request is still rendering, we've freed up a slot for a new request engineRunner.request(ssrRequest); tick(1); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `Rendering started (${ssrRequest})` ); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 1, }); expect(getRenderCallbacksCount(engineRunner, ssrRequest)).toEqual({ renderCallbacksCount: 1, }); flush(); expect(getCurrentConcurrency(engineRunner)).toEqual({ currentConcurrency: 0, }); expect(getRenderCallbacksCount(engineRunner, ssrRequest)).toEqual({ renderCallbacksCount: 0, }); })); }); it('should perform separate renders for different rendering keys', fakeAsync(() => { const timeout = 300; const engineRunner = new TestEngineRunner( { timeout, reuseCurrentRendering: true }, 400 ); spyOn<any>(engineRunner.optimizedSsrEngine, 'log').and.callThrough(); engineRunner.request(requestUrl); tick(200); engineRunner.request(differentUrl); tick(300); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `SSR rendering exceeded timeout ${timeout}, fallbacking to CSR for ${requestUrl}`, false ); expect(engineRunner.optimizedSsrEngine['log']).toHaveBeenCalledWith( `SSR rendering exceeded timeout ${timeout}, fallbacking to CSR for ${differentUrl}`, false ); expect(engineRunner.renderCount).toEqual(1); expect(engineRunner.renders).toEqual(['', '']); flush(); })); }); }); });
the_stack
import { DevSkimAutoFixEdit, DevskimRuleSeverity, IDevSkimSettings } from "../devskimObjects"; import { Range } from 'vscode-languageserver'; import { SourceContext } from "./sourceContext"; import { DocumentUtilities } from './document'; /** * Class to handle Suppressions (i.e. comments that direct devskim to ignore a finding for either a period of time or permanently) * a suppression in practice would look something like this (assuming a finding in a C file): * * strcpy(a,b); //DevSkim: ignore DS185832 until 2016-12-28 * * The comment after strcpy (which DevSkim would normally flag) tells devskim to ignore that specific finding (as Identified by the DS185832 - the strcpy rule) * until 2016-12-28. prior to that date DevSkim shouldn't flag the finding. After that date it should. This is an example of a temporary suppression, and is used * when the dev wants to fix something but is busy with other work at the moment. If the date is omitted DevSkim will never flag that finding again (provided the * suppression comment remains next to the finding). * * The logic to determine if a finding should be suppressed, as well as the logic to create the code action to add a suppression exist in this class * @export * @class DevSkimSuppression */ export class DevSkimSuppression { public static suppressionRegEx: RegExp = /DevSkim: ignore ([^\s]+)(?:\suntil ((\d{4})-(\d{2})-(\d{2})))?/i; public static reviewRegEx: RegExp = /DevSkim: reviewed ([^\s]+)(?:\son ((\d{4})-(\d{2})-(\d{2})))?/i; /** * Instantiate a Suppressions object. This is necessary to insert a new suppression, but if * the only action necessary is checking if a finding is already suppressed, the static method * isFindingCommented() should be used without instantiating the class * @param dsSettings - the current settings, necessary to determine preferred comment style and reviewer name */ constructor(public dsSettings: IDevSkimSettings) { } /** * Create an array of Code Action(s) for the user to invoke should they want to suppress or mark a finding reviews * * @param {string} ruleID the rule to be suppressed * @param {string} documentContents the current document * @param {number} startCharacter the start point of the finding * @param {number} lineStart the line the finding starts on * @param {string} langID the language for the file according to VSCode (so that we can get the correct comment syntax) * @param {DevskimRuleSeverity} ruleSeverity (option) the severity of the rule - necessary if the rule is a Manual Review rule, since slightly different * logic is employed because of the different comment string. If omitted, assume a normal suppression * @returns {DevSkimAutoFixEdit[]} an array of code actions for suppressions (usually "Suppress X Days" and "Suppress Indefinitely") * * @memberOf DevSkimSuppression */ public createActions(ruleID: string, documentContents: string, startCharacter: number, lineStart: number, langID: string, ruleSeverity: DevskimRuleSeverity): DevSkimAutoFixEdit[] { let codeActions: DevSkimAutoFixEdit[] = []; let isReviewRule = (ruleSeverity !== undefined && ruleSeverity != null && ruleSeverity == DevskimRuleSeverity.ManualReview); //if this is a suppression and temporary suppressions are enabled (i.e. the setting for suppression duration is > 0) then //first add a code action for a temporary suppression if (!isReviewRule && this.dsSettings.suppressionDurationInDays > 0) { codeActions.push(this.addAction(ruleID, documentContents, startCharacter, lineStart, langID, isReviewRule, this.dsSettings.suppressionDurationInDays)); } //now either add a code action to mark this reviewed, or to suppress the finding indefinitely codeActions.push(this.addAction(ruleID, documentContents, startCharacter, lineStart, langID, isReviewRule)); return codeActions; } /** * Create a Code Action for the user to invoke should they want to suppress a finding * * @private * @param {string} ruleID the rule to be suppressed * @param {string} documentContents the current document * @param {number} startCharacter the start point of the finding * @param {number} lineStart the line the finding starts on * @param {string} langID the language for the file according to VSCode (so that we can get the correct comment syntax) * @param {boolean} isReviewRule true if this is a manual review rule - the text is slightly different if it is * @param {number} daysOffset the number of days in the future a time based suppression should insert, comes from the user settings * @returns {DevSkimAutoFixEdit[]} an array of code actions for suppressions (usually "Suppress X Days" and "Suppress Indefinitely") * * @memberOf DevSkimSuppression */ private addAction(ruleID: string, documentContents: string, startCharacter: number, lineStart: number, langID: string, isReviewRule: boolean, daysOffset: number = -1): DevSkimAutoFixEdit { let action: DevSkimAutoFixEdit = Object.create(null); let regex: RegExp = (isReviewRule) ? DevSkimSuppression.reviewRegEx : DevSkimSuppression.suppressionRegEx; let startingWhitespace = " "; this.setActionFixName(isReviewRule, action, ruleID, daysOffset); //make the day in the future that a time based expression will expire const date = new Date(); if (!isReviewRule && daysOffset > 0) { date.setDate(date.getDate() + daysOffset); } //find the end of the current line of the finding let XRegExp = require('xregexp'); let range: Range; let match; //start off generating a new suppression. If its going on the same line as the finding look for the //newline (if it exists) and insert just before it if(this.dsSettings.suppressionCommentPlacement == "same line as finding") { //check to see if this is the end of the document or not, as there is no newline at the end match = XRegExp.exec(documentContents, DocumentUtilities.newlinePattern, startCharacter); if (match) { let columnStart = (lineStart == 0) ? match.index : match.index - documentContents.substr(0, match.index).lastIndexOf("\n") - 1; range = Range.create(lineStart, columnStart, lineStart, columnStart + match[0].length); documentContents = documentContents.substr(0, match.index); } else { //replace with end of file let columnStart = (lineStart == 0) ? documentContents.length : documentContents.length - documentContents.lastIndexOf("\n") - 1; range = Range.create(lineStart, columnStart, lineStart, columnStart); } } //if the suppression goes on the line above the logic is much simpler - we just insert at the front //of the line and below we add a newline at the end of the suppression else { range = Range.create(lineStart, 0, lineStart, 0); startingWhitespace = DocumentUtilities.GetLeadingWhiteSpace(documentContents, lineStart); } // if there is an existing suppression that has expired (or there for a different issue) // then it needs to be replaced let existingSuppression : DevSkimSuppressionFinding; let suppressionStart : number = startCharacter; let suppressionLine : number = lineStart; //this checks for any existing suppression, regardless of whether it is expired, or for a different finding, because regardless //that comment gets modified existingSuppression= DevSkimSuppression.isFindingCommented(startCharacter,documentContents,ruleID,langID, isReviewRule, true); //yep, there is an existing suppression, so start working off of its location if (existingSuppression.showSuppressionFinding) { suppressionStart = DocumentUtilities.GetDocumentPosition(documentContents, existingSuppression.suppressionRange.start.line); suppressionLine = existingSuppression.suppressionRange.start.line; } //now get the actual suppression text out so it can be modified match = XRegExp.exec(documentContents, regex, suppressionStart); if (match && DocumentUtilities.GetLineNumber(documentContents, match.index) == suppressionLine) { //parse the existing suppression and set the range/text to modify it let columnStart: number = (suppressionLine == 0) ? match.index : match.index - documentContents.substr(0, match.index).lastIndexOf("\n") - 1; range = Range.create(suppressionLine, columnStart, suppressionLine, columnStart + match[0].length); if (match[1] !== undefined && match[1] != null && match[1].length > 0) { //the existing ruleID was found, so just set it to that string (may include other rules too) //this would be an instance where the date has expired if (match[1].indexOf(ruleID) >= 0) { ruleID = match[1]; } //the finding rule id wasn't found, so this is an instance where there is a separate finding suppressed //on the same line. Append else { ruleID = ruleID + "," + match[1]; } } if (isReviewRule || daysOffset > 0) { action.text = this.makeActionString(ruleID, isReviewRule, date); } else { action.text = this.makeActionString(ruleID, isReviewRule); } } // if there is not an existing suppression we need to create the full suppression text else { let StartComment: string = ""; let EndComment : string = ""; //select the right comment type, based on the user settings and the //comment capability of the programming language if(this.dsSettings.suppressionCommentStyle == "block") { StartComment = SourceContext.GetBlockCommentStart(langID); EndComment = SourceContext.GetBlockCommentEnd(langID); if (!StartComment || StartComment.length < 1 || !EndComment || EndComment.length < 1) { StartComment = SourceContext.GetLineComment(langID); } } else { StartComment = SourceContext.GetLineComment(langID); if (!StartComment || StartComment.length < 1) { StartComment = SourceContext.GetBlockCommentStart(langID); EndComment = SourceContext.GetBlockCommentEnd(langID); } } let optionalNewline: string = ""; //we will need a newline if this suppression is supposed to go above the finding if (this.dsSettings.suppressionCommentPlacement == "line above finding") { optionalNewline = DocumentUtilities.GetNewlineCharacter(documentContents); } //make the actual text inserted as the suppression if (isReviewRule || daysOffset > 0) { action.text = startingWhitespace + StartComment + this.makeActionString(ruleID, isReviewRule, date) + " " + EndComment + optionalNewline; } else { action.text = startingWhitespace + StartComment + this.makeActionString(ruleID, isReviewRule) + " " + EndComment + optionalNewline; } } action.range = range; return action; } /** * Create the string that goes into the IDE UI to allow a user to automatically create a suppression * @param isReviewRule True if this is a manual review rule - the text is slightly different if it is * @param action the associated action that is triggered when the user clicks on this name in the IDE UI * @param ruleID the rule id for the current finding * @param daysOffset how many days to suppress the finding, if this */ private setActionFixName(isReviewRule: boolean, action: DevSkimAutoFixEdit, ruleID: string, daysOffset: number = -1) { // These are the strings that appear on the light bulb menu to the user. // @todo: make localized. Right now these are the only hard coded strings in the app. // The rest come from the rules files and we have plans to make those localized as well if (isReviewRule) { action.fixName = `DevSkim: Mark ${ruleID} as Reviewed`; } else if (daysOffset > 0) { action.fixName = `DevSkim: Suppress ${ruleID} for ${daysOffset.toString(10)} days`; } else { action.fixName = `DevSkim: Suppress ${ruleID} permanently`; } } /** * Determine if there is a suppression comment in the line of the finding, if it * corresponds to the rule that triggered the finding, and if there is a date the suppression * expires. Return true if the finding should be suppressed for now, so that it isn't added * to the list of diagnostics * * @private * @param {number} startPosition the start of the finding in the document (#of chars from the start) * @param {string} documentContents the content containing the finding * @param {string} ruleID the rule that triggered the finding * @param {string} langID the VS Code language ID for the file being analyzed (to look up comment syntax) * @param {boolean} isReviewRule true if this is a manual review rule, otherwise false, as the comment syntax is different for review rules * @param {boolean} anySuppression will look for any suppression, regardless of if it doesn't match ruleID, or is expired * @returns {boolean} true if this finding should be ignored, false if it shouldn't * * @memberOf DevSkimWorker */ public static isFindingCommented(startPosition: number, documentContents: string, ruleID: string, langID : string, isReviewRule: boolean, anySuppression : boolean = false): DevSkimSuppressionFinding { let XRegExp = require('xregexp'); let regex: RegExp = (isReviewRule) ? DevSkimSuppression.reviewRegEx : DevSkimSuppression.suppressionRegEx; let line : string; let returnFinding : DevSkimSuppressionFinding; //its a little ugly to have a local function, but this is a convenient way of recalling this code repeatedly //while not exposing it to any other function. This code checks to see if a suppression for the current issue //is present in the line of code being analyzed. It also allows the use of the current Document without increasing //its memory footprint, given that this code has access to the parent function scope as well /** * Check if the current finding is suppressed on the line of code provided * @param line the line of code to inspect for a suppression * @param startPosition where in the document the line starts (for calculating line number) * * @returns {DevSkimSuppressionFinding} a DevSkimSuppressionFinding - this object is used to highlight the DS#### in the suppression * so that mousing over it provides details on what was suppressed */ let suppressionCheck = (line: string, startPosition: number) : DevSkimSuppressionFinding => { let finding: DevSkimSuppressionFinding = Object.create(null); finding.showSuppressionFinding = false; //look for the suppression comment let match = XRegExp.exec(line, regex); if (match) { let suppressionIndex : number = match[0].indexOf(ruleID); if (suppressionIndex > -1 || anySuppression) { let lineStart : number = DocumentUtilities.GetLineNumber(documentContents,startPosition); suppressionIndex += match.index; finding.suppressionRange = Range.create(lineStart, suppressionIndex, lineStart, suppressionIndex + ruleID.length); finding.noRange = false; if (!isReviewRule && match[2] !== undefined && match[2] != null && match[2].length > 0) { const untilDate: number = Date.UTC(match[3], match[4] - 1, match[5], 0, 0, 0, 0); //we have a match of the rule, and haven't yet reached the "until" date, so ignore finding //if the "until" date is less than the current time, the suppression has expired and we should not ignore if (untilDate > Date.now() || anySuppression) { finding.showSuppressionFinding = true; } } else //we have a match with the rule (or all rules), and no "until" date, so we should ignore this finding { finding.showSuppressionFinding = true; } } else if (match[0].indexOf("all") > -1) { finding.showSuppressionFinding = true; finding.noRange = true; } } return finding; }; let lineNumber : number = DocumentUtilities.GetLineNumber(documentContents,startPosition); startPosition = DocumentUtilities.GetDocumentPosition(documentContents, lineNumber); line = DocumentUtilities.GetPartialLine(documentContents, startPosition); returnFinding = suppressionCheck(line, startPosition); //we didn't find a suppression on the same line, but it might be a comment on the previous line if(!returnFinding.showSuppressionFinding) { lineNumber--; while(lineNumber > -1) { //get the start position of the current line we are looking for a comment in startPosition = DocumentUtilities.GetDocumentPosition(documentContents, lineNumber); //extract the line, and trim off the trailing space // let match = XRegExp.exec(documentContents, DocumentUtilities.newlinePattern, startPosition); //let secondLastMatch = (lineNumber -1 > -1) ? XRegExp.exec(documentContents, DocumentUtilities.newlinePattern, DocumentUtilities.GetDocumentPosition(documentContents, lineNumber -1)) : false; //let lastMatch = (secondLastMatch) ? secondLastMatch.index : startPosition; //let subDoc : string = documentContents.substr(0, (match) ? match.index : startPosition); let subDoc : string = DocumentUtilities.GetLineFromPosition(documentContents, startPosition); //check if the last line is a full line comment if(SourceContext.IsLineCommented(langID, subDoc)) { returnFinding = suppressionCheck(subDoc, startPosition); if(returnFinding.showSuppressionFinding) { break; } } //check if its part of a block comment else if(SourceContext.IsLineBlockCommented(langID, documentContents, lineNumber)) { let commentStart : number = SourceContext.GetStartOfLastBlockComment(langID,documentContents.substr(0,startPosition + subDoc.length)); let doc : string = DocumentUtilities.GetLineFromPosition(documentContents, commentStart).trim(); if(SourceContext.GetStartOfLastBlockComment(langID,doc) == 0) { returnFinding = suppressionCheck(subDoc, commentStart); if(returnFinding.showSuppressionFinding) { break; } } } else { break; } lineNumber--; } } return returnFinding; } /** * Generate the string that gets inserted into a comment for a suppression * * @private * @param {string} ruleIDs the DevSkim Rule ID that is being suppressed or reviewed (e.g. DS102158). Can be a list of IDs, comma separated (eg. DS102158,DS162445) if suppressing * multiple issues on a single line * @param {boolean} isReviewRule different strings are used if this is a code review rule versus a normal rule; one is marked reviewed and the other suppressed * @param {Date} date (optional) if this is a manual review rule (i.e. rule someone has to look at) this should be today's date, signifying that the person has reviewed the finding today. * if it is a suppression (i.e. a normal finding) this is the date that they would like to be reminded of the finding. For example, if someone suppresses a finding for * thirty days this should be today + 30 days. If omitted for a suppression the finding will be suppressed permanently * @returns {string} * * @memberOf DevSkimSuppression */ private makeActionString(ruleIDs: string, isReviewRule: boolean, date?: Date): string { let actionString: string = (isReviewRule) ? "DevSkim: reviewed " : "DevSkim: ignore "; actionString += ruleIDs; if (date !== undefined && date != null && (date.getTime() > Date.now() || isReviewRule)) { //both month and day should be in two digit format, so prepend a "0". Also, month is 0 indexed so needs to be incremented //to be in a format that reflects how months are actually represented by humans (and every other programming language) const day: string = (date.getDate() > 9) ? date.getDate().toString() : "0" + date.getDate().toString(); const month: string = ((date.getMonth() + 1) > 9) ? (date.getMonth() + 1).toString(10) : "0" + (date.getMonth() + 1).toString(10); actionString = (isReviewRule) ? actionString + " on " : actionString + " until "; actionString = actionString + date.getFullYear() + "-" + month + "-" + day; } if (isReviewRule && this.dsSettings.manualReviewerName !== undefined && this.dsSettings.manualReviewerName != null && this.dsSettings.manualReviewerName.length > 0) { actionString = `${actionString} by ${this.dsSettings.manualReviewerName}`; } return actionString; } } export class DevSkimSuppressionFinding { /** * True to display the suppression finding * e.g. put an informational squiggle with the finding text on the DS##### * in the suppression */ public showSuppressionFinding: boolean; /** * The location of DS###### in the suppression */ public suppressionRange: Range; /** * true if suppressionRange wasn't set or should be ignored but showSuppressionFinding is true * used because verifying that all of the range values were appropriately set is a pain */ public noRange : boolean; }
the_stack
import { EditCrmItem } from '../edit-crm-item/edit-crm-item'; import { Polymer } from '../../../../tools/definitions/polymer'; import { I18NKeys } from '../../../_locales/i18n-keys'; declare const browserAPI: browserAPI; export interface CRMColumnElement extends HTMLElement { index: number; items: (CRM.Node & { expanded: boolean; name: string; shadow: boolean; index: number; hiddenOnCrmType: boolean; })[]; } namespace EditCrmElement { export const editCrmProperties: { crm: CRMBuilder; crmLoading: boolean; crmEmpty: boolean; isSelecting: boolean; isAdding: boolean; isAddingOrSelecting: boolean; appExists: boolean; } = { crm: { type: Array, value: [], notify: true }, crmLoading: { type: Boolean, value: true, notify: true }, crmEmpty: { type: Boolean, value: false, notify: true, computed: '_isCrmEmpty(crm, crmLoading)' }, /** * Whether the user is currently selecting nodes to remove * * @attribute isSelecting * @type Boolean * @default false */ isSelecting: { type: Boolean, value: false, notify: true }, /** * Whether the user is adding a node * * @attribute isAdding * @type Boolean * @default false */ isAdding: { type: Boolean, value: false, notify: true }, /** * Whether the user is adding or selecting a node * * @attribute isAddingOrSelecting * @type Boolean * @default false */ isAddingOrSelecting: { type: Boolean, value: false, notify: true, computed: '_isAddingOrSelecting(isAdding, isSelecting)' }, /** * Whether the window.app element is registered yet */ appExists: { type: Boolean, value: false, notify: true } } as any; interface CRMColumn { list: (CRM.Node & { expanded: boolean; name: string; shadow: boolean; index: number; hiddenOnCrmType: boolean; })[]; dragging: boolean; draggingItem: EditCrmItem; } interface CRMBuilderColumn { list: (CRM.Node & { expanded: boolean; name: string; shadow: boolean; index: number; isPossibleAddLocation?: boolean; hiddenOnCrmType: boolean; })[]; menuPath: number[]; indent: void[]; index: number; shadow: boolean; isEmpty: boolean; } type CRMBuilder = CRMBuilderColumn[]; namespace Sortable { export interface Instance { option<T>(name: string, value?: T): T; closest(el: string, selector?: HTMLElement): HTMLElement|null; toArray(): string[]; sort(order: string[]): void; save(): void; destroy(): void; } type SortableEvent<T, U> = Event & { /** * List in which the element is moved */ to: U; /** * Previous list */ from: U; /** * Dragged element */ item: T; clone: T; oldIndex: number; newIndex: number; originalEvent: MouseEvent; }; type DragEvent<T, U> = Event & { /** * List in which the element is moved */ to: U; /** * Previous list */ from: U; /** * Dragged element */ dragged: T; draggedRect: ClientRect; related: T; relatedRect: ClientRect; }; export interface Sortable { new<T extends HTMLElement, U extends HTMLElement>(target: HTMLElement, options: { group?: string; sort?: boolean; delay?: number; disabled?: boolean; store?: any; animation?: number; handle?: string; filter?: string; preventOnFilter?: boolean; draggable?: string; ghostClass?: string; chosenClass?: string; dragClass?: string; dataIdAttr?: string; forceFallback?: boolean; fallbackClass?: string; fallbackOnBody?: boolean; fallbackTolerance?: number; scroll: boolean; scrollFn?(offsetX: number, offsetY: number, originalEvent: Event): void; scrollSensitivirt?: number; scrollSpeed?: number; setData?(dataTransfer: any, dragEl: T): void; onChoose?(evt: SortableEvent<T, U>): void; onStart?(evt: SortableEvent<T, U>): void; onEnd?(evt: SortableEvent<T, U>): void; onAdd?(evt: SortableEvent<T, U>): void; onUpdate?(evt: SortableEvent<T, U>): void; onSort?(evt: SortableEvent<T, U>): void; onFilter?(evt: SortableEvent<T, U>): void; onMove?(evt: DragEvent<T, U>, originalEvent: Event): void; onClone?(evt: SortableEvent<T, U>): void; }): Instance; } } declare const Sortable: Sortable.Sortable; export class EC { static is: string = 'edit-crm'; /** * The currently used timeout for settings the crm */ private static _currentTimeout: number = null; /** * The currently used set menus */ static setMenus: number[] = []; /** * A list of selected nodes */ static selectedElements: number[] = []; /** * A list of all the column elements */ private static _columns: CRMColumnElement[] = []; /** * The sortable object */ private static _sortables: Sortable.Instance[] = []; /** * Whether sortable is listening for drag events */ static dragging: boolean = false; /** * The type of the node that's being added */ static addingType: CRM.NodeType|null = null; static properties = editCrmProperties; static listeners = { 'crmTypeChanged': '_typeChanged' }; static _addNodeType(this: EditCrm, nodeType: CRM.NodeType) { return this.___(I18NKeys.options.editCrm.addNodeType, window.app ? window.app.crm.getI18NNodeType(nodeType) : `{{${nodeType}}}` ); } static _isColumnEmpty(this: EditCrm, column: CRMColumn): boolean { return column.list.length === 0 && !this.isAdding; }; static _isCrmEmpty(this: EditCrm, crm: CRM.Tree, crmLoading: boolean): boolean { return !crmLoading && crm.length === 0; }; static _getAriaLabel(this: EditCrm, item: CRM.Node): string { return this.___(I18NKeys.options.editCrm.editItem, item.name); }; static _isAddingOrSelecting(this: EditCrm) { return this.isAdding || this.isSelecting; } /** * Gets the columns in this crm-edit element */ private static _getColumns(this: EditCrm): CRMColumnElement[] { //Check if the nodes still exist if (this._columns && document.contains(this._columns[0])) { return this._columns; } const columnContainer = this.$.CRMEditColumnsContainer; return (this._columns = Array.prototype.slice.apply(columnContainer.children).filter(function(element: CRMColumnElement|HTMLElement) { return element.classList.contains('CRMEditColumnCont'); }).map((columnCont: CRMColumnElement) => { return columnCont.querySelector('.CRMEditColumn'); })); }; /** * Gets the last menu of the list. * * @param list - The list. * @param hidden - The hidden nodes * @param exclude - The menu not to choose * * @return The last menu on the given list. */ private static _getLastMenu(this: EditCrm, list: CRM.Node[], exclude: number) { let lastMenu = -1; let lastFilledMenu = -1; //Find last menu to auto-expand if (list) { list.forEach(function(item, index) { if ((item.type === 'menu' || (window.app.shadowStart && item.menuVal))) { item.children = item.children || []; if (exclude === undefined || index !== exclude) { lastMenu = index; if (item.children.length > 0) { lastFilledMenu = index; } } } }); if (lastFilledMenu !== -1) { return lastFilledMenu; } } return lastMenu; }; /** * Returns whether the node is visible or not (1 if it's visible) */ private static _setInvisibleNodes(this: EditCrm, result: { [nodeId: number]: boolean; }, node: CRM.Node, showContentTypes: boolean[]) { let length; if (node.children && node.children.length > 0) { length = node.children.length; for (let i = 0; i < length; i++) { this._setInvisibleNodes(result, node.children[i], showContentTypes); } } if (!window.app.util.arraysOverlap(node.onContentTypes, showContentTypes)) { result[node.id] = true; } }; /** * Builds crm edit object. * * @param setMenus - An array of menus that are set to be opened (by user input). * @param unsetMenus - An array of menus that should not be opened * * @return the CRM edit object */ private static _buildCRMEditObj(this: EditCrm, setMenus: number[], unsetMenus: number[]): { crm: CRMBuilder; setMenus: number[]; } { let column: CRMBuilderColumn; let indent: number; const path: number[] = []; let columnNum: number = 0; let lastMenu: number = -2; let indentTop: number = 0; const crmEditObj: CRMBuilder = []; const newSetMenus: number[] = []; let list: (CRM.Node & Partial<{ expanded: boolean; name: string; shadow: boolean; index: number; }>)[] = window.app.settings.crm; const setMenusLength: number = setMenus.length; const showContentTypes: boolean[] = window.app.crmTypes; //Hide all nodes that should be hidden const hiddenNodes: { [nodeId: number]: boolean; } = {}; for (let i = 0; i < list.length; i++) { this._setInvisibleNodes(hiddenNodes, list[i], showContentTypes); } if (list.length) { while (lastMenu !== -1) { if (setMenusLength > columnNum && setMenus[columnNum] !== -1) { lastMenu = setMenus[columnNum]; } else { lastMenu = this._getLastMenu(list, unsetMenus[columnNum]); } newSetMenus[columnNum] = lastMenu; indent = lastMenu; const columnIndent = []; columnIndent[indentTop - 1] = undefined; column = { indent: columnIndent, menuPath: path.concat(lastMenu), list: list as (CRM.Node & { expanded: boolean; name: string; shadow: boolean; index: number; isPossibleAddLocation?: boolean; })[], index: columnNum, shadow: window.app.shadowStart && window.app.shadowStart <= columnNum } as any; list.forEach(function(item) { item.expanded = false; }); if (lastMenu !== -1) { indentTop += indent; const lastNode = list[lastMenu]; lastNode.expanded = true; if (window.app.shadowStart && lastNode.menuVal) { list = (lastNode as CRM.ScriptNode|CRM.LinkNode|CRM.DividerNode|CRM.StylesheetNode).menuVal as CRM.Node[]; } else { list = (list[lastMenu] as CRM.MenuNode).children; } } column.list = column.list.map((currentVal, index) => ({ ...currentVal, ...{ path: [...path, index], index, isPossibleAddLocation: false, hiddenOnCrmType: !!hiddenNodes[currentVal.id] } })); path.push(lastMenu); crmEditObj.push(column); columnNum++; } } this._columns = null; return { crm: crmEditObj, setMenus: newSetMenus }; }; private static _setColumnContOffset(column: HTMLElement & { offset: number; }, offset: number, force: boolean = false) { if (column.offset === undefined) { column.offset = 0; } if (force) { column.offset = offset; } else { column.offset += offset; } window.setTransform(column, `translateY(${column.offset}px)`); } private static _resetColumnOffsets() { const topLevelColumns = window.app.editCRM.shadowRoot.querySelectorAll('.CRMEditColumnCont'); for (let i = 0; i < topLevelColumns.length; i++) { this._setColumnContOffset(<unknown>topLevelColumns[i] as HTMLDivElement & { offset: number; }, 0); } } private static _moveFollowingColumns(startColumn: CRMColumnElement, offset: number) { const topLevelColumns = window.app.editCRM.shadowRoot.querySelectorAll('.CRMEditColumnCont'); for (let i = startColumn.index + 1; i < topLevelColumns.length; i++) { this._setColumnContOffset(<unknown>topLevelColumns[i] as HTMLDivElement & { offset: number; }, offset); } } private static _createSorter(this: EditCrm) { this._sortables = this._sortables.filter((sortable) => { sortable.destroy(); return false; }); this._getColumns().forEach((column, columnIndex, allColumns) => { let draggedNode: EditCrmItem = null; let moves: number = 0; let lastMenuSwitch: { item: CRM.MenuNode; direction: 'over'|'under'; } = null; this._sortables.push(new Sortable<EditCrmItem, CRMColumnElement>(column, { group: 'crm', animation: 50, handle: '.dragger', ghostClass: 'draggingCRMItem', chosenClass: 'draggingFiller', scroll: true, forceFallback: true, fallbackOnBody: false, onStart: () => { this.dragging = true; }, onChoose: (event) => { const node = event.item; draggedNode = node; //Collapse menu if it's a menu type node if (node.item.type === 'menu' && node.expanded) { //Hide all its children while dragging to avoid confusion //Disabe expanded status node.expanded = false; node.shadowRoot.querySelector('.menuArrow').removeAttribute('expanded'); //Hide columns to the right for (let i = columnIndex + 1; i < allColumns.length; i++) { allColumns[i].style.display = 'none'; } } node.currentColumn = column; }, onEnd: (event) => { this.dragging = false; const revertPoint = window.app.uploading.createRevertPoint(false); //If target was a menuArrow, place it into that menu let foundElement = window.app.util.findElementWithClassName({ path: (event.originalEvent as any).path }, 'menuArrowCont'); if (foundElement) { while (foundElement && foundElement.tagName !== 'EDIT-CRM-ITEM') { foundElement = (foundElement.parentNode || (foundElement as any).host) as HTMLElement; } const crmItem = foundElement as HTMLEditCrmItemElement; if (crmItem && crmItem.type === 'menu') { window.app.crm.move(event.item.item.path, crmItem.item.path.concat(0)); //Show that menu if it isn't being shown already window.app.crm.buildNodePaths(window.app.settings.crm); const path = window.app.crm.lookupId(event.item.item.id, false).path; window.app.editCRM.setMenus = path.slice(0, path.length - 1); window.app.editCRM.build({ setItems: window.app.editCRM.setMenus, quick: true }); window.app.uploading.showRevertPointToast(revertPoint); return; } } //Get the current column const newColumn = (event.item.parentNode as CRMColumnElement).index; const index = event.newIndex; //Upload changes window.app.crm.move(event.item.item.path, window.app.editCRM.setMenus.slice(0, newColumn).concat(index)); window.app.uploading.showRevertPointToast(revertPoint); }, onMove: (event) => { this.async(() => { if (event.to !== event.dragged.currentColumn) { //Column was switched, reset all column offsets first this._resetColumnOffsets(); //Too many sortable bugs to rely on events, just calculate it const topLevelColumns = window.app.editCRM.shadowRoot.querySelectorAll('.CRMEditColumnCont') as NodeListOf<HTMLElement & { offset: number; }>; const leftmostColumn = Math.min(event.dragged.currentColumn.index, event.to.index); this._setColumnContOffset(topLevelColumns[leftmostColumn], 0, true); for (let i = leftmostColumn; i < topLevelColumns.length - 1; i++) { const col = topLevelColumns[i]; const colMenu: EditCrmItem = Array.prototype.slice.apply(col.querySelectorAll('edit-crm-item')) .filter((node: EditCrmItem) => { return node !== event.dragged && node.item && node.item.type === 'menu' && node.expanded; })[0]; if (!colMenu) { //No menu, exit loop break; } const colMenuIndex = Array.prototype.slice.apply(colMenu.parentElement.children) .indexOf(colMenu) + window.app.editCRM.crm[i].indent.length + col.offset; //Get the base offset of the next column const baseOffset = window.app.editCRM.crm[i + 1].indent.length; this._setColumnContOffset(topLevelColumns[i + 1], ( (colMenuIndex - baseOffset) * 50 ), true); } } else { //In-column switching //Also move the children of any menu if the menu has moved if (event.related.item.type === 'menu' && event.related.expanded) { //It's passed an expanded menu in some direction //If the menu node is below the dragged node before any events, //that means that the dragged node is now above the menu node let moveDown = event.relatedRect.top < event.draggedRect.top; if (lastMenuSwitch && lastMenuSwitch.item === event.related.item && lastMenuSwitch.direction === (moveDown ? 'under' : 'over')) { return; } if (moveDown) { //Above the menu node, move all other columns down if (moves !== 1) { //Ignore second move-up, some weird bug in sortable causes this this._moveFollowingColumns(event.to, 50); } } else { //Below the menu node, move all other columns up this._moveFollowingColumns(event.to, -50); } lastMenuSwitch = { item: event.related.item, direction: moveDown ? 'under' : 'over' }; } } draggedNode.currentColumn = event.to; moves++; }, 10); } })); }); } /** * Builds the crm object * * @param setItems - Set choices for menus by the user * @param quick - Do it quicker than normal * @param instant - Don't show a loading image and do it immediately * * @return The object to be sent to Polymer */ static build(this: EditCrm, { setItems = [], unsetItems = [], quick = false, instant }: { setItems?: number[]; unsetItems?: number[]; quick?: boolean; instant?: boolean; } = { setItems: [], unsetItems: [], quick: false, instant: false }): CRMBuilder { const obj = this._buildCRMEditObj(setItems, unsetItems); this.setMenus = obj.setMenus; const crmBuilder = obj.crm; //Get the highest column's height and apply it to the element to prevent //the page from going and shrinking quickly let hight; let highest = 0; crmBuilder.forEach(function (column) { hight = column.indent.length + column.list.length; hight > highest && (highest = hight); }); this.$.mainCont.style.minHeight = (highest * 50) + 'px'; this.crm = []; if (this._currentTimeout !== null) { window.clearTimeout(this._currentTimeout); } this.crmLoading = true; this._columns = null; const func = () => { this.crm = crmBuilder; this.notifyPath('crm', this.crm); this._currentTimeout = null; setTimeout(() => { this.crmLoading = false; const els = this.getItems(); for (let i = 0; i < els.length; i++) { els[i].update && els[i].update(); } setTimeout(() => { this._createSorter(); }, 0); }, 50); } if (instant) { func(); } else { this._currentTimeout = window.setTimeout(func, quick ? 150 : 1000); } return crmBuilder; }; static ready(this: EditCrm) { window.onExists('app').then(() => { window.app.editCRM = this; this.appExists = true; window.app.addEventListener('crmTypeChanged', () => { this._typeChanged(); }); this._typeChanged(true); }); }; static async addToPosition(this: EditCrm, e: Polymer.ClickEvent) { const node = window.app.util.findElementWithClassName(e, 'addingItemPlaceholder'); const menuPath = JSON.parse(node.getAttribute('data-path')); await this._addItem(menuPath, this.addingType); this.isAdding = false; }; static cancelAddOrSelect(this: EditCrm) { if (this.isAdding) { this.cancelAdding(); } else if (this.isSelecting) { this.cancelSelecting(); } } static cancelAdding(this: EditCrm) { if (this.isAdding) { this.isAdding = false; this.build({ setItems: window.app.editCRM.setMenus }); } }; static setAddStateLink(this: EditCrm) { this._setAddStateForType('link'); } static setAddStateScript(this: EditCrm) { this._setAddStateForType('script'); } static setAddStateStylesheet(this: EditCrm) { this._setAddStateForType('stylesheet'); } static setAddStateMenu(this: EditCrm) { this._setAddStateForType('menu'); } static setAddStateDivider(this: EditCrm) { this._setAddStateForType('divider'); } private static _setAddStateForType(this: EditCrm, type: CRM.NodeType) { //If CRM is completely empty, place it immediately if (window.app.settings.crm.length === 0) { window.app.settings.crm.push(window.app.templates.getDefaultNodeOfType(type, { id: window.app.generateItemId() as CRM.NodeId<any> })); window.app.editCRM.build({ setItems: window.app.editCRM.setMenus }); window.app.upload(); return; } this.isSelecting && this.cancelSelecting(); this.isAdding = true; this.addingType = type; this.build({ setItems: window.app.editCRM.setMenus, instant: true }); } private static async _addItem(this: EditCrm, path: number[], type: CRM.NodeType) { const newItem = window.app.templates.getDefaultNodeOfType(type, { id: window.app.generateItemId() as CRM.NodeId<any> }); window.app.uploading.createRevertPoint(); const container = window.app.crm.lookup(path, true); if (container === null) { window.app.util.showToast(await this.__async(I18NKeys.options.editCrm.addFail, type)); window.app.util.wait(5000).then(() => { window.app.listeners.hideGenericToast(); }); return; } container.push(newItem); window.app.editCRM.build({ setItems: window.app.editCRM.setMenus }); window.app.upload(); }; private static _getSelected(this: EditCrm): CRM.GenericNodeId[] { const selected: CRM.GenericNodeId[] = []; const editCrmItems = this.getItems(); let i; for (i = 0; i < editCrmItems.length; i++) { if (editCrmItems[i].$.itemCont.classList.contains('highlighted')) { selected.push(editCrmItems[i].item.id as CRM.GenericNodeId); } } return selected; }; private static _ifDefSet(this: EditCrm, node: CRM.Node, target: Partial<CRM.SafeNode>, ...props: (keyof CRM.SafeNode)[]) { for (let i = 0; i < props.length; i++) { const property = props[i]; if (node[property] !== void 0) { (target as any)[property] = node[property]; } } } static makeNodeSafe(this: EditCrm, node: CRM.Node): CRM.SafeNode { const newNode: Partial<CRM.SafeNode> = {}; this._ifDefSet(node, newNode, 'type', 'name', 'value', 'linkVal', 'menuVal', 'nodeInfo', 'triggers', 'scriptVal', 'stylesheetVal', 'onContentTypes', 'showOnSpecified'); if (node.children) { newNode.children = []; for (let i = 0; i < node.children.length; i++) { newNode.children[i] = this.makeNodeSafe(node.children[i]); } } return newNode as CRM.SafeNode; }; private static _extractUniqueChildren(this: EditCrm, node: CRM.Node, toExportIds: CRM.GenericNodeId[], results: CRM.Node[]) { if (toExportIds.indexOf(node.id) > -1) { results.push(node); } else { for (let i = 0; node.children && i < node.children.length; i++) { this._extractUniqueChildren(node.children[i], toExportIds, results); } } }; private static _changeAuthor(this: EditCrm, node: CRM.Node|CRM.SafeNode, authorName: string) { if (node.nodeInfo.source !== 'local') { node.nodeInfo.source.author = authorName; for (let i = 0; node.children && i < node.children.length; i++) { this._changeAuthor(node.children[i], authorName); } } }; private static _crmExportNameChange(this: EditCrm, node: CRM.Node, author: string): string { if (author) { node.nodeInfo && node.nodeInfo.source && node.nodeInfo.source !== 'local' && (node.nodeInfo.source.author = author); } return JSON.stringify(node); }; static getMetaIndexes(code: string): { start: number; end: number; }[] { const indexes: { start: number; end: number; }[] = []; let metaStart = -1; let metaEnd = -1; const lines = code.split('\n'); for (let i = 0; i < lines.length; i++) { if (metaStart !== -1) { if (lines[i].indexOf('==/UserScript==') > -1 || lines[i].indexOf('==/UserStyle==') > -1) { metaEnd = i; indexes.push({ start: metaStart, end: metaEnd }); metaStart = -1; metaEnd = -1; } } else if (lines[i].indexOf('==UserScript==') > -1 || lines[i].indexOf('==UserStyle==') > -1) { metaStart = i; } } return indexes; } static getMetaLinesForIndex(code: string, { start, end }: { start: number; end: number; }): string[] { const metaLines: string[] = []; const lines = code.split('\n'); for (let i = start + 1; i < end; i++) { metaLines.push(lines[i]); } return metaLines; } static getMetaLines(code: string): string[] { let metaLines: string[] = []; const metaIndexes = this.getMetaIndexes(code); for (const index of metaIndexes) { metaLines = [...metaLines, ...this.getMetaLinesForIndex(code, index)] } return metaLines; } static getMetaTagsForLines(lines: string[]): { [key: string]: (string|number)[]; } { const metaTags: { [key: string]: any; } = {}; let currentMatch: { key: string; value: string; } = null; const regex = /@(\w+)(\s+)(.+)/; for (let i = 0; i < lines.length; i++) { const regexMatches = lines[i].match(regex); if (regexMatches) { if (currentMatch) { //Write previous match to object const { key, value } = currentMatch; metaTags[key] = metaTags[key] || []; metaTags[key].push(value); } currentMatch = { key: regexMatches[1], value: regexMatches[3] } } else { //No match, that means the last metatag is //still continuing, add to that currentMatch.value += ('\n' + lines[i]); } } if (currentMatch) { //Write previous match to object const { key, value } = currentMatch; metaTags[key] = metaTags[key] || []; metaTags[key].push(value); } return metaTags; } static getMetaTags(this: EditCrm, code: string): { [key: string]: (string|number)[]; } { const metaLines = this.getMetaLines(code); return this.getMetaTagsForLines(metaLines); }; private static _setMetaTagIfSet<K extends keyof U, U>(this: EditCrm, metaTags: CRM.MetaTags, metaTagKey: string, nodeKey: K, node: U) { if (node && node[nodeKey]) { if (Array.isArray(node[nodeKey])) { metaTags[metaTagKey] = node[nodeKey] as any; } else { metaTags[metaTagKey] = [node[nodeKey]] as any; } } }; private static _getUserscriptString(this: EditCrm, node: CRM.ScriptNode|CRM.StylesheetNode, author: string): string { let i; const code = (node.type === 'script' ? node.value.script : node.value.stylesheet); let codeSplit = code.split('\n'); const metaIndexes = this.getMetaIndexes(code); let metaTags: { [key: string]: (string|number)[]; } = {}; const slicedIndexes: number[] = []; for (const { start, end } of metaIndexes) { for (let i = start; i < end; i++) { slicedIndexes.push(i); } } if (metaIndexes.length > 0) { //Remove metaLines for (const line of slicedIndexes.reverse()) { codeSplit.splice(line, 1); } metaTags = this.getMetaTags(code); } this._setMetaTagIfSet(metaTags, 'name', 'name', node); author = (metaTags['nodeInfo'] && JSON.parse(metaTags['nodeInfo'][0] as string).author) || author || 'anonymous'; let authorArr: string[] = []; if (!Array.isArray(author)) { authorArr = [author]; } metaTags['author'] = authorArr; if (node.nodeInfo.source !== 'local') { this._setMetaTagIfSet(metaTags, 'downloadURL', 'url', node.nodeInfo.source); } this._setMetaTagIfSet(metaTags, 'version', 'version', node.nodeInfo); metaTags['CRM_contentTypes'] = [JSON.stringify(node.onContentTypes)]; this._setMetaTagIfSet(metaTags, 'grant', 'permissions', node); const matches = []; const excludes = []; for (i = 0; i < node.triggers.length; i++) { if (node.triggers[i].not) { excludes.push(node.triggers[i].url); } else { matches.push(node.triggers[i].url); } } metaTags['match'] = matches; metaTags['exclude'] = excludes; this._setMetaTagIfSet(metaTags, 'CRM_launchMode', 'launchMode', node.value); if (node.type === 'script' && node.value.libraries) { metaTags['require'] = []; for (i = 0; i < node.value.libraries.length; i++) { //Turn into requires if (node.value.libraries[i].url) { metaTags['require'].push(node.value.libraries[i].url as string); } } } if (node.type === 'stylesheet') { metaTags['CRM_stylesheet'] = ['true']; this._setMetaTagIfSet(metaTags, 'CRM_toggle', 'toggle', node.value); this._setMetaTagIfSet(metaTags, 'CRM_defaultOn', 'defaultOn', node.value); //Convert stylesheet to GM API stylesheet insertion const stylesheetCode = codeSplit.join('\n'); codeSplit = [`GM_addStyle('${stylesheetCode.replace(/\n/g, '\\n\' + \n\'')}');`]; } const metaLines = []; for (let metaKey in metaTags) { if (metaTags.hasOwnProperty(metaKey)) { for (i = 0; i < metaTags[metaKey].length; i++) { metaLines.push('// @' + metaKey + ' ' + metaTags[metaKey][i]); } } } const newScript = `// ==UserScript== ${metaLines.join('\n')} // ==/UserScript ${codeSplit.join('\n')}`; return newScript; }; private static _generateDocumentRule(this: EditCrm, node: CRM.StylesheetNode): string { const rules = node.triggers.map(function (trigger) { if (trigger.url.indexOf('*') === -1) { return 'url(' + trigger + ')'; } else { const schemeAndDomainPath = trigger.url.split('://'); const scheme = schemeAndDomainPath[0]; const domainPath = schemeAndDomainPath.slice(1).join('://'); const domainAndPath = domainPath.split('/'); const domain = domainAndPath[0]; const path = domainAndPath.slice(1).join('/'); let schemeWildCard = scheme.indexOf('*') > -1; let domainWildcard = domain.indexOf('*') > -1; let pathWildcard = path.indexOf('*') > -1; if (~~schemeWildCard + ~~domainWildcard + ~~pathWildcard > 1 || domainWildcard || schemeWildCard) { //Use regex return 'regexp("' + trigger.url .replace(/\*/, '.*') .replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + '")'; } else { return 'url-prefix(' + scheme + '://' + domain + ')'; } } }); let match; let indentation: string; const lines = node.value.stylesheet.split('\n'); for (let i = 0; i < lines.length; i++) { if ((match = /(\s+)(\w+)/.exec(lines[i]))) { indentation = match[1]; break; } } indentation = indentation || ' '; return '@-moz-document ' + rules.join(', ') + ' {' + lines.map(function(line) { return indentation + line; }).join('\n') + '}'; }; private static _getExportString(this: EditCrm, node: CRM.Node, type: string, author: string) { switch (type) { case 'Userscript': return this._getUserscriptString(node as CRM.ScriptNode, author); case 'Userstyle': //Turn triggers into @document rules if ((node as CRM.StylesheetNode).value.launchMode === 0 || (node as CRM.StylesheetNode).value.launchMode === 1) { //On clicking return (node as CRM.StylesheetNode).value.stylesheet.replace( /UserScript/g, 'UserStyle'); } else { return this._generateDocumentRule(node as CRM.StylesheetNode).replace( /UserScript/g, 'UserStyle'); } default: case 'CRM': return this._crmExportNameChange(node as CRM.Node, author); } }; static exportSingleNode(this: EditCrm, exportNode: CRM.Node, exportType: string) { const textArea = window.doc.exportJSONData; textArea.value = this._getExportString(exportNode, exportType, null); window.doc.exportAuthorName.value = (exportNode.nodeInfo && exportNode.nodeInfo.source && exportNode.nodeInfo.source && exportNode.nodeInfo.source !== 'local' && exportNode.nodeInfo.source.author) || 'anonymous'; window.doc.exportAuthorName.addEventListener('keydown', () => { window.setTimeout(() => { const author = window.doc.exportAuthorName.value; browserAPI.storage.local.set({ authorName: author }); let data; data = this._getExportString(exportNode, exportType, author); textArea.value = data; }, 0); }); window.doc.exportDialog.open(); setTimeout(() => { textArea.focus(); textArea.select(); }, 150); }; private static _exportGivenNodes(this: EditCrm, exports: CRM.Node[]) { const __this = this; const safeExports: CRM.SafeNode[] = []; for (let i = 0; i < exports.length; i++) { safeExports[i] = this.makeNodeSafe(exports[i]); } const data = { crm: safeExports }; const textarea = window.doc.exportJSONData; function authorNameChange(event: { target: { value: string } }) { const author = (event.target as { value: string; }).value; browserAPI.storage.local.set({ authorName: author }); for (let j = 0; j < safeExports.length; j++) { __this._changeAuthor(safeExports[j], author); } const dataJson = JSON.stringify({ crm: safeExports }); textarea.value = dataJson; } window.app.$.exportAuthorName.addEventListener('change', (event) => { authorNameChange(event as any); }); textarea.value = JSON.stringify(data); window.app.$.exportDialog.open(); setTimeout(function() { textarea.focus(); textarea.select(); }, 150); if (window.app.storageLocal.authorName) { authorNameChange({ target: { value: window.app.storageLocal.authorName } }); } }; private static _exportGivenNodeIDs(this: EditCrm, toExport: CRM.GenericNodeId[]) { const exports: CRM.Node[] = []; for (let i = 0; i < window.app.settings.crm.length; i++) { this._extractUniqueChildren(window.app.settings.crm[i], toExport, exports); } this._exportGivenNodes(exports); }; static exportSelected(this: EditCrm) { const toExport = this._getSelected(); this._exportGivenNodeIDs(toExport); }; static cancelSelecting(this: EditCrm) { const editCrmItems = this.getItems(); //Select items for (let i = 0; i < editCrmItems.length; i++) { if (editCrmItems[i].rootNode) { continue; } editCrmItems[i].$.itemCont.classList.remove('selecting'); editCrmItems[i].$.itemCont.classList.remove('highlighted'); } setTimeout(() => { this.isSelecting = false; }, 150); }; static removeSelected(this: EditCrm) { window.app.uploading.createRevertPoint(); let j; let arr; const toRemove = this._getSelected(); for (let i = 0; i < toRemove.length; i++) { arr = window.app.crm.lookupId(toRemove[i], true); if (!arr) { continue; } for (j = 0; j < arr.length; j++) { if (arr[j].id === toRemove[i]) { arr.splice(j, 1); } } } window.app.upload(); this.build({ quick: true }); this.isSelecting = false; }; static selectItems(this: EditCrm) { const editCrmItems = this.getItems(); //Select items for (let i = 0; i < editCrmItems.length; i++) { editCrmItems[i].$.itemCont.classList.add('selecting'); } setTimeout(() => { this.isSelecting = true; }, 150); }; static getCRMElementFromPath(this: EditCrm, path: number[], showPath: boolean = false): EditCrmItem { let i; for (i = 0; i < path.length - 1; i++) { if (this.setMenus[i] !== path[i]) { if (showPath) { this.build({ setItems: path }); break; } else { return null; } } } const cols = this.$.CRMEditColumnsContainer.children; let row = cols[path.length - 1].querySelector('.CRMEditColumn').children; for (i = 0; i < row.length; i++) { if (window.app.util.compareArray((row[i] as EditCrmItem).item.path, path)) { return (row[i] as EditCrmItem); } } return null; }; private static _getCrmTypeFromNumber(crmType: number): string { const types = ['page', 'link', 'selection', 'image', 'video', 'audio']; return types[crmType]; }; private static _typeChanged(this: EditCrm, quick: boolean = false) { const crmTypes = window.app.crmTypes || [true, true, true, true, true, true]; for (let i = 0; i < 6; i++) { window.app.editCRM.classList[crmTypes[i] ? 'add' : 'remove'](this._getCrmTypeFromNumber(i)); } window.runOrAddAsCallback(window.app.editCRM.build, window.app.editCRM, [{ quick: quick }]); } static getItems(this: EditCrm): EditCrmItem[] { return Array.prototype.slice.apply(this.shadowRoot.querySelectorAll('edit-crm-item')); } static getItemsWithClass(this: EditCrm, className: string): EditCrmItem[] { return this.getItems().filter((item) => { return item.$.itemCont.classList.contains(className); }); } } if (window.objectify) { window.register(EC); } else { window.addEventListener('RegisterReady', () => { window.register(EC); }); } } export type EditCrm = Polymer.El<'edit-crm', typeof EditCrmElement.EC & typeof EditCrmElement.editCrmProperties>;
the_stack
import React, { FunctionComponent, useEffect, useState } from "react"; import { observer } from "mobx-react-lite"; import { RouteProp, useNavigation, useRoute } from "@react-navigation/native"; import { RegisterConfig } from "@keplr-wallet/hooks"; import { useStyle } from "../../../styles"; import { useSmartNavigation } from "../../../navigation"; import { Controller, useForm } from "react-hook-form"; import { PageWithScrollView } from "../../../components/page"; import { TextInput } from "../../../components/input"; import { View } from "react-native"; import { Button } from "../../../components/button"; import * as WebBrowser from "expo-web-browser"; import { Buffer } from "buffer/"; import NodeDetailManager from "@toruslabs/fetch-node-details"; import Torus from "@toruslabs/torus.js"; import { useStore } from "../../../stores"; import { useLoadingScreen } from "../../../providers/loading-screen"; import * as AppleAuthentication from "expo-apple-authentication"; interface FormData { name: string; password: string; confirmPassword: string; } const useTorusGoogleSignIn = (): { privateKey: Uint8Array | undefined; email: string | undefined; } => { const [privateKey, setPrivateKey] = useState<Uint8Array | undefined>(); const [email, setEmail] = useState<string | undefined>(); const loadingScreen = useLoadingScreen(); const naviagtion = useNavigation(); useEffect(() => { loadingScreen.setIsLoading(true); (async () => { try { const nonce: string = Math.floor(Math.random() * 10000).toString(); const state = encodeURIComponent( Buffer.from( JSON.stringify({ instanceId: nonce, redirectToOpener: false, }) ).toString("base64") ); const finalUrl = new URL( "https://accounts.google.com/o/oauth2/v2/auth" ); finalUrl.searchParams.append("response_type", "token id_token"); finalUrl.searchParams.append( "client_id", "413984222848-8r7u4ip9i6htppalo6jopu5qbktto6mi.apps.googleusercontent.com" ); finalUrl.searchParams.append("state", state); finalUrl.searchParams.append("scope", "profile email openid"); finalUrl.searchParams.append("nonce", nonce); finalUrl.searchParams.append("prompt", "consent select_account"); finalUrl.searchParams.append( "redirect_uri", "https://oauth.keplr.app/google.html" ); const result = await WebBrowser.openAuthSessionAsync( finalUrl.href, "app.keplr.oauth://" ); if (result.type !== "success") { throw new Error("Failed to get the oauth"); } if (!result.url.startsWith("app.keplr.oauth://google#")) { throw new Error("Invalid redirection"); } const redirectedUrl = new URL(result.url); const paramsString = redirectedUrl.hash; const searchParams = new URLSearchParams( paramsString.startsWith("#") ? paramsString.slice(1) : paramsString ); if (state !== searchParams.get("state")) { throw new Error("State doesn't match"); } const idToken = searchParams.get("id_token"); const accessToken = searchParams.get("access_token"); const userResponse = await fetch( "https://www.googleapis.com/userinfo/v2/me", { method: "GET", headers: { Authorization: `Bearer ${accessToken || idToken}`, }, } ); if (userResponse.ok) { const userInfo: { picture: string; email: string; name: string; } = await userResponse.json(); const { email } = userInfo; const nodeDetailManager = new NodeDetailManager({ network: "mainnet", proxyAddress: "0x638646503746d5456209e33a2ff5e3226d698bea", }); const { torusNodeEndpoints, torusNodePub, torusIndexes, } = await nodeDetailManager.getNodeDetails(); const torus = new Torus({ enableLogging: __DEV__, metadataHost: "https://metadata.tor.us", allowHost: "https://signer.tor.us/api/allow", }); const response = await torus.getPublicAddress( torusNodeEndpoints, torusNodePub, { verifier: "chainapsis-google", verifierId: email.toLowerCase(), }, true ); const data = await torus.retrieveShares( torusNodeEndpoints, torusIndexes, "chainapsis-google", { verifier_id: email.toLowerCase(), }, (idToken || accessToken) as string ); if (typeof response === "string") throw new Error("must use extended pub key"); if ( data.ethAddress.toLowerCase() !== response.address.toLowerCase() ) { throw new Error("data ethAddress does not match response address"); } setPrivateKey(Buffer.from(data.privKey.toString(), "hex")); setEmail(email); } else { throw new Error("Failed to fetch user data"); } } catch (e) { console.log(e); naviagtion.goBack(); } finally { loadingScreen.setIsLoading(false); } })(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return { privateKey, email, }; }; // CONTRACT: Only supported on IOS const useTorusAppleSignIn = (): { privateKey: Uint8Array | undefined; email: string | undefined; } => { const [privateKey, setPrivateKey] = useState<Uint8Array | undefined>(); const [email, setEmail] = useState<string | undefined>(); const loadingScreen = useLoadingScreen(); const naviagtion = useNavigation(); useEffect(() => { loadingScreen.setIsLoading(true); (async () => { try { const credential = await AppleAuthentication.signInAsync({ requestedScopes: [AppleAuthentication.AppleAuthenticationScope.EMAIL], }); if (!credential.identityToken) { throw new Error("Token is not provided"); } const identityTokenSplit = credential.identityToken.split("."); if (identityTokenSplit.length !== 3) { throw new Error("Invalid token"); } const payload = JSON.parse( Buffer.from(identityTokenSplit[1], "base64").toString() ); const email = payload.email as string | undefined; if (!email) { throw new Error("Email is not provided"); } const sub = payload.sub as string | undefined; if (!sub) { throw new Error("Subject is not provided"); } const nodeDetailManager = new NodeDetailManager({ network: "mainnet", proxyAddress: "0x638646503746d5456209e33a2ff5e3226d698bea", }); const { torusNodeEndpoints, torusNodePub, torusIndexes, } = await nodeDetailManager.getNodeDetails(); const torus = new Torus({ enableLogging: __DEV__, metadataHost: "https://metadata.tor.us", allowHost: "https://signer.tor.us/api/allow", }); const response = await torus.getPublicAddress( torusNodeEndpoints, torusNodePub, { verifier: "chainapsis-apple", verifierId: sub, }, true ); const data = await torus.retrieveShares( torusNodeEndpoints, torusIndexes, "chainapsis-apple", { verifier_id: sub, }, credential.identityToken ); if (typeof response === "string") throw new Error("must use extended pub key"); if (data.ethAddress.toLowerCase() !== response.address.toLowerCase()) { throw new Error("data ethAddress does not match response address"); } setPrivateKey(Buffer.from(data.privKey.toString(), "hex")); setEmail(email); } catch (e) { console.log(e); naviagtion.goBack(); } finally { loadingScreen.setIsLoading(false); } })(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return { privateKey, email, }; }; export const TorusSignInScreen: FunctionComponent = observer(() => { const route = useRoute< RouteProp< Record< string, { registerConfig: RegisterConfig; type: "google" | "apple"; } >, string > >(); const style = useStyle(); const { analyticsStore } = useStore(); const smartNavigation = useSmartNavigation(); useEffect(() => { smartNavigation.setOptions({ title: route.params.type === "apple" ? "Sign in with Apple" : "Sign in with Google", }); }, [route.params.type, smartNavigation]); const registerConfig: RegisterConfig = route.params.registerConfig; const [mode] = useState(registerConfig.mode); // Below uses the hook conditionally. // This is a silly way, but `route.params.type` never changed in the logic. const { privateKey, email } = route.params.type === "apple" ? useTorusAppleSignIn() : useTorusGoogleSignIn(); const { control, handleSubmit, setFocus, getValues, formState: { errors }, } = useForm<FormData>(); const [isCreating, setIsCreating] = useState(false); const submit = handleSubmit(async () => { if (!privateKey || !email) { return; } setIsCreating(true); try { await registerConfig.createPrivateKey( getValues("name"), privateKey, getValues("password"), { email, socialType: route.params.type } ); analyticsStore.setUserId(); analyticsStore.setUserProperties({ registerType: "google", }); analyticsStore.logEvent("OAuth sign in finished", { accountType: "privateKey", }); smartNavigation.reset({ index: 0, routes: [ { name: "Register.End", params: { password: getValues("password"), }, }, ], }); } catch (e) { console.log(e); setIsCreating(false); } }); return ( <PageWithScrollView contentContainerStyle={style.get("flex-grow-1")} style={style.flatten(["padding-x-page"])} > <Controller control={control} rules={{ required: "Name is required", }} render={({ field: { onChange, onBlur, value, ref } }) => { return ( <TextInput label="Wallet nickname" returnKeyType={mode === "add" ? "done" : "next"} onSubmitEditing={() => { if (mode === "add") { submit(); } if (mode === "create") { setFocus("password"); } }} error={errors.name?.message} onBlur={onBlur} onChangeText={onChange} value={value} ref={ref} /> ); }} name="name" defaultValue="" /> {mode === "create" ? ( <React.Fragment> <Controller control={control} rules={{ required: "Password is required", validate: (value: string) => { if (value.length < 8) { return "Password must be longer than 8 characters"; } }, }} render={({ field: { onChange, onBlur, value, ref } }) => { return ( <TextInput label="Password" returnKeyType="next" secureTextEntry={true} onSubmitEditing={() => { setFocus("confirmPassword"); }} error={errors.password?.message} onBlur={onBlur} onChangeText={onChange} value={value} ref={ref} /> ); }} name="password" defaultValue="" /> <Controller control={control} rules={{ required: "Confirm password is required", validate: (value: string) => { if (value.length < 8) { return "Password must be longer than 8 characters"; } if (getValues("password") !== value) { return "Password doesn't match"; } }, }} render={({ field: { onChange, onBlur, value, ref } }) => { return ( <TextInput label="Confirm password" returnKeyType="done" secureTextEntry={true} onSubmitEditing={() => { submit(); }} error={errors.confirmPassword?.message} onBlur={onBlur} onChangeText={onChange} value={value} ref={ref} /> ); }} name="confirmPassword" defaultValue="" /> </React.Fragment> ) : null} <View style={style.flatten(["flex-1"])} /> <Button text="Next" size="large" loading={isCreating} onPress={submit} disabled={!privateKey || !email} /> {/* Mock element for bottom padding */} <View style={style.flatten(["height-page-pad"])} /> </PageWithScrollView> ); });
the_stack
import { customElement, html, property, TemplateResult } from 'lit-element'; import { styles } from './mgt-file-upload-css'; import { strings } from './strings'; import { getSvg, SvgIcon } from '../../../utils/SvgHelper'; import { formatBytes } from '../../../utils/Utils'; import { IGraph, MgtBaseComponent } from '@microsoft/mgt-element'; import { ViewType } from '../../../graph/types'; import { DriveItem } from '@microsoft/microsoft-graph-types'; import { clearFilesCache, getGraphfile, getUploadSession, sendFileContent, sendFileChunck, deleteSessionFile } from '../../../graph/graph.files'; export { FluentProgress, FluentButton, FluentCheckbox, FluentCard } from '@fluentui/web-components'; // import { registerFluentComponents } from '../../../utils/FluentComponents'; // import { fluentButton, fluentCheckbox, fluentProgress } from '@fluentui/web-components'; // registerFluentComponents(fluentProgress, fluentButton, fluentCheckbox); /** * Upload conflict behavior status */ export const enum MgtFileUploadConflictBehavior { rename, replace } /** * MgtFileUpload upload item lifecycle object. * * @export * @interface MgtFileUploadItem */ export interface MgtFileUploadItem { /** * Session url to keep upload progress open untill all chuncks are sent */ uploadUrl?: string; /** * Upload file progress value */ percent?: number; /** * Validate if File has any conflict Behavior */ conflictBehavior?: MgtFileUploadConflictBehavior; /** * Output "Success" or "Fail" icon base on upload response */ iconStatus?: TemplateResult; /** * File object to be upload. */ file?: File; /** * Full file Path to be upload. */ fullPath?: string; /** * Mgt-File View state change on upload response */ view?: ViewType; /** * Manipulate fileDetails on upload lifecycle */ driveItem?: DriveItem; /** * Mgt-File line2Property output field message */ fieldUploadResponse?: string; /** * Validates state of upload progress */ completed?: boolean; /** * Load large Files into ArrayBuffer to send by chuncks */ mimeStreamString?: ArrayBuffer; /** * Max chunck size to upload file by slice */ maxSize?: number; /** * Minimal chunck size to upload file by slice */ minSize?: number; } /** * MgtFileUpload configuration object with MgtFileList Properties. * * @export * @interface MgtFileUploadConfig */ export interface MgtFileUploadConfig { /** * MS Graph APIs connector * @type {IGraph} */ graph: IGraph; /** * allows developer to provide site id for a file * @type {string} */ siteId?: string; /** * DriveId to upload Files * @type {string} */ driveId?: string; /** * GroupId to upload Files * @type {string} */ groupId?: string; /** * allows developer to provide item id for a file * @type {string} */ itemId?: string; /** * allows developer to provide item path for a file * @type {string} */ itemPath?: string; /** * allows developer to provide user id for a file * @type {string} */ userId?: string; /** * A number value indication for file size upload (KB) * @type {Number} */ maxFileSize?: number; /** * A number value to indicate the number of files to upload. * @type {Number} */ maxUploadFile?: Number; /** * A Array of file extensions to be excluded from file upload. * * @type {string[]} */ excludedFileExtensions?: string[]; } /** * A component to upload files to OneDrive or SharePoint Sites * * @export * @class MgtFileUpload * @extends {MgtBaseComponent} * * @cssprop --file-upload-border- {String} File upload border top style * @cssprop --file-upload-background-color - {Color} File upload background color with opacity style * @cssprop --file-upload-button-float - {string} Upload button float position * @cssprop --file-upload-button-background-color - {Color} Background color of upload button * @cssprop --file-upload-dialog-background-color - {Color} Background color of dialog * @cssprop --file-upload-dialog-content-background-color - {Color} Background color of dialog content * @cssprop --file-upload-dialog-content-color - {Color} Color of dialog content * @cssprop --file-upload-button-color - {Color} Text color of upload button * @cssprop --file-upload-dialog-primarybutton-background-color - {Color} Background color of primary button * @cssprop --file-upload-dialog-primarybutton-color - {Color} Color text of primary button * @cssprop --file-item-margin - {String} File item margin * @cssprop --file-item-background-color--hover - {Color} File item background hover color * @cssprop --file-item-border-top - {String} File item border top style * @cssprop --file-item-border-left - {String} File item border left style * @cssprop --file-item-border-right - {String} File item border right style * @cssprop --file-item-border-bottom - {String} File item border bottom style * @cssprop --file-item-background-color--active - {Color} File item background active color */ @customElement('mgt-file-upload') export class MgtFileUpload extends MgtBaseComponent { /** * Array of styles to apply to the element. The styles should be defined * using the `css` tag function. */ static get styles() { return styles; } protected get strings() { return strings; } /** * Allows developer to provide an array of MgtFileUploadItem to upload * * @type {MgtFileUploadItem[]} * @memberof MgtFileUpload */ @property({ type: Object }) public filesToUpload: MgtFileUploadItem[]; /** * List of mgt-file-list properties used to upload files. * * @type {MgtFileUploadConfig} * @memberof MgtFileUpload */ @property({ type: Object }) public fileUploadList: MgtFileUploadConfig; /** * Get the scopes required for file upload * * @static * @return {*} {string[]} * @memberof MgtFileUpload */ public static get requiredScopes(): string[] { return [...new Set(['files.readwrite', 'files.readwrite.all', 'sites.readwrite.all'])]; } // variable manage drag style when mouse over private _dragCounter: number = 0; // variable avoids removal of files after drag and drop, https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/dropEffect private _dropEffect: string = 'copy'; // variable defined max chuck size "4MB" for large files . private _maxChunckSize: number = 4 * 1024 * 1024; private _dialogTitle: string = ''; private _dialogContent: string = ''; private _dialogPrimaryButton: string = ''; private _dialogSecondaryButton: string = ''; private _dialogCheckBox: string = ''; private _applyAll: boolean = false; private _applyAllConflitBehavior: number = null; private _maximumFiles: boolean = false; private _maximumFileSize: boolean = false; private _excludedFileType: boolean = false; constructor() { super(); this.filesToUpload = []; } /** * * @returns */ public render(): TemplateResult { if (this.parentElement !== null) { const root = this.parentElement; root.addEventListener('dragenter', this.handleonDragEnter); root.addEventListener('dragleave', this.handleonDragLeave); root.addEventListener('dragover', this.handleonDragOver); root.addEventListener('drop', this.handleonDrop); } return html` <div id="file-upload-dialog" class="file-upload-dialog"> <!-- Modal content --> <fluent-card class="file-upload-dialog-content"> <span class="file-upload-dialog-close" id="file-upload-dialog-close" >${getSvg(SvgIcon.Cancel)}</span> <div class="file-upload-dialog-content-text"> <h2 class="file-upload-dialog-title">${this._dialogTitle}</h2> <div>${this._dialogContent}</div> <div class="file-upload-dialog-check-wrapper"> <fluent-checkbox id="file-upload-dialog-check" class="file-upload-dialog-check" > <span>${this._dialogCheckBox}</span> </fluent-checkbox> </div> </div> <div class="file-upload-dialog-editor"> <fluent-button class="file-upload-dialog-ok"> ${this._dialogPrimaryButton} </fluent-button> <fluent-button class="file-upload-dialog-cancel"> ${this._dialogSecondaryButton} </fluent-button> </div> </fluent-card> </div> <div id="file-upload-border" > </div> <div class="file-upload-area-button"> <div> <input id="file-upload-input" type="file" multiple="true" @change="${this.onFileUploadChange}" /> <fluent-button class="file-upload-button" @click=${this.onFileUploadClick}> ${getSvg(SvgIcon.Upload)}${strings.buttonUploadFile} </fluent-button> </div> </div> <div class="file-upload-Template"> ${this.renderFolderTemplate(this.filesToUpload)} </div> `; } /** * Render Folder structure of files to upload * @param fileItems * @returns */ protected renderFolderTemplate(fileItems: MgtFileUploadItem[]) { let folderStructure: string[] = []; if (fileItems.length > 0) { const TemplateFileItems = fileItems.map(fileItem => { if (folderStructure.indexOf(fileItem.fullPath.substring(0, fileItem.fullPath.lastIndexOf('/'))) === -1) { if (fileItem.fullPath.substring(0, fileItem.fullPath.lastIndexOf('/')) !== '') { folderStructure.push(fileItem.fullPath.substring(0, fileItem.fullPath.lastIndexOf('/'))); return html` <div class='file-upload-table'> <div class='file-upload-cell'> <mgt-file .fileDetails=${{ name: fileItem.fullPath.substring(1, fileItem.fullPath.lastIndexOf('/')), folder: 'Folder' }} .view=${ViewType.oneline} class="mgt-file-item" > </mgt-file> </div> </div> ${this.renderFileTemplate(fileItem, 'file-upload-folder-tab')}`; } else { return html`${this.renderFileTemplate(fileItem, '')}`; } } else { return html`${this.renderFileTemplate(fileItem, 'file-upload-folder-tab')}`; } }); return html`${TemplateFileItems}`; } else { return null; } } /** * Render file upload area * * @param fileItem * @returns */ protected renderFileTemplate(fileItem: MgtFileUploadItem, folderTabStyle: string) { return html` <div class="${fileItem.completed ? 'file-upload-table' : 'file-upload-table upload'}"> <div class="${ folderTabStyle + (fileItem.fieldUploadResponse === 'lastModifiedDateTime' ? ' file-upload-dialog-success' : '') }"> <div class='file-upload-cell'> <div style=${fileItem.fieldUploadResponse === 'description' ? 'opacity: 0.5;' : ''}> <div class="file-upload-status"> ${fileItem.iconStatus} </div> <mgt-file .fileDetails=${fileItem.driveItem} .view=${fileItem.view} .line2Property=${fileItem.fieldUploadResponse} class="mgt-file-item" > </mgt-file> </div> </div> ${fileItem.completed === false ? this.renderFileUploadTemplate(fileItem) : null} </div> </div> </div> `; } /** * Render file upload progress * * @param fileItem * @returns */ protected renderFileUploadTemplate(fileItem: MgtFileUploadItem) { return html` <div class='file-upload-cell'> <div class='file-upload-table file-upload-name' > <div class='file-upload-cell'> <div title="${fileItem.file.name}" class='file-upload-filename'>${fileItem.file.name}</div> </div> </div> <div class='file-upload-table'> <div class='file-upload-cell'> <div class="${fileItem.completed ? 'file-upload-table' : 'file-upload-table upload'}"> <fluent-progress class="file-upload-bar" value="${fileItem.percent}" ></fluent-progress> <div class='file-upload-cell' style="padding-left:5px"> <span>${fileItem.percent}%</span> <span class="file-upload-cancel" @click=${e => this.deleteFileUploadSession(fileItem)}> ${getSvg(SvgIcon.Cancel)} </span> </div> <div> </div> </div> </div> `; } /** * Handle the "Upload Files" button click event to open dialog and select files. * * @param event * @returns */ protected async onFileUploadChange(event) { if (!event || event.target.files.length < 1) { return; } else { this.getSelectedFiles(await this.getFilesFromUploadArea(event.target.files)); event.target.value = null; } } /** * Handle the click event on upload file button that open select files dialog to upload. * */ protected onFileUploadClick() { const uploadInput: HTMLElement = this.renderRoot.querySelector('#file-upload-input'); uploadInput.click(); } /** * Function delete existing file upload sessions * * @param fileItem */ protected async deleteFileUploadSession(fileItem: MgtFileUploadItem) { try { if (fileItem.uploadUrl !== undefined) { // Responses that confirm cancelation of session. // 404 means (The upload session was not found/The resource could not be found/) // 409 means The resource has changed since the caller last read it; usually an eTag mismatch const response = await deleteSessionFile(this.fileUploadList.graph, fileItem.uploadUrl); fileItem.uploadUrl = undefined; fileItem.completed = true; this.setUploadFail(fileItem, strings.cancelUploadFile); } else { fileItem.uploadUrl = undefined; fileItem.completed = true; this.setUploadFail(fileItem, strings.cancelUploadFile); } } catch { fileItem.uploadUrl = undefined; fileItem.completed = true; this.setUploadFail(fileItem, strings.cancelUploadFile); } } /** * Stop listeners from onDragOver event. * * @param event */ protected handleonDragOver = async event => { event.preventDefault(); event.stopPropagation(); if (event.dataTransfer.items && event.dataTransfer.items.length > 0) { event.dataTransfer.dropEffect = event.dataTransfer.dropEffect = this._dropEffect; } }; /** * Stop listeners from onDragEnter event, enable drag and drop view. * * @param event */ protected handleonDragEnter = async event => { event.preventDefault(); event.stopPropagation(); this._dragCounter++; if (event.dataTransfer.items && event.dataTransfer.items.length > 0) { event.dataTransfer.dropEffect = this._dropEffect; const dragFileBorder: HTMLElement = this.renderRoot.querySelector('#file-upload-border'); dragFileBorder.classList.add('visible'); } }; /** * Stop listeners from ondragenter event, disable drag and drop view. * * @param event */ protected handleonDragLeave = event => { event.preventDefault(); event.stopPropagation(); this._dragCounter--; if (this._dragCounter === 0) { const dragFileBorder: HTMLElement = this.renderRoot.querySelector('#file-upload-border'); dragFileBorder.classList.remove('visible'); } }; /** * Stop listeners from onDrop event and process files. * * @param event */ protected handleonDrop = async event => { event.preventDefault(); event.stopPropagation(); const dragFileBorder: HTMLElement = this.renderRoot.querySelector('#file-upload-border'); dragFileBorder.classList.remove('visible'); if (event.dataTransfer && event.dataTransfer.items) { this.getSelectedFiles(await this.getFilesFromUploadArea(event.dataTransfer.items)); } event.dataTransfer.clearData(); this._dragCounter = 0; }; /** * Get Files and initalize MgtFileUploadItem object life cycle to be uploaded * * @param inputFiles */ protected async getSelectedFiles(files: File[]) { let fileItems: MgtFileUploadItem[] = []; let fileItemsCompleted: MgtFileUploadItem[] = []; this._applyAll = false; this._applyAllConflitBehavior = null; this._maximumFiles = false; this._maximumFileSize = false; this._excludedFileType = false; //Collect ongoing upload files this.filesToUpload.forEach(async fileItem => { if (!fileItem.completed) { fileItems.push(fileItem); } else { fileItemsCompleted.push(fileItem); } }); for (var i = 0; i < files.length; i++) { const file: any = files[i]; const fullPath = file.fullPath === '' ? '/' + file.name : file.fullPath; if (fileItems.filter(item => item.fullPath === fullPath).length === 0) { //Initialize variable for File validation let acceptFile = true; //Exclude file based on max files upload allowed if (fileItems.length >= this.fileUploadList.maxUploadFile) { acceptFile = false; if (!this._maximumFiles) { const maximumFiles: (number | true)[] = await this.getFileUploadStatus( files[i], fullPath, 'MaxFiles', this.fileUploadList ); if (maximumFiles !== null) { if (maximumFiles[0] === 0) { return null; } if (maximumFiles[0] === 1) { this._maximumFiles = true; } } } } //Exclude file based on max file size allowed if (this.fileUploadList.maxFileSize !== undefined && acceptFile) { if (files[i].size > this.fileUploadList.maxFileSize * 1024) { acceptFile = false; if (this._maximumFileSize === false) { const maximumFileSize: (number | true)[] = await this.getFileUploadStatus( files[i], fullPath, 'MaxFileSize', this.fileUploadList ); if (maximumFileSize !== null) { if (maximumFileSize[0] === 1) { this._maximumFileSize = true; } } } } } //Exclude file based on File extensions if (this.fileUploadList.excludedFileExtensions !== undefined) { if (this.fileUploadList.excludedFileExtensions.length > 0 && acceptFile) { if ( this.fileUploadList.excludedFileExtensions.filter(fileExtension => { return files[i].name.toLowerCase().indexOf(fileExtension.toLowerCase()) > -1; }).length > 0 ) { acceptFile = false; if (this._excludedFileType === false) { const excludedFileType: (number | true)[] = await this.getFileUploadStatus( files[i], fullPath, 'ExcludedFileType', this.fileUploadList ); if (excludedFileType !== null) { if (excludedFileType[0] === 1) { this._excludedFileType = true; } } } } } } //Collect accepted files if (acceptFile) { const conflictBehavior: (number | true)[] = await this.getFileUploadStatus( files[i], fullPath, 'Upload', this.fileUploadList ); let _completed = false; if (conflictBehavior !== null) { if (conflictBehavior[0] === -1) { _completed = true; } else { this._applyAll = Boolean(conflictBehavior[0]); this._applyAllConflitBehavior = conflictBehavior[1] ? 1 : 0; } } //Initialize MgtFileUploadItem Life cycle fileItems.push({ file: files[i], driveItem: { name: files[i].name }, fullPath: fullPath, conflictBehavior: conflictBehavior !== null ? (conflictBehavior[1] ? 1 : 0) : null, iconStatus: null, percent: 1, view: ViewType.image, completed: _completed, maxSize: this._maxChunckSize, minSize: 0 }); } } } fileItems = fileItems.sort((firstFile, secondFile) => { return firstFile.fullPath .substring(0, firstFile.fullPath.lastIndexOf('/')) .localeCompare(secondFile.fullPath.substring(0, secondFile.fullPath.lastIndexOf('/'))); }); //remove completed file report image to be reuploaded. fileItems.forEach(fileItem => { if (fileItemsCompleted.filter(item => item.fullPath === fileItem.fullPath).length !== 0) { let index = fileItemsCompleted.findIndex(item => item.fullPath === fileItem.fullPath); fileItemsCompleted.splice(index, 1); } }); fileItems.push(...fileItemsCompleted); this.filesToUpload = fileItems; // Send multiple Files to upload this.filesToUpload.forEach(async fileItem => { await this.sendFileItemGraph(fileItem); }); } /** * Call modal dialog to replace or keep file. * * @param file * @returns */ protected async getFileUploadStatus( file: File, fullPath: string, DialogStatus: string, fileUploadList: MgtFileUploadConfig ) { const fileUploadDialog: HTMLElement = this.renderRoot.querySelector('#file-upload-dialog'); switch (DialogStatus) { case 'Upload': const driveItem = await getGraphfile(this.fileUploadList.graph, `${this.getGrapQuery(fullPath)}?$select=id`); if (driveItem !== null) { if (this._applyAll === true) { return [this._applyAll, this._applyAllConflitBehavior]; } fileUploadDialog.classList.add('visible'); this._dialogTitle = strings.fileReplaceTitle; this._dialogContent = strings.fileReplace.replace('{FileName}', file.name); this._dialogCheckBox = strings.checkApplyAll; this._dialogPrimaryButton = strings.buttonReplace; this._dialogSecondaryButton = strings.buttonKeep; super.requestStateUpdate(true); return new Promise<number[]>(async resolve => { let fileUploadDialogClose: HTMLElement = this.renderRoot.querySelector('.file-upload-dialog-close'); let fileUploadDialogOk: HTMLElement = this.renderRoot.querySelector('.file-upload-dialog-ok'); let fileUploadDialogCancel: HTMLElement = this.renderRoot.querySelector('.file-upload-dialog-cancel'); let fileUploadDialogCheck: HTMLInputElement = this.renderRoot.querySelector('#file-upload-dialog-check'); fileUploadDialogCheck.checked = false; fileUploadDialogCheck.classList.remove('hide'); //Remove and include event listener to validate options. fileUploadDialogOk.removeEventListener('click', onOkDialogClick); fileUploadDialogCancel.removeEventListener('click', onCancelDialogClick); fileUploadDialogClose.removeEventListener('click', onCloseDialogClick); fileUploadDialogOk.addEventListener('click', onOkDialogClick); fileUploadDialogCancel.addEventListener('click', onCancelDialogClick); fileUploadDialogClose.addEventListener('click', onCloseDialogClick); //Replace File function onOkDialogClick() { fileUploadDialog.classList.remove('visible'); resolve([fileUploadDialogCheck.checked ? 1 : 0, MgtFileUploadConflictBehavior.replace]); } //Rename File function onCancelDialogClick() { fileUploadDialog.classList.remove('visible'); resolve([fileUploadDialogCheck.checked ? 1 : 0, MgtFileUploadConflictBehavior.rename]); } //Cancel File function onCloseDialogClick() { fileUploadDialog.classList.remove('visible'); resolve([-1]); } }); } else { return null; } break; case 'MaxFiles': fileUploadDialog.classList.add('visible'); this._dialogTitle = strings.maximumFilesTitle; this._dialogContent = strings.maximumFiles.split('{MaxNumber}').join(fileUploadList.maxUploadFile.toString()); this._dialogCheckBox = strings.checkApplyAll; this._dialogPrimaryButton = strings.buttonUpload; this._dialogSecondaryButton = strings.buttonReselect; super.requestStateUpdate(true); return new Promise<number[]>(async resolve => { let fileUploadDialogOk: HTMLElement = this.renderRoot.querySelector('.file-upload-dialog-ok'); let fileUploadDialogCancel: HTMLElement = this.renderRoot.querySelector('.file-upload-dialog-cancel'); let fileUploadDialogClose: HTMLElement = this.renderRoot.querySelector('.file-upload-dialog-close'); let fileUploadDialogCheck: HTMLInputElement = this.renderRoot.querySelector('#file-upload-dialog-check'); fileUploadDialogCheck.checked = false; fileUploadDialogCheck.classList.add('hide'); //Remove and include event listener to validate options. fileUploadDialogOk.removeEventListener('click', onOkDialogClick); fileUploadDialogCancel.removeEventListener('click', onCancelDialogClick); fileUploadDialogClose.removeEventListener('click', onCancelDialogClick); fileUploadDialogOk.addEventListener('click', onOkDialogClick); fileUploadDialogCancel.addEventListener('click', onCancelDialogClick); fileUploadDialogClose.addEventListener('click', onCancelDialogClick); function onOkDialogClick() { fileUploadDialog.classList.remove('visible'); //Continue upload resolve([1]); } function onCancelDialogClick() { fileUploadDialog.classList.remove('visible'); //Cancel all resolve([0]); } }); break; case 'ExcludedFileType': fileUploadDialog.classList.add('visible'); this._dialogTitle = strings.fileTypeTitle; this._dialogContent = strings.fileType.replace('{FileName}', file.name) + ' (' + fileUploadList.excludedFileExtensions.join(',') + ')'; this._dialogCheckBox = strings.checkAgain; this._dialogPrimaryButton = strings.buttonOk; this._dialogSecondaryButton = strings.buttonCancel; super.requestStateUpdate(true); return new Promise<number[]>(async resolve => { let fileUploadDialogOk: HTMLElement = this.renderRoot.querySelector('.file-upload-dialog-ok'); let fileUploadDialogCancel: HTMLElement = this.renderRoot.querySelector('.file-upload-dialog-cancel'); let fileUploadDialogClose: HTMLElement = this.renderRoot.querySelector('.file-upload-dialog-close'); let fileUploadDialogCheck: HTMLInputElement = this.renderRoot.querySelector('#file-upload-dialog-check'); fileUploadDialogCheck.checked = false; fileUploadDialogCheck.classList.remove('hide'); //Remove and include event listener to validate options. fileUploadDialogOk.removeEventListener('click', onOkDialogClick); fileUploadDialogCancel.removeEventListener('click', onCancelDialogClick); fileUploadDialogClose.removeEventListener('click', onCancelDialogClick); fileUploadDialogOk.addEventListener('click', onOkDialogClick); fileUploadDialogCancel.addEventListener('click', onCancelDialogClick); fileUploadDialogClose.addEventListener('click', onCancelDialogClick); function onOkDialogClick() { fileUploadDialog.classList.remove('visible'); //Confirm info resolve([fileUploadDialogCheck.checked ? 1 : 0]); } function onCancelDialogClick() { fileUploadDialog.classList.remove('visible'); //Cancel all resolve([0]); } }); case 'MaxFileSize': fileUploadDialog.classList.add('visible'); this._dialogTitle = strings.maximumFileSizeTitle; this._dialogContent = strings.maximumFileSize .replace('{FileSize}', formatBytes(fileUploadList.maxFileSize)) .replace('{FileName}', file.name) + formatBytes(file.size) + '.'; this._dialogCheckBox = strings.checkAgain; this._dialogPrimaryButton = strings.buttonOk; this._dialogSecondaryButton = strings.buttonCancel; super.requestStateUpdate(true); return new Promise<number[]>(async resolve => { let fileUploadDialogOk: HTMLElement = this.renderRoot.querySelector('.file-upload-dialog-ok'); let fileUploadDialogCancel: HTMLElement = this.renderRoot.querySelector('.file-upload-dialog-cancel'); let fileUploadDialogClose: HTMLElement = this.renderRoot.querySelector('.file-upload-dialog-close'); let fileUploadDialogCheck: HTMLInputElement = this.renderRoot.querySelector('#file-upload-dialog-check'); fileUploadDialogCheck.checked = false; fileUploadDialogCheck.classList.remove('hide'); //Remove and include event listener to validate options. fileUploadDialogOk.removeEventListener('click', onOkDialogClick); fileUploadDialogCancel.removeEventListener('click', onCancelDialogClick); fileUploadDialogClose.removeEventListener('click', onCancelDialogClick); fileUploadDialogOk.addEventListener('click', onOkDialogClick); fileUploadDialogCancel.addEventListener('click', onCancelDialogClick); fileUploadDialogClose.addEventListener('click', onCancelDialogClick); function onOkDialogClick() { fileUploadDialog.classList.remove('visible'); //Confirm info resolve([fileUploadDialogCheck.checked ? 1 : 0]); } function onCancelDialogClick() { fileUploadDialog.classList.remove('visible'); //Cancel all resolve([0]); } }); default: break; } } /** * Get GraphQuery based on pre defined parameters. * * @param fileItem * @returns */ protected getGrapQuery(fullPath: string) { let itemPath = ''; if (this.fileUploadList.itemPath) { if (this.fileUploadList.itemPath.length > 0) { itemPath = this.fileUploadList.itemPath.substring(0, 1) === '/' ? this.fileUploadList.itemPath : '/' + this.fileUploadList.itemPath; } } // {userId} {itemId} if (this.fileUploadList.userId && this.fileUploadList.itemId) { return `/users/${this.fileUploadList.userId}/drive/items/${this.fileUploadList.itemId}:${fullPath}`; } // {userId} {itemPath} if (this.fileUploadList.userId && this.fileUploadList.itemPath) { return `/users/${this.fileUploadList.userId}/drive/root:${itemPath}${fullPath}`; } // {groupId} {itemId} if (this.fileUploadList.groupId && this.fileUploadList.itemId) { return `/groups/${this.fileUploadList.groupId}/drive/items/${this.fileUploadList.itemId}:${fullPath}`; } // {groupId} {itemPath} if (this.fileUploadList.groupId && this.fileUploadList.itemPath) { return `/groups/${this.fileUploadList.groupId}/drive/root:${itemPath}${fullPath}`; } // {driveId} {itemId} if (this.fileUploadList.driveId && this.fileUploadList.itemId) { return `/drives/${this.fileUploadList.driveId}/items/${this.fileUploadList.itemId}:${fullPath}`; } // {driveId} {itemPath} if (this.fileUploadList.driveId && this.fileUploadList.itemPath) { return `/drives/${this.fileUploadList.driveId}/root:${itemPath}${fullPath}`; } // {siteId} {itemId} if (this.fileUploadList.siteId && this.fileUploadList.itemId) { return `/sites/${this.fileUploadList.siteId}/drive/items/${this.fileUploadList.itemId}:${fullPath}`; } // {siteId} {itemPath} if (this.fileUploadList.siteId && this.fileUploadList.itemPath) { return `/sites/${this.fileUploadList.siteId}/drive/root:${itemPath}${fullPath}`; } // default OneDrive {itemId} if (this.fileUploadList.itemId) { return `/me/drive/items/${this.fileUploadList.itemId}:${fullPath}`; } // default OneDrive {itemPath} if (this.fileUploadList.itemPath) { return `/me/drive/root:${itemPath}${fullPath}`; } // default OneDrive root return `/me/drive/root:${fullPath}`; } /** * Send file using Upload using Graph based on length * * @param fileUpload * @returns */ protected async sendFileItemGraph(fileItem: MgtFileUploadItem) { const graph: IGraph = this.fileUploadList.graph; let graphQuery = ''; if (fileItem.file.size < this._maxChunckSize) { try { if (!fileItem.completed) { if ( fileItem.conflictBehavior === null || fileItem.conflictBehavior === MgtFileUploadConflictBehavior.replace ) { graphQuery = `${this.getGrapQuery(fileItem.fullPath)}:/content`; } if (fileItem.conflictBehavior === MgtFileUploadConflictBehavior.rename) { graphQuery = `${this.getGrapQuery(fileItem.fullPath)}:/content?@microsoft.graph.conflictBehavior=rename`; } fileItem.driveItem = await sendFileContent(graph, graphQuery, fileItem.file); if (fileItem.driveItem !== null) { this.setUploadSuccess(fileItem); } else { fileItem.driveItem = { name: fileItem.file.name }; this.setUploadFail(fileItem, strings.failUploadFile); } } } catch (error) { this.setUploadFail(fileItem, strings.failUploadFile); } } else { if (!fileItem.completed) { if (fileItem.uploadUrl === undefined) { const response = await getUploadSession( graph, `${this.getGrapQuery(fileItem.fullPath)}:/createUploadSession`, fileItem.conflictBehavior ); try { if (response !== null) { // uploadSession url used to send chuncks of file fileItem.uploadUrl = response.uploadUrl; const driveItem = await this.sendSessionUrlGraph(graph, fileItem); if (driveItem !== null) { fileItem.driveItem = driveItem; this.setUploadSuccess(fileItem); } else { this.setUploadFail(fileItem, strings.failUploadFile); } } else { this.setUploadFail(fileItem, strings.failUploadFile); } } catch {} } } } } /** * Manage slices of File to upload file by chuncks using Graph and Session Url * * @param Graph * @param fileItem * @returns */ protected async sendSessionUrlGraph(graph: IGraph, fileItem: MgtFileUploadItem) { while (fileItem.file.size > fileItem.minSize) { if (fileItem.mimeStreamString === undefined) { fileItem.mimeStreamString = (await this.readFileContent(fileItem.file)) as ArrayBuffer; } //Graph client API uses Buffer package to manage ArrayBuffer, change to Blob avoids external package dependency const fileSlice: Blob = new Blob([fileItem.mimeStreamString.slice(fileItem.minSize, fileItem.maxSize)]); fileItem.percent = Math.round((fileItem.maxSize / fileItem.file.size) * 100); super.requestStateUpdate(true); if (fileItem.uploadUrl !== undefined) { const response = await sendFileChunck( graph, fileItem.uploadUrl, `${fileItem.maxSize - fileItem.minSize}`, `bytes ${fileItem.minSize}-${fileItem.maxSize - 1}/${fileItem.file.size}`, fileSlice ); if (response === null) { return null; } else if (response.id !== undefined) { return response as DriveItem; } else if (response.nextExpectedRanges !== undefined) { //Define next Chunck fileItem.minSize = parseInt(response.nextExpectedRanges[0].split('-')[0]); fileItem.maxSize = fileItem.minSize + this._maxChunckSize; if (fileItem.maxSize > fileItem.file.size) { fileItem.maxSize = fileItem.file.size; } } } else { return null; } } } /** * Change the state of Mgt-File icon upload to Success * * @param fileUpload */ protected setUploadSuccess(fileUpload: MgtFileUploadItem) { fileUpload.percent = 100; super.requestStateUpdate(true); setTimeout(() => { fileUpload.iconStatus = getSvg(SvgIcon.Success); fileUpload.view = ViewType.twolines; fileUpload.fieldUploadResponse = 'lastModifiedDateTime'; fileUpload.completed = true; super.requestStateUpdate(true); clearFilesCache(); }, 500); } /** * Change the state of Mgt-File icon upload to Fail * * @param fileUpload */ protected setUploadFail(fileUpload: MgtFileUploadItem, errorMessage: string) { setTimeout(() => { fileUpload.iconStatus = getSvg(SvgIcon.Fail); fileUpload.view = ViewType.twolines; fileUpload.driveItem.description = errorMessage; fileUpload.fieldUploadResponse = 'description'; fileUpload.completed = true; super.requestStateUpdate(true); }, 500); } /** * Retrieve File content as ArrayBuffer * * @param file * @returns */ protected readFileContent(file: File): Promise<string | ArrayBuffer> { return new Promise<string | ArrayBuffer>((resolve, reject) => { const myReader: FileReader = new FileReader(); myReader.onloadend = e => { resolve(myReader.result); }; myReader.onerror = e => { reject(e); }; myReader.readAsArrayBuffer(file); }); } /** * Collect Files from Upload Area based on maxUploadFile * * @param uploadFilesItems * @returns */ protected async getFilesFromUploadArea(filesItems) { const folders = []; let entry: any; const collectFilesItems: File[] = []; for (let i = 0; i < filesItems.length; i++) { const uploadFileItem = filesItems[i]; if (uploadFileItem.kind === 'file') { //Defensive code to validate if function exists in Browser //Collect all Folders into Array if (uploadFileItem.getAsEntry) { entry = uploadFileItem.getAsEntry(); if (entry.isDirectory) { folders.push(entry); } else { const file = uploadFileItem.getAsFile(); if (file) { file.fullPath = ''; collectFilesItems.push(file); } } } else if (uploadFileItem.webkitGetAsEntry) { entry = uploadFileItem.webkitGetAsEntry(); if (entry.isDirectory) { folders.push(entry); } else { const file = uploadFileItem.getAsFile(); if (file) { file.fullPath = ''; collectFilesItems.push(file); } } } else if ('function' == typeof uploadFileItem.getAsFile) { const file = uploadFileItem.getAsFile(); if (file) { file.fullPath = ''; collectFilesItems.push(file); } } continue; } else { const fileItem = uploadFileItem; if (fileItem) { fileItem.fullPath = ''; collectFilesItems.push(fileItem); } } } //Collect Files from folder if (folders.length > 0) { const folderFiles = await this.getFolderFiles(folders); collectFilesItems.push(...folderFiles); } return collectFilesItems; } /** * Retrieve files from folder and subfolders to array. * * @param folders * @returns */ protected getFolderFiles(folders) { return new Promise<File[]>(resolve => { let reading = 0; const contents: File[] = []; folders.forEach(entry => { readEntry(entry, ''); }); function readEntry(entry, path) { if (entry.isDirectory) { readReaderContent(entry.createReader()); } else { reading++; entry.file(file => { reading--; //Include Folder path where File is located file.fullPath = path; contents.push(file); if (reading === 0) { resolve(contents); } }); } } function readReaderContent(reader) { reading++; reader.readEntries(entries => { reading--; for (const entry of entries) { readEntry(entry, entry.fullPath); } if (reading === 0) { resolve(contents); } }); } }); } }
the_stack
import { shell } from "@tauri-apps/api"; /** * Generates commandline arguments for yt-dl. Optionally also generates ffmpeg arguments. */ export class Downloader { private readonly runningProcesses = new Map<string, shell.Child>(); constructor() {} /** Video extension */ static get videoFormats() { // Format order taken from https://github.com/yt-dlp/yt-dlp#sorting-formats return ["best", "mp4", "webm", "mkv"] as const; } /** Audio extension */ static get audioFormats() { // No idea if I should remove some of those formats return ["best", "m4a", "aac", "mp3", "ogg", "opus", "webm", "flac", "vorbis", "wav"] as const; } /** Checks if youtube-dl or an alternative exists. Will return the version number, if possible */ async checkYoutubeDl(pathsToCheck: string[]) { for (let i = 0; i < pathsToCheck.length; i++) { const youtubeDlVersion = await this.checkIfBinaryExists(pathsToCheck[i], ["--version"]); if (youtubeDlVersion !== null) { return { binary: pathsToCheck[i], version: youtubeDlVersion, }; } } // TODO: Also check the save file location (where the config file is saved) ^ return null; } /** * * @throws an error if youtube-dl is missing */ async fetchInfoQuick(urls: string[], path: string, dataCallback: (data: DownloadableItemBasic | DownloadableItem) => void) { if (urls.length === 0) return; const args = this.fetchInfoQuickArgs(urls); return this.callYoutubeDl(urls[0], path, args, (data) => { const item = this.parseDownloadableItem(data); if (!item) return; dataCallback(item); }); } /** * * @throws an error if youtube-dl is missing */ async fetchInfo(urls: string[], path: string, dataCallback: (data: DownloadableItem) => void) { if (urls.length === 0) return; const args = this.fetchInfoArgs(urls); return this.callYoutubeDl(urls[0], path, args, (data) => { const item = this.parseDownloadableItem(data); if (item && "formats" in item) { dataCallback(item); } }); } /** * * @throws an error if youtube-dl is missing */ async download( item: DownloadableItem, downloadOptions: DownloadOptions, path: string, dataCallback: (data: { progress: DownloadProgress | null; progressStatus: string; filepath: string | null }) => void ) { const args = this.downloadArgs(item, downloadOptions); return this.callYoutubeDl(item.url, path, args, (data: string) => { console.log(data); data = ((data ?? "") + "").trimStart(); let progress: null | DownloadProgress = { value: 0, }; let filePath: null | string = null; if (data.startsWith("[download]")) { const downloadString = data.replace(/^\[download\]\s*/, ""); if (downloadString.startsWith("Unknown %")) { progress.value = 0; } else { let match = /^(?<percentage>\d+(?:\.\d+)?)%/.exec(downloadString); if (match && match[1]) { progress.value = +match[1]; } else { progress = null; } } if (progress != null) { // TODO: Finish progress: https://github.com/ytdl-org/youtube-dl/blob/5208ae92fc3e2916cdccae45c6b9a516be3d5796/youtube_dl/downloader/common.py#L289-L304 // \[download\][^0-9]*(?<percentage>\d+(?:\.\d+)?)[^0-9]+(?<size>\d+(?:\.\d+)?)(?<size_unit>\w+)(?:[^0-9]+(\d+\.\d+\w+\/s)\D+((?:\d+:?)+))? } // [download] Destination: ... // [download] ... has already been downloaded let filePathMatch = /^Destination:\s?(.+)|^(.+)\shas already been downloaded/.exec(downloadString); if (filePathMatch && filePathMatch[1]) { filePath = filePathMatch[1]; } } else if (data.startsWith("[ffmpeg]")) { const ffmpegString = data.replace(/^\[ffmpeg\]\s*/, ""); // Encountered during merging of audio and video let filePathMatch = /.*?\"(.*)\"/.exec(ffmpegString); if (filePathMatch && filePathMatch[1]) { filePath = filePathMatch[1]; } // Encountered during format conversion filePathMatch = /.*?Destination:\s(.*)/.exec(ffmpegString); if (filePathMatch && filePathMatch[1]) { filePath = filePathMatch[1]; } } else if (data.startsWith("[Merger]")) { const mergerString = data.replace(/^\[Merger\]\s*/, ""); let filePathMatch = /^Merging formats into "(.+)"/.exec(mergerString); if (filePathMatch && filePathMatch[1]) { filePath = filePathMatch[1]; } } // TODO: Handle le case where the format isn't available in that specific resolution const result = { progress: progress, progressStatus: "petting cats", //this._isPostprocessing(data.toString()), filepath: filePath, }; dataCallback(result); }); } /** Simply kills the child process */ async pause(id: string) { const child = this.runningProcesses.get(id); if (child) { try { await child.kill(); } catch (e) { console.warn(e); } // And now the usual handler will take care of deleting the child process } } /** * * @throws an error if youtube-dl is missing */ async updateYoutubeDl(path: string, dataCallback: (message: string) => void) { const args = this.updateYoutubeDlArgs(); return this.callYoutubeDl("update", path, args, (data) => { dataCallback(data); }); } /** Fetches very basic information for a list of URLs */ private fetchInfoQuickArgs(urls: string[]) { const args = ["--dump-json", "--flat-playlist", "--ignore-errors", ...urls]; return args; } /** Fetches information for a list of URLs */ private fetchInfoArgs(urls: string[]) { const args = ["--all-subs", "--dump-json", "--no-playlist", "--ignore-errors", ...urls]; return args; } private downloadArgs(item: DownloadableItem, { videoFormat, audioFormat, downloadLocation, outputTemplate, compatibilityMode }: DownloadOptions) { const args = []; // Progress bar args.push("--newline"); let audioQuality = item.formats.audioIndex === item.formats.audio.length - 1 ? "" : `[abr<=${item.formats.audio[item.formats.audioIndex]}]`; let videoQuality = item.formats.videoIndex === item.formats.video.length - 1 ? "" : `[height<=${item.formats.video[item.formats.videoIndex]}]`; // Choose format (file extension) if (item.isAudioChosen) { args.push("--format"); let format = `best*[vcodec=none]${audioQuality}`; // Pick best format by default if (audioFormat !== "best") { // Pick format with a given extension format = `bestaudio[ext=${audioFormat}]${audioQuality} / ${format}`; } args.push(format); } else { args.push("--format"); let format = `bestvideo*${videoQuality}+bestaudio${videoQuality}/best${videoQuality}`; // Pick best format by default if (videoFormat !== "best") { // Pick format with a given extension format = `bestvideo*[ext=${videoFormat}]${videoQuality}+bestaudio[ext=${videoFormat}]${videoQuality}/best[ext=${videoFormat}]${videoQuality} / ${format}`; } args.push(format); } // Output file name if ((outputTemplate + "").trim().length > 0) { // TODO: Put in correct folder (path join) // https://github.com/ytdl-org/youtube-dl#how-do-i-put-downloads-into-a-specific-folder // downloadLocation args.push(...["--output", outputTemplate]); } args.push("--embed-subs"); // Subtitles (TODO: Does this need --write-subs) args.push("--embed-thumbnail"); // Pretty thumbnails //args.push("--embed-metadata"); // More metadata (TODO: Youtube-dl doesn't understand this) // TODO: --limit-rate // https://github.com/yt-dlp/yt-dlp#post-processing-options // TODO: Optionally convert it with ffmpeg, if ffmpeg exists /* let args; if (item.isSubsChosen && item.subtitles.length !== 0) { // Download and embed subtitles args = ["--ffmpeg-location", this.ffmpegPath, "--all-subs", "--embed-subs", "-f", format, "-o", outputFormat]; } else { args = ["--ffmpeg-location", this.ffmpegPath, "-f", format, "-o", outputFormat]; } if (item.isAudioChosen) { args.push(...["--extract-audio", "--audio-format", audioFormat]); } else if (videoFormat != "default") { args.push(...["--recode-video", videoFormat]); }*/ args.push("--"); args.push(item.url); return args; } private updateYoutubeDlArgs() { const args = ["--update"]; return args; } private async checkIfBinaryExists(name: string, args: string[]) { try { const result = await new shell.Command(name, args).execute(); if (result.code === null || result.code === 0) { return result.stdout; } } catch (e) { return null; } return null; } private parseDownloadableItem(data: string): DownloadableItemBasic | DownloadableItem | null { try { let item = JSON.parse(data); if (item.formats) { // It's a typical DownloadableItem let video: number[] = []; let audio: number[] = []; item.formats.forEach((format: { vcodec?: string; acodec?: string; height?: null | number; abr?: null | number; tbr?: null | number }) => { if (format.vcodec !== "none" && video.indexOf(format.height ?? 0) === -1) { video.push(format.height ?? 0); } else if (format.acodec !== "none" && audio.indexOf(format.abr ?? format.tbr ?? 0) === -1) { audio.push(format.abr ?? format.tbr ?? 0); } }); // Sort in ascending order video.sort((a, b) => a - b); audio.sort((a, b) => a - b); let downloadableItem: DownloadableItem = { // Basic url: item.webpage_url || item.url, title: item.title, duration: item.duration, uploader: item.uploader, // More stuff directly taken from the item thumbnail: item.thumbnail, // Stuff parsed from the item formats: { video: video, audio: audio, videoIndex: video.length - 1, audioIndex: audio.length - 1, }, playlist: item.playlist ? { entries: item.n_entries, title: item.playlist_title, id: item.playlist_id + "", index: item.playlist_index, } : undefined, subtitles: item.requested_subtitles == null ? [] : Object.keys(item.requested_subtitles), // UI state progress: { value: 0, }, state: "stopped", isChosen: false, isSubsChosen: false, isAudioChosen: false, }; return downloadableItem; // } else { // It's a DownloadableItemBasic let downloadableItem: DownloadableItemBasic = { url: item.url, title: item.title, duration: item.duration, uploader: item.uploader, } as DownloadableItemBasic; return downloadableItem; } } catch (e) { console.warn("Unable to parse", e, data); } return null; } /** * Calls youtube-dl with the given arguments and returns some info. Throws an error if youtube-dl cannot be found */ private callYoutubeDl(id: string, path: string, args: string[], dataCallback: (data: any) => void) { if (this.runningProcesses.get(id) !== undefined) { console.warn(`Process with id ${id} is still running`); return; } const command = new shell.Command(path, args); console.info(path, args); // Always print this! // Data command.stdout.on("data", (data) => { // Every new playlist entry will be on its own line dataCallback(data); }); command.stderr.on("data", (error) => { // TODO: Better error handling, for now this is fine console.error(error); }); // Done let resolveFinishedPromise = () => {}; let rejectFinishedPromise = (reason?: any) => {}; const finishedPromise = new Promise<void>((resolve, reject) => { resolveFinishedPromise = resolve; rejectFinishedPromise = reject; }); command.on("close", (data) => { if (data.code === null || data.code === 0) { resolveFinishedPromise(); } else { rejectFinishedPromise("Unexpected result: " + data); } }); command.on("error", (error) => rejectFinishedPromise(error)); // Start the child process const childPromise = command.spawn().then((childProcess) => { this.runningProcesses.set(id, childProcess); }); // And wait for everything to be done return finishedPromise.finally(() => { return childPromise.finally(() => { this.runningProcesses.delete(id); }); }); } // TODO: checkFfmpeg(path?: string) // TODO: downloadYoutubeDl() which tries to download it from multiple mirrors (first yt-dlc then youtube-dl) // https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest // https://api.github.com/repos/ytdl-org/youtube-dl/releases/latest // Take the .exe asset on Windows, and the no extension asset otherwise // Oh, it should also be able to ask the locally installed package manager to do so? // TODO: downloadFfmpeg() which tries to download it from multiple mirrors // https://api.github.com/repos/BtbN/youtube-dl/FFmpeg-Builds/latest with build ffmpeg-n4.4-78-g031c0cb0b4-win64-gpl-shared-4.4.zip // needs unzipping (???) // https://www.gyan.dev/ffmpeg/builds/ // https://github.com/GyanD/codexffmpeg/releases/tag/4.4 with build ffmpeg-4.4-essentials_build.7z // needs un7zipping (???) // TODO: Better playlist support https://github.com/ytdl-org/youtube-dl#how-do-i-download-only-new-videos-from-a-playlist // TODO: Wait, should we automatically download dependencies on linux? Or can we just politely ask the Linux-fu-masters to do it themselves? // Windows Operating System detection in Rust https://doc.rust-lang.org/rust-by-example/attribute/cfg.html } export interface DownloadableItemBasic { url: string; title: string; /** Duration in seconds */ duration: number; uploader?: string; } export interface DownloadableItem extends DownloadableItemBasic { filepath?: string; thumbnail?: string; isChosen: boolean; state: "stopped" | "completed" | "downloading" | "queued" | "postprocessing"; isSubsChosen: boolean; /** * Only download audio. * @default false, both video and audio will be downloaded */ isAudioChosen: boolean; formats: { /** Video resolution, sorted from worst to best */ video: number[]; /** Audio quality, sorted from worst to best */ audio: number[]; videoIndex: number; audioIndex: number; }; subtitles: string[]; progress: DownloadProgress; playlist?: { entries: number; title: string; id: string; index: number; }; } type DownloadProgress = { value: number; size?: string; speed?: string; eta?: string; }; // TODO: Rename to VideoExtension type VideoFormat = typeof Downloader.videoFormats[number]; type AudioFormat = typeof Downloader.audioFormats[number]; type DownloadOptions = { videoFormat: VideoFormat; audioFormat: AudioFormat; downloadLocation: string; outputTemplate: string; compatibilityMode: boolean; }; function assertUnreachable(value: never): never { throw new Error("Didn't expect to get here" + value); }
the_stack
var has = Object.prototype.hasOwnProperty; var prefix: any = '~'; /** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @private */ function Events() { } // // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if (Object.create) { Events.prototype = Object.create(null); // // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if (!new Events().__proto__) prefix = false; } /** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Add a listener for a given event. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} once Specify if the listener is a one-time listener. * @returns {EventEmitter} * @private */ function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } /** * Clear event by name. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} evt The Event name. * @private */ function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } export class EventEmitter { public _events = new Events(); public _eventsCount = 0; /** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @public */ constructor() { this._events = new Events(); this._eventsCount = 0; } /** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @public */ public eventNames() { var names = [] , events , name; if (this._eventsCount === 0) return names; for (name in (events = this._events)) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; /** * Return the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Array} The registered listeners. * @public */ public listeners(event) { var evt = prefix ? prefix + event : event , handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; /** * Return the number of listeners listening to a given event. * * @param {(String|Symbol)} event The event name. * @returns {Number} The number of listeners. * @public */ public listenerCount(event) { var evt = prefix ? prefix + event : event , listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; /** * Calls each of the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Boolean} `true` if the event had listeners, else `false`. * @public */ public emit(event, a1?, a2?, a3?, a4?, a5?) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt] , len = arguments.length , args , i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len - 1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Add a listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ public on(event, fn, context?) { return addListener(this, event, fn, context, false); }; /** * Add a one-time listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ public once(event, fn, context) { return addListener(this, event, fn, context, true); }; /** * Remove the listeners of a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn Only remove the listeners that match this function. * @param {*} context Only remove the listeners that have this context. * @param {Boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. * @public */ public removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if ( listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context) ) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if ( listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context) ) { events.push(listeners[i]); } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; /** * Remove all listeners, or those of the specified event. * * @param {(String|Symbol)} [event] The event name. * @returns {EventEmitter} `this`. * @public */ public removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; } // // Alias methods names because people roll like that. // (<any>EventEmitter).prototype.off = EventEmitter.prototype.removeListener; (<any>EventEmitter).prototype.addListener = EventEmitter.prototype.on; // // Expose the prefix. // (<any>EventEmitter).prefixed = prefix; // // Allow `EventEmitter` to be imported as module namespace. // (<any>EventEmitter).EventEmitter = EventEmitter;
the_stack
import { Client } from '@elastic/elasticsearch' import merge from 'lodash/merge' import * as AWS from 'aws-sdk' import AwsConnector from 'aws-elasticsearch-connector' import { Injectable } from '@nestjs/common' import { logger } from '@island.is/logging' import { autocompleteTermQuery } from '../queries/autocomplete' import { searchQuery } from '../queries/search' import { documentByMetaDataQuery } from '../queries/documentByMetaData' import { AutocompleteTermInput, SearchInput, TagAggregationResponse, DocumentByMetaDataInput, DateAggregationInput, DateAggregationResponse, AutocompleteTermResponse, TagAggregationInput, SyncRequest, TypeAggregationInput, TypeAggregationResponse, RankEvaluationInput, GroupedRankEvaluationResponse, rankEvaluationMetrics, } from '../types' import { DeleteByQueryResponse, GetByIdResponse, RankEvaluationResponse, SearchResponse, } from '@island.is/shared/types' import { MappedData } from '@island.is/content-search-indexer/types' import { environment } from '../environments/environment' import { dateAggregationQuery } from '../queries/dateAggregation' import { tagAggregationQuery } from '../queries/tagAggregation' import { typeAggregationQuery } from '../queries/typeAggregation' import { rankEvaluationQuery } from '../queries/rankEvaluation' type RankResultMap<T extends string> = Record<string, RankEvaluationResponse<T>> const { elastic } = environment @Injectable() export class ElasticService { private client: Client | null = null constructor() { logger.debug('Created ES Service') } async index(index: string, { _id, ...body }: MappedData) { try { const client = await this.getClient() return await client.index({ id: _id, index: index, body, }) } catch (error) { logger.error('Elastic request failed on index', error) throw error } } // this can partially succeed async bulk(index: string, documents: SyncRequest) { logger.info('Processing documents', { index, added: documents.add.length, removed: documents.remove.length, }) const requests: Record<string, unknown>[] = [] // if we have any documents to add add them to the request if (documents.add.length) { documents.add.forEach(({ _id, ...document }) => { requests.push({ update: { _index: index, _id }, }) requests.push({ doc: document, doc_as_upsert: true, }) return requests }) } // if we have any documents to remove add them to the request if (documents.remove.length) { documents.remove.forEach((_id) => { requests.push({ delete: { _index: index, _id }, }) }) } if (!requests.length) { logger.info('No requests for elasticsearch to execute') // no need to continue return false } await this.bulkRequest(index, requests) } async bulkRequest(index: string, requests: Record<string, unknown>[]) { try { // elasticsearch does not like big requests (above 5mb) so we limit the size to X entries just in case const chunkSize = 20 // this has to be an even number const client = await this.getClient() let requestChunk = requests.splice(-chunkSize, chunkSize) while (requestChunk.length) { // wait for request b4 continuing const response = await client.bulk({ index: index, body: requestChunk, }) // not all errors are thrown log if the response has any errors if (response.body.errors) { logger.error('Failed to import some documents in bulk import', { response, }) } requestChunk = requests.splice(-chunkSize, chunkSize) } return true } catch (error) { logger.error('Elasticsearch request failed on bulk import', error) throw error } } async findByQuery<ResponseBody, RequestBody>( index: string, query: RequestBody, ) { try { const client = await this.getClient() return client.search<ResponseBody, RequestBody>({ body: query, index, }) } catch (e) { return ElasticService.handleError( 'Error in ElasticService.findByQuery', { query, index }, e, ) } } async findById(index: string, id: string) { try { const client = await this.getClient() return await client.get<GetByIdResponse<MappedData>>({ id, index }) } catch (e) { return ElasticService.handleError( 'Error in ElasticService.findById', { id, index }, e, ) } } async rankEvaluation<ResponseBody, RequestBody>( index: string, body: RequestBody, ) { const client = await this.getClient() return client.rank_eval<ResponseBody, RequestBody>({ index, body, }) } async getRankEvaluation<searchTermUnion extends string>( index: string, termRatings: RankEvaluationInput['termRatings'], metrics: RankEvaluationInput['metric'][], ): Promise<GroupedRankEvaluationResponse<searchTermUnion>> { // elasticsearch does not support multiple metric request per rank_eval call so we make multiple calls const requests = metrics.map(async (metric) => { const requestBody = rankEvaluationQuery({ termRatings, metric }) const data = await this.rankEvaluation< RankEvaluationResponse<searchTermUnion>, typeof requestBody >(index, requestBody) return data.body }) const results = await Promise.all(requests) return results.reduce<RankResultMap<searchTermUnion>>( (groupedResults, result, index) => { groupedResults[metrics[index]] = result return groupedResults }, {}, ) } async getDocumentsByMetaData(index: string, query: DocumentByMetaDataInput) { const requestBody = documentByMetaDataQuery(query) const data = await this.findByQuery< SearchResponse<MappedData>, typeof requestBody >(index, requestBody) return data.body } async getSingleDocumentByMetaData( index: string, query: DocumentByMetaDataInput, ) { const results = await this.getDocumentsByMetaData(index, query) if (results.hits?.hits.length) { this.updateDocumentPopularityScore(index, results.hits?.hits[0]._id) } return results } // we use this equation to update the popularity score // https://stackoverflow.com/questions/11128086/simple-popularity-algorithm async updateDocumentPopularityScore(index: string, id: string) { const client = await this.getClient() client .update({ index, id, body: { script: { lang: 'painless', source: `if (ctx._source.containsKey('popularityScore')) { ctx._source.popularityScore = params.a * params.t + (1 - params.a) * ctx._source.popularityScore } else { ctx._source.popularityScore = 0 } `, params: { a: environment.popularityFactor, t: Number(new Date()) / 1000, }, }, }, retry_on_conflict: 1, }) .catch((error) => { // failing to update the popularity score is not the end of the world so // we don't throw the error. we will see in the logs how common this is logger.error('Could not update popularityScore', error) }) } async getTagAggregation(index: string, query: TagAggregationInput) { const requestBody = tagAggregationQuery(query) const data = await this.findByQuery< SearchResponse<any, TagAggregationResponse>, typeof requestBody >(index, requestBody) return data.body } async getTypeAggregation(index: string, query: TypeAggregationInput) { const requestBody = typeAggregationQuery(query) const data = await this.findByQuery< SearchResponse<any, TypeAggregationResponse>, typeof requestBody >(index, requestBody) return data.body } async getDateAggregation(index: string, query: DateAggregationInput) { const requestBody = dateAggregationQuery(query) const data = await this.findByQuery< SearchResponse<any, DateAggregationResponse>, typeof requestBody >(index, requestBody) return data.body } async search(index: string, query: SearchInput) { const requestBody = searchQuery(query) return this.findByQuery< SearchResponse< MappedData, TagAggregationResponse | TypeAggregationResponse >, typeof requestBody >(index, requestBody) } async fetchAutocompleteTerm( index: string, input: AutocompleteTermInput, ): Promise<AutocompleteTermResponse> { const { singleTerm, size } = input const requestBody = autocompleteTermQuery({ singleTerm, size }) const data = await this.findByQuery< AutocompleteTermResponse, typeof requestBody >(index, requestBody) return data.body } async deleteByIds(index: string, ids: Array<string>) { // In case we get an empty list, ES will match that to all records... which we don't want to delete if (!ids.length) { return } const client = await this.getClient() return client.delete_by_query({ index: index, body: { query: { bool: { must: ids.map((id) => ({ match: { _id: id } })), }, }, }, }) } // remove all documents that have not been updated in the last X minutes async deleteAllDocumentsNotVeryRecentlyUpdated(index: string) { const client = await this.getClient() return client.delete_by_query<DeleteByQueryResponse>({ index: index, body: { query: { range: { dateUpdated: { lt: 'now-30m', // older than 30 minutes from now }, }, }, }, }) } async ping() { const client = await this.getClient() const result = await client.ping().catch((error) => { ElasticService.handleError('Error in ping', {}, error) }) logger.info('Got elasticsearch ping response') return result } async getClient(): Promise<Client> { if (this.client) { return this.client } this.client = await this.createEsClient() return this.client } async createEsClient(): Promise<Client> { const hasAWS = 'AWS_WEB_IDENTITY_TOKEN_FILE' in process.env logger.info('Create AWS ES Client', { esConfig: elastic, withAWS: hasAWS, }) if (!hasAWS) { return new Client({ node: elastic.node, requestTimeout: 30000, }) } return new Client({ ...AwsConnector(AWS.config), node: elastic.node, }) } // eslint-disable-next-line @typescript-eslint/no-explicit-any static handleError(message: string, context: any, error: Error): never { ElasticService.logError(message, context, error) throw error } // eslint-disable-next-line @typescript-eslint/no-explicit-any static logError(message: string, context: any, error: any) { const errorCtx = { error: { message: error.message, reason: error.error?.meta?.body?.error?.reason, status: error.error?.meta?.body?.status, statusCode: error.error?.meta?.statusCode, }, } logger.error(message, merge(context, errorCtx)) } }
the_stack
type BigInt = number declare const BigInt: typeof Number type BigUint64Array = Float32Array declare const BigUint64Array: typeof Float32Array declare var VkInout: { $: number; } export interface VkInout { $: number; } declare var VkInoutAddress: { $: BigInt; } export interface VkInoutAddress { $: BigInt; } /** #### ENUMS #### **/ /** ## API_Extensions_Strings ## */ export enum API_Extensions_Strings { VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_DISPLAY_EXTENSION_NAME, VK_KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME, VK_KHR_XLIB_SURFACE_EXTENSION_NAME, VK_KHR_XCB_SURFACE_EXTENSION_NAME, VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, VK_KHR_MIR_SURFACE_EXTENSION_NAME, VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME, VK_ANDROID_NATIVE_BUFFER_NAME, VK_EXT_DEBUG_REPORT_EXTENSION_NAME, VK_NV_GLSL_SHADER_EXTENSION_NAME, VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME, VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME, VK_IMG_FILTER_CUBIC_EXTENSION_NAME, VK_AMD_EXTENSION_17_EXTENSION_NAME, VK_AMD_EXTENSION_18_EXTENSION_NAME, VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME, VK_AMD_EXTENSION_20_EXTENSION_NAME, VK_AMD_SHADER_TRINARY_MINMAX_EXTENSION_NAME, VK_AMD_SHADER_EXPLICIT_VERTEX_PARAMETER_EXTENSION_NAME, VK_EXT_DEBUG_MARKER_EXTENSION_NAME, VK_AMD_EXTENSION_24_EXTENSION_NAME, VK_AMD_EXTENSION_25_EXTENSION_NAME, VK_AMD_GCN_SHADER_EXTENSION_NAME, VK_NV_DEDICATED_ALLOCATION_EXTENSION_NAME, VK_EXT_EXTENSION_28_EXTENSION_NAME, VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME, VK_NVX_EXTENSION_30_EXTENSION_NAME, VK_NVX_EXTENSION_31_EXTENSION_NAME, VK_AMD_EXTENSION_32_EXTENSION_NAME, VK_AMD_EXTENSION_33_EXTENSION_NAME, VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME, VK_AMD_EXTENSION_35_EXTENSION_NAME, VK_AMD_NEGATIVE_VIEWPORT_HEIGHT_EXTENSION_NAME, VK_AMD_GPU_SHADER_HALF_FLOAT_EXTENSION_NAME, VK_AMD_SHADER_BALLOT_EXTENSION_NAME, VK_AMD_EXTENSION_39_EXTENSION_NAME, VK_AMD_EXTENSION_40_EXTENSION_NAME, VK_AMD_EXTENSION_41_EXTENSION_NAME, VK_AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME, VK_AMD_SHADER_INFO_EXTENSION_NAME, VK_AMD_EXTENSION_44_EXTENSION_NAME, VK_AMD_EXTENSION_45_EXTENSION_NAME, VK_AMD_EXTENSION_46_EXTENSION_NAME, VK_AMD_SHADER_IMAGE_LOAD_STORE_LOD_EXTENSION_NAME, VK_NVX_EXTENSION_48_EXTENSION_NAME, VK_GOOGLE_EXTENSION_49_EXTENSION_NAME, VK_GOOGLE_EXTENSION_50_EXTENSION_NAME, VK_NV_CORNER_SAMPLED_IMAGE_EXTENSION_NAME, VK_NVX_EXTENSION_52_EXTENSION_NAME, VK_NV_EXTENSION_53_EXTENSION_NAME, VK_KHR_MULTIVIEW_EXTENSION_NAME, VK_IMG_FORMAT_PVRTC_EXTENSION_NAME, VK_NV_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME, VK_NV_EXTERNAL_MEMORY_EXTENSION_NAME, VK_NV_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME, VK_NV_WIN32_KEYED_MUTEX_EXTENSION_NAME, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, VK_KHR_DEVICE_GROUP_EXTENSION_NAME, VK_EXT_VALIDATION_FLAGS_EXTENSION_NAME, VK_NN_VI_SURFACE_EXTENSION_NAME, VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, VK_ARM_EXTENSION_01_EXTENSION_NAME, VK_EXT_ASTC_DECODE_MODE_EXTENSION_NAME, VK_IMG_EXTENSION_69_EXTENSION_NAME, VK_KHR_MAINTENANCE1_EXTENSION_NAME, VK_KHR_DEVICE_GROUP_CREATION_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, VK_KHR_WIN32_KEYED_MUTEX_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME, VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME, VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME, VK_KHR_16BIT_STORAGE_EXTENSION_NAME, VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME, VK_NVX_DEVICE_GENERATED_COMMANDS_EXTENSION_NAME, VK_NV_CLIP_SPACE_W_SCALING_EXTENSION_NAME, VK_EXT_DIRECT_MODE_DISPLAY_EXTENSION_NAME, VK_EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME, VK_EXT_DISPLAY_SURFACE_COUNTER_EXTENSION_NAME, VK_EXT_DISPLAY_CONTROL_EXTENSION_NAME, VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME, VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, VK_NVX_MULTIVIEW_PER_VIEW_ATTRIBUTES_EXTENSION_NAME, VK_NV_VIEWPORT_SWIZZLE_EXTENSION_NAME, VK_EXT_DISCARD_RECTANGLES_EXTENSION_NAME, VK_NV_EXTENSION_101_EXTENSION_NAME, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME, VK_NV_EXTENSION_103_EXTENSION_NAME, VK_NV_EXTENSION_104_EXTENSION_NAME, VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME, VK_EXT_HDR_METADATA_EXTENSION_NAME, VK_IMG_EXTENSION_107_EXTENSION_NAME, VK_IMG_EXTENSION_108_EXTENSION_NAME, VK_IMG_EXTENSION_109_EXTENSION_NAME, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME, VK_IMG_EXTENSION_111_EXTENSION_NAME, VK_KHR_SHARED_PRESENTABLE_IMAGE_EXTENSION_NAME, VK_KHR_EXTERNAL_FENCE_CAPABILITIES_EXTENSION_NAME, VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME, VK_KHR_EXTERNAL_FENCE_WIN32_EXTENSION_NAME, VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME, VK_KHR_EXTENSION_117_EXTENSION_NAME, VK_KHR_MAINTENANCE2_EXTENSION_NAME, VK_KHR_EXTENSION_119_EXTENSION_NAME, VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME, VK_KHR_VARIABLE_POINTERS_EXTENSION_NAME, VK_KHR_GET_DISPLAY_PROPERTIES_2_EXTENSION_NAME, VK_MVK_IOS_SURFACE_EXTENSION_NAME, VK_MVK_MACOS_SURFACE_EXTENSION_NAME, VK_MVK_MOLTENVK_EXTENSION_NAME, VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME, VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME, VK_EXT_DEBUG_UTILS_EXTENSION_NAME, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME, VK_EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME, VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME, VK_AMD_GPU_SHADER_INT16_EXTENSION_NAME, VK_AMD_EXTENSION_134_EXTENSION_NAME, VK_AMD_EXTENSION_135_EXTENSION_NAME, VK_AMD_EXTENSION_136_EXTENSION_NAME, VK_AMD_MIXED_ATTACHMENT_SAMPLES_EXTENSION_NAME, VK_AMD_SHADER_FRAGMENT_MASK_EXTENSION_NAME, VK_EXT_INLINE_UNIFORM_BLOCK_EXTENSION_NAME, VK_AMD_EXTENSION_140_EXTENSION_NAME, VK_EXT_SHADER_STENCIL_EXPORT_EXTENSION_NAME, VK_AMD_EXTENSION_142_EXTENSION_NAME, VK_AMD_EXTENSION_143_EXTENSION_NAME, VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME, VK_KHR_RELAXED_BLOCK_LAYOUT_EXTENSION_NAME, VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME, VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME, VK_EXT_BLEND_OPERATION_ADVANCED_EXTENSION_NAME, VK_NV_FRAGMENT_COVERAGE_TO_COLOR_EXTENSION_NAME, VK_NV_EXTENSION_151_EXTENSION_NAME, VK_NV_EXTENSION_152_EXTENSION_NAME, VK_NV_FRAMEBUFFER_MIXED_SAMPLES_EXTENSION_NAME, VK_NV_FILL_RECTANGLE_EXTENSION_NAME, VK_NV_EXTENSION_155_EXTENSION_NAME, VK_EXT_POST_DEPTH_COVERAGE_EXTENSION_NAME, VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME, VK_KHR_BIND_MEMORY_2_EXTENSION_NAME, VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME, VK_EXT_EXTENSION_160_EXTENSION_NAME, VK_EXT_VALIDATION_CACHE_EXTENSION_NAME, VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, VK_EXT_EXTENSION_164_EXTENSION_NAME, VK_NV_SHADING_RATE_IMAGE_EXTENSION_NAME, VK_NV_RAY_TRACING_EXTENSION_NAME, VK_NV_REPRESENTATIVE_FRAGMENT_TEST_EXTENSION_NAME, VK_EXT_EXTENSION_168_EXTENSION_NAME, VK_KHR_MAINTENANCE3_EXTENSION_NAME, VK_KHR_DRAW_INDIRECT_COUNT_EXTENSION_NAME, VK_QCOM_extension_171_EXTENSION_NAME, VK_QCOM_extension_172_EXTENSION_NAME, VK_QCOM_extension_173_EXTENSION_NAME, VK_QCOM_extension_174_EXTENSION_NAME, VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME, VK_KHR_EXTENSION_176_EXTENSION_NAME, VK_KHR_EXTENSION_177_EXTENSION_NAME, VK_KHR_8BIT_STORAGE_EXTENSION_NAME, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME, VK_AMD_BUFFER_MARKER_EXTENSION_NAME, VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME, VK_KHR_EXTENSION_182_EXTENSION_NAME, VK_KHR_EXTENSION_183_EXTENSION_NAME, VK_KHR_EXTENSION_184_EXTENSION_NAME, VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME, VK_AMD_SHADER_CORE_PROPERTIES_EXTENSION_NAME, VK_KHR_EXTENSION_187_EXTENSION_NAME, VK_KHR_EXTENSION_188_EXTENSION_NAME, VK_KHR_EXTENSION_189_EXTENSION_NAME, VK_AMD_MEMORY_OVERALLOCATION_BEHAVIOR_EXTENSION_NAME, VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME, VK_GOOGLE_EXTENSION_192_EXTENSION_NAME, VK_GOOGLE_EXTENSION_193_EXTENSION_NAME, VK_GOOGLE_EXTENSION_194_EXTENSION_NAME, VK_GOOGLE_EXTENSION_195_EXTENSION_NAME, VK_GOOGLE_EXTENSION_196_EXTENSION_NAME, VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME, VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME, VK_NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME, VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME, VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME, VK_NV_COMPUTE_SHADER_DERIVATIVES_EXTENSION_NAME, VK_NV_MESH_SHADER_EXTENSION_NAME, VK_NV_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, VK_NV_SHADER_IMAGE_FOOTPRINT_EXTENSION_NAME, VK_NV_SCISSOR_EXCLUSIVE_EXTENSION_NAME, VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME, VK_KHR_EXTENSION_208_EXTENSION_NAME, VK_KHR_EXTENSION_209_EXTENSION_NAME, VK_KHR_EXTENSION_210_EXTENSION_NAME, VK_KHR_EXTENSION_211_EXTENSION_NAME, VK_KHR_VULKAN_MEMORY_MODEL_EXTENSION_NAME, VK_EXT_PCI_BUS_INFO_EXTENSION_NAME, VK_KHR_EXTENSION_214_EXTENSION_NAME, VK_FUCHSIA_IMAGEPIPE_SURFACE_EXTENSION_NAME, VK_KHR_EXTENSION_216_EXTENSION_NAME, VK_KHR_EXTENSION_217_EXTENSION_NAME, VK_EXT_MACOS_IOS_WINDOW_EXTENSION_NAME, VK_EXT_FRAGMENT_DENSITY_MAP_EXTENSION_NAME, VK_EXT_EXTENSION_220_EXTENSION_NAME, VK_KHR_EXTENSION_221_EXTENSION_NAME, VK_EXT_SCALAR_BLOCK_LAYOUT_EXTENSION_NAME, VK_EXT_EXTENSION_223_EXTENSION_NAME, VK_GOOGLE_HLSL_FUNCTIONALITY1_EXTENSION_NAME, VK_GOOGLE_DECORATE_STRING_EXTENSION_NAME, VK_AMD_EXTENSION_226_EXTENSION_NAME, VK_AMD_EXTENSION_227_EXTENSION_NAME, VK_AMD_EXTENSION_228_EXTENSION_NAME, VK_AMD_EXTENSION_229_EXTENSION_NAME, VK_AMD_EXTENSION_230_EXTENSION_NAME, VK_AMD_EXTENSION_231_EXTENSION_NAME, VK_AMD_EXTENSION_232_EXTENSION_NAME, VK_AMD_EXTENSION_233_EXTENSION_NAME, VK_AMD_EXTENSION_234_EXTENSION_NAME, VK_AMD_EXTENSION_235_EXTENSION_NAME, VK_AMD_EXTENSION_236_EXTENSION_NAME, VK_KHR_EXTENSION_237_EXTENSION_NAME, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, VK_EXT_MEMORY_PRIORITY_EXTENSION_NAME, VK_KHR_EXTENSION_240_EXTENSION_NAME, VK_NV_EXTENSION_241_EXTENSION_NAME, VK_NV_EXTENSION_242_EXTENSION_NAME, VK_INTEL_EXTENSION_243_EXTENSION_NAME, VK_MESA_EXTENSION_244_EXTENSION_NAME, VK_EXT_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME, VK_EXT_EXTENSION_246_EXTENSION_NAME, VK_EXT_SEPARATE_STENCIL_USAGE_EXTENSION_NAME, VK_EXT_VALIDATION_FEATURES_EXTENSION_NAME, VK_KHR_EXTENSION_249_EXTENSION_NAME, VK_NV_EXTENSION_250_EXTENSION_NAME, } /** ## API_Extensions ## */ export enum API_Extensions { VK_KHR_SURFACE_SPEC_VERSION, VK_KHR_SWAPCHAIN_SPEC_VERSION, VK_KHR_DISPLAY_SPEC_VERSION, VK_KHR_DISPLAY_SWAPCHAIN_SPEC_VERSION, VK_KHR_XLIB_SURFACE_SPEC_VERSION, VK_KHR_XCB_SURFACE_SPEC_VERSION, VK_KHR_WAYLAND_SURFACE_SPEC_VERSION, VK_KHR_MIR_SURFACE_SPEC_VERSION, VK_KHR_ANDROID_SURFACE_SPEC_VERSION, VK_KHR_WIN32_SURFACE_SPEC_VERSION, VK_ANDROID_NATIVE_BUFFER_SPEC_VERSION, VK_ANDROID_NATIVE_BUFFER_NUMBER, VK_EXT_DEBUG_REPORT_SPEC_VERSION, VK_NV_GLSL_SHADER_SPEC_VERSION, VK_EXT_DEPTH_RANGE_UNRESTRICTED_SPEC_VERSION, VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_SPEC_VERSION, VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE, VK_IMG_FILTER_CUBIC_SPEC_VERSION, VK_AMD_EXTENSION_17_SPEC_VERSION, VK_AMD_EXTENSION_18_SPEC_VERSION, VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION, VK_AMD_EXTENSION_20_SPEC_VERSION, VK_AMD_SHADER_TRINARY_MINMAX_SPEC_VERSION, VK_AMD_SHADER_EXPLICIT_VERTEX_PARAMETER_SPEC_VERSION, VK_EXT_DEBUG_MARKER_SPEC_VERSION, VK_AMD_EXTENSION_24_SPEC_VERSION, VK_AMD_EXTENSION_25_SPEC_VERSION, VK_AMD_GCN_SHADER_SPEC_VERSION, VK_NV_DEDICATED_ALLOCATION_SPEC_VERSION, VK_EXT_EXTENSION_28_SPEC_VERSION, VK_EXT_TRANSFORM_FEEDBACK_SPEC_VERSION, VK_NVX_EXTENSION_30_SPEC_VERSION, VK_NVX_EXTENSION_31_SPEC_VERSION, VK_AMD_EXTENSION_32_SPEC_VERSION, VK_AMD_EXTENSION_33_SPEC_VERSION, VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION, VK_AMD_EXTENSION_35_SPEC_VERSION, VK_AMD_NEGATIVE_VIEWPORT_HEIGHT_SPEC_VERSION, VK_AMD_GPU_SHADER_HALF_FLOAT_SPEC_VERSION, VK_AMD_SHADER_BALLOT_SPEC_VERSION, VK_AMD_EXTENSION_39_SPEC_VERSION, VK_AMD_EXTENSION_40_SPEC_VERSION, VK_AMD_EXTENSION_41_SPEC_VERSION, VK_AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION, VK_AMD_SHADER_INFO_SPEC_VERSION, VK_AMD_EXTENSION_44_SPEC_VERSION, VK_AMD_EXTENSION_45_SPEC_VERSION, VK_AMD_EXTENSION_46_SPEC_VERSION, VK_AMD_SHADER_IMAGE_LOAD_STORE_LOD_SPEC_VERSION, VK_NVX_EXTENSION_48_SPEC_VERSION, VK_GOOGLE_EXTENSION_49_SPEC_VERSION, VK_GOOGLE_EXTENSION_50_SPEC_VERSION, VK_NV_CORNER_SAMPLED_IMAGE_SPEC_VERSION, VK_NVX_EXTENSION_52_SPEC_VERSION, VK_NV_EXTENSION_53_SPEC_VERSION, VK_KHR_MULTIVIEW_SPEC_VERSION, VK_IMG_FORMAT_PVRTC_SPEC_VERSION, VK_NV_EXTERNAL_MEMORY_CAPABILITIES_SPEC_VERSION, VK_NV_EXTERNAL_MEMORY_SPEC_VERSION, VK_NV_EXTERNAL_MEMORY_WIN32_SPEC_VERSION, VK_NV_WIN32_KEYED_MUTEX_SPEC_VERSION, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_SPEC_VERSION, VK_KHR_DEVICE_GROUP_SPEC_VERSION, VK_EXT_VALIDATION_FLAGS_SPEC_VERSION, VK_NN_VI_SURFACE_SPEC_VERSION, VK_KHR_SHADER_DRAW_PARAMETERS_SPEC_VERSION, VK_EXT_SHADER_SUBGROUP_BALLOT_SPEC_VERSION, VK_EXT_SHADER_SUBGROUP_VOTE_SPEC_VERSION, VK_ARM_EXTENSION_01_SPEC_VERSION, VK_EXT_ASTC_DECODE_MODE_SPEC_VERSION, VK_IMG_EXTENSION_69_SPEC_VERSION, VK_KHR_MAINTENANCE1_SPEC_VERSION, VK_KHR_DEVICE_GROUP_CREATION_SPEC_VERSION, VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_SPEC_VERSION, VK_KHR_EXTERNAL_MEMORY_SPEC_VERSION, VK_KHR_EXTERNAL_MEMORY_WIN32_SPEC_VERSION, VK_KHR_EXTERNAL_MEMORY_FD_SPEC_VERSION, VK_KHR_WIN32_KEYED_MUTEX_SPEC_VERSION, VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_SPEC_VERSION, VK_KHR_EXTERNAL_SEMAPHORE_SPEC_VERSION, VK_KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION, VK_KHR_EXTERNAL_SEMAPHORE_FD_SPEC_VERSION, VK_KHR_PUSH_DESCRIPTOR_SPEC_VERSION, VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR, VK_EXT_CONDITIONAL_RENDERING_SPEC_VERSION, VK_KHR_SHADER_FLOAT16_INT8_SPEC_VERSION, VK_KHR_16BIT_STORAGE_SPEC_VERSION, VK_KHR_INCREMENTAL_PRESENT_SPEC_VERSION, VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_SPEC_VERSION, VK_NVX_DEVICE_GENERATED_COMMANDS_SPEC_VERSION, VK_NV_CLIP_SPACE_W_SCALING_SPEC_VERSION, VK_EXT_DIRECT_MODE_DISPLAY_SPEC_VERSION, VK_EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION, VK_EXT_DISPLAY_SURFACE_COUNTER_SPEC_VERSION, VK_EXT_DISPLAY_CONTROL_SPEC_VERSION, VK_GOOGLE_DISPLAY_TIMING_SPEC_VERSION, VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION, VK_NV_GEOMETRY_SHADER_PASSTHROUGH_SPEC_VERSION, VK_NV_VIEWPORT_ARRAY2_SPEC_VERSION, VK_NVX_MULTIVIEW_PER_VIEW_ATTRIBUTES_SPEC_VERSION, VK_NV_VIEWPORT_SWIZZLE_SPEC_VERSION, VK_EXT_DISCARD_RECTANGLES_SPEC_VERSION, VK_NV_EXTENSION_101_SPEC_VERSION, VK_EXT_CONSERVATIVE_RASTERIZATION_SPEC_VERSION, VK_NV_EXTENSION_103_SPEC_VERSION, VK_NV_EXTENSION_104_SPEC_VERSION, VK_EXT_SWAPCHAIN_COLOR_SPACE_SPEC_VERSION, VK_EXT_HDR_METADATA_SPEC_VERSION, VK_IMG_EXTENSION_107_SPEC_VERSION, VK_IMG_EXTENSION_108_SPEC_VERSION, VK_IMG_EXTENSION_109_SPEC_VERSION, VK_KHR_CREATE_RENDERPASS_2_SPEC_VERSION, VK_IMG_EXTENSION_111_SPEC_VERSION, VK_KHR_SHARED_PRESENTABLE_IMAGE_SPEC_VERSION, VK_KHR_EXTERNAL_FENCE_CAPABILITIES_SPEC_VERSION, VK_KHR_EXTERNAL_FENCE_SPEC_VERSION, VK_KHR_EXTERNAL_FENCE_WIN32_SPEC_VERSION, VK_KHR_EXTERNAL_FENCE_FD_SPEC_VERSION, VK_KHR_EXTENSION_117_SPEC_VERSION, VK_KHR_MAINTENANCE2_SPEC_VERSION, VK_KHR_EXTENSION_119_SPEC_VERSION, VK_KHR_GET_SURFACE_CAPABILITIES_2_SPEC_VERSION, VK_KHR_VARIABLE_POINTERS_SPEC_VERSION, VK_KHR_GET_DISPLAY_PROPERTIES_2_SPEC_VERSION, VK_MVK_IOS_SURFACE_SPEC_VERSION, VK_MVK_MACOS_SURFACE_SPEC_VERSION, VK_MVK_MOLTENVK_SPEC_VERSION, VK_EXT_EXTERNAL_MEMORY_DMA_BUF_SPEC_VERSION, VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION, VK_KHR_DEDICATED_ALLOCATION_SPEC_VERSION, VK_EXT_DEBUG_UTILS_SPEC_VERSION, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_SPEC_VERSION, VK_EXT_SAMPLER_FILTER_MINMAX_SPEC_VERSION, VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_SPEC_VERSION, VK_AMD_GPU_SHADER_INT16_SPEC_VERSION, VK_AMD_EXTENSION_134_SPEC_VERSION, VK_AMD_EXTENSION_135_SPEC_VERSION, VK_AMD_EXTENSION_136_SPEC_VERSION, VK_AMD_MIXED_ATTACHMENT_SAMPLES_SPEC_VERSION, VK_AMD_SHADER_FRAGMENT_MASK_SPEC_VERSION, VK_EXT_INLINE_UNIFORM_BLOCK_SPEC_VERSION, VK_AMD_EXTENSION_140_SPEC_VERSION, VK_EXT_SHADER_STENCIL_EXPORT_SPEC_VERSION, VK_AMD_EXTENSION_142_SPEC_VERSION, VK_AMD_EXTENSION_143_SPEC_VERSION, VK_EXT_SAMPLE_LOCATIONS_SPEC_VERSION, VK_KHR_RELAXED_BLOCK_LAYOUT_SPEC_VERSION, VK_KHR_GET_MEMORY_REQUIREMENTS_2_SPEC_VERSION, VK_KHR_IMAGE_FORMAT_LIST_SPEC_VERSION, VK_EXT_BLEND_OPERATION_ADVANCED_SPEC_VERSION, VK_NV_FRAGMENT_COVERAGE_TO_COLOR_SPEC_VERSION, VK_NV_EXTENSION_151_SPEC_VERSION, VK_NV_EXTENSION_152_SPEC_VERSION, VK_NV_FRAMEBUFFER_MIXED_SAMPLES_SPEC_VERSION, VK_NV_FILL_RECTANGLE_SPEC_VERSION, VK_NV_EXTENSION_155_SPEC_VERSION, VK_EXT_POST_DEPTH_COVERAGE_SPEC_VERSION, VK_KHR_SAMPLER_YCBCR_CONVERSION_SPEC_VERSION, VK_KHR_BIND_MEMORY_2_SPEC_VERSION, VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_SPEC_VERSION, VK_EXT_EXTENSION_160_SPEC_VERSION, VK_EXT_VALIDATION_CACHE_SPEC_VERSION, VK_EXT_DESCRIPTOR_INDEXING_SPEC_VERSION, VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION, VK_EXT_EXTENSION_164_SPEC_VERSION, VK_NV_SHADING_RATE_IMAGE_SPEC_VERSION, VK_NV_RAY_TRACING_SPEC_VERSION, VK_NV_REPRESENTATIVE_FRAGMENT_TEST_SPEC_VERSION, VK_EXT_EXTENSION_168_SPEC_VERSION, VK_KHR_MAINTENANCE3_SPEC_VERSION, VK_KHR_DRAW_INDIRECT_COUNT_SPEC_VERSION, VK_QCOM_extension_171_SPEC_VERSION, VK_QCOM_extension_172_SPEC_VERSION, VK_QCOM_extension_173_SPEC_VERSION, VK_QCOM_extension_174_SPEC_VERSION, VK_EXT_GLOBAL_PRIORITY_SPEC_VERSION, VK_KHR_EXTENSION_176_SPEC_VERSION, VK_KHR_EXTENSION_177_SPEC_VERSION, VK_KHR_8BIT_STORAGE_SPEC_VERSION, VK_EXT_EXTERNAL_MEMORY_HOST_SPEC_VERSION, VK_AMD_BUFFER_MARKER_SPEC_VERSION, VK_KHR_SHADER_ATOMIC_INT64_SPEC_VERSION, VK_KHR_EXTENSION_182_SPEC_VERSION, VK_KHR_EXTENSION_183_SPEC_VERSION, VK_KHR_EXTENSION_184_SPEC_VERSION, VK_EXT_CALIBRATED_TIMESTAMPS_SPEC_VERSION, VK_AMD_SHADER_CORE_PROPERTIES_SPEC_VERSION, VK_KHR_EXTENSION_187_SPEC_VERSION, VK_KHR_EXTENSION_188_SPEC_VERSION, VK_KHR_EXTENSION_189_SPEC_VERSION, VK_AMD_MEMORY_OVERALLOCATION_BEHAVIOR_SPEC_VERSION, VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_SPEC_VERSION, VK_GOOGLE_EXTENSION_192_SPEC_VERSION, VK_GOOGLE_EXTENSION_193_SPEC_VERSION, VK_GOOGLE_EXTENSION_194_SPEC_VERSION, VK_GOOGLE_EXTENSION_195_SPEC_VERSION, VK_GOOGLE_EXTENSION_196_SPEC_VERSION, VK_KHR_DRIVER_PROPERTIES_SPEC_VERSION, VK_KHR_SHADER_FLOAT_CONTROLS_SPEC_VERSION, VK_NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION, VK_KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION, VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_SPEC_VERSION, VK_NV_COMPUTE_SHADER_DERIVATIVES_SPEC_VERSION, VK_NV_MESH_SHADER_SPEC_VERSION, VK_NV_FRAGMENT_SHADER_BARYCENTRIC_SPEC_VERSION, VK_NV_SHADER_IMAGE_FOOTPRINT_SPEC_VERSION, VK_NV_SCISSOR_EXCLUSIVE_SPEC_VERSION, VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION, VK_KHR_EXTENSION_208_SPEC_VERSION, VK_KHR_EXTENSION_209_SPEC_VERSION, VK_KHR_EXTENSION_210_SPEC_VERSION, VK_KHR_EXTENSION_211_SPEC_VERSION, VK_KHR_VULKAN_MEMORY_MODEL_SPEC_VERSION, VK_EXT_PCI_BUS_INFO_SPEC_VERSION, VK_KHR_EXTENSION_214_SPEC_VERSION, VK_FUCHSIA_IMAGEPIPE_SURFACE_SPEC_VERSION, VK_KHR_EXTENSION_216_SPEC_VERSION, VK_KHR_EXTENSION_217_SPEC_VERSION, VK_EXT_MACOS_IOS_WINDOW_SPEC_VERSION, VK_EXT_FRAGMENT_DENSITY_MAP_SPEC_VERSION, VK_EXT_EXTENSION_220_SPEC_VERSION, VK_KHR_EXTENSION_221_SPEC_VERSION, VK_EXT_SCALAR_BLOCK_LAYOUT_SPEC_VERSION, VK_EXT_EXTENSION_223_SPEC_VERSION, VK_GOOGLE_HLSL_FUNCTIONALITY1_SPEC_VERSION, VK_GOOGLE_DECORATE_STRING_SPEC_VERSION, VK_AMD_EXTENSION_226_SPEC_VERSION, VK_AMD_EXTENSION_227_SPEC_VERSION, VK_AMD_EXTENSION_228_SPEC_VERSION, VK_AMD_EXTENSION_229_SPEC_VERSION, VK_AMD_EXTENSION_230_SPEC_VERSION, VK_AMD_EXTENSION_231_SPEC_VERSION, VK_AMD_EXTENSION_232_SPEC_VERSION, VK_AMD_EXTENSION_233_SPEC_VERSION, VK_AMD_EXTENSION_234_SPEC_VERSION, VK_AMD_EXTENSION_235_SPEC_VERSION, VK_AMD_EXTENSION_236_SPEC_VERSION, VK_KHR_EXTENSION_237_SPEC_VERSION, VK_EXT_MEMORY_BUDGET_SPEC_VERSION, VK_EXT_MEMORY_PRIORITY_SPEC_VERSION, VK_KHR_EXTENSION_240_SPEC_VERSION, VK_NV_EXTENSION_241_SPEC_VERSION, VK_NV_EXTENSION_242_SPEC_VERSION, VK_INTEL_EXTENSION_243_SPEC_VERSION, VK_MESA_EXTENSION_244_SPEC_VERSION, VK_EXT_BUFFER_DEVICE_ADDRESS_SPEC_VERSION, VK_EXT_EXTENSION_246_SPEC_VERSION, VK_EXT_SEPARATE_STENCIL_USAGE_SPEC_VERSION, VK_EXT_VALIDATION_FEATURES_SPEC_VERSION, VK_KHR_EXTENSION_249_SPEC_VERSION, VK_NV_EXTENSION_250_SPEC_VERSION, } /** ## API_Constants ## */ export enum API_Constants { VK_MAX_PHYSICAL_DEVICE_NAME_SIZE, VK_UUID_SIZE, VK_LUID_SIZE, VK_LUID_SIZE_KHR, VK_MAX_EXTENSION_NAME_SIZE, VK_MAX_DESCRIPTION_SIZE, VK_MAX_MEMORY_TYPES, VK_MAX_MEMORY_HEAPS, VK_LOD_CLAMP_NONE, VK_REMAINING_MIP_LEVELS, VK_REMAINING_ARRAY_LAYERS, VK_WHOLE_SIZE, VK_ATTACHMENT_UNUSED, VK_TRUE, VK_FALSE, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_EXTERNAL, VK_QUEUE_FAMILY_EXTERNAL_KHR, VK_QUEUE_FAMILY_FOREIGN_EXT, VK_SUBPASS_EXTERNAL, VK_MAX_DEVICE_GROUP_SIZE, VK_MAX_DEVICE_GROUP_SIZE_KHR, VK_MAX_DRIVER_NAME_SIZE_KHR, VK_MAX_DRIVER_INFO_SIZE_KHR, VK_SHADER_UNUSED_NV, VK_NULL_HANDLE, } /** ## VkImageLayout ## */ export enum VkImageLayout { VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PREINITIALIZED, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR, VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL_KHR, VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL_KHR, VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV, VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT, } /** ## VkAttachmentLoadOp ## */ export enum VkAttachmentLoadOp { VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_LOAD_OP_DONT_CARE, } /** ## VkAttachmentStoreOp ## */ export enum VkAttachmentStoreOp { VK_ATTACHMENT_STORE_OP_STORE, VK_ATTACHMENT_STORE_OP_DONT_CARE, } /** ## VkImageType ## */ export enum VkImageType { VK_IMAGE_TYPE_1D, VK_IMAGE_TYPE_2D, VK_IMAGE_TYPE_3D, } /** ## VkImageTiling ## */ export enum VkImageTiling { VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_TILING_LINEAR, VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT, } /** ## VkImageViewType ## */ export enum VkImageViewType { VK_IMAGE_VIEW_TYPE_1D, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_CUBE, VK_IMAGE_VIEW_TYPE_1D_ARRAY, VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_IMAGE_VIEW_TYPE_CUBE_ARRAY, } /** ## VkCommandBufferLevel ## */ export enum VkCommandBufferLevel { VK_COMMAND_BUFFER_LEVEL_PRIMARY, VK_COMMAND_BUFFER_LEVEL_SECONDARY, } /** ## VkComponentSwizzle ## */ export enum VkComponentSwizzle { VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_ZERO, VK_COMPONENT_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A, } /** ## VkDescriptorType ## */ export enum VkDescriptorType { VK_DESCRIPTOR_TYPE_SAMPLER, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT, VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV, } /** ## VkQueryType ## */ export enum VkQueryType { VK_QUERY_TYPE_OCCLUSION, VK_QUERY_TYPE_PIPELINE_STATISTICS, VK_QUERY_TYPE_TIMESTAMP, VK_QUERY_TYPE_RESERVED_8, VK_QUERY_TYPE_RESERVED_4, VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT, VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_NV, } /** ## VkBorderColor ## */ export enum VkBorderColor { VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK, VK_BORDER_COLOR_INT_TRANSPARENT_BLACK, VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK, VK_BORDER_COLOR_INT_OPAQUE_BLACK, VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, VK_BORDER_COLOR_INT_OPAQUE_WHITE, } /** ## VkPipelineBindPoint ## */ export enum VkPipelineBindPoint { VK_PIPELINE_BIND_POINT_GRAPHICS, VK_PIPELINE_BIND_POINT_COMPUTE, VK_PIPELINE_BIND_POINT_RAY_TRACING_NV, } /** ## VkPipelineCacheHeaderVersion ## */ export enum VkPipelineCacheHeaderVersion { VK_PIPELINE_CACHE_HEADER_VERSION_ONE, } /** ## VkPrimitiveTopology ## */ export enum VkPrimitiveTopology { VK_PRIMITIVE_TOPOLOGY_POINT_LIST, VK_PRIMITIVE_TOPOLOGY_LINE_LIST, VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY, VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY, VK_PRIMITIVE_TOPOLOGY_PATCH_LIST, } /** ## VkSharingMode ## */ export enum VkSharingMode { VK_SHARING_MODE_EXCLUSIVE, VK_SHARING_MODE_CONCURRENT, } /** ## VkIndexType ## */ export enum VkIndexType { VK_INDEX_TYPE_UINT16, VK_INDEX_TYPE_UINT32, VK_INDEX_TYPE_NONE_NV, } /** ## VkFilter ## */ export enum VkFilter { VK_FILTER_NEAREST, VK_FILTER_LINEAR, VK_FILTER_CUBIC_IMG, } /** ## VkSamplerMipmapMode ## */ export enum VkSamplerMipmapMode { VK_SAMPLER_MIPMAP_MODE_NEAREST, VK_SAMPLER_MIPMAP_MODE_LINEAR, } /** ## VkSamplerAddressMode ## */ export enum VkSamplerAddressMode { VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, } /** ## VkCompareOp ## */ export enum VkCompareOp { VK_COMPARE_OP_NEVER, VK_COMPARE_OP_LESS, VK_COMPARE_OP_EQUAL, VK_COMPARE_OP_LESS_OR_EQUAL, VK_COMPARE_OP_GREATER, VK_COMPARE_OP_NOT_EQUAL, VK_COMPARE_OP_GREATER_OR_EQUAL, VK_COMPARE_OP_ALWAYS, } /** ## VkPolygonMode ## */ export enum VkPolygonMode { VK_POLYGON_MODE_FILL, VK_POLYGON_MODE_LINE, VK_POLYGON_MODE_POINT, VK_POLYGON_MODE_FILL_RECTANGLE_NV, } /** ## VkFrontFace ## */ export enum VkFrontFace { VK_FRONT_FACE_COUNTER_CLOCKWISE, VK_FRONT_FACE_CLOCKWISE, } /** ## VkBlendFactor ## */ export enum VkBlendFactor { VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_SRC_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR, VK_BLEND_FACTOR_DST_COLOR, VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_FACTOR_DST_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA, VK_BLEND_FACTOR_CONSTANT_COLOR, VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR, VK_BLEND_FACTOR_CONSTANT_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA, VK_BLEND_FACTOR_SRC_ALPHA_SATURATE, VK_BLEND_FACTOR_SRC1_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_FACTOR_SRC1_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, } /** ## VkBlendOp ## */ export enum VkBlendOp { VK_BLEND_OP_ADD, VK_BLEND_OP_SUBTRACT, VK_BLEND_OP_REVERSE_SUBTRACT, VK_BLEND_OP_MIN, VK_BLEND_OP_MAX, VK_BLEND_OP_ZERO_EXT, VK_BLEND_OP_SRC_EXT, VK_BLEND_OP_DST_EXT, VK_BLEND_OP_SRC_OVER_EXT, VK_BLEND_OP_DST_OVER_EXT, VK_BLEND_OP_SRC_IN_EXT, VK_BLEND_OP_DST_IN_EXT, VK_BLEND_OP_SRC_OUT_EXT, VK_BLEND_OP_DST_OUT_EXT, VK_BLEND_OP_SRC_ATOP_EXT, VK_BLEND_OP_DST_ATOP_EXT, VK_BLEND_OP_XOR_EXT, VK_BLEND_OP_MULTIPLY_EXT, VK_BLEND_OP_SCREEN_EXT, VK_BLEND_OP_OVERLAY_EXT, VK_BLEND_OP_DARKEN_EXT, VK_BLEND_OP_LIGHTEN_EXT, VK_BLEND_OP_COLORDODGE_EXT, VK_BLEND_OP_COLORBURN_EXT, VK_BLEND_OP_HARDLIGHT_EXT, VK_BLEND_OP_SOFTLIGHT_EXT, VK_BLEND_OP_DIFFERENCE_EXT, VK_BLEND_OP_EXCLUSION_EXT, VK_BLEND_OP_INVERT_EXT, VK_BLEND_OP_INVERT_RGB_EXT, VK_BLEND_OP_LINEARDODGE_EXT, VK_BLEND_OP_LINEARBURN_EXT, VK_BLEND_OP_VIVIDLIGHT_EXT, VK_BLEND_OP_LINEARLIGHT_EXT, VK_BLEND_OP_PINLIGHT_EXT, VK_BLEND_OP_HARDMIX_EXT, VK_BLEND_OP_HSL_HUE_EXT, VK_BLEND_OP_HSL_SATURATION_EXT, VK_BLEND_OP_HSL_COLOR_EXT, VK_BLEND_OP_HSL_LUMINOSITY_EXT, VK_BLEND_OP_PLUS_EXT, VK_BLEND_OP_PLUS_CLAMPED_EXT, VK_BLEND_OP_PLUS_CLAMPED_ALPHA_EXT, VK_BLEND_OP_PLUS_DARKER_EXT, VK_BLEND_OP_MINUS_EXT, VK_BLEND_OP_MINUS_CLAMPED_EXT, VK_BLEND_OP_CONTRAST_EXT, VK_BLEND_OP_INVERT_OVG_EXT, VK_BLEND_OP_RED_EXT, VK_BLEND_OP_GREEN_EXT, VK_BLEND_OP_BLUE_EXT, } /** ## VkStencilOp ## */ export enum VkStencilOp { VK_STENCIL_OP_KEEP, VK_STENCIL_OP_ZERO, VK_STENCIL_OP_REPLACE, VK_STENCIL_OP_INCREMENT_AND_CLAMP, VK_STENCIL_OP_DECREMENT_AND_CLAMP, VK_STENCIL_OP_INVERT, VK_STENCIL_OP_INCREMENT_AND_WRAP, VK_STENCIL_OP_DECREMENT_AND_WRAP, } /** ## VkLogicOp ## */ export enum VkLogicOp { VK_LOGIC_OP_CLEAR, VK_LOGIC_OP_AND, VK_LOGIC_OP_AND_REVERSE, VK_LOGIC_OP_COPY, VK_LOGIC_OP_AND_INVERTED, VK_LOGIC_OP_NO_OP, VK_LOGIC_OP_XOR, VK_LOGIC_OP_OR, VK_LOGIC_OP_NOR, VK_LOGIC_OP_EQUIVALENT, VK_LOGIC_OP_INVERT, VK_LOGIC_OP_OR_REVERSE, VK_LOGIC_OP_COPY_INVERTED, VK_LOGIC_OP_OR_INVERTED, VK_LOGIC_OP_NAND, VK_LOGIC_OP_SET, } /** ## VkInternalAllocationType ## */ export enum VkInternalAllocationType { VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE, } /** ## VkSystemAllocationScope ## */ export enum VkSystemAllocationScope { VK_SYSTEM_ALLOCATION_SCOPE_COMMAND, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT, VK_SYSTEM_ALLOCATION_SCOPE_CACHE, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE, } /** ## VkPhysicalDeviceType ## */ export enum VkPhysicalDeviceType { VK_PHYSICAL_DEVICE_TYPE_OTHER, VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU, VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU, VK_PHYSICAL_DEVICE_TYPE_CPU, } /** ## VkVertexInputRate ## */ export enum VkVertexInputRate { VK_VERTEX_INPUT_RATE_VERTEX, VK_VERTEX_INPUT_RATE_INSTANCE, } /** ## VkFormat ## */ export enum VkFormat { VK_FORMAT_UNDEFINED, VK_FORMAT_R4G4_UNORM_PACK8, VK_FORMAT_R4G4B4A4_UNORM_PACK16, VK_FORMAT_B4G4R4A4_UNORM_PACK16, VK_FORMAT_R5G6B5_UNORM_PACK16, VK_FORMAT_B5G6R5_UNORM_PACK16, VK_FORMAT_R5G5B5A1_UNORM_PACK16, VK_FORMAT_B5G5R5A1_UNORM_PACK16, VK_FORMAT_A1R5G5B5_UNORM_PACK16, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_SNORM, VK_FORMAT_R8_USCALED, VK_FORMAT_R8_SSCALED, VK_FORMAT_R8_UINT, VK_FORMAT_R8_SINT, VK_FORMAT_R8_SRGB, VK_FORMAT_R8G8_UNORM, VK_FORMAT_R8G8_SNORM, VK_FORMAT_R8G8_USCALED, VK_FORMAT_R8G8_SSCALED, VK_FORMAT_R8G8_UINT, VK_FORMAT_R8G8_SINT, VK_FORMAT_R8G8_SRGB, VK_FORMAT_R8G8B8_UNORM, VK_FORMAT_R8G8B8_SNORM, VK_FORMAT_R8G8B8_USCALED, VK_FORMAT_R8G8B8_SSCALED, VK_FORMAT_R8G8B8_UINT, VK_FORMAT_R8G8B8_SINT, VK_FORMAT_R8G8B8_SRGB, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_B8G8R8_SNORM, VK_FORMAT_B8G8R8_USCALED, VK_FORMAT_B8G8R8_SSCALED, VK_FORMAT_B8G8R8_UINT, VK_FORMAT_B8G8R8_SINT, VK_FORMAT_B8G8R8_SRGB, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_SNORM, VK_FORMAT_R8G8B8A8_USCALED, VK_FORMAT_R8G8B8A8_SSCALED, VK_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_SINT, VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_SNORM, VK_FORMAT_B8G8R8A8_USCALED, VK_FORMAT_B8G8R8A8_SSCALED, VK_FORMAT_B8G8R8A8_UINT, VK_FORMAT_B8G8R8A8_SINT, VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_A8B8G8R8_UNORM_PACK32, VK_FORMAT_A8B8G8R8_SNORM_PACK32, VK_FORMAT_A8B8G8R8_USCALED_PACK32, VK_FORMAT_A8B8G8R8_SSCALED_PACK32, VK_FORMAT_A8B8G8R8_UINT_PACK32, VK_FORMAT_A8B8G8R8_SINT_PACK32, VK_FORMAT_A8B8G8R8_SRGB_PACK32, VK_FORMAT_A2R10G10B10_UNORM_PACK32, VK_FORMAT_A2R10G10B10_SNORM_PACK32, VK_FORMAT_A2R10G10B10_USCALED_PACK32, VK_FORMAT_A2R10G10B10_SSCALED_PACK32, VK_FORMAT_A2R10G10B10_UINT_PACK32, VK_FORMAT_A2R10G10B10_SINT_PACK32, VK_FORMAT_A2B10G10R10_UNORM_PACK32, VK_FORMAT_A2B10G10R10_SNORM_PACK32, VK_FORMAT_A2B10G10R10_USCALED_PACK32, VK_FORMAT_A2B10G10R10_SSCALED_PACK32, VK_FORMAT_A2B10G10R10_UINT_PACK32, VK_FORMAT_A2B10G10R10_SINT_PACK32, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_SNORM, VK_FORMAT_R16_USCALED, VK_FORMAT_R16_SSCALED, VK_FORMAT_R16_UINT, VK_FORMAT_R16_SINT, VK_FORMAT_R16_SFLOAT, VK_FORMAT_R16G16_UNORM, VK_FORMAT_R16G16_SNORM, VK_FORMAT_R16G16_USCALED, VK_FORMAT_R16G16_SSCALED, VK_FORMAT_R16G16_UINT, VK_FORMAT_R16G16_SINT, VK_FORMAT_R16G16_SFLOAT, VK_FORMAT_R16G16B16_UNORM, VK_FORMAT_R16G16B16_SNORM, VK_FORMAT_R16G16B16_USCALED, VK_FORMAT_R16G16B16_SSCALED, VK_FORMAT_R16G16B16_UINT, VK_FORMAT_R16G16B16_SINT, VK_FORMAT_R16G16B16_SFLOAT, VK_FORMAT_R16G16B16A16_UNORM, VK_FORMAT_R16G16B16A16_SNORM, VK_FORMAT_R16G16B16A16_USCALED, VK_FORMAT_R16G16B16A16_SSCALED, VK_FORMAT_R16G16B16A16_UINT, VK_FORMAT_R16G16B16A16_SINT, VK_FORMAT_R16G16B16A16_SFLOAT, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32G32_UINT, VK_FORMAT_R32G32_SINT, VK_FORMAT_R32G32_SFLOAT, VK_FORMAT_R32G32B32_UINT, VK_FORMAT_R32G32B32_SINT, VK_FORMAT_R32G32B32_SFLOAT, VK_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_SINT, VK_FORMAT_R32G32B32A32_SFLOAT, VK_FORMAT_R64_UINT, VK_FORMAT_R64_SINT, VK_FORMAT_R64_SFLOAT, VK_FORMAT_R64G64_UINT, VK_FORMAT_R64G64_SINT, VK_FORMAT_R64G64_SFLOAT, VK_FORMAT_R64G64B64_UINT, VK_FORMAT_R64G64B64_SINT, VK_FORMAT_R64G64B64_SFLOAT, VK_FORMAT_R64G64B64A64_UINT, VK_FORMAT_R64G64B64A64_SINT, VK_FORMAT_R64G64B64A64_SFLOAT, VK_FORMAT_B10G11R11_UFLOAT_PACK32, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, VK_FORMAT_D16_UNORM, VK_FORMAT_X8_D24_UNORM_PACK32, VK_FORMAT_D32_SFLOAT, VK_FORMAT_S8_UINT, VK_FORMAT_D16_UNORM_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_BC1_RGB_UNORM_BLOCK, VK_FORMAT_BC1_RGB_SRGB_BLOCK, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, VK_FORMAT_BC1_RGBA_SRGB_BLOCK, VK_FORMAT_BC2_UNORM_BLOCK, VK_FORMAT_BC2_SRGB_BLOCK, VK_FORMAT_BC3_UNORM_BLOCK, VK_FORMAT_BC3_SRGB_BLOCK, VK_FORMAT_BC4_UNORM_BLOCK, VK_FORMAT_BC4_SNORM_BLOCK, VK_FORMAT_BC5_UNORM_BLOCK, VK_FORMAT_BC5_SNORM_BLOCK, VK_FORMAT_BC6H_UFLOAT_BLOCK, VK_FORMAT_BC6H_SFLOAT_BLOCK, VK_FORMAT_BC7_UNORM_BLOCK, VK_FORMAT_BC7_SRGB_BLOCK, VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK, VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK, VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK, VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK, VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK, VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK, VK_FORMAT_EAC_R11_UNORM_BLOCK, VK_FORMAT_EAC_R11_SNORM_BLOCK, VK_FORMAT_EAC_R11G11_UNORM_BLOCK, VK_FORMAT_EAC_R11G11_SNORM_BLOCK, VK_FORMAT_ASTC_4x4_UNORM_BLOCK, VK_FORMAT_ASTC_4x4_SRGB_BLOCK, VK_FORMAT_ASTC_5x4_UNORM_BLOCK, VK_FORMAT_ASTC_5x4_SRGB_BLOCK, VK_FORMAT_ASTC_5x5_UNORM_BLOCK, VK_FORMAT_ASTC_5x5_SRGB_BLOCK, VK_FORMAT_ASTC_6x5_UNORM_BLOCK, VK_FORMAT_ASTC_6x5_SRGB_BLOCK, VK_FORMAT_ASTC_6x6_UNORM_BLOCK, VK_FORMAT_ASTC_6x6_SRGB_BLOCK, VK_FORMAT_ASTC_8x5_UNORM_BLOCK, VK_FORMAT_ASTC_8x5_SRGB_BLOCK, VK_FORMAT_ASTC_8x6_UNORM_BLOCK, VK_FORMAT_ASTC_8x6_SRGB_BLOCK, VK_FORMAT_ASTC_8x8_UNORM_BLOCK, VK_FORMAT_ASTC_8x8_SRGB_BLOCK, VK_FORMAT_ASTC_10x5_UNORM_BLOCK, VK_FORMAT_ASTC_10x5_SRGB_BLOCK, VK_FORMAT_ASTC_10x6_UNORM_BLOCK, VK_FORMAT_ASTC_10x6_SRGB_BLOCK, VK_FORMAT_ASTC_10x8_UNORM_BLOCK, VK_FORMAT_ASTC_10x8_SRGB_BLOCK, VK_FORMAT_ASTC_10x10_UNORM_BLOCK, VK_FORMAT_ASTC_10x10_SRGB_BLOCK, VK_FORMAT_ASTC_12x10_UNORM_BLOCK, VK_FORMAT_ASTC_12x10_SRGB_BLOCK, VK_FORMAT_ASTC_12x12_UNORM_BLOCK, VK_FORMAT_ASTC_12x12_SRGB_BLOCK, VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG, VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG, VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG, VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG, VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG, VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG, VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG, VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG, VK_FORMAT_G8B8G8R8_422_UNORM_KHR, VK_FORMAT_B8G8R8G8_422_UNORM_KHR, VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM_KHR, VK_FORMAT_G8_B8R8_2PLANE_420_UNORM_KHR, VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM_KHR, VK_FORMAT_G8_B8R8_2PLANE_422_UNORM_KHR, VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM_KHR, VK_FORMAT_R10X6_UNORM_PACK16_KHR, VK_FORMAT_R10X6G10X6_UNORM_2PACK16_KHR, VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16_KHR, VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16_KHR, VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16_KHR, VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16_KHR, VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16_KHR, VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16_KHR, VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16_KHR, VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16_KHR, VK_FORMAT_R12X4_UNORM_PACK16_KHR, VK_FORMAT_R12X4G12X4_UNORM_2PACK16_KHR, VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16_KHR, VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16_KHR, VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16_KHR, VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16_KHR, VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16_KHR, VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16_KHR, VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16_KHR, VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16_KHR, VK_FORMAT_G16B16G16R16_422_UNORM_KHR, VK_FORMAT_B16G16R16G16_422_UNORM_KHR, VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM_KHR, VK_FORMAT_G16_B16R16_2PLANE_420_UNORM_KHR, VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM_KHR, VK_FORMAT_G16_B16R16_2PLANE_422_UNORM_KHR, VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM_KHR, } /** ## VkStructureType ## */ export enum VkStructureType { VK_STRUCTURE_TYPE_APPLICATION_INFO, VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, VK_STRUCTURE_TYPE_SUBMIT_INFO, VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, VK_STRUCTURE_TYPE_EVENT_CREATE_INFO, VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO, VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO, VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET, VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, VK_STRUCTURE_TYPE_MEMORY_BARRIER, VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO, VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO, VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR, VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR, VK_STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR, VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR, VK_STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_DISPLAY_MODE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_DISPLAY_PRESENT_INFO_KHR, VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID, VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD, VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT, VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT, VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT, VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_IMAGE_CREATE_INFO_NV, VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_BUFFER_CREATE_INFO_NV, VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_MEMORY_ALLOCATE_INFO_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT, VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_STREAM_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CORNER_SAMPLED_IMAGE_FEATURES_NV, VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHR, VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_NV, VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_NV, VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV, VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_NV, VK_STRUCTURE_TYPE_WIN32_KEYED_MUTEX_ACQUIRE_RELEASE_INFO_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR, VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2_KHR, VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2_KHR, VK_STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2_KHR, VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SPARSE_IMAGE_FORMAT_INFO_2_KHR, VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR, VK_STRUCTURE_TYPE_DEVICE_GROUP_RENDER_PASS_BEGIN_INFO_KHR, VK_STRUCTURE_TYPE_DEVICE_GROUP_COMMAND_BUFFER_BEGIN_INFO_KHR, VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO_KHR, VK_STRUCTURE_TYPE_DEVICE_GROUP_BIND_SPARSE_INFO_KHR, VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_DEVICE_GROUP_INFO_KHR, VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_DEVICE_GROUP_INFO_KHR, VK_STRUCTURE_TYPE_VALIDATION_FLAGS_EXT, VK_STRUCTURE_TYPE_VI_SURFACE_CREATE_INFO_NN, VK_STRUCTURE_TYPE_IMAGE_VIEW_ASTC_DECODE_MODE_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ASTC_DECODE_FEATURES_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES_KHR, VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO_KHR, VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO_KHR, VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHR, VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR, VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR, VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_KHR, VK_STRUCTURE_TYPE_MEMORY_WIN32_HANDLE_PROPERTIES_KHR, VK_STRUCTURE_TYPE_MEMORY_GET_WIN32_HANDLE_INFO_KHR, VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR, VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR, VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR, VK_STRUCTURE_TYPE_WIN32_KEYED_MUTEX_ACQUIRE_RELEASE_INFO_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO_KHR, VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES_KHR, VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR, VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR, VK_STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR, VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR, VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR, VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR, VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_CONDITIONAL_RENDERING_INFO_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT, VK_STRUCTURE_TYPE_CONDITIONAL_RENDERING_BEGIN_INFO_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT16_INT8_FEATURES_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR, VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR, VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_OBJECT_TABLE_CREATE_INFO_NVX, VK_STRUCTURE_TYPE_INDIRECT_COMMANDS_LAYOUT_CREATE_INFO_NVX, VK_STRUCTURE_TYPE_CMD_PROCESS_COMMANDS_INFO_NVX, VK_STRUCTURE_TYPE_CMD_RESERVE_SPACE_FOR_COMMANDS_INFO_NVX, VK_STRUCTURE_TYPE_DEVICE_GENERATED_COMMANDS_LIMITS_NVX, VK_STRUCTURE_TYPE_DEVICE_GENERATED_COMMANDS_FEATURES_NVX, VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV, VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_EXT, VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES2_EXT, VK_STRUCTURE_TYPE_DISPLAY_POWER_INFO_EXT, VK_STRUCTURE_TYPE_DEVICE_EVENT_INFO_EXT, VK_STRUCTURE_TYPE_DISPLAY_EVENT_INFO_EXT, VK_STRUCTURE_TYPE_SWAPCHAIN_COUNTER_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PER_VIEW_ATTRIBUTES_PROPERTIES_NVX, VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_SWIZZLE_STATE_CREATE_INFO_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DISCARD_RECTANGLE_PROPERTIES_EXT, VK_STRUCTURE_TYPE_PIPELINE_DISCARD_RECTANGLE_STATE_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT, VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_CONSERVATIVE_STATE_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_HDR_METADATA_EXT, VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2_KHR, VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR, VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR, VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2_KHR, VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2_KHR, VK_STRUCTURE_TYPE_SUBPASS_BEGIN_INFO_KHR, VK_STRUCTURE_TYPE_SUBPASS_END_INFO_KHR, VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_FENCE_INFO_KHR, VK_STRUCTURE_TYPE_EXTERNAL_FENCE_PROPERTIES_KHR, VK_STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_IMPORT_FENCE_WIN32_HANDLE_INFO_KHR, VK_STRUCTURE_TYPE_EXPORT_FENCE_WIN32_HANDLE_INFO_KHR, VK_STRUCTURE_TYPE_FENCE_GET_WIN32_HANDLE_INFO_KHR, VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR, VK_STRUCTURE_TYPE_FENCE_GET_FD_INFO_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES_KHR, VK_STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR, VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR, VK_STRUCTURE_TYPE_SURFACE_FORMAT_2_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES_KHR, VK_STRUCTURE_TYPE_DISPLAY_PROPERTIES_2_KHR, VK_STRUCTURE_TYPE_DISPLAY_PLANE_PROPERTIES_2_KHR, VK_STRUCTURE_TYPE_DISPLAY_MODE_PROPERTIES_2_KHR, VK_STRUCTURE_TYPE_DISPLAY_PLANE_INFO_2_KHR, VK_STRUCTURE_TYPE_DISPLAY_PLANE_CAPABILITIES_2_KHR, VK_STRUCTURE_TYPE_IOS_SURFACE_CREATE_INFO_MVK, VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK, VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR, VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR, VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT, VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_TAG_INFO_EXT, VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT, VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_USAGE_ANDROID, VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID, VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, VK_STRUCTURE_TYPE_MEMORY_GET_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT, VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_FEATURES_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_PROPERTIES_EXT, VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_INLINE_UNIFORM_BLOCK_EXT, VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_INLINE_UNIFORM_BLOCK_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT, VK_STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT, VK_STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT, VK_STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT, VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR, VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR, VK_STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2_KHR, VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR, VK_STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2_KHR, VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_FEATURES_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_PROPERTIES_EXT, VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_ADVANCED_STATE_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_TO_COLOR_STATE_CREATE_INFO_NV, VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_MODULATION_STATE_CREATE_INFO_NV, VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO_KHR, VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO_KHR, VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO_KHR, VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES_KHR, VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_IMAGE_FORMAT_PROPERTIES_KHR, VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR, VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO_KHR, VK_STRUCTURE_TYPE_DRM_FORMAT_MODIFIER_PROPERTIES_LIST_EXT, VK_STRUCTURE_TYPE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_DRM_FORMAT_MODIFIER_INFO_EXT, VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_LIST_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT, VK_STRUCTURE_TYPE_VALIDATION_CACHE_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_PROPERTIES_EXT, VK_STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_ALLOCATE_INFO_EXT, VK_STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_LAYOUT_SUPPORT_EXT, VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_SHADING_RATE_IMAGE_STATE_CREATE_INFO_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_FEATURES_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_PROPERTIES_NV, VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_COARSE_SAMPLE_ORDER_STATE_CREATE_INFO_NV, VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV, VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV, VK_STRUCTURE_TYPE_GEOMETRY_NV, VK_STRUCTURE_TYPE_GEOMETRY_TRIANGLES_NV, VK_STRUCTURE_TYPE_GEOMETRY_AABB_NV, VK_STRUCTURE_TYPE_BIND_ACCELERATION_STRUCTURE_MEMORY_INFO_NV, VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_NV, VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_INFO_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PROPERTIES_NV, VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_NV, VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_REPRESENTATIVE_FRAGMENT_TEST_FEATURES_NV, VK_STRUCTURE_TYPE_PIPELINE_REPRESENTATIVE_FRAGMENT_TEST_STATE_CREATE_INFO_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES_KHR, VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT_KHR, VK_STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR, VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT, VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES_KHR, VK_STRUCTURE_TYPE_CALIBRATED_TIMESTAMP_INFO_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_PROPERTIES_AMD, VK_STRUCTURE_TYPE_DEVICE_MEMORY_OVERALLOCATION_CREATE_INFO_AMD, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT, VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR, VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_IMAGE_FOOTPRINT_FEATURES_NV, VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_EXCLUSIVE_SCISSOR_STATE_CREATE_INFO_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXCLUSIVE_SCISSOR_FEATURES_NV, VK_STRUCTURE_TYPE_CHECKPOINT_DATA_NV, VK_STRUCTURE_TYPE_QUEUE_FAMILY_CHECKPOINT_PROPERTIES_NV, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES_KHR, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT, VK_STRUCTURE_TYPE_IMAGEPIPE_SURFACE_CREATE_INFO_FUCHSIA, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_FEATURES_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_PROPERTIES_EXT, VK_STRUCTURE_TYPE_RENDER_PASS_FRAGMENT_DENSITY_MAP_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT, VK_STRUCTURE_TYPE_MEMORY_PRIORITY_ALLOCATE_INFO_EXT, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_ADDRESS_FEATURES_EXT, VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO_EXT, VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_IMAGE_STENCIL_USAGE_CREATE_INFO_EXT, VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT, } /** ## VkSubpassContents ## */ export enum VkSubpassContents { VK_SUBPASS_CONTENTS_INLINE, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS, } /** ## VkResult ## */ export enum VkResult { VK_SUCCESS, VK_NOT_READY, VK_TIMEOUT, VK_EVENT_SET, VK_EVENT_RESET, VK_INCOMPLETE, VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY, VK_ERROR_INITIALIZATION_FAILED, VK_ERROR_DEVICE_LOST, VK_ERROR_MEMORY_MAP_FAILED, VK_ERROR_LAYER_NOT_PRESENT, VK_ERROR_EXTENSION_NOT_PRESENT, VK_ERROR_FEATURE_NOT_PRESENT, VK_ERROR_INCOMPATIBLE_DRIVER, VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_FORMAT_NOT_SUPPORTED, VK_ERROR_FRAGMENTED_POOL, VK_ERROR_SURFACE_LOST_KHR, VK_ERROR_NATIVE_WINDOW_IN_USE_KHR, VK_SUBOPTIMAL_KHR, VK_ERROR_OUT_OF_DATE_KHR, VK_ERROR_INCOMPATIBLE_DISPLAY_KHR, VK_ERROR_VALIDATION_FAILED_EXT, VK_ERROR_INVALID_SHADER_NV, VK_ERROR_OUT_OF_POOL_MEMORY_KHR, VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR, VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT, VK_ERROR_FRAGMENTATION_EXT, VK_ERROR_NOT_PERMITTED_EXT, VK_ERROR_INVALID_DEVICE_ADDRESS_EXT, } /** ## VkDynamicState ## */ export enum VkDynamicState { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_LINE_WIDTH, VK_DYNAMIC_STATE_DEPTH_BIAS, VK_DYNAMIC_STATE_BLEND_CONSTANTS, VK_DYNAMIC_STATE_DEPTH_BOUNDS, VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK, VK_DYNAMIC_STATE_STENCIL_WRITE_MASK, VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_VIEWPORT_W_SCALING_NV, VK_DYNAMIC_STATE_DISCARD_RECTANGLE_EXT, VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT, VK_DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV, VK_DYNAMIC_STATE_VIEWPORT_COARSE_SAMPLE_ORDER_NV, VK_DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV, } /** ## VkDescriptorUpdateTemplateType ## */ export enum VkDescriptorUpdateTemplateType { VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET, VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET_KHR, } /** ## VkObjectType ## */ export enum VkObjectType { VK_OBJECT_TYPE_UNKNOWN, VK_OBJECT_TYPE_INSTANCE, VK_OBJECT_TYPE_PHYSICAL_DEVICE, VK_OBJECT_TYPE_DEVICE, VK_OBJECT_TYPE_QUEUE, VK_OBJECT_TYPE_SEMAPHORE, VK_OBJECT_TYPE_COMMAND_BUFFER, VK_OBJECT_TYPE_FENCE, VK_OBJECT_TYPE_DEVICE_MEMORY, VK_OBJECT_TYPE_BUFFER, VK_OBJECT_TYPE_IMAGE, VK_OBJECT_TYPE_EVENT, VK_OBJECT_TYPE_QUERY_POOL, VK_OBJECT_TYPE_BUFFER_VIEW, VK_OBJECT_TYPE_IMAGE_VIEW, VK_OBJECT_TYPE_SHADER_MODULE, VK_OBJECT_TYPE_PIPELINE_CACHE, VK_OBJECT_TYPE_PIPELINE_LAYOUT, VK_OBJECT_TYPE_RENDER_PASS, VK_OBJECT_TYPE_PIPELINE, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, VK_OBJECT_TYPE_SAMPLER, VK_OBJECT_TYPE_DESCRIPTOR_POOL, VK_OBJECT_TYPE_DESCRIPTOR_SET, VK_OBJECT_TYPE_FRAMEBUFFER, VK_OBJECT_TYPE_COMMAND_POOL, VK_OBJECT_TYPE_SURFACE_KHR, VK_OBJECT_TYPE_SWAPCHAIN_KHR, VK_OBJECT_TYPE_DISPLAY_KHR, VK_OBJECT_TYPE_DISPLAY_MODE_KHR, VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT, VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_KHR, VK_OBJECT_TYPE_OBJECT_TABLE_NVX, VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX, VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT, VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_KHR, VK_OBJECT_TYPE_VALIDATION_CACHE_EXT, VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NV, } /** ## VkPresentModeKHR ## */ export enum VkPresentModeKHR { VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR, VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR, VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR, } /** ## VkColorSpaceKHR ## */ export enum VkColorSpaceKHR { VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, VK_COLORSPACE_SRGB_NONLINEAR_KHR, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT, VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT, VK_COLOR_SPACE_DCI_P3_LINEAR_EXT, VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT, VK_COLOR_SPACE_BT709_LINEAR_EXT, VK_COLOR_SPACE_BT709_NONLINEAR_EXT, VK_COLOR_SPACE_BT2020_LINEAR_EXT, VK_COLOR_SPACE_HDR10_ST2084_EXT, VK_COLOR_SPACE_DOLBYVISION_EXT, VK_COLOR_SPACE_HDR10_HLG_EXT, VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT, VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT, VK_COLOR_SPACE_PASS_THROUGH_EXT, VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT, } /** ## VkTimeDomainEXT ## */ export enum VkTimeDomainEXT { VK_TIME_DOMAIN_DEVICE_EXT, VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT, VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT, VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_EXT, } /** ## VkDebugReportObjectTypeEXT ## */ export enum VkDebugReportObjectTypeEXT { VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_KHR_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_MODE_KHR_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_OBJECT_TABLE_NVX_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_KHR_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_KHR_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_ACCELERATION_STRUCTURE_NV_EXT, } /** ## VkRasterizationOrderAMD ## */ export enum VkRasterizationOrderAMD { VK_RASTERIZATION_ORDER_STRICT_AMD, VK_RASTERIZATION_ORDER_RELAXED_AMD, } /** ## VkValidationCheckEXT ## */ export enum VkValidationCheckEXT { VK_VALIDATION_CHECK_ALL_EXT, VK_VALIDATION_CHECK_SHADERS_EXT, } /** ## VkValidationFeatureEnableEXT ## */ export enum VkValidationFeatureEnableEXT { VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT, VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT, } /** ## VkValidationFeatureDisableEXT ## */ export enum VkValidationFeatureDisableEXT { VK_VALIDATION_FEATURE_DISABLE_ALL_EXT, VK_VALIDATION_FEATURE_DISABLE_SHADERS_EXT, VK_VALIDATION_FEATURE_DISABLE_THREAD_SAFETY_EXT, VK_VALIDATION_FEATURE_DISABLE_API_PARAMETERS_EXT, VK_VALIDATION_FEATURE_DISABLE_OBJECT_LIFETIMES_EXT, VK_VALIDATION_FEATURE_DISABLE_CORE_CHECKS_EXT, VK_VALIDATION_FEATURE_DISABLE_UNIQUE_HANDLES_EXT, } /** ## VkIndirectCommandsTokenTypeNVX ## */ export enum VkIndirectCommandsTokenTypeNVX { VK_INDIRECT_COMMANDS_TOKEN_TYPE_PIPELINE_NVX, VK_INDIRECT_COMMANDS_TOKEN_TYPE_DESCRIPTOR_SET_NVX, VK_INDIRECT_COMMANDS_TOKEN_TYPE_INDEX_BUFFER_NVX, VK_INDIRECT_COMMANDS_TOKEN_TYPE_VERTEX_BUFFER_NVX, VK_INDIRECT_COMMANDS_TOKEN_TYPE_PUSH_CONSTANT_NVX, VK_INDIRECT_COMMANDS_TOKEN_TYPE_DRAW_INDEXED_NVX, VK_INDIRECT_COMMANDS_TOKEN_TYPE_DRAW_NVX, VK_INDIRECT_COMMANDS_TOKEN_TYPE_DISPATCH_NVX, } /** ## VkObjectEntryTypeNVX ## */ export enum VkObjectEntryTypeNVX { VK_OBJECT_ENTRY_TYPE_DESCRIPTOR_SET_NVX, VK_OBJECT_ENTRY_TYPE_PIPELINE_NVX, VK_OBJECT_ENTRY_TYPE_INDEX_BUFFER_NVX, VK_OBJECT_ENTRY_TYPE_VERTEX_BUFFER_NVX, VK_OBJECT_ENTRY_TYPE_PUSH_CONSTANT_NVX, } /** ## VkDisplayPowerStateEXT ## */ export enum VkDisplayPowerStateEXT { VK_DISPLAY_POWER_STATE_OFF_EXT, VK_DISPLAY_POWER_STATE_SUSPEND_EXT, VK_DISPLAY_POWER_STATE_ON_EXT, } /** ## VkDeviceEventTypeEXT ## */ export enum VkDeviceEventTypeEXT { VK_DEVICE_EVENT_TYPE_DISPLAY_HOTPLUG_EXT, } /** ## VkDisplayEventTypeEXT ## */ export enum VkDisplayEventTypeEXT { VK_DISPLAY_EVENT_TYPE_FIRST_PIXEL_OUT_EXT, } /** ## VkViewportCoordinateSwizzleNV ## */ export enum VkViewportCoordinateSwizzleNV { VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_X_NV, VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_X_NV, VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_Y_NV, VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_Y_NV, VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_Z_NV, VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_Z_NV, VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_W_NV, VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_W_NV, } /** ## VkDiscardRectangleModeEXT ## */ export enum VkDiscardRectangleModeEXT { VK_DISCARD_RECTANGLE_MODE_INCLUSIVE_EXT, VK_DISCARD_RECTANGLE_MODE_EXCLUSIVE_EXT, } /** ## VkPointClippingBehavior ## */ export enum VkPointClippingBehavior { VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES, VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY, VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES_KHR, VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY_KHR, } /** ## VkSamplerReductionModeEXT ## */ export enum VkSamplerReductionModeEXT { VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT, VK_SAMPLER_REDUCTION_MODE_MIN_EXT, VK_SAMPLER_REDUCTION_MODE_MAX_EXT, } /** ## VkTessellationDomainOrigin ## */ export enum VkTessellationDomainOrigin { VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT, VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT, VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT_KHR, VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT_KHR, } /** ## VkSamplerYcbcrModelConversion ## */ export enum VkSamplerYcbcrModelConversion { VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY, VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY, VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709, VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601, VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020, VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY_KHR, VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY_KHR, VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709_KHR, VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601_KHR, VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020_KHR, } /** ## VkSamplerYcbcrRange ## */ export enum VkSamplerYcbcrRange { VK_SAMPLER_YCBCR_RANGE_ITU_FULL, VK_SAMPLER_YCBCR_RANGE_ITU_NARROW, VK_SAMPLER_YCBCR_RANGE_ITU_FULL_KHR, VK_SAMPLER_YCBCR_RANGE_ITU_NARROW_KHR, } /** ## VkChromaLocation ## */ export enum VkChromaLocation { VK_CHROMA_LOCATION_COSITED_EVEN, VK_CHROMA_LOCATION_MIDPOINT, VK_CHROMA_LOCATION_COSITED_EVEN_KHR, VK_CHROMA_LOCATION_MIDPOINT_KHR, } /** ## VkBlendOverlapEXT ## */ export enum VkBlendOverlapEXT { VK_BLEND_OVERLAP_UNCORRELATED_EXT, VK_BLEND_OVERLAP_DISJOINT_EXT, VK_BLEND_OVERLAP_CONJOINT_EXT, } /** ## VkCoverageModulationModeNV ## */ export enum VkCoverageModulationModeNV { VK_COVERAGE_MODULATION_MODE_NONE_NV, VK_COVERAGE_MODULATION_MODE_RGB_NV, VK_COVERAGE_MODULATION_MODE_ALPHA_NV, VK_COVERAGE_MODULATION_MODE_RGBA_NV, } /** ## VkValidationCacheHeaderVersionEXT ## */ export enum VkValidationCacheHeaderVersionEXT { VK_VALIDATION_CACHE_HEADER_VERSION_ONE_EXT, } /** ## VkShaderInfoTypeAMD ## */ export enum VkShaderInfoTypeAMD { VK_SHADER_INFO_TYPE_STATISTICS_AMD, VK_SHADER_INFO_TYPE_BINARY_AMD, VK_SHADER_INFO_TYPE_DISASSEMBLY_AMD, } /** ## VkQueueGlobalPriorityEXT ## */ export enum VkQueueGlobalPriorityEXT { VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT, VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT, VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT, VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT, } /** ## VkConservativeRasterizationModeEXT ## */ export enum VkConservativeRasterizationModeEXT { VK_CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT, VK_CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT, VK_CONSERVATIVE_RASTERIZATION_MODE_UNDERESTIMATE_EXT, } /** ## VkVendorId ## */ export enum VkVendorId { VK_VENDOR_ID_VIV, VK_VENDOR_ID_VSI, VK_VENDOR_ID_KAZAN, } /** ## VkDriverIdKHR ## */ export enum VkDriverIdKHR { VK_DRIVER_ID_AMD_PROPRIETARY_KHR, VK_DRIVER_ID_AMD_OPEN_SOURCE_KHR, VK_DRIVER_ID_MESA_RADV_KHR, VK_DRIVER_ID_NVIDIA_PROPRIETARY_KHR, VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS_KHR, VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA_KHR, VK_DRIVER_ID_IMAGINATION_PROPRIETARY_KHR, VK_DRIVER_ID_QUALCOMM_PROPRIETARY_KHR, VK_DRIVER_ID_ARM_PROPRIETARY_KHR, VK_DRIVER_ID_GOOGLE_PASTEL_KHR, } /** ## VkShadingRatePaletteEntryNV ## */ export enum VkShadingRatePaletteEntryNV { VK_SHADING_RATE_PALETTE_ENTRY_NO_INVOCATIONS_NV, VK_SHADING_RATE_PALETTE_ENTRY_16_INVOCATIONS_PER_PIXEL_NV, VK_SHADING_RATE_PALETTE_ENTRY_8_INVOCATIONS_PER_PIXEL_NV, VK_SHADING_RATE_PALETTE_ENTRY_4_INVOCATIONS_PER_PIXEL_NV, VK_SHADING_RATE_PALETTE_ENTRY_2_INVOCATIONS_PER_PIXEL_NV, VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_PIXEL_NV, VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X1_PIXELS_NV, VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV, VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X2_PIXELS_NV, VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X2_PIXELS_NV, VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X4_PIXELS_NV, VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X4_PIXELS_NV, } /** ## VkCoarseSampleOrderTypeNV ## */ export enum VkCoarseSampleOrderTypeNV { VK_COARSE_SAMPLE_ORDER_TYPE_DEFAULT_NV, VK_COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV, VK_COARSE_SAMPLE_ORDER_TYPE_PIXEL_MAJOR_NV, VK_COARSE_SAMPLE_ORDER_TYPE_SAMPLE_MAJOR_NV, } /** ## VkCopyAccelerationStructureModeNV ## */ export enum VkCopyAccelerationStructureModeNV { VK_COPY_ACCELERATION_STRUCTURE_MODE_CLONE_NV, VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_NV, } /** ## VkAccelerationStructureTypeNV ## */ export enum VkAccelerationStructureTypeNV { VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV, VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV, } /** ## VkGeometryTypeNV ## */ export enum VkGeometryTypeNV { VK_GEOMETRY_TYPE_TRIANGLES_NV, VK_GEOMETRY_TYPE_AABBS_NV, } /** ## VkAccelerationStructureMemoryRequirementsTypeNV ## */ export enum VkAccelerationStructureMemoryRequirementsTypeNV { VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_OBJECT_NV, VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_BUILD_SCRATCH_NV, VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_UPDATE_SCRATCH_NV, } /** ## VkRayTracingShaderGroupTypeNV ## */ export enum VkRayTracingShaderGroupTypeNV { VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV, VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV, VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV, } /** ## VkMemoryOverallocationBehaviorAMD ## */ export enum VkMemoryOverallocationBehaviorAMD { VK_MEMORY_OVERALLOCATION_BEHAVIOR_DEFAULT_AMD, VK_MEMORY_OVERALLOCATION_BEHAVIOR_ALLOWED_AMD, VK_MEMORY_OVERALLOCATION_BEHAVIOR_DISALLOWED_AMD, } /** ## VkCullModeFlagBits ## */ export enum VkCullModeFlagBits { VK_CULL_MODE_NONE, VK_CULL_MODE_FRONT_BIT, VK_CULL_MODE_BACK_BIT, VK_CULL_MODE_FRONT_AND_BACK, } /** ## VkQueueFlagBits ## */ export enum VkQueueFlagBits { VK_QUEUE_GRAPHICS_BIT, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_SPARSE_BINDING_BIT, VK_QUEUE_RESERVED_6_BIT_KHR, VK_QUEUE_RESERVED_5_BIT_KHR, } /** ## VkRenderPassCreateFlagBits ## */ export enum VkRenderPassCreateFlagBits { VK_RENDER_PASS_CREATE_RESERVED_0_BIT_KHR, } /** ## VkDeviceQueueCreateFlagBits ## */ export enum VkDeviceQueueCreateFlagBits { } /** ## VkMemoryPropertyFlagBits ## */ export enum VkMemoryPropertyFlagBits { VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT, VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT, } /** ## VkMemoryHeapFlagBits ## */ export enum VkMemoryHeapFlagBits { VK_MEMORY_HEAP_DEVICE_LOCAL_BIT, VK_MEMORY_HEAP_MULTI_INSTANCE_BIT_KHR, } /** ## VkAccessFlagBits ## */ export enum VkAccessFlagBits { VK_ACCESS_INDIRECT_COMMAND_READ_BIT, VK_ACCESS_INDEX_READ_BIT, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, VK_ACCESS_UNIFORM_READ_BIT, VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_RESERVED_30_BIT_KHR, VK_ACCESS_RESERVED_31_BIT_KHR, VK_ACCESS_RESERVED_28_BIT_KHR, VK_ACCESS_RESERVED_29_BIT_KHR, VK_ACCESS_TRANSFORM_FEEDBACK_WRITE_BIT_EXT, VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT, VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT, VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT, VK_ACCESS_COMMAND_PROCESS_READ_BIT_NVX, VK_ACCESS_COMMAND_PROCESS_WRITE_BIT_NVX, VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT, VK_ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV, VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV, VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV, VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT, } /** ## VkBufferUsageFlagBits ## */ export enum VkBufferUsageFlagBits { VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, VK_BUFFER_USAGE_RESERVED_15_BIT_KHR, VK_BUFFER_USAGE_RESERVED_16_BIT_KHR, VK_BUFFER_USAGE_RESERVED_13_BIT_KHR, VK_BUFFER_USAGE_RESERVED_14_BIT_KHR, VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT, VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT, VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT, VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT, } /** ## VkBufferCreateFlagBits ## */ export enum VkBufferCreateFlagBits { VK_BUFFER_CREATE_SPARSE_BINDING_BIT, VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT, VK_BUFFER_CREATE_SPARSE_ALIASED_BIT, VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT_EXT, } /** ## VkShaderStageFlagBits ## */ export enum VkShaderStageFlagBits { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, VK_SHADER_STAGE_GEOMETRY_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, VK_SHADER_STAGE_COMPUTE_BIT, VK_SHADER_STAGE_ALL_GRAPHICS, VK_SHADER_STAGE_ALL, VK_SHADER_STAGE_RAYGEN_BIT_NV, VK_SHADER_STAGE_ANY_HIT_BIT_NV, VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV, VK_SHADER_STAGE_MISS_BIT_NV, VK_SHADER_STAGE_INTERSECTION_BIT_NV, VK_SHADER_STAGE_CALLABLE_BIT_NV, VK_SHADER_STAGE_TASK_BIT_NV, VK_SHADER_STAGE_MESH_BIT_NV, } /** ## VkImageUsageFlagBits ## */ export enum VkImageUsageFlagBits { VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_USAGE_STORAGE_BIT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT, VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, VK_IMAGE_USAGE_RESERVED_13_BIT_KHR, VK_IMAGE_USAGE_RESERVED_14_BIT_KHR, VK_IMAGE_USAGE_RESERVED_15_BIT_KHR, VK_IMAGE_USAGE_RESERVED_10_BIT_KHR, VK_IMAGE_USAGE_RESERVED_11_BIT_KHR, VK_IMAGE_USAGE_RESERVED_12_BIT_KHR, VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV, VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT, } /** ## VkImageCreateFlagBits ## */ export enum VkImageCreateFlagBits { VK_IMAGE_CREATE_SPARSE_BINDING_BIT, VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT, VK_IMAGE_CREATE_SPARSE_ALIASED_BIT, VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT, VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV, VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR, VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR, VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT_KHR, VK_IMAGE_CREATE_EXTENDED_USAGE_BIT_KHR, VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT, VK_IMAGE_CREATE_DISJOINT_BIT_KHR, VK_IMAGE_CREATE_ALIAS_BIT_KHR, VK_IMAGE_CREATE_SUBSAMPLED_BIT_EXT, } /** ## VkImageViewCreateFlagBits ## */ export enum VkImageViewCreateFlagBits { VK_IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT, } /** ## VkSamplerCreateFlagBits ## */ export enum VkSamplerCreateFlagBits { VK_SAMPLER_CREATE_SUBSAMPLED_BIT_EXT, VK_SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT, } /** ## VkPipelineCreateFlagBits ## */ export enum VkPipelineCreateFlagBits { VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT, VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT, VK_PIPELINE_CREATE_DERIVATIVE_BIT, VK_PIPELINE_CREATE_VIEW_INDEX_FROM_DEVICE_INDEX_BIT_KHR, VK_PIPELINE_CREATE_DISPATCH_BASE_KHR, VK_PIPELINE_CREATE_DEFER_COMPILE_BIT_NV, } /** ## VkColorComponentFlagBits ## */ export enum VkColorComponentFlagBits { VK_COLOR_COMPONENT_R_BIT, VK_COLOR_COMPONENT_G_BIT, VK_COLOR_COMPONENT_B_BIT, VK_COLOR_COMPONENT_A_BIT, } /** ## VkFenceCreateFlagBits ## */ export enum VkFenceCreateFlagBits { VK_FENCE_CREATE_SIGNALED_BIT, } /** ## VkFormatFeatureFlagBits ## */ export enum VkFormatFeatureFlagBits { VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT, VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT, VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT, VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT, VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT, VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT, VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_FORMAT_FEATURE_BLIT_SRC_BIT, VK_FORMAT_FEATURE_BLIT_DST_BIT, VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT, VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG, VK_FORMAT_FEATURE_RESERVED_27_BIT_KHR, VK_FORMAT_FEATURE_RESERVED_28_BIT_KHR, VK_FORMAT_FEATURE_RESERVED_25_BIT_KHR, VK_FORMAT_FEATURE_RESERVED_26_BIT_KHR, VK_FORMAT_FEATURE_TRANSFER_SRC_BIT_KHR, VK_FORMAT_FEATURE_TRANSFER_DST_BIT_KHR, VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT_EXT, VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT_KHR, VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT_KHR, VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT_KHR, VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT_KHR, VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT_KHR, VK_FORMAT_FEATURE_DISJOINT_BIT_KHR, VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT_KHR, VK_FORMAT_FEATURE_FRAGMENT_DENSITY_MAP_BIT_EXT, } /** ## VkQueryControlFlagBits ## */ export enum VkQueryControlFlagBits { VK_QUERY_CONTROL_PRECISE_BIT, } /** ## VkQueryResultFlagBits ## */ export enum VkQueryResultFlagBits { VK_QUERY_RESULT_64_BIT, VK_QUERY_RESULT_WAIT_BIT, VK_QUERY_RESULT_WITH_AVAILABILITY_BIT, VK_QUERY_RESULT_PARTIAL_BIT, } /** ## VkCommandBufferUsageFlagBits ## */ export enum VkCommandBufferUsageFlagBits { VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT, } /** ## VkQueryPipelineStatisticFlagBits ## */ export enum VkQueryPipelineStatisticFlagBits { VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT, VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT, VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT, VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT, VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT, VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT, VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT, VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT, VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT, VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT, VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT, } /** ## VkImageAspectFlagBits ## */ export enum VkImageAspectFlagBits { VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT, VK_IMAGE_ASPECT_METADATA_BIT, VK_IMAGE_ASPECT_PLANE_0_BIT_KHR, VK_IMAGE_ASPECT_PLANE_1_BIT_KHR, VK_IMAGE_ASPECT_PLANE_2_BIT_KHR, VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT, VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT, VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT, VK_IMAGE_ASPECT_MEMORY_PLANE_3_BIT_EXT, } /** ## VkSparseImageFormatFlagBits ## */ export enum VkSparseImageFormatFlagBits { VK_SPARSE_IMAGE_FORMAT_SINGLE_MIPTAIL_BIT, VK_SPARSE_IMAGE_FORMAT_ALIGNED_MIP_SIZE_BIT, VK_SPARSE_IMAGE_FORMAT_NONSTANDARD_BLOCK_SIZE_BIT, } /** ## VkSparseMemoryBindFlagBits ## */ export enum VkSparseMemoryBindFlagBits { VK_SPARSE_MEMORY_BIND_METADATA_BIT, } /** ## VkPipelineStageFlagBits ## */ export enum VkPipelineStageFlagBits { VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_RESERVED_27_BIT_KHR, VK_PIPELINE_STAGE_RESERVED_26_BIT_KHR, VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT, VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT, VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX, VK_PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV, VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV, VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV, VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT, } /** ## VkCommandPoolCreateFlagBits ## */ export enum VkCommandPoolCreateFlagBits { VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, } /** ## VkCommandPoolResetFlagBits ## */ export enum VkCommandPoolResetFlagBits { VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT, } /** ## VkCommandBufferResetFlagBits ## */ export enum VkCommandBufferResetFlagBits { VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT, } /** ## VkSampleCountFlagBits ## */ export enum VkSampleCountFlagBits { VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_2_BIT, VK_SAMPLE_COUNT_4_BIT, VK_SAMPLE_COUNT_8_BIT, VK_SAMPLE_COUNT_16_BIT, VK_SAMPLE_COUNT_32_BIT, VK_SAMPLE_COUNT_64_BIT, } /** ## VkAttachmentDescriptionFlagBits ## */ export enum VkAttachmentDescriptionFlagBits { VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT, } /** ## VkStencilFaceFlagBits ## */ export enum VkStencilFaceFlagBits { VK_STENCIL_FACE_FRONT_BIT, VK_STENCIL_FACE_BACK_BIT, VK_STENCIL_FRONT_AND_BACK, } /** ## VkDescriptorPoolCreateFlagBits ## */ export enum VkDescriptorPoolCreateFlagBits { VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT, } /** ## VkDependencyFlagBits ## */ export enum VkDependencyFlagBits { VK_DEPENDENCY_BY_REGION_BIT, VK_DEPENDENCY_VIEW_LOCAL_BIT_KHR, VK_DEPENDENCY_DEVICE_GROUP_BIT_KHR, } /** ## VkDisplayPlaneAlphaFlagBitsKHR ## */ export enum VkDisplayPlaneAlphaFlagBitsKHR { VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR, VK_DISPLAY_PLANE_ALPHA_GLOBAL_BIT_KHR, VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR, VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR, } /** ## VkCompositeAlphaFlagBitsKHR ## */ export enum VkCompositeAlphaFlagBitsKHR { VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR, VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR, } /** ## VkSurfaceTransformFlagBitsKHR ## */ export enum VkSurfaceTransformFlagBitsKHR { VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR, VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR, VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR, VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR, VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR, VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR, VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR, VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR, } /** ## VkDebugReportFlagBitsEXT ## */ export enum VkDebugReportFlagBitsEXT { VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_DEBUG_BIT_EXT, } /** ## VkExternalMemoryHandleTypeFlagBitsNV ## */ export enum VkExternalMemoryHandleTypeFlagBitsNV { VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_NV, VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_NV, VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_IMAGE_BIT_NV, VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_IMAGE_KMT_BIT_NV, } /** ## VkExternalMemoryFeatureFlagBitsNV ## */ export enum VkExternalMemoryFeatureFlagBitsNV { VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT_NV, VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT_NV, VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT_NV, } /** ## VkSubgroupFeatureFlagBits ## */ export enum VkSubgroupFeatureFlagBits { VK_SUBGROUP_FEATURE_BASIC_BIT, VK_SUBGROUP_FEATURE_VOTE_BIT, VK_SUBGROUP_FEATURE_ARITHMETIC_BIT, VK_SUBGROUP_FEATURE_BALLOT_BIT, VK_SUBGROUP_FEATURE_SHUFFLE_BIT, VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT, VK_SUBGROUP_FEATURE_CLUSTERED_BIT, VK_SUBGROUP_FEATURE_QUAD_BIT, VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV, } /** ## VkIndirectCommandsLayoutUsageFlagBitsNVX ## */ export enum VkIndirectCommandsLayoutUsageFlagBitsNVX { VK_INDIRECT_COMMANDS_LAYOUT_USAGE_UNORDERED_SEQUENCES_BIT_NVX, VK_INDIRECT_COMMANDS_LAYOUT_USAGE_SPARSE_SEQUENCES_BIT_NVX, VK_INDIRECT_COMMANDS_LAYOUT_USAGE_EMPTY_EXECUTIONS_BIT_NVX, VK_INDIRECT_COMMANDS_LAYOUT_USAGE_INDEXED_SEQUENCES_BIT_NVX, } /** ## VkObjectEntryUsageFlagBitsNVX ## */ export enum VkObjectEntryUsageFlagBitsNVX { VK_OBJECT_ENTRY_USAGE_GRAPHICS_BIT_NVX, VK_OBJECT_ENTRY_USAGE_COMPUTE_BIT_NVX, } /** ## VkDescriptorSetLayoutCreateFlagBits ## */ export enum VkDescriptorSetLayoutCreateFlagBits { VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR, VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT, } /** ## VkExternalMemoryHandleTypeFlagBits ## */ export enum VkExternalMemoryHandleTypeFlagBits { VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT, VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT, VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT, VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT, VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT, VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT, VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT, VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR, VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR, VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_KHR, VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT_KHR, VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT_KHR, VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT_KHR, VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT_KHR, VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT, } /** ## VkExternalMemoryFeatureFlagBits ## */ export enum VkExternalMemoryFeatureFlagBits { VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT, VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT, VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT, VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT_KHR, VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT_KHR, VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT_KHR, } /** ## VkExternalSemaphoreHandleTypeFlagBits ## */ export enum VkExternalSemaphoreHandleTypeFlagBits { VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT, VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT, VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT, VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT, VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT, VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR, VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR, VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_KHR, VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT_KHR, VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT_KHR, } /** ## VkExternalSemaphoreFeatureFlagBits ## */ export enum VkExternalSemaphoreFeatureFlagBits { VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT, VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT, VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT_KHR, VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT_KHR, } /** ## VkSemaphoreImportFlagBits ## */ export enum VkSemaphoreImportFlagBits { VK_SEMAPHORE_IMPORT_TEMPORARY_BIT, VK_SEMAPHORE_IMPORT_TEMPORARY_BIT_KHR, } /** ## VkExternalFenceHandleTypeFlagBits ## */ export enum VkExternalFenceHandleTypeFlagBits { VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT, VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT, VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT, VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT, VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR, VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR, VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_KHR, VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT_KHR, } /** ## VkExternalFenceFeatureFlagBits ## */ export enum VkExternalFenceFeatureFlagBits { VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT, VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT, VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT_KHR, VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT_KHR, } /** ## VkFenceImportFlagBits ## */ export enum VkFenceImportFlagBits { VK_FENCE_IMPORT_TEMPORARY_BIT, VK_FENCE_IMPORT_TEMPORARY_BIT_KHR, } /** ## VkSurfaceCounterFlagBitsEXT ## */ export enum VkSurfaceCounterFlagBitsEXT { VK_SURFACE_COUNTER_VBLANK_EXT, } /** ## VkPeerMemoryFeatureFlagBits ## */ export enum VkPeerMemoryFeatureFlagBits { VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT, VK_PEER_MEMORY_FEATURE_COPY_DST_BIT, VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT, VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT, VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT_KHR, VK_PEER_MEMORY_FEATURE_COPY_DST_BIT_KHR, VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT_KHR, VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT_KHR, } /** ## VkMemoryAllocateFlagBits ## */ export enum VkMemoryAllocateFlagBits { VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT, VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT_KHR, } /** ## VkDeviceGroupPresentModeFlagBitsKHR ## */ export enum VkDeviceGroupPresentModeFlagBitsKHR { VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR, VK_DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR, VK_DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR, VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR, } /** ## VkSwapchainCreateFlagBitsKHR ## */ export enum VkSwapchainCreateFlagBitsKHR { VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR, VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR, VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR, } /** ## VkSubpassDescriptionFlagBits ## */ export enum VkSubpassDescriptionFlagBits { VK_SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX, VK_SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX, } /** ## VkDebugUtilsMessageSeverityFlagBitsEXT ## */ export enum VkDebugUtilsMessageSeverityFlagBitsEXT { VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT, VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT, VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT, VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT, } /** ## VkDebugUtilsMessageTypeFlagBitsEXT ## */ export enum VkDebugUtilsMessageTypeFlagBitsEXT { VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT, VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT, VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, } /** ## VkDescriptorBindingFlagBitsEXT ## */ export enum VkDescriptorBindingFlagBitsEXT { VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT, VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT, VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT_EXT, VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT, } /** ## VkConditionalRenderingFlagBitsEXT ## */ export enum VkConditionalRenderingFlagBitsEXT { VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT, } /** ## VkResolveModeFlagBitsKHR ## */ export enum VkResolveModeFlagBitsKHR { VK_RESOLVE_MODE_NONE_KHR, VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR, VK_RESOLVE_MODE_AVERAGE_BIT_KHR, VK_RESOLVE_MODE_MIN_BIT_KHR, VK_RESOLVE_MODE_MAX_BIT_KHR, } /** ## VkGeometryInstanceFlagBitsNV ## */ export enum VkGeometryInstanceFlagBitsNV { VK_GEOMETRY_INSTANCE_TRIANGLE_CULL_DISABLE_BIT_NV, VK_GEOMETRY_INSTANCE_TRIANGLE_FRONT_COUNTERCLOCKWISE_BIT_NV, VK_GEOMETRY_INSTANCE_FORCE_OPAQUE_BIT_NV, VK_GEOMETRY_INSTANCE_FORCE_NO_OPAQUE_BIT_NV, } /** ## VkGeometryFlagBitsNV ## */ export enum VkGeometryFlagBitsNV { VK_GEOMETRY_OPAQUE_BIT_NV, VK_GEOMETRY_NO_DUPLICATE_ANY_HIT_INVOCATION_BIT_NV, } /** ## VkBuildAccelerationStructureFlagBitsNV ## */ export enum VkBuildAccelerationStructureFlagBitsNV { VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_NV, VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_NV, VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_NV, VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_NV, VK_BUILD_ACCELERATION_STRUCTURE_LOW_MEMORY_BIT_NV, } /** #### HANDLES #### **/ /** ## VkDebugUtilsMessengerEXT ## */ interface VkDebugUtilsMessengerEXT {} declare var VkDebugUtilsMessengerEXT: { prototype: VkDebugUtilsMessengerEXT; new(): VkDebugUtilsMessengerEXT; } export interface VkDebugUtilsMessengerEXT {} /** ## VkDebugReportCallbackEXT ## */ interface VkDebugReportCallbackEXT {} declare var VkDebugReportCallbackEXT: { prototype: VkDebugReportCallbackEXT; new(): VkDebugReportCallbackEXT; } export interface VkDebugReportCallbackEXT {} /** ## VkSwapchainKHR ## */ interface VkSwapchainKHR {} declare var VkSwapchainKHR: { prototype: VkSwapchainKHR; new(): VkSwapchainKHR; } export interface VkSwapchainKHR {} /** ## VkSurfaceKHR ## */ interface VkSurfaceKHR {} declare var VkSurfaceKHR: { prototype: VkSurfaceKHR; new(): VkSurfaceKHR; } export interface VkSurfaceKHR {} /** ## VkDisplayModeKHR ## */ interface VkDisplayModeKHR {} declare var VkDisplayModeKHR: { prototype: VkDisplayModeKHR; new(): VkDisplayModeKHR; } export interface VkDisplayModeKHR {} /** ## VkDisplayKHR ## */ interface VkDisplayKHR {} declare var VkDisplayKHR: { prototype: VkDisplayKHR; new(): VkDisplayKHR; } export interface VkDisplayKHR {} /** ## VkAccelerationStructureNV ## */ interface VkAccelerationStructureNV {} declare var VkAccelerationStructureNV: { prototype: VkAccelerationStructureNV; new(): VkAccelerationStructureNV; } export interface VkAccelerationStructureNV {} /** ## VkValidationCacheEXT ## */ interface VkValidationCacheEXT {} declare var VkValidationCacheEXT: { prototype: VkValidationCacheEXT; new(): VkValidationCacheEXT; } export interface VkValidationCacheEXT {} /** ## VkSamplerYcbcrConversion ## */ interface VkSamplerYcbcrConversion {} declare var VkSamplerYcbcrConversion: { prototype: VkSamplerYcbcrConversion; new(): VkSamplerYcbcrConversion; } export interface VkSamplerYcbcrConversion {} /** ## VkDescriptorUpdateTemplate ## */ interface VkDescriptorUpdateTemplate {} declare var VkDescriptorUpdateTemplate: { prototype: VkDescriptorUpdateTemplate; new(): VkDescriptorUpdateTemplate; } export interface VkDescriptorUpdateTemplate {} /** ## VkIndirectCommandsLayoutNVX ## */ interface VkIndirectCommandsLayoutNVX {} declare var VkIndirectCommandsLayoutNVX: { prototype: VkIndirectCommandsLayoutNVX; new(): VkIndirectCommandsLayoutNVX; } export interface VkIndirectCommandsLayoutNVX {} /** ## VkObjectTableNVX ## */ interface VkObjectTableNVX {} declare var VkObjectTableNVX: { prototype: VkObjectTableNVX; new(): VkObjectTableNVX; } export interface VkObjectTableNVX {} /** ## VkPipelineCache ## */ interface VkPipelineCache {} declare var VkPipelineCache: { prototype: VkPipelineCache; new(): VkPipelineCache; } export interface VkPipelineCache {} /** ## VkRenderPass ## */ interface VkRenderPass {} declare var VkRenderPass: { prototype: VkRenderPass; new(): VkRenderPass; } export interface VkRenderPass {} /** ## VkFramebuffer ## */ interface VkFramebuffer {} declare var VkFramebuffer: { prototype: VkFramebuffer; new(): VkFramebuffer; } export interface VkFramebuffer {} /** ## VkQueryPool ## */ interface VkQueryPool {} declare var VkQueryPool: { prototype: VkQueryPool; new(): VkQueryPool; } export interface VkQueryPool {} /** ## VkEvent ## */ interface VkEvent {} declare var VkEvent: { prototype: VkEvent; new(): VkEvent; } export interface VkEvent {} /** ## VkSemaphore ## */ interface VkSemaphore {} declare var VkSemaphore: { prototype: VkSemaphore; new(): VkSemaphore; } export interface VkSemaphore {} /** ## VkFence ## */ interface VkFence {} declare var VkFence: { prototype: VkFence; new(): VkFence; } export interface VkFence {} /** ## VkDescriptorPool ## */ interface VkDescriptorPool {} declare var VkDescriptorPool: { prototype: VkDescriptorPool; new(): VkDescriptorPool; } export interface VkDescriptorPool {} /** ## VkDescriptorSetLayout ## */ interface VkDescriptorSetLayout {} declare var VkDescriptorSetLayout: { prototype: VkDescriptorSetLayout; new(): VkDescriptorSetLayout; } export interface VkDescriptorSetLayout {} /** ## VkDescriptorSet ## */ interface VkDescriptorSet {} declare var VkDescriptorSet: { prototype: VkDescriptorSet; new(): VkDescriptorSet; } export interface VkDescriptorSet {} /** ## VkSampler ## */ interface VkSampler {} declare var VkSampler: { prototype: VkSampler; new(): VkSampler; } export interface VkSampler {} /** ## VkPipelineLayout ## */ interface VkPipelineLayout {} declare var VkPipelineLayout: { prototype: VkPipelineLayout; new(): VkPipelineLayout; } export interface VkPipelineLayout {} /** ## VkPipeline ## */ interface VkPipeline {} declare var VkPipeline: { prototype: VkPipeline; new(): VkPipeline; } export interface VkPipeline {} /** ## VkShaderModule ## */ interface VkShaderModule {} declare var VkShaderModule: { prototype: VkShaderModule; new(): VkShaderModule; } export interface VkShaderModule {} /** ## VkImageView ## */ interface VkImageView {} declare var VkImageView: { prototype: VkImageView; new(): VkImageView; } export interface VkImageView {} /** ## VkImage ## */ interface VkImage {} declare var VkImage: { prototype: VkImage; new(): VkImage; } export interface VkImage {} /** ## VkBufferView ## */ interface VkBufferView {} declare var VkBufferView: { prototype: VkBufferView; new(): VkBufferView; } export interface VkBufferView {} /** ## VkBuffer ## */ interface VkBuffer {} declare var VkBuffer: { prototype: VkBuffer; new(): VkBuffer; } export interface VkBuffer {} /** ## VkCommandPool ## */ interface VkCommandPool {} declare var VkCommandPool: { prototype: VkCommandPool; new(): VkCommandPool; } export interface VkCommandPool {} /** ## VkDeviceMemory ## */ interface VkDeviceMemory {} declare var VkDeviceMemory: { prototype: VkDeviceMemory; new(): VkDeviceMemory; } export interface VkDeviceMemory {} /** ## VkCommandBuffer ## */ interface VkCommandBuffer {} declare var VkCommandBuffer: { prototype: VkCommandBuffer; new(): VkCommandBuffer; } export interface VkCommandBuffer {} /** ## VkQueue ## */ interface VkQueue {} declare var VkQueue: { prototype: VkQueue; new(): VkQueue; } export interface VkQueue {} /** ## VkDevice ## */ interface VkDevice {} declare var VkDevice: { prototype: VkDevice; new(): VkDevice; } export interface VkDevice {} /** ## VkPhysicalDevice ## */ interface VkPhysicalDevice {} declare var VkPhysicalDevice: { prototype: VkPhysicalDevice; new(): VkPhysicalDevice; } export interface VkPhysicalDevice {} /** ## VkInstance ## */ interface VkInstance {} declare var VkInstance: { prototype: VkInstance; new(): VkInstance; } export interface VkInstance {} /** #### STRUCTS #### **/ /** ## VkClearValue ## */ interface VkClearValueInitializer { color?: VkClearColorValue | null; depthStencil?: VkClearDepthStencilValue | null; } declare var VkClearValue: { prototype: VkClearValue; new(param?: VkClearValueInitializer | null): VkClearValue; color: VkClearColorValue | null; depthStencil: VkClearDepthStencilValue | null; } export interface VkClearValue { color: VkClearColorValue | null; depthStencil: VkClearDepthStencilValue | null; } /** ## VkClearColorValue ## */ interface VkClearColorValueInitializer { float32?: number[] | null; int32?: number[] | null; uint32?: number[] | null; } declare var VkClearColorValue: { prototype: VkClearColorValue; new(param?: VkClearColorValueInitializer | null): VkClearColorValue; float32: number[] | null; int32: number[] | null; uint32: number[] | null; } export interface VkClearColorValue { float32: number[] | null; int32: number[] | null; uint32: number[] | null; } /** ## VkBufferDeviceAddressCreateInfoEXT ## */ interface VkBufferDeviceAddressCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; deviceAddress?: number; } declare var VkBufferDeviceAddressCreateInfoEXT: { prototype: VkBufferDeviceAddressCreateInfoEXT; new(param?: VkBufferDeviceAddressCreateInfoEXTInitializer | null): VkBufferDeviceAddressCreateInfoEXT; sType: VkStructureType; pNext: null; deviceAddress: number; } export interface VkBufferDeviceAddressCreateInfoEXT { sType: VkStructureType; pNext: null; deviceAddress: number; } /** ## VkBufferDeviceAddressInfoEXT ## */ interface VkBufferDeviceAddressInfoEXTInitializer { sType?: VkStructureType; pNext?: null; buffer?: VkBuffer | null; } declare var VkBufferDeviceAddressInfoEXT: { prototype: VkBufferDeviceAddressInfoEXT; new(param?: VkBufferDeviceAddressInfoEXTInitializer | null): VkBufferDeviceAddressInfoEXT; sType: VkStructureType; pNext: null; buffer: VkBuffer | null; } export interface VkBufferDeviceAddressInfoEXT { sType: VkStructureType; pNext: null; buffer: VkBuffer | null; } /** ## VkPhysicalDeviceBufferAddressFeaturesEXT ## */ interface VkPhysicalDeviceBufferAddressFeaturesEXTInitializer { sType?: VkStructureType; pNext?: null; bufferDeviceAddress?: number; bufferDeviceAddressCaptureReplay?: number; bufferDeviceAddressMultiDevice?: number; } declare var VkPhysicalDeviceBufferAddressFeaturesEXT: { prototype: VkPhysicalDeviceBufferAddressFeaturesEXT; new(param?: VkPhysicalDeviceBufferAddressFeaturesEXTInitializer | null): VkPhysicalDeviceBufferAddressFeaturesEXT; sType: VkStructureType; pNext: null; bufferDeviceAddress: number; bufferDeviceAddressCaptureReplay: number; bufferDeviceAddressMultiDevice: number; } export interface VkPhysicalDeviceBufferAddressFeaturesEXT { sType: VkStructureType; pNext: null; bufferDeviceAddress: number; bufferDeviceAddressCaptureReplay: number; bufferDeviceAddressMultiDevice: number; } /** ## VkMemoryPriorityAllocateInfoEXT ## */ interface VkMemoryPriorityAllocateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; priority?: number; } declare var VkMemoryPriorityAllocateInfoEXT: { prototype: VkMemoryPriorityAllocateInfoEXT; new(param?: VkMemoryPriorityAllocateInfoEXTInitializer | null): VkMemoryPriorityAllocateInfoEXT; sType: VkStructureType; pNext: null; priority: number; } export interface VkMemoryPriorityAllocateInfoEXT { sType: VkStructureType; pNext: null; priority: number; } /** ## VkPhysicalDeviceMemoryPriorityFeaturesEXT ## */ interface VkPhysicalDeviceMemoryPriorityFeaturesEXTInitializer { sType?: VkStructureType; pNext?: null; memoryPriority?: number; } declare var VkPhysicalDeviceMemoryPriorityFeaturesEXT: { prototype: VkPhysicalDeviceMemoryPriorityFeaturesEXT; new(param?: VkPhysicalDeviceMemoryPriorityFeaturesEXTInitializer | null): VkPhysicalDeviceMemoryPriorityFeaturesEXT; sType: VkStructureType; pNext: null; memoryPriority: number; } export interface VkPhysicalDeviceMemoryPriorityFeaturesEXT { sType: VkStructureType; pNext: null; memoryPriority: number; } /** ## VkPhysicalDeviceMemoryBudgetPropertiesEXT ## */ interface VkPhysicalDeviceMemoryBudgetPropertiesEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly heapBudget?: number[] | null; readonly heapUsage?: number[] | null; } declare var VkPhysicalDeviceMemoryBudgetPropertiesEXT: { prototype: VkPhysicalDeviceMemoryBudgetPropertiesEXT; new(param?: VkPhysicalDeviceMemoryBudgetPropertiesEXTInitializer | null): VkPhysicalDeviceMemoryBudgetPropertiesEXT; readonly sType: VkStructureType; readonly pNext: null; readonly heapBudget: number[] | null; readonly heapUsage: number[] | null; } export interface VkPhysicalDeviceMemoryBudgetPropertiesEXT { readonly sType: VkStructureType; readonly pNext: null; readonly heapBudget: number[] | null; readonly heapUsage: number[] | null; } /** ## VkPhysicalDeviceScalarBlockLayoutFeaturesEXT ## */ interface VkPhysicalDeviceScalarBlockLayoutFeaturesEXTInitializer { sType?: VkStructureType; pNext?: null; scalarBlockLayout?: number; } declare var VkPhysicalDeviceScalarBlockLayoutFeaturesEXT: { prototype: VkPhysicalDeviceScalarBlockLayoutFeaturesEXT; new(param?: VkPhysicalDeviceScalarBlockLayoutFeaturesEXTInitializer | null): VkPhysicalDeviceScalarBlockLayoutFeaturesEXT; sType: VkStructureType; pNext: null; scalarBlockLayout: number; } export interface VkPhysicalDeviceScalarBlockLayoutFeaturesEXT { sType: VkStructureType; pNext: null; scalarBlockLayout: number; } /** ## VkRenderPassFragmentDensityMapCreateInfoEXT ## */ interface VkRenderPassFragmentDensityMapCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; fragmentDensityMapAttachment?: VkAttachmentReference | null; } declare var VkRenderPassFragmentDensityMapCreateInfoEXT: { prototype: VkRenderPassFragmentDensityMapCreateInfoEXT; new(param?: VkRenderPassFragmentDensityMapCreateInfoEXTInitializer | null): VkRenderPassFragmentDensityMapCreateInfoEXT; sType: VkStructureType; pNext: null; fragmentDensityMapAttachment: VkAttachmentReference | null; } export interface VkRenderPassFragmentDensityMapCreateInfoEXT { sType: VkStructureType; pNext: null; fragmentDensityMapAttachment: VkAttachmentReference | null; } /** ## VkPhysicalDeviceFragmentDensityMapPropertiesEXT ## */ interface VkPhysicalDeviceFragmentDensityMapPropertiesEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly minFragmentDensityTexelSize?: VkExtent2D | null; readonly maxFragmentDensityTexelSize?: VkExtent2D | null; readonly fragmentDensityInvocations?: number; } declare var VkPhysicalDeviceFragmentDensityMapPropertiesEXT: { prototype: VkPhysicalDeviceFragmentDensityMapPropertiesEXT; new(param?: VkPhysicalDeviceFragmentDensityMapPropertiesEXTInitializer | null): VkPhysicalDeviceFragmentDensityMapPropertiesEXT; readonly sType: VkStructureType; readonly pNext: null; readonly minFragmentDensityTexelSize: VkExtent2D | null; readonly maxFragmentDensityTexelSize: VkExtent2D | null; readonly fragmentDensityInvocations: number; } export interface VkPhysicalDeviceFragmentDensityMapPropertiesEXT { readonly sType: VkStructureType; readonly pNext: null; readonly minFragmentDensityTexelSize: VkExtent2D | null; readonly maxFragmentDensityTexelSize: VkExtent2D | null; readonly fragmentDensityInvocations: number; } /** ## VkPhysicalDeviceFragmentDensityMapFeaturesEXT ## */ interface VkPhysicalDeviceFragmentDensityMapFeaturesEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly fragmentDensityMap?: number; readonly fragmentDensityMapDynamic?: number; readonly fragmentDensityMapNonSubsampledImages?: number; } declare var VkPhysicalDeviceFragmentDensityMapFeaturesEXT: { prototype: VkPhysicalDeviceFragmentDensityMapFeaturesEXT; new(param?: VkPhysicalDeviceFragmentDensityMapFeaturesEXTInitializer | null): VkPhysicalDeviceFragmentDensityMapFeaturesEXT; readonly sType: VkStructureType; readonly pNext: null; readonly fragmentDensityMap: number; readonly fragmentDensityMapDynamic: number; readonly fragmentDensityMapNonSubsampledImages: number; } export interface VkPhysicalDeviceFragmentDensityMapFeaturesEXT { readonly sType: VkStructureType; readonly pNext: null; readonly fragmentDensityMap: number; readonly fragmentDensityMapDynamic: number; readonly fragmentDensityMapNonSubsampledImages: number; } /** ## VkDeviceMemoryOverallocationCreateInfoAMD ## */ interface VkDeviceMemoryOverallocationCreateInfoAMDInitializer { sType?: VkStructureType; pNext?: null; overallocationBehavior?: VkMemoryOverallocationBehaviorAMD; } declare var VkDeviceMemoryOverallocationCreateInfoAMD: { prototype: VkDeviceMemoryOverallocationCreateInfoAMD; new(param?: VkDeviceMemoryOverallocationCreateInfoAMDInitializer | null): VkDeviceMemoryOverallocationCreateInfoAMD; sType: VkStructureType; pNext: null; overallocationBehavior: VkMemoryOverallocationBehaviorAMD; } export interface VkDeviceMemoryOverallocationCreateInfoAMD { sType: VkStructureType; pNext: null; overallocationBehavior: VkMemoryOverallocationBehaviorAMD; } /** ## VkImageStencilUsageCreateInfoEXT ## */ interface VkImageStencilUsageCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; stencilUsage?: VkImageUsageFlagBits; } declare var VkImageStencilUsageCreateInfoEXT: { prototype: VkImageStencilUsageCreateInfoEXT; new(param?: VkImageStencilUsageCreateInfoEXTInitializer | null): VkImageStencilUsageCreateInfoEXT; sType: VkStructureType; pNext: null; stencilUsage: VkImageUsageFlagBits; } export interface VkImageStencilUsageCreateInfoEXT { sType: VkStructureType; pNext: null; stencilUsage: VkImageUsageFlagBits; } /** ## VkImageDrmFormatModifierPropertiesEXT ## */ interface VkImageDrmFormatModifierPropertiesEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly drmFormatModifier?: number; } declare var VkImageDrmFormatModifierPropertiesEXT: { prototype: VkImageDrmFormatModifierPropertiesEXT; new(param?: VkImageDrmFormatModifierPropertiesEXTInitializer | null): VkImageDrmFormatModifierPropertiesEXT; readonly sType: VkStructureType; readonly pNext: null; readonly drmFormatModifier: number; } export interface VkImageDrmFormatModifierPropertiesEXT { readonly sType: VkStructureType; readonly pNext: null; readonly drmFormatModifier: number; } /** ## VkImageDrmFormatModifierExplicitCreateInfoEXT ## */ interface VkImageDrmFormatModifierExplicitCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; drmFormatModifier?: number; drmFormatModifierPlaneCount?: number; pPlaneLayouts?: VkSubresourceLayout[] | null; } declare var VkImageDrmFormatModifierExplicitCreateInfoEXT: { prototype: VkImageDrmFormatModifierExplicitCreateInfoEXT; new(param?: VkImageDrmFormatModifierExplicitCreateInfoEXTInitializer | null): VkImageDrmFormatModifierExplicitCreateInfoEXT; sType: VkStructureType; pNext: null; drmFormatModifier: number; drmFormatModifierPlaneCount: number; pPlaneLayouts: VkSubresourceLayout[] | null; } export interface VkImageDrmFormatModifierExplicitCreateInfoEXT { sType: VkStructureType; pNext: null; drmFormatModifier: number; drmFormatModifierPlaneCount: number; pPlaneLayouts: VkSubresourceLayout[] | null; } /** ## VkImageDrmFormatModifierListCreateInfoEXT ## */ interface VkImageDrmFormatModifierListCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; drmFormatModifierCount?: number; pDrmFormatModifiers?: BigUint64Array | null; } declare var VkImageDrmFormatModifierListCreateInfoEXT: { prototype: VkImageDrmFormatModifierListCreateInfoEXT; new(param?: VkImageDrmFormatModifierListCreateInfoEXTInitializer | null): VkImageDrmFormatModifierListCreateInfoEXT; sType: VkStructureType; pNext: null; drmFormatModifierCount: number; pDrmFormatModifiers: BigUint64Array | null; } export interface VkImageDrmFormatModifierListCreateInfoEXT { sType: VkStructureType; pNext: null; drmFormatModifierCount: number; pDrmFormatModifiers: BigUint64Array | null; } /** ## VkPhysicalDeviceImageDrmFormatModifierInfoEXT ## */ interface VkPhysicalDeviceImageDrmFormatModifierInfoEXTInitializer { sType?: VkStructureType; pNext?: null; drmFormatModifier?: number; sharingMode?: VkSharingMode; queueFamilyIndexCount?: number; pQueueFamilyIndices?: Uint32Array | null; } declare var VkPhysicalDeviceImageDrmFormatModifierInfoEXT: { prototype: VkPhysicalDeviceImageDrmFormatModifierInfoEXT; new(param?: VkPhysicalDeviceImageDrmFormatModifierInfoEXTInitializer | null): VkPhysicalDeviceImageDrmFormatModifierInfoEXT; sType: VkStructureType; pNext: null; drmFormatModifier: number; sharingMode: VkSharingMode; queueFamilyIndexCount: number; pQueueFamilyIndices: Uint32Array | null; } export interface VkPhysicalDeviceImageDrmFormatModifierInfoEXT { sType: VkStructureType; pNext: null; drmFormatModifier: number; sharingMode: VkSharingMode; queueFamilyIndexCount: number; pQueueFamilyIndices: Uint32Array | null; } /** ## VkDrmFormatModifierPropertiesEXT ## */ interface VkDrmFormatModifierPropertiesEXTInitializer { readonly drmFormatModifier?: number; readonly drmFormatModifierPlaneCount?: number; readonly drmFormatModifierTilingFeatures?: VkFormatFeatureFlagBits; } declare var VkDrmFormatModifierPropertiesEXT: { prototype: VkDrmFormatModifierPropertiesEXT; new(param?: VkDrmFormatModifierPropertiesEXTInitializer | null): VkDrmFormatModifierPropertiesEXT; readonly drmFormatModifier: number; readonly drmFormatModifierPlaneCount: number; readonly drmFormatModifierTilingFeatures: VkFormatFeatureFlagBits; } export interface VkDrmFormatModifierPropertiesEXT { readonly drmFormatModifier: number; readonly drmFormatModifierPlaneCount: number; readonly drmFormatModifierTilingFeatures: VkFormatFeatureFlagBits; } /** ## VkDrmFormatModifierPropertiesListEXT ## */ interface VkDrmFormatModifierPropertiesListEXTInitializer { sType?: VkStructureType; pNext?: null; drmFormatModifierCount?: number; pDrmFormatModifierProperties?: VkDrmFormatModifierPropertiesEXT[] | null; } declare var VkDrmFormatModifierPropertiesListEXT: { prototype: VkDrmFormatModifierPropertiesListEXT; new(param?: VkDrmFormatModifierPropertiesListEXTInitializer | null): VkDrmFormatModifierPropertiesListEXT; sType: VkStructureType; pNext: null; drmFormatModifierCount: number; pDrmFormatModifierProperties: VkDrmFormatModifierPropertiesEXT[] | null; } export interface VkDrmFormatModifierPropertiesListEXT { sType: VkStructureType; pNext: null; drmFormatModifierCount: number; pDrmFormatModifierProperties: VkDrmFormatModifierPropertiesEXT[] | null; } /** ## VkPhysicalDeviceRayTracingPropertiesNV ## */ interface VkPhysicalDeviceRayTracingPropertiesNVInitializer { sType?: VkStructureType; pNext?: null; shaderGroupHandleSize?: number; maxRecursionDepth?: number; maxShaderGroupStride?: number; shaderGroupBaseAlignment?: number; maxGeometryCount?: number; maxInstanceCount?: number; maxTriangleCount?: number; maxDescriptorSetAccelerationStructures?: number; } declare var VkPhysicalDeviceRayTracingPropertiesNV: { prototype: VkPhysicalDeviceRayTracingPropertiesNV; new(param?: VkPhysicalDeviceRayTracingPropertiesNVInitializer | null): VkPhysicalDeviceRayTracingPropertiesNV; sType: VkStructureType; pNext: null; shaderGroupHandleSize: number; maxRecursionDepth: number; maxShaderGroupStride: number; shaderGroupBaseAlignment: number; maxGeometryCount: number; maxInstanceCount: number; maxTriangleCount: number; maxDescriptorSetAccelerationStructures: number; } export interface VkPhysicalDeviceRayTracingPropertiesNV { sType: VkStructureType; pNext: null; shaderGroupHandleSize: number; maxRecursionDepth: number; maxShaderGroupStride: number; shaderGroupBaseAlignment: number; maxGeometryCount: number; maxInstanceCount: number; maxTriangleCount: number; maxDescriptorSetAccelerationStructures: number; } /** ## VkAccelerationStructureMemoryRequirementsInfoNV ## */ interface VkAccelerationStructureMemoryRequirementsInfoNVInitializer { sType?: VkStructureType; pNext?: null; type?: VkAccelerationStructureMemoryRequirementsTypeNV; accelerationStructure?: VkAccelerationStructureNV | null; } declare var VkAccelerationStructureMemoryRequirementsInfoNV: { prototype: VkAccelerationStructureMemoryRequirementsInfoNV; new(param?: VkAccelerationStructureMemoryRequirementsInfoNVInitializer | null): VkAccelerationStructureMemoryRequirementsInfoNV; sType: VkStructureType; pNext: null; type: VkAccelerationStructureMemoryRequirementsTypeNV; accelerationStructure: VkAccelerationStructureNV | null; } export interface VkAccelerationStructureMemoryRequirementsInfoNV { sType: VkStructureType; pNext: null; type: VkAccelerationStructureMemoryRequirementsTypeNV; accelerationStructure: VkAccelerationStructureNV | null; } /** ## VkWriteDescriptorSetAccelerationStructureNV ## */ interface VkWriteDescriptorSetAccelerationStructureNVInitializer { sType?: VkStructureType; pNext?: null; accelerationStructureCount?: number; pAccelerationStructures?: VkAccelerationStructureNV[] | null; } declare var VkWriteDescriptorSetAccelerationStructureNV: { prototype: VkWriteDescriptorSetAccelerationStructureNV; new(param?: VkWriteDescriptorSetAccelerationStructureNVInitializer | null): VkWriteDescriptorSetAccelerationStructureNV; sType: VkStructureType; pNext: null; accelerationStructureCount: number; pAccelerationStructures: VkAccelerationStructureNV[] | null; } export interface VkWriteDescriptorSetAccelerationStructureNV { sType: VkStructureType; pNext: null; accelerationStructureCount: number; pAccelerationStructures: VkAccelerationStructureNV[] | null; } /** ## VkBindAccelerationStructureMemoryInfoNV ## */ interface VkBindAccelerationStructureMemoryInfoNVInitializer { sType?: VkStructureType; pNext?: null; accelerationStructure?: VkAccelerationStructureNV | null; memory?: VkDeviceMemory | null; memoryOffset?: number; deviceIndexCount?: number; pDeviceIndices?: Uint32Array | null; } declare var VkBindAccelerationStructureMemoryInfoNV: { prototype: VkBindAccelerationStructureMemoryInfoNV; new(param?: VkBindAccelerationStructureMemoryInfoNVInitializer | null): VkBindAccelerationStructureMemoryInfoNV; sType: VkStructureType; pNext: null; accelerationStructure: VkAccelerationStructureNV | null; memory: VkDeviceMemory | null; memoryOffset: number; deviceIndexCount: number; pDeviceIndices: Uint32Array | null; } export interface VkBindAccelerationStructureMemoryInfoNV { sType: VkStructureType; pNext: null; accelerationStructure: VkAccelerationStructureNV | null; memory: VkDeviceMemory | null; memoryOffset: number; deviceIndexCount: number; pDeviceIndices: Uint32Array | null; } /** ## VkAccelerationStructureCreateInfoNV ## */ interface VkAccelerationStructureCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; compactedSize?: number; info?: VkAccelerationStructureInfoNV | null; } declare var VkAccelerationStructureCreateInfoNV: { prototype: VkAccelerationStructureCreateInfoNV; new(param?: VkAccelerationStructureCreateInfoNVInitializer | null): VkAccelerationStructureCreateInfoNV; sType: VkStructureType; pNext: null; compactedSize: number; info: VkAccelerationStructureInfoNV | null; } export interface VkAccelerationStructureCreateInfoNV { sType: VkStructureType; pNext: null; compactedSize: number; info: VkAccelerationStructureInfoNV | null; } /** ## VkAccelerationStructureInfoNV ## */ interface VkAccelerationStructureInfoNVInitializer { sType?: VkStructureType; pNext?: null; type?: VkAccelerationStructureTypeNV; flags?: VkBuildAccelerationStructureFlagBitsNV; instanceCount?: number; geometryCount?: number; pGeometries?: VkGeometryNV[] | null; } declare var VkAccelerationStructureInfoNV: { prototype: VkAccelerationStructureInfoNV; new(param?: VkAccelerationStructureInfoNVInitializer | null): VkAccelerationStructureInfoNV; sType: VkStructureType; pNext: null; type: VkAccelerationStructureTypeNV; flags: VkBuildAccelerationStructureFlagBitsNV; instanceCount: number; geometryCount: number; pGeometries: VkGeometryNV[] | null; } export interface VkAccelerationStructureInfoNV { sType: VkStructureType; pNext: null; type: VkAccelerationStructureTypeNV; flags: VkBuildAccelerationStructureFlagBitsNV; instanceCount: number; geometryCount: number; pGeometries: VkGeometryNV[] | null; } /** ## VkGeometryNV ## */ interface VkGeometryNVInitializer { sType?: VkStructureType; pNext?: null; geometryType?: VkGeometryTypeNV; geometry?: VkGeometryDataNV | null; flags?: VkGeometryFlagBitsNV; } declare var VkGeometryNV: { prototype: VkGeometryNV; new(param?: VkGeometryNVInitializer | null): VkGeometryNV; sType: VkStructureType; pNext: null; geometryType: VkGeometryTypeNV; geometry: VkGeometryDataNV | null; flags: VkGeometryFlagBitsNV; } export interface VkGeometryNV { sType: VkStructureType; pNext: null; geometryType: VkGeometryTypeNV; geometry: VkGeometryDataNV | null; flags: VkGeometryFlagBitsNV; } /** ## VkGeometryDataNV ## */ interface VkGeometryDataNVInitializer { triangles?: VkGeometryTrianglesNV | null; aabbs?: VkGeometryAABBNV | null; } declare var VkGeometryDataNV: { prototype: VkGeometryDataNV; new(param?: VkGeometryDataNVInitializer | null): VkGeometryDataNV; triangles: VkGeometryTrianglesNV | null; aabbs: VkGeometryAABBNV | null; } export interface VkGeometryDataNV { triangles: VkGeometryTrianglesNV | null; aabbs: VkGeometryAABBNV | null; } /** ## VkGeometryAABBNV ## */ interface VkGeometryAABBNVInitializer { sType?: VkStructureType; pNext?: null; aabbData?: VkBuffer | null; numAABBs?: number; stride?: number; offset?: number; } declare var VkGeometryAABBNV: { prototype: VkGeometryAABBNV; new(param?: VkGeometryAABBNVInitializer | null): VkGeometryAABBNV; sType: VkStructureType; pNext: null; aabbData: VkBuffer | null; numAABBs: number; stride: number; offset: number; } export interface VkGeometryAABBNV { sType: VkStructureType; pNext: null; aabbData: VkBuffer | null; numAABBs: number; stride: number; offset: number; } /** ## VkGeometryTrianglesNV ## */ interface VkGeometryTrianglesNVInitializer { sType?: VkStructureType; pNext?: null; vertexData?: VkBuffer | null; vertexOffset?: number; vertexCount?: number; vertexStride?: number; vertexFormat?: VkFormat; indexData?: VkBuffer | null; indexOffset?: number; indexCount?: number; indexType?: VkIndexType; transformData?: VkBuffer | null; transformOffset?: number; } declare var VkGeometryTrianglesNV: { prototype: VkGeometryTrianglesNV; new(param?: VkGeometryTrianglesNVInitializer | null): VkGeometryTrianglesNV; sType: VkStructureType; pNext: null; vertexData: VkBuffer | null; vertexOffset: number; vertexCount: number; vertexStride: number; vertexFormat: VkFormat; indexData: VkBuffer | null; indexOffset: number; indexCount: number; indexType: VkIndexType; transformData: VkBuffer | null; transformOffset: number; } export interface VkGeometryTrianglesNV { sType: VkStructureType; pNext: null; vertexData: VkBuffer | null; vertexOffset: number; vertexCount: number; vertexStride: number; vertexFormat: VkFormat; indexData: VkBuffer | null; indexOffset: number; indexCount: number; indexType: VkIndexType; transformData: VkBuffer | null; transformOffset: number; } /** ## VkRayTracingPipelineCreateInfoNV ## */ interface VkRayTracingPipelineCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; flags?: VkPipelineCreateFlagBits; stageCount?: number; pStages?: VkPipelineShaderStageCreateInfo[] | null; groupCount?: number; pGroups?: VkRayTracingShaderGroupCreateInfoNV[] | null; maxRecursionDepth?: number; layout?: VkPipelineLayout | null; basePipelineHandle?: VkPipeline | null; basePipelineIndex?: number; } declare var VkRayTracingPipelineCreateInfoNV: { prototype: VkRayTracingPipelineCreateInfoNV; new(param?: VkRayTracingPipelineCreateInfoNVInitializer | null): VkRayTracingPipelineCreateInfoNV; sType: VkStructureType; pNext: null; flags: VkPipelineCreateFlagBits; stageCount: number; pStages: VkPipelineShaderStageCreateInfo[] | null; groupCount: number; pGroups: VkRayTracingShaderGroupCreateInfoNV[] | null; maxRecursionDepth: number; layout: VkPipelineLayout | null; basePipelineHandle: VkPipeline | null; basePipelineIndex: number; } export interface VkRayTracingPipelineCreateInfoNV { sType: VkStructureType; pNext: null; flags: VkPipelineCreateFlagBits; stageCount: number; pStages: VkPipelineShaderStageCreateInfo[] | null; groupCount: number; pGroups: VkRayTracingShaderGroupCreateInfoNV[] | null; maxRecursionDepth: number; layout: VkPipelineLayout | null; basePipelineHandle: VkPipeline | null; basePipelineIndex: number; } /** ## VkRayTracingShaderGroupCreateInfoNV ## */ interface VkRayTracingShaderGroupCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; type?: VkRayTracingShaderGroupTypeNV; generalShader?: number; closestHitShader?: number; anyHitShader?: number; intersectionShader?: number; } declare var VkRayTracingShaderGroupCreateInfoNV: { prototype: VkRayTracingShaderGroupCreateInfoNV; new(param?: VkRayTracingShaderGroupCreateInfoNVInitializer | null): VkRayTracingShaderGroupCreateInfoNV; sType: VkStructureType; pNext: null; type: VkRayTracingShaderGroupTypeNV; generalShader: number; closestHitShader: number; anyHitShader: number; intersectionShader: number; } export interface VkRayTracingShaderGroupCreateInfoNV { sType: VkStructureType; pNext: null; type: VkRayTracingShaderGroupTypeNV; generalShader: number; closestHitShader: number; anyHitShader: number; intersectionShader: number; } /** ## VkDrawMeshTasksIndirectCommandNV ## */ interface VkDrawMeshTasksIndirectCommandNVInitializer { taskCount?: number; firstTask?: number; } declare var VkDrawMeshTasksIndirectCommandNV: { prototype: VkDrawMeshTasksIndirectCommandNV; new(param?: VkDrawMeshTasksIndirectCommandNVInitializer | null): VkDrawMeshTasksIndirectCommandNV; taskCount: number; firstTask: number; } export interface VkDrawMeshTasksIndirectCommandNV { taskCount: number; firstTask: number; } /** ## VkPhysicalDeviceMeshShaderPropertiesNV ## */ interface VkPhysicalDeviceMeshShaderPropertiesNVInitializer { sType?: VkStructureType; pNext?: null; maxDrawMeshTasksCount?: number; maxTaskWorkGroupInvocations?: number; maxTaskWorkGroupSize?: number[] | null; maxTaskTotalMemorySize?: number; maxTaskOutputCount?: number; maxMeshWorkGroupInvocations?: number; maxMeshWorkGroupSize?: number[] | null; maxMeshTotalMemorySize?: number; maxMeshOutputVertices?: number; maxMeshOutputPrimitives?: number; maxMeshMultiviewViewCount?: number; meshOutputPerVertexGranularity?: number; meshOutputPerPrimitiveGranularity?: number; } declare var VkPhysicalDeviceMeshShaderPropertiesNV: { prototype: VkPhysicalDeviceMeshShaderPropertiesNV; new(param?: VkPhysicalDeviceMeshShaderPropertiesNVInitializer | null): VkPhysicalDeviceMeshShaderPropertiesNV; sType: VkStructureType; pNext: null; maxDrawMeshTasksCount: number; maxTaskWorkGroupInvocations: number; maxTaskWorkGroupSize: number[] | null; maxTaskTotalMemorySize: number; maxTaskOutputCount: number; maxMeshWorkGroupInvocations: number; maxMeshWorkGroupSize: number[] | null; maxMeshTotalMemorySize: number; maxMeshOutputVertices: number; maxMeshOutputPrimitives: number; maxMeshMultiviewViewCount: number; meshOutputPerVertexGranularity: number; meshOutputPerPrimitiveGranularity: number; } export interface VkPhysicalDeviceMeshShaderPropertiesNV { sType: VkStructureType; pNext: null; maxDrawMeshTasksCount: number; maxTaskWorkGroupInvocations: number; maxTaskWorkGroupSize: number[] | null; maxTaskTotalMemorySize: number; maxTaskOutputCount: number; maxMeshWorkGroupInvocations: number; maxMeshWorkGroupSize: number[] | null; maxMeshTotalMemorySize: number; maxMeshOutputVertices: number; maxMeshOutputPrimitives: number; maxMeshMultiviewViewCount: number; meshOutputPerVertexGranularity: number; meshOutputPerPrimitiveGranularity: number; } /** ## VkPhysicalDeviceMeshShaderFeaturesNV ## */ interface VkPhysicalDeviceMeshShaderFeaturesNVInitializer { sType?: VkStructureType; pNext?: null; taskShader?: number; meshShader?: number; } declare var VkPhysicalDeviceMeshShaderFeaturesNV: { prototype: VkPhysicalDeviceMeshShaderFeaturesNV; new(param?: VkPhysicalDeviceMeshShaderFeaturesNVInitializer | null): VkPhysicalDeviceMeshShaderFeaturesNV; sType: VkStructureType; pNext: null; taskShader: number; meshShader: number; } export interface VkPhysicalDeviceMeshShaderFeaturesNV { sType: VkStructureType; pNext: null; taskShader: number; meshShader: number; } /** ## VkPipelineViewportCoarseSampleOrderStateCreateInfoNV ## */ interface VkPipelineViewportCoarseSampleOrderStateCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; sampleOrderType?: VkCoarseSampleOrderTypeNV; customSampleOrderCount?: number; pCustomSampleOrders?: VkCoarseSampleOrderCustomNV[] | null; } declare var VkPipelineViewportCoarseSampleOrderStateCreateInfoNV: { prototype: VkPipelineViewportCoarseSampleOrderStateCreateInfoNV; new(param?: VkPipelineViewportCoarseSampleOrderStateCreateInfoNVInitializer | null): VkPipelineViewportCoarseSampleOrderStateCreateInfoNV; sType: VkStructureType; pNext: null; sampleOrderType: VkCoarseSampleOrderTypeNV; customSampleOrderCount: number; pCustomSampleOrders: VkCoarseSampleOrderCustomNV[] | null; } export interface VkPipelineViewportCoarseSampleOrderStateCreateInfoNV { sType: VkStructureType; pNext: null; sampleOrderType: VkCoarseSampleOrderTypeNV; customSampleOrderCount: number; pCustomSampleOrders: VkCoarseSampleOrderCustomNV[] | null; } /** ## VkCoarseSampleOrderCustomNV ## */ interface VkCoarseSampleOrderCustomNVInitializer { shadingRate?: VkShadingRatePaletteEntryNV; sampleCount?: number; sampleLocationCount?: number; pSampleLocations?: VkCoarseSampleLocationNV[] | null; } declare var VkCoarseSampleOrderCustomNV: { prototype: VkCoarseSampleOrderCustomNV; new(param?: VkCoarseSampleOrderCustomNVInitializer | null): VkCoarseSampleOrderCustomNV; shadingRate: VkShadingRatePaletteEntryNV; sampleCount: number; sampleLocationCount: number; pSampleLocations: VkCoarseSampleLocationNV[] | null; } export interface VkCoarseSampleOrderCustomNV { shadingRate: VkShadingRatePaletteEntryNV; sampleCount: number; sampleLocationCount: number; pSampleLocations: VkCoarseSampleLocationNV[] | null; } /** ## VkCoarseSampleLocationNV ## */ interface VkCoarseSampleLocationNVInitializer { pixelX?: number; pixelY?: number; sample?: number; } declare var VkCoarseSampleLocationNV: { prototype: VkCoarseSampleLocationNV; new(param?: VkCoarseSampleLocationNVInitializer | null): VkCoarseSampleLocationNV; pixelX: number; pixelY: number; sample: number; } export interface VkCoarseSampleLocationNV { pixelX: number; pixelY: number; sample: number; } /** ## VkPhysicalDeviceShadingRateImagePropertiesNV ## */ interface VkPhysicalDeviceShadingRateImagePropertiesNVInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly shadingRateTexelSize?: VkExtent2D | null; readonly shadingRatePaletteSize?: number; readonly shadingRateMaxCoarseSamples?: number; } declare var VkPhysicalDeviceShadingRateImagePropertiesNV: { prototype: VkPhysicalDeviceShadingRateImagePropertiesNV; new(param?: VkPhysicalDeviceShadingRateImagePropertiesNVInitializer | null): VkPhysicalDeviceShadingRateImagePropertiesNV; readonly sType: VkStructureType; readonly pNext: null; readonly shadingRateTexelSize: VkExtent2D | null; readonly shadingRatePaletteSize: number; readonly shadingRateMaxCoarseSamples: number; } export interface VkPhysicalDeviceShadingRateImagePropertiesNV { readonly sType: VkStructureType; readonly pNext: null; readonly shadingRateTexelSize: VkExtent2D | null; readonly shadingRatePaletteSize: number; readonly shadingRateMaxCoarseSamples: number; } /** ## VkPhysicalDeviceShadingRateImageFeaturesNV ## */ interface VkPhysicalDeviceShadingRateImageFeaturesNVInitializer { sType?: VkStructureType; pNext?: null; shadingRateImage?: number; shadingRateCoarseSampleOrder?: number; } declare var VkPhysicalDeviceShadingRateImageFeaturesNV: { prototype: VkPhysicalDeviceShadingRateImageFeaturesNV; new(param?: VkPhysicalDeviceShadingRateImageFeaturesNVInitializer | null): VkPhysicalDeviceShadingRateImageFeaturesNV; sType: VkStructureType; pNext: null; shadingRateImage: number; shadingRateCoarseSampleOrder: number; } export interface VkPhysicalDeviceShadingRateImageFeaturesNV { sType: VkStructureType; pNext: null; shadingRateImage: number; shadingRateCoarseSampleOrder: number; } /** ## VkPipelineViewportShadingRateImageStateCreateInfoNV ## */ interface VkPipelineViewportShadingRateImageStateCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; shadingRateImageEnable?: number; viewportCount?: number; pShadingRatePalettes?: VkShadingRatePaletteNV[] | null; } declare var VkPipelineViewportShadingRateImageStateCreateInfoNV: { prototype: VkPipelineViewportShadingRateImageStateCreateInfoNV; new(param?: VkPipelineViewportShadingRateImageStateCreateInfoNVInitializer | null): VkPipelineViewportShadingRateImageStateCreateInfoNV; sType: VkStructureType; pNext: null; shadingRateImageEnable: number; viewportCount: number; pShadingRatePalettes: VkShadingRatePaletteNV[] | null; } export interface VkPipelineViewportShadingRateImageStateCreateInfoNV { sType: VkStructureType; pNext: null; shadingRateImageEnable: number; viewportCount: number; pShadingRatePalettes: VkShadingRatePaletteNV[] | null; } /** ## VkShadingRatePaletteNV ## */ interface VkShadingRatePaletteNVInitializer { shadingRatePaletteEntryCount?: number; pShadingRatePaletteEntries?: Int32Array | null; } declare var VkShadingRatePaletteNV: { prototype: VkShadingRatePaletteNV; new(param?: VkShadingRatePaletteNVInitializer | null): VkShadingRatePaletteNV; shadingRatePaletteEntryCount: number; pShadingRatePaletteEntries: Int32Array | null; } export interface VkShadingRatePaletteNV { shadingRatePaletteEntryCount: number; pShadingRatePaletteEntries: Int32Array | null; } /** ## VkPhysicalDeviceShaderImageFootprintFeaturesNV ## */ interface VkPhysicalDeviceShaderImageFootprintFeaturesNVInitializer { sType?: VkStructureType; pNext?: null; imageFootprint?: number; } declare var VkPhysicalDeviceShaderImageFootprintFeaturesNV: { prototype: VkPhysicalDeviceShaderImageFootprintFeaturesNV; new(param?: VkPhysicalDeviceShaderImageFootprintFeaturesNVInitializer | null): VkPhysicalDeviceShaderImageFootprintFeaturesNV; sType: VkStructureType; pNext: null; imageFootprint: number; } export interface VkPhysicalDeviceShaderImageFootprintFeaturesNV { sType: VkStructureType; pNext: null; imageFootprint: number; } /** ## VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV ## */ interface VkPhysicalDeviceFragmentShaderBarycentricFeaturesNVInitializer { sType?: VkStructureType; pNext?: null; fragmentShaderBarycentric?: number; } declare var VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV: { prototype: VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV; new(param?: VkPhysicalDeviceFragmentShaderBarycentricFeaturesNVInitializer | null): VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV; sType: VkStructureType; pNext: null; fragmentShaderBarycentric: number; } export interface VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV { sType: VkStructureType; pNext: null; fragmentShaderBarycentric: number; } /** ## VkPhysicalDeviceComputeShaderDerivativesFeaturesNV ## */ interface VkPhysicalDeviceComputeShaderDerivativesFeaturesNVInitializer { sType?: VkStructureType; pNext?: null; computeDerivativeGroupQuads?: number; computeDerivativeGroupLinear?: number; } declare var VkPhysicalDeviceComputeShaderDerivativesFeaturesNV: { prototype: VkPhysicalDeviceComputeShaderDerivativesFeaturesNV; new(param?: VkPhysicalDeviceComputeShaderDerivativesFeaturesNVInitializer | null): VkPhysicalDeviceComputeShaderDerivativesFeaturesNV; sType: VkStructureType; pNext: null; computeDerivativeGroupQuads: number; computeDerivativeGroupLinear: number; } export interface VkPhysicalDeviceComputeShaderDerivativesFeaturesNV { sType: VkStructureType; pNext: null; computeDerivativeGroupQuads: number; computeDerivativeGroupLinear: number; } /** ## VkPhysicalDeviceCornerSampledImageFeaturesNV ## */ interface VkPhysicalDeviceCornerSampledImageFeaturesNVInitializer { sType?: VkStructureType; pNext?: null; cornerSampledImage?: number; } declare var VkPhysicalDeviceCornerSampledImageFeaturesNV: { prototype: VkPhysicalDeviceCornerSampledImageFeaturesNV; new(param?: VkPhysicalDeviceCornerSampledImageFeaturesNVInitializer | null): VkPhysicalDeviceCornerSampledImageFeaturesNV; sType: VkStructureType; pNext: null; cornerSampledImage: number; } export interface VkPhysicalDeviceCornerSampledImageFeaturesNV { sType: VkStructureType; pNext: null; cornerSampledImage: number; } /** ## VkPipelineViewportExclusiveScissorStateCreateInfoNV ## */ interface VkPipelineViewportExclusiveScissorStateCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; exclusiveScissorCount?: number; pExclusiveScissors?: VkRect2D[] | null; } declare var VkPipelineViewportExclusiveScissorStateCreateInfoNV: { prototype: VkPipelineViewportExclusiveScissorStateCreateInfoNV; new(param?: VkPipelineViewportExclusiveScissorStateCreateInfoNVInitializer | null): VkPipelineViewportExclusiveScissorStateCreateInfoNV; sType: VkStructureType; pNext: null; exclusiveScissorCount: number; pExclusiveScissors: VkRect2D[] | null; } export interface VkPipelineViewportExclusiveScissorStateCreateInfoNV { sType: VkStructureType; pNext: null; exclusiveScissorCount: number; pExclusiveScissors: VkRect2D[] | null; } /** ## VkPhysicalDeviceExclusiveScissorFeaturesNV ## */ interface VkPhysicalDeviceExclusiveScissorFeaturesNVInitializer { sType?: VkStructureType; pNext?: null; exclusiveScissor?: number; } declare var VkPhysicalDeviceExclusiveScissorFeaturesNV: { prototype: VkPhysicalDeviceExclusiveScissorFeaturesNV; new(param?: VkPhysicalDeviceExclusiveScissorFeaturesNVInitializer | null): VkPhysicalDeviceExclusiveScissorFeaturesNV; sType: VkStructureType; pNext: null; exclusiveScissor: number; } export interface VkPhysicalDeviceExclusiveScissorFeaturesNV { sType: VkStructureType; pNext: null; exclusiveScissor: number; } /** ## VkPipelineRepresentativeFragmentTestStateCreateInfoNV ## */ interface VkPipelineRepresentativeFragmentTestStateCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; representativeFragmentTestEnable?: number; } declare var VkPipelineRepresentativeFragmentTestStateCreateInfoNV: { prototype: VkPipelineRepresentativeFragmentTestStateCreateInfoNV; new(param?: VkPipelineRepresentativeFragmentTestStateCreateInfoNVInitializer | null): VkPipelineRepresentativeFragmentTestStateCreateInfoNV; sType: VkStructureType; pNext: null; representativeFragmentTestEnable: number; } export interface VkPipelineRepresentativeFragmentTestStateCreateInfoNV { sType: VkStructureType; pNext: null; representativeFragmentTestEnable: number; } /** ## VkPhysicalDeviceRepresentativeFragmentTestFeaturesNV ## */ interface VkPhysicalDeviceRepresentativeFragmentTestFeaturesNVInitializer { sType?: VkStructureType; pNext?: null; representativeFragmentTest?: number; } declare var VkPhysicalDeviceRepresentativeFragmentTestFeaturesNV: { prototype: VkPhysicalDeviceRepresentativeFragmentTestFeaturesNV; new(param?: VkPhysicalDeviceRepresentativeFragmentTestFeaturesNVInitializer | null): VkPhysicalDeviceRepresentativeFragmentTestFeaturesNV; sType: VkStructureType; pNext: null; representativeFragmentTest: number; } export interface VkPhysicalDeviceRepresentativeFragmentTestFeaturesNV { sType: VkStructureType; pNext: null; representativeFragmentTest: number; } /** ## VkPipelineRasterizationStateStreamCreateInfoEXT ## */ interface VkPipelineRasterizationStateStreamCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; flags?: null; rasterizationStream?: number; } declare var VkPipelineRasterizationStateStreamCreateInfoEXT: { prototype: VkPipelineRasterizationStateStreamCreateInfoEXT; new(param?: VkPipelineRasterizationStateStreamCreateInfoEXTInitializer | null): VkPipelineRasterizationStateStreamCreateInfoEXT; sType: VkStructureType; pNext: null; flags: null; rasterizationStream: number; } export interface VkPipelineRasterizationStateStreamCreateInfoEXT { sType: VkStructureType; pNext: null; flags: null; rasterizationStream: number; } /** ## VkPhysicalDeviceTransformFeedbackPropertiesEXT ## */ interface VkPhysicalDeviceTransformFeedbackPropertiesEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly maxTransformFeedbackStreams?: number; readonly maxTransformFeedbackBuffers?: number; readonly maxTransformFeedbackBufferSize?: number; readonly maxTransformFeedbackStreamDataSize?: number; readonly maxTransformFeedbackBufferDataSize?: number; readonly maxTransformFeedbackBufferDataStride?: number; readonly transformFeedbackQueries?: number; readonly transformFeedbackStreamsLinesTriangles?: number; readonly transformFeedbackRasterizationStreamSelect?: number; readonly transformFeedbackDraw?: number; } declare var VkPhysicalDeviceTransformFeedbackPropertiesEXT: { prototype: VkPhysicalDeviceTransformFeedbackPropertiesEXT; new(param?: VkPhysicalDeviceTransformFeedbackPropertiesEXTInitializer | null): VkPhysicalDeviceTransformFeedbackPropertiesEXT; readonly sType: VkStructureType; readonly pNext: null; readonly maxTransformFeedbackStreams: number; readonly maxTransformFeedbackBuffers: number; readonly maxTransformFeedbackBufferSize: number; readonly maxTransformFeedbackStreamDataSize: number; readonly maxTransformFeedbackBufferDataSize: number; readonly maxTransformFeedbackBufferDataStride: number; readonly transformFeedbackQueries: number; readonly transformFeedbackStreamsLinesTriangles: number; readonly transformFeedbackRasterizationStreamSelect: number; readonly transformFeedbackDraw: number; } export interface VkPhysicalDeviceTransformFeedbackPropertiesEXT { readonly sType: VkStructureType; readonly pNext: null; readonly maxTransformFeedbackStreams: number; readonly maxTransformFeedbackBuffers: number; readonly maxTransformFeedbackBufferSize: number; readonly maxTransformFeedbackStreamDataSize: number; readonly maxTransformFeedbackBufferDataSize: number; readonly maxTransformFeedbackBufferDataStride: number; readonly transformFeedbackQueries: number; readonly transformFeedbackStreamsLinesTriangles: number; readonly transformFeedbackRasterizationStreamSelect: number; readonly transformFeedbackDraw: number; } /** ## VkPhysicalDeviceTransformFeedbackFeaturesEXT ## */ interface VkPhysicalDeviceTransformFeedbackFeaturesEXTInitializer { sType?: VkStructureType; pNext?: null; transformFeedback?: number; geometryStreams?: number; } declare var VkPhysicalDeviceTransformFeedbackFeaturesEXT: { prototype: VkPhysicalDeviceTransformFeedbackFeaturesEXT; new(param?: VkPhysicalDeviceTransformFeedbackFeaturesEXTInitializer | null): VkPhysicalDeviceTransformFeedbackFeaturesEXT; sType: VkStructureType; pNext: null; transformFeedback: number; geometryStreams: number; } export interface VkPhysicalDeviceTransformFeedbackFeaturesEXT { sType: VkStructureType; pNext: null; transformFeedback: number; geometryStreams: number; } /** ## VkPhysicalDeviceASTCDecodeFeaturesEXT ## */ interface VkPhysicalDeviceASTCDecodeFeaturesEXTInitializer { sType?: VkStructureType; pNext?: null; decodeModeSharedExponent?: number; } declare var VkPhysicalDeviceASTCDecodeFeaturesEXT: { prototype: VkPhysicalDeviceASTCDecodeFeaturesEXT; new(param?: VkPhysicalDeviceASTCDecodeFeaturesEXTInitializer | null): VkPhysicalDeviceASTCDecodeFeaturesEXT; sType: VkStructureType; pNext: null; decodeModeSharedExponent: number; } export interface VkPhysicalDeviceASTCDecodeFeaturesEXT { sType: VkStructureType; pNext: null; decodeModeSharedExponent: number; } /** ## VkImageViewASTCDecodeModeEXT ## */ interface VkImageViewASTCDecodeModeEXTInitializer { sType?: VkStructureType; pNext?: null; decodeMode?: VkFormat; } declare var VkImageViewASTCDecodeModeEXT: { prototype: VkImageViewASTCDecodeModeEXT; new(param?: VkImageViewASTCDecodeModeEXTInitializer | null): VkImageViewASTCDecodeModeEXT; sType: VkStructureType; pNext: null; decodeMode: VkFormat; } export interface VkImageViewASTCDecodeModeEXT { sType: VkStructureType; pNext: null; decodeMode: VkFormat; } /** ## VkSubpassDescriptionDepthStencilResolveKHR ## */ interface VkSubpassDescriptionDepthStencilResolveKHRInitializer { sType?: VkStructureType; pNext?: null; depthResolveMode?: VkResolveModeFlagBitsKHR; stencilResolveMode?: VkResolveModeFlagBitsKHR; pDepthStencilResolveAttachment?: VkAttachmentReference2KHR | null; } declare var VkSubpassDescriptionDepthStencilResolveKHR: { prototype: VkSubpassDescriptionDepthStencilResolveKHR; new(param?: VkSubpassDescriptionDepthStencilResolveKHRInitializer | null): VkSubpassDescriptionDepthStencilResolveKHR; sType: VkStructureType; pNext: null; depthResolveMode: VkResolveModeFlagBitsKHR; stencilResolveMode: VkResolveModeFlagBitsKHR; pDepthStencilResolveAttachment: VkAttachmentReference2KHR | null; } export interface VkSubpassDescriptionDepthStencilResolveKHR { sType: VkStructureType; pNext: null; depthResolveMode: VkResolveModeFlagBitsKHR; stencilResolveMode: VkResolveModeFlagBitsKHR; pDepthStencilResolveAttachment: VkAttachmentReference2KHR | null; } /** ## VkPhysicalDeviceDepthStencilResolvePropertiesKHR ## */ interface VkPhysicalDeviceDepthStencilResolvePropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly supportedDepthResolveModes?: VkResolveModeFlagBitsKHR; readonly supportedStencilResolveModes?: VkResolveModeFlagBitsKHR; readonly independentResolveNone?: number; readonly independentResolve?: number; } declare var VkPhysicalDeviceDepthStencilResolvePropertiesKHR: { prototype: VkPhysicalDeviceDepthStencilResolvePropertiesKHR; new(param?: VkPhysicalDeviceDepthStencilResolvePropertiesKHRInitializer | null): VkPhysicalDeviceDepthStencilResolvePropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly supportedDepthResolveModes: VkResolveModeFlagBitsKHR; readonly supportedStencilResolveModes: VkResolveModeFlagBitsKHR; readonly independentResolveNone: number; readonly independentResolve: number; } export interface VkPhysicalDeviceDepthStencilResolvePropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly supportedDepthResolveModes: VkResolveModeFlagBitsKHR; readonly supportedStencilResolveModes: VkResolveModeFlagBitsKHR; readonly independentResolveNone: number; readonly independentResolve: number; } /** ## VkCheckpointDataNV ## */ interface VkCheckpointDataNVInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly stage?: VkPipelineStageFlagBits; readonly pCheckpointMarker?: ArrayBuffer | null; } declare var VkCheckpointDataNV: { prototype: VkCheckpointDataNV; new(param?: VkCheckpointDataNVInitializer | null): VkCheckpointDataNV; readonly sType: VkStructureType; readonly pNext: null; readonly stage: VkPipelineStageFlagBits; readonly pCheckpointMarker: ArrayBuffer | null; } export interface VkCheckpointDataNV { readonly sType: VkStructureType; readonly pNext: null; readonly stage: VkPipelineStageFlagBits; readonly pCheckpointMarker: ArrayBuffer | null; } /** ## VkQueueFamilyCheckpointPropertiesNV ## */ interface VkQueueFamilyCheckpointPropertiesNVInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly checkpointExecutionStageMask?: VkPipelineStageFlagBits; } declare var VkQueueFamilyCheckpointPropertiesNV: { prototype: VkQueueFamilyCheckpointPropertiesNV; new(param?: VkQueueFamilyCheckpointPropertiesNVInitializer | null): VkQueueFamilyCheckpointPropertiesNV; readonly sType: VkStructureType; readonly pNext: null; readonly checkpointExecutionStageMask: VkPipelineStageFlagBits; } export interface VkQueueFamilyCheckpointPropertiesNV { readonly sType: VkStructureType; readonly pNext: null; readonly checkpointExecutionStageMask: VkPipelineStageFlagBits; } /** ## VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT ## */ interface VkPhysicalDeviceVertexAttributeDivisorFeaturesEXTInitializer { sType?: VkStructureType; pNext?: null; vertexAttributeInstanceRateDivisor?: number; vertexAttributeInstanceRateZeroDivisor?: number; } declare var VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT: { prototype: VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT; new(param?: VkPhysicalDeviceVertexAttributeDivisorFeaturesEXTInitializer | null): VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT; sType: VkStructureType; pNext: null; vertexAttributeInstanceRateDivisor: number; vertexAttributeInstanceRateZeroDivisor: number; } export interface VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT { sType: VkStructureType; pNext: null; vertexAttributeInstanceRateDivisor: number; vertexAttributeInstanceRateZeroDivisor: number; } /** ## VkPhysicalDeviceShaderAtomicInt64FeaturesKHR ## */ interface VkPhysicalDeviceShaderAtomicInt64FeaturesKHRInitializer { sType?: VkStructureType; pNext?: null; shaderBufferInt64Atomics?: number; shaderSharedInt64Atomics?: number; } declare var VkPhysicalDeviceShaderAtomicInt64FeaturesKHR: { prototype: VkPhysicalDeviceShaderAtomicInt64FeaturesKHR; new(param?: VkPhysicalDeviceShaderAtomicInt64FeaturesKHRInitializer | null): VkPhysicalDeviceShaderAtomicInt64FeaturesKHR; sType: VkStructureType; pNext: null; shaderBufferInt64Atomics: number; shaderSharedInt64Atomics: number; } export interface VkPhysicalDeviceShaderAtomicInt64FeaturesKHR { sType: VkStructureType; pNext: null; shaderBufferInt64Atomics: number; shaderSharedInt64Atomics: number; } /** ## VkPhysicalDeviceVulkanMemoryModelFeaturesKHR ## */ interface VkPhysicalDeviceVulkanMemoryModelFeaturesKHRInitializer { sType?: VkStructureType; pNext?: null; vulkanMemoryModel?: number; vulkanMemoryModelDeviceScope?: number; } declare var VkPhysicalDeviceVulkanMemoryModelFeaturesKHR: { prototype: VkPhysicalDeviceVulkanMemoryModelFeaturesKHR; new(param?: VkPhysicalDeviceVulkanMemoryModelFeaturesKHRInitializer | null): VkPhysicalDeviceVulkanMemoryModelFeaturesKHR; sType: VkStructureType; pNext: null; vulkanMemoryModel: number; vulkanMemoryModelDeviceScope: number; } export interface VkPhysicalDeviceVulkanMemoryModelFeaturesKHR { sType: VkStructureType; pNext: null; vulkanMemoryModel: number; vulkanMemoryModelDeviceScope: number; } /** ## VkPhysicalDeviceConditionalRenderingFeaturesEXT ## */ interface VkPhysicalDeviceConditionalRenderingFeaturesEXTInitializer { sType?: VkStructureType; pNext?: null; conditionalRendering?: number; inheritedConditionalRendering?: number; } declare var VkPhysicalDeviceConditionalRenderingFeaturesEXT: { prototype: VkPhysicalDeviceConditionalRenderingFeaturesEXT; new(param?: VkPhysicalDeviceConditionalRenderingFeaturesEXTInitializer | null): VkPhysicalDeviceConditionalRenderingFeaturesEXT; sType: VkStructureType; pNext: null; conditionalRendering: number; inheritedConditionalRendering: number; } export interface VkPhysicalDeviceConditionalRenderingFeaturesEXT { sType: VkStructureType; pNext: null; conditionalRendering: number; inheritedConditionalRendering: number; } /** ## VkPhysicalDevice8BitStorageFeaturesKHR ## */ interface VkPhysicalDevice8BitStorageFeaturesKHRInitializer { sType?: VkStructureType; pNext?: null; storageBuffer8BitAccess?: number; uniformAndStorageBuffer8BitAccess?: number; storagePushConstant8?: number; } declare var VkPhysicalDevice8BitStorageFeaturesKHR: { prototype: VkPhysicalDevice8BitStorageFeaturesKHR; new(param?: VkPhysicalDevice8BitStorageFeaturesKHRInitializer | null): VkPhysicalDevice8BitStorageFeaturesKHR; sType: VkStructureType; pNext: null; storageBuffer8BitAccess: number; uniformAndStorageBuffer8BitAccess: number; storagePushConstant8: number; } export interface VkPhysicalDevice8BitStorageFeaturesKHR { sType: VkStructureType; pNext: null; storageBuffer8BitAccess: number; uniformAndStorageBuffer8BitAccess: number; storagePushConstant8: number; } /** ## VkCommandBufferInheritanceConditionalRenderingInfoEXT ## */ interface VkCommandBufferInheritanceConditionalRenderingInfoEXTInitializer { sType?: VkStructureType; pNext?: null; conditionalRenderingEnable?: number; } declare var VkCommandBufferInheritanceConditionalRenderingInfoEXT: { prototype: VkCommandBufferInheritanceConditionalRenderingInfoEXT; new(param?: VkCommandBufferInheritanceConditionalRenderingInfoEXTInitializer | null): VkCommandBufferInheritanceConditionalRenderingInfoEXT; sType: VkStructureType; pNext: null; conditionalRenderingEnable: number; } export interface VkCommandBufferInheritanceConditionalRenderingInfoEXT { sType: VkStructureType; pNext: null; conditionalRenderingEnable: number; } /** ## VkPhysicalDevicePCIBusInfoPropertiesEXT ## */ interface VkPhysicalDevicePCIBusInfoPropertiesEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly pciDomain?: number; readonly pciBus?: number; readonly pciDevice?: number; readonly pciFunction?: number; } declare var VkPhysicalDevicePCIBusInfoPropertiesEXT: { prototype: VkPhysicalDevicePCIBusInfoPropertiesEXT; new(param?: VkPhysicalDevicePCIBusInfoPropertiesEXTInitializer | null): VkPhysicalDevicePCIBusInfoPropertiesEXT; readonly sType: VkStructureType; readonly pNext: null; readonly pciDomain: number; readonly pciBus: number; readonly pciDevice: number; readonly pciFunction: number; } export interface VkPhysicalDevicePCIBusInfoPropertiesEXT { readonly sType: VkStructureType; readonly pNext: null; readonly pciDomain: number; readonly pciBus: number; readonly pciDevice: number; readonly pciFunction: number; } /** ## VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT ## */ interface VkPhysicalDeviceVertexAttributeDivisorPropertiesEXTInitializer { sType?: VkStructureType; pNext?: null; maxVertexAttribDivisor?: number; } declare var VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT: { prototype: VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT; new(param?: VkPhysicalDeviceVertexAttributeDivisorPropertiesEXTInitializer | null): VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT; sType: VkStructureType; pNext: null; maxVertexAttribDivisor: number; } export interface VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT { sType: VkStructureType; pNext: null; maxVertexAttribDivisor: number; } /** ## VkPipelineVertexInputDivisorStateCreateInfoEXT ## */ interface VkPipelineVertexInputDivisorStateCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; vertexBindingDivisorCount?: number; pVertexBindingDivisors?: VkVertexInputBindingDivisorDescriptionEXT[] | null; } declare var VkPipelineVertexInputDivisorStateCreateInfoEXT: { prototype: VkPipelineVertexInputDivisorStateCreateInfoEXT; new(param?: VkPipelineVertexInputDivisorStateCreateInfoEXTInitializer | null): VkPipelineVertexInputDivisorStateCreateInfoEXT; sType: VkStructureType; pNext: null; vertexBindingDivisorCount: number; pVertexBindingDivisors: VkVertexInputBindingDivisorDescriptionEXT[] | null; } export interface VkPipelineVertexInputDivisorStateCreateInfoEXT { sType: VkStructureType; pNext: null; vertexBindingDivisorCount: number; pVertexBindingDivisors: VkVertexInputBindingDivisorDescriptionEXT[] | null; } /** ## VkVertexInputBindingDivisorDescriptionEXT ## */ interface VkVertexInputBindingDivisorDescriptionEXTInitializer { binding?: number; divisor?: number; } declare var VkVertexInputBindingDivisorDescriptionEXT: { prototype: VkVertexInputBindingDivisorDescriptionEXT; new(param?: VkVertexInputBindingDivisorDescriptionEXTInitializer | null): VkVertexInputBindingDivisorDescriptionEXT; binding: number; divisor: number; } export interface VkVertexInputBindingDivisorDescriptionEXT { binding: number; divisor: number; } /** ## VkSubpassEndInfoKHR ## */ interface VkSubpassEndInfoKHRInitializer { sType?: VkStructureType; pNext?: null; } declare var VkSubpassEndInfoKHR: { prototype: VkSubpassEndInfoKHR; new(param?: VkSubpassEndInfoKHRInitializer | null): VkSubpassEndInfoKHR; sType: VkStructureType; pNext: null; } export interface VkSubpassEndInfoKHR { sType: VkStructureType; pNext: null; } /** ## VkSubpassBeginInfoKHR ## */ interface VkSubpassBeginInfoKHRInitializer { sType?: VkStructureType; pNext?: null; contents?: VkSubpassContents; } declare var VkSubpassBeginInfoKHR: { prototype: VkSubpassBeginInfoKHR; new(param?: VkSubpassBeginInfoKHRInitializer | null): VkSubpassBeginInfoKHR; sType: VkStructureType; pNext: null; contents: VkSubpassContents; } export interface VkSubpassBeginInfoKHR { sType: VkStructureType; pNext: null; contents: VkSubpassContents; } /** ## VkRenderPassCreateInfo2KHR ## */ interface VkRenderPassCreateInfo2KHRInitializer { sType?: VkStructureType; pNext?: null; flags?: null; attachmentCount?: number; pAttachments?: VkAttachmentDescription2KHR[] | null; subpassCount?: number; pSubpasses?: VkSubpassDescription2KHR[] | null; dependencyCount?: number; pDependencies?: VkSubpassDependency2KHR[] | null; correlatedViewMaskCount?: number; pCorrelatedViewMasks?: Uint32Array | null; } declare var VkRenderPassCreateInfo2KHR: { prototype: VkRenderPassCreateInfo2KHR; new(param?: VkRenderPassCreateInfo2KHRInitializer | null): VkRenderPassCreateInfo2KHR; sType: VkStructureType; pNext: null; flags: null; attachmentCount: number; pAttachments: VkAttachmentDescription2KHR[] | null; subpassCount: number; pSubpasses: VkSubpassDescription2KHR[] | null; dependencyCount: number; pDependencies: VkSubpassDependency2KHR[] | null; correlatedViewMaskCount: number; pCorrelatedViewMasks: Uint32Array | null; } export interface VkRenderPassCreateInfo2KHR { sType: VkStructureType; pNext: null; flags: null; attachmentCount: number; pAttachments: VkAttachmentDescription2KHR[] | null; subpassCount: number; pSubpasses: VkSubpassDescription2KHR[] | null; dependencyCount: number; pDependencies: VkSubpassDependency2KHR[] | null; correlatedViewMaskCount: number; pCorrelatedViewMasks: Uint32Array | null; } /** ## VkSubpassDependency2KHR ## */ interface VkSubpassDependency2KHRInitializer { sType?: VkStructureType; pNext?: null; srcSubpass?: number; dstSubpass?: number; srcStageMask?: VkPipelineStageFlagBits; dstStageMask?: VkPipelineStageFlagBits; srcAccessMask?: VkAccessFlagBits; dstAccessMask?: VkAccessFlagBits; dependencyFlags?: VkDependencyFlagBits; viewOffset?: number; } declare var VkSubpassDependency2KHR: { prototype: VkSubpassDependency2KHR; new(param?: VkSubpassDependency2KHRInitializer | null): VkSubpassDependency2KHR; sType: VkStructureType; pNext: null; srcSubpass: number; dstSubpass: number; srcStageMask: VkPipelineStageFlagBits; dstStageMask: VkPipelineStageFlagBits; srcAccessMask: VkAccessFlagBits; dstAccessMask: VkAccessFlagBits; dependencyFlags: VkDependencyFlagBits; viewOffset: number; } export interface VkSubpassDependency2KHR { sType: VkStructureType; pNext: null; srcSubpass: number; dstSubpass: number; srcStageMask: VkPipelineStageFlagBits; dstStageMask: VkPipelineStageFlagBits; srcAccessMask: VkAccessFlagBits; dstAccessMask: VkAccessFlagBits; dependencyFlags: VkDependencyFlagBits; viewOffset: number; } /** ## VkSubpassDescription2KHR ## */ interface VkSubpassDescription2KHRInitializer { sType?: VkStructureType; pNext?: null; flags?: VkSubpassDescriptionFlagBits; pipelineBindPoint?: VkPipelineBindPoint; viewMask?: number; inputAttachmentCount?: number; pInputAttachments?: VkAttachmentReference2KHR[] | null; colorAttachmentCount?: number; pColorAttachments?: VkAttachmentReference2KHR[] | null; pResolveAttachments?: VkAttachmentReference2KHR[] | null; pDepthStencilAttachment?: VkAttachmentReference2KHR | null; preserveAttachmentCount?: number; pPreserveAttachments?: Uint32Array | null; } declare var VkSubpassDescription2KHR: { prototype: VkSubpassDescription2KHR; new(param?: VkSubpassDescription2KHRInitializer | null): VkSubpassDescription2KHR; sType: VkStructureType; pNext: null; flags: VkSubpassDescriptionFlagBits; pipelineBindPoint: VkPipelineBindPoint; viewMask: number; inputAttachmentCount: number; pInputAttachments: VkAttachmentReference2KHR[] | null; colorAttachmentCount: number; pColorAttachments: VkAttachmentReference2KHR[] | null; pResolveAttachments: VkAttachmentReference2KHR[] | null; pDepthStencilAttachment: VkAttachmentReference2KHR | null; preserveAttachmentCount: number; pPreserveAttachments: Uint32Array | null; } export interface VkSubpassDescription2KHR { sType: VkStructureType; pNext: null; flags: VkSubpassDescriptionFlagBits; pipelineBindPoint: VkPipelineBindPoint; viewMask: number; inputAttachmentCount: number; pInputAttachments: VkAttachmentReference2KHR[] | null; colorAttachmentCount: number; pColorAttachments: VkAttachmentReference2KHR[] | null; pResolveAttachments: VkAttachmentReference2KHR[] | null; pDepthStencilAttachment: VkAttachmentReference2KHR | null; preserveAttachmentCount: number; pPreserveAttachments: Uint32Array | null; } /** ## VkAttachmentReference2KHR ## */ interface VkAttachmentReference2KHRInitializer { sType?: VkStructureType; pNext?: null; attachment?: number; layout?: VkImageLayout; aspectMask?: VkImageAspectFlagBits; } declare var VkAttachmentReference2KHR: { prototype: VkAttachmentReference2KHR; new(param?: VkAttachmentReference2KHRInitializer | null): VkAttachmentReference2KHR; sType: VkStructureType; pNext: null; attachment: number; layout: VkImageLayout; aspectMask: VkImageAspectFlagBits; } export interface VkAttachmentReference2KHR { sType: VkStructureType; pNext: null; attachment: number; layout: VkImageLayout; aspectMask: VkImageAspectFlagBits; } /** ## VkAttachmentDescription2KHR ## */ interface VkAttachmentDescription2KHRInitializer { sType?: VkStructureType; pNext?: null; flags?: VkAttachmentDescriptionFlagBits; format?: VkFormat; samples?: VkSampleCountFlagBits; loadOp?: VkAttachmentLoadOp; storeOp?: VkAttachmentStoreOp; stencilLoadOp?: VkAttachmentLoadOp; stencilStoreOp?: VkAttachmentStoreOp; initialLayout?: VkImageLayout; finalLayout?: VkImageLayout; } declare var VkAttachmentDescription2KHR: { prototype: VkAttachmentDescription2KHR; new(param?: VkAttachmentDescription2KHRInitializer | null): VkAttachmentDescription2KHR; sType: VkStructureType; pNext: null; flags: VkAttachmentDescriptionFlagBits; format: VkFormat; samples: VkSampleCountFlagBits; loadOp: VkAttachmentLoadOp; storeOp: VkAttachmentStoreOp; stencilLoadOp: VkAttachmentLoadOp; stencilStoreOp: VkAttachmentStoreOp; initialLayout: VkImageLayout; finalLayout: VkImageLayout; } export interface VkAttachmentDescription2KHR { sType: VkStructureType; pNext: null; flags: VkAttachmentDescriptionFlagBits; format: VkFormat; samples: VkSampleCountFlagBits; loadOp: VkAttachmentLoadOp; storeOp: VkAttachmentStoreOp; stencilLoadOp: VkAttachmentLoadOp; stencilStoreOp: VkAttachmentStoreOp; initialLayout: VkImageLayout; finalLayout: VkImageLayout; } /** ## VkDescriptorSetVariableDescriptorCountLayoutSupportEXT ## */ interface VkDescriptorSetVariableDescriptorCountLayoutSupportEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly maxVariableDescriptorCount?: number; } declare var VkDescriptorSetVariableDescriptorCountLayoutSupportEXT: { prototype: VkDescriptorSetVariableDescriptorCountLayoutSupportEXT; new(param?: VkDescriptorSetVariableDescriptorCountLayoutSupportEXTInitializer | null): VkDescriptorSetVariableDescriptorCountLayoutSupportEXT; readonly sType: VkStructureType; readonly pNext: null; readonly maxVariableDescriptorCount: number; } export interface VkDescriptorSetVariableDescriptorCountLayoutSupportEXT { readonly sType: VkStructureType; readonly pNext: null; readonly maxVariableDescriptorCount: number; } /** ## VkDescriptorSetVariableDescriptorCountAllocateInfoEXT ## */ interface VkDescriptorSetVariableDescriptorCountAllocateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; descriptorSetCount?: number; pDescriptorCounts?: Uint32Array | null; } declare var VkDescriptorSetVariableDescriptorCountAllocateInfoEXT: { prototype: VkDescriptorSetVariableDescriptorCountAllocateInfoEXT; new(param?: VkDescriptorSetVariableDescriptorCountAllocateInfoEXTInitializer | null): VkDescriptorSetVariableDescriptorCountAllocateInfoEXT; sType: VkStructureType; pNext: null; descriptorSetCount: number; pDescriptorCounts: Uint32Array | null; } export interface VkDescriptorSetVariableDescriptorCountAllocateInfoEXT { sType: VkStructureType; pNext: null; descriptorSetCount: number; pDescriptorCounts: Uint32Array | null; } /** ## VkDescriptorSetLayoutBindingFlagsCreateInfoEXT ## */ interface VkDescriptorSetLayoutBindingFlagsCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; bindingCount?: number; pBindingFlags?: Int32Array | null; } declare var VkDescriptorSetLayoutBindingFlagsCreateInfoEXT: { prototype: VkDescriptorSetLayoutBindingFlagsCreateInfoEXT; new(param?: VkDescriptorSetLayoutBindingFlagsCreateInfoEXTInitializer | null): VkDescriptorSetLayoutBindingFlagsCreateInfoEXT; sType: VkStructureType; pNext: null; bindingCount: number; pBindingFlags: Int32Array | null; } export interface VkDescriptorSetLayoutBindingFlagsCreateInfoEXT { sType: VkStructureType; pNext: null; bindingCount: number; pBindingFlags: Int32Array | null; } /** ## VkPhysicalDeviceDescriptorIndexingPropertiesEXT ## */ interface VkPhysicalDeviceDescriptorIndexingPropertiesEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly maxUpdateAfterBindDescriptorsInAllPools?: number; readonly shaderUniformBufferArrayNonUniformIndexingNative?: number; readonly shaderSampledImageArrayNonUniformIndexingNative?: number; readonly shaderStorageBufferArrayNonUniformIndexingNative?: number; readonly shaderStorageImageArrayNonUniformIndexingNative?: number; readonly shaderInputAttachmentArrayNonUniformIndexingNative?: number; readonly robustBufferAccessUpdateAfterBind?: number; readonly quadDivergentImplicitLod?: number; readonly maxPerStageDescriptorUpdateAfterBindSamplers?: number; readonly maxPerStageDescriptorUpdateAfterBindUniformBuffers?: number; readonly maxPerStageDescriptorUpdateAfterBindStorageBuffers?: number; readonly maxPerStageDescriptorUpdateAfterBindSampledImages?: number; readonly maxPerStageDescriptorUpdateAfterBindStorageImages?: number; readonly maxPerStageDescriptorUpdateAfterBindInputAttachments?: number; readonly maxPerStageUpdateAfterBindResources?: number; readonly maxDescriptorSetUpdateAfterBindSamplers?: number; readonly maxDescriptorSetUpdateAfterBindUniformBuffers?: number; readonly maxDescriptorSetUpdateAfterBindUniformBuffersDynamic?: number; readonly maxDescriptorSetUpdateAfterBindStorageBuffers?: number; readonly maxDescriptorSetUpdateAfterBindStorageBuffersDynamic?: number; readonly maxDescriptorSetUpdateAfterBindSampledImages?: number; readonly maxDescriptorSetUpdateAfterBindStorageImages?: number; readonly maxDescriptorSetUpdateAfterBindInputAttachments?: number; } declare var VkPhysicalDeviceDescriptorIndexingPropertiesEXT: { prototype: VkPhysicalDeviceDescriptorIndexingPropertiesEXT; new(param?: VkPhysicalDeviceDescriptorIndexingPropertiesEXTInitializer | null): VkPhysicalDeviceDescriptorIndexingPropertiesEXT; readonly sType: VkStructureType; readonly pNext: null; readonly maxUpdateAfterBindDescriptorsInAllPools: number; readonly shaderUniformBufferArrayNonUniformIndexingNative: number; readonly shaderSampledImageArrayNonUniformIndexingNative: number; readonly shaderStorageBufferArrayNonUniformIndexingNative: number; readonly shaderStorageImageArrayNonUniformIndexingNative: number; readonly shaderInputAttachmentArrayNonUniformIndexingNative: number; readonly robustBufferAccessUpdateAfterBind: number; readonly quadDivergentImplicitLod: number; readonly maxPerStageDescriptorUpdateAfterBindSamplers: number; readonly maxPerStageDescriptorUpdateAfterBindUniformBuffers: number; readonly maxPerStageDescriptorUpdateAfterBindStorageBuffers: number; readonly maxPerStageDescriptorUpdateAfterBindSampledImages: number; readonly maxPerStageDescriptorUpdateAfterBindStorageImages: number; readonly maxPerStageDescriptorUpdateAfterBindInputAttachments: number; readonly maxPerStageUpdateAfterBindResources: number; readonly maxDescriptorSetUpdateAfterBindSamplers: number; readonly maxDescriptorSetUpdateAfterBindUniformBuffers: number; readonly maxDescriptorSetUpdateAfterBindUniformBuffersDynamic: number; readonly maxDescriptorSetUpdateAfterBindStorageBuffers: number; readonly maxDescriptorSetUpdateAfterBindStorageBuffersDynamic: number; readonly maxDescriptorSetUpdateAfterBindSampledImages: number; readonly maxDescriptorSetUpdateAfterBindStorageImages: number; readonly maxDescriptorSetUpdateAfterBindInputAttachments: number; } export interface VkPhysicalDeviceDescriptorIndexingPropertiesEXT { readonly sType: VkStructureType; readonly pNext: null; readonly maxUpdateAfterBindDescriptorsInAllPools: number; readonly shaderUniformBufferArrayNonUniformIndexingNative: number; readonly shaderSampledImageArrayNonUniformIndexingNative: number; readonly shaderStorageBufferArrayNonUniformIndexingNative: number; readonly shaderStorageImageArrayNonUniformIndexingNative: number; readonly shaderInputAttachmentArrayNonUniformIndexingNative: number; readonly robustBufferAccessUpdateAfterBind: number; readonly quadDivergentImplicitLod: number; readonly maxPerStageDescriptorUpdateAfterBindSamplers: number; readonly maxPerStageDescriptorUpdateAfterBindUniformBuffers: number; readonly maxPerStageDescriptorUpdateAfterBindStorageBuffers: number; readonly maxPerStageDescriptorUpdateAfterBindSampledImages: number; readonly maxPerStageDescriptorUpdateAfterBindStorageImages: number; readonly maxPerStageDescriptorUpdateAfterBindInputAttachments: number; readonly maxPerStageUpdateAfterBindResources: number; readonly maxDescriptorSetUpdateAfterBindSamplers: number; readonly maxDescriptorSetUpdateAfterBindUniformBuffers: number; readonly maxDescriptorSetUpdateAfterBindUniformBuffersDynamic: number; readonly maxDescriptorSetUpdateAfterBindStorageBuffers: number; readonly maxDescriptorSetUpdateAfterBindStorageBuffersDynamic: number; readonly maxDescriptorSetUpdateAfterBindSampledImages: number; readonly maxDescriptorSetUpdateAfterBindStorageImages: number; readonly maxDescriptorSetUpdateAfterBindInputAttachments: number; } /** ## VkPhysicalDeviceDescriptorIndexingFeaturesEXT ## */ interface VkPhysicalDeviceDescriptorIndexingFeaturesEXTInitializer { sType?: VkStructureType; pNext?: null; shaderInputAttachmentArrayDynamicIndexing?: number; shaderUniformTexelBufferArrayDynamicIndexing?: number; shaderStorageTexelBufferArrayDynamicIndexing?: number; shaderUniformBufferArrayNonUniformIndexing?: number; shaderSampledImageArrayNonUniformIndexing?: number; shaderStorageBufferArrayNonUniformIndexing?: number; shaderStorageImageArrayNonUniformIndexing?: number; shaderInputAttachmentArrayNonUniformIndexing?: number; shaderUniformTexelBufferArrayNonUniformIndexing?: number; shaderStorageTexelBufferArrayNonUniformIndexing?: number; descriptorBindingUniformBufferUpdateAfterBind?: number; descriptorBindingSampledImageUpdateAfterBind?: number; descriptorBindingStorageImageUpdateAfterBind?: number; descriptorBindingStorageBufferUpdateAfterBind?: number; descriptorBindingUniformTexelBufferUpdateAfterBind?: number; descriptorBindingStorageTexelBufferUpdateAfterBind?: number; descriptorBindingUpdateUnusedWhilePending?: number; descriptorBindingPartiallyBound?: number; descriptorBindingVariableDescriptorCount?: number; runtimeDescriptorArray?: number; } declare var VkPhysicalDeviceDescriptorIndexingFeaturesEXT: { prototype: VkPhysicalDeviceDescriptorIndexingFeaturesEXT; new(param?: VkPhysicalDeviceDescriptorIndexingFeaturesEXTInitializer | null): VkPhysicalDeviceDescriptorIndexingFeaturesEXT; sType: VkStructureType; pNext: null; shaderInputAttachmentArrayDynamicIndexing: number; shaderUniformTexelBufferArrayDynamicIndexing: number; shaderStorageTexelBufferArrayDynamicIndexing: number; shaderUniformBufferArrayNonUniformIndexing: number; shaderSampledImageArrayNonUniformIndexing: number; shaderStorageBufferArrayNonUniformIndexing: number; shaderStorageImageArrayNonUniformIndexing: number; shaderInputAttachmentArrayNonUniformIndexing: number; shaderUniformTexelBufferArrayNonUniformIndexing: number; shaderStorageTexelBufferArrayNonUniformIndexing: number; descriptorBindingUniformBufferUpdateAfterBind: number; descriptorBindingSampledImageUpdateAfterBind: number; descriptorBindingStorageImageUpdateAfterBind: number; descriptorBindingStorageBufferUpdateAfterBind: number; descriptorBindingUniformTexelBufferUpdateAfterBind: number; descriptorBindingStorageTexelBufferUpdateAfterBind: number; descriptorBindingUpdateUnusedWhilePending: number; descriptorBindingPartiallyBound: number; descriptorBindingVariableDescriptorCount: number; runtimeDescriptorArray: number; } export interface VkPhysicalDeviceDescriptorIndexingFeaturesEXT { sType: VkStructureType; pNext: null; shaderInputAttachmentArrayDynamicIndexing: number; shaderUniformTexelBufferArrayDynamicIndexing: number; shaderStorageTexelBufferArrayDynamicIndexing: number; shaderUniformBufferArrayNonUniformIndexing: number; shaderSampledImageArrayNonUniformIndexing: number; shaderStorageBufferArrayNonUniformIndexing: number; shaderStorageImageArrayNonUniformIndexing: number; shaderInputAttachmentArrayNonUniformIndexing: number; shaderUniformTexelBufferArrayNonUniformIndexing: number; shaderStorageTexelBufferArrayNonUniformIndexing: number; descriptorBindingUniformBufferUpdateAfterBind: number; descriptorBindingSampledImageUpdateAfterBind: number; descriptorBindingStorageImageUpdateAfterBind: number; descriptorBindingStorageBufferUpdateAfterBind: number; descriptorBindingUniformTexelBufferUpdateAfterBind: number; descriptorBindingStorageTexelBufferUpdateAfterBind: number; descriptorBindingUpdateUnusedWhilePending: number; descriptorBindingPartiallyBound: number; descriptorBindingVariableDescriptorCount: number; runtimeDescriptorArray: number; } /** ## VkPipelineRasterizationConservativeStateCreateInfoEXT ## */ interface VkPipelineRasterizationConservativeStateCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; flags?: null; conservativeRasterizationMode?: VkConservativeRasterizationModeEXT; extraPrimitiveOverestimationSize?: number; } declare var VkPipelineRasterizationConservativeStateCreateInfoEXT: { prototype: VkPipelineRasterizationConservativeStateCreateInfoEXT; new(param?: VkPipelineRasterizationConservativeStateCreateInfoEXTInitializer | null): VkPipelineRasterizationConservativeStateCreateInfoEXT; sType: VkStructureType; pNext: null; flags: null; conservativeRasterizationMode: VkConservativeRasterizationModeEXT; extraPrimitiveOverestimationSize: number; } export interface VkPipelineRasterizationConservativeStateCreateInfoEXT { sType: VkStructureType; pNext: null; flags: null; conservativeRasterizationMode: VkConservativeRasterizationModeEXT; extraPrimitiveOverestimationSize: number; } /** ## VkPhysicalDeviceShaderCorePropertiesAMD ## */ interface VkPhysicalDeviceShaderCorePropertiesAMDInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly shaderEngineCount?: number; readonly shaderArraysPerEngineCount?: number; readonly computeUnitsPerShaderArray?: number; readonly simdPerComputeUnit?: number; readonly wavefrontsPerSimd?: number; readonly wavefrontSize?: number; readonly sgprsPerSimd?: number; readonly minSgprAllocation?: number; readonly maxSgprAllocation?: number; readonly sgprAllocationGranularity?: number; readonly vgprsPerSimd?: number; readonly minVgprAllocation?: number; readonly maxVgprAllocation?: number; readonly vgprAllocationGranularity?: number; } declare var VkPhysicalDeviceShaderCorePropertiesAMD: { prototype: VkPhysicalDeviceShaderCorePropertiesAMD; new(param?: VkPhysicalDeviceShaderCorePropertiesAMDInitializer | null): VkPhysicalDeviceShaderCorePropertiesAMD; readonly sType: VkStructureType; readonly pNext: null; readonly shaderEngineCount: number; readonly shaderArraysPerEngineCount: number; readonly computeUnitsPerShaderArray: number; readonly simdPerComputeUnit: number; readonly wavefrontsPerSimd: number; readonly wavefrontSize: number; readonly sgprsPerSimd: number; readonly minSgprAllocation: number; readonly maxSgprAllocation: number; readonly sgprAllocationGranularity: number; readonly vgprsPerSimd: number; readonly minVgprAllocation: number; readonly maxVgprAllocation: number; readonly vgprAllocationGranularity: number; } export interface VkPhysicalDeviceShaderCorePropertiesAMD { readonly sType: VkStructureType; readonly pNext: null; readonly shaderEngineCount: number; readonly shaderArraysPerEngineCount: number; readonly computeUnitsPerShaderArray: number; readonly simdPerComputeUnit: number; readonly wavefrontsPerSimd: number; readonly wavefrontSize: number; readonly sgprsPerSimd: number; readonly minSgprAllocation: number; readonly maxSgprAllocation: number; readonly sgprAllocationGranularity: number; readonly vgprsPerSimd: number; readonly minVgprAllocation: number; readonly maxVgprAllocation: number; readonly vgprAllocationGranularity: number; } /** ## VkCalibratedTimestampInfoEXT ## */ interface VkCalibratedTimestampInfoEXTInitializer { sType?: VkStructureType; pNext?: null; timeDomain?: VkTimeDomainEXT; } declare var VkCalibratedTimestampInfoEXT: { prototype: VkCalibratedTimestampInfoEXT; new(param?: VkCalibratedTimestampInfoEXTInitializer | null): VkCalibratedTimestampInfoEXT; sType: VkStructureType; pNext: null; timeDomain: VkTimeDomainEXT; } export interface VkCalibratedTimestampInfoEXT { sType: VkStructureType; pNext: null; timeDomain: VkTimeDomainEXT; } /** ## VkPhysicalDeviceConservativeRasterizationPropertiesEXT ## */ interface VkPhysicalDeviceConservativeRasterizationPropertiesEXTInitializer { sType?: VkStructureType; pNext?: null; primitiveOverestimationSize?: number; maxExtraPrimitiveOverestimationSize?: number; extraPrimitiveOverestimationSizeGranularity?: number; primitiveUnderestimation?: number; conservativePointAndLineRasterization?: number; degenerateTrianglesRasterized?: number; degenerateLinesRasterized?: number; fullyCoveredFragmentShaderInputVariable?: number; conservativeRasterizationPostDepthCoverage?: number; } declare var VkPhysicalDeviceConservativeRasterizationPropertiesEXT: { prototype: VkPhysicalDeviceConservativeRasterizationPropertiesEXT; new(param?: VkPhysicalDeviceConservativeRasterizationPropertiesEXTInitializer | null): VkPhysicalDeviceConservativeRasterizationPropertiesEXT; sType: VkStructureType; pNext: null; primitiveOverestimationSize: number; maxExtraPrimitiveOverestimationSize: number; extraPrimitiveOverestimationSizeGranularity: number; primitiveUnderestimation: number; conservativePointAndLineRasterization: number; degenerateTrianglesRasterized: number; degenerateLinesRasterized: number; fullyCoveredFragmentShaderInputVariable: number; conservativeRasterizationPostDepthCoverage: number; } export interface VkPhysicalDeviceConservativeRasterizationPropertiesEXT { sType: VkStructureType; pNext: null; primitiveOverestimationSize: number; maxExtraPrimitiveOverestimationSize: number; extraPrimitiveOverestimationSizeGranularity: number; primitiveUnderestimation: number; conservativePointAndLineRasterization: number; degenerateTrianglesRasterized: number; degenerateLinesRasterized: number; fullyCoveredFragmentShaderInputVariable: number; conservativeRasterizationPostDepthCoverage: number; } /** ## VkPhysicalDeviceExternalMemoryHostPropertiesEXT ## */ interface VkPhysicalDeviceExternalMemoryHostPropertiesEXTInitializer { sType?: VkStructureType; pNext?: null; minImportedHostPointerAlignment?: number; } declare var VkPhysicalDeviceExternalMemoryHostPropertiesEXT: { prototype: VkPhysicalDeviceExternalMemoryHostPropertiesEXT; new(param?: VkPhysicalDeviceExternalMemoryHostPropertiesEXTInitializer | null): VkPhysicalDeviceExternalMemoryHostPropertiesEXT; sType: VkStructureType; pNext: null; minImportedHostPointerAlignment: number; } export interface VkPhysicalDeviceExternalMemoryHostPropertiesEXT { sType: VkStructureType; pNext: null; minImportedHostPointerAlignment: number; } /** ## VkMemoryHostPointerPropertiesEXT ## */ interface VkMemoryHostPointerPropertiesEXTInitializer { sType?: VkStructureType; pNext?: null; memoryTypeBits?: number; } declare var VkMemoryHostPointerPropertiesEXT: { prototype: VkMemoryHostPointerPropertiesEXT; new(param?: VkMemoryHostPointerPropertiesEXTInitializer | null): VkMemoryHostPointerPropertiesEXT; sType: VkStructureType; pNext: null; memoryTypeBits: number; } export interface VkMemoryHostPointerPropertiesEXT { sType: VkStructureType; pNext: null; memoryTypeBits: number; } /** ## VkImportMemoryHostPointerInfoEXT ## */ interface VkImportMemoryHostPointerInfoEXTInitializer { sType?: VkStructureType; pNext?: null; handleType?: VkExternalMemoryHandleTypeFlagBits; pHostPointer?: ArrayBuffer | null; } declare var VkImportMemoryHostPointerInfoEXT: { prototype: VkImportMemoryHostPointerInfoEXT; new(param?: VkImportMemoryHostPointerInfoEXTInitializer | null): VkImportMemoryHostPointerInfoEXT; sType: VkStructureType; pNext: null; handleType: VkExternalMemoryHandleTypeFlagBits; pHostPointer: ArrayBuffer | null; } export interface VkImportMemoryHostPointerInfoEXT { sType: VkStructureType; pNext: null; handleType: VkExternalMemoryHandleTypeFlagBits; pHostPointer: ArrayBuffer | null; } /** ## VkDebugUtilsMessengerCallbackDataEXT ## */ interface VkDebugUtilsMessengerCallbackDataEXTInitializer { sType?: VkStructureType; pNext?: null; flags?: null; pMessageIdName?: string | null; messageIdNumber?: number; pMessage?: string | null; queueLabelCount?: number; pQueueLabels?: VkDebugUtilsLabelEXT[] | null; cmdBufLabelCount?: number; pCmdBufLabels?: VkDebugUtilsLabelEXT[] | null; objectCount?: number; pObjects?: VkDebugUtilsObjectNameInfoEXT[] | null; } declare var VkDebugUtilsMessengerCallbackDataEXT: { prototype: VkDebugUtilsMessengerCallbackDataEXT; new(param?: VkDebugUtilsMessengerCallbackDataEXTInitializer | null): VkDebugUtilsMessengerCallbackDataEXT; sType: VkStructureType; pNext: null; flags: null; pMessageIdName: string | null; messageIdNumber: number; pMessage: string | null; queueLabelCount: number; pQueueLabels: VkDebugUtilsLabelEXT[] | null; cmdBufLabelCount: number; pCmdBufLabels: VkDebugUtilsLabelEXT[] | null; objectCount: number; pObjects: VkDebugUtilsObjectNameInfoEXT[] | null; } export interface VkDebugUtilsMessengerCallbackDataEXT { sType: VkStructureType; pNext: null; flags: null; pMessageIdName: string | null; messageIdNumber: number; pMessage: string | null; queueLabelCount: number; pQueueLabels: VkDebugUtilsLabelEXT[] | null; cmdBufLabelCount: number; pCmdBufLabels: VkDebugUtilsLabelEXT[] | null; objectCount: number; pObjects: VkDebugUtilsObjectNameInfoEXT[] | null; } /** ## VkDebugUtilsMessengerCreateInfoEXT ## */ interface VkDebugUtilsMessengerCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; flags?: null; messageSeverity?: VkDebugUtilsMessageSeverityFlagBitsEXT; messageType?: VkDebugUtilsMessageTypeFlagBitsEXT; pfnUserCallback?: null; pUserData?: ArrayBuffer | null; } declare var VkDebugUtilsMessengerCreateInfoEXT: { prototype: VkDebugUtilsMessengerCreateInfoEXT; new(param?: VkDebugUtilsMessengerCreateInfoEXTInitializer | null): VkDebugUtilsMessengerCreateInfoEXT; sType: VkStructureType; pNext: null; flags: null; messageSeverity: VkDebugUtilsMessageSeverityFlagBitsEXT; messageType: VkDebugUtilsMessageTypeFlagBitsEXT; pfnUserCallback: null; pUserData: ArrayBuffer | null; } export interface VkDebugUtilsMessengerCreateInfoEXT { sType: VkStructureType; pNext: null; flags: null; messageSeverity: VkDebugUtilsMessageSeverityFlagBitsEXT; messageType: VkDebugUtilsMessageTypeFlagBitsEXT; pfnUserCallback: null; pUserData: ArrayBuffer | null; } /** ## VkDebugUtilsLabelEXT ## */ interface VkDebugUtilsLabelEXTInitializer { sType?: VkStructureType; pNext?: null; pLabelName?: string | null; color?: number[] | null; } declare var VkDebugUtilsLabelEXT: { prototype: VkDebugUtilsLabelEXT; new(param?: VkDebugUtilsLabelEXTInitializer | null): VkDebugUtilsLabelEXT; sType: VkStructureType; pNext: null; pLabelName: string | null; color: number[] | null; } export interface VkDebugUtilsLabelEXT { sType: VkStructureType; pNext: null; pLabelName: string | null; color: number[] | null; } /** ## VkDebugUtilsObjectTagInfoEXT ## */ interface VkDebugUtilsObjectTagInfoEXTInitializer { sType?: VkStructureType; pNext?: null; objectType?: VkObjectType; objectHandle?: number; tagName?: number; tagSize?: number; pTag?: ArrayBuffer | null; } declare var VkDebugUtilsObjectTagInfoEXT: { prototype: VkDebugUtilsObjectTagInfoEXT; new(param?: VkDebugUtilsObjectTagInfoEXTInitializer | null): VkDebugUtilsObjectTagInfoEXT; sType: VkStructureType; pNext: null; objectType: VkObjectType; objectHandle: number; tagName: number; tagSize: number; pTag: ArrayBuffer | null; } export interface VkDebugUtilsObjectTagInfoEXT { sType: VkStructureType; pNext: null; objectType: VkObjectType; objectHandle: number; tagName: number; tagSize: number; pTag: ArrayBuffer | null; } /** ## VkDebugUtilsObjectNameInfoEXT ## */ interface VkDebugUtilsObjectNameInfoEXTInitializer { sType?: VkStructureType; pNext?: null; objectType?: VkObjectType; objectHandle?: number; pObjectName?: string | null; } declare var VkDebugUtilsObjectNameInfoEXT: { prototype: VkDebugUtilsObjectNameInfoEXT; new(param?: VkDebugUtilsObjectNameInfoEXTInitializer | null): VkDebugUtilsObjectNameInfoEXT; sType: VkStructureType; pNext: null; objectType: VkObjectType; objectHandle: number; pObjectName: string | null; } export interface VkDebugUtilsObjectNameInfoEXT { sType: VkStructureType; pNext: null; objectType: VkObjectType; objectHandle: number; pObjectName: string | null; } /** ## VkDeviceQueueGlobalPriorityCreateInfoEXT ## */ interface VkDeviceQueueGlobalPriorityCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; globalPriority?: VkQueueGlobalPriorityEXT; } declare var VkDeviceQueueGlobalPriorityCreateInfoEXT: { prototype: VkDeviceQueueGlobalPriorityCreateInfoEXT; new(param?: VkDeviceQueueGlobalPriorityCreateInfoEXTInitializer | null): VkDeviceQueueGlobalPriorityCreateInfoEXT; sType: VkStructureType; pNext: null; globalPriority: VkQueueGlobalPriorityEXT; } export interface VkDeviceQueueGlobalPriorityCreateInfoEXT { sType: VkStructureType; pNext: null; globalPriority: VkQueueGlobalPriorityEXT; } /** ## VkShaderStatisticsInfoAMD ## */ interface VkShaderStatisticsInfoAMDInitializer { readonly shaderStageMask?: VkShaderStageFlagBits; readonly resourceUsage?: VkShaderResourceUsageAMD | null; readonly numPhysicalVgprs?: number; readonly numPhysicalSgprs?: number; readonly numAvailableVgprs?: number; readonly numAvailableSgprs?: number; readonly computeWorkGroupSize?: number[] | null; } declare var VkShaderStatisticsInfoAMD: { prototype: VkShaderStatisticsInfoAMD; new(param?: VkShaderStatisticsInfoAMDInitializer | null): VkShaderStatisticsInfoAMD; readonly shaderStageMask: VkShaderStageFlagBits; readonly resourceUsage: VkShaderResourceUsageAMD | null; readonly numPhysicalVgprs: number; readonly numPhysicalSgprs: number; readonly numAvailableVgprs: number; readonly numAvailableSgprs: number; readonly computeWorkGroupSize: number[] | null; } export interface VkShaderStatisticsInfoAMD { readonly shaderStageMask: VkShaderStageFlagBits; readonly resourceUsage: VkShaderResourceUsageAMD | null; readonly numPhysicalVgprs: number; readonly numPhysicalSgprs: number; readonly numAvailableVgprs: number; readonly numAvailableSgprs: number; readonly computeWorkGroupSize: number[] | null; } /** ## VkShaderResourceUsageAMD ## */ interface VkShaderResourceUsageAMDInitializer { readonly numUsedVgprs?: number; readonly numUsedSgprs?: number; readonly ldsSizePerLocalWorkGroup?: number; readonly ldsUsageSizeInBytes?: number; readonly scratchMemUsageInBytes?: number; } declare var VkShaderResourceUsageAMD: { prototype: VkShaderResourceUsageAMD; new(param?: VkShaderResourceUsageAMDInitializer | null): VkShaderResourceUsageAMD; readonly numUsedVgprs: number; readonly numUsedSgprs: number; readonly ldsSizePerLocalWorkGroup: number; readonly ldsUsageSizeInBytes: number; readonly scratchMemUsageInBytes: number; } export interface VkShaderResourceUsageAMD { readonly numUsedVgprs: number; readonly numUsedSgprs: number; readonly ldsSizePerLocalWorkGroup: number; readonly ldsUsageSizeInBytes: number; readonly scratchMemUsageInBytes: number; } /** ## VkPhysicalDeviceFloatControlsPropertiesKHR ## */ interface VkPhysicalDeviceFloatControlsPropertiesKHRInitializer { sType?: VkStructureType; pNext?: null; separateDenormSettings?: number; separateRoundingModeSettings?: number; shaderSignedZeroInfNanPreserveFloat16?: number; shaderSignedZeroInfNanPreserveFloat32?: number; shaderSignedZeroInfNanPreserveFloat64?: number; shaderDenormPreserveFloat16?: number; shaderDenormPreserveFloat32?: number; shaderDenormPreserveFloat64?: number; shaderDenormFlushToZeroFloat16?: number; shaderDenormFlushToZeroFloat32?: number; shaderDenormFlushToZeroFloat64?: number; shaderRoundingModeRTEFloat16?: number; shaderRoundingModeRTEFloat32?: number; shaderRoundingModeRTEFloat64?: number; shaderRoundingModeRTZFloat16?: number; shaderRoundingModeRTZFloat32?: number; shaderRoundingModeRTZFloat64?: number; } declare var VkPhysicalDeviceFloatControlsPropertiesKHR: { prototype: VkPhysicalDeviceFloatControlsPropertiesKHR; new(param?: VkPhysicalDeviceFloatControlsPropertiesKHRInitializer | null): VkPhysicalDeviceFloatControlsPropertiesKHR; sType: VkStructureType; pNext: null; separateDenormSettings: number; separateRoundingModeSettings: number; shaderSignedZeroInfNanPreserveFloat16: number; shaderSignedZeroInfNanPreserveFloat32: number; shaderSignedZeroInfNanPreserveFloat64: number; shaderDenormPreserveFloat16: number; shaderDenormPreserveFloat32: number; shaderDenormPreserveFloat64: number; shaderDenormFlushToZeroFloat16: number; shaderDenormFlushToZeroFloat32: number; shaderDenormFlushToZeroFloat64: number; shaderRoundingModeRTEFloat16: number; shaderRoundingModeRTEFloat32: number; shaderRoundingModeRTEFloat64: number; shaderRoundingModeRTZFloat16: number; shaderRoundingModeRTZFloat32: number; shaderRoundingModeRTZFloat64: number; } export interface VkPhysicalDeviceFloatControlsPropertiesKHR { sType: VkStructureType; pNext: null; separateDenormSettings: number; separateRoundingModeSettings: number; shaderSignedZeroInfNanPreserveFloat16: number; shaderSignedZeroInfNanPreserveFloat32: number; shaderSignedZeroInfNanPreserveFloat64: number; shaderDenormPreserveFloat16: number; shaderDenormPreserveFloat32: number; shaderDenormPreserveFloat64: number; shaderDenormFlushToZeroFloat16: number; shaderDenormFlushToZeroFloat32: number; shaderDenormFlushToZeroFloat64: number; shaderRoundingModeRTEFloat16: number; shaderRoundingModeRTEFloat32: number; shaderRoundingModeRTEFloat64: number; shaderRoundingModeRTZFloat16: number; shaderRoundingModeRTZFloat32: number; shaderRoundingModeRTZFloat64: number; } /** ## VkPhysicalDeviceFloat16Int8FeaturesKHR ## */ interface VkPhysicalDeviceFloat16Int8FeaturesKHRInitializer { sType?: VkStructureType; pNext?: null; shaderFloat16?: number; shaderInt8?: number; } declare var VkPhysicalDeviceFloat16Int8FeaturesKHR: { prototype: VkPhysicalDeviceFloat16Int8FeaturesKHR; new(param?: VkPhysicalDeviceFloat16Int8FeaturesKHRInitializer | null): VkPhysicalDeviceFloat16Int8FeaturesKHR; sType: VkStructureType; pNext: null; shaderFloat16: number; shaderInt8: number; } export interface VkPhysicalDeviceFloat16Int8FeaturesKHR { sType: VkStructureType; pNext: null; shaderFloat16: number; shaderInt8: number; } /** ## VkPhysicalDeviceShaderDrawParameterFeatures ## */ interface VkPhysicalDeviceShaderDrawParameterFeaturesInitializer { sType?: VkStructureType; pNext?: null; shaderDrawParameters?: number; } declare var VkPhysicalDeviceShaderDrawParameterFeatures: { prototype: VkPhysicalDeviceShaderDrawParameterFeatures; new(param?: VkPhysicalDeviceShaderDrawParameterFeaturesInitializer | null): VkPhysicalDeviceShaderDrawParameterFeatures; sType: VkStructureType; pNext: null; shaderDrawParameters: number; } export interface VkPhysicalDeviceShaderDrawParameterFeatures { sType: VkStructureType; pNext: null; shaderDrawParameters: number; } /** ## VkDescriptorSetLayoutSupportKHR ## */ interface VkDescriptorSetLayoutSupportKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly supported?: number; } declare var VkDescriptorSetLayoutSupportKHR: { prototype: VkDescriptorSetLayoutSupportKHR; new(param?: VkDescriptorSetLayoutSupportKHRInitializer | null): VkDescriptorSetLayoutSupportKHR; readonly sType: VkStructureType; readonly pNext: null; readonly supported: number; } export interface VkDescriptorSetLayoutSupportKHR { readonly sType: VkStructureType; readonly pNext: null; readonly supported: number; } /** ## VkDescriptorSetLayoutSupport ## */ interface VkDescriptorSetLayoutSupportInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly supported?: number; } declare var VkDescriptorSetLayoutSupport: { prototype: VkDescriptorSetLayoutSupport; new(param?: VkDescriptorSetLayoutSupportInitializer | null): VkDescriptorSetLayoutSupport; readonly sType: VkStructureType; readonly pNext: null; readonly supported: number; } export interface VkDescriptorSetLayoutSupport { readonly sType: VkStructureType; readonly pNext: null; readonly supported: number; } /** ## VkPhysicalDeviceMaintenance3PropertiesKHR ## */ interface VkPhysicalDeviceMaintenance3PropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly maxPerSetDescriptors?: number; readonly maxMemoryAllocationSize?: number; } declare var VkPhysicalDeviceMaintenance3PropertiesKHR: { prototype: VkPhysicalDeviceMaintenance3PropertiesKHR; new(param?: VkPhysicalDeviceMaintenance3PropertiesKHRInitializer | null): VkPhysicalDeviceMaintenance3PropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly maxPerSetDescriptors: number; readonly maxMemoryAllocationSize: number; } export interface VkPhysicalDeviceMaintenance3PropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly maxPerSetDescriptors: number; readonly maxMemoryAllocationSize: number; } /** ## VkPhysicalDeviceMaintenance3Properties ## */ interface VkPhysicalDeviceMaintenance3PropertiesInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly maxPerSetDescriptors?: number; readonly maxMemoryAllocationSize?: number; } declare var VkPhysicalDeviceMaintenance3Properties: { prototype: VkPhysicalDeviceMaintenance3Properties; new(param?: VkPhysicalDeviceMaintenance3PropertiesInitializer | null): VkPhysicalDeviceMaintenance3Properties; readonly sType: VkStructureType; readonly pNext: null; readonly maxPerSetDescriptors: number; readonly maxMemoryAllocationSize: number; } export interface VkPhysicalDeviceMaintenance3Properties { readonly sType: VkStructureType; readonly pNext: null; readonly maxPerSetDescriptors: number; readonly maxMemoryAllocationSize: number; } /** ## VkShaderModuleValidationCacheCreateInfoEXT ## */ interface VkShaderModuleValidationCacheCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; validationCache?: VkValidationCacheEXT | null; } declare var VkShaderModuleValidationCacheCreateInfoEXT: { prototype: VkShaderModuleValidationCacheCreateInfoEXT; new(param?: VkShaderModuleValidationCacheCreateInfoEXTInitializer | null): VkShaderModuleValidationCacheCreateInfoEXT; sType: VkStructureType; pNext: null; validationCache: VkValidationCacheEXT | null; } export interface VkShaderModuleValidationCacheCreateInfoEXT { sType: VkStructureType; pNext: null; validationCache: VkValidationCacheEXT | null; } /** ## VkValidationCacheCreateInfoEXT ## */ interface VkValidationCacheCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; flags?: null; initialDataSize?: number; pInitialData?: ArrayBuffer | null; } declare var VkValidationCacheCreateInfoEXT: { prototype: VkValidationCacheCreateInfoEXT; new(param?: VkValidationCacheCreateInfoEXTInitializer | null): VkValidationCacheCreateInfoEXT; sType: VkStructureType; pNext: null; flags: null; initialDataSize: number; pInitialData: ArrayBuffer | null; } export interface VkValidationCacheCreateInfoEXT { sType: VkStructureType; pNext: null; flags: null; initialDataSize: number; pInitialData: ArrayBuffer | null; } /** ## VkImageFormatListCreateInfoKHR ## */ interface VkImageFormatListCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; viewFormatCount?: number; pViewFormats?: Int32Array | null; } declare var VkImageFormatListCreateInfoKHR: { prototype: VkImageFormatListCreateInfoKHR; new(param?: VkImageFormatListCreateInfoKHRInitializer | null): VkImageFormatListCreateInfoKHR; sType: VkStructureType; pNext: null; viewFormatCount: number; pViewFormats: Int32Array | null; } export interface VkImageFormatListCreateInfoKHR { sType: VkStructureType; pNext: null; viewFormatCount: number; pViewFormats: Int32Array | null; } /** ## VkPipelineCoverageModulationStateCreateInfoNV ## */ interface VkPipelineCoverageModulationStateCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; flags?: null; coverageModulationMode?: VkCoverageModulationModeNV; coverageModulationTableEnable?: number; coverageModulationTableCount?: number; pCoverageModulationTable?: Float32Array | null; } declare var VkPipelineCoverageModulationStateCreateInfoNV: { prototype: VkPipelineCoverageModulationStateCreateInfoNV; new(param?: VkPipelineCoverageModulationStateCreateInfoNVInitializer | null): VkPipelineCoverageModulationStateCreateInfoNV; sType: VkStructureType; pNext: null; flags: null; coverageModulationMode: VkCoverageModulationModeNV; coverageModulationTableEnable: number; coverageModulationTableCount: number; pCoverageModulationTable: Float32Array | null; } export interface VkPipelineCoverageModulationStateCreateInfoNV { sType: VkStructureType; pNext: null; flags: null; coverageModulationMode: VkCoverageModulationModeNV; coverageModulationTableEnable: number; coverageModulationTableCount: number; pCoverageModulationTable: Float32Array | null; } /** ## VkDescriptorPoolInlineUniformBlockCreateInfoEXT ## */ interface VkDescriptorPoolInlineUniformBlockCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; maxInlineUniformBlockBindings?: number; } declare var VkDescriptorPoolInlineUniformBlockCreateInfoEXT: { prototype: VkDescriptorPoolInlineUniformBlockCreateInfoEXT; new(param?: VkDescriptorPoolInlineUniformBlockCreateInfoEXTInitializer | null): VkDescriptorPoolInlineUniformBlockCreateInfoEXT; sType: VkStructureType; pNext: null; maxInlineUniformBlockBindings: number; } export interface VkDescriptorPoolInlineUniformBlockCreateInfoEXT { sType: VkStructureType; pNext: null; maxInlineUniformBlockBindings: number; } /** ## VkWriteDescriptorSetInlineUniformBlockEXT ## */ interface VkWriteDescriptorSetInlineUniformBlockEXTInitializer { sType?: VkStructureType; pNext?: null; dataSize?: number; pData?: ArrayBuffer | null; } declare var VkWriteDescriptorSetInlineUniformBlockEXT: { prototype: VkWriteDescriptorSetInlineUniformBlockEXT; new(param?: VkWriteDescriptorSetInlineUniformBlockEXTInitializer | null): VkWriteDescriptorSetInlineUniformBlockEXT; sType: VkStructureType; pNext: null; dataSize: number; pData: ArrayBuffer | null; } export interface VkWriteDescriptorSetInlineUniformBlockEXT { sType: VkStructureType; pNext: null; dataSize: number; pData: ArrayBuffer | null; } /** ## VkPhysicalDeviceInlineUniformBlockPropertiesEXT ## */ interface VkPhysicalDeviceInlineUniformBlockPropertiesEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly maxInlineUniformBlockSize?: number; readonly maxPerStageDescriptorInlineUniformBlocks?: number; readonly maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks?: number; readonly maxDescriptorSetInlineUniformBlocks?: number; readonly maxDescriptorSetUpdateAfterBindInlineUniformBlocks?: number; } declare var VkPhysicalDeviceInlineUniformBlockPropertiesEXT: { prototype: VkPhysicalDeviceInlineUniformBlockPropertiesEXT; new(param?: VkPhysicalDeviceInlineUniformBlockPropertiesEXTInitializer | null): VkPhysicalDeviceInlineUniformBlockPropertiesEXT; readonly sType: VkStructureType; readonly pNext: null; readonly maxInlineUniformBlockSize: number; readonly maxPerStageDescriptorInlineUniformBlocks: number; readonly maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks: number; readonly maxDescriptorSetInlineUniformBlocks: number; readonly maxDescriptorSetUpdateAfterBindInlineUniformBlocks: number; } export interface VkPhysicalDeviceInlineUniformBlockPropertiesEXT { readonly sType: VkStructureType; readonly pNext: null; readonly maxInlineUniformBlockSize: number; readonly maxPerStageDescriptorInlineUniformBlocks: number; readonly maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks: number; readonly maxDescriptorSetInlineUniformBlocks: number; readonly maxDescriptorSetUpdateAfterBindInlineUniformBlocks: number; } /** ## VkPhysicalDeviceInlineUniformBlockFeaturesEXT ## */ interface VkPhysicalDeviceInlineUniformBlockFeaturesEXTInitializer { sType?: VkStructureType; pNext?: null; inlineUniformBlock?: number; descriptorBindingInlineUniformBlockUpdateAfterBind?: number; } declare var VkPhysicalDeviceInlineUniformBlockFeaturesEXT: { prototype: VkPhysicalDeviceInlineUniformBlockFeaturesEXT; new(param?: VkPhysicalDeviceInlineUniformBlockFeaturesEXTInitializer | null): VkPhysicalDeviceInlineUniformBlockFeaturesEXT; sType: VkStructureType; pNext: null; inlineUniformBlock: number; descriptorBindingInlineUniformBlockUpdateAfterBind: number; } export interface VkPhysicalDeviceInlineUniformBlockFeaturesEXT { sType: VkStructureType; pNext: null; inlineUniformBlock: number; descriptorBindingInlineUniformBlockUpdateAfterBind: number; } /** ## VkPipelineColorBlendAdvancedStateCreateInfoEXT ## */ interface VkPipelineColorBlendAdvancedStateCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; srcPremultiplied?: number; dstPremultiplied?: number; blendOverlap?: VkBlendOverlapEXT; } declare var VkPipelineColorBlendAdvancedStateCreateInfoEXT: { prototype: VkPipelineColorBlendAdvancedStateCreateInfoEXT; new(param?: VkPipelineColorBlendAdvancedStateCreateInfoEXTInitializer | null): VkPipelineColorBlendAdvancedStateCreateInfoEXT; sType: VkStructureType; pNext: null; srcPremultiplied: number; dstPremultiplied: number; blendOverlap: VkBlendOverlapEXT; } export interface VkPipelineColorBlendAdvancedStateCreateInfoEXT { sType: VkStructureType; pNext: null; srcPremultiplied: number; dstPremultiplied: number; blendOverlap: VkBlendOverlapEXT; } /** ## VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT ## */ interface VkPhysicalDeviceBlendOperationAdvancedPropertiesEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly advancedBlendMaxColorAttachments?: number; readonly advancedBlendIndependentBlend?: number; readonly advancedBlendNonPremultipliedSrcColor?: number; readonly advancedBlendNonPremultipliedDstColor?: number; readonly advancedBlendCorrelatedOverlap?: number; readonly advancedBlendAllOperations?: number; } declare var VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT: { prototype: VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT; new(param?: VkPhysicalDeviceBlendOperationAdvancedPropertiesEXTInitializer | null): VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT; readonly sType: VkStructureType; readonly pNext: null; readonly advancedBlendMaxColorAttachments: number; readonly advancedBlendIndependentBlend: number; readonly advancedBlendNonPremultipliedSrcColor: number; readonly advancedBlendNonPremultipliedDstColor: number; readonly advancedBlendCorrelatedOverlap: number; readonly advancedBlendAllOperations: number; } export interface VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT { readonly sType: VkStructureType; readonly pNext: null; readonly advancedBlendMaxColorAttachments: number; readonly advancedBlendIndependentBlend: number; readonly advancedBlendNonPremultipliedSrcColor: number; readonly advancedBlendNonPremultipliedDstColor: number; readonly advancedBlendCorrelatedOverlap: number; readonly advancedBlendAllOperations: number; } /** ## VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT ## */ interface VkPhysicalDeviceBlendOperationAdvancedFeaturesEXTInitializer { sType?: VkStructureType; pNext?: null; advancedBlendCoherentOperations?: number; } declare var VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT: { prototype: VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT; new(param?: VkPhysicalDeviceBlendOperationAdvancedFeaturesEXTInitializer | null): VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT; sType: VkStructureType; pNext: null; advancedBlendCoherentOperations: number; } export interface VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT { sType: VkStructureType; pNext: null; advancedBlendCoherentOperations: number; } /** ## VkSamplerReductionModeCreateInfoEXT ## */ interface VkSamplerReductionModeCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; reductionMode?: VkSamplerReductionModeEXT; } declare var VkSamplerReductionModeCreateInfoEXT: { prototype: VkSamplerReductionModeCreateInfoEXT; new(param?: VkSamplerReductionModeCreateInfoEXTInitializer | null): VkSamplerReductionModeCreateInfoEXT; sType: VkStructureType; pNext: null; reductionMode: VkSamplerReductionModeEXT; } export interface VkSamplerReductionModeCreateInfoEXT { sType: VkStructureType; pNext: null; reductionMode: VkSamplerReductionModeEXT; } /** ## VkMultisamplePropertiesEXT ## */ interface VkMultisamplePropertiesEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly maxSampleLocationGridSize?: VkExtent2D | null; } declare var VkMultisamplePropertiesEXT: { prototype: VkMultisamplePropertiesEXT; new(param?: VkMultisamplePropertiesEXTInitializer | null): VkMultisamplePropertiesEXT; readonly sType: VkStructureType; readonly pNext: null; readonly maxSampleLocationGridSize: VkExtent2D | null; } export interface VkMultisamplePropertiesEXT { readonly sType: VkStructureType; readonly pNext: null; readonly maxSampleLocationGridSize: VkExtent2D | null; } /** ## VkPhysicalDeviceSampleLocationsPropertiesEXT ## */ interface VkPhysicalDeviceSampleLocationsPropertiesEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly sampleLocationSampleCounts?: VkSampleCountFlagBits; readonly maxSampleLocationGridSize?: VkExtent2D | null; readonly sampleLocationCoordinateRange?: number[] | null; readonly sampleLocationSubPixelBits?: number; readonly variableSampleLocations?: number; } declare var VkPhysicalDeviceSampleLocationsPropertiesEXT: { prototype: VkPhysicalDeviceSampleLocationsPropertiesEXT; new(param?: VkPhysicalDeviceSampleLocationsPropertiesEXTInitializer | null): VkPhysicalDeviceSampleLocationsPropertiesEXT; readonly sType: VkStructureType; readonly pNext: null; readonly sampleLocationSampleCounts: VkSampleCountFlagBits; readonly maxSampleLocationGridSize: VkExtent2D | null; readonly sampleLocationCoordinateRange: number[] | null; readonly sampleLocationSubPixelBits: number; readonly variableSampleLocations: number; } export interface VkPhysicalDeviceSampleLocationsPropertiesEXT { readonly sType: VkStructureType; readonly pNext: null; readonly sampleLocationSampleCounts: VkSampleCountFlagBits; readonly maxSampleLocationGridSize: VkExtent2D | null; readonly sampleLocationCoordinateRange: number[] | null; readonly sampleLocationSubPixelBits: number; readonly variableSampleLocations: number; } /** ## VkPipelineSampleLocationsStateCreateInfoEXT ## */ interface VkPipelineSampleLocationsStateCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; sampleLocationsEnable?: number; sampleLocationsInfo?: VkSampleLocationsInfoEXT | null; } declare var VkPipelineSampleLocationsStateCreateInfoEXT: { prototype: VkPipelineSampleLocationsStateCreateInfoEXT; new(param?: VkPipelineSampleLocationsStateCreateInfoEXTInitializer | null): VkPipelineSampleLocationsStateCreateInfoEXT; sType: VkStructureType; pNext: null; sampleLocationsEnable: number; sampleLocationsInfo: VkSampleLocationsInfoEXT | null; } export interface VkPipelineSampleLocationsStateCreateInfoEXT { sType: VkStructureType; pNext: null; sampleLocationsEnable: number; sampleLocationsInfo: VkSampleLocationsInfoEXT | null; } /** ## VkRenderPassSampleLocationsBeginInfoEXT ## */ interface VkRenderPassSampleLocationsBeginInfoEXTInitializer { sType?: VkStructureType; pNext?: null; attachmentInitialSampleLocationsCount?: number; pAttachmentInitialSampleLocations?: VkAttachmentSampleLocationsEXT[] | null; postSubpassSampleLocationsCount?: number; pPostSubpassSampleLocations?: VkSubpassSampleLocationsEXT[] | null; } declare var VkRenderPassSampleLocationsBeginInfoEXT: { prototype: VkRenderPassSampleLocationsBeginInfoEXT; new(param?: VkRenderPassSampleLocationsBeginInfoEXTInitializer | null): VkRenderPassSampleLocationsBeginInfoEXT; sType: VkStructureType; pNext: null; attachmentInitialSampleLocationsCount: number; pAttachmentInitialSampleLocations: VkAttachmentSampleLocationsEXT[] | null; postSubpassSampleLocationsCount: number; pPostSubpassSampleLocations: VkSubpassSampleLocationsEXT[] | null; } export interface VkRenderPassSampleLocationsBeginInfoEXT { sType: VkStructureType; pNext: null; attachmentInitialSampleLocationsCount: number; pAttachmentInitialSampleLocations: VkAttachmentSampleLocationsEXT[] | null; postSubpassSampleLocationsCount: number; pPostSubpassSampleLocations: VkSubpassSampleLocationsEXT[] | null; } /** ## VkSubpassSampleLocationsEXT ## */ interface VkSubpassSampleLocationsEXTInitializer { subpassIndex?: number; sampleLocationsInfo?: VkSampleLocationsInfoEXT | null; } declare var VkSubpassSampleLocationsEXT: { prototype: VkSubpassSampleLocationsEXT; new(param?: VkSubpassSampleLocationsEXTInitializer | null): VkSubpassSampleLocationsEXT; subpassIndex: number; sampleLocationsInfo: VkSampleLocationsInfoEXT | null; } export interface VkSubpassSampleLocationsEXT { subpassIndex: number; sampleLocationsInfo: VkSampleLocationsInfoEXT | null; } /** ## VkAttachmentSampleLocationsEXT ## */ interface VkAttachmentSampleLocationsEXTInitializer { attachmentIndex?: number; sampleLocationsInfo?: VkSampleLocationsInfoEXT | null; } declare var VkAttachmentSampleLocationsEXT: { prototype: VkAttachmentSampleLocationsEXT; new(param?: VkAttachmentSampleLocationsEXTInitializer | null): VkAttachmentSampleLocationsEXT; attachmentIndex: number; sampleLocationsInfo: VkSampleLocationsInfoEXT | null; } export interface VkAttachmentSampleLocationsEXT { attachmentIndex: number; sampleLocationsInfo: VkSampleLocationsInfoEXT | null; } /** ## VkSampleLocationsInfoEXT ## */ interface VkSampleLocationsInfoEXTInitializer { sType?: VkStructureType; pNext?: null; sampleLocationsPerPixel?: VkSampleCountFlagBits; sampleLocationGridSize?: VkExtent2D | null; sampleLocationsCount?: number; pSampleLocations?: VkSampleLocationEXT[] | null; } declare var VkSampleLocationsInfoEXT: { prototype: VkSampleLocationsInfoEXT; new(param?: VkSampleLocationsInfoEXTInitializer | null): VkSampleLocationsInfoEXT; sType: VkStructureType; pNext: null; sampleLocationsPerPixel: VkSampleCountFlagBits; sampleLocationGridSize: VkExtent2D | null; sampleLocationsCount: number; pSampleLocations: VkSampleLocationEXT[] | null; } export interface VkSampleLocationsInfoEXT { sType: VkStructureType; pNext: null; sampleLocationsPerPixel: VkSampleCountFlagBits; sampleLocationGridSize: VkExtent2D | null; sampleLocationsCount: number; pSampleLocations: VkSampleLocationEXT[] | null; } /** ## VkSampleLocationEXT ## */ interface VkSampleLocationEXTInitializer { x?: number; y?: number; } declare var VkSampleLocationEXT: { prototype: VkSampleLocationEXT; new(param?: VkSampleLocationEXTInitializer | null): VkSampleLocationEXT; x: number; y: number; } export interface VkSampleLocationEXT { x: number; y: number; } /** ## VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT ## */ interface VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly filterMinmaxSingleComponentFormats?: number; readonly filterMinmaxImageComponentMapping?: number; } declare var VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT: { prototype: VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT; new(param?: VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXTInitializer | null): VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT; readonly sType: VkStructureType; readonly pNext: null; readonly filterMinmaxSingleComponentFormats: number; readonly filterMinmaxImageComponentMapping: number; } export interface VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT { readonly sType: VkStructureType; readonly pNext: null; readonly filterMinmaxSingleComponentFormats: number; readonly filterMinmaxImageComponentMapping: number; } /** ## VkPipelineCoverageToColorStateCreateInfoNV ## */ interface VkPipelineCoverageToColorStateCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; flags?: null; coverageToColorEnable?: number; coverageToColorLocation?: number; } declare var VkPipelineCoverageToColorStateCreateInfoNV: { prototype: VkPipelineCoverageToColorStateCreateInfoNV; new(param?: VkPipelineCoverageToColorStateCreateInfoNVInitializer | null): VkPipelineCoverageToColorStateCreateInfoNV; sType: VkStructureType; pNext: null; flags: null; coverageToColorEnable: number; coverageToColorLocation: number; } export interface VkPipelineCoverageToColorStateCreateInfoNV { sType: VkStructureType; pNext: null; flags: null; coverageToColorEnable: number; coverageToColorLocation: number; } /** ## VkDeviceQueueInfo2 ## */ interface VkDeviceQueueInfo2Initializer { sType?: VkStructureType; pNext?: null; flags?: VkDeviceQueueCreateFlagBits; queueFamilyIndex?: number; queueIndex?: number; } declare var VkDeviceQueueInfo2: { prototype: VkDeviceQueueInfo2; new(param?: VkDeviceQueueInfo2Initializer | null): VkDeviceQueueInfo2; sType: VkStructureType; pNext: null; flags: VkDeviceQueueCreateFlagBits; queueFamilyIndex: number; queueIndex: number; } export interface VkDeviceQueueInfo2 { sType: VkStructureType; pNext: null; flags: VkDeviceQueueCreateFlagBits; queueFamilyIndex: number; queueIndex: number; } /** ## VkPhysicalDeviceProtectedMemoryProperties ## */ interface VkPhysicalDeviceProtectedMemoryPropertiesInitializer { sType?: VkStructureType; pNext?: null; protectedNoFault?: number; } declare var VkPhysicalDeviceProtectedMemoryProperties: { prototype: VkPhysicalDeviceProtectedMemoryProperties; new(param?: VkPhysicalDeviceProtectedMemoryPropertiesInitializer | null): VkPhysicalDeviceProtectedMemoryProperties; sType: VkStructureType; pNext: null; protectedNoFault: number; } export interface VkPhysicalDeviceProtectedMemoryProperties { sType: VkStructureType; pNext: null; protectedNoFault: number; } /** ## VkPhysicalDeviceProtectedMemoryFeatures ## */ interface VkPhysicalDeviceProtectedMemoryFeaturesInitializer { sType?: VkStructureType; pNext?: null; protectedMemory?: number; } declare var VkPhysicalDeviceProtectedMemoryFeatures: { prototype: VkPhysicalDeviceProtectedMemoryFeatures; new(param?: VkPhysicalDeviceProtectedMemoryFeaturesInitializer | null): VkPhysicalDeviceProtectedMemoryFeatures; sType: VkStructureType; pNext: null; protectedMemory: number; } export interface VkPhysicalDeviceProtectedMemoryFeatures { sType: VkStructureType; pNext: null; protectedMemory: number; } /** ## VkProtectedSubmitInfo ## */ interface VkProtectedSubmitInfoInitializer { sType?: VkStructureType; pNext?: null; protectedSubmit?: number; } declare var VkProtectedSubmitInfo: { prototype: VkProtectedSubmitInfo; new(param?: VkProtectedSubmitInfoInitializer | null): VkProtectedSubmitInfo; sType: VkStructureType; pNext: null; protectedSubmit: number; } export interface VkProtectedSubmitInfo { sType: VkStructureType; pNext: null; protectedSubmit: number; } /** ## VkConditionalRenderingBeginInfoEXT ## */ interface VkConditionalRenderingBeginInfoEXTInitializer { sType?: VkStructureType; pNext?: null; buffer?: VkBuffer | null; offset?: number; flags?: VkConditionalRenderingFlagBitsEXT; } declare var VkConditionalRenderingBeginInfoEXT: { prototype: VkConditionalRenderingBeginInfoEXT; new(param?: VkConditionalRenderingBeginInfoEXTInitializer | null): VkConditionalRenderingBeginInfoEXT; sType: VkStructureType; pNext: null; buffer: VkBuffer | null; offset: number; flags: VkConditionalRenderingFlagBitsEXT; } export interface VkConditionalRenderingBeginInfoEXT { sType: VkStructureType; pNext: null; buffer: VkBuffer | null; offset: number; flags: VkConditionalRenderingFlagBitsEXT; } /** ## VkTextureLODGatherFormatPropertiesAMD ## */ interface VkTextureLODGatherFormatPropertiesAMDInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly supportsTextureGatherLODBiasAMD?: number; } declare var VkTextureLODGatherFormatPropertiesAMD: { prototype: VkTextureLODGatherFormatPropertiesAMD; new(param?: VkTextureLODGatherFormatPropertiesAMDInitializer | null): VkTextureLODGatherFormatPropertiesAMD; readonly sType: VkStructureType; readonly pNext: null; readonly supportsTextureGatherLODBiasAMD: number; } export interface VkTextureLODGatherFormatPropertiesAMD { readonly sType: VkStructureType; readonly pNext: null; readonly supportsTextureGatherLODBiasAMD: number; } /** ## VkSamplerYcbcrConversionImageFormatPropertiesKHR ## */ interface VkSamplerYcbcrConversionImageFormatPropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly combinedImageSamplerDescriptorCount?: number; } declare var VkSamplerYcbcrConversionImageFormatPropertiesKHR: { prototype: VkSamplerYcbcrConversionImageFormatPropertiesKHR; new(param?: VkSamplerYcbcrConversionImageFormatPropertiesKHRInitializer | null): VkSamplerYcbcrConversionImageFormatPropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly combinedImageSamplerDescriptorCount: number; } export interface VkSamplerYcbcrConversionImageFormatPropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly combinedImageSamplerDescriptorCount: number; } /** ## VkSamplerYcbcrConversionImageFormatProperties ## */ interface VkSamplerYcbcrConversionImageFormatPropertiesInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly combinedImageSamplerDescriptorCount?: number; } declare var VkSamplerYcbcrConversionImageFormatProperties: { prototype: VkSamplerYcbcrConversionImageFormatProperties; new(param?: VkSamplerYcbcrConversionImageFormatPropertiesInitializer | null): VkSamplerYcbcrConversionImageFormatProperties; readonly sType: VkStructureType; readonly pNext: null; readonly combinedImageSamplerDescriptorCount: number; } export interface VkSamplerYcbcrConversionImageFormatProperties { readonly sType: VkStructureType; readonly pNext: null; readonly combinedImageSamplerDescriptorCount: number; } /** ## VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR ## */ interface VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHRInitializer { sType?: VkStructureType; pNext?: null; samplerYcbcrConversion?: number; } declare var VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR: { prototype: VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR; new(param?: VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHRInitializer | null): VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR; sType: VkStructureType; pNext: null; samplerYcbcrConversion: number; } export interface VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR { sType: VkStructureType; pNext: null; samplerYcbcrConversion: number; } /** ## VkPhysicalDeviceSamplerYcbcrConversionFeatures ## */ interface VkPhysicalDeviceSamplerYcbcrConversionFeaturesInitializer { sType?: VkStructureType; pNext?: null; samplerYcbcrConversion?: number; } declare var VkPhysicalDeviceSamplerYcbcrConversionFeatures: { prototype: VkPhysicalDeviceSamplerYcbcrConversionFeatures; new(param?: VkPhysicalDeviceSamplerYcbcrConversionFeaturesInitializer | null): VkPhysicalDeviceSamplerYcbcrConversionFeatures; sType: VkStructureType; pNext: null; samplerYcbcrConversion: number; } export interface VkPhysicalDeviceSamplerYcbcrConversionFeatures { sType: VkStructureType; pNext: null; samplerYcbcrConversion: number; } /** ## VkImagePlaneMemoryRequirementsInfoKHR ## */ interface VkImagePlaneMemoryRequirementsInfoKHRInitializer { sType?: VkStructureType; pNext?: null; planeAspect?: VkImageAspectFlagBits; } declare var VkImagePlaneMemoryRequirementsInfoKHR: { prototype: VkImagePlaneMemoryRequirementsInfoKHR; new(param?: VkImagePlaneMemoryRequirementsInfoKHRInitializer | null): VkImagePlaneMemoryRequirementsInfoKHR; sType: VkStructureType; pNext: null; planeAspect: VkImageAspectFlagBits; } export interface VkImagePlaneMemoryRequirementsInfoKHR { sType: VkStructureType; pNext: null; planeAspect: VkImageAspectFlagBits; } /** ## VkImagePlaneMemoryRequirementsInfo ## */ interface VkImagePlaneMemoryRequirementsInfoInitializer { sType?: VkStructureType; pNext?: null; planeAspect?: VkImageAspectFlagBits; } declare var VkImagePlaneMemoryRequirementsInfo: { prototype: VkImagePlaneMemoryRequirementsInfo; new(param?: VkImagePlaneMemoryRequirementsInfoInitializer | null): VkImagePlaneMemoryRequirementsInfo; sType: VkStructureType; pNext: null; planeAspect: VkImageAspectFlagBits; } export interface VkImagePlaneMemoryRequirementsInfo { sType: VkStructureType; pNext: null; planeAspect: VkImageAspectFlagBits; } /** ## VkBindImagePlaneMemoryInfoKHR ## */ interface VkBindImagePlaneMemoryInfoKHRInitializer { sType?: VkStructureType; pNext?: null; planeAspect?: VkImageAspectFlagBits; } declare var VkBindImagePlaneMemoryInfoKHR: { prototype: VkBindImagePlaneMemoryInfoKHR; new(param?: VkBindImagePlaneMemoryInfoKHRInitializer | null): VkBindImagePlaneMemoryInfoKHR; sType: VkStructureType; pNext: null; planeAspect: VkImageAspectFlagBits; } export interface VkBindImagePlaneMemoryInfoKHR { sType: VkStructureType; pNext: null; planeAspect: VkImageAspectFlagBits; } /** ## VkBindImagePlaneMemoryInfo ## */ interface VkBindImagePlaneMemoryInfoInitializer { sType?: VkStructureType; pNext?: null; planeAspect?: VkImageAspectFlagBits; } declare var VkBindImagePlaneMemoryInfo: { prototype: VkBindImagePlaneMemoryInfo; new(param?: VkBindImagePlaneMemoryInfoInitializer | null): VkBindImagePlaneMemoryInfo; sType: VkStructureType; pNext: null; planeAspect: VkImageAspectFlagBits; } export interface VkBindImagePlaneMemoryInfo { sType: VkStructureType; pNext: null; planeAspect: VkImageAspectFlagBits; } /** ## VkSamplerYcbcrConversionCreateInfoKHR ## */ interface VkSamplerYcbcrConversionCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; format?: VkFormat; ycbcrModel?: VkSamplerYcbcrModelConversion; ycbcrRange?: VkSamplerYcbcrRange; components?: VkComponentMapping | null; xChromaOffset?: VkChromaLocation; yChromaOffset?: VkChromaLocation; chromaFilter?: VkFilter; forceExplicitReconstruction?: number; } declare var VkSamplerYcbcrConversionCreateInfoKHR: { prototype: VkSamplerYcbcrConversionCreateInfoKHR; new(param?: VkSamplerYcbcrConversionCreateInfoKHRInitializer | null): VkSamplerYcbcrConversionCreateInfoKHR; sType: VkStructureType; pNext: null; format: VkFormat; ycbcrModel: VkSamplerYcbcrModelConversion; ycbcrRange: VkSamplerYcbcrRange; components: VkComponentMapping | null; xChromaOffset: VkChromaLocation; yChromaOffset: VkChromaLocation; chromaFilter: VkFilter; forceExplicitReconstruction: number; } export interface VkSamplerYcbcrConversionCreateInfoKHR { sType: VkStructureType; pNext: null; format: VkFormat; ycbcrModel: VkSamplerYcbcrModelConversion; ycbcrRange: VkSamplerYcbcrRange; components: VkComponentMapping | null; xChromaOffset: VkChromaLocation; yChromaOffset: VkChromaLocation; chromaFilter: VkFilter; forceExplicitReconstruction: number; } /** ## VkSamplerYcbcrConversionCreateInfo ## */ interface VkSamplerYcbcrConversionCreateInfoInitializer { sType?: VkStructureType; pNext?: null; format?: VkFormat; ycbcrModel?: VkSamplerYcbcrModelConversion; ycbcrRange?: VkSamplerYcbcrRange; components?: VkComponentMapping | null; xChromaOffset?: VkChromaLocation; yChromaOffset?: VkChromaLocation; chromaFilter?: VkFilter; forceExplicitReconstruction?: number; } declare var VkSamplerYcbcrConversionCreateInfo: { prototype: VkSamplerYcbcrConversionCreateInfo; new(param?: VkSamplerYcbcrConversionCreateInfoInitializer | null): VkSamplerYcbcrConversionCreateInfo; sType: VkStructureType; pNext: null; format: VkFormat; ycbcrModel: VkSamplerYcbcrModelConversion; ycbcrRange: VkSamplerYcbcrRange; components: VkComponentMapping | null; xChromaOffset: VkChromaLocation; yChromaOffset: VkChromaLocation; chromaFilter: VkFilter; forceExplicitReconstruction: number; } export interface VkSamplerYcbcrConversionCreateInfo { sType: VkStructureType; pNext: null; format: VkFormat; ycbcrModel: VkSamplerYcbcrModelConversion; ycbcrRange: VkSamplerYcbcrRange; components: VkComponentMapping | null; xChromaOffset: VkChromaLocation; yChromaOffset: VkChromaLocation; chromaFilter: VkFilter; forceExplicitReconstruction: number; } /** ## VkSamplerYcbcrConversionInfoKHR ## */ interface VkSamplerYcbcrConversionInfoKHRInitializer { sType?: VkStructureType; pNext?: null; conversion?: VkSamplerYcbcrConversion | null; } declare var VkSamplerYcbcrConversionInfoKHR: { prototype: VkSamplerYcbcrConversionInfoKHR; new(param?: VkSamplerYcbcrConversionInfoKHRInitializer | null): VkSamplerYcbcrConversionInfoKHR; sType: VkStructureType; pNext: null; conversion: VkSamplerYcbcrConversion | null; } export interface VkSamplerYcbcrConversionInfoKHR { sType: VkStructureType; pNext: null; conversion: VkSamplerYcbcrConversion | null; } /** ## VkSamplerYcbcrConversionInfo ## */ interface VkSamplerYcbcrConversionInfoInitializer { sType?: VkStructureType; pNext?: null; conversion?: VkSamplerYcbcrConversion | null; } declare var VkSamplerYcbcrConversionInfo: { prototype: VkSamplerYcbcrConversionInfo; new(param?: VkSamplerYcbcrConversionInfoInitializer | null): VkSamplerYcbcrConversionInfo; sType: VkStructureType; pNext: null; conversion: VkSamplerYcbcrConversion | null; } export interface VkSamplerYcbcrConversionInfo { sType: VkStructureType; pNext: null; conversion: VkSamplerYcbcrConversion | null; } /** ## VkPipelineTessellationDomainOriginStateCreateInfoKHR ## */ interface VkPipelineTessellationDomainOriginStateCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; domainOrigin?: VkTessellationDomainOrigin; } declare var VkPipelineTessellationDomainOriginStateCreateInfoKHR: { prototype: VkPipelineTessellationDomainOriginStateCreateInfoKHR; new(param?: VkPipelineTessellationDomainOriginStateCreateInfoKHRInitializer | null): VkPipelineTessellationDomainOriginStateCreateInfoKHR; sType: VkStructureType; pNext: null; domainOrigin: VkTessellationDomainOrigin; } export interface VkPipelineTessellationDomainOriginStateCreateInfoKHR { sType: VkStructureType; pNext: null; domainOrigin: VkTessellationDomainOrigin; } /** ## VkPipelineTessellationDomainOriginStateCreateInfo ## */ interface VkPipelineTessellationDomainOriginStateCreateInfoInitializer { sType?: VkStructureType; pNext?: null; domainOrigin?: VkTessellationDomainOrigin; } declare var VkPipelineTessellationDomainOriginStateCreateInfo: { prototype: VkPipelineTessellationDomainOriginStateCreateInfo; new(param?: VkPipelineTessellationDomainOriginStateCreateInfoInitializer | null): VkPipelineTessellationDomainOriginStateCreateInfo; sType: VkStructureType; pNext: null; domainOrigin: VkTessellationDomainOrigin; } export interface VkPipelineTessellationDomainOriginStateCreateInfo { sType: VkStructureType; pNext: null; domainOrigin: VkTessellationDomainOrigin; } /** ## VkImageViewUsageCreateInfoKHR ## */ interface VkImageViewUsageCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; usage?: VkImageUsageFlagBits; } declare var VkImageViewUsageCreateInfoKHR: { prototype: VkImageViewUsageCreateInfoKHR; new(param?: VkImageViewUsageCreateInfoKHRInitializer | null): VkImageViewUsageCreateInfoKHR; sType: VkStructureType; pNext: null; usage: VkImageUsageFlagBits; } export interface VkImageViewUsageCreateInfoKHR { sType: VkStructureType; pNext: null; usage: VkImageUsageFlagBits; } /** ## VkImageViewUsageCreateInfo ## */ interface VkImageViewUsageCreateInfoInitializer { sType?: VkStructureType; pNext?: null; usage?: VkImageUsageFlagBits; } declare var VkImageViewUsageCreateInfo: { prototype: VkImageViewUsageCreateInfo; new(param?: VkImageViewUsageCreateInfoInitializer | null): VkImageViewUsageCreateInfo; sType: VkStructureType; pNext: null; usage: VkImageUsageFlagBits; } export interface VkImageViewUsageCreateInfo { sType: VkStructureType; pNext: null; usage: VkImageUsageFlagBits; } /** ## VkMemoryDedicatedAllocateInfoKHR ## */ interface VkMemoryDedicatedAllocateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; image?: VkImage | null; buffer?: VkBuffer | null; } declare var VkMemoryDedicatedAllocateInfoKHR: { prototype: VkMemoryDedicatedAllocateInfoKHR; new(param?: VkMemoryDedicatedAllocateInfoKHRInitializer | null): VkMemoryDedicatedAllocateInfoKHR; sType: VkStructureType; pNext: null; image: VkImage | null; buffer: VkBuffer | null; } export interface VkMemoryDedicatedAllocateInfoKHR { sType: VkStructureType; pNext: null; image: VkImage | null; buffer: VkBuffer | null; } /** ## VkMemoryDedicatedAllocateInfo ## */ interface VkMemoryDedicatedAllocateInfoInitializer { sType?: VkStructureType; pNext?: null; image?: VkImage | null; buffer?: VkBuffer | null; } declare var VkMemoryDedicatedAllocateInfo: { prototype: VkMemoryDedicatedAllocateInfo; new(param?: VkMemoryDedicatedAllocateInfoInitializer | null): VkMemoryDedicatedAllocateInfo; sType: VkStructureType; pNext: null; image: VkImage | null; buffer: VkBuffer | null; } export interface VkMemoryDedicatedAllocateInfo { sType: VkStructureType; pNext: null; image: VkImage | null; buffer: VkBuffer | null; } /** ## VkMemoryDedicatedRequirementsKHR ## */ interface VkMemoryDedicatedRequirementsKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly prefersDedicatedAllocation?: number; readonly requiresDedicatedAllocation?: number; } declare var VkMemoryDedicatedRequirementsKHR: { prototype: VkMemoryDedicatedRequirementsKHR; new(param?: VkMemoryDedicatedRequirementsKHRInitializer | null): VkMemoryDedicatedRequirementsKHR; readonly sType: VkStructureType; readonly pNext: null; readonly prefersDedicatedAllocation: number; readonly requiresDedicatedAllocation: number; } export interface VkMemoryDedicatedRequirementsKHR { readonly sType: VkStructureType; readonly pNext: null; readonly prefersDedicatedAllocation: number; readonly requiresDedicatedAllocation: number; } /** ## VkMemoryDedicatedRequirements ## */ interface VkMemoryDedicatedRequirementsInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly prefersDedicatedAllocation?: number; readonly requiresDedicatedAllocation?: number; } declare var VkMemoryDedicatedRequirements: { prototype: VkMemoryDedicatedRequirements; new(param?: VkMemoryDedicatedRequirementsInitializer | null): VkMemoryDedicatedRequirements; readonly sType: VkStructureType; readonly pNext: null; readonly prefersDedicatedAllocation: number; readonly requiresDedicatedAllocation: number; } export interface VkMemoryDedicatedRequirements { readonly sType: VkStructureType; readonly pNext: null; readonly prefersDedicatedAllocation: number; readonly requiresDedicatedAllocation: number; } /** ## VkPhysicalDevicePointClippingPropertiesKHR ## */ interface VkPhysicalDevicePointClippingPropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly pointClippingBehavior?: VkPointClippingBehavior; } declare var VkPhysicalDevicePointClippingPropertiesKHR: { prototype: VkPhysicalDevicePointClippingPropertiesKHR; new(param?: VkPhysicalDevicePointClippingPropertiesKHRInitializer | null): VkPhysicalDevicePointClippingPropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly pointClippingBehavior: VkPointClippingBehavior; } export interface VkPhysicalDevicePointClippingPropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly pointClippingBehavior: VkPointClippingBehavior; } /** ## VkPhysicalDevicePointClippingProperties ## */ interface VkPhysicalDevicePointClippingPropertiesInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly pointClippingBehavior?: VkPointClippingBehavior; } declare var VkPhysicalDevicePointClippingProperties: { prototype: VkPhysicalDevicePointClippingProperties; new(param?: VkPhysicalDevicePointClippingPropertiesInitializer | null): VkPhysicalDevicePointClippingProperties; readonly sType: VkStructureType; readonly pNext: null; readonly pointClippingBehavior: VkPointClippingBehavior; } export interface VkPhysicalDevicePointClippingProperties { readonly sType: VkStructureType; readonly pNext: null; readonly pointClippingBehavior: VkPointClippingBehavior; } /** ## VkSparseImageMemoryRequirements2KHR ## */ interface VkSparseImageMemoryRequirements2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly memoryRequirements?: VkSparseImageMemoryRequirements | null; } declare var VkSparseImageMemoryRequirements2KHR: { prototype: VkSparseImageMemoryRequirements2KHR; new(param?: VkSparseImageMemoryRequirements2KHRInitializer | null): VkSparseImageMemoryRequirements2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly memoryRequirements: VkSparseImageMemoryRequirements | null; } export interface VkSparseImageMemoryRequirements2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly memoryRequirements: VkSparseImageMemoryRequirements | null; } /** ## VkSparseImageMemoryRequirements2 ## */ interface VkSparseImageMemoryRequirements2Initializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly memoryRequirements?: VkSparseImageMemoryRequirements | null; } declare var VkSparseImageMemoryRequirements2: { prototype: VkSparseImageMemoryRequirements2; new(param?: VkSparseImageMemoryRequirements2Initializer | null): VkSparseImageMemoryRequirements2; readonly sType: VkStructureType; readonly pNext: null; readonly memoryRequirements: VkSparseImageMemoryRequirements | null; } export interface VkSparseImageMemoryRequirements2 { readonly sType: VkStructureType; readonly pNext: null; readonly memoryRequirements: VkSparseImageMemoryRequirements | null; } /** ## VkMemoryRequirements2KHR ## */ interface VkMemoryRequirements2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly memoryRequirements?: VkMemoryRequirements | null; } declare var VkMemoryRequirements2KHR: { prototype: VkMemoryRequirements2KHR; new(param?: VkMemoryRequirements2KHRInitializer | null): VkMemoryRequirements2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly memoryRequirements: VkMemoryRequirements | null; } export interface VkMemoryRequirements2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly memoryRequirements: VkMemoryRequirements | null; } /** ## VkMemoryRequirements2 ## */ interface VkMemoryRequirements2Initializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly memoryRequirements?: VkMemoryRequirements | null; } declare var VkMemoryRequirements2: { prototype: VkMemoryRequirements2; new(param?: VkMemoryRequirements2Initializer | null): VkMemoryRequirements2; readonly sType: VkStructureType; readonly pNext: null; readonly memoryRequirements: VkMemoryRequirements | null; } export interface VkMemoryRequirements2 { readonly sType: VkStructureType; readonly pNext: null; readonly memoryRequirements: VkMemoryRequirements | null; } /** ## VkImageSparseMemoryRequirementsInfo2KHR ## */ interface VkImageSparseMemoryRequirementsInfo2KHRInitializer { sType?: VkStructureType; pNext?: null; image?: VkImage | null; } declare var VkImageSparseMemoryRequirementsInfo2KHR: { prototype: VkImageSparseMemoryRequirementsInfo2KHR; new(param?: VkImageSparseMemoryRequirementsInfo2KHRInitializer | null): VkImageSparseMemoryRequirementsInfo2KHR; sType: VkStructureType; pNext: null; image: VkImage | null; } export interface VkImageSparseMemoryRequirementsInfo2KHR { sType: VkStructureType; pNext: null; image: VkImage | null; } /** ## VkImageSparseMemoryRequirementsInfo2 ## */ interface VkImageSparseMemoryRequirementsInfo2Initializer { sType?: VkStructureType; pNext?: null; image?: VkImage | null; } declare var VkImageSparseMemoryRequirementsInfo2: { prototype: VkImageSparseMemoryRequirementsInfo2; new(param?: VkImageSparseMemoryRequirementsInfo2Initializer | null): VkImageSparseMemoryRequirementsInfo2; sType: VkStructureType; pNext: null; image: VkImage | null; } export interface VkImageSparseMemoryRequirementsInfo2 { sType: VkStructureType; pNext: null; image: VkImage | null; } /** ## VkImageMemoryRequirementsInfo2KHR ## */ interface VkImageMemoryRequirementsInfo2KHRInitializer { sType?: VkStructureType; pNext?: null; image?: VkImage | null; } declare var VkImageMemoryRequirementsInfo2KHR: { prototype: VkImageMemoryRequirementsInfo2KHR; new(param?: VkImageMemoryRequirementsInfo2KHRInitializer | null): VkImageMemoryRequirementsInfo2KHR; sType: VkStructureType; pNext: null; image: VkImage | null; } export interface VkImageMemoryRequirementsInfo2KHR { sType: VkStructureType; pNext: null; image: VkImage | null; } /** ## VkImageMemoryRequirementsInfo2 ## */ interface VkImageMemoryRequirementsInfo2Initializer { sType?: VkStructureType; pNext?: null; image?: VkImage | null; } declare var VkImageMemoryRequirementsInfo2: { prototype: VkImageMemoryRequirementsInfo2; new(param?: VkImageMemoryRequirementsInfo2Initializer | null): VkImageMemoryRequirementsInfo2; sType: VkStructureType; pNext: null; image: VkImage | null; } export interface VkImageMemoryRequirementsInfo2 { sType: VkStructureType; pNext: null; image: VkImage | null; } /** ## VkBufferMemoryRequirementsInfo2KHR ## */ interface VkBufferMemoryRequirementsInfo2KHRInitializer { sType?: VkStructureType; pNext?: null; buffer?: VkBuffer | null; } declare var VkBufferMemoryRequirementsInfo2KHR: { prototype: VkBufferMemoryRequirementsInfo2KHR; new(param?: VkBufferMemoryRequirementsInfo2KHRInitializer | null): VkBufferMemoryRequirementsInfo2KHR; sType: VkStructureType; pNext: null; buffer: VkBuffer | null; } export interface VkBufferMemoryRequirementsInfo2KHR { sType: VkStructureType; pNext: null; buffer: VkBuffer | null; } /** ## VkBufferMemoryRequirementsInfo2 ## */ interface VkBufferMemoryRequirementsInfo2Initializer { sType?: VkStructureType; pNext?: null; buffer?: VkBuffer | null; } declare var VkBufferMemoryRequirementsInfo2: { prototype: VkBufferMemoryRequirementsInfo2; new(param?: VkBufferMemoryRequirementsInfo2Initializer | null): VkBufferMemoryRequirementsInfo2; sType: VkStructureType; pNext: null; buffer: VkBuffer | null; } export interface VkBufferMemoryRequirementsInfo2 { sType: VkStructureType; pNext: null; buffer: VkBuffer | null; } /** ## VkPhysicalDeviceSubgroupProperties ## */ interface VkPhysicalDeviceSubgroupPropertiesInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly subgroupSize?: number; readonly supportedStages?: VkShaderStageFlagBits; readonly supportedOperations?: VkSubgroupFeatureFlagBits; readonly quadOperationsInAllStages?: number; } declare var VkPhysicalDeviceSubgroupProperties: { prototype: VkPhysicalDeviceSubgroupProperties; new(param?: VkPhysicalDeviceSubgroupPropertiesInitializer | null): VkPhysicalDeviceSubgroupProperties; readonly sType: VkStructureType; readonly pNext: null; readonly subgroupSize: number; readonly supportedStages: VkShaderStageFlagBits; readonly supportedOperations: VkSubgroupFeatureFlagBits; readonly quadOperationsInAllStages: number; } export interface VkPhysicalDeviceSubgroupProperties { readonly sType: VkStructureType; readonly pNext: null; readonly subgroupSize: number; readonly supportedStages: VkShaderStageFlagBits; readonly supportedOperations: VkSubgroupFeatureFlagBits; readonly quadOperationsInAllStages: number; } /** ## VkPhysicalDevice16BitStorageFeaturesKHR ## */ interface VkPhysicalDevice16BitStorageFeaturesKHRInitializer { sType?: VkStructureType; pNext?: null; storageBuffer16BitAccess?: number; uniformAndStorageBuffer16BitAccess?: number; storagePushConstant16?: number; storageInputOutput16?: number; } declare var VkPhysicalDevice16BitStorageFeaturesKHR: { prototype: VkPhysicalDevice16BitStorageFeaturesKHR; new(param?: VkPhysicalDevice16BitStorageFeaturesKHRInitializer | null): VkPhysicalDevice16BitStorageFeaturesKHR; sType: VkStructureType; pNext: null; storageBuffer16BitAccess: number; uniformAndStorageBuffer16BitAccess: number; storagePushConstant16: number; storageInputOutput16: number; } export interface VkPhysicalDevice16BitStorageFeaturesKHR { sType: VkStructureType; pNext: null; storageBuffer16BitAccess: number; uniformAndStorageBuffer16BitAccess: number; storagePushConstant16: number; storageInputOutput16: number; } /** ## VkPhysicalDevice16BitStorageFeatures ## */ interface VkPhysicalDevice16BitStorageFeaturesInitializer { sType?: VkStructureType; pNext?: null; storageBuffer16BitAccess?: number; uniformAndStorageBuffer16BitAccess?: number; storagePushConstant16?: number; storageInputOutput16?: number; } declare var VkPhysicalDevice16BitStorageFeatures: { prototype: VkPhysicalDevice16BitStorageFeatures; new(param?: VkPhysicalDevice16BitStorageFeaturesInitializer | null): VkPhysicalDevice16BitStorageFeatures; sType: VkStructureType; pNext: null; storageBuffer16BitAccess: number; uniformAndStorageBuffer16BitAccess: number; storagePushConstant16: number; storageInputOutput16: number; } export interface VkPhysicalDevice16BitStorageFeatures { sType: VkStructureType; pNext: null; storageBuffer16BitAccess: number; uniformAndStorageBuffer16BitAccess: number; storagePushConstant16: number; storageInputOutput16: number; } /** ## VkSharedPresentSurfaceCapabilitiesKHR ## */ interface VkSharedPresentSurfaceCapabilitiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly sharedPresentSupportedUsageFlags?: VkImageUsageFlagBits; } declare var VkSharedPresentSurfaceCapabilitiesKHR: { prototype: VkSharedPresentSurfaceCapabilitiesKHR; new(param?: VkSharedPresentSurfaceCapabilitiesKHRInitializer | null): VkSharedPresentSurfaceCapabilitiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly sharedPresentSupportedUsageFlags: VkImageUsageFlagBits; } export interface VkSharedPresentSurfaceCapabilitiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly sharedPresentSupportedUsageFlags: VkImageUsageFlagBits; } /** ## VkDisplayPlaneCapabilities2KHR ## */ interface VkDisplayPlaneCapabilities2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly capabilities?: VkDisplayPlaneCapabilitiesKHR | null; } declare var VkDisplayPlaneCapabilities2KHR: { prototype: VkDisplayPlaneCapabilities2KHR; new(param?: VkDisplayPlaneCapabilities2KHRInitializer | null): VkDisplayPlaneCapabilities2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly capabilities: VkDisplayPlaneCapabilitiesKHR | null; } export interface VkDisplayPlaneCapabilities2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly capabilities: VkDisplayPlaneCapabilitiesKHR | null; } /** ## VkDisplayPlaneInfo2KHR ## */ interface VkDisplayPlaneInfo2KHRInitializer { sType?: VkStructureType; pNext?: null; mode?: VkDisplayModeKHR | null; planeIndex?: number; } declare var VkDisplayPlaneInfo2KHR: { prototype: VkDisplayPlaneInfo2KHR; new(param?: VkDisplayPlaneInfo2KHRInitializer | null): VkDisplayPlaneInfo2KHR; sType: VkStructureType; pNext: null; mode: VkDisplayModeKHR | null; planeIndex: number; } export interface VkDisplayPlaneInfo2KHR { sType: VkStructureType; pNext: null; mode: VkDisplayModeKHR | null; planeIndex: number; } /** ## VkDisplayModeProperties2KHR ## */ interface VkDisplayModeProperties2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly displayModeProperties?: VkDisplayModePropertiesKHR | null; } declare var VkDisplayModeProperties2KHR: { prototype: VkDisplayModeProperties2KHR; new(param?: VkDisplayModeProperties2KHRInitializer | null): VkDisplayModeProperties2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly displayModeProperties: VkDisplayModePropertiesKHR | null; } export interface VkDisplayModeProperties2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly displayModeProperties: VkDisplayModePropertiesKHR | null; } /** ## VkDisplayPlaneProperties2KHR ## */ interface VkDisplayPlaneProperties2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly displayPlaneProperties?: VkDisplayPlanePropertiesKHR | null; } declare var VkDisplayPlaneProperties2KHR: { prototype: VkDisplayPlaneProperties2KHR; new(param?: VkDisplayPlaneProperties2KHRInitializer | null): VkDisplayPlaneProperties2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly displayPlaneProperties: VkDisplayPlanePropertiesKHR | null; } export interface VkDisplayPlaneProperties2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly displayPlaneProperties: VkDisplayPlanePropertiesKHR | null; } /** ## VkDisplayProperties2KHR ## */ interface VkDisplayProperties2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly displayProperties?: VkDisplayPropertiesKHR | null; } declare var VkDisplayProperties2KHR: { prototype: VkDisplayProperties2KHR; new(param?: VkDisplayProperties2KHRInitializer | null): VkDisplayProperties2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly displayProperties: VkDisplayPropertiesKHR | null; } export interface VkDisplayProperties2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly displayProperties: VkDisplayPropertiesKHR | null; } /** ## VkSurfaceFormat2KHR ## */ interface VkSurfaceFormat2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly surfaceFormat?: VkSurfaceFormatKHR | null; } declare var VkSurfaceFormat2KHR: { prototype: VkSurfaceFormat2KHR; new(param?: VkSurfaceFormat2KHRInitializer | null): VkSurfaceFormat2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly surfaceFormat: VkSurfaceFormatKHR | null; } export interface VkSurfaceFormat2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly surfaceFormat: VkSurfaceFormatKHR | null; } /** ## VkSurfaceCapabilities2KHR ## */ interface VkSurfaceCapabilities2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly surfaceCapabilities?: VkSurfaceCapabilitiesKHR | null; } declare var VkSurfaceCapabilities2KHR: { prototype: VkSurfaceCapabilities2KHR; new(param?: VkSurfaceCapabilities2KHRInitializer | null): VkSurfaceCapabilities2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly surfaceCapabilities: VkSurfaceCapabilitiesKHR | null; } export interface VkSurfaceCapabilities2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly surfaceCapabilities: VkSurfaceCapabilitiesKHR | null; } /** ## VkPhysicalDeviceSurfaceInfo2KHR ## */ interface VkPhysicalDeviceSurfaceInfo2KHRInitializer { sType?: VkStructureType; pNext?: null; surface?: VkSurfaceKHR | null; } declare var VkPhysicalDeviceSurfaceInfo2KHR: { prototype: VkPhysicalDeviceSurfaceInfo2KHR; new(param?: VkPhysicalDeviceSurfaceInfo2KHRInitializer | null): VkPhysicalDeviceSurfaceInfo2KHR; sType: VkStructureType; pNext: null; surface: VkSurfaceKHR | null; } export interface VkPhysicalDeviceSurfaceInfo2KHR { sType: VkStructureType; pNext: null; surface: VkSurfaceKHR | null; } /** ## VkRenderPassInputAttachmentAspectCreateInfoKHR ## */ interface VkRenderPassInputAttachmentAspectCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; aspectReferenceCount?: number; pAspectReferences?: VkInputAttachmentAspectReference[] | null; } declare var VkRenderPassInputAttachmentAspectCreateInfoKHR: { prototype: VkRenderPassInputAttachmentAspectCreateInfoKHR; new(param?: VkRenderPassInputAttachmentAspectCreateInfoKHRInitializer | null): VkRenderPassInputAttachmentAspectCreateInfoKHR; sType: VkStructureType; pNext: null; aspectReferenceCount: number; pAspectReferences: VkInputAttachmentAspectReference[] | null; } export interface VkRenderPassInputAttachmentAspectCreateInfoKHR { sType: VkStructureType; pNext: null; aspectReferenceCount: number; pAspectReferences: VkInputAttachmentAspectReference[] | null; } /** ## VkRenderPassInputAttachmentAspectCreateInfo ## */ interface VkRenderPassInputAttachmentAspectCreateInfoInitializer { sType?: VkStructureType; pNext?: null; aspectReferenceCount?: number; pAspectReferences?: VkInputAttachmentAspectReference[] | null; } declare var VkRenderPassInputAttachmentAspectCreateInfo: { prototype: VkRenderPassInputAttachmentAspectCreateInfo; new(param?: VkRenderPassInputAttachmentAspectCreateInfoInitializer | null): VkRenderPassInputAttachmentAspectCreateInfo; sType: VkStructureType; pNext: null; aspectReferenceCount: number; pAspectReferences: VkInputAttachmentAspectReference[] | null; } export interface VkRenderPassInputAttachmentAspectCreateInfo { sType: VkStructureType; pNext: null; aspectReferenceCount: number; pAspectReferences: VkInputAttachmentAspectReference[] | null; } /** ## VkInputAttachmentAspectReferenceKHR ## */ interface VkInputAttachmentAspectReferenceKHRInitializer { subpass?: number; inputAttachmentIndex?: number; aspectMask?: VkImageAspectFlagBits; } declare var VkInputAttachmentAspectReferenceKHR: { prototype: VkInputAttachmentAspectReferenceKHR; new(param?: VkInputAttachmentAspectReferenceKHRInitializer | null): VkInputAttachmentAspectReferenceKHR; subpass: number; inputAttachmentIndex: number; aspectMask: VkImageAspectFlagBits; } export interface VkInputAttachmentAspectReferenceKHR { subpass: number; inputAttachmentIndex: number; aspectMask: VkImageAspectFlagBits; } /** ## VkInputAttachmentAspectReference ## */ interface VkInputAttachmentAspectReferenceInitializer { subpass?: number; inputAttachmentIndex?: number; aspectMask?: VkImageAspectFlagBits; } declare var VkInputAttachmentAspectReference: { prototype: VkInputAttachmentAspectReference; new(param?: VkInputAttachmentAspectReferenceInitializer | null): VkInputAttachmentAspectReference; subpass: number; inputAttachmentIndex: number; aspectMask: VkImageAspectFlagBits; } export interface VkInputAttachmentAspectReference { subpass: number; inputAttachmentIndex: number; aspectMask: VkImageAspectFlagBits; } /** ## VkPhysicalDeviceMultiviewPerViewAttributesPropertiesNVX ## */ interface VkPhysicalDeviceMultiviewPerViewAttributesPropertiesNVXInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly perViewPositionAllComponents?: number; } declare var VkPhysicalDeviceMultiviewPerViewAttributesPropertiesNVX: { prototype: VkPhysicalDeviceMultiviewPerViewAttributesPropertiesNVX; new(param?: VkPhysicalDeviceMultiviewPerViewAttributesPropertiesNVXInitializer | null): VkPhysicalDeviceMultiviewPerViewAttributesPropertiesNVX; readonly sType: VkStructureType; readonly pNext: null; readonly perViewPositionAllComponents: number; } export interface VkPhysicalDeviceMultiviewPerViewAttributesPropertiesNVX { readonly sType: VkStructureType; readonly pNext: null; readonly perViewPositionAllComponents: number; } /** ## VkPipelineDiscardRectangleStateCreateInfoEXT ## */ interface VkPipelineDiscardRectangleStateCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; flags?: null; discardRectangleMode?: VkDiscardRectangleModeEXT; discardRectangleCount?: number; pDiscardRectangles?: VkRect2D[] | null; } declare var VkPipelineDiscardRectangleStateCreateInfoEXT: { prototype: VkPipelineDiscardRectangleStateCreateInfoEXT; new(param?: VkPipelineDiscardRectangleStateCreateInfoEXTInitializer | null): VkPipelineDiscardRectangleStateCreateInfoEXT; sType: VkStructureType; pNext: null; flags: null; discardRectangleMode: VkDiscardRectangleModeEXT; discardRectangleCount: number; pDiscardRectangles: VkRect2D[] | null; } export interface VkPipelineDiscardRectangleStateCreateInfoEXT { sType: VkStructureType; pNext: null; flags: null; discardRectangleMode: VkDiscardRectangleModeEXT; discardRectangleCount: number; pDiscardRectangles: VkRect2D[] | null; } /** ## VkPhysicalDeviceDiscardRectanglePropertiesEXT ## */ interface VkPhysicalDeviceDiscardRectanglePropertiesEXTInitializer { sType?: VkStructureType; pNext?: null; maxDiscardRectangles?: number; } declare var VkPhysicalDeviceDiscardRectanglePropertiesEXT: { prototype: VkPhysicalDeviceDiscardRectanglePropertiesEXT; new(param?: VkPhysicalDeviceDiscardRectanglePropertiesEXTInitializer | null): VkPhysicalDeviceDiscardRectanglePropertiesEXT; sType: VkStructureType; pNext: null; maxDiscardRectangles: number; } export interface VkPhysicalDeviceDiscardRectanglePropertiesEXT { sType: VkStructureType; pNext: null; maxDiscardRectangles: number; } /** ## VkPipelineViewportSwizzleStateCreateInfoNV ## */ interface VkPipelineViewportSwizzleStateCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; flags?: null; viewportCount?: number; pViewportSwizzles?: VkViewportSwizzleNV[] | null; } declare var VkPipelineViewportSwizzleStateCreateInfoNV: { prototype: VkPipelineViewportSwizzleStateCreateInfoNV; new(param?: VkPipelineViewportSwizzleStateCreateInfoNVInitializer | null): VkPipelineViewportSwizzleStateCreateInfoNV; sType: VkStructureType; pNext: null; flags: null; viewportCount: number; pViewportSwizzles: VkViewportSwizzleNV[] | null; } export interface VkPipelineViewportSwizzleStateCreateInfoNV { sType: VkStructureType; pNext: null; flags: null; viewportCount: number; pViewportSwizzles: VkViewportSwizzleNV[] | null; } /** ## VkViewportSwizzleNV ## */ interface VkViewportSwizzleNVInitializer { x?: VkViewportCoordinateSwizzleNV; y?: VkViewportCoordinateSwizzleNV; z?: VkViewportCoordinateSwizzleNV; w?: VkViewportCoordinateSwizzleNV; } declare var VkViewportSwizzleNV: { prototype: VkViewportSwizzleNV; new(param?: VkViewportSwizzleNVInitializer | null): VkViewportSwizzleNV; x: VkViewportCoordinateSwizzleNV; y: VkViewportCoordinateSwizzleNV; z: VkViewportCoordinateSwizzleNV; w: VkViewportCoordinateSwizzleNV; } export interface VkViewportSwizzleNV { x: VkViewportCoordinateSwizzleNV; y: VkViewportCoordinateSwizzleNV; z: VkViewportCoordinateSwizzleNV; w: VkViewportCoordinateSwizzleNV; } /** ## VkPipelineViewportWScalingStateCreateInfoNV ## */ interface VkPipelineViewportWScalingStateCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; viewportWScalingEnable?: number; viewportCount?: number; pViewportWScalings?: VkViewportWScalingNV[] | null; } declare var VkPipelineViewportWScalingStateCreateInfoNV: { prototype: VkPipelineViewportWScalingStateCreateInfoNV; new(param?: VkPipelineViewportWScalingStateCreateInfoNVInitializer | null): VkPipelineViewportWScalingStateCreateInfoNV; sType: VkStructureType; pNext: null; viewportWScalingEnable: number; viewportCount: number; pViewportWScalings: VkViewportWScalingNV[] | null; } export interface VkPipelineViewportWScalingStateCreateInfoNV { sType: VkStructureType; pNext: null; viewportWScalingEnable: number; viewportCount: number; pViewportWScalings: VkViewportWScalingNV[] | null; } /** ## VkViewportWScalingNV ## */ interface VkViewportWScalingNVInitializer { xcoeff?: number; ycoeff?: number; } declare var VkViewportWScalingNV: { prototype: VkViewportWScalingNV; new(param?: VkViewportWScalingNVInitializer | null): VkViewportWScalingNV; xcoeff: number; ycoeff: number; } export interface VkViewportWScalingNV { xcoeff: number; ycoeff: number; } /** ## VkPresentTimeGOOGLE ## */ interface VkPresentTimeGOOGLEInitializer { presentID?: number; desiredPresentTime?: number; } declare var VkPresentTimeGOOGLE: { prototype: VkPresentTimeGOOGLE; new(param?: VkPresentTimeGOOGLEInitializer | null): VkPresentTimeGOOGLE; presentID: number; desiredPresentTime: number; } export interface VkPresentTimeGOOGLE { presentID: number; desiredPresentTime: number; } /** ## VkPresentTimesInfoGOOGLE ## */ interface VkPresentTimesInfoGOOGLEInitializer { sType?: VkStructureType; pNext?: null; swapchainCount?: number; pTimes?: VkPresentTimeGOOGLE[] | null; } declare var VkPresentTimesInfoGOOGLE: { prototype: VkPresentTimesInfoGOOGLE; new(param?: VkPresentTimesInfoGOOGLEInitializer | null): VkPresentTimesInfoGOOGLE; sType: VkStructureType; pNext: null; swapchainCount: number; pTimes: VkPresentTimeGOOGLE[] | null; } export interface VkPresentTimesInfoGOOGLE { sType: VkStructureType; pNext: null; swapchainCount: number; pTimes: VkPresentTimeGOOGLE[] | null; } /** ## VkPastPresentationTimingGOOGLE ## */ interface VkPastPresentationTimingGOOGLEInitializer { readonly presentID?: number; readonly desiredPresentTime?: number; readonly actualPresentTime?: number; readonly earliestPresentTime?: number; readonly presentMargin?: number; } declare var VkPastPresentationTimingGOOGLE: { prototype: VkPastPresentationTimingGOOGLE; new(param?: VkPastPresentationTimingGOOGLEInitializer | null): VkPastPresentationTimingGOOGLE; readonly presentID: number; readonly desiredPresentTime: number; readonly actualPresentTime: number; readonly earliestPresentTime: number; readonly presentMargin: number; } export interface VkPastPresentationTimingGOOGLE { readonly presentID: number; readonly desiredPresentTime: number; readonly actualPresentTime: number; readonly earliestPresentTime: number; readonly presentMargin: number; } /** ## VkRefreshCycleDurationGOOGLE ## */ interface VkRefreshCycleDurationGOOGLEInitializer { readonly refreshDuration?: number; } declare var VkRefreshCycleDurationGOOGLE: { prototype: VkRefreshCycleDurationGOOGLE; new(param?: VkRefreshCycleDurationGOOGLEInitializer | null): VkRefreshCycleDurationGOOGLE; readonly refreshDuration: number; } export interface VkRefreshCycleDurationGOOGLE { readonly refreshDuration: number; } /** ## VkHdrMetadataEXT ## */ interface VkHdrMetadataEXTInitializer { sType?: VkStructureType; pNext?: null; displayPrimaryRed?: VkXYColorEXT | null; displayPrimaryGreen?: VkXYColorEXT | null; displayPrimaryBlue?: VkXYColorEXT | null; whitePoint?: VkXYColorEXT | null; maxLuminance?: number; minLuminance?: number; maxContentLightLevel?: number; maxFrameAverageLightLevel?: number; } declare var VkHdrMetadataEXT: { prototype: VkHdrMetadataEXT; new(param?: VkHdrMetadataEXTInitializer | null): VkHdrMetadataEXT; sType: VkStructureType; pNext: null; displayPrimaryRed: VkXYColorEXT | null; displayPrimaryGreen: VkXYColorEXT | null; displayPrimaryBlue: VkXYColorEXT | null; whitePoint: VkXYColorEXT | null; maxLuminance: number; minLuminance: number; maxContentLightLevel: number; maxFrameAverageLightLevel: number; } export interface VkHdrMetadataEXT { sType: VkStructureType; pNext: null; displayPrimaryRed: VkXYColorEXT | null; displayPrimaryGreen: VkXYColorEXT | null; displayPrimaryBlue: VkXYColorEXT | null; whitePoint: VkXYColorEXT | null; maxLuminance: number; minLuminance: number; maxContentLightLevel: number; maxFrameAverageLightLevel: number; } /** ## VkXYColorEXT ## */ interface VkXYColorEXTInitializer { x?: number; y?: number; } declare var VkXYColorEXT: { prototype: VkXYColorEXT; new(param?: VkXYColorEXTInitializer | null): VkXYColorEXT; x: number; y: number; } export interface VkXYColorEXT { x: number; y: number; } /** ## VkDescriptorUpdateTemplateCreateInfoKHR ## */ interface VkDescriptorUpdateTemplateCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; flags?: null; descriptorUpdateEntryCount?: number; pDescriptorUpdateEntries?: VkDescriptorUpdateTemplateEntry[] | null; templateType?: VkDescriptorUpdateTemplateType; descriptorSetLayout?: VkDescriptorSetLayout | null; pipelineBindPoint?: VkPipelineBindPoint; pipelineLayout?: VkPipelineLayout | null; set?: number; } declare var VkDescriptorUpdateTemplateCreateInfoKHR: { prototype: VkDescriptorUpdateTemplateCreateInfoKHR; new(param?: VkDescriptorUpdateTemplateCreateInfoKHRInitializer | null): VkDescriptorUpdateTemplateCreateInfoKHR; sType: VkStructureType; pNext: null; flags: null; descriptorUpdateEntryCount: number; pDescriptorUpdateEntries: VkDescriptorUpdateTemplateEntry[] | null; templateType: VkDescriptorUpdateTemplateType; descriptorSetLayout: VkDescriptorSetLayout | null; pipelineBindPoint: VkPipelineBindPoint; pipelineLayout: VkPipelineLayout | null; set: number; } export interface VkDescriptorUpdateTemplateCreateInfoKHR { sType: VkStructureType; pNext: null; flags: null; descriptorUpdateEntryCount: number; pDescriptorUpdateEntries: VkDescriptorUpdateTemplateEntry[] | null; templateType: VkDescriptorUpdateTemplateType; descriptorSetLayout: VkDescriptorSetLayout | null; pipelineBindPoint: VkPipelineBindPoint; pipelineLayout: VkPipelineLayout | null; set: number; } /** ## VkDescriptorUpdateTemplateCreateInfo ## */ interface VkDescriptorUpdateTemplateCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; descriptorUpdateEntryCount?: number; pDescriptorUpdateEntries?: VkDescriptorUpdateTemplateEntry[] | null; templateType?: VkDescriptorUpdateTemplateType; descriptorSetLayout?: VkDescriptorSetLayout | null; pipelineBindPoint?: VkPipelineBindPoint; pipelineLayout?: VkPipelineLayout | null; set?: number; } declare var VkDescriptorUpdateTemplateCreateInfo: { prototype: VkDescriptorUpdateTemplateCreateInfo; new(param?: VkDescriptorUpdateTemplateCreateInfoInitializer | null): VkDescriptorUpdateTemplateCreateInfo; sType: VkStructureType; pNext: null; flags: null; descriptorUpdateEntryCount: number; pDescriptorUpdateEntries: VkDescriptorUpdateTemplateEntry[] | null; templateType: VkDescriptorUpdateTemplateType; descriptorSetLayout: VkDescriptorSetLayout | null; pipelineBindPoint: VkPipelineBindPoint; pipelineLayout: VkPipelineLayout | null; set: number; } export interface VkDescriptorUpdateTemplateCreateInfo { sType: VkStructureType; pNext: null; flags: null; descriptorUpdateEntryCount: number; pDescriptorUpdateEntries: VkDescriptorUpdateTemplateEntry[] | null; templateType: VkDescriptorUpdateTemplateType; descriptorSetLayout: VkDescriptorSetLayout | null; pipelineBindPoint: VkPipelineBindPoint; pipelineLayout: VkPipelineLayout | null; set: number; } /** ## VkDescriptorUpdateTemplateEntryKHR ## */ interface VkDescriptorUpdateTemplateEntryKHRInitializer { dstBinding?: number; dstArrayElement?: number; descriptorCount?: number; descriptorType?: VkDescriptorType; offset?: number; stride?: number; } declare var VkDescriptorUpdateTemplateEntryKHR: { prototype: VkDescriptorUpdateTemplateEntryKHR; new(param?: VkDescriptorUpdateTemplateEntryKHRInitializer | null): VkDescriptorUpdateTemplateEntryKHR; dstBinding: number; dstArrayElement: number; descriptorCount: number; descriptorType: VkDescriptorType; offset: number; stride: number; } export interface VkDescriptorUpdateTemplateEntryKHR { dstBinding: number; dstArrayElement: number; descriptorCount: number; descriptorType: VkDescriptorType; offset: number; stride: number; } /** ## VkDescriptorUpdateTemplateEntry ## */ interface VkDescriptorUpdateTemplateEntryInitializer { dstBinding?: number; dstArrayElement?: number; descriptorCount?: number; descriptorType?: VkDescriptorType; offset?: number; stride?: number; } declare var VkDescriptorUpdateTemplateEntry: { prototype: VkDescriptorUpdateTemplateEntry; new(param?: VkDescriptorUpdateTemplateEntryInitializer | null): VkDescriptorUpdateTemplateEntry; dstBinding: number; dstArrayElement: number; descriptorCount: number; descriptorType: VkDescriptorType; offset: number; stride: number; } export interface VkDescriptorUpdateTemplateEntry { dstBinding: number; dstArrayElement: number; descriptorCount: number; descriptorType: VkDescriptorType; offset: number; stride: number; } /** ## VkDeviceGroupSwapchainCreateInfoKHR ## */ interface VkDeviceGroupSwapchainCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; modes?: VkDeviceGroupPresentModeFlagBitsKHR; } declare var VkDeviceGroupSwapchainCreateInfoKHR: { prototype: VkDeviceGroupSwapchainCreateInfoKHR; new(param?: VkDeviceGroupSwapchainCreateInfoKHRInitializer | null): VkDeviceGroupSwapchainCreateInfoKHR; sType: VkStructureType; pNext: null; modes: VkDeviceGroupPresentModeFlagBitsKHR; } export interface VkDeviceGroupSwapchainCreateInfoKHR { sType: VkStructureType; pNext: null; modes: VkDeviceGroupPresentModeFlagBitsKHR; } /** ## VkDeviceGroupDeviceCreateInfoKHR ## */ interface VkDeviceGroupDeviceCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; physicalDeviceCount?: number; pPhysicalDevices?: VkPhysicalDevice[] | null; } declare var VkDeviceGroupDeviceCreateInfoKHR: { prototype: VkDeviceGroupDeviceCreateInfoKHR; new(param?: VkDeviceGroupDeviceCreateInfoKHRInitializer | null): VkDeviceGroupDeviceCreateInfoKHR; sType: VkStructureType; pNext: null; physicalDeviceCount: number; pPhysicalDevices: VkPhysicalDevice[] | null; } export interface VkDeviceGroupDeviceCreateInfoKHR { sType: VkStructureType; pNext: null; physicalDeviceCount: number; pPhysicalDevices: VkPhysicalDevice[] | null; } /** ## VkDeviceGroupDeviceCreateInfo ## */ interface VkDeviceGroupDeviceCreateInfoInitializer { sType?: VkStructureType; pNext?: null; physicalDeviceCount?: number; pPhysicalDevices?: VkPhysicalDevice[] | null; } declare var VkDeviceGroupDeviceCreateInfo: { prototype: VkDeviceGroupDeviceCreateInfo; new(param?: VkDeviceGroupDeviceCreateInfoInitializer | null): VkDeviceGroupDeviceCreateInfo; sType: VkStructureType; pNext: null; physicalDeviceCount: number; pPhysicalDevices: VkPhysicalDevice[] | null; } export interface VkDeviceGroupDeviceCreateInfo { sType: VkStructureType; pNext: null; physicalDeviceCount: number; pPhysicalDevices: VkPhysicalDevice[] | null; } /** ## VkDeviceGroupPresentInfoKHR ## */ interface VkDeviceGroupPresentInfoKHRInitializer { sType?: VkStructureType; pNext?: null; swapchainCount?: number; pDeviceMasks?: Uint32Array | null; mode?: VkDeviceGroupPresentModeFlagBitsKHR; } declare var VkDeviceGroupPresentInfoKHR: { prototype: VkDeviceGroupPresentInfoKHR; new(param?: VkDeviceGroupPresentInfoKHRInitializer | null): VkDeviceGroupPresentInfoKHR; sType: VkStructureType; pNext: null; swapchainCount: number; pDeviceMasks: Uint32Array | null; mode: VkDeviceGroupPresentModeFlagBitsKHR; } export interface VkDeviceGroupPresentInfoKHR { sType: VkStructureType; pNext: null; swapchainCount: number; pDeviceMasks: Uint32Array | null; mode: VkDeviceGroupPresentModeFlagBitsKHR; } /** ## VkAcquireNextImageInfoKHR ## */ interface VkAcquireNextImageInfoKHRInitializer { sType?: VkStructureType; pNext?: null; swapchain?: VkSwapchainKHR | null; timeout?: number; semaphore?: VkSemaphore | null; fence?: VkFence | null; deviceMask?: number; } declare var VkAcquireNextImageInfoKHR: { prototype: VkAcquireNextImageInfoKHR; new(param?: VkAcquireNextImageInfoKHRInitializer | null): VkAcquireNextImageInfoKHR; sType: VkStructureType; pNext: null; swapchain: VkSwapchainKHR | null; timeout: number; semaphore: VkSemaphore | null; fence: VkFence | null; deviceMask: number; } export interface VkAcquireNextImageInfoKHR { sType: VkStructureType; pNext: null; swapchain: VkSwapchainKHR | null; timeout: number; semaphore: VkSemaphore | null; fence: VkFence | null; deviceMask: number; } /** ## VkBindImageMemorySwapchainInfoKHR ## */ interface VkBindImageMemorySwapchainInfoKHRInitializer { sType?: VkStructureType; pNext?: null; swapchain?: VkSwapchainKHR | null; imageIndex?: number; } declare var VkBindImageMemorySwapchainInfoKHR: { prototype: VkBindImageMemorySwapchainInfoKHR; new(param?: VkBindImageMemorySwapchainInfoKHRInitializer | null): VkBindImageMemorySwapchainInfoKHR; sType: VkStructureType; pNext: null; swapchain: VkSwapchainKHR | null; imageIndex: number; } export interface VkBindImageMemorySwapchainInfoKHR { sType: VkStructureType; pNext: null; swapchain: VkSwapchainKHR | null; imageIndex: number; } /** ## VkImageSwapchainCreateInfoKHR ## */ interface VkImageSwapchainCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; swapchain?: VkSwapchainKHR | null; } declare var VkImageSwapchainCreateInfoKHR: { prototype: VkImageSwapchainCreateInfoKHR; new(param?: VkImageSwapchainCreateInfoKHRInitializer | null): VkImageSwapchainCreateInfoKHR; sType: VkStructureType; pNext: null; swapchain: VkSwapchainKHR | null; } export interface VkImageSwapchainCreateInfoKHR { sType: VkStructureType; pNext: null; swapchain: VkSwapchainKHR | null; } /** ## VkDeviceGroupPresentCapabilitiesKHR ## */ interface VkDeviceGroupPresentCapabilitiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly presentMask?: number[] | null; readonly modes?: VkDeviceGroupPresentModeFlagBitsKHR; } declare var VkDeviceGroupPresentCapabilitiesKHR: { prototype: VkDeviceGroupPresentCapabilitiesKHR; new(param?: VkDeviceGroupPresentCapabilitiesKHRInitializer | null): VkDeviceGroupPresentCapabilitiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly presentMask: number[] | null; readonly modes: VkDeviceGroupPresentModeFlagBitsKHR; } export interface VkDeviceGroupPresentCapabilitiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly presentMask: number[] | null; readonly modes: VkDeviceGroupPresentModeFlagBitsKHR; } /** ## VkDeviceGroupBindSparseInfoKHR ## */ interface VkDeviceGroupBindSparseInfoKHRInitializer { sType?: VkStructureType; pNext?: null; resourceDeviceIndex?: number; memoryDeviceIndex?: number; } declare var VkDeviceGroupBindSparseInfoKHR: { prototype: VkDeviceGroupBindSparseInfoKHR; new(param?: VkDeviceGroupBindSparseInfoKHRInitializer | null): VkDeviceGroupBindSparseInfoKHR; sType: VkStructureType; pNext: null; resourceDeviceIndex: number; memoryDeviceIndex: number; } export interface VkDeviceGroupBindSparseInfoKHR { sType: VkStructureType; pNext: null; resourceDeviceIndex: number; memoryDeviceIndex: number; } /** ## VkDeviceGroupBindSparseInfo ## */ interface VkDeviceGroupBindSparseInfoInitializer { sType?: VkStructureType; pNext?: null; resourceDeviceIndex?: number; memoryDeviceIndex?: number; } declare var VkDeviceGroupBindSparseInfo: { prototype: VkDeviceGroupBindSparseInfo; new(param?: VkDeviceGroupBindSparseInfoInitializer | null): VkDeviceGroupBindSparseInfo; sType: VkStructureType; pNext: null; resourceDeviceIndex: number; memoryDeviceIndex: number; } export interface VkDeviceGroupBindSparseInfo { sType: VkStructureType; pNext: null; resourceDeviceIndex: number; memoryDeviceIndex: number; } /** ## VkDeviceGroupSubmitInfoKHR ## */ interface VkDeviceGroupSubmitInfoKHRInitializer { sType?: VkStructureType; pNext?: null; waitSemaphoreCount?: number; pWaitSemaphoreDeviceIndices?: Uint32Array | null; commandBufferCount?: number; pCommandBufferDeviceMasks?: Uint32Array | null; signalSemaphoreCount?: number; pSignalSemaphoreDeviceIndices?: Uint32Array | null; } declare var VkDeviceGroupSubmitInfoKHR: { prototype: VkDeviceGroupSubmitInfoKHR; new(param?: VkDeviceGroupSubmitInfoKHRInitializer | null): VkDeviceGroupSubmitInfoKHR; sType: VkStructureType; pNext: null; waitSemaphoreCount: number; pWaitSemaphoreDeviceIndices: Uint32Array | null; commandBufferCount: number; pCommandBufferDeviceMasks: Uint32Array | null; signalSemaphoreCount: number; pSignalSemaphoreDeviceIndices: Uint32Array | null; } export interface VkDeviceGroupSubmitInfoKHR { sType: VkStructureType; pNext: null; waitSemaphoreCount: number; pWaitSemaphoreDeviceIndices: Uint32Array | null; commandBufferCount: number; pCommandBufferDeviceMasks: Uint32Array | null; signalSemaphoreCount: number; pSignalSemaphoreDeviceIndices: Uint32Array | null; } /** ## VkDeviceGroupSubmitInfo ## */ interface VkDeviceGroupSubmitInfoInitializer { sType?: VkStructureType; pNext?: null; waitSemaphoreCount?: number; pWaitSemaphoreDeviceIndices?: Uint32Array | null; commandBufferCount?: number; pCommandBufferDeviceMasks?: Uint32Array | null; signalSemaphoreCount?: number; pSignalSemaphoreDeviceIndices?: Uint32Array | null; } declare var VkDeviceGroupSubmitInfo: { prototype: VkDeviceGroupSubmitInfo; new(param?: VkDeviceGroupSubmitInfoInitializer | null): VkDeviceGroupSubmitInfo; sType: VkStructureType; pNext: null; waitSemaphoreCount: number; pWaitSemaphoreDeviceIndices: Uint32Array | null; commandBufferCount: number; pCommandBufferDeviceMasks: Uint32Array | null; signalSemaphoreCount: number; pSignalSemaphoreDeviceIndices: Uint32Array | null; } export interface VkDeviceGroupSubmitInfo { sType: VkStructureType; pNext: null; waitSemaphoreCount: number; pWaitSemaphoreDeviceIndices: Uint32Array | null; commandBufferCount: number; pCommandBufferDeviceMasks: Uint32Array | null; signalSemaphoreCount: number; pSignalSemaphoreDeviceIndices: Uint32Array | null; } /** ## VkDeviceGroupCommandBufferBeginInfoKHR ## */ interface VkDeviceGroupCommandBufferBeginInfoKHRInitializer { sType?: VkStructureType; pNext?: null; deviceMask?: number; } declare var VkDeviceGroupCommandBufferBeginInfoKHR: { prototype: VkDeviceGroupCommandBufferBeginInfoKHR; new(param?: VkDeviceGroupCommandBufferBeginInfoKHRInitializer | null): VkDeviceGroupCommandBufferBeginInfoKHR; sType: VkStructureType; pNext: null; deviceMask: number; } export interface VkDeviceGroupCommandBufferBeginInfoKHR { sType: VkStructureType; pNext: null; deviceMask: number; } /** ## VkDeviceGroupCommandBufferBeginInfo ## */ interface VkDeviceGroupCommandBufferBeginInfoInitializer { sType?: VkStructureType; pNext?: null; deviceMask?: number; } declare var VkDeviceGroupCommandBufferBeginInfo: { prototype: VkDeviceGroupCommandBufferBeginInfo; new(param?: VkDeviceGroupCommandBufferBeginInfoInitializer | null): VkDeviceGroupCommandBufferBeginInfo; sType: VkStructureType; pNext: null; deviceMask: number; } export interface VkDeviceGroupCommandBufferBeginInfo { sType: VkStructureType; pNext: null; deviceMask: number; } /** ## VkDeviceGroupRenderPassBeginInfoKHR ## */ interface VkDeviceGroupRenderPassBeginInfoKHRInitializer { sType?: VkStructureType; pNext?: null; deviceMask?: number; deviceRenderAreaCount?: number; pDeviceRenderAreas?: VkRect2D[] | null; } declare var VkDeviceGroupRenderPassBeginInfoKHR: { prototype: VkDeviceGroupRenderPassBeginInfoKHR; new(param?: VkDeviceGroupRenderPassBeginInfoKHRInitializer | null): VkDeviceGroupRenderPassBeginInfoKHR; sType: VkStructureType; pNext: null; deviceMask: number; deviceRenderAreaCount: number; pDeviceRenderAreas: VkRect2D[] | null; } export interface VkDeviceGroupRenderPassBeginInfoKHR { sType: VkStructureType; pNext: null; deviceMask: number; deviceRenderAreaCount: number; pDeviceRenderAreas: VkRect2D[] | null; } /** ## VkDeviceGroupRenderPassBeginInfo ## */ interface VkDeviceGroupRenderPassBeginInfoInitializer { sType?: VkStructureType; pNext?: null; deviceMask?: number; deviceRenderAreaCount?: number; pDeviceRenderAreas?: VkRect2D[] | null; } declare var VkDeviceGroupRenderPassBeginInfo: { prototype: VkDeviceGroupRenderPassBeginInfo; new(param?: VkDeviceGroupRenderPassBeginInfoInitializer | null): VkDeviceGroupRenderPassBeginInfo; sType: VkStructureType; pNext: null; deviceMask: number; deviceRenderAreaCount: number; pDeviceRenderAreas: VkRect2D[] | null; } export interface VkDeviceGroupRenderPassBeginInfo { sType: VkStructureType; pNext: null; deviceMask: number; deviceRenderAreaCount: number; pDeviceRenderAreas: VkRect2D[] | null; } /** ## VkBindImageMemoryDeviceGroupInfoKHR ## */ interface VkBindImageMemoryDeviceGroupInfoKHRInitializer { sType?: VkStructureType; pNext?: null; deviceIndexCount?: number; pDeviceIndices?: Uint32Array | null; splitInstanceBindRegionCount?: number; pSplitInstanceBindRegions?: VkRect2D[] | null; } declare var VkBindImageMemoryDeviceGroupInfoKHR: { prototype: VkBindImageMemoryDeviceGroupInfoKHR; new(param?: VkBindImageMemoryDeviceGroupInfoKHRInitializer | null): VkBindImageMemoryDeviceGroupInfoKHR; sType: VkStructureType; pNext: null; deviceIndexCount: number; pDeviceIndices: Uint32Array | null; splitInstanceBindRegionCount: number; pSplitInstanceBindRegions: VkRect2D[] | null; } export interface VkBindImageMemoryDeviceGroupInfoKHR { sType: VkStructureType; pNext: null; deviceIndexCount: number; pDeviceIndices: Uint32Array | null; splitInstanceBindRegionCount: number; pSplitInstanceBindRegions: VkRect2D[] | null; } /** ## VkBindImageMemoryDeviceGroupInfo ## */ interface VkBindImageMemoryDeviceGroupInfoInitializer { sType?: VkStructureType; pNext?: null; deviceIndexCount?: number; pDeviceIndices?: Uint32Array | null; splitInstanceBindRegionCount?: number; pSplitInstanceBindRegions?: VkRect2D[] | null; } declare var VkBindImageMemoryDeviceGroupInfo: { prototype: VkBindImageMemoryDeviceGroupInfo; new(param?: VkBindImageMemoryDeviceGroupInfoInitializer | null): VkBindImageMemoryDeviceGroupInfo; sType: VkStructureType; pNext: null; deviceIndexCount: number; pDeviceIndices: Uint32Array | null; splitInstanceBindRegionCount: number; pSplitInstanceBindRegions: VkRect2D[] | null; } export interface VkBindImageMemoryDeviceGroupInfo { sType: VkStructureType; pNext: null; deviceIndexCount: number; pDeviceIndices: Uint32Array | null; splitInstanceBindRegionCount: number; pSplitInstanceBindRegions: VkRect2D[] | null; } /** ## VkBindImageMemoryInfoKHR ## */ interface VkBindImageMemoryInfoKHRInitializer { sType?: VkStructureType; pNext?: null; image?: VkImage | null; memory?: VkDeviceMemory | null; memoryOffset?: number; } declare var VkBindImageMemoryInfoKHR: { prototype: VkBindImageMemoryInfoKHR; new(param?: VkBindImageMemoryInfoKHRInitializer | null): VkBindImageMemoryInfoKHR; sType: VkStructureType; pNext: null; image: VkImage | null; memory: VkDeviceMemory | null; memoryOffset: number; } export interface VkBindImageMemoryInfoKHR { sType: VkStructureType; pNext: null; image: VkImage | null; memory: VkDeviceMemory | null; memoryOffset: number; } /** ## VkBindImageMemoryInfo ## */ interface VkBindImageMemoryInfoInitializer { sType?: VkStructureType; pNext?: null; image?: VkImage | null; memory?: VkDeviceMemory | null; memoryOffset?: number; } declare var VkBindImageMemoryInfo: { prototype: VkBindImageMemoryInfo; new(param?: VkBindImageMemoryInfoInitializer | null): VkBindImageMemoryInfo; sType: VkStructureType; pNext: null; image: VkImage | null; memory: VkDeviceMemory | null; memoryOffset: number; } export interface VkBindImageMemoryInfo { sType: VkStructureType; pNext: null; image: VkImage | null; memory: VkDeviceMemory | null; memoryOffset: number; } /** ## VkBindBufferMemoryDeviceGroupInfoKHR ## */ interface VkBindBufferMemoryDeviceGroupInfoKHRInitializer { sType?: VkStructureType; pNext?: null; deviceIndexCount?: number; pDeviceIndices?: Uint32Array | null; } declare var VkBindBufferMemoryDeviceGroupInfoKHR: { prototype: VkBindBufferMemoryDeviceGroupInfoKHR; new(param?: VkBindBufferMemoryDeviceGroupInfoKHRInitializer | null): VkBindBufferMemoryDeviceGroupInfoKHR; sType: VkStructureType; pNext: null; deviceIndexCount: number; pDeviceIndices: Uint32Array | null; } export interface VkBindBufferMemoryDeviceGroupInfoKHR { sType: VkStructureType; pNext: null; deviceIndexCount: number; pDeviceIndices: Uint32Array | null; } /** ## VkBindBufferMemoryDeviceGroupInfo ## */ interface VkBindBufferMemoryDeviceGroupInfoInitializer { sType?: VkStructureType; pNext?: null; deviceIndexCount?: number; pDeviceIndices?: Uint32Array | null; } declare var VkBindBufferMemoryDeviceGroupInfo: { prototype: VkBindBufferMemoryDeviceGroupInfo; new(param?: VkBindBufferMemoryDeviceGroupInfoInitializer | null): VkBindBufferMemoryDeviceGroupInfo; sType: VkStructureType; pNext: null; deviceIndexCount: number; pDeviceIndices: Uint32Array | null; } export interface VkBindBufferMemoryDeviceGroupInfo { sType: VkStructureType; pNext: null; deviceIndexCount: number; pDeviceIndices: Uint32Array | null; } /** ## VkBindBufferMemoryInfoKHR ## */ interface VkBindBufferMemoryInfoKHRInitializer { sType?: VkStructureType; pNext?: null; buffer?: VkBuffer | null; memory?: VkDeviceMemory | null; memoryOffset?: number; } declare var VkBindBufferMemoryInfoKHR: { prototype: VkBindBufferMemoryInfoKHR; new(param?: VkBindBufferMemoryInfoKHRInitializer | null): VkBindBufferMemoryInfoKHR; sType: VkStructureType; pNext: null; buffer: VkBuffer | null; memory: VkDeviceMemory | null; memoryOffset: number; } export interface VkBindBufferMemoryInfoKHR { sType: VkStructureType; pNext: null; buffer: VkBuffer | null; memory: VkDeviceMemory | null; memoryOffset: number; } /** ## VkBindBufferMemoryInfo ## */ interface VkBindBufferMemoryInfoInitializer { sType?: VkStructureType; pNext?: null; buffer?: VkBuffer | null; memory?: VkDeviceMemory | null; memoryOffset?: number; } declare var VkBindBufferMemoryInfo: { prototype: VkBindBufferMemoryInfo; new(param?: VkBindBufferMemoryInfoInitializer | null): VkBindBufferMemoryInfo; sType: VkStructureType; pNext: null; buffer: VkBuffer | null; memory: VkDeviceMemory | null; memoryOffset: number; } export interface VkBindBufferMemoryInfo { sType: VkStructureType; pNext: null; buffer: VkBuffer | null; memory: VkDeviceMemory | null; memoryOffset: number; } /** ## VkMemoryAllocateFlagsInfoKHR ## */ interface VkMemoryAllocateFlagsInfoKHRInitializer { sType?: VkStructureType; pNext?: null; flags?: VkMemoryAllocateFlagBits; deviceMask?: number; } declare var VkMemoryAllocateFlagsInfoKHR: { prototype: VkMemoryAllocateFlagsInfoKHR; new(param?: VkMemoryAllocateFlagsInfoKHRInitializer | null): VkMemoryAllocateFlagsInfoKHR; sType: VkStructureType; pNext: null; flags: VkMemoryAllocateFlagBits; deviceMask: number; } export interface VkMemoryAllocateFlagsInfoKHR { sType: VkStructureType; pNext: null; flags: VkMemoryAllocateFlagBits; deviceMask: number; } /** ## VkMemoryAllocateFlagsInfo ## */ interface VkMemoryAllocateFlagsInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkMemoryAllocateFlagBits; deviceMask?: number; } declare var VkMemoryAllocateFlagsInfo: { prototype: VkMemoryAllocateFlagsInfo; new(param?: VkMemoryAllocateFlagsInfoInitializer | null): VkMemoryAllocateFlagsInfo; sType: VkStructureType; pNext: null; flags: VkMemoryAllocateFlagBits; deviceMask: number; } export interface VkMemoryAllocateFlagsInfo { sType: VkStructureType; pNext: null; flags: VkMemoryAllocateFlagBits; deviceMask: number; } /** ## VkPhysicalDeviceGroupPropertiesKHR ## */ interface VkPhysicalDeviceGroupPropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly physicalDeviceCount?: number; readonly physicalDevices?: number[] | null; readonly subsetAllocation?: number; } declare var VkPhysicalDeviceGroupPropertiesKHR: { prototype: VkPhysicalDeviceGroupPropertiesKHR; new(param?: VkPhysicalDeviceGroupPropertiesKHRInitializer | null): VkPhysicalDeviceGroupPropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly physicalDeviceCount: number; readonly physicalDevices: number[] | null; readonly subsetAllocation: number; } export interface VkPhysicalDeviceGroupPropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly physicalDeviceCount: number; readonly physicalDevices: number[] | null; readonly subsetAllocation: number; } /** ## VkPhysicalDeviceGroupProperties ## */ interface VkPhysicalDeviceGroupPropertiesInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly physicalDeviceCount?: number; readonly physicalDevices?: number[] | null; readonly subsetAllocation?: number; } declare var VkPhysicalDeviceGroupProperties: { prototype: VkPhysicalDeviceGroupProperties; new(param?: VkPhysicalDeviceGroupPropertiesInitializer | null): VkPhysicalDeviceGroupProperties; readonly sType: VkStructureType; readonly pNext: null; readonly physicalDeviceCount: number; readonly physicalDevices: number[] | null; readonly subsetAllocation: number; } export interface VkPhysicalDeviceGroupProperties { readonly sType: VkStructureType; readonly pNext: null; readonly physicalDeviceCount: number; readonly physicalDevices: number[] | null; readonly subsetAllocation: number; } /** ## VkSwapchainCounterCreateInfoEXT ## */ interface VkSwapchainCounterCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; surfaceCounters?: VkSurfaceCounterFlagBitsEXT; } declare var VkSwapchainCounterCreateInfoEXT: { prototype: VkSwapchainCounterCreateInfoEXT; new(param?: VkSwapchainCounterCreateInfoEXTInitializer | null): VkSwapchainCounterCreateInfoEXT; sType: VkStructureType; pNext: null; surfaceCounters: VkSurfaceCounterFlagBitsEXT; } export interface VkSwapchainCounterCreateInfoEXT { sType: VkStructureType; pNext: null; surfaceCounters: VkSurfaceCounterFlagBitsEXT; } /** ## VkDisplayEventInfoEXT ## */ interface VkDisplayEventInfoEXTInitializer { sType?: VkStructureType; pNext?: null; displayEvent?: VkDisplayEventTypeEXT; } declare var VkDisplayEventInfoEXT: { prototype: VkDisplayEventInfoEXT; new(param?: VkDisplayEventInfoEXTInitializer | null): VkDisplayEventInfoEXT; sType: VkStructureType; pNext: null; displayEvent: VkDisplayEventTypeEXT; } export interface VkDisplayEventInfoEXT { sType: VkStructureType; pNext: null; displayEvent: VkDisplayEventTypeEXT; } /** ## VkDeviceEventInfoEXT ## */ interface VkDeviceEventInfoEXTInitializer { sType?: VkStructureType; pNext?: null; deviceEvent?: VkDeviceEventTypeEXT; } declare var VkDeviceEventInfoEXT: { prototype: VkDeviceEventInfoEXT; new(param?: VkDeviceEventInfoEXTInitializer | null): VkDeviceEventInfoEXT; sType: VkStructureType; pNext: null; deviceEvent: VkDeviceEventTypeEXT; } export interface VkDeviceEventInfoEXT { sType: VkStructureType; pNext: null; deviceEvent: VkDeviceEventTypeEXT; } /** ## VkDisplayPowerInfoEXT ## */ interface VkDisplayPowerInfoEXTInitializer { sType?: VkStructureType; pNext?: null; powerState?: VkDisplayPowerStateEXT; } declare var VkDisplayPowerInfoEXT: { prototype: VkDisplayPowerInfoEXT; new(param?: VkDisplayPowerInfoEXTInitializer | null): VkDisplayPowerInfoEXT; sType: VkStructureType; pNext: null; powerState: VkDisplayPowerStateEXT; } export interface VkDisplayPowerInfoEXT { sType: VkStructureType; pNext: null; powerState: VkDisplayPowerStateEXT; } /** ## VkSurfaceCapabilities2EXT ## */ interface VkSurfaceCapabilities2EXTInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly minImageCount?: number; readonly maxImageCount?: number; readonly currentExtent?: VkExtent2D | null; readonly minImageExtent?: VkExtent2D | null; readonly maxImageExtent?: VkExtent2D | null; readonly maxImageArrayLayers?: number; readonly supportedTransforms?: VkSurfaceTransformFlagBitsKHR; readonly currentTransform?: VkSurfaceTransformFlagBitsKHR; readonly supportedCompositeAlpha?: VkCompositeAlphaFlagBitsKHR; readonly supportedUsageFlags?: VkImageUsageFlagBits; readonly supportedSurfaceCounters?: VkSurfaceCounterFlagBitsEXT; } declare var VkSurfaceCapabilities2EXT: { prototype: VkSurfaceCapabilities2EXT; new(param?: VkSurfaceCapabilities2EXTInitializer | null): VkSurfaceCapabilities2EXT; readonly sType: VkStructureType; readonly pNext: null; readonly minImageCount: number; readonly maxImageCount: number; readonly currentExtent: VkExtent2D | null; readonly minImageExtent: VkExtent2D | null; readonly maxImageExtent: VkExtent2D | null; readonly maxImageArrayLayers: number; readonly supportedTransforms: VkSurfaceTransformFlagBitsKHR; readonly currentTransform: VkSurfaceTransformFlagBitsKHR; readonly supportedCompositeAlpha: VkCompositeAlphaFlagBitsKHR; readonly supportedUsageFlags: VkImageUsageFlagBits; readonly supportedSurfaceCounters: VkSurfaceCounterFlagBitsEXT; } export interface VkSurfaceCapabilities2EXT { readonly sType: VkStructureType; readonly pNext: null; readonly minImageCount: number; readonly maxImageCount: number; readonly currentExtent: VkExtent2D | null; readonly minImageExtent: VkExtent2D | null; readonly maxImageExtent: VkExtent2D | null; readonly maxImageArrayLayers: number; readonly supportedTransforms: VkSurfaceTransformFlagBitsKHR; readonly currentTransform: VkSurfaceTransformFlagBitsKHR; readonly supportedCompositeAlpha: VkCompositeAlphaFlagBitsKHR; readonly supportedUsageFlags: VkImageUsageFlagBits; readonly supportedSurfaceCounters: VkSurfaceCounterFlagBitsEXT; } /** ## VkRenderPassMultiviewCreateInfoKHR ## */ interface VkRenderPassMultiviewCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; subpassCount?: number; pViewMasks?: Uint32Array | null; dependencyCount?: number; pViewOffsets?: Int32Array | null; correlationMaskCount?: number; pCorrelationMasks?: Uint32Array | null; } declare var VkRenderPassMultiviewCreateInfoKHR: { prototype: VkRenderPassMultiviewCreateInfoKHR; new(param?: VkRenderPassMultiviewCreateInfoKHRInitializer | null): VkRenderPassMultiviewCreateInfoKHR; sType: VkStructureType; pNext: null; subpassCount: number; pViewMasks: Uint32Array | null; dependencyCount: number; pViewOffsets: Int32Array | null; correlationMaskCount: number; pCorrelationMasks: Uint32Array | null; } export interface VkRenderPassMultiviewCreateInfoKHR { sType: VkStructureType; pNext: null; subpassCount: number; pViewMasks: Uint32Array | null; dependencyCount: number; pViewOffsets: Int32Array | null; correlationMaskCount: number; pCorrelationMasks: Uint32Array | null; } /** ## VkRenderPassMultiviewCreateInfo ## */ interface VkRenderPassMultiviewCreateInfoInitializer { sType?: VkStructureType; pNext?: null; subpassCount?: number; pViewMasks?: Uint32Array | null; dependencyCount?: number; pViewOffsets?: Int32Array | null; correlationMaskCount?: number; pCorrelationMasks?: Uint32Array | null; } declare var VkRenderPassMultiviewCreateInfo: { prototype: VkRenderPassMultiviewCreateInfo; new(param?: VkRenderPassMultiviewCreateInfoInitializer | null): VkRenderPassMultiviewCreateInfo; sType: VkStructureType; pNext: null; subpassCount: number; pViewMasks: Uint32Array | null; dependencyCount: number; pViewOffsets: Int32Array | null; correlationMaskCount: number; pCorrelationMasks: Uint32Array | null; } export interface VkRenderPassMultiviewCreateInfo { sType: VkStructureType; pNext: null; subpassCount: number; pViewMasks: Uint32Array | null; dependencyCount: number; pViewOffsets: Int32Array | null; correlationMaskCount: number; pCorrelationMasks: Uint32Array | null; } /** ## VkPhysicalDeviceMultiviewPropertiesKHR ## */ interface VkPhysicalDeviceMultiviewPropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly maxMultiviewViewCount?: number; readonly maxMultiviewInstanceIndex?: number; } declare var VkPhysicalDeviceMultiviewPropertiesKHR: { prototype: VkPhysicalDeviceMultiviewPropertiesKHR; new(param?: VkPhysicalDeviceMultiviewPropertiesKHRInitializer | null): VkPhysicalDeviceMultiviewPropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly maxMultiviewViewCount: number; readonly maxMultiviewInstanceIndex: number; } export interface VkPhysicalDeviceMultiviewPropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly maxMultiviewViewCount: number; readonly maxMultiviewInstanceIndex: number; } /** ## VkPhysicalDeviceMultiviewProperties ## */ interface VkPhysicalDeviceMultiviewPropertiesInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly maxMultiviewViewCount?: number; readonly maxMultiviewInstanceIndex?: number; } declare var VkPhysicalDeviceMultiviewProperties: { prototype: VkPhysicalDeviceMultiviewProperties; new(param?: VkPhysicalDeviceMultiviewPropertiesInitializer | null): VkPhysicalDeviceMultiviewProperties; readonly sType: VkStructureType; readonly pNext: null; readonly maxMultiviewViewCount: number; readonly maxMultiviewInstanceIndex: number; } export interface VkPhysicalDeviceMultiviewProperties { readonly sType: VkStructureType; readonly pNext: null; readonly maxMultiviewViewCount: number; readonly maxMultiviewInstanceIndex: number; } /** ## VkPhysicalDeviceMultiviewFeaturesKHR ## */ interface VkPhysicalDeviceMultiviewFeaturesKHRInitializer { sType?: VkStructureType; pNext?: null; multiview?: number; multiviewGeometryShader?: number; multiviewTessellationShader?: number; } declare var VkPhysicalDeviceMultiviewFeaturesKHR: { prototype: VkPhysicalDeviceMultiviewFeaturesKHR; new(param?: VkPhysicalDeviceMultiviewFeaturesKHRInitializer | null): VkPhysicalDeviceMultiviewFeaturesKHR; sType: VkStructureType; pNext: null; multiview: number; multiviewGeometryShader: number; multiviewTessellationShader: number; } export interface VkPhysicalDeviceMultiviewFeaturesKHR { sType: VkStructureType; pNext: null; multiview: number; multiviewGeometryShader: number; multiviewTessellationShader: number; } /** ## VkPhysicalDeviceMultiviewFeatures ## */ interface VkPhysicalDeviceMultiviewFeaturesInitializer { sType?: VkStructureType; pNext?: null; multiview?: number; multiviewGeometryShader?: number; multiviewTessellationShader?: number; } declare var VkPhysicalDeviceMultiviewFeatures: { prototype: VkPhysicalDeviceMultiviewFeatures; new(param?: VkPhysicalDeviceMultiviewFeaturesInitializer | null): VkPhysicalDeviceMultiviewFeatures; sType: VkStructureType; pNext: null; multiview: number; multiviewGeometryShader: number; multiviewTessellationShader: number; } export interface VkPhysicalDeviceMultiviewFeatures { sType: VkStructureType; pNext: null; multiview: number; multiviewGeometryShader: number; multiviewTessellationShader: number; } /** ## VkFenceGetFdInfoKHR ## */ interface VkFenceGetFdInfoKHRInitializer { sType?: VkStructureType; pNext?: null; fence?: VkFence | null; handleType?: VkExternalFenceHandleTypeFlagBits; } declare var VkFenceGetFdInfoKHR: { prototype: VkFenceGetFdInfoKHR; new(param?: VkFenceGetFdInfoKHRInitializer | null): VkFenceGetFdInfoKHR; sType: VkStructureType; pNext: null; fence: VkFence | null; handleType: VkExternalFenceHandleTypeFlagBits; } export interface VkFenceGetFdInfoKHR { sType: VkStructureType; pNext: null; fence: VkFence | null; handleType: VkExternalFenceHandleTypeFlagBits; } /** ## VkImportFenceFdInfoKHR ## */ interface VkImportFenceFdInfoKHRInitializer { sType?: VkStructureType; pNext?: null; fence?: VkFence | null; flags?: VkFenceImportFlagBits; handleType?: VkExternalFenceHandleTypeFlagBits; fd?: number; } declare var VkImportFenceFdInfoKHR: { prototype: VkImportFenceFdInfoKHR; new(param?: VkImportFenceFdInfoKHRInitializer | null): VkImportFenceFdInfoKHR; sType: VkStructureType; pNext: null; fence: VkFence | null; flags: VkFenceImportFlagBits; handleType: VkExternalFenceHandleTypeFlagBits; fd: number; } export interface VkImportFenceFdInfoKHR { sType: VkStructureType; pNext: null; fence: VkFence | null; flags: VkFenceImportFlagBits; handleType: VkExternalFenceHandleTypeFlagBits; fd: number; } /** ## VkExportFenceCreateInfoKHR ## */ interface VkExportFenceCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; handleTypes?: VkExternalFenceHandleTypeFlagBits; } declare var VkExportFenceCreateInfoKHR: { prototype: VkExportFenceCreateInfoKHR; new(param?: VkExportFenceCreateInfoKHRInitializer | null): VkExportFenceCreateInfoKHR; sType: VkStructureType; pNext: null; handleTypes: VkExternalFenceHandleTypeFlagBits; } export interface VkExportFenceCreateInfoKHR { sType: VkStructureType; pNext: null; handleTypes: VkExternalFenceHandleTypeFlagBits; } /** ## VkExportFenceCreateInfo ## */ interface VkExportFenceCreateInfoInitializer { sType?: VkStructureType; pNext?: null; handleTypes?: VkExternalFenceHandleTypeFlagBits; } declare var VkExportFenceCreateInfo: { prototype: VkExportFenceCreateInfo; new(param?: VkExportFenceCreateInfoInitializer | null): VkExportFenceCreateInfo; sType: VkStructureType; pNext: null; handleTypes: VkExternalFenceHandleTypeFlagBits; } export interface VkExportFenceCreateInfo { sType: VkStructureType; pNext: null; handleTypes: VkExternalFenceHandleTypeFlagBits; } /** ## VkExternalFencePropertiesKHR ## */ interface VkExternalFencePropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly exportFromImportedHandleTypes?: VkExternalFenceHandleTypeFlagBits; readonly compatibleHandleTypes?: VkExternalFenceHandleTypeFlagBits; readonly externalFenceFeatures?: VkExternalFenceFeatureFlagBits; } declare var VkExternalFencePropertiesKHR: { prototype: VkExternalFencePropertiesKHR; new(param?: VkExternalFencePropertiesKHRInitializer | null): VkExternalFencePropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly exportFromImportedHandleTypes: VkExternalFenceHandleTypeFlagBits; readonly compatibleHandleTypes: VkExternalFenceHandleTypeFlagBits; readonly externalFenceFeatures: VkExternalFenceFeatureFlagBits; } export interface VkExternalFencePropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly exportFromImportedHandleTypes: VkExternalFenceHandleTypeFlagBits; readonly compatibleHandleTypes: VkExternalFenceHandleTypeFlagBits; readonly externalFenceFeatures: VkExternalFenceFeatureFlagBits; } /** ## VkExternalFenceProperties ## */ interface VkExternalFencePropertiesInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly exportFromImportedHandleTypes?: VkExternalFenceHandleTypeFlagBits; readonly compatibleHandleTypes?: VkExternalFenceHandleTypeFlagBits; readonly externalFenceFeatures?: VkExternalFenceFeatureFlagBits; } declare var VkExternalFenceProperties: { prototype: VkExternalFenceProperties; new(param?: VkExternalFencePropertiesInitializer | null): VkExternalFenceProperties; readonly sType: VkStructureType; readonly pNext: null; readonly exportFromImportedHandleTypes: VkExternalFenceHandleTypeFlagBits; readonly compatibleHandleTypes: VkExternalFenceHandleTypeFlagBits; readonly externalFenceFeatures: VkExternalFenceFeatureFlagBits; } export interface VkExternalFenceProperties { readonly sType: VkStructureType; readonly pNext: null; readonly exportFromImportedHandleTypes: VkExternalFenceHandleTypeFlagBits; readonly compatibleHandleTypes: VkExternalFenceHandleTypeFlagBits; readonly externalFenceFeatures: VkExternalFenceFeatureFlagBits; } /** ## VkPhysicalDeviceExternalFenceInfoKHR ## */ interface VkPhysicalDeviceExternalFenceInfoKHRInitializer { sType?: VkStructureType; pNext?: null; handleType?: VkExternalFenceHandleTypeFlagBits; } declare var VkPhysicalDeviceExternalFenceInfoKHR: { prototype: VkPhysicalDeviceExternalFenceInfoKHR; new(param?: VkPhysicalDeviceExternalFenceInfoKHRInitializer | null): VkPhysicalDeviceExternalFenceInfoKHR; sType: VkStructureType; pNext: null; handleType: VkExternalFenceHandleTypeFlagBits; } export interface VkPhysicalDeviceExternalFenceInfoKHR { sType: VkStructureType; pNext: null; handleType: VkExternalFenceHandleTypeFlagBits; } /** ## VkPhysicalDeviceExternalFenceInfo ## */ interface VkPhysicalDeviceExternalFenceInfoInitializer { sType?: VkStructureType; pNext?: null; handleType?: VkExternalFenceHandleTypeFlagBits; } declare var VkPhysicalDeviceExternalFenceInfo: { prototype: VkPhysicalDeviceExternalFenceInfo; new(param?: VkPhysicalDeviceExternalFenceInfoInitializer | null): VkPhysicalDeviceExternalFenceInfo; sType: VkStructureType; pNext: null; handleType: VkExternalFenceHandleTypeFlagBits; } export interface VkPhysicalDeviceExternalFenceInfo { sType: VkStructureType; pNext: null; handleType: VkExternalFenceHandleTypeFlagBits; } /** ## VkSemaphoreGetFdInfoKHR ## */ interface VkSemaphoreGetFdInfoKHRInitializer { sType?: VkStructureType; pNext?: null; semaphore?: VkSemaphore | null; handleType?: VkExternalSemaphoreHandleTypeFlagBits; } declare var VkSemaphoreGetFdInfoKHR: { prototype: VkSemaphoreGetFdInfoKHR; new(param?: VkSemaphoreGetFdInfoKHRInitializer | null): VkSemaphoreGetFdInfoKHR; sType: VkStructureType; pNext: null; semaphore: VkSemaphore | null; handleType: VkExternalSemaphoreHandleTypeFlagBits; } export interface VkSemaphoreGetFdInfoKHR { sType: VkStructureType; pNext: null; semaphore: VkSemaphore | null; handleType: VkExternalSemaphoreHandleTypeFlagBits; } /** ## VkImportSemaphoreFdInfoKHR ## */ interface VkImportSemaphoreFdInfoKHRInitializer { sType?: VkStructureType; pNext?: null; semaphore?: VkSemaphore | null; flags?: VkSemaphoreImportFlagBits; handleType?: VkExternalSemaphoreHandleTypeFlagBits; fd?: number; } declare var VkImportSemaphoreFdInfoKHR: { prototype: VkImportSemaphoreFdInfoKHR; new(param?: VkImportSemaphoreFdInfoKHRInitializer | null): VkImportSemaphoreFdInfoKHR; sType: VkStructureType; pNext: null; semaphore: VkSemaphore | null; flags: VkSemaphoreImportFlagBits; handleType: VkExternalSemaphoreHandleTypeFlagBits; fd: number; } export interface VkImportSemaphoreFdInfoKHR { sType: VkStructureType; pNext: null; semaphore: VkSemaphore | null; flags: VkSemaphoreImportFlagBits; handleType: VkExternalSemaphoreHandleTypeFlagBits; fd: number; } /** ## VkExportSemaphoreCreateInfoKHR ## */ interface VkExportSemaphoreCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; handleTypes?: VkExternalSemaphoreHandleTypeFlagBits; } declare var VkExportSemaphoreCreateInfoKHR: { prototype: VkExportSemaphoreCreateInfoKHR; new(param?: VkExportSemaphoreCreateInfoKHRInitializer | null): VkExportSemaphoreCreateInfoKHR; sType: VkStructureType; pNext: null; handleTypes: VkExternalSemaphoreHandleTypeFlagBits; } export interface VkExportSemaphoreCreateInfoKHR { sType: VkStructureType; pNext: null; handleTypes: VkExternalSemaphoreHandleTypeFlagBits; } /** ## VkExportSemaphoreCreateInfo ## */ interface VkExportSemaphoreCreateInfoInitializer { sType?: VkStructureType; pNext?: null; handleTypes?: VkExternalSemaphoreHandleTypeFlagBits; } declare var VkExportSemaphoreCreateInfo: { prototype: VkExportSemaphoreCreateInfo; new(param?: VkExportSemaphoreCreateInfoInitializer | null): VkExportSemaphoreCreateInfo; sType: VkStructureType; pNext: null; handleTypes: VkExternalSemaphoreHandleTypeFlagBits; } export interface VkExportSemaphoreCreateInfo { sType: VkStructureType; pNext: null; handleTypes: VkExternalSemaphoreHandleTypeFlagBits; } /** ## VkExternalSemaphorePropertiesKHR ## */ interface VkExternalSemaphorePropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly exportFromImportedHandleTypes?: VkExternalSemaphoreHandleTypeFlagBits; readonly compatibleHandleTypes?: VkExternalSemaphoreHandleTypeFlagBits; readonly externalSemaphoreFeatures?: VkExternalSemaphoreFeatureFlagBits; } declare var VkExternalSemaphorePropertiesKHR: { prototype: VkExternalSemaphorePropertiesKHR; new(param?: VkExternalSemaphorePropertiesKHRInitializer | null): VkExternalSemaphorePropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly exportFromImportedHandleTypes: VkExternalSemaphoreHandleTypeFlagBits; readonly compatibleHandleTypes: VkExternalSemaphoreHandleTypeFlagBits; readonly externalSemaphoreFeatures: VkExternalSemaphoreFeatureFlagBits; } export interface VkExternalSemaphorePropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly exportFromImportedHandleTypes: VkExternalSemaphoreHandleTypeFlagBits; readonly compatibleHandleTypes: VkExternalSemaphoreHandleTypeFlagBits; readonly externalSemaphoreFeatures: VkExternalSemaphoreFeatureFlagBits; } /** ## VkExternalSemaphoreProperties ## */ interface VkExternalSemaphorePropertiesInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly exportFromImportedHandleTypes?: VkExternalSemaphoreHandleTypeFlagBits; readonly compatibleHandleTypes?: VkExternalSemaphoreHandleTypeFlagBits; readonly externalSemaphoreFeatures?: VkExternalSemaphoreFeatureFlagBits; } declare var VkExternalSemaphoreProperties: { prototype: VkExternalSemaphoreProperties; new(param?: VkExternalSemaphorePropertiesInitializer | null): VkExternalSemaphoreProperties; readonly sType: VkStructureType; readonly pNext: null; readonly exportFromImportedHandleTypes: VkExternalSemaphoreHandleTypeFlagBits; readonly compatibleHandleTypes: VkExternalSemaphoreHandleTypeFlagBits; readonly externalSemaphoreFeatures: VkExternalSemaphoreFeatureFlagBits; } export interface VkExternalSemaphoreProperties { readonly sType: VkStructureType; readonly pNext: null; readonly exportFromImportedHandleTypes: VkExternalSemaphoreHandleTypeFlagBits; readonly compatibleHandleTypes: VkExternalSemaphoreHandleTypeFlagBits; readonly externalSemaphoreFeatures: VkExternalSemaphoreFeatureFlagBits; } /** ## VkPhysicalDeviceExternalSemaphoreInfoKHR ## */ interface VkPhysicalDeviceExternalSemaphoreInfoKHRInitializer { sType?: VkStructureType; pNext?: null; handleType?: VkExternalSemaphoreHandleTypeFlagBits; } declare var VkPhysicalDeviceExternalSemaphoreInfoKHR: { prototype: VkPhysicalDeviceExternalSemaphoreInfoKHR; new(param?: VkPhysicalDeviceExternalSemaphoreInfoKHRInitializer | null): VkPhysicalDeviceExternalSemaphoreInfoKHR; sType: VkStructureType; pNext: null; handleType: VkExternalSemaphoreHandleTypeFlagBits; } export interface VkPhysicalDeviceExternalSemaphoreInfoKHR { sType: VkStructureType; pNext: null; handleType: VkExternalSemaphoreHandleTypeFlagBits; } /** ## VkPhysicalDeviceExternalSemaphoreInfo ## */ interface VkPhysicalDeviceExternalSemaphoreInfoInitializer { sType?: VkStructureType; pNext?: null; handleType?: VkExternalSemaphoreHandleTypeFlagBits; } declare var VkPhysicalDeviceExternalSemaphoreInfo: { prototype: VkPhysicalDeviceExternalSemaphoreInfo; new(param?: VkPhysicalDeviceExternalSemaphoreInfoInitializer | null): VkPhysicalDeviceExternalSemaphoreInfo; sType: VkStructureType; pNext: null; handleType: VkExternalSemaphoreHandleTypeFlagBits; } export interface VkPhysicalDeviceExternalSemaphoreInfo { sType: VkStructureType; pNext: null; handleType: VkExternalSemaphoreHandleTypeFlagBits; } /** ## VkMemoryGetFdInfoKHR ## */ interface VkMemoryGetFdInfoKHRInitializer { sType?: VkStructureType; pNext?: null; memory?: VkDeviceMemory | null; handleType?: VkExternalMemoryHandleTypeFlagBits; } declare var VkMemoryGetFdInfoKHR: { prototype: VkMemoryGetFdInfoKHR; new(param?: VkMemoryGetFdInfoKHRInitializer | null): VkMemoryGetFdInfoKHR; sType: VkStructureType; pNext: null; memory: VkDeviceMemory | null; handleType: VkExternalMemoryHandleTypeFlagBits; } export interface VkMemoryGetFdInfoKHR { sType: VkStructureType; pNext: null; memory: VkDeviceMemory | null; handleType: VkExternalMemoryHandleTypeFlagBits; } /** ## VkMemoryFdPropertiesKHR ## */ interface VkMemoryFdPropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly memoryTypeBits?: number; } declare var VkMemoryFdPropertiesKHR: { prototype: VkMemoryFdPropertiesKHR; new(param?: VkMemoryFdPropertiesKHRInitializer | null): VkMemoryFdPropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly memoryTypeBits: number; } export interface VkMemoryFdPropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly memoryTypeBits: number; } /** ## VkImportMemoryFdInfoKHR ## */ interface VkImportMemoryFdInfoKHRInitializer { sType?: VkStructureType; pNext?: null; handleType?: VkExternalMemoryHandleTypeFlagBits; fd?: number; } declare var VkImportMemoryFdInfoKHR: { prototype: VkImportMemoryFdInfoKHR; new(param?: VkImportMemoryFdInfoKHRInitializer | null): VkImportMemoryFdInfoKHR; sType: VkStructureType; pNext: null; handleType: VkExternalMemoryHandleTypeFlagBits; fd: number; } export interface VkImportMemoryFdInfoKHR { sType: VkStructureType; pNext: null; handleType: VkExternalMemoryHandleTypeFlagBits; fd: number; } /** ## VkExportMemoryAllocateInfoKHR ## */ interface VkExportMemoryAllocateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; handleTypes?: VkExternalMemoryHandleTypeFlagBits; } declare var VkExportMemoryAllocateInfoKHR: { prototype: VkExportMemoryAllocateInfoKHR; new(param?: VkExportMemoryAllocateInfoKHRInitializer | null): VkExportMemoryAllocateInfoKHR; sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBits; } export interface VkExportMemoryAllocateInfoKHR { sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBits; } /** ## VkExportMemoryAllocateInfo ## */ interface VkExportMemoryAllocateInfoInitializer { sType?: VkStructureType; pNext?: null; handleTypes?: VkExternalMemoryHandleTypeFlagBits; } declare var VkExportMemoryAllocateInfo: { prototype: VkExportMemoryAllocateInfo; new(param?: VkExportMemoryAllocateInfoInitializer | null): VkExportMemoryAllocateInfo; sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBits; } export interface VkExportMemoryAllocateInfo { sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBits; } /** ## VkExternalMemoryBufferCreateInfoKHR ## */ interface VkExternalMemoryBufferCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; handleTypes?: VkExternalMemoryHandleTypeFlagBits; } declare var VkExternalMemoryBufferCreateInfoKHR: { prototype: VkExternalMemoryBufferCreateInfoKHR; new(param?: VkExternalMemoryBufferCreateInfoKHRInitializer | null): VkExternalMemoryBufferCreateInfoKHR; sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBits; } export interface VkExternalMemoryBufferCreateInfoKHR { sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBits; } /** ## VkExternalMemoryBufferCreateInfo ## */ interface VkExternalMemoryBufferCreateInfoInitializer { sType?: VkStructureType; pNext?: null; handleTypes?: VkExternalMemoryHandleTypeFlagBits; } declare var VkExternalMemoryBufferCreateInfo: { prototype: VkExternalMemoryBufferCreateInfo; new(param?: VkExternalMemoryBufferCreateInfoInitializer | null): VkExternalMemoryBufferCreateInfo; sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBits; } export interface VkExternalMemoryBufferCreateInfo { sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBits; } /** ## VkExternalMemoryImageCreateInfoKHR ## */ interface VkExternalMemoryImageCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; handleTypes?: VkExternalMemoryHandleTypeFlagBits; } declare var VkExternalMemoryImageCreateInfoKHR: { prototype: VkExternalMemoryImageCreateInfoKHR; new(param?: VkExternalMemoryImageCreateInfoKHRInitializer | null): VkExternalMemoryImageCreateInfoKHR; sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBits; } export interface VkExternalMemoryImageCreateInfoKHR { sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBits; } /** ## VkExternalMemoryImageCreateInfo ## */ interface VkExternalMemoryImageCreateInfoInitializer { sType?: VkStructureType; pNext?: null; handleTypes?: VkExternalMemoryHandleTypeFlagBits; } declare var VkExternalMemoryImageCreateInfo: { prototype: VkExternalMemoryImageCreateInfo; new(param?: VkExternalMemoryImageCreateInfoInitializer | null): VkExternalMemoryImageCreateInfo; sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBits; } export interface VkExternalMemoryImageCreateInfo { sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBits; } /** ## VkPhysicalDeviceIDPropertiesKHR ## */ interface VkPhysicalDeviceIDPropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly deviceUUID?: number[] | null; readonly driverUUID?: number[] | null; readonly deviceLUID?: number[] | null; readonly deviceNodeMask?: number; readonly deviceLUIDValid?: number; } declare var VkPhysicalDeviceIDPropertiesKHR: { prototype: VkPhysicalDeviceIDPropertiesKHR; new(param?: VkPhysicalDeviceIDPropertiesKHRInitializer | null): VkPhysicalDeviceIDPropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly deviceUUID: number[] | null; readonly driverUUID: number[] | null; readonly deviceLUID: number[] | null; readonly deviceNodeMask: number; readonly deviceLUIDValid: number; } export interface VkPhysicalDeviceIDPropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly deviceUUID: number[] | null; readonly driverUUID: number[] | null; readonly deviceLUID: number[] | null; readonly deviceNodeMask: number; readonly deviceLUIDValid: number; } /** ## VkPhysicalDeviceIDProperties ## */ interface VkPhysicalDeviceIDPropertiesInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly deviceUUID?: number[] | null; readonly driverUUID?: number[] | null; readonly deviceLUID?: number[] | null; readonly deviceNodeMask?: number; readonly deviceLUIDValid?: number; } declare var VkPhysicalDeviceIDProperties: { prototype: VkPhysicalDeviceIDProperties; new(param?: VkPhysicalDeviceIDPropertiesInitializer | null): VkPhysicalDeviceIDProperties; readonly sType: VkStructureType; readonly pNext: null; readonly deviceUUID: number[] | null; readonly driverUUID: number[] | null; readonly deviceLUID: number[] | null; readonly deviceNodeMask: number; readonly deviceLUIDValid: number; } export interface VkPhysicalDeviceIDProperties { readonly sType: VkStructureType; readonly pNext: null; readonly deviceUUID: number[] | null; readonly driverUUID: number[] | null; readonly deviceLUID: number[] | null; readonly deviceNodeMask: number; readonly deviceLUIDValid: number; } /** ## VkExternalBufferPropertiesKHR ## */ interface VkExternalBufferPropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly externalMemoryProperties?: VkExternalMemoryProperties | null; } declare var VkExternalBufferPropertiesKHR: { prototype: VkExternalBufferPropertiesKHR; new(param?: VkExternalBufferPropertiesKHRInitializer | null): VkExternalBufferPropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly externalMemoryProperties: VkExternalMemoryProperties | null; } export interface VkExternalBufferPropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly externalMemoryProperties: VkExternalMemoryProperties | null; } /** ## VkExternalBufferProperties ## */ interface VkExternalBufferPropertiesInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly externalMemoryProperties?: VkExternalMemoryProperties | null; } declare var VkExternalBufferProperties: { prototype: VkExternalBufferProperties; new(param?: VkExternalBufferPropertiesInitializer | null): VkExternalBufferProperties; readonly sType: VkStructureType; readonly pNext: null; readonly externalMemoryProperties: VkExternalMemoryProperties | null; } export interface VkExternalBufferProperties { readonly sType: VkStructureType; readonly pNext: null; readonly externalMemoryProperties: VkExternalMemoryProperties | null; } /** ## VkPhysicalDeviceExternalBufferInfoKHR ## */ interface VkPhysicalDeviceExternalBufferInfoKHRInitializer { sType?: VkStructureType; pNext?: null; flags?: VkBufferCreateFlagBits; usage?: VkBufferUsageFlagBits; handleType?: VkExternalMemoryHandleTypeFlagBits; } declare var VkPhysicalDeviceExternalBufferInfoKHR: { prototype: VkPhysicalDeviceExternalBufferInfoKHR; new(param?: VkPhysicalDeviceExternalBufferInfoKHRInitializer | null): VkPhysicalDeviceExternalBufferInfoKHR; sType: VkStructureType; pNext: null; flags: VkBufferCreateFlagBits; usage: VkBufferUsageFlagBits; handleType: VkExternalMemoryHandleTypeFlagBits; } export interface VkPhysicalDeviceExternalBufferInfoKHR { sType: VkStructureType; pNext: null; flags: VkBufferCreateFlagBits; usage: VkBufferUsageFlagBits; handleType: VkExternalMemoryHandleTypeFlagBits; } /** ## VkPhysicalDeviceExternalBufferInfo ## */ interface VkPhysicalDeviceExternalBufferInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkBufferCreateFlagBits; usage?: VkBufferUsageFlagBits; handleType?: VkExternalMemoryHandleTypeFlagBits; } declare var VkPhysicalDeviceExternalBufferInfo: { prototype: VkPhysicalDeviceExternalBufferInfo; new(param?: VkPhysicalDeviceExternalBufferInfoInitializer | null): VkPhysicalDeviceExternalBufferInfo; sType: VkStructureType; pNext: null; flags: VkBufferCreateFlagBits; usage: VkBufferUsageFlagBits; handleType: VkExternalMemoryHandleTypeFlagBits; } export interface VkPhysicalDeviceExternalBufferInfo { sType: VkStructureType; pNext: null; flags: VkBufferCreateFlagBits; usage: VkBufferUsageFlagBits; handleType: VkExternalMemoryHandleTypeFlagBits; } /** ## VkExternalImageFormatPropertiesKHR ## */ interface VkExternalImageFormatPropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly externalMemoryProperties?: VkExternalMemoryProperties | null; } declare var VkExternalImageFormatPropertiesKHR: { prototype: VkExternalImageFormatPropertiesKHR; new(param?: VkExternalImageFormatPropertiesKHRInitializer | null): VkExternalImageFormatPropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly externalMemoryProperties: VkExternalMemoryProperties | null; } export interface VkExternalImageFormatPropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly externalMemoryProperties: VkExternalMemoryProperties | null; } /** ## VkExternalImageFormatProperties ## */ interface VkExternalImageFormatPropertiesInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly externalMemoryProperties?: VkExternalMemoryProperties | null; } declare var VkExternalImageFormatProperties: { prototype: VkExternalImageFormatProperties; new(param?: VkExternalImageFormatPropertiesInitializer | null): VkExternalImageFormatProperties; readonly sType: VkStructureType; readonly pNext: null; readonly externalMemoryProperties: VkExternalMemoryProperties | null; } export interface VkExternalImageFormatProperties { readonly sType: VkStructureType; readonly pNext: null; readonly externalMemoryProperties: VkExternalMemoryProperties | null; } /** ## VkPhysicalDeviceExternalImageFormatInfoKHR ## */ interface VkPhysicalDeviceExternalImageFormatInfoKHRInitializer { sType?: VkStructureType; pNext?: null; handleType?: VkExternalMemoryHandleTypeFlagBits; } declare var VkPhysicalDeviceExternalImageFormatInfoKHR: { prototype: VkPhysicalDeviceExternalImageFormatInfoKHR; new(param?: VkPhysicalDeviceExternalImageFormatInfoKHRInitializer | null): VkPhysicalDeviceExternalImageFormatInfoKHR; sType: VkStructureType; pNext: null; handleType: VkExternalMemoryHandleTypeFlagBits; } export interface VkPhysicalDeviceExternalImageFormatInfoKHR { sType: VkStructureType; pNext: null; handleType: VkExternalMemoryHandleTypeFlagBits; } /** ## VkPhysicalDeviceExternalImageFormatInfo ## */ interface VkPhysicalDeviceExternalImageFormatInfoInitializer { sType?: VkStructureType; pNext?: null; handleType?: VkExternalMemoryHandleTypeFlagBits; } declare var VkPhysicalDeviceExternalImageFormatInfo: { prototype: VkPhysicalDeviceExternalImageFormatInfo; new(param?: VkPhysicalDeviceExternalImageFormatInfoInitializer | null): VkPhysicalDeviceExternalImageFormatInfo; sType: VkStructureType; pNext: null; handleType: VkExternalMemoryHandleTypeFlagBits; } export interface VkPhysicalDeviceExternalImageFormatInfo { sType: VkStructureType; pNext: null; handleType: VkExternalMemoryHandleTypeFlagBits; } /** ## VkExternalMemoryPropertiesKHR ## */ interface VkExternalMemoryPropertiesKHRInitializer { readonly externalMemoryFeatures?: VkExternalMemoryFeatureFlagBits; readonly exportFromImportedHandleTypes?: VkExternalMemoryHandleTypeFlagBits; readonly compatibleHandleTypes?: VkExternalMemoryHandleTypeFlagBits; } declare var VkExternalMemoryPropertiesKHR: { prototype: VkExternalMemoryPropertiesKHR; new(param?: VkExternalMemoryPropertiesKHRInitializer | null): VkExternalMemoryPropertiesKHR; readonly externalMemoryFeatures: VkExternalMemoryFeatureFlagBits; readonly exportFromImportedHandleTypes: VkExternalMemoryHandleTypeFlagBits; readonly compatibleHandleTypes: VkExternalMemoryHandleTypeFlagBits; } export interface VkExternalMemoryPropertiesKHR { readonly externalMemoryFeatures: VkExternalMemoryFeatureFlagBits; readonly exportFromImportedHandleTypes: VkExternalMemoryHandleTypeFlagBits; readonly compatibleHandleTypes: VkExternalMemoryHandleTypeFlagBits; } /** ## VkExternalMemoryProperties ## */ interface VkExternalMemoryPropertiesInitializer { readonly externalMemoryFeatures?: VkExternalMemoryFeatureFlagBits; readonly exportFromImportedHandleTypes?: VkExternalMemoryHandleTypeFlagBits; readonly compatibleHandleTypes?: VkExternalMemoryHandleTypeFlagBits; } declare var VkExternalMemoryProperties: { prototype: VkExternalMemoryProperties; new(param?: VkExternalMemoryPropertiesInitializer | null): VkExternalMemoryProperties; readonly externalMemoryFeatures: VkExternalMemoryFeatureFlagBits; readonly exportFromImportedHandleTypes: VkExternalMemoryHandleTypeFlagBits; readonly compatibleHandleTypes: VkExternalMemoryHandleTypeFlagBits; } export interface VkExternalMemoryProperties { readonly externalMemoryFeatures: VkExternalMemoryFeatureFlagBits; readonly exportFromImportedHandleTypes: VkExternalMemoryHandleTypeFlagBits; readonly compatibleHandleTypes: VkExternalMemoryHandleTypeFlagBits; } /** ## VkPhysicalDeviceVariablePointerFeaturesKHR ## */ interface VkPhysicalDeviceVariablePointerFeaturesKHRInitializer { sType?: VkStructureType; pNext?: null; variablePointersStorageBuffer?: number; variablePointers?: number; } declare var VkPhysicalDeviceVariablePointerFeaturesKHR: { prototype: VkPhysicalDeviceVariablePointerFeaturesKHR; new(param?: VkPhysicalDeviceVariablePointerFeaturesKHRInitializer | null): VkPhysicalDeviceVariablePointerFeaturesKHR; sType: VkStructureType; pNext: null; variablePointersStorageBuffer: number; variablePointers: number; } export interface VkPhysicalDeviceVariablePointerFeaturesKHR { sType: VkStructureType; pNext: null; variablePointersStorageBuffer: number; variablePointers: number; } /** ## VkPhysicalDeviceVariablePointerFeatures ## */ interface VkPhysicalDeviceVariablePointerFeaturesInitializer { sType?: VkStructureType; pNext?: null; variablePointersStorageBuffer?: number; variablePointers?: number; } declare var VkPhysicalDeviceVariablePointerFeatures: { prototype: VkPhysicalDeviceVariablePointerFeatures; new(param?: VkPhysicalDeviceVariablePointerFeaturesInitializer | null): VkPhysicalDeviceVariablePointerFeatures; sType: VkStructureType; pNext: null; variablePointersStorageBuffer: number; variablePointers: number; } export interface VkPhysicalDeviceVariablePointerFeatures { sType: VkStructureType; pNext: null; variablePointersStorageBuffer: number; variablePointers: number; } /** ## VkRectLayerKHR ## */ interface VkRectLayerKHRInitializer { offset?: VkOffset2D | null; extent?: VkExtent2D | null; layer?: number; } declare var VkRectLayerKHR: { prototype: VkRectLayerKHR; new(param?: VkRectLayerKHRInitializer | null): VkRectLayerKHR; offset: VkOffset2D | null; extent: VkExtent2D | null; layer: number; } export interface VkRectLayerKHR { offset: VkOffset2D | null; extent: VkExtent2D | null; layer: number; } /** ## VkPresentRegionKHR ## */ interface VkPresentRegionKHRInitializer { rectangleCount?: number; pRectangles?: VkRectLayerKHR[] | null; } declare var VkPresentRegionKHR: { prototype: VkPresentRegionKHR; new(param?: VkPresentRegionKHRInitializer | null): VkPresentRegionKHR; rectangleCount: number; pRectangles: VkRectLayerKHR[] | null; } export interface VkPresentRegionKHR { rectangleCount: number; pRectangles: VkRectLayerKHR[] | null; } /** ## VkPresentRegionsKHR ## */ interface VkPresentRegionsKHRInitializer { sType?: VkStructureType; pNext?: null; swapchainCount?: number; pRegions?: VkPresentRegionKHR[] | null; } declare var VkPresentRegionsKHR: { prototype: VkPresentRegionsKHR; new(param?: VkPresentRegionsKHRInitializer | null): VkPresentRegionsKHR; sType: VkStructureType; pNext: null; swapchainCount: number; pRegions: VkPresentRegionKHR[] | null; } export interface VkPresentRegionsKHR { sType: VkStructureType; pNext: null; swapchainCount: number; pRegions: VkPresentRegionKHR[] | null; } /** ## VkPhysicalDeviceDriverPropertiesKHR ## */ interface VkPhysicalDeviceDriverPropertiesKHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly driverID?: VkDriverIdKHR; readonly driverName?: string | null; readonly driverInfo?: string | null; readonly conformanceVersion?: VkConformanceVersionKHR | null; } declare var VkPhysicalDeviceDriverPropertiesKHR: { prototype: VkPhysicalDeviceDriverPropertiesKHR; new(param?: VkPhysicalDeviceDriverPropertiesKHRInitializer | null): VkPhysicalDeviceDriverPropertiesKHR; readonly sType: VkStructureType; readonly pNext: null; readonly driverID: VkDriverIdKHR; readonly driverName: string | null; readonly driverInfo: string | null; readonly conformanceVersion: VkConformanceVersionKHR | null; } export interface VkPhysicalDeviceDriverPropertiesKHR { readonly sType: VkStructureType; readonly pNext: null; readonly driverID: VkDriverIdKHR; readonly driverName: string | null; readonly driverInfo: string | null; readonly conformanceVersion: VkConformanceVersionKHR | null; } /** ## VkConformanceVersionKHR ## */ interface VkConformanceVersionKHRInitializer { major?: number; minor?: number; subminor?: number; patch?: number; } declare var VkConformanceVersionKHR: { prototype: VkConformanceVersionKHR; new(param?: VkConformanceVersionKHRInitializer | null): VkConformanceVersionKHR; major: number; minor: number; subminor: number; patch: number; } export interface VkConformanceVersionKHR { major: number; minor: number; subminor: number; patch: number; } /** ## VkPhysicalDevicePushDescriptorPropertiesKHR ## */ interface VkPhysicalDevicePushDescriptorPropertiesKHRInitializer { sType?: VkStructureType; pNext?: null; maxPushDescriptors?: number; } declare var VkPhysicalDevicePushDescriptorPropertiesKHR: { prototype: VkPhysicalDevicePushDescriptorPropertiesKHR; new(param?: VkPhysicalDevicePushDescriptorPropertiesKHRInitializer | null): VkPhysicalDevicePushDescriptorPropertiesKHR; sType: VkStructureType; pNext: null; maxPushDescriptors: number; } export interface VkPhysicalDevicePushDescriptorPropertiesKHR { sType: VkStructureType; pNext: null; maxPushDescriptors: number; } /** ## VkPhysicalDeviceSparseImageFormatInfo2KHR ## */ interface VkPhysicalDeviceSparseImageFormatInfo2KHRInitializer { sType?: VkStructureType; pNext?: null; format?: VkFormat; type?: VkImageType; samples?: VkSampleCountFlagBits; usage?: VkImageUsageFlagBits; tiling?: VkImageTiling; } declare var VkPhysicalDeviceSparseImageFormatInfo2KHR: { prototype: VkPhysicalDeviceSparseImageFormatInfo2KHR; new(param?: VkPhysicalDeviceSparseImageFormatInfo2KHRInitializer | null): VkPhysicalDeviceSparseImageFormatInfo2KHR; sType: VkStructureType; pNext: null; format: VkFormat; type: VkImageType; samples: VkSampleCountFlagBits; usage: VkImageUsageFlagBits; tiling: VkImageTiling; } export interface VkPhysicalDeviceSparseImageFormatInfo2KHR { sType: VkStructureType; pNext: null; format: VkFormat; type: VkImageType; samples: VkSampleCountFlagBits; usage: VkImageUsageFlagBits; tiling: VkImageTiling; } /** ## VkPhysicalDeviceSparseImageFormatInfo2 ## */ interface VkPhysicalDeviceSparseImageFormatInfo2Initializer { sType?: VkStructureType; pNext?: null; format?: VkFormat; type?: VkImageType; samples?: VkSampleCountFlagBits; usage?: VkImageUsageFlagBits; tiling?: VkImageTiling; } declare var VkPhysicalDeviceSparseImageFormatInfo2: { prototype: VkPhysicalDeviceSparseImageFormatInfo2; new(param?: VkPhysicalDeviceSparseImageFormatInfo2Initializer | null): VkPhysicalDeviceSparseImageFormatInfo2; sType: VkStructureType; pNext: null; format: VkFormat; type: VkImageType; samples: VkSampleCountFlagBits; usage: VkImageUsageFlagBits; tiling: VkImageTiling; } export interface VkPhysicalDeviceSparseImageFormatInfo2 { sType: VkStructureType; pNext: null; format: VkFormat; type: VkImageType; samples: VkSampleCountFlagBits; usage: VkImageUsageFlagBits; tiling: VkImageTiling; } /** ## VkSparseImageFormatProperties2KHR ## */ interface VkSparseImageFormatProperties2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly properties?: VkSparseImageFormatProperties | null; } declare var VkSparseImageFormatProperties2KHR: { prototype: VkSparseImageFormatProperties2KHR; new(param?: VkSparseImageFormatProperties2KHRInitializer | null): VkSparseImageFormatProperties2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly properties: VkSparseImageFormatProperties | null; } export interface VkSparseImageFormatProperties2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly properties: VkSparseImageFormatProperties | null; } /** ## VkSparseImageFormatProperties2 ## */ interface VkSparseImageFormatProperties2Initializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly properties?: VkSparseImageFormatProperties | null; } declare var VkSparseImageFormatProperties2: { prototype: VkSparseImageFormatProperties2; new(param?: VkSparseImageFormatProperties2Initializer | null): VkSparseImageFormatProperties2; readonly sType: VkStructureType; readonly pNext: null; readonly properties: VkSparseImageFormatProperties | null; } export interface VkSparseImageFormatProperties2 { readonly sType: VkStructureType; readonly pNext: null; readonly properties: VkSparseImageFormatProperties | null; } /** ## VkPhysicalDeviceMemoryProperties2KHR ## */ interface VkPhysicalDeviceMemoryProperties2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly memoryProperties?: VkPhysicalDeviceMemoryProperties | null; } declare var VkPhysicalDeviceMemoryProperties2KHR: { prototype: VkPhysicalDeviceMemoryProperties2KHR; new(param?: VkPhysicalDeviceMemoryProperties2KHRInitializer | null): VkPhysicalDeviceMemoryProperties2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly memoryProperties: VkPhysicalDeviceMemoryProperties | null; } export interface VkPhysicalDeviceMemoryProperties2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly memoryProperties: VkPhysicalDeviceMemoryProperties | null; } /** ## VkPhysicalDeviceMemoryProperties2 ## */ interface VkPhysicalDeviceMemoryProperties2Initializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly memoryProperties?: VkPhysicalDeviceMemoryProperties | null; } declare var VkPhysicalDeviceMemoryProperties2: { prototype: VkPhysicalDeviceMemoryProperties2; new(param?: VkPhysicalDeviceMemoryProperties2Initializer | null): VkPhysicalDeviceMemoryProperties2; readonly sType: VkStructureType; readonly pNext: null; readonly memoryProperties: VkPhysicalDeviceMemoryProperties | null; } export interface VkPhysicalDeviceMemoryProperties2 { readonly sType: VkStructureType; readonly pNext: null; readonly memoryProperties: VkPhysicalDeviceMemoryProperties | null; } /** ## VkQueueFamilyProperties2KHR ## */ interface VkQueueFamilyProperties2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly queueFamilyProperties?: VkQueueFamilyProperties | null; } declare var VkQueueFamilyProperties2KHR: { prototype: VkQueueFamilyProperties2KHR; new(param?: VkQueueFamilyProperties2KHRInitializer | null): VkQueueFamilyProperties2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly queueFamilyProperties: VkQueueFamilyProperties | null; } export interface VkQueueFamilyProperties2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly queueFamilyProperties: VkQueueFamilyProperties | null; } /** ## VkQueueFamilyProperties2 ## */ interface VkQueueFamilyProperties2Initializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly queueFamilyProperties?: VkQueueFamilyProperties | null; } declare var VkQueueFamilyProperties2: { prototype: VkQueueFamilyProperties2; new(param?: VkQueueFamilyProperties2Initializer | null): VkQueueFamilyProperties2; readonly sType: VkStructureType; readonly pNext: null; readonly queueFamilyProperties: VkQueueFamilyProperties | null; } export interface VkQueueFamilyProperties2 { readonly sType: VkStructureType; readonly pNext: null; readonly queueFamilyProperties: VkQueueFamilyProperties | null; } /** ## VkPhysicalDeviceImageFormatInfo2KHR ## */ interface VkPhysicalDeviceImageFormatInfo2KHRInitializer { sType?: VkStructureType; pNext?: null; format?: VkFormat; type?: VkImageType; tiling?: VkImageTiling; usage?: VkImageUsageFlagBits; flags?: VkImageCreateFlagBits; } declare var VkPhysicalDeviceImageFormatInfo2KHR: { prototype: VkPhysicalDeviceImageFormatInfo2KHR; new(param?: VkPhysicalDeviceImageFormatInfo2KHRInitializer | null): VkPhysicalDeviceImageFormatInfo2KHR; sType: VkStructureType; pNext: null; format: VkFormat; type: VkImageType; tiling: VkImageTiling; usage: VkImageUsageFlagBits; flags: VkImageCreateFlagBits; } export interface VkPhysicalDeviceImageFormatInfo2KHR { sType: VkStructureType; pNext: null; format: VkFormat; type: VkImageType; tiling: VkImageTiling; usage: VkImageUsageFlagBits; flags: VkImageCreateFlagBits; } /** ## VkPhysicalDeviceImageFormatInfo2 ## */ interface VkPhysicalDeviceImageFormatInfo2Initializer { sType?: VkStructureType; pNext?: null; format?: VkFormat; type?: VkImageType; tiling?: VkImageTiling; usage?: VkImageUsageFlagBits; flags?: VkImageCreateFlagBits; } declare var VkPhysicalDeviceImageFormatInfo2: { prototype: VkPhysicalDeviceImageFormatInfo2; new(param?: VkPhysicalDeviceImageFormatInfo2Initializer | null): VkPhysicalDeviceImageFormatInfo2; sType: VkStructureType; pNext: null; format: VkFormat; type: VkImageType; tiling: VkImageTiling; usage: VkImageUsageFlagBits; flags: VkImageCreateFlagBits; } export interface VkPhysicalDeviceImageFormatInfo2 { sType: VkStructureType; pNext: null; format: VkFormat; type: VkImageType; tiling: VkImageTiling; usage: VkImageUsageFlagBits; flags: VkImageCreateFlagBits; } /** ## VkImageFormatProperties2KHR ## */ interface VkImageFormatProperties2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly imageFormatProperties?: VkImageFormatProperties | null; } declare var VkImageFormatProperties2KHR: { prototype: VkImageFormatProperties2KHR; new(param?: VkImageFormatProperties2KHRInitializer | null): VkImageFormatProperties2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly imageFormatProperties: VkImageFormatProperties | null; } export interface VkImageFormatProperties2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly imageFormatProperties: VkImageFormatProperties | null; } /** ## VkImageFormatProperties2 ## */ interface VkImageFormatProperties2Initializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly imageFormatProperties?: VkImageFormatProperties | null; } declare var VkImageFormatProperties2: { prototype: VkImageFormatProperties2; new(param?: VkImageFormatProperties2Initializer | null): VkImageFormatProperties2; readonly sType: VkStructureType; readonly pNext: null; readonly imageFormatProperties: VkImageFormatProperties | null; } export interface VkImageFormatProperties2 { readonly sType: VkStructureType; readonly pNext: null; readonly imageFormatProperties: VkImageFormatProperties | null; } /** ## VkFormatProperties2KHR ## */ interface VkFormatProperties2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly formatProperties?: VkFormatProperties | null; } declare var VkFormatProperties2KHR: { prototype: VkFormatProperties2KHR; new(param?: VkFormatProperties2KHRInitializer | null): VkFormatProperties2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly formatProperties: VkFormatProperties | null; } export interface VkFormatProperties2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly formatProperties: VkFormatProperties | null; } /** ## VkFormatProperties2 ## */ interface VkFormatProperties2Initializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly formatProperties?: VkFormatProperties | null; } declare var VkFormatProperties2: { prototype: VkFormatProperties2; new(param?: VkFormatProperties2Initializer | null): VkFormatProperties2; readonly sType: VkStructureType; readonly pNext: null; readonly formatProperties: VkFormatProperties | null; } export interface VkFormatProperties2 { readonly sType: VkStructureType; readonly pNext: null; readonly formatProperties: VkFormatProperties | null; } /** ## VkPhysicalDeviceProperties2KHR ## */ interface VkPhysicalDeviceProperties2KHRInitializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly properties?: VkPhysicalDeviceProperties | null; } declare var VkPhysicalDeviceProperties2KHR: { prototype: VkPhysicalDeviceProperties2KHR; new(param?: VkPhysicalDeviceProperties2KHRInitializer | null): VkPhysicalDeviceProperties2KHR; readonly sType: VkStructureType; readonly pNext: null; readonly properties: VkPhysicalDeviceProperties | null; } export interface VkPhysicalDeviceProperties2KHR { readonly sType: VkStructureType; readonly pNext: null; readonly properties: VkPhysicalDeviceProperties | null; } /** ## VkPhysicalDeviceProperties2 ## */ interface VkPhysicalDeviceProperties2Initializer { readonly sType?: VkStructureType; readonly pNext?: null; readonly properties?: VkPhysicalDeviceProperties | null; } declare var VkPhysicalDeviceProperties2: { prototype: VkPhysicalDeviceProperties2; new(param?: VkPhysicalDeviceProperties2Initializer | null): VkPhysicalDeviceProperties2; readonly sType: VkStructureType; readonly pNext: null; readonly properties: VkPhysicalDeviceProperties | null; } export interface VkPhysicalDeviceProperties2 { readonly sType: VkStructureType; readonly pNext: null; readonly properties: VkPhysicalDeviceProperties | null; } /** ## VkPhysicalDeviceFeatures2KHR ## */ interface VkPhysicalDeviceFeatures2KHRInitializer { sType?: VkStructureType; pNext?: null; features?: VkPhysicalDeviceFeatures | null; } declare var VkPhysicalDeviceFeatures2KHR: { prototype: VkPhysicalDeviceFeatures2KHR; new(param?: VkPhysicalDeviceFeatures2KHRInitializer | null): VkPhysicalDeviceFeatures2KHR; sType: VkStructureType; pNext: null; features: VkPhysicalDeviceFeatures | null; } export interface VkPhysicalDeviceFeatures2KHR { sType: VkStructureType; pNext: null; features: VkPhysicalDeviceFeatures | null; } /** ## VkPhysicalDeviceFeatures2 ## */ interface VkPhysicalDeviceFeatures2Initializer { sType?: VkStructureType; pNext?: null; features?: VkPhysicalDeviceFeatures | null; } declare var VkPhysicalDeviceFeatures2: { prototype: VkPhysicalDeviceFeatures2; new(param?: VkPhysicalDeviceFeatures2Initializer | null): VkPhysicalDeviceFeatures2; sType: VkStructureType; pNext: null; features: VkPhysicalDeviceFeatures | null; } export interface VkPhysicalDeviceFeatures2 { sType: VkStructureType; pNext: null; features: VkPhysicalDeviceFeatures | null; } /** ## VkObjectTablePushConstantEntryNVX ## */ interface VkObjectTablePushConstantEntryNVXInitializer { type?: VkObjectEntryTypeNVX; flags?: VkObjectEntryUsageFlagBitsNVX; pipelineLayout?: VkPipelineLayout | null; stageFlags?: VkShaderStageFlagBits; } declare var VkObjectTablePushConstantEntryNVX: { prototype: VkObjectTablePushConstantEntryNVX; new(param?: VkObjectTablePushConstantEntryNVXInitializer | null): VkObjectTablePushConstantEntryNVX; type: VkObjectEntryTypeNVX; flags: VkObjectEntryUsageFlagBitsNVX; pipelineLayout: VkPipelineLayout | null; stageFlags: VkShaderStageFlagBits; } export interface VkObjectTablePushConstantEntryNVX { type: VkObjectEntryTypeNVX; flags: VkObjectEntryUsageFlagBitsNVX; pipelineLayout: VkPipelineLayout | null; stageFlags: VkShaderStageFlagBits; } /** ## VkObjectTableIndexBufferEntryNVX ## */ interface VkObjectTableIndexBufferEntryNVXInitializer { type?: VkObjectEntryTypeNVX; flags?: VkObjectEntryUsageFlagBitsNVX; buffer?: VkBuffer | null; indexType?: VkIndexType; } declare var VkObjectTableIndexBufferEntryNVX: { prototype: VkObjectTableIndexBufferEntryNVX; new(param?: VkObjectTableIndexBufferEntryNVXInitializer | null): VkObjectTableIndexBufferEntryNVX; type: VkObjectEntryTypeNVX; flags: VkObjectEntryUsageFlagBitsNVX; buffer: VkBuffer | null; indexType: VkIndexType; } export interface VkObjectTableIndexBufferEntryNVX { type: VkObjectEntryTypeNVX; flags: VkObjectEntryUsageFlagBitsNVX; buffer: VkBuffer | null; indexType: VkIndexType; } /** ## VkObjectTableVertexBufferEntryNVX ## */ interface VkObjectTableVertexBufferEntryNVXInitializer { type?: VkObjectEntryTypeNVX; flags?: VkObjectEntryUsageFlagBitsNVX; buffer?: VkBuffer | null; } declare var VkObjectTableVertexBufferEntryNVX: { prototype: VkObjectTableVertexBufferEntryNVX; new(param?: VkObjectTableVertexBufferEntryNVXInitializer | null): VkObjectTableVertexBufferEntryNVX; type: VkObjectEntryTypeNVX; flags: VkObjectEntryUsageFlagBitsNVX; buffer: VkBuffer | null; } export interface VkObjectTableVertexBufferEntryNVX { type: VkObjectEntryTypeNVX; flags: VkObjectEntryUsageFlagBitsNVX; buffer: VkBuffer | null; } /** ## VkObjectTableDescriptorSetEntryNVX ## */ interface VkObjectTableDescriptorSetEntryNVXInitializer { type?: VkObjectEntryTypeNVX; flags?: VkObjectEntryUsageFlagBitsNVX; pipelineLayout?: VkPipelineLayout | null; descriptorSet?: VkDescriptorSet | null; } declare var VkObjectTableDescriptorSetEntryNVX: { prototype: VkObjectTableDescriptorSetEntryNVX; new(param?: VkObjectTableDescriptorSetEntryNVXInitializer | null): VkObjectTableDescriptorSetEntryNVX; type: VkObjectEntryTypeNVX; flags: VkObjectEntryUsageFlagBitsNVX; pipelineLayout: VkPipelineLayout | null; descriptorSet: VkDescriptorSet | null; } export interface VkObjectTableDescriptorSetEntryNVX { type: VkObjectEntryTypeNVX; flags: VkObjectEntryUsageFlagBitsNVX; pipelineLayout: VkPipelineLayout | null; descriptorSet: VkDescriptorSet | null; } /** ## VkObjectTablePipelineEntryNVX ## */ interface VkObjectTablePipelineEntryNVXInitializer { type?: VkObjectEntryTypeNVX; flags?: VkObjectEntryUsageFlagBitsNVX; pipeline?: VkPipeline | null; } declare var VkObjectTablePipelineEntryNVX: { prototype: VkObjectTablePipelineEntryNVX; new(param?: VkObjectTablePipelineEntryNVXInitializer | null): VkObjectTablePipelineEntryNVX; type: VkObjectEntryTypeNVX; flags: VkObjectEntryUsageFlagBitsNVX; pipeline: VkPipeline | null; } export interface VkObjectTablePipelineEntryNVX { type: VkObjectEntryTypeNVX; flags: VkObjectEntryUsageFlagBitsNVX; pipeline: VkPipeline | null; } /** ## VkObjectTableEntryNVX ## */ interface VkObjectTableEntryNVXInitializer { type?: VkObjectEntryTypeNVX; flags?: VkObjectEntryUsageFlagBitsNVX; } declare var VkObjectTableEntryNVX: { prototype: VkObjectTableEntryNVX; new(param?: VkObjectTableEntryNVXInitializer | null): VkObjectTableEntryNVX; type: VkObjectEntryTypeNVX; flags: VkObjectEntryUsageFlagBitsNVX; } export interface VkObjectTableEntryNVX { type: VkObjectEntryTypeNVX; flags: VkObjectEntryUsageFlagBitsNVX; } /** ## VkObjectTableCreateInfoNVX ## */ interface VkObjectTableCreateInfoNVXInitializer { sType?: VkStructureType; pNext?: null; objectCount?: number; pObjectEntryTypes?: Int32Array | null; pObjectEntryCounts?: Uint32Array | null; pObjectEntryUsageFlags?: Int32Array | null; maxUniformBuffersPerDescriptor?: number; maxStorageBuffersPerDescriptor?: number; maxStorageImagesPerDescriptor?: number; maxSampledImagesPerDescriptor?: number; maxPipelineLayouts?: number; } declare var VkObjectTableCreateInfoNVX: { prototype: VkObjectTableCreateInfoNVX; new(param?: VkObjectTableCreateInfoNVXInitializer | null): VkObjectTableCreateInfoNVX; sType: VkStructureType; pNext: null; objectCount: number; pObjectEntryTypes: Int32Array | null; pObjectEntryCounts: Uint32Array | null; pObjectEntryUsageFlags: Int32Array | null; maxUniformBuffersPerDescriptor: number; maxStorageBuffersPerDescriptor: number; maxStorageImagesPerDescriptor: number; maxSampledImagesPerDescriptor: number; maxPipelineLayouts: number; } export interface VkObjectTableCreateInfoNVX { sType: VkStructureType; pNext: null; objectCount: number; pObjectEntryTypes: Int32Array | null; pObjectEntryCounts: Uint32Array | null; pObjectEntryUsageFlags: Int32Array | null; maxUniformBuffersPerDescriptor: number; maxStorageBuffersPerDescriptor: number; maxStorageImagesPerDescriptor: number; maxSampledImagesPerDescriptor: number; maxPipelineLayouts: number; } /** ## VkCmdReserveSpaceForCommandsInfoNVX ## */ interface VkCmdReserveSpaceForCommandsInfoNVXInitializer { sType?: VkStructureType; pNext?: null; objectTable?: VkObjectTableNVX | null; indirectCommandsLayout?: VkIndirectCommandsLayoutNVX | null; maxSequencesCount?: number; } declare var VkCmdReserveSpaceForCommandsInfoNVX: { prototype: VkCmdReserveSpaceForCommandsInfoNVX; new(param?: VkCmdReserveSpaceForCommandsInfoNVXInitializer | null): VkCmdReserveSpaceForCommandsInfoNVX; sType: VkStructureType; pNext: null; objectTable: VkObjectTableNVX | null; indirectCommandsLayout: VkIndirectCommandsLayoutNVX | null; maxSequencesCount: number; } export interface VkCmdReserveSpaceForCommandsInfoNVX { sType: VkStructureType; pNext: null; objectTable: VkObjectTableNVX | null; indirectCommandsLayout: VkIndirectCommandsLayoutNVX | null; maxSequencesCount: number; } /** ## VkCmdProcessCommandsInfoNVX ## */ interface VkCmdProcessCommandsInfoNVXInitializer { sType?: VkStructureType; pNext?: null; objectTable?: VkObjectTableNVX | null; indirectCommandsLayout?: VkIndirectCommandsLayoutNVX | null; indirectCommandsTokenCount?: number; pIndirectCommandsTokens?: VkIndirectCommandsTokenNVX[] | null; maxSequencesCount?: number; targetCommandBuffer?: VkCommandBuffer | null; sequencesCountBuffer?: VkBuffer | null; sequencesCountOffset?: number; sequencesIndexBuffer?: VkBuffer | null; sequencesIndexOffset?: number; } declare var VkCmdProcessCommandsInfoNVX: { prototype: VkCmdProcessCommandsInfoNVX; new(param?: VkCmdProcessCommandsInfoNVXInitializer | null): VkCmdProcessCommandsInfoNVX; sType: VkStructureType; pNext: null; objectTable: VkObjectTableNVX | null; indirectCommandsLayout: VkIndirectCommandsLayoutNVX | null; indirectCommandsTokenCount: number; pIndirectCommandsTokens: VkIndirectCommandsTokenNVX[] | null; maxSequencesCount: number; targetCommandBuffer: VkCommandBuffer | null; sequencesCountBuffer: VkBuffer | null; sequencesCountOffset: number; sequencesIndexBuffer: VkBuffer | null; sequencesIndexOffset: number; } export interface VkCmdProcessCommandsInfoNVX { sType: VkStructureType; pNext: null; objectTable: VkObjectTableNVX | null; indirectCommandsLayout: VkIndirectCommandsLayoutNVX | null; indirectCommandsTokenCount: number; pIndirectCommandsTokens: VkIndirectCommandsTokenNVX[] | null; maxSequencesCount: number; targetCommandBuffer: VkCommandBuffer | null; sequencesCountBuffer: VkBuffer | null; sequencesCountOffset: number; sequencesIndexBuffer: VkBuffer | null; sequencesIndexOffset: number; } /** ## VkIndirectCommandsLayoutCreateInfoNVX ## */ interface VkIndirectCommandsLayoutCreateInfoNVXInitializer { sType?: VkStructureType; pNext?: null; pipelineBindPoint?: VkPipelineBindPoint; flags?: VkIndirectCommandsLayoutUsageFlagBitsNVX; tokenCount?: number; pTokens?: VkIndirectCommandsLayoutTokenNVX[] | null; } declare var VkIndirectCommandsLayoutCreateInfoNVX: { prototype: VkIndirectCommandsLayoutCreateInfoNVX; new(param?: VkIndirectCommandsLayoutCreateInfoNVXInitializer | null): VkIndirectCommandsLayoutCreateInfoNVX; sType: VkStructureType; pNext: null; pipelineBindPoint: VkPipelineBindPoint; flags: VkIndirectCommandsLayoutUsageFlagBitsNVX; tokenCount: number; pTokens: VkIndirectCommandsLayoutTokenNVX[] | null; } export interface VkIndirectCommandsLayoutCreateInfoNVX { sType: VkStructureType; pNext: null; pipelineBindPoint: VkPipelineBindPoint; flags: VkIndirectCommandsLayoutUsageFlagBitsNVX; tokenCount: number; pTokens: VkIndirectCommandsLayoutTokenNVX[] | null; } /** ## VkIndirectCommandsLayoutTokenNVX ## */ interface VkIndirectCommandsLayoutTokenNVXInitializer { tokenType?: VkIndirectCommandsTokenTypeNVX; bindingUnit?: number; dynamicCount?: number; divisor?: number; } declare var VkIndirectCommandsLayoutTokenNVX: { prototype: VkIndirectCommandsLayoutTokenNVX; new(param?: VkIndirectCommandsLayoutTokenNVXInitializer | null): VkIndirectCommandsLayoutTokenNVX; tokenType: VkIndirectCommandsTokenTypeNVX; bindingUnit: number; dynamicCount: number; divisor: number; } export interface VkIndirectCommandsLayoutTokenNVX { tokenType: VkIndirectCommandsTokenTypeNVX; bindingUnit: number; dynamicCount: number; divisor: number; } /** ## VkIndirectCommandsTokenNVX ## */ interface VkIndirectCommandsTokenNVXInitializer { tokenType?: VkIndirectCommandsTokenTypeNVX; buffer?: VkBuffer | null; offset?: number; } declare var VkIndirectCommandsTokenNVX: { prototype: VkIndirectCommandsTokenNVX; new(param?: VkIndirectCommandsTokenNVXInitializer | null): VkIndirectCommandsTokenNVX; tokenType: VkIndirectCommandsTokenTypeNVX; buffer: VkBuffer | null; offset: number; } export interface VkIndirectCommandsTokenNVX { tokenType: VkIndirectCommandsTokenTypeNVX; buffer: VkBuffer | null; offset: number; } /** ## VkDeviceGeneratedCommandsLimitsNVX ## */ interface VkDeviceGeneratedCommandsLimitsNVXInitializer { sType?: VkStructureType; pNext?: null; maxIndirectCommandsLayoutTokenCount?: number; maxObjectEntryCounts?: number; minSequenceCountBufferOffsetAlignment?: number; minSequenceIndexBufferOffsetAlignment?: number; minCommandsTokenBufferOffsetAlignment?: number; } declare var VkDeviceGeneratedCommandsLimitsNVX: { prototype: VkDeviceGeneratedCommandsLimitsNVX; new(param?: VkDeviceGeneratedCommandsLimitsNVXInitializer | null): VkDeviceGeneratedCommandsLimitsNVX; sType: VkStructureType; pNext: null; maxIndirectCommandsLayoutTokenCount: number; maxObjectEntryCounts: number; minSequenceCountBufferOffsetAlignment: number; minSequenceIndexBufferOffsetAlignment: number; minCommandsTokenBufferOffsetAlignment: number; } export interface VkDeviceGeneratedCommandsLimitsNVX { sType: VkStructureType; pNext: null; maxIndirectCommandsLayoutTokenCount: number; maxObjectEntryCounts: number; minSequenceCountBufferOffsetAlignment: number; minSequenceIndexBufferOffsetAlignment: number; minCommandsTokenBufferOffsetAlignment: number; } /** ## VkDeviceGeneratedCommandsFeaturesNVX ## */ interface VkDeviceGeneratedCommandsFeaturesNVXInitializer { sType?: VkStructureType; pNext?: null; computeBindingPointSupport?: number; } declare var VkDeviceGeneratedCommandsFeaturesNVX: { prototype: VkDeviceGeneratedCommandsFeaturesNVX; new(param?: VkDeviceGeneratedCommandsFeaturesNVXInitializer | null): VkDeviceGeneratedCommandsFeaturesNVX; sType: VkStructureType; pNext: null; computeBindingPointSupport: number; } export interface VkDeviceGeneratedCommandsFeaturesNVX { sType: VkStructureType; pNext: null; computeBindingPointSupport: number; } /** ## VkExportMemoryAllocateInfoNV ## */ interface VkExportMemoryAllocateInfoNVInitializer { sType?: VkStructureType; pNext?: null; handleTypes?: VkExternalMemoryHandleTypeFlagBitsNV; } declare var VkExportMemoryAllocateInfoNV: { prototype: VkExportMemoryAllocateInfoNV; new(param?: VkExportMemoryAllocateInfoNVInitializer | null): VkExportMemoryAllocateInfoNV; sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBitsNV; } export interface VkExportMemoryAllocateInfoNV { sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBitsNV; } /** ## VkExternalMemoryImageCreateInfoNV ## */ interface VkExternalMemoryImageCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; handleTypes?: VkExternalMemoryHandleTypeFlagBitsNV; } declare var VkExternalMemoryImageCreateInfoNV: { prototype: VkExternalMemoryImageCreateInfoNV; new(param?: VkExternalMemoryImageCreateInfoNVInitializer | null): VkExternalMemoryImageCreateInfoNV; sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBitsNV; } export interface VkExternalMemoryImageCreateInfoNV { sType: VkStructureType; pNext: null; handleTypes: VkExternalMemoryHandleTypeFlagBitsNV; } /** ## VkExternalImageFormatPropertiesNV ## */ interface VkExternalImageFormatPropertiesNVInitializer { readonly imageFormatProperties?: VkImageFormatProperties | null; readonly externalMemoryFeatures?: VkExternalMemoryFeatureFlagBitsNV; readonly exportFromImportedHandleTypes?: VkExternalMemoryHandleTypeFlagBitsNV; readonly compatibleHandleTypes?: VkExternalMemoryHandleTypeFlagBitsNV; } declare var VkExternalImageFormatPropertiesNV: { prototype: VkExternalImageFormatPropertiesNV; new(param?: VkExternalImageFormatPropertiesNVInitializer | null): VkExternalImageFormatPropertiesNV; readonly imageFormatProperties: VkImageFormatProperties | null; readonly externalMemoryFeatures: VkExternalMemoryFeatureFlagBitsNV; readonly exportFromImportedHandleTypes: VkExternalMemoryHandleTypeFlagBitsNV; readonly compatibleHandleTypes: VkExternalMemoryHandleTypeFlagBitsNV; } export interface VkExternalImageFormatPropertiesNV { readonly imageFormatProperties: VkImageFormatProperties | null; readonly externalMemoryFeatures: VkExternalMemoryFeatureFlagBitsNV; readonly exportFromImportedHandleTypes: VkExternalMemoryHandleTypeFlagBitsNV; readonly compatibleHandleTypes: VkExternalMemoryHandleTypeFlagBitsNV; } /** ## VkDedicatedAllocationMemoryAllocateInfoNV ## */ interface VkDedicatedAllocationMemoryAllocateInfoNVInitializer { sType?: VkStructureType; pNext?: null; image?: VkImage | null; buffer?: VkBuffer | null; } declare var VkDedicatedAllocationMemoryAllocateInfoNV: { prototype: VkDedicatedAllocationMemoryAllocateInfoNV; new(param?: VkDedicatedAllocationMemoryAllocateInfoNVInitializer | null): VkDedicatedAllocationMemoryAllocateInfoNV; sType: VkStructureType; pNext: null; image: VkImage | null; buffer: VkBuffer | null; } export interface VkDedicatedAllocationMemoryAllocateInfoNV { sType: VkStructureType; pNext: null; image: VkImage | null; buffer: VkBuffer | null; } /** ## VkDedicatedAllocationBufferCreateInfoNV ## */ interface VkDedicatedAllocationBufferCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; dedicatedAllocation?: number; } declare var VkDedicatedAllocationBufferCreateInfoNV: { prototype: VkDedicatedAllocationBufferCreateInfoNV; new(param?: VkDedicatedAllocationBufferCreateInfoNVInitializer | null): VkDedicatedAllocationBufferCreateInfoNV; sType: VkStructureType; pNext: null; dedicatedAllocation: number; } export interface VkDedicatedAllocationBufferCreateInfoNV { sType: VkStructureType; pNext: null; dedicatedAllocation: number; } /** ## VkDedicatedAllocationImageCreateInfoNV ## */ interface VkDedicatedAllocationImageCreateInfoNVInitializer { sType?: VkStructureType; pNext?: null; dedicatedAllocation?: number; } declare var VkDedicatedAllocationImageCreateInfoNV: { prototype: VkDedicatedAllocationImageCreateInfoNV; new(param?: VkDedicatedAllocationImageCreateInfoNVInitializer | null): VkDedicatedAllocationImageCreateInfoNV; sType: VkStructureType; pNext: null; dedicatedAllocation: number; } export interface VkDedicatedAllocationImageCreateInfoNV { sType: VkStructureType; pNext: null; dedicatedAllocation: number; } /** ## VkDebugMarkerMarkerInfoEXT ## */ interface VkDebugMarkerMarkerInfoEXTInitializer { sType?: VkStructureType; pNext?: null; pMarkerName?: string | null; color?: number[] | null; } declare var VkDebugMarkerMarkerInfoEXT: { prototype: VkDebugMarkerMarkerInfoEXT; new(param?: VkDebugMarkerMarkerInfoEXTInitializer | null): VkDebugMarkerMarkerInfoEXT; sType: VkStructureType; pNext: null; pMarkerName: string | null; color: number[] | null; } export interface VkDebugMarkerMarkerInfoEXT { sType: VkStructureType; pNext: null; pMarkerName: string | null; color: number[] | null; } /** ## VkDebugMarkerObjectTagInfoEXT ## */ interface VkDebugMarkerObjectTagInfoEXTInitializer { sType?: VkStructureType; pNext?: null; objectType?: VkDebugReportObjectTypeEXT; object?: number; tagName?: number; tagSize?: number; pTag?: ArrayBuffer | null; } declare var VkDebugMarkerObjectTagInfoEXT: { prototype: VkDebugMarkerObjectTagInfoEXT; new(param?: VkDebugMarkerObjectTagInfoEXTInitializer | null): VkDebugMarkerObjectTagInfoEXT; sType: VkStructureType; pNext: null; objectType: VkDebugReportObjectTypeEXT; object: number; tagName: number; tagSize: number; pTag: ArrayBuffer | null; } export interface VkDebugMarkerObjectTagInfoEXT { sType: VkStructureType; pNext: null; objectType: VkDebugReportObjectTypeEXT; object: number; tagName: number; tagSize: number; pTag: ArrayBuffer | null; } /** ## VkDebugMarkerObjectNameInfoEXT ## */ interface VkDebugMarkerObjectNameInfoEXTInitializer { sType?: VkStructureType; pNext?: null; objectType?: VkDebugReportObjectTypeEXT; object?: number; pObjectName?: string | null; } declare var VkDebugMarkerObjectNameInfoEXT: { prototype: VkDebugMarkerObjectNameInfoEXT; new(param?: VkDebugMarkerObjectNameInfoEXTInitializer | null): VkDebugMarkerObjectNameInfoEXT; sType: VkStructureType; pNext: null; objectType: VkDebugReportObjectTypeEXT; object: number; pObjectName: string | null; } export interface VkDebugMarkerObjectNameInfoEXT { sType: VkStructureType; pNext: null; objectType: VkDebugReportObjectTypeEXT; object: number; pObjectName: string | null; } /** ## VkPipelineRasterizationStateRasterizationOrderAMD ## */ interface VkPipelineRasterizationStateRasterizationOrderAMDInitializer { sType?: VkStructureType; pNext?: null; rasterizationOrder?: VkRasterizationOrderAMD; } declare var VkPipelineRasterizationStateRasterizationOrderAMD: { prototype: VkPipelineRasterizationStateRasterizationOrderAMD; new(param?: VkPipelineRasterizationStateRasterizationOrderAMDInitializer | null): VkPipelineRasterizationStateRasterizationOrderAMD; sType: VkStructureType; pNext: null; rasterizationOrder: VkRasterizationOrderAMD; } export interface VkPipelineRasterizationStateRasterizationOrderAMD { sType: VkStructureType; pNext: null; rasterizationOrder: VkRasterizationOrderAMD; } /** ## VkValidationFeaturesEXT ## */ interface VkValidationFeaturesEXTInitializer { sType?: VkStructureType; pNext?: null; enabledValidationFeatureCount?: number; pEnabledValidationFeatures?: Int32Array | null; disabledValidationFeatureCount?: number; pDisabledValidationFeatures?: Int32Array | null; } declare var VkValidationFeaturesEXT: { prototype: VkValidationFeaturesEXT; new(param?: VkValidationFeaturesEXTInitializer | null): VkValidationFeaturesEXT; sType: VkStructureType; pNext: null; enabledValidationFeatureCount: number; pEnabledValidationFeatures: Int32Array | null; disabledValidationFeatureCount: number; pDisabledValidationFeatures: Int32Array | null; } export interface VkValidationFeaturesEXT { sType: VkStructureType; pNext: null; enabledValidationFeatureCount: number; pEnabledValidationFeatures: Int32Array | null; disabledValidationFeatureCount: number; pDisabledValidationFeatures: Int32Array | null; } /** ## VkValidationFlagsEXT ## */ interface VkValidationFlagsEXTInitializer { sType?: VkStructureType; pNext?: null; disabledValidationCheckCount?: number; pDisabledValidationChecks?: Int32Array | null; } declare var VkValidationFlagsEXT: { prototype: VkValidationFlagsEXT; new(param?: VkValidationFlagsEXTInitializer | null): VkValidationFlagsEXT; sType: VkStructureType; pNext: null; disabledValidationCheckCount: number; pDisabledValidationChecks: Int32Array | null; } export interface VkValidationFlagsEXT { sType: VkStructureType; pNext: null; disabledValidationCheckCount: number; pDisabledValidationChecks: Int32Array | null; } /** ## VkDebugReportCallbackCreateInfoEXT ## */ interface VkDebugReportCallbackCreateInfoEXTInitializer { sType?: VkStructureType; pNext?: null; flags?: VkDebugReportFlagBitsEXT; pfnCallback?: null; pUserData?: ArrayBuffer | null; } declare var VkDebugReportCallbackCreateInfoEXT: { prototype: VkDebugReportCallbackCreateInfoEXT; new(param?: VkDebugReportCallbackCreateInfoEXTInitializer | null): VkDebugReportCallbackCreateInfoEXT; sType: VkStructureType; pNext: null; flags: VkDebugReportFlagBitsEXT; pfnCallback: null; pUserData: ArrayBuffer | null; } export interface VkDebugReportCallbackCreateInfoEXT { sType: VkStructureType; pNext: null; flags: VkDebugReportFlagBitsEXT; pfnCallback: null; pUserData: ArrayBuffer | null; } /** ## VkPresentInfoKHR ## */ interface VkPresentInfoKHRInitializer { sType?: VkStructureType; pNext?: null; waitSemaphoreCount?: number; pWaitSemaphores?: VkSemaphore[] | null; swapchainCount?: number; pSwapchains?: VkSwapchainKHR[] | null; pImageIndices?: Uint32Array | null; pResults?: Int32Array | null; } declare var VkPresentInfoKHR: { prototype: VkPresentInfoKHR; new(param?: VkPresentInfoKHRInitializer | null): VkPresentInfoKHR; sType: VkStructureType; pNext: null; waitSemaphoreCount: number; pWaitSemaphores: VkSemaphore[] | null; swapchainCount: number; pSwapchains: VkSwapchainKHR[] | null; pImageIndices: Uint32Array | null; pResults: Int32Array | null; } export interface VkPresentInfoKHR { sType: VkStructureType; pNext: null; waitSemaphoreCount: number; pWaitSemaphores: VkSemaphore[] | null; swapchainCount: number; pSwapchains: VkSwapchainKHR[] | null; pImageIndices: Uint32Array | null; pResults: Int32Array | null; } /** ## VkSwapchainCreateInfoKHR ## */ interface VkSwapchainCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; flags?: VkSwapchainCreateFlagBitsKHR; surface?: VkSurfaceKHR | null; minImageCount?: number; imageFormat?: VkFormat; imageColorSpace?: VkColorSpaceKHR; imageExtent?: VkExtent2D | null; imageArrayLayers?: number; imageUsage?: VkImageUsageFlagBits; imageSharingMode?: VkSharingMode; queueFamilyIndexCount?: number; pQueueFamilyIndices?: Uint32Array | null; preTransform?: VkSurfaceTransformFlagBitsKHR; compositeAlpha?: VkCompositeAlphaFlagBitsKHR; presentMode?: VkPresentModeKHR; clipped?: number; oldSwapchain?: VkSwapchainKHR | null; } declare var VkSwapchainCreateInfoKHR: { prototype: VkSwapchainCreateInfoKHR; new(param?: VkSwapchainCreateInfoKHRInitializer | null): VkSwapchainCreateInfoKHR; sType: VkStructureType; pNext: null; flags: VkSwapchainCreateFlagBitsKHR; surface: VkSurfaceKHR | null; minImageCount: number; imageFormat: VkFormat; imageColorSpace: VkColorSpaceKHR; imageExtent: VkExtent2D | null; imageArrayLayers: number; imageUsage: VkImageUsageFlagBits; imageSharingMode: VkSharingMode; queueFamilyIndexCount: number; pQueueFamilyIndices: Uint32Array | null; preTransform: VkSurfaceTransformFlagBitsKHR; compositeAlpha: VkCompositeAlphaFlagBitsKHR; presentMode: VkPresentModeKHR; clipped: number; oldSwapchain: VkSwapchainKHR | null; } export interface VkSwapchainCreateInfoKHR { sType: VkStructureType; pNext: null; flags: VkSwapchainCreateFlagBitsKHR; surface: VkSurfaceKHR | null; minImageCount: number; imageFormat: VkFormat; imageColorSpace: VkColorSpaceKHR; imageExtent: VkExtent2D | null; imageArrayLayers: number; imageUsage: VkImageUsageFlagBits; imageSharingMode: VkSharingMode; queueFamilyIndexCount: number; pQueueFamilyIndices: Uint32Array | null; preTransform: VkSurfaceTransformFlagBitsKHR; compositeAlpha: VkCompositeAlphaFlagBitsKHR; presentMode: VkPresentModeKHR; clipped: number; oldSwapchain: VkSwapchainKHR | null; } /** ## VkSurfaceFormatKHR ## */ interface VkSurfaceFormatKHRInitializer { readonly format?: VkFormat; readonly colorSpace?: VkColorSpaceKHR; } declare var VkSurfaceFormatKHR: { prototype: VkSurfaceFormatKHR; new(param?: VkSurfaceFormatKHRInitializer | null): VkSurfaceFormatKHR; readonly format: VkFormat; readonly colorSpace: VkColorSpaceKHR; } export interface VkSurfaceFormatKHR { readonly format: VkFormat; readonly colorSpace: VkColorSpaceKHR; } /** ## VkSurfaceCapabilitiesKHR ## */ interface VkSurfaceCapabilitiesKHRInitializer { readonly minImageCount?: number; readonly maxImageCount?: number; readonly currentExtent?: VkExtent2D | null; readonly minImageExtent?: VkExtent2D | null; readonly maxImageExtent?: VkExtent2D | null; readonly maxImageArrayLayers?: number; readonly supportedTransforms?: VkSurfaceTransformFlagBitsKHR; readonly currentTransform?: VkSurfaceTransformFlagBitsKHR; readonly supportedCompositeAlpha?: VkCompositeAlphaFlagBitsKHR; readonly supportedUsageFlags?: VkImageUsageFlagBits; } declare var VkSurfaceCapabilitiesKHR: { prototype: VkSurfaceCapabilitiesKHR; new(param?: VkSurfaceCapabilitiesKHRInitializer | null): VkSurfaceCapabilitiesKHR; readonly minImageCount: number; readonly maxImageCount: number; readonly currentExtent: VkExtent2D | null; readonly minImageExtent: VkExtent2D | null; readonly maxImageExtent: VkExtent2D | null; readonly maxImageArrayLayers: number; readonly supportedTransforms: VkSurfaceTransformFlagBitsKHR; readonly currentTransform: VkSurfaceTransformFlagBitsKHR; readonly supportedCompositeAlpha: VkCompositeAlphaFlagBitsKHR; readonly supportedUsageFlags: VkImageUsageFlagBits; } export interface VkSurfaceCapabilitiesKHR { readonly minImageCount: number; readonly maxImageCount: number; readonly currentExtent: VkExtent2D | null; readonly minImageExtent: VkExtent2D | null; readonly maxImageExtent: VkExtent2D | null; readonly maxImageArrayLayers: number; readonly supportedTransforms: VkSurfaceTransformFlagBitsKHR; readonly currentTransform: VkSurfaceTransformFlagBitsKHR; readonly supportedCompositeAlpha: VkCompositeAlphaFlagBitsKHR; readonly supportedUsageFlags: VkImageUsageFlagBits; } /** ## VkDisplayPresentInfoKHR ## */ interface VkDisplayPresentInfoKHRInitializer { sType?: VkStructureType; pNext?: null; srcRect?: VkRect2D | null; dstRect?: VkRect2D | null; persistent?: number; } declare var VkDisplayPresentInfoKHR: { prototype: VkDisplayPresentInfoKHR; new(param?: VkDisplayPresentInfoKHRInitializer | null): VkDisplayPresentInfoKHR; sType: VkStructureType; pNext: null; srcRect: VkRect2D | null; dstRect: VkRect2D | null; persistent: number; } export interface VkDisplayPresentInfoKHR { sType: VkStructureType; pNext: null; srcRect: VkRect2D | null; dstRect: VkRect2D | null; persistent: number; } /** ## VkDisplaySurfaceCreateInfoKHR ## */ interface VkDisplaySurfaceCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; flags?: null; displayMode?: VkDisplayModeKHR | null; planeIndex?: number; planeStackIndex?: number; transform?: VkSurfaceTransformFlagBitsKHR; globalAlpha?: number; alphaMode?: VkDisplayPlaneAlphaFlagBitsKHR; imageExtent?: VkExtent2D | null; } declare var VkDisplaySurfaceCreateInfoKHR: { prototype: VkDisplaySurfaceCreateInfoKHR; new(param?: VkDisplaySurfaceCreateInfoKHRInitializer | null): VkDisplaySurfaceCreateInfoKHR; sType: VkStructureType; pNext: null; flags: null; displayMode: VkDisplayModeKHR | null; planeIndex: number; planeStackIndex: number; transform: VkSurfaceTransformFlagBitsKHR; globalAlpha: number; alphaMode: VkDisplayPlaneAlphaFlagBitsKHR; imageExtent: VkExtent2D | null; } export interface VkDisplaySurfaceCreateInfoKHR { sType: VkStructureType; pNext: null; flags: null; displayMode: VkDisplayModeKHR | null; planeIndex: number; planeStackIndex: number; transform: VkSurfaceTransformFlagBitsKHR; globalAlpha: number; alphaMode: VkDisplayPlaneAlphaFlagBitsKHR; imageExtent: VkExtent2D | null; } /** ## VkDisplayPlaneCapabilitiesKHR ## */ interface VkDisplayPlaneCapabilitiesKHRInitializer { readonly supportedAlpha?: VkDisplayPlaneAlphaFlagBitsKHR; readonly minSrcPosition?: VkOffset2D | null; readonly maxSrcPosition?: VkOffset2D | null; readonly minSrcExtent?: VkExtent2D | null; readonly maxSrcExtent?: VkExtent2D | null; readonly minDstPosition?: VkOffset2D | null; readonly maxDstPosition?: VkOffset2D | null; readonly minDstExtent?: VkExtent2D | null; readonly maxDstExtent?: VkExtent2D | null; } declare var VkDisplayPlaneCapabilitiesKHR: { prototype: VkDisplayPlaneCapabilitiesKHR; new(param?: VkDisplayPlaneCapabilitiesKHRInitializer | null): VkDisplayPlaneCapabilitiesKHR; readonly supportedAlpha: VkDisplayPlaneAlphaFlagBitsKHR; readonly minSrcPosition: VkOffset2D | null; readonly maxSrcPosition: VkOffset2D | null; readonly minSrcExtent: VkExtent2D | null; readonly maxSrcExtent: VkExtent2D | null; readonly minDstPosition: VkOffset2D | null; readonly maxDstPosition: VkOffset2D | null; readonly minDstExtent: VkExtent2D | null; readonly maxDstExtent: VkExtent2D | null; } export interface VkDisplayPlaneCapabilitiesKHR { readonly supportedAlpha: VkDisplayPlaneAlphaFlagBitsKHR; readonly minSrcPosition: VkOffset2D | null; readonly maxSrcPosition: VkOffset2D | null; readonly minSrcExtent: VkExtent2D | null; readonly maxSrcExtent: VkExtent2D | null; readonly minDstPosition: VkOffset2D | null; readonly maxDstPosition: VkOffset2D | null; readonly minDstExtent: VkExtent2D | null; readonly maxDstExtent: VkExtent2D | null; } /** ## VkDisplayModeCreateInfoKHR ## */ interface VkDisplayModeCreateInfoKHRInitializer { sType?: VkStructureType; pNext?: null; flags?: null; parameters?: VkDisplayModeParametersKHR | null; } declare var VkDisplayModeCreateInfoKHR: { prototype: VkDisplayModeCreateInfoKHR; new(param?: VkDisplayModeCreateInfoKHRInitializer | null): VkDisplayModeCreateInfoKHR; sType: VkStructureType; pNext: null; flags: null; parameters: VkDisplayModeParametersKHR | null; } export interface VkDisplayModeCreateInfoKHR { sType: VkStructureType; pNext: null; flags: null; parameters: VkDisplayModeParametersKHR | null; } /** ## VkDisplayModePropertiesKHR ## */ interface VkDisplayModePropertiesKHRInitializer { readonly displayMode?: VkDisplayModeKHR | null; readonly parameters?: VkDisplayModeParametersKHR | null; } declare var VkDisplayModePropertiesKHR: { prototype: VkDisplayModePropertiesKHR; new(param?: VkDisplayModePropertiesKHRInitializer | null): VkDisplayModePropertiesKHR; readonly displayMode: VkDisplayModeKHR | null; readonly parameters: VkDisplayModeParametersKHR | null; } export interface VkDisplayModePropertiesKHR { readonly displayMode: VkDisplayModeKHR | null; readonly parameters: VkDisplayModeParametersKHR | null; } /** ## VkDisplayModeParametersKHR ## */ interface VkDisplayModeParametersKHRInitializer { visibleRegion?: VkExtent2D | null; refreshRate?: number; } declare var VkDisplayModeParametersKHR: { prototype: VkDisplayModeParametersKHR; new(param?: VkDisplayModeParametersKHRInitializer | null): VkDisplayModeParametersKHR; visibleRegion: VkExtent2D | null; refreshRate: number; } export interface VkDisplayModeParametersKHR { visibleRegion: VkExtent2D | null; refreshRate: number; } /** ## VkDisplayPlanePropertiesKHR ## */ interface VkDisplayPlanePropertiesKHRInitializer { readonly currentDisplay?: VkDisplayKHR | null; readonly currentStackIndex?: number; } declare var VkDisplayPlanePropertiesKHR: { prototype: VkDisplayPlanePropertiesKHR; new(param?: VkDisplayPlanePropertiesKHRInitializer | null): VkDisplayPlanePropertiesKHR; readonly currentDisplay: VkDisplayKHR | null; readonly currentStackIndex: number; } export interface VkDisplayPlanePropertiesKHR { readonly currentDisplay: VkDisplayKHR | null; readonly currentStackIndex: number; } /** ## VkDisplayPropertiesKHR ## */ interface VkDisplayPropertiesKHRInitializer { readonly display?: VkDisplayKHR | null; readonly displayName?: string | null; readonly physicalDimensions?: VkExtent2D | null; readonly physicalResolution?: VkExtent2D | null; readonly supportedTransforms?: VkSurfaceTransformFlagBitsKHR; readonly planeReorderPossible?: number; readonly persistentContent?: number; } declare var VkDisplayPropertiesKHR: { prototype: VkDisplayPropertiesKHR; new(param?: VkDisplayPropertiesKHRInitializer | null): VkDisplayPropertiesKHR; readonly display: VkDisplayKHR | null; readonly displayName: string | null; readonly physicalDimensions: VkExtent2D | null; readonly physicalResolution: VkExtent2D | null; readonly supportedTransforms: VkSurfaceTransformFlagBitsKHR; readonly planeReorderPossible: number; readonly persistentContent: number; } export interface VkDisplayPropertiesKHR { readonly display: VkDisplayKHR | null; readonly displayName: string | null; readonly physicalDimensions: VkExtent2D | null; readonly physicalResolution: VkExtent2D | null; readonly supportedTransforms: VkSurfaceTransformFlagBitsKHR; readonly planeReorderPossible: number; readonly persistentContent: number; } /** ## VkSubmitInfo ## */ interface VkSubmitInfoInitializer { sType?: VkStructureType; pNext?: null; waitSemaphoreCount?: number; pWaitSemaphores?: VkSemaphore[] | null; pWaitDstStageMask?: Int32Array | null; commandBufferCount?: number; pCommandBuffers?: VkCommandBuffer[] | null; signalSemaphoreCount?: number; pSignalSemaphores?: VkSemaphore[] | null; } declare var VkSubmitInfo: { prototype: VkSubmitInfo; new(param?: VkSubmitInfoInitializer | null): VkSubmitInfo; sType: VkStructureType; pNext: null; waitSemaphoreCount: number; pWaitSemaphores: VkSemaphore[] | null; pWaitDstStageMask: Int32Array | null; commandBufferCount: number; pCommandBuffers: VkCommandBuffer[] | null; signalSemaphoreCount: number; pSignalSemaphores: VkSemaphore[] | null; } export interface VkSubmitInfo { sType: VkStructureType; pNext: null; waitSemaphoreCount: number; pWaitSemaphores: VkSemaphore[] | null; pWaitDstStageMask: Int32Array | null; commandBufferCount: number; pCommandBuffers: VkCommandBuffer[] | null; signalSemaphoreCount: number; pSignalSemaphores: VkSemaphore[] | null; } /** ## VkDispatchIndirectCommand ## */ interface VkDispatchIndirectCommandInitializer { x?: number; y?: number; z?: number; } declare var VkDispatchIndirectCommand: { prototype: VkDispatchIndirectCommand; new(param?: VkDispatchIndirectCommandInitializer | null): VkDispatchIndirectCommand; x: number; y: number; z: number; } export interface VkDispatchIndirectCommand { x: number; y: number; z: number; } /** ## VkDrawIndexedIndirectCommand ## */ interface VkDrawIndexedIndirectCommandInitializer { indexCount?: number; instanceCount?: number; firstIndex?: number; vertexOffset?: number; firstInstance?: number; } declare var VkDrawIndexedIndirectCommand: { prototype: VkDrawIndexedIndirectCommand; new(param?: VkDrawIndexedIndirectCommandInitializer | null): VkDrawIndexedIndirectCommand; indexCount: number; instanceCount: number; firstIndex: number; vertexOffset: number; firstInstance: number; } export interface VkDrawIndexedIndirectCommand { indexCount: number; instanceCount: number; firstIndex: number; vertexOffset: number; firstInstance: number; } /** ## VkDrawIndirectCommand ## */ interface VkDrawIndirectCommandInitializer { vertexCount?: number; instanceCount?: number; firstVertex?: number; firstInstance?: number; } declare var VkDrawIndirectCommand: { prototype: VkDrawIndirectCommand; new(param?: VkDrawIndirectCommandInitializer | null): VkDrawIndirectCommand; vertexCount: number; instanceCount: number; firstVertex: number; firstInstance: number; } export interface VkDrawIndirectCommand { vertexCount: number; instanceCount: number; firstVertex: number; firstInstance: number; } /** ## VkFramebufferCreateInfo ## */ interface VkFramebufferCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; renderPass?: VkRenderPass | null; attachmentCount?: number; pAttachments?: VkImageView[] | null; width?: number; height?: number; layers?: number; } declare var VkFramebufferCreateInfo: { prototype: VkFramebufferCreateInfo; new(param?: VkFramebufferCreateInfoInitializer | null): VkFramebufferCreateInfo; sType: VkStructureType; pNext: null; flags: null; renderPass: VkRenderPass | null; attachmentCount: number; pAttachments: VkImageView[] | null; width: number; height: number; layers: number; } export interface VkFramebufferCreateInfo { sType: VkStructureType; pNext: null; flags: null; renderPass: VkRenderPass | null; attachmentCount: number; pAttachments: VkImageView[] | null; width: number; height: number; layers: number; } /** ## VkQueryPoolCreateInfo ## */ interface VkQueryPoolCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; queryType?: VkQueryType; queryCount?: number; pipelineStatistics?: VkQueryPipelineStatisticFlagBits; } declare var VkQueryPoolCreateInfo: { prototype: VkQueryPoolCreateInfo; new(param?: VkQueryPoolCreateInfoInitializer | null): VkQueryPoolCreateInfo; sType: VkStructureType; pNext: null; flags: null; queryType: VkQueryType; queryCount: number; pipelineStatistics: VkQueryPipelineStatisticFlagBits; } export interface VkQueryPoolCreateInfo { sType: VkStructureType; pNext: null; flags: null; queryType: VkQueryType; queryCount: number; pipelineStatistics: VkQueryPipelineStatisticFlagBits; } /** ## VkSemaphoreCreateInfo ## */ interface VkSemaphoreCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; } declare var VkSemaphoreCreateInfo: { prototype: VkSemaphoreCreateInfo; new(param?: VkSemaphoreCreateInfoInitializer | null): VkSemaphoreCreateInfo; sType: VkStructureType; pNext: null; flags: null; } export interface VkSemaphoreCreateInfo { sType: VkStructureType; pNext: null; flags: null; } /** ## VkPhysicalDeviceLimits ## */ interface VkPhysicalDeviceLimitsInitializer { readonly maxImageDimension1D?: number; readonly maxImageDimension2D?: number; readonly maxImageDimension3D?: number; readonly maxImageDimensionCube?: number; readonly maxImageArrayLayers?: number; readonly maxTexelBufferElements?: number; readonly maxUniformBufferRange?: number; readonly maxStorageBufferRange?: number; readonly maxPushConstantsSize?: number; readonly maxMemoryAllocationCount?: number; readonly maxSamplerAllocationCount?: number; readonly bufferImageGranularity?: number; readonly sparseAddressSpaceSize?: number; readonly maxBoundDescriptorSets?: number; readonly maxPerStageDescriptorSamplers?: number; readonly maxPerStageDescriptorUniformBuffers?: number; readonly maxPerStageDescriptorStorageBuffers?: number; readonly maxPerStageDescriptorSampledImages?: number; readonly maxPerStageDescriptorStorageImages?: number; readonly maxPerStageDescriptorInputAttachments?: number; readonly maxPerStageResources?: number; readonly maxDescriptorSetSamplers?: number; readonly maxDescriptorSetUniformBuffers?: number; readonly maxDescriptorSetUniformBuffersDynamic?: number; readonly maxDescriptorSetStorageBuffers?: number; readonly maxDescriptorSetStorageBuffersDynamic?: number; readonly maxDescriptorSetSampledImages?: number; readonly maxDescriptorSetStorageImages?: number; readonly maxDescriptorSetInputAttachments?: number; readonly maxVertexInputAttributes?: number; readonly maxVertexInputBindings?: number; readonly maxVertexInputAttributeOffset?: number; readonly maxVertexInputBindingStride?: number; readonly maxVertexOutputComponents?: number; readonly maxTessellationGenerationLevel?: number; readonly maxTessellationPatchSize?: number; readonly maxTessellationControlPerVertexInputComponents?: number; readonly maxTessellationControlPerVertexOutputComponents?: number; readonly maxTessellationControlPerPatchOutputComponents?: number; readonly maxTessellationControlTotalOutputComponents?: number; readonly maxTessellationEvaluationInputComponents?: number; readonly maxTessellationEvaluationOutputComponents?: number; readonly maxGeometryShaderInvocations?: number; readonly maxGeometryInputComponents?: number; readonly maxGeometryOutputComponents?: number; readonly maxGeometryOutputVertices?: number; readonly maxGeometryTotalOutputComponents?: number; readonly maxFragmentInputComponents?: number; readonly maxFragmentOutputAttachments?: number; readonly maxFragmentDualSrcAttachments?: number; readonly maxFragmentCombinedOutputResources?: number; readonly maxComputeSharedMemorySize?: number; readonly maxComputeWorkGroupCount?: number[] | null; readonly maxComputeWorkGroupInvocations?: number; readonly maxComputeWorkGroupSize?: number[] | null; readonly subPixelPrecisionBits?: number; readonly subTexelPrecisionBits?: number; readonly mipmapPrecisionBits?: number; readonly maxDrawIndexedIndexValue?: number; readonly maxDrawIndirectCount?: number; readonly maxSamplerLodBias?: number; readonly maxSamplerAnisotropy?: number; readonly maxViewports?: number; readonly maxViewportDimensions?: number[] | null; readonly viewportBoundsRange?: number[] | null; readonly viewportSubPixelBits?: number; readonly minMemoryMapAlignment?: number; readonly minTexelBufferOffsetAlignment?: number; readonly minUniformBufferOffsetAlignment?: number; readonly minStorageBufferOffsetAlignment?: number; readonly minTexelOffset?: number; readonly maxTexelOffset?: number; readonly minTexelGatherOffset?: number; readonly maxTexelGatherOffset?: number; readonly minInterpolationOffset?: number; readonly maxInterpolationOffset?: number; readonly subPixelInterpolationOffsetBits?: number; readonly maxFramebufferWidth?: number; readonly maxFramebufferHeight?: number; readonly maxFramebufferLayers?: number; readonly framebufferColorSampleCounts?: VkSampleCountFlagBits; readonly framebufferDepthSampleCounts?: VkSampleCountFlagBits; readonly framebufferStencilSampleCounts?: VkSampleCountFlagBits; readonly framebufferNoAttachmentsSampleCounts?: VkSampleCountFlagBits; readonly maxColorAttachments?: number; readonly sampledImageColorSampleCounts?: VkSampleCountFlagBits; readonly sampledImageIntegerSampleCounts?: VkSampleCountFlagBits; readonly sampledImageDepthSampleCounts?: VkSampleCountFlagBits; readonly sampledImageStencilSampleCounts?: VkSampleCountFlagBits; readonly storageImageSampleCounts?: VkSampleCountFlagBits; readonly maxSampleMaskWords?: number; readonly timestampComputeAndGraphics?: number; readonly timestampPeriod?: number; readonly maxClipDistances?: number; readonly maxCullDistances?: number; readonly maxCombinedClipAndCullDistances?: number; readonly discreteQueuePriorities?: number; readonly pointSizeRange?: number[] | null; readonly lineWidthRange?: number[] | null; readonly pointSizeGranularity?: number; readonly lineWidthGranularity?: number; readonly strictLines?: number; readonly standardSampleLocations?: number; readonly optimalBufferCopyOffsetAlignment?: number; readonly optimalBufferCopyRowPitchAlignment?: number; readonly nonCoherentAtomSize?: number; } declare var VkPhysicalDeviceLimits: { prototype: VkPhysicalDeviceLimits; new(param?: VkPhysicalDeviceLimitsInitializer | null): VkPhysicalDeviceLimits; readonly maxImageDimension1D: number; readonly maxImageDimension2D: number; readonly maxImageDimension3D: number; readonly maxImageDimensionCube: number; readonly maxImageArrayLayers: number; readonly maxTexelBufferElements: number; readonly maxUniformBufferRange: number; readonly maxStorageBufferRange: number; readonly maxPushConstantsSize: number; readonly maxMemoryAllocationCount: number; readonly maxSamplerAllocationCount: number; readonly bufferImageGranularity: number; readonly sparseAddressSpaceSize: number; readonly maxBoundDescriptorSets: number; readonly maxPerStageDescriptorSamplers: number; readonly maxPerStageDescriptorUniformBuffers: number; readonly maxPerStageDescriptorStorageBuffers: number; readonly maxPerStageDescriptorSampledImages: number; readonly maxPerStageDescriptorStorageImages: number; readonly maxPerStageDescriptorInputAttachments: number; readonly maxPerStageResources: number; readonly maxDescriptorSetSamplers: number; readonly maxDescriptorSetUniformBuffers: number; readonly maxDescriptorSetUniformBuffersDynamic: number; readonly maxDescriptorSetStorageBuffers: number; readonly maxDescriptorSetStorageBuffersDynamic: number; readonly maxDescriptorSetSampledImages: number; readonly maxDescriptorSetStorageImages: number; readonly maxDescriptorSetInputAttachments: number; readonly maxVertexInputAttributes: number; readonly maxVertexInputBindings: number; readonly maxVertexInputAttributeOffset: number; readonly maxVertexInputBindingStride: number; readonly maxVertexOutputComponents: number; readonly maxTessellationGenerationLevel: number; readonly maxTessellationPatchSize: number; readonly maxTessellationControlPerVertexInputComponents: number; readonly maxTessellationControlPerVertexOutputComponents: number; readonly maxTessellationControlPerPatchOutputComponents: number; readonly maxTessellationControlTotalOutputComponents: number; readonly maxTessellationEvaluationInputComponents: number; readonly maxTessellationEvaluationOutputComponents: number; readonly maxGeometryShaderInvocations: number; readonly maxGeometryInputComponents: number; readonly maxGeometryOutputComponents: number; readonly maxGeometryOutputVertices: number; readonly maxGeometryTotalOutputComponents: number; readonly maxFragmentInputComponents: number; readonly maxFragmentOutputAttachments: number; readonly maxFragmentDualSrcAttachments: number; readonly maxFragmentCombinedOutputResources: number; readonly maxComputeSharedMemorySize: number; readonly maxComputeWorkGroupCount: number[] | null; readonly maxComputeWorkGroupInvocations: number; readonly maxComputeWorkGroupSize: number[] | null; readonly subPixelPrecisionBits: number; readonly subTexelPrecisionBits: number; readonly mipmapPrecisionBits: number; readonly maxDrawIndexedIndexValue: number; readonly maxDrawIndirectCount: number; readonly maxSamplerLodBias: number; readonly maxSamplerAnisotropy: number; readonly maxViewports: number; readonly maxViewportDimensions: number[] | null; readonly viewportBoundsRange: number[] | null; readonly viewportSubPixelBits: number; readonly minMemoryMapAlignment: number; readonly minTexelBufferOffsetAlignment: number; readonly minUniformBufferOffsetAlignment: number; readonly minStorageBufferOffsetAlignment: number; readonly minTexelOffset: number; readonly maxTexelOffset: number; readonly minTexelGatherOffset: number; readonly maxTexelGatherOffset: number; readonly minInterpolationOffset: number; readonly maxInterpolationOffset: number; readonly subPixelInterpolationOffsetBits: number; readonly maxFramebufferWidth: number; readonly maxFramebufferHeight: number; readonly maxFramebufferLayers: number; readonly framebufferColorSampleCounts: VkSampleCountFlagBits; readonly framebufferDepthSampleCounts: VkSampleCountFlagBits; readonly framebufferStencilSampleCounts: VkSampleCountFlagBits; readonly framebufferNoAttachmentsSampleCounts: VkSampleCountFlagBits; readonly maxColorAttachments: number; readonly sampledImageColorSampleCounts: VkSampleCountFlagBits; readonly sampledImageIntegerSampleCounts: VkSampleCountFlagBits; readonly sampledImageDepthSampleCounts: VkSampleCountFlagBits; readonly sampledImageStencilSampleCounts: VkSampleCountFlagBits; readonly storageImageSampleCounts: VkSampleCountFlagBits; readonly maxSampleMaskWords: number; readonly timestampComputeAndGraphics: number; readonly timestampPeriod: number; readonly maxClipDistances: number; readonly maxCullDistances: number; readonly maxCombinedClipAndCullDistances: number; readonly discreteQueuePriorities: number; readonly pointSizeRange: number[] | null; readonly lineWidthRange: number[] | null; readonly pointSizeGranularity: number; readonly lineWidthGranularity: number; readonly strictLines: number; readonly standardSampleLocations: number; readonly optimalBufferCopyOffsetAlignment: number; readonly optimalBufferCopyRowPitchAlignment: number; readonly nonCoherentAtomSize: number; } export interface VkPhysicalDeviceLimits { readonly maxImageDimension1D: number; readonly maxImageDimension2D: number; readonly maxImageDimension3D: number; readonly maxImageDimensionCube: number; readonly maxImageArrayLayers: number; readonly maxTexelBufferElements: number; readonly maxUniformBufferRange: number; readonly maxStorageBufferRange: number; readonly maxPushConstantsSize: number; readonly maxMemoryAllocationCount: number; readonly maxSamplerAllocationCount: number; readonly bufferImageGranularity: number; readonly sparseAddressSpaceSize: number; readonly maxBoundDescriptorSets: number; readonly maxPerStageDescriptorSamplers: number; readonly maxPerStageDescriptorUniformBuffers: number; readonly maxPerStageDescriptorStorageBuffers: number; readonly maxPerStageDescriptorSampledImages: number; readonly maxPerStageDescriptorStorageImages: number; readonly maxPerStageDescriptorInputAttachments: number; readonly maxPerStageResources: number; readonly maxDescriptorSetSamplers: number; readonly maxDescriptorSetUniformBuffers: number; readonly maxDescriptorSetUniformBuffersDynamic: number; readonly maxDescriptorSetStorageBuffers: number; readonly maxDescriptorSetStorageBuffersDynamic: number; readonly maxDescriptorSetSampledImages: number; readonly maxDescriptorSetStorageImages: number; readonly maxDescriptorSetInputAttachments: number; readonly maxVertexInputAttributes: number; readonly maxVertexInputBindings: number; readonly maxVertexInputAttributeOffset: number; readonly maxVertexInputBindingStride: number; readonly maxVertexOutputComponents: number; readonly maxTessellationGenerationLevel: number; readonly maxTessellationPatchSize: number; readonly maxTessellationControlPerVertexInputComponents: number; readonly maxTessellationControlPerVertexOutputComponents: number; readonly maxTessellationControlPerPatchOutputComponents: number; readonly maxTessellationControlTotalOutputComponents: number; readonly maxTessellationEvaluationInputComponents: number; readonly maxTessellationEvaluationOutputComponents: number; readonly maxGeometryShaderInvocations: number; readonly maxGeometryInputComponents: number; readonly maxGeometryOutputComponents: number; readonly maxGeometryOutputVertices: number; readonly maxGeometryTotalOutputComponents: number; readonly maxFragmentInputComponents: number; readonly maxFragmentOutputAttachments: number; readonly maxFragmentDualSrcAttachments: number; readonly maxFragmentCombinedOutputResources: number; readonly maxComputeSharedMemorySize: number; readonly maxComputeWorkGroupCount: number[] | null; readonly maxComputeWorkGroupInvocations: number; readonly maxComputeWorkGroupSize: number[] | null; readonly subPixelPrecisionBits: number; readonly subTexelPrecisionBits: number; readonly mipmapPrecisionBits: number; readonly maxDrawIndexedIndexValue: number; readonly maxDrawIndirectCount: number; readonly maxSamplerLodBias: number; readonly maxSamplerAnisotropy: number; readonly maxViewports: number; readonly maxViewportDimensions: number[] | null; readonly viewportBoundsRange: number[] | null; readonly viewportSubPixelBits: number; readonly minMemoryMapAlignment: number; readonly minTexelBufferOffsetAlignment: number; readonly minUniformBufferOffsetAlignment: number; readonly minStorageBufferOffsetAlignment: number; readonly minTexelOffset: number; readonly maxTexelOffset: number; readonly minTexelGatherOffset: number; readonly maxTexelGatherOffset: number; readonly minInterpolationOffset: number; readonly maxInterpolationOffset: number; readonly subPixelInterpolationOffsetBits: number; readonly maxFramebufferWidth: number; readonly maxFramebufferHeight: number; readonly maxFramebufferLayers: number; readonly framebufferColorSampleCounts: VkSampleCountFlagBits; readonly framebufferDepthSampleCounts: VkSampleCountFlagBits; readonly framebufferStencilSampleCounts: VkSampleCountFlagBits; readonly framebufferNoAttachmentsSampleCounts: VkSampleCountFlagBits; readonly maxColorAttachments: number; readonly sampledImageColorSampleCounts: VkSampleCountFlagBits; readonly sampledImageIntegerSampleCounts: VkSampleCountFlagBits; readonly sampledImageDepthSampleCounts: VkSampleCountFlagBits; readonly sampledImageStencilSampleCounts: VkSampleCountFlagBits; readonly storageImageSampleCounts: VkSampleCountFlagBits; readonly maxSampleMaskWords: number; readonly timestampComputeAndGraphics: number; readonly timestampPeriod: number; readonly maxClipDistances: number; readonly maxCullDistances: number; readonly maxCombinedClipAndCullDistances: number; readonly discreteQueuePriorities: number; readonly pointSizeRange: number[] | null; readonly lineWidthRange: number[] | null; readonly pointSizeGranularity: number; readonly lineWidthGranularity: number; readonly strictLines: number; readonly standardSampleLocations: number; readonly optimalBufferCopyOffsetAlignment: number; readonly optimalBufferCopyRowPitchAlignment: number; readonly nonCoherentAtomSize: number; } /** ## VkPhysicalDeviceSparseProperties ## */ interface VkPhysicalDeviceSparsePropertiesInitializer { readonly residencyStandard2DBlockShape?: number; readonly residencyStandard2DMultisampleBlockShape?: number; readonly residencyStandard3DBlockShape?: number; readonly residencyAlignedMipSize?: number; readonly residencyNonResidentStrict?: number; } declare var VkPhysicalDeviceSparseProperties: { prototype: VkPhysicalDeviceSparseProperties; new(param?: VkPhysicalDeviceSparsePropertiesInitializer | null): VkPhysicalDeviceSparseProperties; readonly residencyStandard2DBlockShape: number; readonly residencyStandard2DMultisampleBlockShape: number; readonly residencyStandard3DBlockShape: number; readonly residencyAlignedMipSize: number; readonly residencyNonResidentStrict: number; } export interface VkPhysicalDeviceSparseProperties { readonly residencyStandard2DBlockShape: number; readonly residencyStandard2DMultisampleBlockShape: number; readonly residencyStandard3DBlockShape: number; readonly residencyAlignedMipSize: number; readonly residencyNonResidentStrict: number; } /** ## VkPhysicalDeviceFeatures ## */ interface VkPhysicalDeviceFeaturesInitializer { robustBufferAccess?: number; fullDrawIndexUint32?: number; imageCubeArray?: number; independentBlend?: number; geometryShader?: number; tessellationShader?: number; sampleRateShading?: number; dualSrcBlend?: number; logicOp?: number; multiDrawIndirect?: number; drawIndirectFirstInstance?: number; depthClamp?: number; depthBiasClamp?: number; fillModeNonSolid?: number; depthBounds?: number; wideLines?: number; largePoints?: number; alphaToOne?: number; multiViewport?: number; samplerAnisotropy?: number; textureCompressionETC2?: number; textureCompressionASTC_LDR?: number; textureCompressionBC?: number; occlusionQueryPrecise?: number; pipelineStatisticsQuery?: number; vertexPipelineStoresAndAtomics?: number; fragmentStoresAndAtomics?: number; shaderTessellationAndGeometryPointSize?: number; shaderImageGatherExtended?: number; shaderStorageImageExtendedFormats?: number; shaderStorageImageMultisample?: number; shaderStorageImageReadWithoutFormat?: number; shaderStorageImageWriteWithoutFormat?: number; shaderUniformBufferArrayDynamicIndexing?: number; shaderSampledImageArrayDynamicIndexing?: number; shaderStorageBufferArrayDynamicIndexing?: number; shaderStorageImageArrayDynamicIndexing?: number; shaderClipDistance?: number; shaderCullDistance?: number; shaderFloat64?: number; shaderInt64?: number; shaderInt16?: number; shaderResourceResidency?: number; shaderResourceMinLod?: number; sparseBinding?: number; sparseResidencyBuffer?: number; sparseResidencyImage2D?: number; sparseResidencyImage3D?: number; sparseResidency2Samples?: number; sparseResidency4Samples?: number; sparseResidency8Samples?: number; sparseResidency16Samples?: number; sparseResidencyAliased?: number; variableMultisampleRate?: number; inheritedQueries?: number; } declare var VkPhysicalDeviceFeatures: { prototype: VkPhysicalDeviceFeatures; new(param?: VkPhysicalDeviceFeaturesInitializer | null): VkPhysicalDeviceFeatures; robustBufferAccess: number; fullDrawIndexUint32: number; imageCubeArray: number; independentBlend: number; geometryShader: number; tessellationShader: number; sampleRateShading: number; dualSrcBlend: number; logicOp: number; multiDrawIndirect: number; drawIndirectFirstInstance: number; depthClamp: number; depthBiasClamp: number; fillModeNonSolid: number; depthBounds: number; wideLines: number; largePoints: number; alphaToOne: number; multiViewport: number; samplerAnisotropy: number; textureCompressionETC2: number; textureCompressionASTC_LDR: number; textureCompressionBC: number; occlusionQueryPrecise: number; pipelineStatisticsQuery: number; vertexPipelineStoresAndAtomics: number; fragmentStoresAndAtomics: number; shaderTessellationAndGeometryPointSize: number; shaderImageGatherExtended: number; shaderStorageImageExtendedFormats: number; shaderStorageImageMultisample: number; shaderStorageImageReadWithoutFormat: number; shaderStorageImageWriteWithoutFormat: number; shaderUniformBufferArrayDynamicIndexing: number; shaderSampledImageArrayDynamicIndexing: number; shaderStorageBufferArrayDynamicIndexing: number; shaderStorageImageArrayDynamicIndexing: number; shaderClipDistance: number; shaderCullDistance: number; shaderFloat64: number; shaderInt64: number; shaderInt16: number; shaderResourceResidency: number; shaderResourceMinLod: number; sparseBinding: number; sparseResidencyBuffer: number; sparseResidencyImage2D: number; sparseResidencyImage3D: number; sparseResidency2Samples: number; sparseResidency4Samples: number; sparseResidency8Samples: number; sparseResidency16Samples: number; sparseResidencyAliased: number; variableMultisampleRate: number; inheritedQueries: number; } export interface VkPhysicalDeviceFeatures { robustBufferAccess: number; fullDrawIndexUint32: number; imageCubeArray: number; independentBlend: number; geometryShader: number; tessellationShader: number; sampleRateShading: number; dualSrcBlend: number; logicOp: number; multiDrawIndirect: number; drawIndirectFirstInstance: number; depthClamp: number; depthBiasClamp: number; fillModeNonSolid: number; depthBounds: number; wideLines: number; largePoints: number; alphaToOne: number; multiViewport: number; samplerAnisotropy: number; textureCompressionETC2: number; textureCompressionASTC_LDR: number; textureCompressionBC: number; occlusionQueryPrecise: number; pipelineStatisticsQuery: number; vertexPipelineStoresAndAtomics: number; fragmentStoresAndAtomics: number; shaderTessellationAndGeometryPointSize: number; shaderImageGatherExtended: number; shaderStorageImageExtendedFormats: number; shaderStorageImageMultisample: number; shaderStorageImageReadWithoutFormat: number; shaderStorageImageWriteWithoutFormat: number; shaderUniformBufferArrayDynamicIndexing: number; shaderSampledImageArrayDynamicIndexing: number; shaderStorageBufferArrayDynamicIndexing: number; shaderStorageImageArrayDynamicIndexing: number; shaderClipDistance: number; shaderCullDistance: number; shaderFloat64: number; shaderInt64: number; shaderInt16: number; shaderResourceResidency: number; shaderResourceMinLod: number; sparseBinding: number; sparseResidencyBuffer: number; sparseResidencyImage2D: number; sparseResidencyImage3D: number; sparseResidency2Samples: number; sparseResidency4Samples: number; sparseResidency8Samples: number; sparseResidency16Samples: number; sparseResidencyAliased: number; variableMultisampleRate: number; inheritedQueries: number; } /** ## VkFenceCreateInfo ## */ interface VkFenceCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkFenceCreateFlagBits; } declare var VkFenceCreateInfo: { prototype: VkFenceCreateInfo; new(param?: VkFenceCreateInfoInitializer | null): VkFenceCreateInfo; sType: VkStructureType; pNext: null; flags: VkFenceCreateFlagBits; } export interface VkFenceCreateInfo { sType: VkStructureType; pNext: null; flags: VkFenceCreateFlagBits; } /** ## VkEventCreateInfo ## */ interface VkEventCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; } declare var VkEventCreateInfo: { prototype: VkEventCreateInfo; new(param?: VkEventCreateInfoInitializer | null): VkEventCreateInfo; sType: VkStructureType; pNext: null; flags: null; } export interface VkEventCreateInfo { sType: VkStructureType; pNext: null; flags: null; } /** ## VkRenderPassCreateInfo ## */ interface VkRenderPassCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; attachmentCount?: number; pAttachments?: VkAttachmentDescription[] | null; subpassCount?: number; pSubpasses?: VkSubpassDescription[] | null; dependencyCount?: number; pDependencies?: VkSubpassDependency[] | null; } declare var VkRenderPassCreateInfo: { prototype: VkRenderPassCreateInfo; new(param?: VkRenderPassCreateInfoInitializer | null): VkRenderPassCreateInfo; sType: VkStructureType; pNext: null; flags: null; attachmentCount: number; pAttachments: VkAttachmentDescription[] | null; subpassCount: number; pSubpasses: VkSubpassDescription[] | null; dependencyCount: number; pDependencies: VkSubpassDependency[] | null; } export interface VkRenderPassCreateInfo { sType: VkStructureType; pNext: null; flags: null; attachmentCount: number; pAttachments: VkAttachmentDescription[] | null; subpassCount: number; pSubpasses: VkSubpassDescription[] | null; dependencyCount: number; pDependencies: VkSubpassDependency[] | null; } /** ## VkSubpassDependency ## */ interface VkSubpassDependencyInitializer { srcSubpass?: number; dstSubpass?: number; srcStageMask?: VkPipelineStageFlagBits; dstStageMask?: VkPipelineStageFlagBits; srcAccessMask?: VkAccessFlagBits; dstAccessMask?: VkAccessFlagBits; dependencyFlags?: VkDependencyFlagBits; } declare var VkSubpassDependency: { prototype: VkSubpassDependency; new(param?: VkSubpassDependencyInitializer | null): VkSubpassDependency; srcSubpass: number; dstSubpass: number; srcStageMask: VkPipelineStageFlagBits; dstStageMask: VkPipelineStageFlagBits; srcAccessMask: VkAccessFlagBits; dstAccessMask: VkAccessFlagBits; dependencyFlags: VkDependencyFlagBits; } export interface VkSubpassDependency { srcSubpass: number; dstSubpass: number; srcStageMask: VkPipelineStageFlagBits; dstStageMask: VkPipelineStageFlagBits; srcAccessMask: VkAccessFlagBits; dstAccessMask: VkAccessFlagBits; dependencyFlags: VkDependencyFlagBits; } /** ## VkSubpassDescription ## */ interface VkSubpassDescriptionInitializer { flags?: VkSubpassDescriptionFlagBits; pipelineBindPoint?: VkPipelineBindPoint; inputAttachmentCount?: number; pInputAttachments?: VkAttachmentReference[] | null; colorAttachmentCount?: number; pColorAttachments?: VkAttachmentReference[] | null; pResolveAttachments?: VkAttachmentReference[] | null; pDepthStencilAttachment?: VkAttachmentReference | null; preserveAttachmentCount?: number; pPreserveAttachments?: Uint32Array | null; } declare var VkSubpassDescription: { prototype: VkSubpassDescription; new(param?: VkSubpassDescriptionInitializer | null): VkSubpassDescription; flags: VkSubpassDescriptionFlagBits; pipelineBindPoint: VkPipelineBindPoint; inputAttachmentCount: number; pInputAttachments: VkAttachmentReference[] | null; colorAttachmentCount: number; pColorAttachments: VkAttachmentReference[] | null; pResolveAttachments: VkAttachmentReference[] | null; pDepthStencilAttachment: VkAttachmentReference | null; preserveAttachmentCount: number; pPreserveAttachments: Uint32Array | null; } export interface VkSubpassDescription { flags: VkSubpassDescriptionFlagBits; pipelineBindPoint: VkPipelineBindPoint; inputAttachmentCount: number; pInputAttachments: VkAttachmentReference[] | null; colorAttachmentCount: number; pColorAttachments: VkAttachmentReference[] | null; pResolveAttachments: VkAttachmentReference[] | null; pDepthStencilAttachment: VkAttachmentReference | null; preserveAttachmentCount: number; pPreserveAttachments: Uint32Array | null; } /** ## VkAttachmentReference ## */ interface VkAttachmentReferenceInitializer { attachment?: number; layout?: VkImageLayout; } declare var VkAttachmentReference: { prototype: VkAttachmentReference; new(param?: VkAttachmentReferenceInitializer | null): VkAttachmentReference; attachment: number; layout: VkImageLayout; } export interface VkAttachmentReference { attachment: number; layout: VkImageLayout; } /** ## VkAttachmentDescription ## */ interface VkAttachmentDescriptionInitializer { flags?: VkAttachmentDescriptionFlagBits; format?: VkFormat; samples?: VkSampleCountFlagBits; loadOp?: VkAttachmentLoadOp; storeOp?: VkAttachmentStoreOp; stencilLoadOp?: VkAttachmentLoadOp; stencilStoreOp?: VkAttachmentStoreOp; initialLayout?: VkImageLayout; finalLayout?: VkImageLayout; } declare var VkAttachmentDescription: { prototype: VkAttachmentDescription; new(param?: VkAttachmentDescriptionInitializer | null): VkAttachmentDescription; flags: VkAttachmentDescriptionFlagBits; format: VkFormat; samples: VkSampleCountFlagBits; loadOp: VkAttachmentLoadOp; storeOp: VkAttachmentStoreOp; stencilLoadOp: VkAttachmentLoadOp; stencilStoreOp: VkAttachmentStoreOp; initialLayout: VkImageLayout; finalLayout: VkImageLayout; } export interface VkAttachmentDescription { flags: VkAttachmentDescriptionFlagBits; format: VkFormat; samples: VkSampleCountFlagBits; loadOp: VkAttachmentLoadOp; storeOp: VkAttachmentStoreOp; stencilLoadOp: VkAttachmentLoadOp; stencilStoreOp: VkAttachmentStoreOp; initialLayout: VkImageLayout; finalLayout: VkImageLayout; } /** ## VkClearAttachment ## */ interface VkClearAttachmentInitializer { aspectMask?: VkImageAspectFlagBits; colorAttachment?: number; clearValue?: VkClearValue | null; } declare var VkClearAttachment: { prototype: VkClearAttachment; new(param?: VkClearAttachmentInitializer | null): VkClearAttachment; aspectMask: VkImageAspectFlagBits; colorAttachment: number; clearValue: VkClearValue | null; } export interface VkClearAttachment { aspectMask: VkImageAspectFlagBits; colorAttachment: number; clearValue: VkClearValue | null; } /** ## VkClearDepthStencilValue ## */ interface VkClearDepthStencilValueInitializer { depth?: number; stencil?: number; } declare var VkClearDepthStencilValue: { prototype: VkClearDepthStencilValue; new(param?: VkClearDepthStencilValueInitializer | null): VkClearDepthStencilValue; depth: number; stencil: number; } export interface VkClearDepthStencilValue { depth: number; stencil: number; } /** ## VkRenderPassBeginInfo ## */ interface VkRenderPassBeginInfoInitializer { sType?: VkStructureType; pNext?: null; renderPass?: VkRenderPass | null; framebuffer?: VkFramebuffer | null; renderArea?: VkRect2D | null; clearValueCount?: number; pClearValues?: VkClearValue[] | null; } declare var VkRenderPassBeginInfo: { prototype: VkRenderPassBeginInfo; new(param?: VkRenderPassBeginInfoInitializer | null): VkRenderPassBeginInfo; sType: VkStructureType; pNext: null; renderPass: VkRenderPass | null; framebuffer: VkFramebuffer | null; renderArea: VkRect2D | null; clearValueCount: number; pClearValues: VkClearValue[] | null; } export interface VkRenderPassBeginInfo { sType: VkStructureType; pNext: null; renderPass: VkRenderPass | null; framebuffer: VkFramebuffer | null; renderArea: VkRect2D | null; clearValueCount: number; pClearValues: VkClearValue[] | null; } /** ## VkCommandBufferBeginInfo ## */ interface VkCommandBufferBeginInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkCommandBufferUsageFlagBits; pInheritanceInfo?: VkCommandBufferInheritanceInfo | null; } declare var VkCommandBufferBeginInfo: { prototype: VkCommandBufferBeginInfo; new(param?: VkCommandBufferBeginInfoInitializer | null): VkCommandBufferBeginInfo; sType: VkStructureType; pNext: null; flags: VkCommandBufferUsageFlagBits; pInheritanceInfo: VkCommandBufferInheritanceInfo | null; } export interface VkCommandBufferBeginInfo { sType: VkStructureType; pNext: null; flags: VkCommandBufferUsageFlagBits; pInheritanceInfo: VkCommandBufferInheritanceInfo | null; } /** ## VkCommandBufferInheritanceInfo ## */ interface VkCommandBufferInheritanceInfoInitializer { sType?: VkStructureType; pNext?: null; renderPass?: VkRenderPass | null; subpass?: number; framebuffer?: VkFramebuffer | null; occlusionQueryEnable?: number; queryFlags?: VkQueryControlFlagBits; pipelineStatistics?: VkQueryPipelineStatisticFlagBits; } declare var VkCommandBufferInheritanceInfo: { prototype: VkCommandBufferInheritanceInfo; new(param?: VkCommandBufferInheritanceInfoInitializer | null): VkCommandBufferInheritanceInfo; sType: VkStructureType; pNext: null; renderPass: VkRenderPass | null; subpass: number; framebuffer: VkFramebuffer | null; occlusionQueryEnable: number; queryFlags: VkQueryControlFlagBits; pipelineStatistics: VkQueryPipelineStatisticFlagBits; } export interface VkCommandBufferInheritanceInfo { sType: VkStructureType; pNext: null; renderPass: VkRenderPass | null; subpass: number; framebuffer: VkFramebuffer | null; occlusionQueryEnable: number; queryFlags: VkQueryControlFlagBits; pipelineStatistics: VkQueryPipelineStatisticFlagBits; } /** ## VkCommandBufferAllocateInfo ## */ interface VkCommandBufferAllocateInfoInitializer { sType?: VkStructureType; pNext?: null; commandPool?: VkCommandPool | null; level?: VkCommandBufferLevel; commandBufferCount?: number; } declare var VkCommandBufferAllocateInfo: { prototype: VkCommandBufferAllocateInfo; new(param?: VkCommandBufferAllocateInfoInitializer | null): VkCommandBufferAllocateInfo; sType: VkStructureType; pNext: null; commandPool: VkCommandPool | null; level: VkCommandBufferLevel; commandBufferCount: number; } export interface VkCommandBufferAllocateInfo { sType: VkStructureType; pNext: null; commandPool: VkCommandPool | null; level: VkCommandBufferLevel; commandBufferCount: number; } /** ## VkCommandPoolCreateInfo ## */ interface VkCommandPoolCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkCommandPoolCreateFlagBits; queueFamilyIndex?: number; } declare var VkCommandPoolCreateInfo: { prototype: VkCommandPoolCreateInfo; new(param?: VkCommandPoolCreateInfoInitializer | null): VkCommandPoolCreateInfo; sType: VkStructureType; pNext: null; flags: VkCommandPoolCreateFlagBits; queueFamilyIndex: number; } export interface VkCommandPoolCreateInfo { sType: VkStructureType; pNext: null; flags: VkCommandPoolCreateFlagBits; queueFamilyIndex: number; } /** ## VkSamplerCreateInfo ## */ interface VkSamplerCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkSamplerCreateFlagBits; magFilter?: VkFilter; minFilter?: VkFilter; mipmapMode?: VkSamplerMipmapMode; addressModeU?: VkSamplerAddressMode; addressModeV?: VkSamplerAddressMode; addressModeW?: VkSamplerAddressMode; mipLodBias?: number; anisotropyEnable?: number; maxAnisotropy?: number; compareEnable?: number; compareOp?: VkCompareOp; minLod?: number; maxLod?: number; borderColor?: VkBorderColor; unnormalizedCoordinates?: number; } declare var VkSamplerCreateInfo: { prototype: VkSamplerCreateInfo; new(param?: VkSamplerCreateInfoInitializer | null): VkSamplerCreateInfo; sType: VkStructureType; pNext: null; flags: VkSamplerCreateFlagBits; magFilter: VkFilter; minFilter: VkFilter; mipmapMode: VkSamplerMipmapMode; addressModeU: VkSamplerAddressMode; addressModeV: VkSamplerAddressMode; addressModeW: VkSamplerAddressMode; mipLodBias: number; anisotropyEnable: number; maxAnisotropy: number; compareEnable: number; compareOp: VkCompareOp; minLod: number; maxLod: number; borderColor: VkBorderColor; unnormalizedCoordinates: number; } export interface VkSamplerCreateInfo { sType: VkStructureType; pNext: null; flags: VkSamplerCreateFlagBits; magFilter: VkFilter; minFilter: VkFilter; mipmapMode: VkSamplerMipmapMode; addressModeU: VkSamplerAddressMode; addressModeV: VkSamplerAddressMode; addressModeW: VkSamplerAddressMode; mipLodBias: number; anisotropyEnable: number; maxAnisotropy: number; compareEnable: number; compareOp: VkCompareOp; minLod: number; maxLod: number; borderColor: VkBorderColor; unnormalizedCoordinates: number; } /** ## VkPipelineLayoutCreateInfo ## */ interface VkPipelineLayoutCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; setLayoutCount?: number; pSetLayouts?: VkDescriptorSetLayout[] | null; pushConstantRangeCount?: number; pPushConstantRanges?: VkPushConstantRange[] | null; } declare var VkPipelineLayoutCreateInfo: { prototype: VkPipelineLayoutCreateInfo; new(param?: VkPipelineLayoutCreateInfoInitializer | null): VkPipelineLayoutCreateInfo; sType: VkStructureType; pNext: null; flags: null; setLayoutCount: number; pSetLayouts: VkDescriptorSetLayout[] | null; pushConstantRangeCount: number; pPushConstantRanges: VkPushConstantRange[] | null; } export interface VkPipelineLayoutCreateInfo { sType: VkStructureType; pNext: null; flags: null; setLayoutCount: number; pSetLayouts: VkDescriptorSetLayout[] | null; pushConstantRangeCount: number; pPushConstantRanges: VkPushConstantRange[] | null; } /** ## VkPushConstantRange ## */ interface VkPushConstantRangeInitializer { stageFlags?: VkShaderStageFlagBits; offset?: number; size?: number; } declare var VkPushConstantRange: { prototype: VkPushConstantRange; new(param?: VkPushConstantRangeInitializer | null): VkPushConstantRange; stageFlags: VkShaderStageFlagBits; offset: number; size: number; } export interface VkPushConstantRange { stageFlags: VkShaderStageFlagBits; offset: number; size: number; } /** ## VkPipelineCacheCreateInfo ## */ interface VkPipelineCacheCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; initialDataSize?: number; pInitialData?: ArrayBuffer | null; } declare var VkPipelineCacheCreateInfo: { prototype: VkPipelineCacheCreateInfo; new(param?: VkPipelineCacheCreateInfoInitializer | null): VkPipelineCacheCreateInfo; sType: VkStructureType; pNext: null; flags: null; initialDataSize: number; pInitialData: ArrayBuffer | null; } export interface VkPipelineCacheCreateInfo { sType: VkStructureType; pNext: null; flags: null; initialDataSize: number; pInitialData: ArrayBuffer | null; } /** ## VkGraphicsPipelineCreateInfo ## */ interface VkGraphicsPipelineCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkPipelineCreateFlagBits; stageCount?: number; pStages?: VkPipelineShaderStageCreateInfo[] | null; pVertexInputState?: VkPipelineVertexInputStateCreateInfo | null; pInputAssemblyState?: VkPipelineInputAssemblyStateCreateInfo | null; pTessellationState?: VkPipelineTessellationStateCreateInfo | null; pViewportState?: VkPipelineViewportStateCreateInfo | null; pRasterizationState?: VkPipelineRasterizationStateCreateInfo | null; pMultisampleState?: VkPipelineMultisampleStateCreateInfo | null; pDepthStencilState?: VkPipelineDepthStencilStateCreateInfo | null; pColorBlendState?: VkPipelineColorBlendStateCreateInfo | null; pDynamicState?: VkPipelineDynamicStateCreateInfo | null; layout?: VkPipelineLayout | null; renderPass?: VkRenderPass | null; subpass?: number; basePipelineHandle?: VkPipeline | null; basePipelineIndex?: number; } declare var VkGraphicsPipelineCreateInfo: { prototype: VkGraphicsPipelineCreateInfo; new(param?: VkGraphicsPipelineCreateInfoInitializer | null): VkGraphicsPipelineCreateInfo; sType: VkStructureType; pNext: null; flags: VkPipelineCreateFlagBits; stageCount: number; pStages: VkPipelineShaderStageCreateInfo[] | null; pVertexInputState: VkPipelineVertexInputStateCreateInfo | null; pInputAssemblyState: VkPipelineInputAssemblyStateCreateInfo | null; pTessellationState: VkPipelineTessellationStateCreateInfo | null; pViewportState: VkPipelineViewportStateCreateInfo | null; pRasterizationState: VkPipelineRasterizationStateCreateInfo | null; pMultisampleState: VkPipelineMultisampleStateCreateInfo | null; pDepthStencilState: VkPipelineDepthStencilStateCreateInfo | null; pColorBlendState: VkPipelineColorBlendStateCreateInfo | null; pDynamicState: VkPipelineDynamicStateCreateInfo | null; layout: VkPipelineLayout | null; renderPass: VkRenderPass | null; subpass: number; basePipelineHandle: VkPipeline | null; basePipelineIndex: number; } export interface VkGraphicsPipelineCreateInfo { sType: VkStructureType; pNext: null; flags: VkPipelineCreateFlagBits; stageCount: number; pStages: VkPipelineShaderStageCreateInfo[] | null; pVertexInputState: VkPipelineVertexInputStateCreateInfo | null; pInputAssemblyState: VkPipelineInputAssemblyStateCreateInfo | null; pTessellationState: VkPipelineTessellationStateCreateInfo | null; pViewportState: VkPipelineViewportStateCreateInfo | null; pRasterizationState: VkPipelineRasterizationStateCreateInfo | null; pMultisampleState: VkPipelineMultisampleStateCreateInfo | null; pDepthStencilState: VkPipelineDepthStencilStateCreateInfo | null; pColorBlendState: VkPipelineColorBlendStateCreateInfo | null; pDynamicState: VkPipelineDynamicStateCreateInfo | null; layout: VkPipelineLayout | null; renderPass: VkRenderPass | null; subpass: number; basePipelineHandle: VkPipeline | null; basePipelineIndex: number; } /** ## VkPipelineDepthStencilStateCreateInfo ## */ interface VkPipelineDepthStencilStateCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; depthTestEnable?: number; depthWriteEnable?: number; depthCompareOp?: VkCompareOp; depthBoundsTestEnable?: number; stencilTestEnable?: number; front?: VkStencilOpState | null; back?: VkStencilOpState | null; minDepthBounds?: number; maxDepthBounds?: number; } declare var VkPipelineDepthStencilStateCreateInfo: { prototype: VkPipelineDepthStencilStateCreateInfo; new(param?: VkPipelineDepthStencilStateCreateInfoInitializer | null): VkPipelineDepthStencilStateCreateInfo; sType: VkStructureType; pNext: null; flags: null; depthTestEnable: number; depthWriteEnable: number; depthCompareOp: VkCompareOp; depthBoundsTestEnable: number; stencilTestEnable: number; front: VkStencilOpState | null; back: VkStencilOpState | null; minDepthBounds: number; maxDepthBounds: number; } export interface VkPipelineDepthStencilStateCreateInfo { sType: VkStructureType; pNext: null; flags: null; depthTestEnable: number; depthWriteEnable: number; depthCompareOp: VkCompareOp; depthBoundsTestEnable: number; stencilTestEnable: number; front: VkStencilOpState | null; back: VkStencilOpState | null; minDepthBounds: number; maxDepthBounds: number; } /** ## VkStencilOpState ## */ interface VkStencilOpStateInitializer { failOp?: VkStencilOp; passOp?: VkStencilOp; depthFailOp?: VkStencilOp; compareOp?: VkCompareOp; compareMask?: number; writeMask?: number; reference?: number; } declare var VkStencilOpState: { prototype: VkStencilOpState; new(param?: VkStencilOpStateInitializer | null): VkStencilOpState; failOp: VkStencilOp; passOp: VkStencilOp; depthFailOp: VkStencilOp; compareOp: VkCompareOp; compareMask: number; writeMask: number; reference: number; } export interface VkStencilOpState { failOp: VkStencilOp; passOp: VkStencilOp; depthFailOp: VkStencilOp; compareOp: VkCompareOp; compareMask: number; writeMask: number; reference: number; } /** ## VkPipelineDynamicStateCreateInfo ## */ interface VkPipelineDynamicStateCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; dynamicStateCount?: number; pDynamicStates?: Int32Array | null; } declare var VkPipelineDynamicStateCreateInfo: { prototype: VkPipelineDynamicStateCreateInfo; new(param?: VkPipelineDynamicStateCreateInfoInitializer | null): VkPipelineDynamicStateCreateInfo; sType: VkStructureType; pNext: null; flags: null; dynamicStateCount: number; pDynamicStates: Int32Array | null; } export interface VkPipelineDynamicStateCreateInfo { sType: VkStructureType; pNext: null; flags: null; dynamicStateCount: number; pDynamicStates: Int32Array | null; } /** ## VkPipelineColorBlendStateCreateInfo ## */ interface VkPipelineColorBlendStateCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; logicOpEnable?: number; logicOp?: VkLogicOp; attachmentCount?: number; pAttachments?: VkPipelineColorBlendAttachmentState[] | null; blendConstants?: number[] | null; } declare var VkPipelineColorBlendStateCreateInfo: { prototype: VkPipelineColorBlendStateCreateInfo; new(param?: VkPipelineColorBlendStateCreateInfoInitializer | null): VkPipelineColorBlendStateCreateInfo; sType: VkStructureType; pNext: null; flags: null; logicOpEnable: number; logicOp: VkLogicOp; attachmentCount: number; pAttachments: VkPipelineColorBlendAttachmentState[] | null; blendConstants: number[] | null; } export interface VkPipelineColorBlendStateCreateInfo { sType: VkStructureType; pNext: null; flags: null; logicOpEnable: number; logicOp: VkLogicOp; attachmentCount: number; pAttachments: VkPipelineColorBlendAttachmentState[] | null; blendConstants: number[] | null; } /** ## VkPipelineColorBlendAttachmentState ## */ interface VkPipelineColorBlendAttachmentStateInitializer { blendEnable?: number; srcColorBlendFactor?: VkBlendFactor; dstColorBlendFactor?: VkBlendFactor; colorBlendOp?: VkBlendOp; srcAlphaBlendFactor?: VkBlendFactor; dstAlphaBlendFactor?: VkBlendFactor; alphaBlendOp?: VkBlendOp; colorWriteMask?: VkColorComponentFlagBits; } declare var VkPipelineColorBlendAttachmentState: { prototype: VkPipelineColorBlendAttachmentState; new(param?: VkPipelineColorBlendAttachmentStateInitializer | null): VkPipelineColorBlendAttachmentState; blendEnable: number; srcColorBlendFactor: VkBlendFactor; dstColorBlendFactor: VkBlendFactor; colorBlendOp: VkBlendOp; srcAlphaBlendFactor: VkBlendFactor; dstAlphaBlendFactor: VkBlendFactor; alphaBlendOp: VkBlendOp; colorWriteMask: VkColorComponentFlagBits; } export interface VkPipelineColorBlendAttachmentState { blendEnable: number; srcColorBlendFactor: VkBlendFactor; dstColorBlendFactor: VkBlendFactor; colorBlendOp: VkBlendOp; srcAlphaBlendFactor: VkBlendFactor; dstAlphaBlendFactor: VkBlendFactor; alphaBlendOp: VkBlendOp; colorWriteMask: VkColorComponentFlagBits; } /** ## VkPipelineMultisampleStateCreateInfo ## */ interface VkPipelineMultisampleStateCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; rasterizationSamples?: VkSampleCountFlagBits; sampleShadingEnable?: number; minSampleShading?: number; pSampleMask?: Uint32Array | null; alphaToCoverageEnable?: number; alphaToOneEnable?: number; } declare var VkPipelineMultisampleStateCreateInfo: { prototype: VkPipelineMultisampleStateCreateInfo; new(param?: VkPipelineMultisampleStateCreateInfoInitializer | null): VkPipelineMultisampleStateCreateInfo; sType: VkStructureType; pNext: null; flags: null; rasterizationSamples: VkSampleCountFlagBits; sampleShadingEnable: number; minSampleShading: number; pSampleMask: Uint32Array | null; alphaToCoverageEnable: number; alphaToOneEnable: number; } export interface VkPipelineMultisampleStateCreateInfo { sType: VkStructureType; pNext: null; flags: null; rasterizationSamples: VkSampleCountFlagBits; sampleShadingEnable: number; minSampleShading: number; pSampleMask: Uint32Array | null; alphaToCoverageEnable: number; alphaToOneEnable: number; } /** ## VkPipelineRasterizationStateCreateInfo ## */ interface VkPipelineRasterizationStateCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; depthClampEnable?: number; rasterizerDiscardEnable?: number; polygonMode?: VkPolygonMode; cullMode?: VkCullModeFlagBits; frontFace?: VkFrontFace; depthBiasEnable?: number; depthBiasConstantFactor?: number; depthBiasClamp?: number; depthBiasSlopeFactor?: number; lineWidth?: number; } declare var VkPipelineRasterizationStateCreateInfo: { prototype: VkPipelineRasterizationStateCreateInfo; new(param?: VkPipelineRasterizationStateCreateInfoInitializer | null): VkPipelineRasterizationStateCreateInfo; sType: VkStructureType; pNext: null; flags: null; depthClampEnable: number; rasterizerDiscardEnable: number; polygonMode: VkPolygonMode; cullMode: VkCullModeFlagBits; frontFace: VkFrontFace; depthBiasEnable: number; depthBiasConstantFactor: number; depthBiasClamp: number; depthBiasSlopeFactor: number; lineWidth: number; } export interface VkPipelineRasterizationStateCreateInfo { sType: VkStructureType; pNext: null; flags: null; depthClampEnable: number; rasterizerDiscardEnable: number; polygonMode: VkPolygonMode; cullMode: VkCullModeFlagBits; frontFace: VkFrontFace; depthBiasEnable: number; depthBiasConstantFactor: number; depthBiasClamp: number; depthBiasSlopeFactor: number; lineWidth: number; } /** ## VkPipelineViewportStateCreateInfo ## */ interface VkPipelineViewportStateCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; viewportCount?: number; pViewports?: VkViewport[] | null; scissorCount?: number; pScissors?: VkRect2D[] | null; } declare var VkPipelineViewportStateCreateInfo: { prototype: VkPipelineViewportStateCreateInfo; new(param?: VkPipelineViewportStateCreateInfoInitializer | null): VkPipelineViewportStateCreateInfo; sType: VkStructureType; pNext: null; flags: null; viewportCount: number; pViewports: VkViewport[] | null; scissorCount: number; pScissors: VkRect2D[] | null; } export interface VkPipelineViewportStateCreateInfo { sType: VkStructureType; pNext: null; flags: null; viewportCount: number; pViewports: VkViewport[] | null; scissorCount: number; pScissors: VkRect2D[] | null; } /** ## VkPipelineTessellationStateCreateInfo ## */ interface VkPipelineTessellationStateCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; patchControlPoints?: number; } declare var VkPipelineTessellationStateCreateInfo: { prototype: VkPipelineTessellationStateCreateInfo; new(param?: VkPipelineTessellationStateCreateInfoInitializer | null): VkPipelineTessellationStateCreateInfo; sType: VkStructureType; pNext: null; flags: null; patchControlPoints: number; } export interface VkPipelineTessellationStateCreateInfo { sType: VkStructureType; pNext: null; flags: null; patchControlPoints: number; } /** ## VkPipelineInputAssemblyStateCreateInfo ## */ interface VkPipelineInputAssemblyStateCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; topology?: VkPrimitiveTopology; primitiveRestartEnable?: number; } declare var VkPipelineInputAssemblyStateCreateInfo: { prototype: VkPipelineInputAssemblyStateCreateInfo; new(param?: VkPipelineInputAssemblyStateCreateInfoInitializer | null): VkPipelineInputAssemblyStateCreateInfo; sType: VkStructureType; pNext: null; flags: null; topology: VkPrimitiveTopology; primitiveRestartEnable: number; } export interface VkPipelineInputAssemblyStateCreateInfo { sType: VkStructureType; pNext: null; flags: null; topology: VkPrimitiveTopology; primitiveRestartEnable: number; } /** ## VkPipelineVertexInputStateCreateInfo ## */ interface VkPipelineVertexInputStateCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; vertexBindingDescriptionCount?: number; pVertexBindingDescriptions?: VkVertexInputBindingDescription[] | null; vertexAttributeDescriptionCount?: number; pVertexAttributeDescriptions?: VkVertexInputAttributeDescription[] | null; } declare var VkPipelineVertexInputStateCreateInfo: { prototype: VkPipelineVertexInputStateCreateInfo; new(param?: VkPipelineVertexInputStateCreateInfoInitializer | null): VkPipelineVertexInputStateCreateInfo; sType: VkStructureType; pNext: null; flags: null; vertexBindingDescriptionCount: number; pVertexBindingDescriptions: VkVertexInputBindingDescription[] | null; vertexAttributeDescriptionCount: number; pVertexAttributeDescriptions: VkVertexInputAttributeDescription[] | null; } export interface VkPipelineVertexInputStateCreateInfo { sType: VkStructureType; pNext: null; flags: null; vertexBindingDescriptionCount: number; pVertexBindingDescriptions: VkVertexInputBindingDescription[] | null; vertexAttributeDescriptionCount: number; pVertexAttributeDescriptions: VkVertexInputAttributeDescription[] | null; } /** ## VkVertexInputAttributeDescription ## */ interface VkVertexInputAttributeDescriptionInitializer { location?: number; binding?: number; format?: VkFormat; offset?: number; } declare var VkVertexInputAttributeDescription: { prototype: VkVertexInputAttributeDescription; new(param?: VkVertexInputAttributeDescriptionInitializer | null): VkVertexInputAttributeDescription; location: number; binding: number; format: VkFormat; offset: number; } export interface VkVertexInputAttributeDescription { location: number; binding: number; format: VkFormat; offset: number; } /** ## VkVertexInputBindingDescription ## */ interface VkVertexInputBindingDescriptionInitializer { binding?: number; stride?: number; inputRate?: VkVertexInputRate; } declare var VkVertexInputBindingDescription: { prototype: VkVertexInputBindingDescription; new(param?: VkVertexInputBindingDescriptionInitializer | null): VkVertexInputBindingDescription; binding: number; stride: number; inputRate: VkVertexInputRate; } export interface VkVertexInputBindingDescription { binding: number; stride: number; inputRate: VkVertexInputRate; } /** ## VkComputePipelineCreateInfo ## */ interface VkComputePipelineCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkPipelineCreateFlagBits; stage?: VkPipelineShaderStageCreateInfo | null; layout?: VkPipelineLayout | null; basePipelineHandle?: VkPipeline | null; basePipelineIndex?: number; } declare var VkComputePipelineCreateInfo: { prototype: VkComputePipelineCreateInfo; new(param?: VkComputePipelineCreateInfoInitializer | null): VkComputePipelineCreateInfo; sType: VkStructureType; pNext: null; flags: VkPipelineCreateFlagBits; stage: VkPipelineShaderStageCreateInfo | null; layout: VkPipelineLayout | null; basePipelineHandle: VkPipeline | null; basePipelineIndex: number; } export interface VkComputePipelineCreateInfo { sType: VkStructureType; pNext: null; flags: VkPipelineCreateFlagBits; stage: VkPipelineShaderStageCreateInfo | null; layout: VkPipelineLayout | null; basePipelineHandle: VkPipeline | null; basePipelineIndex: number; } /** ## VkPipelineShaderStageCreateInfo ## */ interface VkPipelineShaderStageCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; stage?: VkShaderStageFlagBits; module?: VkShaderModule | null; pName?: string | null; pSpecializationInfo?: VkSpecializationInfo | null; } declare var VkPipelineShaderStageCreateInfo: { prototype: VkPipelineShaderStageCreateInfo; new(param?: VkPipelineShaderStageCreateInfoInitializer | null): VkPipelineShaderStageCreateInfo; sType: VkStructureType; pNext: null; flags: null; stage: VkShaderStageFlagBits; module: VkShaderModule | null; pName: string | null; pSpecializationInfo: VkSpecializationInfo | null; } export interface VkPipelineShaderStageCreateInfo { sType: VkStructureType; pNext: null; flags: null; stage: VkShaderStageFlagBits; module: VkShaderModule | null; pName: string | null; pSpecializationInfo: VkSpecializationInfo | null; } /** ## VkSpecializationInfo ## */ interface VkSpecializationInfoInitializer { mapEntryCount?: number; pMapEntries?: VkSpecializationMapEntry[] | null; dataSize?: number; pData?: ArrayBuffer | null; } declare var VkSpecializationInfo: { prototype: VkSpecializationInfo; new(param?: VkSpecializationInfoInitializer | null): VkSpecializationInfo; mapEntryCount: number; pMapEntries: VkSpecializationMapEntry[] | null; dataSize: number; pData: ArrayBuffer | null; } export interface VkSpecializationInfo { mapEntryCount: number; pMapEntries: VkSpecializationMapEntry[] | null; dataSize: number; pData: ArrayBuffer | null; } /** ## VkSpecializationMapEntry ## */ interface VkSpecializationMapEntryInitializer { constantID?: number; offset?: number; size?: number; } declare var VkSpecializationMapEntry: { prototype: VkSpecializationMapEntry; new(param?: VkSpecializationMapEntryInitializer | null): VkSpecializationMapEntry; constantID: number; offset: number; size: number; } export interface VkSpecializationMapEntry { constantID: number; offset: number; size: number; } /** ## VkDescriptorSetAllocateInfo ## */ interface VkDescriptorSetAllocateInfoInitializer { sType?: VkStructureType; pNext?: null; descriptorPool?: VkDescriptorPool | null; descriptorSetCount?: number; pSetLayouts?: VkDescriptorSetLayout[] | null; } declare var VkDescriptorSetAllocateInfo: { prototype: VkDescriptorSetAllocateInfo; new(param?: VkDescriptorSetAllocateInfoInitializer | null): VkDescriptorSetAllocateInfo; sType: VkStructureType; pNext: null; descriptorPool: VkDescriptorPool | null; descriptorSetCount: number; pSetLayouts: VkDescriptorSetLayout[] | null; } export interface VkDescriptorSetAllocateInfo { sType: VkStructureType; pNext: null; descriptorPool: VkDescriptorPool | null; descriptorSetCount: number; pSetLayouts: VkDescriptorSetLayout[] | null; } /** ## VkDescriptorPoolCreateInfo ## */ interface VkDescriptorPoolCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkDescriptorPoolCreateFlagBits; maxSets?: number; poolSizeCount?: number; pPoolSizes?: VkDescriptorPoolSize[] | null; } declare var VkDescriptorPoolCreateInfo: { prototype: VkDescriptorPoolCreateInfo; new(param?: VkDescriptorPoolCreateInfoInitializer | null): VkDescriptorPoolCreateInfo; sType: VkStructureType; pNext: null; flags: VkDescriptorPoolCreateFlagBits; maxSets: number; poolSizeCount: number; pPoolSizes: VkDescriptorPoolSize[] | null; } export interface VkDescriptorPoolCreateInfo { sType: VkStructureType; pNext: null; flags: VkDescriptorPoolCreateFlagBits; maxSets: number; poolSizeCount: number; pPoolSizes: VkDescriptorPoolSize[] | null; } /** ## VkDescriptorPoolSize ## */ interface VkDescriptorPoolSizeInitializer { type?: VkDescriptorType; descriptorCount?: number; } declare var VkDescriptorPoolSize: { prototype: VkDescriptorPoolSize; new(param?: VkDescriptorPoolSizeInitializer | null): VkDescriptorPoolSize; type: VkDescriptorType; descriptorCount: number; } export interface VkDescriptorPoolSize { type: VkDescriptorType; descriptorCount: number; } /** ## VkDescriptorSetLayoutCreateInfo ## */ interface VkDescriptorSetLayoutCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkDescriptorSetLayoutCreateFlagBits; bindingCount?: number; pBindings?: VkDescriptorSetLayoutBinding[] | null; } declare var VkDescriptorSetLayoutCreateInfo: { prototype: VkDescriptorSetLayoutCreateInfo; new(param?: VkDescriptorSetLayoutCreateInfoInitializer | null): VkDescriptorSetLayoutCreateInfo; sType: VkStructureType; pNext: null; flags: VkDescriptorSetLayoutCreateFlagBits; bindingCount: number; pBindings: VkDescriptorSetLayoutBinding[] | null; } export interface VkDescriptorSetLayoutCreateInfo { sType: VkStructureType; pNext: null; flags: VkDescriptorSetLayoutCreateFlagBits; bindingCount: number; pBindings: VkDescriptorSetLayoutBinding[] | null; } /** ## VkDescriptorSetLayoutBinding ## */ interface VkDescriptorSetLayoutBindingInitializer { binding?: number; descriptorType?: VkDescriptorType; descriptorCount?: number; stageFlags?: VkShaderStageFlagBits; pImmutableSamplers?: VkSampler[] | null; } declare var VkDescriptorSetLayoutBinding: { prototype: VkDescriptorSetLayoutBinding; new(param?: VkDescriptorSetLayoutBindingInitializer | null): VkDescriptorSetLayoutBinding; binding: number; descriptorType: VkDescriptorType; descriptorCount: number; stageFlags: VkShaderStageFlagBits; pImmutableSamplers: VkSampler[] | null; } export interface VkDescriptorSetLayoutBinding { binding: number; descriptorType: VkDescriptorType; descriptorCount: number; stageFlags: VkShaderStageFlagBits; pImmutableSamplers: VkSampler[] | null; } /** ## VkShaderModuleCreateInfo ## */ interface VkShaderModuleCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; codeSize?: number; pCode?: Uint8Array | null; } declare var VkShaderModuleCreateInfo: { prototype: VkShaderModuleCreateInfo; new(param?: VkShaderModuleCreateInfoInitializer | null): VkShaderModuleCreateInfo; sType: VkStructureType; pNext: null; flags: null; codeSize: number; pCode: Uint8Array | null; } export interface VkShaderModuleCreateInfo { sType: VkStructureType; pNext: null; flags: null; codeSize: number; pCode: Uint8Array | null; } /** ## VkImageResolve ## */ interface VkImageResolveInitializer { srcSubresource?: VkImageSubresourceLayers | null; srcOffset?: VkOffset3D | null; dstSubresource?: VkImageSubresourceLayers | null; dstOffset?: VkOffset3D | null; extent?: VkExtent3D | null; } declare var VkImageResolve: { prototype: VkImageResolve; new(param?: VkImageResolveInitializer | null): VkImageResolve; srcSubresource: VkImageSubresourceLayers | null; srcOffset: VkOffset3D | null; dstSubresource: VkImageSubresourceLayers | null; dstOffset: VkOffset3D | null; extent: VkExtent3D | null; } export interface VkImageResolve { srcSubresource: VkImageSubresourceLayers | null; srcOffset: VkOffset3D | null; dstSubresource: VkImageSubresourceLayers | null; dstOffset: VkOffset3D | null; extent: VkExtent3D | null; } /** ## VkBufferImageCopy ## */ interface VkBufferImageCopyInitializer { bufferOffset?: number; bufferRowLength?: number; bufferImageHeight?: number; imageSubresource?: VkImageSubresourceLayers | null; imageOffset?: VkOffset3D | null; imageExtent?: VkExtent3D | null; } declare var VkBufferImageCopy: { prototype: VkBufferImageCopy; new(param?: VkBufferImageCopyInitializer | null): VkBufferImageCopy; bufferOffset: number; bufferRowLength: number; bufferImageHeight: number; imageSubresource: VkImageSubresourceLayers | null; imageOffset: VkOffset3D | null; imageExtent: VkExtent3D | null; } export interface VkBufferImageCopy { bufferOffset: number; bufferRowLength: number; bufferImageHeight: number; imageSubresource: VkImageSubresourceLayers | null; imageOffset: VkOffset3D | null; imageExtent: VkExtent3D | null; } /** ## VkImageBlit ## */ interface VkImageBlitInitializer { srcSubresource?: VkImageSubresourceLayers | null; srcOffsets?: number[] | null; dstSubresource?: VkImageSubresourceLayers | null; dstOffsets?: number[] | null; } declare var VkImageBlit: { prototype: VkImageBlit; new(param?: VkImageBlitInitializer | null): VkImageBlit; srcSubresource: VkImageSubresourceLayers | null; srcOffsets: number[] | null; dstSubresource: VkImageSubresourceLayers | null; dstOffsets: number[] | null; } export interface VkImageBlit { srcSubresource: VkImageSubresourceLayers | null; srcOffsets: number[] | null; dstSubresource: VkImageSubresourceLayers | null; dstOffsets: number[] | null; } /** ## VkImageCopy ## */ interface VkImageCopyInitializer { srcSubresource?: VkImageSubresourceLayers | null; srcOffset?: VkOffset3D | null; dstSubresource?: VkImageSubresourceLayers | null; dstOffset?: VkOffset3D | null; extent?: VkExtent3D | null; } declare var VkImageCopy: { prototype: VkImageCopy; new(param?: VkImageCopyInitializer | null): VkImageCopy; srcSubresource: VkImageSubresourceLayers | null; srcOffset: VkOffset3D | null; dstSubresource: VkImageSubresourceLayers | null; dstOffset: VkOffset3D | null; extent: VkExtent3D | null; } export interface VkImageCopy { srcSubresource: VkImageSubresourceLayers | null; srcOffset: VkOffset3D | null; dstSubresource: VkImageSubresourceLayers | null; dstOffset: VkOffset3D | null; extent: VkExtent3D | null; } /** ## VkBindSparseInfo ## */ interface VkBindSparseInfoInitializer { sType?: VkStructureType; pNext?: null; waitSemaphoreCount?: number; pWaitSemaphores?: VkSemaphore[] | null; bufferBindCount?: number; pBufferBinds?: VkSparseBufferMemoryBindInfo[] | null; imageOpaqueBindCount?: number; pImageOpaqueBinds?: VkSparseImageOpaqueMemoryBindInfo[] | null; imageBindCount?: number; pImageBinds?: VkSparseImageMemoryBindInfo[] | null; signalSemaphoreCount?: number; pSignalSemaphores?: VkSemaphore[] | null; } declare var VkBindSparseInfo: { prototype: VkBindSparseInfo; new(param?: VkBindSparseInfoInitializer | null): VkBindSparseInfo; sType: VkStructureType; pNext: null; waitSemaphoreCount: number; pWaitSemaphores: VkSemaphore[] | null; bufferBindCount: number; pBufferBinds: VkSparseBufferMemoryBindInfo[] | null; imageOpaqueBindCount: number; pImageOpaqueBinds: VkSparseImageOpaqueMemoryBindInfo[] | null; imageBindCount: number; pImageBinds: VkSparseImageMemoryBindInfo[] | null; signalSemaphoreCount: number; pSignalSemaphores: VkSemaphore[] | null; } export interface VkBindSparseInfo { sType: VkStructureType; pNext: null; waitSemaphoreCount: number; pWaitSemaphores: VkSemaphore[] | null; bufferBindCount: number; pBufferBinds: VkSparseBufferMemoryBindInfo[] | null; imageOpaqueBindCount: number; pImageOpaqueBinds: VkSparseImageOpaqueMemoryBindInfo[] | null; imageBindCount: number; pImageBinds: VkSparseImageMemoryBindInfo[] | null; signalSemaphoreCount: number; pSignalSemaphores: VkSemaphore[] | null; } /** ## VkSparseImageMemoryBindInfo ## */ interface VkSparseImageMemoryBindInfoInitializer { image?: VkImage | null; bindCount?: number; pBinds?: VkSparseImageMemoryBind[] | null; } declare var VkSparseImageMemoryBindInfo: { prototype: VkSparseImageMemoryBindInfo; new(param?: VkSparseImageMemoryBindInfoInitializer | null): VkSparseImageMemoryBindInfo; image: VkImage | null; bindCount: number; pBinds: VkSparseImageMemoryBind[] | null; } export interface VkSparseImageMemoryBindInfo { image: VkImage | null; bindCount: number; pBinds: VkSparseImageMemoryBind[] | null; } /** ## VkSparseImageOpaqueMemoryBindInfo ## */ interface VkSparseImageOpaqueMemoryBindInfoInitializer { image?: VkImage | null; bindCount?: number; pBinds?: VkSparseMemoryBind[] | null; } declare var VkSparseImageOpaqueMemoryBindInfo: { prototype: VkSparseImageOpaqueMemoryBindInfo; new(param?: VkSparseImageOpaqueMemoryBindInfoInitializer | null): VkSparseImageOpaqueMemoryBindInfo; image: VkImage | null; bindCount: number; pBinds: VkSparseMemoryBind[] | null; } export interface VkSparseImageOpaqueMemoryBindInfo { image: VkImage | null; bindCount: number; pBinds: VkSparseMemoryBind[] | null; } /** ## VkSparseBufferMemoryBindInfo ## */ interface VkSparseBufferMemoryBindInfoInitializer { buffer?: VkBuffer | null; bindCount?: number; pBinds?: VkSparseMemoryBind[] | null; } declare var VkSparseBufferMemoryBindInfo: { prototype: VkSparseBufferMemoryBindInfo; new(param?: VkSparseBufferMemoryBindInfoInitializer | null): VkSparseBufferMemoryBindInfo; buffer: VkBuffer | null; bindCount: number; pBinds: VkSparseMemoryBind[] | null; } export interface VkSparseBufferMemoryBindInfo { buffer: VkBuffer | null; bindCount: number; pBinds: VkSparseMemoryBind[] | null; } /** ## VkSparseImageMemoryBind ## */ interface VkSparseImageMemoryBindInitializer { subresource?: VkImageSubresource | null; offset?: VkOffset3D | null; extent?: VkExtent3D | null; memory?: VkDeviceMemory | null; memoryOffset?: number; flags?: VkSparseMemoryBindFlagBits; } declare var VkSparseImageMemoryBind: { prototype: VkSparseImageMemoryBind; new(param?: VkSparseImageMemoryBindInitializer | null): VkSparseImageMemoryBind; subresource: VkImageSubresource | null; offset: VkOffset3D | null; extent: VkExtent3D | null; memory: VkDeviceMemory | null; memoryOffset: number; flags: VkSparseMemoryBindFlagBits; } export interface VkSparseImageMemoryBind { subresource: VkImageSubresource | null; offset: VkOffset3D | null; extent: VkExtent3D | null; memory: VkDeviceMemory | null; memoryOffset: number; flags: VkSparseMemoryBindFlagBits; } /** ## VkSparseMemoryBind ## */ interface VkSparseMemoryBindInitializer { resourceOffset?: number; size?: number; memory?: VkDeviceMemory | null; memoryOffset?: number; flags?: VkSparseMemoryBindFlagBits; } declare var VkSparseMemoryBind: { prototype: VkSparseMemoryBind; new(param?: VkSparseMemoryBindInitializer | null): VkSparseMemoryBind; resourceOffset: number; size: number; memory: VkDeviceMemory | null; memoryOffset: number; flags: VkSparseMemoryBindFlagBits; } export interface VkSparseMemoryBind { resourceOffset: number; size: number; memory: VkDeviceMemory | null; memoryOffset: number; flags: VkSparseMemoryBindFlagBits; } /** ## VkBufferCopy ## */ interface VkBufferCopyInitializer { srcOffset?: number; dstOffset?: number; size?: number; } declare var VkBufferCopy: { prototype: VkBufferCopy; new(param?: VkBufferCopyInitializer | null): VkBufferCopy; srcOffset: number; dstOffset: number; size: number; } export interface VkBufferCopy { srcOffset: number; dstOffset: number; size: number; } /** ## VkImageViewCreateInfo ## */ interface VkImageViewCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkImageViewCreateFlagBits; image?: VkImage | null; viewType?: VkImageViewType; format?: VkFormat; components?: VkComponentMapping | null; subresourceRange?: VkImageSubresourceRange | null; } declare var VkImageViewCreateInfo: { prototype: VkImageViewCreateInfo; new(param?: VkImageViewCreateInfoInitializer | null): VkImageViewCreateInfo; sType: VkStructureType; pNext: null; flags: VkImageViewCreateFlagBits; image: VkImage | null; viewType: VkImageViewType; format: VkFormat; components: VkComponentMapping | null; subresourceRange: VkImageSubresourceRange | null; } export interface VkImageViewCreateInfo { sType: VkStructureType; pNext: null; flags: VkImageViewCreateFlagBits; image: VkImage | null; viewType: VkImageViewType; format: VkFormat; components: VkComponentMapping | null; subresourceRange: VkImageSubresourceRange | null; } /** ## VkSubresourceLayout ## */ interface VkSubresourceLayoutInitializer { readonly offset?: number; readonly size?: number; readonly rowPitch?: number; readonly arrayPitch?: number; readonly depthPitch?: number; } declare var VkSubresourceLayout: { prototype: VkSubresourceLayout; new(param?: VkSubresourceLayoutInitializer | null): VkSubresourceLayout; readonly offset: number; readonly size: number; readonly rowPitch: number; readonly arrayPitch: number; readonly depthPitch: number; } export interface VkSubresourceLayout { readonly offset: number; readonly size: number; readonly rowPitch: number; readonly arrayPitch: number; readonly depthPitch: number; } /** ## VkImageCreateInfo ## */ interface VkImageCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkImageCreateFlagBits; imageType?: VkImageType; format?: VkFormat; extent?: VkExtent3D | null; mipLevels?: number; arrayLayers?: number; samples?: VkSampleCountFlagBits; tiling?: VkImageTiling; usage?: VkImageUsageFlagBits; sharingMode?: VkSharingMode; queueFamilyIndexCount?: number; pQueueFamilyIndices?: Uint32Array | null; initialLayout?: VkImageLayout; } declare var VkImageCreateInfo: { prototype: VkImageCreateInfo; new(param?: VkImageCreateInfoInitializer | null): VkImageCreateInfo; sType: VkStructureType; pNext: null; flags: VkImageCreateFlagBits; imageType: VkImageType; format: VkFormat; extent: VkExtent3D | null; mipLevels: number; arrayLayers: number; samples: VkSampleCountFlagBits; tiling: VkImageTiling; usage: VkImageUsageFlagBits; sharingMode: VkSharingMode; queueFamilyIndexCount: number; pQueueFamilyIndices: Uint32Array | null; initialLayout: VkImageLayout; } export interface VkImageCreateInfo { sType: VkStructureType; pNext: null; flags: VkImageCreateFlagBits; imageType: VkImageType; format: VkFormat; extent: VkExtent3D | null; mipLevels: number; arrayLayers: number; samples: VkSampleCountFlagBits; tiling: VkImageTiling; usage: VkImageUsageFlagBits; sharingMode: VkSharingMode; queueFamilyIndexCount: number; pQueueFamilyIndices: Uint32Array | null; initialLayout: VkImageLayout; } /** ## VkImageMemoryBarrier ## */ interface VkImageMemoryBarrierInitializer { sType?: VkStructureType; pNext?: null; srcAccessMask?: VkAccessFlagBits; dstAccessMask?: VkAccessFlagBits; oldLayout?: VkImageLayout; newLayout?: VkImageLayout; srcQueueFamilyIndex?: number; dstQueueFamilyIndex?: number; image?: VkImage | null; subresourceRange?: VkImageSubresourceRange | null; } declare var VkImageMemoryBarrier: { prototype: VkImageMemoryBarrier; new(param?: VkImageMemoryBarrierInitializer | null): VkImageMemoryBarrier; sType: VkStructureType; pNext: null; srcAccessMask: VkAccessFlagBits; dstAccessMask: VkAccessFlagBits; oldLayout: VkImageLayout; newLayout: VkImageLayout; srcQueueFamilyIndex: number; dstQueueFamilyIndex: number; image: VkImage | null; subresourceRange: VkImageSubresourceRange | null; } export interface VkImageMemoryBarrier { sType: VkStructureType; pNext: null; srcAccessMask: VkAccessFlagBits; dstAccessMask: VkAccessFlagBits; oldLayout: VkImageLayout; newLayout: VkImageLayout; srcQueueFamilyIndex: number; dstQueueFamilyIndex: number; image: VkImage | null; subresourceRange: VkImageSubresourceRange | null; } /** ## VkBufferMemoryBarrier ## */ interface VkBufferMemoryBarrierInitializer { sType?: VkStructureType; pNext?: null; srcAccessMask?: VkAccessFlagBits; dstAccessMask?: VkAccessFlagBits; srcQueueFamilyIndex?: number; dstQueueFamilyIndex?: number; buffer?: VkBuffer | null; offset?: number; size?: number; } declare var VkBufferMemoryBarrier: { prototype: VkBufferMemoryBarrier; new(param?: VkBufferMemoryBarrierInitializer | null): VkBufferMemoryBarrier; sType: VkStructureType; pNext: null; srcAccessMask: VkAccessFlagBits; dstAccessMask: VkAccessFlagBits; srcQueueFamilyIndex: number; dstQueueFamilyIndex: number; buffer: VkBuffer | null; offset: number; size: number; } export interface VkBufferMemoryBarrier { sType: VkStructureType; pNext: null; srcAccessMask: VkAccessFlagBits; dstAccessMask: VkAccessFlagBits; srcQueueFamilyIndex: number; dstQueueFamilyIndex: number; buffer: VkBuffer | null; offset: number; size: number; } /** ## VkMemoryBarrier ## */ interface VkMemoryBarrierInitializer { sType?: VkStructureType; pNext?: null; srcAccessMask?: VkAccessFlagBits; dstAccessMask?: VkAccessFlagBits; } declare var VkMemoryBarrier: { prototype: VkMemoryBarrier; new(param?: VkMemoryBarrierInitializer | null): VkMemoryBarrier; sType: VkStructureType; pNext: null; srcAccessMask: VkAccessFlagBits; dstAccessMask: VkAccessFlagBits; } export interface VkMemoryBarrier { sType: VkStructureType; pNext: null; srcAccessMask: VkAccessFlagBits; dstAccessMask: VkAccessFlagBits; } /** ## VkImageSubresourceRange ## */ interface VkImageSubresourceRangeInitializer { aspectMask?: VkImageAspectFlagBits; baseMipLevel?: number; levelCount?: number; baseArrayLayer?: number; layerCount?: number; } declare var VkImageSubresourceRange: { prototype: VkImageSubresourceRange; new(param?: VkImageSubresourceRangeInitializer | null): VkImageSubresourceRange; aspectMask: VkImageAspectFlagBits; baseMipLevel: number; levelCount: number; baseArrayLayer: number; layerCount: number; } export interface VkImageSubresourceRange { aspectMask: VkImageAspectFlagBits; baseMipLevel: number; levelCount: number; baseArrayLayer: number; layerCount: number; } /** ## VkImageSubresourceLayers ## */ interface VkImageSubresourceLayersInitializer { aspectMask?: VkImageAspectFlagBits; mipLevel?: number; baseArrayLayer?: number; layerCount?: number; } declare var VkImageSubresourceLayers: { prototype: VkImageSubresourceLayers; new(param?: VkImageSubresourceLayersInitializer | null): VkImageSubresourceLayers; aspectMask: VkImageAspectFlagBits; mipLevel: number; baseArrayLayer: number; layerCount: number; } export interface VkImageSubresourceLayers { aspectMask: VkImageAspectFlagBits; mipLevel: number; baseArrayLayer: number; layerCount: number; } /** ## VkImageSubresource ## */ interface VkImageSubresourceInitializer { aspectMask?: VkImageAspectFlagBits; mipLevel?: number; arrayLayer?: number; } declare var VkImageSubresource: { prototype: VkImageSubresource; new(param?: VkImageSubresourceInitializer | null): VkImageSubresource; aspectMask: VkImageAspectFlagBits; mipLevel: number; arrayLayer: number; } export interface VkImageSubresource { aspectMask: VkImageAspectFlagBits; mipLevel: number; arrayLayer: number; } /** ## VkBufferViewCreateInfo ## */ interface VkBufferViewCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; buffer?: VkBuffer | null; format?: VkFormat; offset?: number; range?: number; } declare var VkBufferViewCreateInfo: { prototype: VkBufferViewCreateInfo; new(param?: VkBufferViewCreateInfoInitializer | null): VkBufferViewCreateInfo; sType: VkStructureType; pNext: null; flags: null; buffer: VkBuffer | null; format: VkFormat; offset: number; range: number; } export interface VkBufferViewCreateInfo { sType: VkStructureType; pNext: null; flags: null; buffer: VkBuffer | null; format: VkFormat; offset: number; range: number; } /** ## VkBufferCreateInfo ## */ interface VkBufferCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkBufferCreateFlagBits; size?: number; usage?: VkBufferUsageFlagBits; sharingMode?: VkSharingMode; queueFamilyIndexCount?: number; pQueueFamilyIndices?: Uint32Array | null; } declare var VkBufferCreateInfo: { prototype: VkBufferCreateInfo; new(param?: VkBufferCreateInfoInitializer | null): VkBufferCreateInfo; sType: VkStructureType; pNext: null; flags: VkBufferCreateFlagBits; size: number; usage: VkBufferUsageFlagBits; sharingMode: VkSharingMode; queueFamilyIndexCount: number; pQueueFamilyIndices: Uint32Array | null; } export interface VkBufferCreateInfo { sType: VkStructureType; pNext: null; flags: VkBufferCreateFlagBits; size: number; usage: VkBufferUsageFlagBits; sharingMode: VkSharingMode; queueFamilyIndexCount: number; pQueueFamilyIndices: Uint32Array | null; } /** ## VkCopyDescriptorSet ## */ interface VkCopyDescriptorSetInitializer { sType?: VkStructureType; pNext?: null; srcSet?: VkDescriptorSet | null; srcBinding?: number; srcArrayElement?: number; dstSet?: VkDescriptorSet | null; dstBinding?: number; dstArrayElement?: number; descriptorCount?: number; } declare var VkCopyDescriptorSet: { prototype: VkCopyDescriptorSet; new(param?: VkCopyDescriptorSetInitializer | null): VkCopyDescriptorSet; sType: VkStructureType; pNext: null; srcSet: VkDescriptorSet | null; srcBinding: number; srcArrayElement: number; dstSet: VkDescriptorSet | null; dstBinding: number; dstArrayElement: number; descriptorCount: number; } export interface VkCopyDescriptorSet { sType: VkStructureType; pNext: null; srcSet: VkDescriptorSet | null; srcBinding: number; srcArrayElement: number; dstSet: VkDescriptorSet | null; dstBinding: number; dstArrayElement: number; descriptorCount: number; } /** ## VkWriteDescriptorSet ## */ interface VkWriteDescriptorSetInitializer { sType?: VkStructureType; pNext?: null; dstSet?: VkDescriptorSet | null; dstBinding?: number; dstArrayElement?: number; descriptorCount?: number; descriptorType?: VkDescriptorType; pImageInfo?: VkDescriptorImageInfo[] | null; pBufferInfo?: VkDescriptorBufferInfo[] | null; pTexelBufferView?: VkBufferView[] | null; } declare var VkWriteDescriptorSet: { prototype: VkWriteDescriptorSet; new(param?: VkWriteDescriptorSetInitializer | null): VkWriteDescriptorSet; sType: VkStructureType; pNext: null; dstSet: VkDescriptorSet | null; dstBinding: number; dstArrayElement: number; descriptorCount: number; descriptorType: VkDescriptorType; pImageInfo: VkDescriptorImageInfo[] | null; pBufferInfo: VkDescriptorBufferInfo[] | null; pTexelBufferView: VkBufferView[] | null; } export interface VkWriteDescriptorSet { sType: VkStructureType; pNext: null; dstSet: VkDescriptorSet | null; dstBinding: number; dstArrayElement: number; descriptorCount: number; descriptorType: VkDescriptorType; pImageInfo: VkDescriptorImageInfo[] | null; pBufferInfo: VkDescriptorBufferInfo[] | null; pTexelBufferView: VkBufferView[] | null; } /** ## VkDescriptorImageInfo ## */ interface VkDescriptorImageInfoInitializer { sampler?: VkSampler | null; imageView?: VkImageView | null; imageLayout?: VkImageLayout; } declare var VkDescriptorImageInfo: { prototype: VkDescriptorImageInfo; new(param?: VkDescriptorImageInfoInitializer | null): VkDescriptorImageInfo; sampler: VkSampler | null; imageView: VkImageView | null; imageLayout: VkImageLayout; } export interface VkDescriptorImageInfo { sampler: VkSampler | null; imageView: VkImageView | null; imageLayout: VkImageLayout; } /** ## VkDescriptorBufferInfo ## */ interface VkDescriptorBufferInfoInitializer { buffer?: VkBuffer | null; offset?: number; range?: number; } declare var VkDescriptorBufferInfo: { prototype: VkDescriptorBufferInfo; new(param?: VkDescriptorBufferInfoInitializer | null): VkDescriptorBufferInfo; buffer: VkBuffer | null; offset: number; range: number; } export interface VkDescriptorBufferInfo { buffer: VkBuffer | null; offset: number; range: number; } /** ## VkImageFormatProperties ## */ interface VkImageFormatPropertiesInitializer { readonly maxExtent?: VkExtent3D | null; readonly maxMipLevels?: number; readonly maxArrayLayers?: number; readonly sampleCounts?: VkSampleCountFlagBits; readonly maxResourceSize?: number; } declare var VkImageFormatProperties: { prototype: VkImageFormatProperties; new(param?: VkImageFormatPropertiesInitializer | null): VkImageFormatProperties; readonly maxExtent: VkExtent3D | null; readonly maxMipLevels: number; readonly maxArrayLayers: number; readonly sampleCounts: VkSampleCountFlagBits; readonly maxResourceSize: number; } export interface VkImageFormatProperties { readonly maxExtent: VkExtent3D | null; readonly maxMipLevels: number; readonly maxArrayLayers: number; readonly sampleCounts: VkSampleCountFlagBits; readonly maxResourceSize: number; } /** ## VkFormatProperties ## */ interface VkFormatPropertiesInitializer { readonly linearTilingFeatures?: VkFormatFeatureFlagBits; readonly optimalTilingFeatures?: VkFormatFeatureFlagBits; readonly bufferFeatures?: VkFormatFeatureFlagBits; } declare var VkFormatProperties: { prototype: VkFormatProperties; new(param?: VkFormatPropertiesInitializer | null): VkFormatProperties; readonly linearTilingFeatures: VkFormatFeatureFlagBits; readonly optimalTilingFeatures: VkFormatFeatureFlagBits; readonly bufferFeatures: VkFormatFeatureFlagBits; } export interface VkFormatProperties { readonly linearTilingFeatures: VkFormatFeatureFlagBits; readonly optimalTilingFeatures: VkFormatFeatureFlagBits; readonly bufferFeatures: VkFormatFeatureFlagBits; } /** ## VkMappedMemoryRange ## */ interface VkMappedMemoryRangeInitializer { sType?: VkStructureType; pNext?: null; memory?: VkDeviceMemory | null; offset?: number; size?: number; } declare var VkMappedMemoryRange: { prototype: VkMappedMemoryRange; new(param?: VkMappedMemoryRangeInitializer | null): VkMappedMemoryRange; sType: VkStructureType; pNext: null; memory: VkDeviceMemory | null; offset: number; size: number; } export interface VkMappedMemoryRange { sType: VkStructureType; pNext: null; memory: VkDeviceMemory | null; offset: number; size: number; } /** ## VkMemoryHeap ## */ interface VkMemoryHeapInitializer { readonly size?: number; readonly flags?: VkMemoryHeapFlagBits; } declare var VkMemoryHeap: { prototype: VkMemoryHeap; new(param?: VkMemoryHeapInitializer | null): VkMemoryHeap; readonly size: number; readonly flags: VkMemoryHeapFlagBits; } export interface VkMemoryHeap { readonly size: number; readonly flags: VkMemoryHeapFlagBits; } /** ## VkMemoryType ## */ interface VkMemoryTypeInitializer { readonly propertyFlags?: VkMemoryPropertyFlagBits; readonly heapIndex?: number; } declare var VkMemoryType: { prototype: VkMemoryType; new(param?: VkMemoryTypeInitializer | null): VkMemoryType; readonly propertyFlags: VkMemoryPropertyFlagBits; readonly heapIndex: number; } export interface VkMemoryType { readonly propertyFlags: VkMemoryPropertyFlagBits; readonly heapIndex: number; } /** ## VkSparseImageMemoryRequirements ## */ interface VkSparseImageMemoryRequirementsInitializer { readonly formatProperties?: VkSparseImageFormatProperties | null; readonly imageMipTailFirstLod?: number; readonly imageMipTailSize?: number; readonly imageMipTailOffset?: number; readonly imageMipTailStride?: number; } declare var VkSparseImageMemoryRequirements: { prototype: VkSparseImageMemoryRequirements; new(param?: VkSparseImageMemoryRequirementsInitializer | null): VkSparseImageMemoryRequirements; readonly formatProperties: VkSparseImageFormatProperties | null; readonly imageMipTailFirstLod: number; readonly imageMipTailSize: number; readonly imageMipTailOffset: number; readonly imageMipTailStride: number; } export interface VkSparseImageMemoryRequirements { readonly formatProperties: VkSparseImageFormatProperties | null; readonly imageMipTailFirstLod: number; readonly imageMipTailSize: number; readonly imageMipTailOffset: number; readonly imageMipTailStride: number; } /** ## VkSparseImageFormatProperties ## */ interface VkSparseImageFormatPropertiesInitializer { readonly aspectMask?: VkImageAspectFlagBits; readonly imageGranularity?: VkExtent3D | null; readonly flags?: VkSparseImageFormatFlagBits; } declare var VkSparseImageFormatProperties: { prototype: VkSparseImageFormatProperties; new(param?: VkSparseImageFormatPropertiesInitializer | null): VkSparseImageFormatProperties; readonly aspectMask: VkImageAspectFlagBits; readonly imageGranularity: VkExtent3D | null; readonly flags: VkSparseImageFormatFlagBits; } export interface VkSparseImageFormatProperties { readonly aspectMask: VkImageAspectFlagBits; readonly imageGranularity: VkExtent3D | null; readonly flags: VkSparseImageFormatFlagBits; } /** ## VkMemoryRequirements ## */ interface VkMemoryRequirementsInitializer { readonly size?: number; readonly alignment?: number; readonly memoryTypeBits?: number; } declare var VkMemoryRequirements: { prototype: VkMemoryRequirements; new(param?: VkMemoryRequirementsInitializer | null): VkMemoryRequirements; readonly size: number; readonly alignment: number; readonly memoryTypeBits: number; } export interface VkMemoryRequirements { readonly size: number; readonly alignment: number; readonly memoryTypeBits: number; } /** ## VkMemoryAllocateInfo ## */ interface VkMemoryAllocateInfoInitializer { sType?: VkStructureType; pNext?: null; allocationSize?: number; memoryTypeIndex?: number; } declare var VkMemoryAllocateInfo: { prototype: VkMemoryAllocateInfo; new(param?: VkMemoryAllocateInfoInitializer | null): VkMemoryAllocateInfo; sType: VkStructureType; pNext: null; allocationSize: number; memoryTypeIndex: number; } export interface VkMemoryAllocateInfo { sType: VkStructureType; pNext: null; allocationSize: number; memoryTypeIndex: number; } /** ## VkPhysicalDeviceMemoryProperties ## */ interface VkPhysicalDeviceMemoryPropertiesInitializer { readonly memoryTypeCount?: number; readonly memoryTypes?: number[] | null; readonly memoryHeapCount?: number; readonly memoryHeaps?: number[] | null; } declare var VkPhysicalDeviceMemoryProperties: { prototype: VkPhysicalDeviceMemoryProperties; new(param?: VkPhysicalDeviceMemoryPropertiesInitializer | null): VkPhysicalDeviceMemoryProperties; readonly memoryTypeCount: number; readonly memoryTypes: number[] | null; readonly memoryHeapCount: number; readonly memoryHeaps: number[] | null; } export interface VkPhysicalDeviceMemoryProperties { readonly memoryTypeCount: number; readonly memoryTypes: number[] | null; readonly memoryHeapCount: number; readonly memoryHeaps: number[] | null; } /** ## VkQueueFamilyProperties ## */ interface VkQueueFamilyPropertiesInitializer { readonly queueFlags?: VkQueueFlagBits; readonly queueCount?: number; readonly timestampValidBits?: number; readonly minImageTransferGranularity?: VkExtent3D | null; } declare var VkQueueFamilyProperties: { prototype: VkQueueFamilyProperties; new(param?: VkQueueFamilyPropertiesInitializer | null): VkQueueFamilyProperties; readonly queueFlags: VkQueueFlagBits; readonly queueCount: number; readonly timestampValidBits: number; readonly minImageTransferGranularity: VkExtent3D | null; } export interface VkQueueFamilyProperties { readonly queueFlags: VkQueueFlagBits; readonly queueCount: number; readonly timestampValidBits: number; readonly minImageTransferGranularity: VkExtent3D | null; } /** ## VkInstanceCreateInfo ## */ interface VkInstanceCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; pApplicationInfo?: VkApplicationInfo | null; enabledLayerCount?: number; ppEnabledLayerNames?: string[] | null; enabledExtensionCount?: number; ppEnabledExtensionNames?: string[] | null; } declare var VkInstanceCreateInfo: { prototype: VkInstanceCreateInfo; new(param?: VkInstanceCreateInfoInitializer | null): VkInstanceCreateInfo; sType: VkStructureType; pNext: null; flags: null; pApplicationInfo: VkApplicationInfo | null; enabledLayerCount: number; ppEnabledLayerNames: string[] | null; enabledExtensionCount: number; ppEnabledExtensionNames: string[] | null; } export interface VkInstanceCreateInfo { sType: VkStructureType; pNext: null; flags: null; pApplicationInfo: VkApplicationInfo | null; enabledLayerCount: number; ppEnabledLayerNames: string[] | null; enabledExtensionCount: number; ppEnabledExtensionNames: string[] | null; } /** ## VkDeviceCreateInfo ## */ interface VkDeviceCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: null; queueCreateInfoCount?: number; pQueueCreateInfos?: VkDeviceQueueCreateInfo[] | null; enabledLayerCount?: number; ppEnabledLayerNames?: string[] | null; enabledExtensionCount?: number; ppEnabledExtensionNames?: string[] | null; pEnabledFeatures?: VkPhysicalDeviceFeatures | null; } declare var VkDeviceCreateInfo: { prototype: VkDeviceCreateInfo; new(param?: VkDeviceCreateInfoInitializer | null): VkDeviceCreateInfo; sType: VkStructureType; pNext: null; flags: null; queueCreateInfoCount: number; pQueueCreateInfos: VkDeviceQueueCreateInfo[] | null; enabledLayerCount: number; ppEnabledLayerNames: string[] | null; enabledExtensionCount: number; ppEnabledExtensionNames: string[] | null; pEnabledFeatures: VkPhysicalDeviceFeatures | null; } export interface VkDeviceCreateInfo { sType: VkStructureType; pNext: null; flags: null; queueCreateInfoCount: number; pQueueCreateInfos: VkDeviceQueueCreateInfo[] | null; enabledLayerCount: number; ppEnabledLayerNames: string[] | null; enabledExtensionCount: number; ppEnabledExtensionNames: string[] | null; pEnabledFeatures: VkPhysicalDeviceFeatures | null; } /** ## VkDeviceQueueCreateInfo ## */ interface VkDeviceQueueCreateInfoInitializer { sType?: VkStructureType; pNext?: null; flags?: VkDeviceQueueCreateFlagBits; queueFamilyIndex?: number; queueCount?: number; pQueuePriorities?: Float32Array | null; } declare var VkDeviceQueueCreateInfo: { prototype: VkDeviceQueueCreateInfo; new(param?: VkDeviceQueueCreateInfoInitializer | null): VkDeviceQueueCreateInfo; sType: VkStructureType; pNext: null; flags: VkDeviceQueueCreateFlagBits; queueFamilyIndex: number; queueCount: number; pQueuePriorities: Float32Array | null; } export interface VkDeviceQueueCreateInfo { sType: VkStructureType; pNext: null; flags: VkDeviceQueueCreateFlagBits; queueFamilyIndex: number; queueCount: number; pQueuePriorities: Float32Array | null; } /** ## VkAllocationCallbacks ## */ interface VkAllocationCallbacksInitializer { pUserData?: ArrayBuffer | null; pfnAllocation?: null; pfnReallocation?: null; pfnFree?: null; pfnInternalAllocation?: null; pfnInternalFree?: null; } declare var VkAllocationCallbacks: { prototype: VkAllocationCallbacks; new(param?: VkAllocationCallbacksInitializer | null): VkAllocationCallbacks; pUserData: ArrayBuffer | null; pfnAllocation: null; pfnReallocation: null; pfnFree: null; pfnInternalAllocation: null; pfnInternalFree: null; } export interface VkAllocationCallbacks { pUserData: ArrayBuffer | null; pfnAllocation: null; pfnReallocation: null; pfnFree: null; pfnInternalAllocation: null; pfnInternalFree: null; } /** ## VkApplicationInfo ## */ interface VkApplicationInfoInitializer { sType?: VkStructureType; pNext?: null; pApplicationName?: string | null; applicationVersion?: number; pEngineName?: string | null; engineVersion?: number; apiVersion?: number; } declare var VkApplicationInfo: { prototype: VkApplicationInfo; new(param?: VkApplicationInfoInitializer | null): VkApplicationInfo; sType: VkStructureType; pNext: null; pApplicationName: string | null; applicationVersion: number; pEngineName: string | null; engineVersion: number; apiVersion: number; } export interface VkApplicationInfo { sType: VkStructureType; pNext: null; pApplicationName: string | null; applicationVersion: number; pEngineName: string | null; engineVersion: number; apiVersion: number; } /** ## VkLayerProperties ## */ interface VkLayerPropertiesInitializer { readonly layerName?: string | null; readonly specVersion?: number; readonly implementationVersion?: number; readonly description?: string | null; } declare var VkLayerProperties: { prototype: VkLayerProperties; new(param?: VkLayerPropertiesInitializer | null): VkLayerProperties; readonly layerName: string | null; readonly specVersion: number; readonly implementationVersion: number; readonly description: string | null; } export interface VkLayerProperties { readonly layerName: string | null; readonly specVersion: number; readonly implementationVersion: number; readonly description: string | null; } /** ## VkExtensionProperties ## */ interface VkExtensionPropertiesInitializer { readonly extensionName?: string | null; readonly specVersion?: number; } declare var VkExtensionProperties: { prototype: VkExtensionProperties; new(param?: VkExtensionPropertiesInitializer | null): VkExtensionProperties; readonly extensionName: string | null; readonly specVersion: number; } export interface VkExtensionProperties { readonly extensionName: string | null; readonly specVersion: number; } /** ## VkPhysicalDeviceProperties ## */ interface VkPhysicalDevicePropertiesInitializer { readonly apiVersion?: number; readonly driverVersion?: number; readonly vendorID?: number; readonly deviceID?: number; readonly deviceType?: VkPhysicalDeviceType; readonly deviceName?: string | null; readonly pipelineCacheUUID?: number[] | null; readonly limits?: VkPhysicalDeviceLimits | null; readonly sparseProperties?: VkPhysicalDeviceSparseProperties | null; } declare var VkPhysicalDeviceProperties: { prototype: VkPhysicalDeviceProperties; new(param?: VkPhysicalDevicePropertiesInitializer | null): VkPhysicalDeviceProperties; readonly apiVersion: number; readonly driverVersion: number; readonly vendorID: number; readonly deviceID: number; readonly deviceType: VkPhysicalDeviceType; readonly deviceName: string | null; readonly pipelineCacheUUID: number[] | null; readonly limits: VkPhysicalDeviceLimits | null; readonly sparseProperties: VkPhysicalDeviceSparseProperties | null; } export interface VkPhysicalDeviceProperties { readonly apiVersion: number; readonly driverVersion: number; readonly vendorID: number; readonly deviceID: number; readonly deviceType: VkPhysicalDeviceType; readonly deviceName: string | null; readonly pipelineCacheUUID: number[] | null; readonly limits: VkPhysicalDeviceLimits | null; readonly sparseProperties: VkPhysicalDeviceSparseProperties | null; } /** ## VkComponentMapping ## */ interface VkComponentMappingInitializer { r?: VkComponentSwizzle; g?: VkComponentSwizzle; b?: VkComponentSwizzle; a?: VkComponentSwizzle; } declare var VkComponentMapping: { prototype: VkComponentMapping; new(param?: VkComponentMappingInitializer | null): VkComponentMapping; r: VkComponentSwizzle; g: VkComponentSwizzle; b: VkComponentSwizzle; a: VkComponentSwizzle; } export interface VkComponentMapping { r: VkComponentSwizzle; g: VkComponentSwizzle; b: VkComponentSwizzle; a: VkComponentSwizzle; } /** ## VkClearRect ## */ interface VkClearRectInitializer { rect?: VkRect2D | null; baseArrayLayer?: number; layerCount?: number; } declare var VkClearRect: { prototype: VkClearRect; new(param?: VkClearRectInitializer | null): VkClearRect; rect: VkRect2D | null; baseArrayLayer: number; layerCount: number; } export interface VkClearRect { rect: VkRect2D | null; baseArrayLayer: number; layerCount: number; } /** ## VkRect2D ## */ interface VkRect2DInitializer { offset?: VkOffset2D | null; extent?: VkExtent2D | null; } declare var VkRect2D: { prototype: VkRect2D; new(param?: VkRect2DInitializer | null): VkRect2D; offset: VkOffset2D | null; extent: VkExtent2D | null; } export interface VkRect2D { offset: VkOffset2D | null; extent: VkExtent2D | null; } /** ## VkViewport ## */ interface VkViewportInitializer { x?: number; y?: number; width?: number; height?: number; minDepth?: number; maxDepth?: number; } declare var VkViewport: { prototype: VkViewport; new(param?: VkViewportInitializer | null): VkViewport; x: number; y: number; width: number; height: number; minDepth: number; maxDepth: number; } export interface VkViewport { x: number; y: number; width: number; height: number; minDepth: number; maxDepth: number; } /** ## VkExtent3D ## */ interface VkExtent3DInitializer { width?: number; height?: number; depth?: number; } declare var VkExtent3D: { prototype: VkExtent3D; new(param?: VkExtent3DInitializer | null): VkExtent3D; width: number; height: number; depth: number; } export interface VkExtent3D { width: number; height: number; depth: number; } /** ## VkExtent2D ## */ interface VkExtent2DInitializer { width?: number; height?: number; } declare var VkExtent2D: { prototype: VkExtent2D; new(param?: VkExtent2DInitializer | null): VkExtent2D; width: number; height: number; } export interface VkExtent2D { width: number; height: number; } /** ## VkOffset3D ## */ interface VkOffset3DInitializer { x?: number; y?: number; z?: number; } declare var VkOffset3D: { prototype: VkOffset3D; new(param?: VkOffset3DInitializer | null): VkOffset3D; x: number; y: number; z: number; } export interface VkOffset3D { x: number; y: number; z: number; } /** ## VkOffset2D ## */ interface VkOffset2DInitializer { x?: number; y?: number; } declare var VkOffset2D: { prototype: VkOffset2D; new(param?: VkOffset2DInitializer | null): VkOffset2D; x: number; y: number; } export interface VkOffset2D { x: number; y: number; } /** ## VkBaseInStructure ## */ interface VkBaseInStructureInitializer { sType?: VkStructureType; pNext?: VkBaseInStructure | null; } declare var VkBaseInStructure: { prototype: VkBaseInStructure; new(param?: VkBaseInStructureInitializer | null): VkBaseInStructure; sType: VkStructureType; pNext: VkBaseInStructure | null; } export interface VkBaseInStructure { sType: VkStructureType; pNext: VkBaseInStructure | null; } /** ## VkBaseOutStructure ## */ interface VkBaseOutStructureInitializer { sType?: VkStructureType; pNext?: VkBaseOutStructure | null; } declare var VkBaseOutStructure: { prototype: VkBaseOutStructure; new(param?: VkBaseOutStructureInitializer | null): VkBaseOutStructure; sType: VkStructureType; pNext: VkBaseOutStructure | null; } export interface VkBaseOutStructure { sType: VkStructureType; pNext: VkBaseOutStructure | null; } /** #### CALLS #### **/ declare function vkCreateInstance(pCreateInfo: VkInstanceCreateInfo | null, pAllocator: null, pInstance: VkInstance | null): number; declare function vkDestroyInstance(instance: VkInstance | null, pAllocator: null): void; declare function vkEnumeratePhysicalDevices(instance: VkInstance | null, pPhysicalDeviceCount: VkInout, pPhysicalDevices: VkPhysicalDevice[] | null): number; declare function vkGetPhysicalDeviceProperties(physicalDevice: VkPhysicalDevice | null, pProperties: VkPhysicalDeviceProperties | null): void; declare function vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice: VkPhysicalDevice | null, pQueueFamilyPropertyCount: VkInout, pQueueFamilyProperties: VkQueueFamilyProperties[] | null): void; declare function vkGetPhysicalDeviceMemoryProperties(physicalDevice: VkPhysicalDevice | null, pMemoryProperties: VkPhysicalDeviceMemoryProperties | null): void; declare function vkGetPhysicalDeviceFeatures(physicalDevice: VkPhysicalDevice | null, pFeatures: VkPhysicalDeviceFeatures | null): void; declare function vkGetPhysicalDeviceFormatProperties(physicalDevice: VkPhysicalDevice | null, format: VkFormat, pFormatProperties: VkFormatProperties | null): void; declare function vkGetPhysicalDeviceImageFormatProperties(physicalDevice: VkPhysicalDevice | null, format: VkFormat, type: VkImageType, tiling: VkImageTiling, usage: VkImageUsageFlagBits, flags: VkImageCreateFlagBits, pImageFormatProperties: VkImageFormatProperties | null): number; declare function vkCreateDevice(physicalDevice: VkPhysicalDevice | null, pCreateInfo: VkDeviceCreateInfo | null, pAllocator: null, pDevice: VkDevice | null): number; declare function vkDestroyDevice(device: VkDevice | null, pAllocator: null): void; declare function vkEnumerateInstanceVersion(pApiVersion: VkInout): number; declare function vkEnumerateInstanceLayerProperties(pPropertyCount: VkInout, pProperties: VkLayerProperties[] | null): number; declare function vkEnumerateInstanceExtensionProperties(pLayerName: string | null, pPropertyCount: VkInout, pProperties: VkExtensionProperties[] | null): number; declare function vkEnumerateDeviceLayerProperties(physicalDevice: VkPhysicalDevice | null, pPropertyCount: VkInout, pProperties: VkLayerProperties[] | null): number; declare function vkEnumerateDeviceExtensionProperties(physicalDevice: VkPhysicalDevice | null, pLayerName: string | null, pPropertyCount: VkInout, pProperties: VkExtensionProperties[] | null): number; declare function vkGetDeviceQueue(device: VkDevice | null, queueFamilyIndex: number, queueIndex: number, pQueue: VkQueue | null): void; declare function vkQueueSubmit(queue: VkQueue | null, submitCount: number, pSubmits: VkSubmitInfo[] | null, fence: VkFence | null): number; declare function vkQueueWaitIdle(queue: VkQueue | null): number; declare function vkDeviceWaitIdle(device: VkDevice | null): number; declare function vkAllocateMemory(device: VkDevice | null, pAllocateInfo: VkMemoryAllocateInfo | null, pAllocator: null, pMemory: VkDeviceMemory | null): number; declare function vkFreeMemory(device: VkDevice | null, memory: VkDeviceMemory | null, pAllocator: null): void; declare function vkMapMemory(device: VkDevice | null, memory: VkDeviceMemory | null, offset: number, size: number, flags: null, ppData: VkInoutAddress): number; declare function vkUnmapMemory(device: VkDevice | null, memory: VkDeviceMemory | null): void; declare function vkFlushMappedMemoryRanges(device: VkDevice | null, memoryRangeCount: number, pMemoryRanges: VkMappedMemoryRange[] | null): number; declare function vkInvalidateMappedMemoryRanges(device: VkDevice | null, memoryRangeCount: number, pMemoryRanges: VkMappedMemoryRange[] | null): number; declare function vkGetDeviceMemoryCommitment(device: VkDevice | null, memory: VkDeviceMemory | null, pCommittedMemoryInBytes: VkInout): void; declare function vkGetBufferMemoryRequirements(device: VkDevice | null, buffer: VkBuffer | null, pMemoryRequirements: VkMemoryRequirements | null): void; declare function vkBindBufferMemory(device: VkDevice | null, buffer: VkBuffer | null, memory: VkDeviceMemory | null, memoryOffset: number): number; declare function vkGetImageMemoryRequirements(device: VkDevice | null, image: VkImage | null, pMemoryRequirements: VkMemoryRequirements | null): void; declare function vkBindImageMemory(device: VkDevice | null, image: VkImage | null, memory: VkDeviceMemory | null, memoryOffset: number): number; declare function vkGetImageSparseMemoryRequirements(device: VkDevice | null, image: VkImage | null, pSparseMemoryRequirementCount: VkInout, pSparseMemoryRequirements: VkSparseImageMemoryRequirements[] | null): void; declare function vkGetPhysicalDeviceSparseImageFormatProperties(physicalDevice: VkPhysicalDevice | null, format: VkFormat, type: VkImageType, samples: number, usage: VkImageUsageFlagBits, tiling: VkImageTiling, pPropertyCount: VkInout, pProperties: VkSparseImageFormatProperties[] | null): void; declare function vkQueueBindSparse(queue: VkQueue | null, bindInfoCount: number, pBindInfo: VkBindSparseInfo[] | null, fence: VkFence | null): number; declare function vkCreateFence(device: VkDevice | null, pCreateInfo: VkFenceCreateInfo | null, pAllocator: null, pFence: VkFence | null): number; declare function vkDestroyFence(device: VkDevice | null, fence: VkFence | null, pAllocator: null): void; declare function vkResetFences(device: VkDevice | null, fenceCount: number, pFences: VkFence[] | null): number; declare function vkGetFenceStatus(device: VkDevice | null, fence: VkFence | null): number; declare function vkWaitForFences(device: VkDevice | null, fenceCount: number, pFences: VkFence[] | null, waitAll: number, timeout: number): number; declare function vkCreateSemaphore(device: VkDevice | null, pCreateInfo: VkSemaphoreCreateInfo | null, pAllocator: null, pSemaphore: VkSemaphore | null): number; declare function vkDestroySemaphore(device: VkDevice | null, semaphore: VkSemaphore | null, pAllocator: null): void; declare function vkCreateEvent(device: VkDevice | null, pCreateInfo: VkEventCreateInfo | null, pAllocator: null, pEvent: VkEvent | null): number; declare function vkDestroyEvent(device: VkDevice | null, event: VkEvent | null, pAllocator: null): void; declare function vkGetEventStatus(device: VkDevice | null, event: VkEvent | null): number; declare function vkSetEvent(device: VkDevice | null, event: VkEvent | null): number; declare function vkResetEvent(device: VkDevice | null, event: VkEvent | null): number; declare function vkCreateQueryPool(device: VkDevice | null, pCreateInfo: VkQueryPoolCreateInfo | null, pAllocator: null, pQueryPool: VkQueryPool | null): number; declare function vkDestroyQueryPool(device: VkDevice | null, queryPool: VkQueryPool | null, pAllocator: null): void; declare function vkGetQueryPoolResults(device: VkDevice | null, queryPool: VkQueryPool | null, firstQuery: number, queryCount: number, dataSize: number, pData: ArrayBuffer | null, stride: number, flags: VkQueryResultFlagBits): number; declare function vkCreateBuffer(device: VkDevice | null, pCreateInfo: VkBufferCreateInfo | null, pAllocator: null, pBuffer: VkBuffer | null): number; declare function vkDestroyBuffer(device: VkDevice | null, buffer: VkBuffer | null, pAllocator: null): void; declare function vkCreateBufferView(device: VkDevice | null, pCreateInfo: VkBufferViewCreateInfo | null, pAllocator: null, pView: VkBufferView | null): number; declare function vkDestroyBufferView(device: VkDevice | null, bufferView: VkBufferView | null, pAllocator: null): void; declare function vkCreateImage(device: VkDevice | null, pCreateInfo: VkImageCreateInfo | null, pAllocator: null, pImage: VkImage | null): number; declare function vkDestroyImage(device: VkDevice | null, image: VkImage | null, pAllocator: null): void; declare function vkGetImageSubresourceLayout(device: VkDevice | null, image: VkImage | null, pSubresource: VkImageSubresource | null, pLayout: VkSubresourceLayout | null): void; declare function vkCreateImageView(device: VkDevice | null, pCreateInfo: VkImageViewCreateInfo | null, pAllocator: null, pView: VkImageView | null): number; declare function vkDestroyImageView(device: VkDevice | null, imageView: VkImageView | null, pAllocator: null): void; declare function vkCreateShaderModule(device: VkDevice | null, pCreateInfo: VkShaderModuleCreateInfo | null, pAllocator: null, pShaderModule: VkShaderModule | null): number; declare function vkDestroyShaderModule(device: VkDevice | null, shaderModule: VkShaderModule | null, pAllocator: null): void; declare function vkCreatePipelineCache(device: VkDevice | null, pCreateInfo: VkPipelineCacheCreateInfo | null, pAllocator: null, pPipelineCache: VkPipelineCache | null): number; declare function vkDestroyPipelineCache(device: VkDevice | null, pipelineCache: VkPipelineCache | null, pAllocator: null): void; declare function vkGetPipelineCacheData(device: VkDevice | null, pipelineCache: VkPipelineCache | null, pDataSize: VkInout, pData: ArrayBuffer | null): number; declare function vkMergePipelineCaches(device: VkDevice | null, dstCache: VkPipelineCache | null, srcCacheCount: number, pSrcCaches: VkPipelineCache[] | null): number; declare function vkCreateGraphicsPipelines(device: VkDevice | null, pipelineCache: VkPipelineCache | null, createInfoCount: number, pCreateInfos: VkGraphicsPipelineCreateInfo[] | null, pAllocator: null, pPipelines: VkPipeline[] | null): number; declare function vkCreateComputePipelines(device: VkDevice | null, pipelineCache: VkPipelineCache | null, createInfoCount: number, pCreateInfos: VkComputePipelineCreateInfo[] | null, pAllocator: null, pPipelines: VkPipeline[] | null): number; declare function vkDestroyPipeline(device: VkDevice | null, pipeline: VkPipeline | null, pAllocator: null): void; declare function vkCreatePipelineLayout(device: VkDevice | null, pCreateInfo: VkPipelineLayoutCreateInfo | null, pAllocator: null, pPipelineLayout: VkPipelineLayout | null): number; declare function vkDestroyPipelineLayout(device: VkDevice | null, pipelineLayout: VkPipelineLayout | null, pAllocator: null): void; declare function vkCreateSampler(device: VkDevice | null, pCreateInfo: VkSamplerCreateInfo | null, pAllocator: null, pSampler: VkSampler | null): number; declare function vkDestroySampler(device: VkDevice | null, sampler: VkSampler | null, pAllocator: null): void; declare function vkCreateDescriptorSetLayout(device: VkDevice | null, pCreateInfo: VkDescriptorSetLayoutCreateInfo | null, pAllocator: null, pSetLayout: VkDescriptorSetLayout | null): number; declare function vkDestroyDescriptorSetLayout(device: VkDevice | null, descriptorSetLayout: VkDescriptorSetLayout | null, pAllocator: null): void; declare function vkCreateDescriptorPool(device: VkDevice | null, pCreateInfo: VkDescriptorPoolCreateInfo | null, pAllocator: null, pDescriptorPool: VkDescriptorPool | null): number; declare function vkDestroyDescriptorPool(device: VkDevice | null, descriptorPool: VkDescriptorPool | null, pAllocator: null): void; declare function vkResetDescriptorPool(device: VkDevice | null, descriptorPool: VkDescriptorPool | null, flags: null): number; declare function vkAllocateDescriptorSets(device: VkDevice | null, pAllocateInfo: VkDescriptorSetAllocateInfo | null, pDescriptorSets: VkDescriptorSet[] | null): number; declare function vkFreeDescriptorSets(device: VkDevice | null, descriptorPool: VkDescriptorPool | null, descriptorSetCount: number, pDescriptorSets: VkDescriptorSet[] | null): number; declare function vkUpdateDescriptorSets(device: VkDevice | null, descriptorWriteCount: number, pDescriptorWrites: VkWriteDescriptorSet[] | null, descriptorCopyCount: number, pDescriptorCopies: VkCopyDescriptorSet[] | null): void; declare function vkCreateFramebuffer(device: VkDevice | null, pCreateInfo: VkFramebufferCreateInfo | null, pAllocator: null, pFramebuffer: VkFramebuffer | null): number; declare function vkDestroyFramebuffer(device: VkDevice | null, framebuffer: VkFramebuffer | null, pAllocator: null): void; declare function vkCreateRenderPass(device: VkDevice | null, pCreateInfo: VkRenderPassCreateInfo | null, pAllocator: null, pRenderPass: VkRenderPass | null): number; declare function vkDestroyRenderPass(device: VkDevice | null, renderPass: VkRenderPass | null, pAllocator: null): void; declare function vkGetRenderAreaGranularity(device: VkDevice | null, renderPass: VkRenderPass | null, pGranularity: VkExtent2D | null): void; declare function vkCreateCommandPool(device: VkDevice | null, pCreateInfo: VkCommandPoolCreateInfo | null, pAllocator: null, pCommandPool: VkCommandPool | null): number; declare function vkDestroyCommandPool(device: VkDevice | null, commandPool: VkCommandPool | null, pAllocator: null): void; declare function vkResetCommandPool(device: VkDevice | null, commandPool: VkCommandPool | null, flags: VkCommandPoolResetFlagBits): number; declare function vkAllocateCommandBuffers(device: VkDevice | null, pAllocateInfo: VkCommandBufferAllocateInfo | null, pCommandBuffers: VkCommandBuffer[] | null): number; declare function vkFreeCommandBuffers(device: VkDevice | null, commandPool: VkCommandPool | null, commandBufferCount: number, pCommandBuffers: VkCommandBuffer[] | null): void; declare function vkBeginCommandBuffer(commandBuffer: VkCommandBuffer | null, pBeginInfo: VkCommandBufferBeginInfo | null): number; declare function vkEndCommandBuffer(commandBuffer: VkCommandBuffer | null): number; declare function vkResetCommandBuffer(commandBuffer: VkCommandBuffer | null, flags: VkCommandBufferResetFlagBits): number; declare function vkCmdBindPipeline(commandBuffer: VkCommandBuffer | null, pipelineBindPoint: VkPipelineBindPoint, pipeline: VkPipeline | null): void; declare function vkCmdSetViewport(commandBuffer: VkCommandBuffer | null, firstViewport: number, viewportCount: number, pViewports: VkViewport[] | null): void; declare function vkCmdSetScissor(commandBuffer: VkCommandBuffer | null, firstScissor: number, scissorCount: number, pScissors: VkRect2D[] | null): void; declare function vkCmdSetLineWidth(commandBuffer: VkCommandBuffer | null, lineWidth: number): void; declare function vkCmdSetDepthBias(commandBuffer: VkCommandBuffer | null, depthBiasConstantFactor: number, depthBiasClamp: number, depthBiasSlopeFactor: number): void; declare function vkCmdSetBlendConstants(commandBuffer: VkCommandBuffer | null, blendConstants: number[] | null): void; declare function vkCmdSetDepthBounds(commandBuffer: VkCommandBuffer | null, minDepthBounds: number, maxDepthBounds: number): void; declare function vkCmdSetStencilCompareMask(commandBuffer: VkCommandBuffer | null, faceMask: VkStencilFaceFlagBits, compareMask: number): void; declare function vkCmdSetStencilWriteMask(commandBuffer: VkCommandBuffer | null, faceMask: VkStencilFaceFlagBits, writeMask: number): void; declare function vkCmdSetStencilReference(commandBuffer: VkCommandBuffer | null, faceMask: VkStencilFaceFlagBits, reference: number): void; declare function vkCmdBindDescriptorSets(commandBuffer: VkCommandBuffer | null, pipelineBindPoint: VkPipelineBindPoint, layout: VkPipelineLayout | null, firstSet: number, descriptorSetCount: number, pDescriptorSets: VkDescriptorSet[] | null, dynamicOffsetCount: number, pDynamicOffsets: VkInout): void; declare function vkCmdBindIndexBuffer(commandBuffer: VkCommandBuffer | null, buffer: VkBuffer | null, offset: number, indexType: VkIndexType): void; declare function vkCmdBindVertexBuffers(commandBuffer: VkCommandBuffer | null, firstBinding: number, bindingCount: number, pBuffers: VkBuffer[] | null, pOffsets: VkInout): void; declare function vkCmdDraw(commandBuffer: VkCommandBuffer | null, vertexCount: number, instanceCount: number, firstVertex: number, firstInstance: number): void; declare function vkCmdDrawIndexed(commandBuffer: VkCommandBuffer | null, indexCount: number, instanceCount: number, firstIndex: number, vertexOffset: number, firstInstance: number): void; declare function vkCmdDrawIndirect(commandBuffer: VkCommandBuffer | null, buffer: VkBuffer | null, offset: number, drawCount: number, stride: number): void; declare function vkCmdDrawIndexedIndirect(commandBuffer: VkCommandBuffer | null, buffer: VkBuffer | null, offset: number, drawCount: number, stride: number): void; declare function vkCmdDispatch(commandBuffer: VkCommandBuffer | null, groupCountX: number, groupCountY: number, groupCountZ: number): void; declare function vkCmdDispatchIndirect(commandBuffer: VkCommandBuffer | null, buffer: VkBuffer | null, offset: number): void; declare function vkCmdCopyBuffer(commandBuffer: VkCommandBuffer | null, srcBuffer: VkBuffer | null, dstBuffer: VkBuffer | null, regionCount: number, pRegions: VkBufferCopy[] | null): void; declare function vkCmdCopyImage(commandBuffer: VkCommandBuffer | null, srcImage: VkImage | null, srcImageLayout: VkImageLayout, dstImage: VkImage | null, dstImageLayout: VkImageLayout, regionCount: number, pRegions: VkImageCopy[] | null): void; declare function vkCmdBlitImage(commandBuffer: VkCommandBuffer | null, srcImage: VkImage | null, srcImageLayout: VkImageLayout, dstImage: VkImage | null, dstImageLayout: VkImageLayout, regionCount: number, pRegions: VkImageBlit[] | null, filter: VkFilter): void; declare function vkCmdCopyBufferToImage(commandBuffer: VkCommandBuffer | null, srcBuffer: VkBuffer | null, dstImage: VkImage | null, dstImageLayout: VkImageLayout, regionCount: number, pRegions: VkBufferImageCopy[] | null): void; declare function vkCmdCopyImageToBuffer(commandBuffer: VkCommandBuffer | null, srcImage: VkImage | null, srcImageLayout: VkImageLayout, dstBuffer: VkBuffer | null, regionCount: number, pRegions: VkBufferImageCopy[] | null): void; declare function vkCmdUpdateBuffer(commandBuffer: VkCommandBuffer | null, dstBuffer: VkBuffer | null, dstOffset: number, dataSize: number, pData: ArrayBuffer | null): void; declare function vkCmdFillBuffer(commandBuffer: VkCommandBuffer | null, dstBuffer: VkBuffer | null, dstOffset: number, size: number, data: number): void; declare function vkCmdClearColorImage(commandBuffer: VkCommandBuffer | null, image: VkImage | null, imageLayout: VkImageLayout, pColor: VkClearColorValue | null, rangeCount: number, pRanges: VkImageSubresourceRange[] | null): void; declare function vkCmdClearDepthStencilImage(commandBuffer: VkCommandBuffer | null, image: VkImage | null, imageLayout: VkImageLayout, pDepthStencil: VkClearDepthStencilValue | null, rangeCount: number, pRanges: VkImageSubresourceRange[] | null): void; declare function vkCmdClearAttachments(commandBuffer: VkCommandBuffer | null, attachmentCount: number, pAttachments: VkClearAttachment[] | null, rectCount: number, pRects: VkClearRect[] | null): void; declare function vkCmdResolveImage(commandBuffer: VkCommandBuffer | null, srcImage: VkImage | null, srcImageLayout: VkImageLayout, dstImage: VkImage | null, dstImageLayout: VkImageLayout, regionCount: number, pRegions: VkImageResolve[] | null): void; declare function vkCmdSetEvent(commandBuffer: VkCommandBuffer | null, event: VkEvent | null, stageMask: VkPipelineStageFlagBits): void; declare function vkCmdResetEvent(commandBuffer: VkCommandBuffer | null, event: VkEvent | null, stageMask: VkPipelineStageFlagBits): void; declare function vkCmdWaitEvents(commandBuffer: VkCommandBuffer | null, eventCount: number, pEvents: VkEvent[] | null, srcStageMask: VkPipelineStageFlagBits, dstStageMask: VkPipelineStageFlagBits, memoryBarrierCount: number, pMemoryBarriers: VkMemoryBarrier[] | null, bufferMemoryBarrierCount: number, pBufferMemoryBarriers: VkBufferMemoryBarrier[] | null, imageMemoryBarrierCount: number, pImageMemoryBarriers: VkImageMemoryBarrier[] | null): void; declare function vkCmdPipelineBarrier(commandBuffer: VkCommandBuffer | null, srcStageMask: VkPipelineStageFlagBits, dstStageMask: VkPipelineStageFlagBits, dependencyFlags: VkDependencyFlagBits, memoryBarrierCount: number, pMemoryBarriers: VkMemoryBarrier[] | null, bufferMemoryBarrierCount: number, pBufferMemoryBarriers: VkBufferMemoryBarrier[] | null, imageMemoryBarrierCount: number, pImageMemoryBarriers: VkImageMemoryBarrier[] | null): void; declare function vkCmdBeginQuery(commandBuffer: VkCommandBuffer | null, queryPool: VkQueryPool | null, query: number, flags: VkQueryControlFlagBits): void; declare function vkCmdEndQuery(commandBuffer: VkCommandBuffer | null, queryPool: VkQueryPool | null, query: number): void; declare function vkCmdBeginConditionalRenderingEXT(commandBuffer: VkCommandBuffer | null, pConditionalRenderingBegin: VkConditionalRenderingBeginInfoEXT | null): void; declare function vkCmdEndConditionalRenderingEXT(commandBuffer: VkCommandBuffer | null): void; declare function vkCmdResetQueryPool(commandBuffer: VkCommandBuffer | null, queryPool: VkQueryPool | null, firstQuery: number, queryCount: number): void; declare function vkCmdWriteTimestamp(commandBuffer: VkCommandBuffer | null, pipelineStage: number, queryPool: VkQueryPool | null, query: number): void; declare function vkCmdCopyQueryPoolResults(commandBuffer: VkCommandBuffer | null, queryPool: VkQueryPool | null, firstQuery: number, queryCount: number, dstBuffer: VkBuffer | null, dstOffset: number, stride: number, flags: VkQueryResultFlagBits): void; declare function vkCmdPushConstants(commandBuffer: VkCommandBuffer | null, layout: VkPipelineLayout | null, stageFlags: VkShaderStageFlagBits, offset: number, size: number, pValues: ArrayBuffer | null): void; declare function vkCmdBeginRenderPass(commandBuffer: VkCommandBuffer | null, pRenderPassBegin: VkRenderPassBeginInfo | null, contents: VkSubpassContents): void; declare function vkCmdNextSubpass(commandBuffer: VkCommandBuffer | null, contents: VkSubpassContents): void; declare function vkCmdEndRenderPass(commandBuffer: VkCommandBuffer | null): void; declare function vkCmdExecuteCommands(commandBuffer: VkCommandBuffer | null, commandBufferCount: number, pCommandBuffers: VkCommandBuffer[] | null): void; declare function vkGetPhysicalDeviceDisplayPropertiesKHR(physicalDevice: VkPhysicalDevice | null, pPropertyCount: VkInout, pProperties: VkDisplayPropertiesKHR[] | null): number; declare function vkGetPhysicalDeviceDisplayPlanePropertiesKHR(physicalDevice: VkPhysicalDevice | null, pPropertyCount: VkInout, pProperties: VkDisplayPlanePropertiesKHR[] | null): number; declare function vkGetDisplayPlaneSupportedDisplaysKHR(physicalDevice: VkPhysicalDevice | null, planeIndex: number, pDisplayCount: VkInout, pDisplays: VkDisplayKHR[] | null): number; declare function vkGetDisplayModePropertiesKHR(physicalDevice: VkPhysicalDevice | null, display: VkDisplayKHR | null, pPropertyCount: VkInout, pProperties: VkDisplayModePropertiesKHR[] | null): number; declare function vkCreateDisplayModeKHR(physicalDevice: VkPhysicalDevice | null, display: VkDisplayKHR | null, pCreateInfo: VkDisplayModeCreateInfoKHR | null, pAllocator: null, pMode: VkDisplayModeKHR | null): number; declare function vkGetDisplayPlaneCapabilitiesKHR(physicalDevice: VkPhysicalDevice | null, mode: VkDisplayModeKHR | null, planeIndex: number, pCapabilities: VkDisplayPlaneCapabilitiesKHR | null): number; declare function vkCreateDisplayPlaneSurfaceKHR(instance: VkInstance | null, pCreateInfo: VkDisplaySurfaceCreateInfoKHR | null, pAllocator: null, pSurface: VkSurfaceKHR | null): number; declare function vkCreateSharedSwapchainsKHR(device: VkDevice | null, swapchainCount: number, pCreateInfos: VkSwapchainCreateInfoKHR[] | null, pAllocator: null, pSwapchains: VkSwapchainKHR[] | null): number; declare function vkDestroySurfaceKHR(instance: VkInstance | null, surface: VkSurfaceKHR | null, pAllocator: null): void; declare function vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice: VkPhysicalDevice | null, queueFamilyIndex: number, surface: VkSurfaceKHR | null, pSupported: VkInout): number; declare function vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice: VkPhysicalDevice | null, surface: VkSurfaceKHR | null, pSurfaceCapabilities: VkSurfaceCapabilitiesKHR | null): number; declare function vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice: VkPhysicalDevice | null, surface: VkSurfaceKHR | null, pSurfaceFormatCount: VkInout, pSurfaceFormats: VkSurfaceFormatKHR[] | null): number; declare function vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice: VkPhysicalDevice | null, surface: VkSurfaceKHR | null, pPresentModeCount: VkInout, pPresentModes: VkInout): number; declare function vkCreateSwapchainKHR(device: VkDevice | null, pCreateInfo: VkSwapchainCreateInfoKHR | null, pAllocator: null, pSwapchain: VkSwapchainKHR | null): number; declare function vkDestroySwapchainKHR(device: VkDevice | null, swapchain: VkSwapchainKHR | null, pAllocator: null): void; declare function vkGetSwapchainImagesKHR(device: VkDevice | null, swapchain: VkSwapchainKHR | null, pSwapchainImageCount: VkInout, pSwapchainImages: VkImage[] | null): number; declare function vkAcquireNextImageKHR(device: VkDevice | null, swapchain: VkSwapchainKHR | null, timeout: number, semaphore: VkSemaphore | null, fence: VkFence | null, pImageIndex: VkInout): number; declare function vkQueuePresentKHR(queue: VkQueue | null, pPresentInfo: VkPresentInfoKHR | null): number; declare function vkCreateDebugReportCallbackEXT(instance: VkInstance | null, pCreateInfo: VkDebugReportCallbackCreateInfoEXT | null, pAllocator: null, pCallback: VkDebugReportCallbackEXT | null): number; declare function vkDestroyDebugReportCallbackEXT(instance: VkInstance | null, callback: VkDebugReportCallbackEXT | null, pAllocator: null): void; declare function vkDebugReportMessageEXT(instance: VkInstance | null, flags: VkDebugReportFlagBitsEXT, objectType: VkDebugReportObjectTypeEXT, object: number, location: number, messageCode: number, pLayerPrefix: string | null, pMessage: string | null): void; declare function vkDebugMarkerSetObjectNameEXT(device: VkDevice | null, pNameInfo: VkDebugMarkerObjectNameInfoEXT | null): number; declare function vkDebugMarkerSetObjectTagEXT(device: VkDevice | null, pTagInfo: VkDebugMarkerObjectTagInfoEXT | null): number; declare function vkCmdDebugMarkerBeginEXT(commandBuffer: VkCommandBuffer | null, pMarkerInfo: VkDebugMarkerMarkerInfoEXT | null): void; declare function vkCmdDebugMarkerEndEXT(commandBuffer: VkCommandBuffer | null): void; declare function vkCmdDebugMarkerInsertEXT(commandBuffer: VkCommandBuffer | null, pMarkerInfo: VkDebugMarkerMarkerInfoEXT | null): void; declare function vkGetPhysicalDeviceExternalImageFormatPropertiesNV(physicalDevice: VkPhysicalDevice | null, format: VkFormat, type: VkImageType, tiling: VkImageTiling, usage: VkImageUsageFlagBits, flags: VkImageCreateFlagBits, externalHandleType: VkExternalMemoryHandleTypeFlagBitsNV, pExternalImageFormatProperties: VkExternalImageFormatPropertiesNV | null): number; declare function vkCmdDrawIndirectCountAMD(commandBuffer: VkCommandBuffer | null, buffer: VkBuffer | null, offset: number, countBuffer: VkBuffer | null, countBufferOffset: number, maxDrawCount: number, stride: number): void; declare function vkCmdDrawIndexedIndirectCountAMD(commandBuffer: VkCommandBuffer | null, buffer: VkBuffer | null, offset: number, countBuffer: VkBuffer | null, countBufferOffset: number, maxDrawCount: number, stride: number): void; declare function vkCmdProcessCommandsNVX(commandBuffer: VkCommandBuffer | null, pProcessCommandsInfo: VkCmdProcessCommandsInfoNVX | null): void; declare function vkCmdReserveSpaceForCommandsNVX(commandBuffer: VkCommandBuffer | null, pReserveSpaceInfo: VkCmdReserveSpaceForCommandsInfoNVX | null): void; declare function vkCreateIndirectCommandsLayoutNVX(device: VkDevice | null, pCreateInfo: VkIndirectCommandsLayoutCreateInfoNVX | null, pAllocator: null, pIndirectCommandsLayout: VkIndirectCommandsLayoutNVX | null): number; declare function vkDestroyIndirectCommandsLayoutNVX(device: VkDevice | null, indirectCommandsLayout: VkIndirectCommandsLayoutNVX | null, pAllocator: null): void; declare function vkCreateObjectTableNVX(device: VkDevice | null, pCreateInfo: VkObjectTableCreateInfoNVX | null, pAllocator: null, pObjectTable: VkObjectTableNVX | null): number; declare function vkDestroyObjectTableNVX(device: VkDevice | null, objectTable: VkObjectTableNVX | null, pAllocator: null): void; declare function vkRegisterObjectsNVX(device: VkDevice | null, objectTable: VkObjectTableNVX | null, objectCount: number, ppObjectTableEntries: VkObjectTableEntryNVX[] | null, pObjectIndices: VkInout): number; declare function vkUnregisterObjectsNVX(device: VkDevice | null, objectTable: VkObjectTableNVX | null, objectCount: number, pObjectEntryTypes: VkInout, pObjectIndices: VkInout): number; declare function vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX(physicalDevice: VkPhysicalDevice | null, pFeatures: VkDeviceGeneratedCommandsFeaturesNVX | null, pLimits: VkDeviceGeneratedCommandsLimitsNVX | null): void; declare function vkGetPhysicalDeviceFeatures2(physicalDevice: VkPhysicalDevice | null, pFeatures: VkPhysicalDeviceFeatures2 | null): void; declare function vkGetPhysicalDeviceProperties2(physicalDevice: VkPhysicalDevice | null, pProperties: VkPhysicalDeviceProperties2 | null): void; declare function vkGetPhysicalDeviceFormatProperties2(physicalDevice: VkPhysicalDevice | null, format: VkFormat, pFormatProperties: VkFormatProperties2 | null): void; declare function vkGetPhysicalDeviceImageFormatProperties2(physicalDevice: VkPhysicalDevice | null, pImageFormatInfo: VkPhysicalDeviceImageFormatInfo2 | null, pImageFormatProperties: VkImageFormatProperties2 | null): number; declare function vkGetPhysicalDeviceQueueFamilyProperties2(physicalDevice: VkPhysicalDevice | null, pQueueFamilyPropertyCount: VkInout, pQueueFamilyProperties: VkQueueFamilyProperties2[] | null): void; declare function vkGetPhysicalDeviceMemoryProperties2(physicalDevice: VkPhysicalDevice | null, pMemoryProperties: VkPhysicalDeviceMemoryProperties2 | null): void; declare function vkGetPhysicalDeviceSparseImageFormatProperties2(physicalDevice: VkPhysicalDevice | null, pFormatInfo: VkPhysicalDeviceSparseImageFormatInfo2 | null, pPropertyCount: VkInout, pProperties: VkSparseImageFormatProperties2[] | null): void; declare function vkCmdPushDescriptorSetKHR(commandBuffer: VkCommandBuffer | null, pipelineBindPoint: VkPipelineBindPoint, layout: VkPipelineLayout | null, set: number, descriptorWriteCount: number, pDescriptorWrites: VkWriteDescriptorSet[] | null): void; declare function vkTrimCommandPool(device: VkDevice | null, commandPool: VkCommandPool | null, flags: null): void; declare function vkGetPhysicalDeviceExternalBufferProperties(physicalDevice: VkPhysicalDevice | null, pExternalBufferInfo: VkPhysicalDeviceExternalBufferInfo | null, pExternalBufferProperties: VkExternalBufferProperties | null): void; declare function vkGetMemoryFdKHR(device: VkDevice | null, pGetFdInfo: VkMemoryGetFdInfoKHR | null, pFd: VkInout): number; declare function vkGetMemoryFdPropertiesKHR(device: VkDevice | null, handleType: number, fd: number, pMemoryFdProperties: VkMemoryFdPropertiesKHR | null): number; declare function vkGetPhysicalDeviceExternalSemaphoreProperties(physicalDevice: VkPhysicalDevice | null, pExternalSemaphoreInfo: VkPhysicalDeviceExternalSemaphoreInfo | null, pExternalSemaphoreProperties: VkExternalSemaphoreProperties | null): void; declare function vkGetSemaphoreFdKHR(device: VkDevice | null, pGetFdInfo: VkSemaphoreGetFdInfoKHR | null, pFd: VkInout): number; declare function vkImportSemaphoreFdKHR(device: VkDevice | null, pImportSemaphoreFdInfo: VkImportSemaphoreFdInfoKHR | null): number; declare function vkGetPhysicalDeviceExternalFenceProperties(physicalDevice: VkPhysicalDevice | null, pExternalFenceInfo: VkPhysicalDeviceExternalFenceInfo | null, pExternalFenceProperties: VkExternalFenceProperties | null): void; declare function vkGetFenceFdKHR(device: VkDevice | null, pGetFdInfo: VkFenceGetFdInfoKHR | null, pFd: VkInout): number; declare function vkImportFenceFdKHR(device: VkDevice | null, pImportFenceFdInfo: VkImportFenceFdInfoKHR | null): number; declare function vkReleaseDisplayEXT(physicalDevice: VkPhysicalDevice | null, display: VkDisplayKHR | null): number; declare function vkDisplayPowerControlEXT(device: VkDevice | null, display: VkDisplayKHR | null, pDisplayPowerInfo: VkDisplayPowerInfoEXT | null): number; declare function vkRegisterDeviceEventEXT(device: VkDevice | null, pDeviceEventInfo: VkDeviceEventInfoEXT | null, pAllocator: null, pFence: VkFence | null): number; declare function vkRegisterDisplayEventEXT(device: VkDevice | null, display: VkDisplayKHR | null, pDisplayEventInfo: VkDisplayEventInfoEXT | null, pAllocator: null, pFence: VkFence | null): number; declare function vkGetSwapchainCounterEXT(device: VkDevice | null, swapchain: VkSwapchainKHR | null, counter: number, pCounterValue: VkInout): number; declare function vkGetPhysicalDeviceSurfaceCapabilities2EXT(physicalDevice: VkPhysicalDevice | null, surface: VkSurfaceKHR | null, pSurfaceCapabilities: VkSurfaceCapabilities2EXT | null): number; declare function vkEnumeratePhysicalDeviceGroups(instance: VkInstance | null, pPhysicalDeviceGroupCount: VkInout, pPhysicalDeviceGroupProperties: VkPhysicalDeviceGroupProperties[] | null): number; declare function vkGetDeviceGroupPeerMemoryFeatures(device: VkDevice | null, heapIndex: number, localDeviceIndex: number, remoteDeviceIndex: number, pPeerMemoryFeatures: VkInout): void; declare function vkBindBufferMemory2(device: VkDevice | null, bindInfoCount: number, pBindInfos: VkBindBufferMemoryInfo[] | null): number; declare function vkBindImageMemory2(device: VkDevice | null, bindInfoCount: number, pBindInfos: VkBindImageMemoryInfo[] | null): number; declare function vkCmdSetDeviceMask(commandBuffer: VkCommandBuffer | null, deviceMask: number): void; declare function vkGetDeviceGroupPresentCapabilitiesKHR(device: VkDevice | null, pDeviceGroupPresentCapabilities: VkDeviceGroupPresentCapabilitiesKHR | null): number; declare function vkGetDeviceGroupSurfacePresentModesKHR(device: VkDevice | null, surface: VkSurfaceKHR | null, pModes: VkInout): number; declare function vkAcquireNextImage2KHR(device: VkDevice | null, pAcquireInfo: VkAcquireNextImageInfoKHR | null, pImageIndex: VkInout): number; declare function vkCmdDispatchBase(commandBuffer: VkCommandBuffer | null, baseGroupX: number, baseGroupY: number, baseGroupZ: number, groupCountX: number, groupCountY: number, groupCountZ: number): void; declare function vkGetPhysicalDevicePresentRectanglesKHR(physicalDevice: VkPhysicalDevice | null, surface: VkSurfaceKHR | null, pRectCount: VkInout, pRects: VkRect2D[] | null): number; declare function vkCreateDescriptorUpdateTemplate(device: VkDevice | null, pCreateInfo: VkDescriptorUpdateTemplateCreateInfo | null, pAllocator: null, pDescriptorUpdateTemplate: VkDescriptorUpdateTemplate | null): number; declare function vkDestroyDescriptorUpdateTemplate(device: VkDevice | null, descriptorUpdateTemplate: VkDescriptorUpdateTemplate | null, pAllocator: null): void; declare function vkUpdateDescriptorSetWithTemplate(device: VkDevice | null, descriptorSet: VkDescriptorSet | null, descriptorUpdateTemplate: VkDescriptorUpdateTemplate | null, pData: ArrayBuffer | null): void; declare function vkCmdPushDescriptorSetWithTemplateKHR(commandBuffer: VkCommandBuffer | null, descriptorUpdateTemplate: VkDescriptorUpdateTemplate | null, layout: VkPipelineLayout | null, set: number, pData: ArrayBuffer | null): void; declare function vkSetHdrMetadataEXT(device: VkDevice | null, swapchainCount: number, pSwapchains: VkSwapchainKHR[] | null, pMetadata: VkHdrMetadataEXT[] | null): void; declare function vkGetSwapchainStatusKHR(device: VkDevice | null, swapchain: VkSwapchainKHR | null): number; declare function vkGetRefreshCycleDurationGOOGLE(device: VkDevice | null, swapchain: VkSwapchainKHR | null, pDisplayTimingProperties: VkRefreshCycleDurationGOOGLE | null): number; declare function vkGetPastPresentationTimingGOOGLE(device: VkDevice | null, swapchain: VkSwapchainKHR | null, pPresentationTimingCount: VkInout, pPresentationTimings: VkPastPresentationTimingGOOGLE[] | null): number; declare function vkCmdSetViewportWScalingNV(commandBuffer: VkCommandBuffer | null, firstViewport: number, viewportCount: number, pViewportWScalings: VkViewportWScalingNV[] | null): void; declare function vkCmdSetDiscardRectangleEXT(commandBuffer: VkCommandBuffer | null, firstDiscardRectangle: number, discardRectangleCount: number, pDiscardRectangles: VkRect2D[] | null): void; declare function vkCmdSetSampleLocationsEXT(commandBuffer: VkCommandBuffer | null, pSampleLocationsInfo: VkSampleLocationsInfoEXT | null): void; declare function vkGetPhysicalDeviceMultisamplePropertiesEXT(physicalDevice: VkPhysicalDevice | null, samples: number, pMultisampleProperties: VkMultisamplePropertiesEXT | null): void; declare function vkGetPhysicalDeviceSurfaceCapabilities2KHR(physicalDevice: VkPhysicalDevice | null, pSurfaceInfo: VkPhysicalDeviceSurfaceInfo2KHR | null, pSurfaceCapabilities: VkSurfaceCapabilities2KHR | null): number; declare function vkGetPhysicalDeviceSurfaceFormats2KHR(physicalDevice: VkPhysicalDevice | null, pSurfaceInfo: VkPhysicalDeviceSurfaceInfo2KHR | null, pSurfaceFormatCount: VkInout, pSurfaceFormats: VkSurfaceFormat2KHR[] | null): number; declare function vkGetPhysicalDeviceDisplayProperties2KHR(physicalDevice: VkPhysicalDevice | null, pPropertyCount: VkInout, pProperties: VkDisplayProperties2KHR[] | null): number; declare function vkGetPhysicalDeviceDisplayPlaneProperties2KHR(physicalDevice: VkPhysicalDevice | null, pPropertyCount: VkInout, pProperties: VkDisplayPlaneProperties2KHR[] | null): number; declare function vkGetDisplayModeProperties2KHR(physicalDevice: VkPhysicalDevice | null, display: VkDisplayKHR | null, pPropertyCount: VkInout, pProperties: VkDisplayModeProperties2KHR[] | null): number; declare function vkGetDisplayPlaneCapabilities2KHR(physicalDevice: VkPhysicalDevice | null, pDisplayPlaneInfo: VkDisplayPlaneInfo2KHR | null, pCapabilities: VkDisplayPlaneCapabilities2KHR | null): number; declare function vkGetBufferMemoryRequirements2(device: VkDevice | null, pInfo: VkBufferMemoryRequirementsInfo2 | null, pMemoryRequirements: VkMemoryRequirements2 | null): void; declare function vkGetImageMemoryRequirements2(device: VkDevice | null, pInfo: VkImageMemoryRequirementsInfo2 | null, pMemoryRequirements: VkMemoryRequirements2 | null): void; declare function vkGetImageSparseMemoryRequirements2(device: VkDevice | null, pInfo: VkImageSparseMemoryRequirementsInfo2 | null, pSparseMemoryRequirementCount: VkInout, pSparseMemoryRequirements: VkSparseImageMemoryRequirements2[] | null): void; declare function vkCreateSamplerYcbcrConversion(device: VkDevice | null, pCreateInfo: VkSamplerYcbcrConversionCreateInfo | null, pAllocator: null, pYcbcrConversion: VkSamplerYcbcrConversion | null): number; declare function vkDestroySamplerYcbcrConversion(device: VkDevice | null, ycbcrConversion: VkSamplerYcbcrConversion | null, pAllocator: null): void; declare function vkGetDeviceQueue2(device: VkDevice | null, pQueueInfo: VkDeviceQueueInfo2 | null, pQueue: VkQueue | null): void; declare function vkCreateValidationCacheEXT(device: VkDevice | null, pCreateInfo: VkValidationCacheCreateInfoEXT | null, pAllocator: null, pValidationCache: VkValidationCacheEXT | null): number; declare function vkDestroyValidationCacheEXT(device: VkDevice | null, validationCache: VkValidationCacheEXT | null, pAllocator: null): void; declare function vkGetValidationCacheDataEXT(device: VkDevice | null, validationCache: VkValidationCacheEXT | null, pDataSize: VkInout, pData: ArrayBuffer | null): number; declare function vkMergeValidationCachesEXT(device: VkDevice | null, dstCache: VkValidationCacheEXT | null, srcCacheCount: number, pSrcCaches: VkValidationCacheEXT[] | null): number; declare function vkGetDescriptorSetLayoutSupport(device: VkDevice | null, pCreateInfo: VkDescriptorSetLayoutCreateInfo | null, pSupport: VkDescriptorSetLayoutSupport | null): void; declare function vkGetShaderInfoAMD(device: VkDevice | null, pipeline: VkPipeline | null, shaderStage: number, infoType: VkShaderInfoTypeAMD, pInfoSize: VkInout, pInfo: ArrayBuffer | null): number; declare function vkGetPhysicalDeviceCalibrateableTimeDomainsEXT(physicalDevice: VkPhysicalDevice | null, pTimeDomainCount: VkInout, pTimeDomains: VkInout): number; declare function vkGetCalibratedTimestampsEXT(device: VkDevice | null, timestampCount: number, pTimestampInfos: VkCalibratedTimestampInfoEXT[] | null, pTimestamps: VkInout, pMaxDeviation: VkInout): number; declare function vkSetDebugUtilsObjectNameEXT(device: VkDevice | null, pNameInfo: VkDebugUtilsObjectNameInfoEXT | null): number; declare function vkSetDebugUtilsObjectTagEXT(device: VkDevice | null, pTagInfo: VkDebugUtilsObjectTagInfoEXT | null): number; declare function vkQueueBeginDebugUtilsLabelEXT(queue: VkQueue | null, pLabelInfo: VkDebugUtilsLabelEXT | null): void; declare function vkQueueEndDebugUtilsLabelEXT(queue: VkQueue | null): void; declare function vkQueueInsertDebugUtilsLabelEXT(queue: VkQueue | null, pLabelInfo: VkDebugUtilsLabelEXT | null): void; declare function vkCmdBeginDebugUtilsLabelEXT(commandBuffer: VkCommandBuffer | null, pLabelInfo: VkDebugUtilsLabelEXT | null): void; declare function vkCmdEndDebugUtilsLabelEXT(commandBuffer: VkCommandBuffer | null): void; declare function vkCmdInsertDebugUtilsLabelEXT(commandBuffer: VkCommandBuffer | null, pLabelInfo: VkDebugUtilsLabelEXT | null): void; declare function vkCreateDebugUtilsMessengerEXT(instance: VkInstance | null, pCreateInfo: VkDebugUtilsMessengerCreateInfoEXT | null, pAllocator: null, pMessenger: VkDebugUtilsMessengerEXT | null): number; declare function vkDestroyDebugUtilsMessengerEXT(instance: VkInstance | null, messenger: VkDebugUtilsMessengerEXT | null, pAllocator: null): void; declare function vkSubmitDebugUtilsMessageEXT(instance: VkInstance | null, messageSeverity: number, messageTypes: VkDebugUtilsMessageTypeFlagBitsEXT, pCallbackData: VkDebugUtilsMessengerCallbackDataEXT | null): void; declare function vkGetMemoryHostPointerPropertiesEXT(device: VkDevice | null, handleType: number, pHostPointer: ArrayBuffer | null, pMemoryHostPointerProperties: VkMemoryHostPointerPropertiesEXT | null): number; declare function vkCmdWriteBufferMarkerAMD(commandBuffer: VkCommandBuffer | null, pipelineStage: number, dstBuffer: VkBuffer | null, dstOffset: number, marker: number): void; declare function vkCreateRenderPass2KHR(device: VkDevice | null, pCreateInfo: VkRenderPassCreateInfo2KHR | null, pAllocator: null, pRenderPass: VkRenderPass | null): number; declare function vkCmdBeginRenderPass2KHR(commandBuffer: VkCommandBuffer | null, pRenderPassBegin: VkRenderPassBeginInfo | null, pSubpassBeginInfo: VkSubpassBeginInfoKHR | null): void; declare function vkCmdNextSubpass2KHR(commandBuffer: VkCommandBuffer | null, pSubpassBeginInfo: VkSubpassBeginInfoKHR | null, pSubpassEndInfo: VkSubpassEndInfoKHR | null): void; declare function vkCmdEndRenderPass2KHR(commandBuffer: VkCommandBuffer | null, pSubpassEndInfo: VkSubpassEndInfoKHR | null): void; declare function vkCmdDrawIndirectCountKHR(commandBuffer: VkCommandBuffer | null, buffer: VkBuffer | null, offset: number, countBuffer: VkBuffer | null, countBufferOffset: number, maxDrawCount: number, stride: number): void; declare function vkCmdDrawIndexedIndirectCountKHR(commandBuffer: VkCommandBuffer | null, buffer: VkBuffer | null, offset: number, countBuffer: VkBuffer | null, countBufferOffset: number, maxDrawCount: number, stride: number): void; declare function vkCmdSetCheckpointNV(commandBuffer: VkCommandBuffer | null, pCheckpointMarker: ArrayBuffer | null): void; declare function vkGetQueueCheckpointDataNV(queue: VkQueue | null, pCheckpointDataCount: VkInout, pCheckpointData: VkCheckpointDataNV[] | null): void; declare function vkCmdBindTransformFeedbackBuffersEXT(commandBuffer: VkCommandBuffer | null, firstBinding: number, bindingCount: number, pBuffers: VkBuffer[] | null, pOffsets: VkInout, pSizes: VkInout): void; declare function vkCmdBeginTransformFeedbackEXT(commandBuffer: VkCommandBuffer | null, firstCounterBuffer: number, counterBufferCount: number, pCounterBuffers: VkBuffer[] | null, pCounterBufferOffsets: VkInout): void; declare function vkCmdEndTransformFeedbackEXT(commandBuffer: VkCommandBuffer | null, firstCounterBuffer: number, counterBufferCount: number, pCounterBuffers: VkBuffer[] | null, pCounterBufferOffsets: VkInout): void; declare function vkCmdBeginQueryIndexedEXT(commandBuffer: VkCommandBuffer | null, queryPool: VkQueryPool | null, query: number, flags: VkQueryControlFlagBits, index: number): void; declare function vkCmdEndQueryIndexedEXT(commandBuffer: VkCommandBuffer | null, queryPool: VkQueryPool | null, query: number, index: number): void; declare function vkCmdDrawIndirectByteCountEXT(commandBuffer: VkCommandBuffer | null, instanceCount: number, firstInstance: number, counterBuffer: VkBuffer | null, counterBufferOffset: number, counterOffset: number, vertexStride: number): void; declare function vkCmdSetExclusiveScissorNV(commandBuffer: VkCommandBuffer | null, firstExclusiveScissor: number, exclusiveScissorCount: number, pExclusiveScissors: VkRect2D[] | null): void; declare function vkCmdBindShadingRateImageNV(commandBuffer: VkCommandBuffer | null, imageView: VkImageView | null, imageLayout: VkImageLayout): void; declare function vkCmdSetViewportShadingRatePaletteNV(commandBuffer: VkCommandBuffer | null, firstViewport: number, viewportCount: number, pShadingRatePalettes: VkShadingRatePaletteNV[] | null): void; declare function vkCmdSetCoarseSampleOrderNV(commandBuffer: VkCommandBuffer | null, sampleOrderType: VkCoarseSampleOrderTypeNV, customSampleOrderCount: number, pCustomSampleOrders: VkCoarseSampleOrderCustomNV[] | null): void; declare function vkCmdDrawMeshTasksNV(commandBuffer: VkCommandBuffer | null, taskCount: number, firstTask: number): void; declare function vkCmdDrawMeshTasksIndirectNV(commandBuffer: VkCommandBuffer | null, buffer: VkBuffer | null, offset: number, drawCount: number, stride: number): void; declare function vkCmdDrawMeshTasksIndirectCountNV(commandBuffer: VkCommandBuffer | null, buffer: VkBuffer | null, offset: number, countBuffer: VkBuffer | null, countBufferOffset: number, maxDrawCount: number, stride: number): void; declare function vkCompileDeferredNV(device: VkDevice | null, pipeline: VkPipeline | null, shader: number): number; declare function vkCreateAccelerationStructureNV(device: VkDevice | null, pCreateInfo: VkAccelerationStructureCreateInfoNV | null, pAllocator: null, pAccelerationStructure: VkAccelerationStructureNV | null): number; declare function vkDestroyAccelerationStructureNV(device: VkDevice | null, accelerationStructure: VkAccelerationStructureNV | null, pAllocator: null): void; declare function vkGetAccelerationStructureMemoryRequirementsNV(device: VkDevice | null, pInfo: VkAccelerationStructureMemoryRequirementsInfoNV | null, pMemoryRequirements: VkMemoryRequirements2KHR | null): void; declare function vkBindAccelerationStructureMemoryNV(device: VkDevice | null, bindInfoCount: number, pBindInfos: VkBindAccelerationStructureMemoryInfoNV[] | null): number; declare function vkCmdCopyAccelerationStructureNV(commandBuffer: VkCommandBuffer | null, dst: VkAccelerationStructureNV | null, src: VkAccelerationStructureNV | null, mode: VkCopyAccelerationStructureModeNV): void; declare function vkCmdWriteAccelerationStructuresPropertiesNV(commandBuffer: VkCommandBuffer | null, accelerationStructureCount: number, pAccelerationStructures: VkAccelerationStructureNV[] | null, queryType: VkQueryType, queryPool: VkQueryPool | null, firstQuery: number): void; declare function vkCmdBuildAccelerationStructureNV(commandBuffer: VkCommandBuffer | null, pInfo: VkAccelerationStructureInfoNV | null, instanceData: VkBuffer | null, instanceOffset: number, update: number, dst: VkAccelerationStructureNV | null, src: VkAccelerationStructureNV | null, scratch: VkBuffer | null, scratchOffset: number): void; declare function vkCmdTraceRaysNV(commandBuffer: VkCommandBuffer | null, raygenShaderBindingTableBuffer: VkBuffer | null, raygenShaderBindingOffset: number, missShaderBindingTableBuffer: VkBuffer | null, missShaderBindingOffset: number, missShaderBindingStride: number, hitShaderBindingTableBuffer: VkBuffer | null, hitShaderBindingOffset: number, hitShaderBindingStride: number, callableShaderBindingTableBuffer: VkBuffer | null, callableShaderBindingOffset: number, callableShaderBindingStride: number, width: number, height: number, depth: number): void; declare function vkGetRayTracingShaderGroupHandlesNV(device: VkDevice | null, pipeline: VkPipeline | null, firstGroup: number, groupCount: number, dataSize: number, pData: ArrayBuffer | null): number; declare function vkGetAccelerationStructureHandleNV(device: VkDevice | null, accelerationStructure: VkAccelerationStructureNV | null, dataSize: number, pData: ArrayBuffer | null): number; declare function vkCreateRayTracingPipelinesNV(device: VkDevice | null, pipelineCache: VkPipelineCache | null, createInfoCount: number, pCreateInfos: VkRayTracingPipelineCreateInfoNV[] | null, pAllocator: null, pPipelines: VkPipeline[] | null): number; declare function vkGetImageDrmFormatModifierPropertiesEXT(device: VkDevice | null, image: VkImage | null, pProperties: VkImageDrmFormatModifierPropertiesEXT | null): number; declare function vkGetBufferDeviceAddressEXT(device: VkDevice | null, pInfo: VkBufferDeviceAddressInfoEXT | null): number; /** #### HARDCODED #### **/ declare function createV8ArrayBufferFromMemory( addr: BigInt, size: number ): ArrayBuffer; declare function VK_MAKE_VERSION( major: number, minor: number, patch: number ): number; declare function VK_VERSION_MAJOR( major: number ): number; declare function VK_VERSION_MINOR( minor: number ): number; declare function VK_VERSION_PATCH( patch: number ): number; declare function vkUseDevice( pDevice: VkDevice ): void; declare function vkUseInstance( pInstance: VkInstance ): void; declare var VK_API_VERSION_1_0: number; /** #### VULKANWINDOW #### */ declare interface ResizeEvent { width: number; height: number; } declare interface FocusEvent { focused: boolean; } declare interface CloseEvent { } declare interface KeydownEvent { keyCode: number; } declare interface KeyupEvent { keyCode: number; } declare interface MousemoveEvent { x: number; y: number; movementX: number; movementY: number; } declare interface MousewheelEvent { x: number; y: number; deltaX: number; deltaY: number; } declare interface MousedownEvent { x: number; y: number; button: number; } declare interface MouseupEvent { x: number; y: number; button: number; } declare interface DropEvent { paths: string[]; } interface VulkanWindowInitializer { width?: number; height?: number; title?: string; } declare var VulkanWindow: { prototype: VulkanWindow; new(param?: VulkanWindowInitializer | null): VulkanWindow; width: number; height: number; title: string; pollEvents(): void; focus(): void; close(): void; shouldClose(): boolean; createSurface(instance: VkInstance | null, pAllocator: null, surface: VkSurfaceKHR | null): number; getRequiredInstanceExtensions(): string[]; onresize: ((ev: ResizeEvent) => any) | null; onfocus: ((ev: FocusEvent) => any) | null; onclose: ((ev: CloseEvent) => any) | null; onkeydown: ((ev: KeydownEvent) => any) | null; onkeyup: ((ev: KeyupEvent) => any) | null; onmousemove: ((ev: MousemoveEvent) => any) | null; onmousewheel: ((ev: MousewheelEvent) => any) | null; onmousedown: ((ev: MousedownEvent) => any) | null; onmouseup: ((ev: MouseupEvent) => any) | null; ondrop: ((ev: DropEvent) => any) | null; } export interface VulkanWindow { width: number; height: number; title: string; pollEvents(): void; focus(): void; close(): void; shouldClose(): boolean; createSurface(instance: VkInstance | null, pAllocator: null, surface: VkSurfaceKHR | null): number; getRequiredInstanceExtensions(): string[]; onresize: ((ev: ResizeEvent) => any) | null; onfocus: ((ev: FocusEvent) => any) | null; onclose: ((ev: CloseEvent) => any) | null; onkeydown: ((ev: KeydownEvent) => any) | null; onkeyup: ((ev: KeyupEvent) => any) | null; onmousemove: ((ev: MousemoveEvent) => any) | null; onmousewheel: ((ev: MousewheelEvent) => any) | null; onmousedown: ((ev: MousedownEvent) => any) | null; onmouseup: ((ev: MouseupEvent) => any) | null; ondrop: ((ev: DropEvent) => any) | null; }
the_stack
'use strict'; import * as vscode from 'vscode'; import * as util from '../common'; import * as cpptools from './client'; import * as telemetry from '../telemetry'; import { getCustomConfigProviders } from './customProviders'; import { TimeTelemetryCollector } from './timeTelemetryCollector'; const defaultClientKey: string = "@@default@@"; export interface ClientKey { name: string; key: string; } export class ClientCollection { private disposables: vscode.Disposable[] = []; private languageClients = new Map<string, cpptools.Client>(); private defaultClient: cpptools.Client; private activeClient: cpptools.Client; private activeDocument?: vscode.TextDocument; public timeTelemetryCollector: TimeTelemetryCollector = new TimeTelemetryCollector(); // This is a one-time switch to a mode that suppresses launching of the cpptools client process. private useFailsafeMode: boolean = false; public get ActiveClient(): cpptools.Client { return this.activeClient; } public get Names(): ClientKey[] { const result: ClientKey[] = []; this.languageClients.forEach((client, key) => { result.push({ name: client.Name, key: key }); }); return result; } public get Count(): number { return this.languageClients.size; } constructor() { let key: string = defaultClientKey; if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) { let isFirstWorkspaceFolder: boolean = true; vscode.workspace.workspaceFolders.forEach(folder => { const newClient: cpptools.Client = cpptools.createClient(this, folder); this.languageClients.set(util.asFolder(folder.uri), newClient); if (isFirstWorkspaceFolder) { isFirstWorkspaceFolder = false; } else { newClient.deactivate(); } }); key = util.asFolder(vscode.workspace.workspaceFolders[0].uri); const client: cpptools.Client | undefined = this.languageClients.get(key); if (!client) { throw new Error("Failed to construct default client"); } this.activeClient = client; } else { this.activeClient = cpptools.createClient(this); } this.defaultClient = this.activeClient; this.languageClients.set(key, this.activeClient); this.disposables.push(vscode.workspace.onDidChangeWorkspaceFolders(e => this.onDidChangeWorkspaceFolders(e))); this.disposables.push(vscode.workspace.onDidCloseTextDocument(d => this.onDidCloseTextDocument(d))); } public async activeDocumentChanged(document: vscode.TextDocument): Promise<void> { this.activeDocument = document; const activeClient: cpptools.Client = this.getClientFor(document.uri); // Notify the active client that the document has changed. await activeClient.activeDocumentChanged(document); // If the active client changed, resume the new client and tell the currently active client to deactivate. if (activeClient !== this.activeClient) { activeClient.activate(); this.activeClient.deactivate(); this.activeClient = activeClient; } } /** * get a handle to a language client. returns undefined if the client was not found. */ public get(key: string): cpptools.Client | undefined { const client: cpptools.Client | undefined = this.languageClients.get(key); console.assert(client, "key not found"); return client; } public forEach(callback: (client: cpptools.Client) => void): void { // Copy this.languageClients to languageClients to avoid an infinite foreach loop // when callback modifies this.languageClients (e.g. when cpptools crashes). const languageClients: cpptools.Client[] = []; this.languageClients.forEach(client => languageClients.push(client)); languageClients.forEach(callback); } public checkOwnership(client: cpptools.Client, document: vscode.TextDocument): boolean { return (this.getClientFor(document.uri) === client); } /** * creates a new client to replace one that crashed. */ public async recreateClients(switchToFailsafeMode?: boolean): Promise<void> { // Swap out the map, so we are not changing it while iterating over it. const oldLanguageClients: Map<string, cpptools.Client> = this.languageClients; this.languageClients = new Map<string, cpptools.Client>(); if (switchToFailsafeMode) { this.useFailsafeMode = true; } for (const pair of oldLanguageClients) { const client: cpptools.Client = pair[1]; const newClient: cpptools.Client = this.createClient(client.RootFolder, true); client.TrackedDocuments.forEach(document => this.transferOwnership(document, client)); if (this.activeClient === client) { // It cannot be undefined. If there is an active document, we activate it later. this.activeClient = newClient; } if (this.defaultClient === client) { this.defaultClient = newClient; } client.dispose(); } if (this.activeDocument) { this.activeClient = this.getClientFor(this.activeDocument.uri); await this.activeClient.activeDocumentChanged(this.activeDocument); this.activeClient.activate(); } } private async onDidChangeWorkspaceFolders(e?: vscode.WorkspaceFoldersChangeEvent): Promise<void> { const folderCount: number = vscode.workspace.workspaceFolders ? vscode.workspace.workspaceFolders.length : 0; if (folderCount > 1) { telemetry.logLanguageServerEvent("workspaceFoldersChange", { "count": folderCount.toString() }); } if (e !== undefined) { let oldDefaultClient: cpptools.Client | undefined; let needNewDefaultClient: boolean = false; e.removed.forEach(folder => { const path: string = util.asFolder(folder.uri); const client: cpptools.Client | undefined = this.languageClients.get(path); if (client) { this.languageClients.delete(path); // Do this first so that we don't iterate on it during the ownership transfer process. // Transfer ownership of the client's documents to another client. // (this includes calling textDocument/didOpen on the new client so that the server knows it's open too) client.TrackedDocuments.forEach(document => this.transferOwnership(document, client)); if (this.activeClient === client) { this.activeClient.deactivate(); } // Defer selecting a new default client until all adds and removes have been processed. if (this.defaultClient === client) { oldDefaultClient = client; } else { client.dispose(); } } }); e.added.forEach(folder => { const path: string = util.asFolder(folder.uri); const client: cpptools.Client | undefined = this.languageClients.get(path); if (!client) { this.createClient(folder, true); } }); // Note: VS Code currently reloads the extension whenever the primary (first) workspace folder is added or removed. // So the following handling of changes to defaultClient are likely unnecessary, unless the behavior of // VS Code changes. The handling of changes to activeClient are still needed. if (oldDefaultClient) { const uri: vscode.Uri | undefined = oldDefaultClient.RootUri; // uri will be set. if (uri) { // Check if there is now another more appropriate client to use. this.defaultClient = this.getClientFor(uri); needNewDefaultClient = this.defaultClient === oldDefaultClient; } oldDefaultClient.dispose(); } else { const defaultDefaultClient: cpptools.Client | undefined = this.languageClients.get(defaultClientKey); if (defaultDefaultClient) { // If there is an entry in languageClients for defaultClientKey, we were not previously tracking any workspace folders. this.languageClients.delete(defaultClientKey); needNewDefaultClient = true; if (this.activeClient === this.defaultClient) { // Redundant deactivation should be OK. this.activeClient.deactivate(); } } } if (needNewDefaultClient) { // Use the first workspaceFolder, if any. if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) { const key: string = util.asFolder(vscode.workspace.workspaceFolders[0].uri); const client: cpptools.Client | undefined = this.languageClients.get(key); if (!client) { // This should not occur. If there is a workspace folder, we should have a client for it by now. throw new Error("Failed to construct default client"); } this.defaultClient = client; } else { // The user removed the last workspace folder. Create a new default defaultClient/activeClient // using the same approach as used in the constructor. this.defaultClient = cpptools.createClient(this); this.languageClients.set(defaultClientKey, this.defaultClient); this.defaultClient.deactivate(); if (this.activeDocument) { // Only change activeClient if it would not be changed by the later check. this.activeClient.deactivate(); this.activeClient = this.defaultClient; } } } // Ensure the best client for the currently active document is activated. if (this.activeDocument) { const newActiveClient: cpptools.Client = this.getClientFor(this.activeDocument.uri); // If a client is newly created here, it will be activated by default. if (this.activeClient !== newActiveClient) { // Redundant deactivate should be OK. this.activeClient.deactivate(); this.activeClient = newActiveClient; await this.activeClient.activeDocumentChanged(this.activeDocument); this.activeClient.activate(); } } } } private transferOwnership(document: vscode.TextDocument, oldOwner: cpptools.Client): void { const newOwner: cpptools.Client = this.getClientFor(document.uri); if (newOwner !== oldOwner) { newOwner.takeOwnership(document); } } public getClientFor(uri: vscode.Uri): cpptools.Client { const folder: vscode.WorkspaceFolder | undefined = uri ? vscode.workspace.getWorkspaceFolder(uri) : undefined; return this.getClientForFolder(folder); } public getClientForFolder(folder?: vscode.WorkspaceFolder): cpptools.Client { if (!folder) { return this.defaultClient; } else { const key: string = util.asFolder(folder.uri); const client: cpptools.Client | undefined = this.languageClients.get(key); if (client) { return client; } return this.createClient(folder); } } public createClient(folder?: vscode.WorkspaceFolder, deactivated?: boolean): cpptools.Client { const newClient: cpptools.Client = this.useFailsafeMode ? cpptools.createNullClient() : cpptools.createClient(this, folder); if (deactivated) { newClient.deactivate(); // e.g. prevent the current config from switching. } const key: string = folder ? util.asFolder(folder.uri) : defaultClientKey; this.languageClients.set(key, newClient); getCustomConfigProviders().forEach(provider => newClient.onRegisterCustomConfigurationProvider(provider)); newClient.sendAllSettings(); return newClient; } private onDidCloseTextDocument(document: vscode.TextDocument): void { // Don't seem to need to do anything here since we clean up when the workspace is closed instead. } public dispose(): Thenable<void> { this.disposables.forEach((d: vscode.Disposable) => d.dispose()); // this.defaultClient is already in this.languageClients, so do not call dispose() on it. this.languageClients.forEach(client => client.dispose()); this.languageClients.clear(); cpptools.disposeWorkspaceData(); return cpptools.DefaultClient.stopLanguageClient(); } }
the_stack
import * as stateTypes from '../reducers/types'; import * as _ from 'lodash'; function raise(e: string): never { throw e; } export class Subpolicy { i: number; title: string; passing?: boolean; condition: string; constructor(i: number) { this.i = i; this.title = ''; this.passing = undefined; this.condition = ''; } } const BLANK_POLICY = (viewName: string) => `CREATE OR REPLACE VIEW rules.${viewName}_POLICY_DEFINITION COPY GRANTS\n` + ` COMMENT='Policy Title\n` + `description goes here'\n` + `AS\n` + ` SELECT 'subpolicy title' AS title\n` + ` , true AS passing\n` + `;`; function stripComment(body: string): {rest: string; comment: string; viewName: string} { const vnameRe = /^CREATE OR REPLACE VIEW [^.]+.[^.]+.([^\s]+) ?COPY GRANTS\s*\n/im; const descrRe = /^\s*COMMENT='((?:\\'|[^'])*)'\s*\nAS\s*\n/gim; const vnameMatch = vnameRe.exec(body); if (!vnameMatch) { return {rest: body, comment: '', viewName: ''}; } const vnameAfter = body.substr(vnameMatch[0].length); const descrMatch = descrRe.exec(vnameAfter) || raise('no descr match'); const descrAfter = vnameAfter.substr(descrMatch[0].length); return { rest: descrAfter, comment: descrMatch[1].replace(/\\'/g, "'"), viewName: vnameMatch[1], }; } function parseComment(comment: string): {summary: string; decorations: {[name: string]: string}} { const decorations: {[name: string]: string} = {}; const summary = comment .split('\n') .map(line => { const match = line.match(/^\s*@([a-z-]+) (.*)$/i); if (match) { decorations[match[1]] = match[2]; return undefined; } else { return line; } }) .filter(x => x !== undefined) .join('\n'); return {summary, decorations}; } export abstract class SQLBackedRule { _raw!: stateTypes.SnowAlertRule; isSaving: boolean; isEditing: boolean; isParsed!: boolean; constructor(rule: stateTypes.SnowAlertRule) { this.raw = rule; this.isSaving = false; this.isEditing = false; } copy(toMerge: any) { return _.mergeWith(_.cloneDeep(this), toMerge, (a, b) => (_.isArray(a) ? b : undefined)); } get raw() { return Object.assign({}, this._raw, this.isParsed ? {body: this.body} : undefined); } set raw(r: stateTypes.SnowAlertRule) { this._raw = r; try { this.load(r.body, r.results); this.isParsed = this.body === r.body; // if (!this.isParsed) { // console.log('r.body', r.body) // console.log('this.body', this.body) // } } catch (e) { // console.log(`error parsing >${r.body}< ${new Error(e)}`, e); this.isParsed = false; } } get type() { return this.raw.type; } get viewName(): string { return `${this._raw.title}_${this._raw.target}_${this._raw.type}`; } get rawTitle(): string { return this.raw.title .replace(/_/g, ' ') .toLowerCase() .replace(/\b[a-z]/g, c => c.toUpperCase()); } get title(): string { return this.rawTitle; } get isSaved() { return this._raw.savedBody !== ''; } get isEdited() { return this.raw.body !== this._raw.savedBody; } abstract load(body: string, results?: stateTypes.SnowAlertRule['results']): void; abstract get body(): string; } export class Policy extends SQLBackedRule { views!: string; comment!: string; subpolicies!: Subpolicy[]; static create() { const viewName = `PD_${Math.random() .toString(36) .substring(2)}`; return new Policy({ target: 'POLICY', type: 'DEFINITION', title: viewName, results: [{PASSING: undefined, TITLE: 'subpolicy title'}], body: BLANK_POLICY(viewName), savedBody: '', isSaving: false, newTitle: '', }); } copy() { return new Policy(this._raw); } get passing(): boolean { return this.subpolicies.reduce((prev, sp) => (sp.passing ? true : prev), true); } get title() { return this.comment.replace(/\n.*$/g, ''); } set title(newTitle: string) { this.comment = this.comment.replace(/^.*?\n/, `${newTitle}\n`); } set summary(newDescription: string) { this.comment = this.comment.replace(/\n.*$/, `\n${newDescription}`); } get summary() { return this.comment.replace(/^.*?\n/g, ''); } load(sql: string, results: stateTypes.SnowAlertRule['results']) { const vnameRe = /^CREATE OR REPLACE VIEW [^.]+.[^.]+.([^\s]+) ?COPY GRANTS\s*\n/m; const descrRe = /^ {2}COMMENT='([^']+)'\nAS\n/gm; const subplRe = /^ {2}SELECT '((?:\\'|[^'])+)' AS title\n {7}, ([^;]+?) AS passing$(?:\n;|\nUNION ALL\n)?/m; const vnameMatch = vnameRe.exec(sql) || raise('no vname match'); const vnameAfter = sql.substr(vnameMatch[0].length); const descrMatch = descrRe.exec(vnameAfter) || raise('no descr match'); const descrAfter = vnameAfter.substr(descrMatch[0].length); this.comment = descrMatch[1]; this.subpolicies = []; let rest = descrAfter; let i = 0; do { const matchSubpl = subplRe.exec(rest) || raise(`no title match >${sql}|${rest}<`); rest = rest.substr(matchSubpl[0].length); this.subpolicies.push({ i, passing: results ? results[i++].PASSING : false, title: matchSubpl[1].replace(/\\'/g, "'"), condition: matchSubpl[2], }); } while (rest.replace(/\s/g, '')); } get isEdited() { return this.raw.body !== this._raw.savedBody; } get body(): string { return ( `CREATE OR REPLACE VIEW rules.${this.viewName} COPY GRANTS\n` + ` COMMENT='${this.comment.replace(/'/g, "\\'")}'\n` + `AS\n` + this.subpolicies .map(sp => ` SELECT '${sp.title.replace(/'/g, "\\'")}' AS title\n , ${sp.condition} AS passing`) .join('\nUNION ALL\n') + `\n;\n` ); } } interface QueryFields { select: { [prop: string]: string; }; from: string; enabled: boolean; where: string; } export class Query extends SQLBackedRule { fields!: QueryFields; summary!: string; tags!: string[]; constructor(rule: stateTypes.SnowAlertRule) { super(rule); // TODO(anfedorov): why doesn't the super() call ? this.raw = rule; this.isSaving = false; this.isEditing = false; } get target() { return this._raw.target; } load(body: string) { function stripField(sql: string): {rest: string; field: string; value: string} | null { const match = sql.match(/^\s*(?:SELECT|,)\s*([\s\S]*?) AS (\w*)$/im); if (!match || sql.match(/^\s*FROM/i)) { // in case of sub-queries, FROM match needs to be explicit return null; } else { const [m, value, field] = match; return { rest: sql.substr(m.length), field, value, }; } } function stripFrom(sql: string): {rest: string; from: string} { const [match, from] = sql.match(/^\s*FROM ([\S\s]*?)\s+^WHERE\s/im) || raise('no from'); return { rest: sql.substr(match.length - 6), from, }; } function stripWhere(sql: string): {enabled: boolean; where: string; more: boolean} { const [match, enabled, where] = sql.match(/^WHERE (1=[01]|)\s*(?:AND )?([\s\S]*?)\s*;$/im) || raise('err2'); return { enabled: !(enabled === '1=0'), where, more: match.length !== sql.length, }; } const fields = { select: {}, from: '', enabled: false, where: '', }; const query = stripComment(body); let {rest} = query; const {comment} = query; const { summary, decorations: {tags}, } = parseComment(comment); this.tags = tags ? tags.split(', ') : []; this.summary = summary; let nextField = stripField(rest); if (!nextField) { throw new Error('err0'); } do { const {field, value} = nextField; // @ts-ignore fields.select[field] = value.replace(/\n {7}/g, '\n'); nextField = stripField(nextField.rest); } while (nextField); const afterFrom = stripFrom(rest); rest = afterFrom.rest; fields.from = afterFrom.from; const {enabled, where} = stripWhere(rest); fields.enabled = enabled; fields.where = where; this.fields = fields; } get title() { try { return this.fields.select.title.match(/^'(.*)'$/)![1]; } catch (e) { return this.rawTitle; } } get body() { const tagsLine = this.tags.length ? `\n @tags ${this.tags.join(', ')}` : ''; const queryId = this.fields.select.query_id.replace(/'/g, ''); const queryLine = `\n @id ${queryId}`; return ( `CREATE OR REPLACE VIEW rules.${this.viewName} COPY GRANTS\n` + ` COMMENT='${this.summary .replace(/'/g, "\\'") .replace(/^/gm, ' ') .substr(2)}` + `${queryLine}` + `${tagsLine}'\n` + `AS\n` + `SELECT ${Object.entries(this.fields.select) .map(([k, v]) => `${v.replace(/\n/g, '\n ')} AS ${k}`) .join('\n , ')}\n` + `FROM ${this.fields.from}\n` + `WHERE 1=${this.fields.enabled ? '1' : '0'}\n` + ` AND ${this.fields.where}\n;` ); } } export class Suppression extends SQLBackedRule { conditions!: string[]; summary!: string; from!: string; tags!: string[]; constructor(rule: stateTypes.SnowAlertRule) { super(rule); // TODO(anfedorov): why doesn't the super() call ? this.raw = rule; this.isSaving = false; this.isEditing = false; } get target() { return this._raw.target; } load(sql: string) { function stripStart(sql: string): {rest: string; from: string} | null { const headRe = /^SELECT (?:\*|id)\s+FROM ([\s\S]+)\s+WHERE suppressed IS NULL\n/im; const m = sql.match(headRe); return m ? {rest: sql.substr(m[0].length), from: m[1]} : null; } const parsedComment = stripComment(sql); const { summary, decorations: {tags}, } = parseComment(parsedComment.comment); const parsedStart = stripStart(parsedComment.rest) || raise('err0'); const {rest} = parsedStart; const {from} = parsedStart; // hack until string array UI is ready const rulesString = rest.replace(/;\s*$/gm, ''); this.conditions = [rulesString]; this.tags = tags ? tags.split(', ') : []; this.summary = summary; this.from = from; } get title() { return this.isParsed ? this.summary.replace(/\n.*$/g, '') : this.raw.title; } set title(newTitle: string) { this.summary = this.summary.replace(/^[^\n]*/, newTitle); } get body() { const tagsLine = this.tags.length ? `\n @tags ${this.tags.join(', ')}` : ''; return ( `CREATE OR REPLACE VIEW rules.${this.viewName} COPY GRANTS\n` + ` COMMENT='${this.summary .replace(/'/g, "\\'") .replace(/^/gm, ' ') .substr(2)}` + `${tagsLine}'\n` + `AS\n` + `SELECT id\n` + `FROM ${this.from}\n` + `WHERE suppressed IS NULL\n` + `${this.conditions[0]}` + `;` ); } } export type Rule = Query | Suppression | Policy;
the_stack
import React, { Component, ReactNode, ComponentClass, FC } from 'react'; /** * concent types.d.ts file v2.15.13 */ declare const mvoid = '$$concent_void_module_624313307'; type CC_CLASS = '$$CcClass'; type CC_HOOK = '$$CcHook'; type CC_FRAGMENT = '$$CcFrag'; type CC_CUSTOMIZE = '$$CcCust'; type CC_OB = '$$CcOb'; export type MODULE_GLOBAL = '$$global'; export type MODULE_DEFAULT = '$$default'; type MODULE_CC = '$$cc'; export type MODULE_VOID = typeof mvoid; type CcCst = { MODULE_GLOBAL: MODULE_GLOBAL; MODULE_DEFAULT: MODULE_DEFAULT; MODULE_CC: MODULE_CC; MODULE_VOID: MODULE_VOID; MODULE_CC_ROUTER: '$$CONCENT_ROUTER'; AUTO_VAL: Symbol, CC_CLASS: CC_CLASS; CC_HOOK: CC_HOOK; CC_FRAGMENT: CC_FRAGMENT; CC_OB: CC_OB; CC_CUSTOMIZE: CC_CUSTOMIZE; CC_PREFIX: '$$Cc'; CC_DISPATCHER: '$$Dispatcher'; CCSYNC_KEY: typeof Symbol; SIG_FN_START: 10; SIG_FN_END: 11; SIG_FN_QUIT: 12; SIG_FN_ERR: 13; SIG_MODULE_CONFIGURED: 14; SIG_STATE_CHANGED: 15; SIG_ASYNC_COMPUTED_START: 30, SIG_ASYNC_COMPUTED_END: 31, SIG_ASYNC_COMPUTED_ERR: 32, SIG_ASYNC_COMPUTED_BATCH_START: 33, SIG_ASYNC_COMPUTED_BATCH_END: 34, RENDER_NO_OP: 1; RENDER_BY_KEY: 2; RENDER_BY_STATE: 3; FOR_CUR_MOD: 1; FOR_ANOTHER_MOD: 2; // EFFECT_AVAILABLE: 1; // EFFECT_STOPPED: 0; DISPATCH: 'dispatch'; SET_STATE: 'setState'; SET_MODULE_STATE: 'setModuleState'; FORCE_UPDATE: 'forceUpdate'; INVOKE: 'invoke'; SYNC: 'sync'; CATE_MODULE: 'module'; CATE_REF: 'ref'; FN_CU: 'computed'; FN_WATCH: 'watch'; } export type CalledBy = CcCst['DISPATCH'] | CcCst['SET_STATE'] | CcCst['SET_MODULE_STATE'] | CcCst['FORCE_UPDATE'] | CcCst['INVOKE'] | CcCst['SYNC']; export type SigFn = CcCst['SIG_FN_START'] | CcCst['SIG_FN_END'] | CcCst['SIG_FN_QUIT'] | CcCst['SIG_FN_ERR']; export type SigModuleConfigured = CcCst['SIG_MODULE_CONFIGURED']; export type SigStateChanged = CcCst['SIG_STATE_CHANGED']; // export interface IAnyObj { [key: string]: any }; type ValueRange = string | number | boolean | symbol | object | null | undefined; type StrKeys<T extends any> = Exclude<keyof T, symbol | number>; /** * 注意: * IState 能约束 plain json object, 而 IAnyObj 不可以 * const o1: IState = [1]; // error * const o2: IAnyObj = [1]; // ok */ export interface IState { [key: string]: ValueRange; } export interface IAnyObj { [key: string]: any } export interface IAnyFn { (...args: any): any; } export interface IAnyFnPromise { (...args: any): any | Promise<any>; } export interface IAnyFnReturnObj { (...args: any): IAnyObj; } export interface IAnyFnInObj { [key: string]: IAnyFn } export interface IAnyClass { new(...args: any[]): any; } export interface ToggleBoolFn { (...args: any): any; } export interface SyncValueToStateFn { (...args: any): any; } // let user export syncer new type when user define private state export type Syncer<FullState> = FullState extends IAnyObj ? { [key in keyof FullState]: SyncValueToStateFn } : {}; // let user export syncerOfBool new type when user define private state export type SyncerOfBool<FullState> = FullState extends IAnyObj ? { [key in GetBoolKeys<FullState>]: ToggleBoolFn } : {}; type ComputedFn<FnCtx extends IFnCtxBase = IFnCtxBase, S extends any = any> = ( newState: S, oldState: S, fnCtx: FnCtx, ) => any; interface IComputedFnDesc<Fn extends ComputedFn = ComputedFn> { fn: Fn; sort?: number; compare?: boolean; depKeys?: DepKeys; retKeyDep?: boolean; } export interface IReducerFn<S extends IAnyObj = any> { // let configure works well, set actionCtx generic type any (payload: any, moduleState: S, actionCtx: IActionCtx<any, any, any, any, any>): any | Promise<any>; } // !!!use infer export type ArrItemsType<T> = T extends (any[] | readonly any[]) ? ( T extends Array<infer E> ? E : never ) : any; export type ComputedValType<T> = { readonly [K in keyof T]: T[K] extends IAnyFn ? GetPromiseT<T[K]> : (T[K] extends IComputedFnDesc ? GetPromiseT<T[K]['fn']> : never); } // for heping refComputed to infer type export type ComputedValTypeForFn<Fn extends IAnyFn> = { readonly [K in keyof ReturnType<Fn>]: ReturnType<Fn>[K] extends IAnyFn ? GetPromiseT<ReturnType<Fn>[K]> : (ReturnType<Fn>[K] extends IComputedFnDesc ? GetPromiseT<ReturnType<Fn>[K]['fn']> : never); } export type SetupFn = (ctx: ICtxBase) => IAnyObj | void; export type SettingsType<Fn> = Fn extends SetupFn ? (ReturnType<Fn> extends IAnyObj ? ReturnType<Fn> : {}) : {}; /** * inspired by * https://github.com/pirix-gh/ts-toolbelt/blob/master/src/List/Tail.ts */ type C2List<A = any> = ReadonlyArray<A>; type Tail<L extends C2List> = ((...t: L) => any) extends ((head: any, ...tail: infer LTail) => any) ? LTail : never type GetRestItemsType<A extends Array<any>> = Exclude<A, A[0]>; // when set bindCtxToMethod as true, user should use SettingsCType to infer ctx.settings type export type SettingsCType<Fn extends SetupFn, Ctx extends ICtxBase = ICtxBase> = ReturnType<Fn> extends IAnyObj ? ( { [key in keyof ReturnType<Fn>]: ( ReturnType<Fn>[key] extends IAnyFn ? (...p: GetRestItemsType<Tail<Parameters<ReturnType<Fn>[key]>>>) => ReturnType<ReturnType<Fn>[key]> : ReturnType<Fn>[key] ) } ) : {} export type StateType<S> = S extends IAnyFn ? ReturnType<S> : S; type RenderKey = string | number | Array<string | number> | null; export interface IDispatchOptions { /** * force update module state no matter state changed or not, bydefaut is false */ force?: boolean; silent?: boolean; lazy?: boolean; renderKey?: RenderKey; /** * delay broadcast state to other refs */ delay?: number; } /** * 自于 mrc.{xxxx} 调用返回的对象类型 */ export interface ReducerCallerParams { module: string, fnName: string, payload: any, renderKey: any, delay: any, } type ReducerMethod<T, K extends keyof T> = T[K] extends IAnyFn ? ( payload: Parameters<T[K]>[0] extends undefined ? void : Parameters<T[K]>[0], renderKeyOrOptions?: RenderKey | IDispatchOptions, delay?: number, ) => (ReturnType<T[K]> extends Promise<any> ? ReturnType<T[K]> : Promise<ReturnType<T[K]>>) : unknown; /** * 推导模块里来得mrc 调用的单个reducer方法的类型 */ type ReducerCallerMethod<T, K extends keyof T> = T[K] extends IAnyFn ? ( payload: Parameters<T[K]>[0] extends undefined ? void : Parameters<T[K]>[0], renderKeyOrOptions?: RenderKey | IDispatchOptions, delay?: number, ) => ReducerCallerParams : unknown; // ) => ReducerCallerParams<Parameters<T[K]>[0] extends undefined ? void : Parameters<T[K]>[0]> : unknown; export type ReducerType<S extends IAnyObj, Rd = IAnyObj> = Rd extends IAnyObj ? ( Rd['setState'] extends Function ? { readonly [K in keyof Rd]: ReducerMethod<Rd, K> } : ( { readonly [K in keyof Rd]: ReducerMethod<Rd, K>; } & { setState: <P extends Partial<S> = {}>(payload: P, renderKeyOrOptions?: RenderKey | IDispatchOptions, delay?: number) => Promise<P> } )) : {}; type ReducerMethodOfDef<RdFn, S> = RdFn extends IAnyFn ? ( payload: any, moduleState: S, actionCtx: IActionCtxBase, ) => any : unknown; export type ReducerTypeOfDef<S extends IAnyObj, Rd = IAnyObj> = Rd extends IAnyObj ? ( { readonly [K in keyof Rd]: Rd[K] extends ReducerMethodOfDef<Rd[K], S> ? ReducerMethodOfDef<Rd[K], S> : never } ) : {}; /** * 推导模块caller类型的reducer方法集合类型 * 即 ctx.mrc 类型 */ export type ReducerCallerType<T> = T extends IAnyObj ? ( T['setState'] extends Function ? { readonly [K in keyof T]: ReducerCallerMethod<T, K> } : ( { readonly [K in keyof T]: ReducerCallerMethod<T, K> } & { setState: <P = IAnyObj>(payload: P, renderKeyOrOptions?: RenderKey | IDispatchOptions, delay?: number) => { module: string, fnName: 'setState', payload: P, renderKey: any, delay: any, } } )) : {}; // attention here omit Ghosts[number] export type ReducerGhostType<Ghosts, Reducer> = Ghosts extends readonly string[] ? { [key in Ghosts[number]]: Omit<Reducer, Ghosts[number]> } : {}; export interface EvMapBase { [key: string]: any[]; } /** watch all keys changed */ export type TStar = '*'; /** collect key change automatically */ export type TAuto = '-'; export type DepKeys<State extends IAnyObj = IAnyObj> = Array<keyof State> | TStar | TAuto; type DepKeyCollector<State> = (state: State) => any; export type DepKeysOfWatch<State extends IAnyObj = IAnyObj> = DepKeyCollector<State> | Array<keyof State> | TStar | TAuto; // type EvSyncReturn = (event: React.ChangeEvent<HTMLInputElement>) => void; type OnCallBack<EventCbArgs extends any[]> = (...args: EventCbArgs) => void; type GetComputedFn<T> = <FnCtx extends IFnCtxBase = IFnCtxBase>( newState: any, oldState: any, fnCtx: FnCtx, ) => T; interface IDict { [customizedKey: string]: any; // [customizedKey2: number]: any; } interface IDictWithT<T> { [customizedKey: string]: T; // [customizedKey2: number]: any; } export interface IRootBase extends IDict { [mvoid]: any $$global: any; $$default: any; [customizedModuleKey: string]: any; } type PropKey = string | number | symbol; type FnState = IAnyFnReturnObj | IAnyObj; // export function dodo<TA, TB, keyof TA extends keyof TB>(a: TA, b: TB): void; type MyPick<RootState extends IRootBase, ConnectedModules extends keyof IRootBase> = Pick<RootState, ConnectedModules>; type Super<T> = T extends infer U ? U : object; /** * * @param eventName * @param cb * suggest use conditional type to maitain EventCbArgsType * // or type EventCbArgsType<EventName> type ET<EventName> = EventName extends 'foo' ? [string, number] : EventName extends 'bar' ? [string, boolean] : []; */ declare function refCtxOn<EventCbArgs extends any[] = any[]>(eventName: string, cb: OnCallBack<EventCbArgs>): void; declare function refCtxOn<EventCbArgs extends any[] = any[]>(eventDesc: [string, string?], cb: OnCallBack<EventCbArgs>): void; declare function refCtxOn<EventCbArgs extends any[] = any[]>(eventDesc: { name: string, identity?: string }, cb: OnCallBack<EventCbArgs>): void; // this way is better!!! declare function refCtxOn<EvMap extends EvMapBase, EvName extends string>(eventName: EvName, cb: OnCallBack<EvMap[EvName]>): void; declare function refCtxOn<EvMap extends EvMapBase, EvName extends string>(eventDesc: [string, string?], cb: OnCallBack<EvMap[EvName]>): void; declare function refCtxOn<EvMap extends EvMapBase, EvName extends string>(eventDesc: { name: string, identity?: string }, cb: OnCallBack<EvMap[EvName]>): void; type EventDesc = { name: string, identity?: string, canPerform?: (ctx: ICtxBase) => boolean, module?: string, ccClassKey?: string, ccUniqueKey?: string }; declare function refCtxEmit<EventCbArgs extends any[] = any[]>(eventName: string, ...args: EventCbArgs): void; declare function refCtxEmit<EventCbArgs extends any[] = any[]>(eventDesc: [string, string?], ...args: EventCbArgs): void; declare function refCtxEmit<EventCbArgs extends any[] = any[]>(eventDesc: EventDesc, ...args: EventCbArgs): void; // this way is better!!! declare function refCtxEmit<EvMap extends EvMapBase, EvName extends string>(eventName: string, ...args: EvMap[EvName]): void; declare function refCtxEmit<EvMap extends EvMapBase, EvName extends string>(eventDesc: [string, string?], ...args: EvMap[EvName]): void; declare function refCtxEmit<EvMap extends EvMapBase, EvName extends string>(eventDesc: EventDesc, ...args: EvMap[EvName]): void; export interface OffOptions { module?: string; ccClassKey?: string; ccUniqueKey?: string; } declare function refCtxOff(eventName: string, offOptions?: OffOptions): void; declare function refCtxOff(eventDesc: [string, string?], offOptions?: OffOptions): void; declare function refCtxOff(eventDesc: { name: string, identity?: string }, offOptions?: OffOptions): void; export type GetPromiseT<F extends (...args: any) => any> = F extends (...args: any) => Promise<infer T> ? T : ReturnType<F>; /** * * @param type * @param payload * @param renderKey * @param delay * if first arg type is string, user should manually make sure fnName an fn is mapped correctly, if you don not want to do so, you can write code like below * * function aaa(){}; function bbb(){}; type reducerFnType<FnName> = FnName extends 'aaa' ? typeof aaa : FnName extends 'bbb' ? typeof bbb : null; type PayloadType<FnName extends string> = (Parameters<reducerFnType<FnName>>)[0]; type reducerFnResultType<FnName extends string> = ReturnType<reducerFnType<FnName>>; */ type RenderKeyOrOpts = RenderKey | IDispatchOptions; declare function refCtxDispatch<RdFn extends IReducerFn> (type: string, payload?: (Parameters<RdFn>)[0], renderKey?: RenderKeyOrOpts, delay?: number): Promise<GetPromiseT<RdFn>>; declare function refCtxDispatch<RdFn extends IReducerFn> (type: RdFn, payload?: (Parameters<RdFn>)[0], renderKey?: RenderKeyOrOpts, delay?: number): Promise<GetPromiseT<RdFn>>; declare function refCtxDispatch<RdFn extends IReducerFn, FullState extends IAnyObj = {}> (type: { module?: string, fn: RdFn, cb?: (state: FullState) => void }, payload?: (Parameters<RdFn>)[0], renderKey?: RenderKeyOrOpts, delay?: number): Promise<GetPromiseT<RdFn>>; declare function refCtxDispatch<RdFn extends IReducerFn, FullState extends IAnyObj = {}> (type: { module?: string, type: string, cb?: (state: FullState) => void }, payload?: (Parameters<RdFn>)[0], renderKey?: RenderKeyOrOpts, delay?: number): Promise<GetPromiseT<RdFn>>; declare function refCtxDispatch<RdFn extends IReducerFn> (type: [string, RdFn], payload?: (Parameters<RdFn>)[0], renderKey?: RenderKeyOrOpts, delay?: number): Promise<GetPromiseT<RdFn>>; declare function refCtxInvoke<UserFn extends IReducerFn> (fn: UserFn, payload?: (Parameters<UserFn>)[0], renderKey?: RenderKeyOrOpts, delay?: number): Promise<GetPromiseT<UserFn>>; declare function refCtxInvoke<UserFn extends IReducerFn> (fn: UserFn, payload?: (Parameters<UserFn>)[0], renderKey?: RenderKeyOrOpts, delay?: number): Promise<GetPromiseT<UserFn>>; declare function refCtxInvoke<UserFn extends IReducerFn> (fn: { module: string, fn: UserFn }, payload?: (Parameters<UserFn>)[0], renderKey?: RenderKeyOrOpts, delay?: number): Promise<GetPromiseT<UserFn>>; declare function refCtxForceUpdate<FullState = {}>(cb?: (newFullState: FullState) => void, renderKey?: RenderKeyOrOpts, delay?: number): void; declare function refCtxGetConnectWatchedKeys(): { [key: string]: string[] }; declare function refCtxGetConnectWatchedKeys(module: string): string[]; declare function reducerSetState<FullState = {}>(state: Partial<FullState>, cb?: (newFullState: FullState) => void, renderKey?: RenderKeyOrOpts, delay?: number): Promise<IAnyObj | undefined>; type ComputeCb<FullState extends IAnyObj = IAnyObj> = (newState: FullState, oldState: FullState, fnCtx: _IFnCtx<FullState>) => any; export type MultiComputed<FullState extends IAnyObj = IAnyObj> = { [retKey: string]: ComputeCb<FullState> | { fn: ComputeCb<FullState>, depKeys?: DepKeys<FullState>, compare?: boolean, sort?: number, retKeyDep?: boolean, } }; export type MultiComputedFn<State extends IAnyObj = IAnyObj> = (ctx: ICtxBase) => MultiComputed<State>; interface ComputedCbOptions<State extends IAnyObj = IAnyObj> { depKeys?: DepKeys<State>, compare?: boolean, sort?: number, retKeyDep?: boolean } /** * ctx.comptued overloading * define how to compute refComputed */ interface RefCtxComputed<State extends IAnyObj = IAnyObj> { <T extends MultiComputed<State>>(multiComputed: T): ComputedValType<T>; <T extends MultiComputedFn<State>>(multiFn: T): ComputedValTypeForFn<T>; <Key extends string, Fn extends ComputeCb<State>> (retKey: Key, fn: Fn, depKeysOrOpts?: DepKeys<State> | ComputedCbOptions<State>): ComputedValType<{ [key in Key]: Fn }>; <Key extends string, Fn extends ComputeCb<State>> (retKey: Key, fnDesc: { fn: Fn } & ComputedCbOptions<State>): ComputedValType<{ [key in Key]: Fn }>; } /** * 不支持 computedModule 传递参数形如 (ctx)=> cuDesc */ interface RefCtxComputedModule<RootState extends IAnyObj = IAnyObj> { <T extends MultiComputed<RootState[M]>, M extends keyof RootState>(moduleName: M, multiComputed: T): ComputedValType<T>; // <T extends MultiComputedFn<RootState[M]>, M extends keyof RootState>(moduleName: M, multiFn: T): ComputedValTypeForFn<T>; <Key extends string, Fn extends ComputeCb<RootState[M]>, M extends keyof RootState> (moduleName: M, retKey: Key, fn: Fn, depKeysOrOpts?: DepKeys<RootState[M]> | ComputedCbOptions<RootState[M]>): ComputedValType<{ [key in Key]: Fn }>; <Key extends string, Fn extends ComputeCb<RootState[M]>, M extends keyof RootState> (moduleName: M, retKey: Key, fnDesc: { fn: Fn } & ComputedCbOptions<RootState[M]>): ComputedValType<{ [key in Key]: Fn }>; } interface WatchCbOptions<State extends IAnyObj = IAnyObj> { depKeys?: DepKeysOfWatch<State>; /** defalut is true */ compare?: boolean; /** defalut is false */ immediate?: boolean; sort?: number; /** retKeyDep: default is true, when key is same as state key, it will be a dep */ retKeyDep?: boolean; } type WatchCb<FullState extends IAnyObj = IAnyObj> = (newState: FullState, oldState: FullState, fnCtx: _IFnCtx<FullState>) => void; type MultiWatch<FullState extends IAnyObj = IAnyObj> = { [fnKey: string]: WatchCb<FullState> | { fn: WatchCb<FullState>, depKeys?: DepKeys<FullState>, compare?: boolean, immediate?: boolean, retKeyDep?: boolean, } }; export type MultiWatchFn<FullState extends IAnyObj = IAnyObj> = (ctx: ICtxBase) => MultiWatch<FullState>; interface RefCtxWatch<State extends IAnyObj = IAnyObj> { /** * ```js * ctx.watch({ * key1Changed: { * fn:(n, o, f){ * const { key1 } = n; // dep collected; * if(f.isFirstCall)return; * // logic * }, * immediate: true, * } * }); * ``` */ <T extends MultiWatch<State>>(multiWatch: T): void; <T extends MultiWatchFn<State>>(multiWatchFn: T): void; <Key extends string, Fn extends WatchCb<State>>(fnKey: Key, fn: Fn, depKeysOrOpts?: DepKeysOfWatch<State> | WatchCbOptions<State>): void; <Key extends string, Fn extends WatchCb<State>>(fnKey: Key, fnDesc: { fn: Fn } & WatchCbOptions<State>): void; } /** * 不支持 watchModule 传递参数形如 (ctx)=> watchDesc * ```ts * ctx.watchModule('foo', { * key1Change: ({key1})=>console.log(`key1 changed`), * key2Change: { * fn: ({key1})=>console.log(`key1 changed`), * immediate: true, * }, * }); * ``` */ interface RefCtxWatchModule<RootState extends IAnyObj = IAnyObj> { <T extends MultiWatch<RootState[M]>, M extends keyof RootState>(moduleName: M, multiWatch: T): void; // <T extends MultiWatchFn<RootState[M]>, M extends keyof RootState>(moduleName: M, multiWatchFn: T): void; <Fn extends WatchCb<RootState[M]>, M extends keyof RootState> (moduleName: M, fn: Fn, depKeysOrOpts?: DepKeysOfWatch<RootState[M]> | WatchCbOptions<RootState[M]>): void; <Fn extends WatchCb<RootState[M]>, M extends keyof RootState> (moduleName: M, fnDesc: { fn: Fn } & WatchCbOptions<RootState[M]>): void; } type ClearEffect = IAnyFnPromise | IAnyFn | void; type EffectDepKeys = string[] | null; type EffectDepPropKeys = string[] | null; interface DepKeysOptions { depKeys?: EffectDepKeys; /** compare is false by default */ compare?: boolean; /** immediate is true by default */ immediate?: boolean; } interface PropDepKeysOptions { depKeys?: EffectDepPropKeys; /** immediate is true by default */ immediate?: boolean; } // compare default is false, 表示针对object类型的值需不需要比较 // immediate default is true declare function refCtxEffect<RefCtx extends ICtxBase = ICtxBase> (cb: (refCtx: RefCtx, isFirstCall: boolean) => ClearEffect, depKeys?: EffectDepKeys, compare?: boolean, immediate?: boolean): void; declare function refCtxEffect<RefCtx extends ICtxBase = ICtxBase> (cb: (refCtx: RefCtx, isFirstCall: boolean) => ClearEffect, depKeysOpt?: DepKeysOptions): void; declare function refCtxEffectProps<RefCtx extends ICtxBase = ICtxBase> (cb: (refCtx: RefCtx, isFirstCall: boolean) => ClearEffect, depPropKeys?: EffectDepPropKeys, immediate?: boolean): void; declare function refCtxEffectProps<RefCtx extends ICtxBase = ICtxBase> (cb: (refCtx: RefCtx, isFirstCall: boolean) => ClearEffect, depPropKeysOpt?: PropDepKeysOptions): void; interface SyncCb { ( value: any, keyPath: string, syncContext: { event: React.BaseSyntheticEvent, module: string, moduleState: object, fullKeyPath: string, state: object, refCtx: object } ): IAnyObj | boolean; // if module state is not equal full state, you need pass generic type FullState <Val, ModuleState, FullState = {}, RefCtx extends ICtxBase = ICtxBase>( value: Val, keyPath: string, syncContext: { event: React.BaseSyntheticEvent, module: string, moduleState: ModuleState, fullKeyPath: string, state: FullState, refCtx: RefCtx } ): any; } declare function asCb ( value: any, keyPath: string, syncContext: { event: React.BaseSyntheticEvent, module: string, moduleState: object, fullKeyPath: string, state: object, refCtx: object } ): any; // if module state is not equal full state, you need pass generic type FullState declare function asCb<Val, ModuleState, RefState, RefCtx extends ICtxBase = ICtxBase> ( value: Val, keyPath: string, syncContext: { event: React.BaseSyntheticEvent, module: string, moduleState: ModuleState, fullKeyPath: string, state: RefState, refCtx: RefCtx } ): any; interface RefCtxSync { (string: string, value?: SyncCb | any, renderKey?: RenderKeyOrOpts, delay?: string): IAnyFn; (...args: any[]): any; // 支持dom直接绑sync时ts语法正确 <input data-ccsync='name' onChange={sync} /> } ////////////////////////////////////////// // exposed interface ////////////////////////////////////////// /** * use this interface to match ctx type that component only defined belong-module * * concent will build ctx for every instance * get ctx in class : this.ctx * get ctx in function : const ctx = useConcent('foo'); */ export interface ICtxBase { // module: '$$default'; readonly module: PropKey; readonly allModules: string[]; /** component type */ readonly type: CC_CLASS | CC_HOOK; /** component instance type */ readonly insType: CC_FRAGMENT | CC_OB | CC_CUSTOMIZE; readonly ccKey: string; readonly ccClassKey: string; readonly ccUniqueKey: string; readonly initTime: number; readonly renderCount: number; readonly watchedKeys: string[] | TStar | TAuto; readonly privStateKeys: string[]; readonly connect: { [key: string]: string[] | TStar | TAuto }; // ref can rewrite these 4 props by ccOption readonly persistStoredKeys: boolean; readonly storedKeys: string[]; readonly renderKey: string | number; readonly tag: string; readonly mapped: any; readonly stateKeys: string[]; readonly extra: any; readonly staticExtra: any; readonly state: any; readonly unProxyState: any; readonly prevState: any; readonly props: any; readonly prevProps: any; readonly moduleState: any; readonly globalState: any; readonly connectedState: any; readonly refComputed: any; readonly moduleComputed: any; readonly globalComputed: any; readonly connectedComputed: any; readonly moduleReducer: any; readonly globalReducer: any; readonly connectedReducer: any; readonly reducer: any; readonly mr: any; // alias of moduleReducer readonly mrc: any; // alias of moduleReducerCaller readonly mrg: any; // alias of moduleReducerGhost readonly gr: any; // alias of globalReducer readonly cr: any; // alias of connectedReducer readonly r: any; // alias of reducer readonly computed: RefCtxComputed<IAnyObj>; readonly computedModule: RefCtxComputedModule<IAnyObj>; readonly watch: RefCtxWatch<IAnyObj>; readonly watchModule: RefCtxWatchModule<IAnyObj>; readonly effect: typeof refCtxEffect; readonly effectProps: typeof refCtxEffectProps; readonly execute: (filters: RefFilters, handler: IAnyFnPromise) => void; readonly on: typeof refCtxOn; readonly emit: typeof refCtxEmit; readonly off: typeof refCtxOff; readonly dispatch: typeof refCtxDispatch; readonly dispatchLazy: typeof refCtxDispatch; readonly dispatchSilent: typeof refCtxDispatch; readonly lazyDispatch: typeof refCtxDispatch; readonly silentDispatch: typeof refCtxDispatch; readonly getWatchedKeys: () => string[]; readonly getConnectWatchedKeys: typeof refCtxGetConnectWatchedKeys; readonly invoke: typeof refCtxInvoke; readonly invokeLazy: typeof refCtxInvoke; readonly invokeSilent: typeof refCtxInvoke; readonly lazyInvoke: typeof refCtxInvoke; readonly silentInvoke: typeof refCtxInvoke; readonly reactSetState: <P, S, K extends keyof S>( state: ((prevState: Readonly<S>, props: Readonly<P>) => (Pick<S, K> | S | null)) | (Pick<S, K> | S | null), callback?: () => void ) => void; readonly reactForceUpdate: (callback?: () => void) => void; readonly initState: RefCtxInitState<any>; readonly setState: RefCtxSetState; readonly refs: { [key: string]: { current: any } }; /** * get target ref from ctx.refs */ readonly getRef: <T extends any = any>(refName: string) => { current: T } | undefined; /** * can work for both class and function */ readonly useRef: <T extends any = any>(refName: string) => ((reactRef: T) => void); readonly forceUpdate: typeof refCtxForceUpdate; readonly setGlobalState: RefCtxSetState; readonly setModuleState: RefCtxSetModuleState<any>; readonly sync: RefCtxSync; readonly syncer: any; readonly syncerOfBool: any; /** alias of syncerOfBool */ readonly sybo: any; readonly syncBool: (string: string, value?: SyncCb | boolean, renderKey?: RenderKey, delay?: string) => IAnyFn; readonly syncInt: (string: string, value?: SyncCb | number, renderKey?: RenderKey, delay?: string) => IAnyFn; readonly syncAs: (string: string, value?: typeof asCb | any, renderKey?: RenderKey, delay?: string) => any; readonly set: (string: string, value: any, renderKey?: RenderKey, delay?: string) => void; readonly setBool: (string: string, renderKey?: RenderKey, delay?: string) => void; readonly settings: IAnyObj; } interface ICtxBaseP<Props extends any> extends ICtxBase { props: Props; } // 第二位泛型参数默认值设为 any,是为了使用 services/concent useSetup 时类型校验通过 type RefCtxInitState<ModuleState extends IAnyObj = IAnyObj, GlobalState extends IAnyObj = any> = <PrivState extends IAnyObj>(state: PrivState | (() => PrivState)) => Extract<keyof PrivState, keyof ModuleState> extends never // you must make sure that there is no common keys between privState and moduleState ? { state: PrivState & ModuleState, computed: RefCtxComputed<PrivState & ModuleState>, watch: RefCtxWatch<PrivState & ModuleState>, setState: RefCtxSetState<PrivState & ModuleState>, sync: RefCtxSync, syncer: Syncer<PrivState & ModuleState>, syncerOfBool: SyncerOfBool<PrivState & ModuleState>, sybo: SyncerOfBool<PrivState & ModuleState>, ccUniqueKey: string; initTime: number; renderCount: number; globalState: GlobalState; setGlobalState: RefCtxSetState<PrivState & GlobalState>; } : never; type DecideFullState<T1, T2 extends IAnyObj> = T2['__no_anyobj_passed__'] extends '_nap_' ? T1 : T2; /** * ctx.setState overloading */ interface RefCtxSetState<FullState extends IAnyObj = IAnyObj> { <MergedFullState extends IAnyObj = { __no_anyobj_passed__: '_nap_' }>( state: Partial<DecideFullState<FullState, MergedFullState>>, cb?: (newFullState: DecideFullState<FullState, MergedFullState>) => void | null, renderKey?: RenderKeyOrOpts, delay?: number, ): void; <MergedFullState extends IAnyObj = { __no_anyobj_passed__: '_nap_' }>( updater: (prevFullState: DecideFullState<FullState, MergedFullState>, props: any) => Partial<DecideFullState<FullState, MergedFullState>>, renderKey?: RenderKeyOrOpts, delay?: number, ): void; } interface RefCtxSetModuleState<RootState extends IAnyObj = IAnyObj> { <M extends StrKeys<RootState>>( moduleName: M, state: Partial<RootState[M]>, cb?: (newFullState: RootState[M]) => void | null, renderKey?: RenderKeyOrOpts, delay?: number, ): void; <M extends StrKeys<RootState>>( moduleName: M, updater: (prevFullState: RootState[M], props: any) => Partial<RootState[M]>, renderKey?: RenderKeyOrOpts, delay?: number, ): void; } /** * the difference between IRefCtx and ICtx is that * IRefCtx doesn't need to know RootModule */ export interface IRefCtx< Props extends IAnyObj = {}, PrivState extends IAnyObj = {}, ModuleState extends IAnyObj = {}, ModuleReducer extends IAnyObj = {}, ModuleReducerCaller extends IAnyObj = {}, ModuleReducerGhost extends IAnyObj = {}, ModuleComputed extends IAnyObj = {}, Settings extends IAnyObj = {}, RefComputed extends IAnyObj = {}, Mapped extends IAnyObj = {}, // when connect other modules ConnectedState extends IAnyObj = {}, ConnectedReducer extends IAnyObj = {}, ConnectedComputed extends IAnyObj = {}, ExtraTypes extends [IAnyObj, any] | [IAnyObj] = [IAnyObj, any], > extends ICtxBase { readonly props: Props; readonly prevProps: Props; readonly state: PrivState & ModuleState; readonly unProxyState: PrivState & ModuleState; readonly extra: ExtraTypes[0]; readonly staticExtra: ExtraTypes[1] extends undefined ? any : ExtraTypes[1]; readonly prevState: PrivState & ModuleState; readonly moduleState: ModuleState; readonly moduleComputed: ModuleComputed; readonly moduleReducer: ModuleReducer; readonly mr: ModuleReducer;// alias of moduleReducer readonly mrc: ModuleReducerCaller;// alias of moduleReducerCaller readonly mrg: ModuleReducerGhost;// alias of moduleReducerGhost readonly settings: Settings; readonly mapped: Mapped; readonly refComputed: RefComputed; // when connect other modules readonly connectedState: ConnectedState; readonly connectedReducer: ConnectedReducer; readonly cr: ConnectedReducer;// alias of connectedReducer readonly connectedComputed: ConnectedComputed; readonly computed: RefCtxComputed<PrivState & ModuleState>; readonly computedModule: RefCtxComputedModule; readonly watch: RefCtxWatch<PrivState & ModuleState>; readonly watchModule: RefCtxWatchModule; readonly initState: RefCtxInitState<ModuleState>; readonly setState: RefCtxSetState<ModuleState>; readonly setModuleState: RefCtxSetModuleState<any>; readonly syncer: Syncer<ModuleState>; readonly syncerOfBool: { [key in keyof PickBool<ModuleState>]: IAnyFn }; /** alias of syncerOfBool */ readonly sybo: { [key in keyof PickBool<ModuleState>]: IAnyFn }; } export interface IRefCtxWithRoot< RootInfo extends IAnyObj = {}, Props extends IAnyObj = {}, PrivState extends IAnyObj = {}, ModuleState extends IAnyObj = {}, ModuleReducer extends IAnyObj = {}, ModuleReducerCaller extends IAnyObj = {}, ModuleReducerGhost extends IAnyObj = {}, ModuleComputed extends IAnyObj = {}, Settings extends IAnyObj = {}, RefComputed extends IAnyObj = {}, Mapped extends IAnyObj = {}, // when connect other modules ConnectedState extends IAnyObj = {}, ConnectedReducer extends IAnyObj = {}, ConnectedComputed extends IAnyObj = {}, ExtraType extends [IAnyObj, any] | [IAnyObj] = [IAnyObj, any], > extends IRefCtx< Props, PrivState, ModuleState, ModuleReducer, ModuleReducerCaller, ModuleReducerGhost, ModuleComputed, Settings, RefComputed, Mapped, ConnectedState, ConnectedReducer, ConnectedComputed, ExtraType > { readonly globalState: GetSubType<GetSubType<RootInfo, 'state'>, MODULE_GLOBAL>; readonly globalComputed: ComputedValType<GetSubType<GetSubType<RootInfo, 'computed'>, MODULE_GLOBAL>>; readonly watchModule: RefCtxWatchModule<GetSubType<RootInfo, 'state'>>; } export interface ModuleDesc<S extends IState = any> { // recommend define state as () => S, then it can been cloned anytime state: S | (() => S); reducer?: { [key: string]: IReducerFn<S> }; computed?: { [key: string]: ComputedFn<IFnCtxBase, S> | IComputedFnDesc<ComputedFn<IFnCtxBase, S>> }; ghosts?: readonly string[]; watch?: { [key: string]: WatchFn<IFnCtxBase, S> | WatchFnDesc<WatchFn<IFnCtxBase, S>> }; } interface RootModule { [key: string]: ModuleDesc; } type GetSubType<T, K> = K extends keyof T ? T[K] : {}; type GetSubArrType<T, K> = K extends keyof T ? T[K] : []; type GetSubRdType<M extends ModuleDesc> = ReducerType<StateType<M['state']>, GetSubType<M, 'reducer'>>; type GetSubRdCallerType<M extends ModuleDesc> = ReducerCallerType<GetSubType<M, 'reducer'>>; type GetSubRdGhostType<M extends ModuleDesc> = ReducerGhostType<GetSubArrType<M, 'ghosts'>, GetSubRdType<M>>; type GetSubCuType<M extends ModuleDesc> = ComputedValType<GetSubType<M, 'computed'>>; type GetConnState<Mods extends RootModule, Conn extends keyof Mods> = { [key in Conn]: StateType<Mods[key]['state']> } & (IncludeModelKey<Mods, MODULE_GLOBAL> extends true ? {} : { [key in MODULE_GLOBAL]: {} }); type GetConnReducer<Mods extends RootModule, Conn extends keyof Mods> = { [key in Conn]: ReducerType<StateType<Mods[key]['state']>, Mods[key]['reducer']> } & (IncludeModelKey<Mods, MODULE_GLOBAL> extends true ? {} : { [key in MODULE_GLOBAL]: {} }); type GetConnComputed<Mods extends RootModule, Conn extends keyof Mods> = { [key in Conn]: ComputedValType<Mods[key]['computed']> } & (IncludeModelKey<Mods, MODULE_GLOBAL> extends true ? {} : { [key in MODULE_GLOBAL]: {} }); export interface IRefCtxM< RootInfo extends IAnyObj, Props extends IAnyObj, M extends ModuleDesc, Se = {}, RefCu = {}, Extra = {} > extends IRefCtxWithRoot< RootInfo, Props, {}, StateType<M['state']>, GetSubRdType<M>, GetSubRdCallerType<M>, GetSubRdGhostType<M>, GetSubCuType<M>, Se, RefCu, {}, {}, {}, {}, [Extra] > { } export interface IRefCtxMS< RootInfo extends IAnyObj, Props extends IAnyObj, M extends ModuleDesc, St extends IAnyObj = {}, Se = {}, RefCu = {}, Extra = {} > extends IRefCtxWithRoot< RootInfo, Props, St, StateType<M['state']>, GetSubRdType<M>, GetSubRdCallerType<M>, GetSubRdGhostType<M>, GetSubCuType<M>, Se, RefCu, {}, {}, {}, {}, [Extra] > { } export interface IRefCtxS< RootInfo extends IAnyObj, Props extends IAnyObj, St extends IAnyObj = {}, Se = {}, RefCu = {}, Extra = {} > extends IRefCtxWithRoot<RootInfo, Props, St, {}, {}, {}, Se, RefCu, {}, {}, {}, {}, [Extra] > { } export interface IRefCtxMConn< RootInfo extends IAnyObj, Props extends IAnyObj, M extends ModuleDesc, Mods extends RootModule, Conn extends keyof Mods, Se = {}, RefCu = {}, Extra = {} > extends IRefCtxWithRoot< RootInfo, Props, {}, StateType<M['state']>, GetSubRdType<M>, GetSubRdCallerType<M>, GetSubRdGhostType<M>, GetSubCuType<M>, Se, RefCu, {}, GetConnState<Mods, Conn>, GetConnReducer<Mods, Conn>, GetConnComputed<Mods, Conn>, [Extra] > { } export interface IRefCtxMSConn< RootInfo extends IAnyObj, Props extends IAnyObj, M extends ModuleDesc, St extends IAnyObj, Mods extends RootModule, Conn extends keyof Mods, Se = {}, RefCu = {}, Extra = {}, > extends IRefCtxWithRoot< RootInfo, Props, St, StateType<M['state']>, GetSubRdType<M>, GetSubRdCallerType<M>, GetSubRdGhostType<M>, GetSubCuType<M>, Se, RefCu, {}, GetConnState<Mods, Conn>, GetConnReducer<Mods, Conn>, GetConnComputed<Mods, Conn>, [Extra] > { } export interface IRefCtxConn< RootInfo extends IAnyObj, Props extends IAnyObj, Mods extends RootModule, Conn extends keyof Mods, Se = {}, RefCu = {}, Extra = {}, > extends IRefCtxWithRoot< RootInfo, Props, {}, {}, {}, {}, Se, RefCu, {}, GetConnState<Mods, Conn>, GetConnReducer<Mods, Conn>, GetConnComputed<Mods, Conn>, [Extra] > { } // !!! only extract boolean value type's keys type GetBoolKeys<T extends IAnyObj> = { [K in keyof T]: T[K] extends boolean ? K : never }[keyof T]; type PickBool<T extends IAnyObj> = Pick<T, GetBoolKeys<T>>; /** * ================================= * ICtx series start! because ICtx has strict type check, so start with RootState RootReducer RootComputed generic type * ================================= */ export interface ICtx < RootState extends IRootBase = IRootBase, RootReducer extends { [key in keyof RootState]?: any } = IRootBase, RootReducerCaller extends { [key in keyof RootState]?: any } = IRootBase, RootReducerGhost extends { [key in keyof RootState]?: any } = IRootBase, RootCu extends { [key in keyof RootState]?: any } = IRootBase, Props = {}, PrivState = {}, ModuleName extends keyof RootState = MODULE_DEFAULT, // ConnectedModules extends keyof IRootBase = MODULE_VOID, // !!! 配合下面的问题注释掉 ConnectedModules extends keyof RootState = MODULE_VOID, Settings extends IAnyObj = {}, RefComputed extends IAnyObj = {}, Mapped extends IAnyObj = {}, ExtraType extends [any, any] | [any] = [any, any], > extends ICtxBase { readonly props: Props; readonly prevProps: Props; readonly globalState: RootState[MODULE_GLOBAL]; readonly globalComputed: RootCu[MODULE_GLOBAL]; readonly extra: ExtraType[0]; readonly staticExtra: ExtraType[1] extends undefined ? any : ExtraType[1]; readonly computed: RefCtxComputed<PrivState & RootState[ModuleName]>; readonly computedModule: RefCtxComputedModule<RootState>; readonly watch: RefCtxWatch<PrivState & RootState[ModuleName]>; readonly watchModule: RefCtxWatchModule<RootState>; readonly initState: RefCtxInitState<RootState[ModuleName], RootState[MODULE_GLOBAL]>; readonly setState: RefCtxSetState<RootState[ModuleName]>; readonly setModuleState: RefCtxSetModuleState<RootState>; readonly setGlobalState: RefCtxSetState<RootState[MODULE_GLOBAL]>; readonly syncer: Syncer<RootState[ModuleName]>; readonly syncerOfBool: { [key in keyof PickBool<RootState[ModuleName]>]: IAnyFn }; /** alias of syncerOfBool */ readonly sybo: { [key in keyof PickBool<RootState[ModuleName]>]: IAnyFn }; readonly state: PrivState & RootState[ModuleName]; readonly unProxyState: PrivState & RootState[ModuleName]; readonly prevState: PrivState & RootState[ModuleName]; readonly moduleState: RootState[ModuleName]; readonly reducer: RootReducer; readonly r: RootReducer; readonly globalReducer: RootReducer[MODULE_GLOBAL]; readonly gr: RootReducer[MODULE_GLOBAL]; readonly moduleReducer: ModuleName extends keyof RootReducer ? ( RootReducer[ModuleName]['setState'] extends Function ? RootReducer[ModuleName] : RootReducer[ModuleName] & { setState: typeof reducerSetState } ) : {}; // alias of moduleReducer readonly mr: ModuleName extends keyof RootReducer ? RootReducer[ModuleName] : {}; // alias of moduleReducerCaller readonly mrc: ModuleName extends keyof RootReducerCaller ? RootReducerCaller[ModuleName] : {}; readonly mrg: ModuleName extends keyof RootReducerGhost ? ( { [K in keyof ArrItemsType<RootReducerGhost[ModuleName]>]: RootReducer[ModuleName] } ) : {}; readonly moduleComputed: ModuleName extends keyof RootCu ? RootCu[ModuleName] : {}; readonly settings: Settings; /** for user get computed value in ui */ readonly refComputed: RefComputed; readonly mapped: Mapped; // overwrite connectedState , connectedComputed readonly connectedState: Pick<RootState, ConnectedModules | MODULE_GLOBAL>; readonly connectedReducer: Pick<RootReducer, ConnectedModules | MODULE_GLOBAL>; readonly cr: Pick<RootReducer, ConnectedModules | MODULE_GLOBAL>;// alias of connectedReducer readonly connectedComputed: Pick<RootCu, ConnectedModules | MODULE_GLOBAL>; // !!! 目前这样写有问题,例如连接是foo,bar, // 外面推导出的是 Pick<RootReducer, 'foo'> | Pick<RootReducer, 'bar'> // 而不是 Pick<RootReducer, 'foo' | 'bar'> // connectedReducer: ConnectedModules extends keyof RootReducer ? Pick<RootReducer, ConnectedModules> : {}; // connectedComputed: ConnectedModules extends keyof RootCu ? Pick<RootCu, ConnectedModules> : {}; } export interface ICtxCommon< Props = {}, PrivState extends IAnyObj = {}, Settings extends IAnyObj = {}, RefComputed extends IAnyObj = {}, RootState extends IRootBase = IRootBase, Extra extends [any, any] | [any] = [any, any], > extends ICtx< RootState, {}, {}, {}, {}, Props, PrivState, MODULE_DEFAULT, MODULE_VOID, Settings, RefComputed, {}, Extra > { } // this kind of ctx must belong to $$default module // it has no default type as it has not been exposed to user! export interface ICtxDefault < RootState extends IRootBase = IRootBase, RootReducer extends { [key in keyof RootState]?: any } = IRootBase, RootReducerCaller extends { [key in keyof RootState]?: any } = IRootBase, RootReducerGhost extends { [key in keyof RootState]?: any } = IRootBase, RootCu extends { [key in keyof RootState]?: any } = IRootBase, Props = {}, PrivState extends IAnyObj = {}, ModuleName extends Required<MODULE_DEFAULT> = MODULE_DEFAULT, ConnectedModules extends keyof RootState = MODULE_VOID, Settings extends IAnyObj = {}, RefComputed extends IAnyObj = {}, Mapped extends IAnyObj = {}, Extra extends [any, any] | [any] = [any, any], > extends ICtx < RootState, RootReducer, RootReducerCaller, RootReducerGhost, RootCu, Props, PrivState, ModuleName, ConnectedModules, Settings, RefComputed, Mapped, Extra > { // __key_as_hint_your_ctx_is_not_default__: 'your component is belong to $$default module by default, but you give a type Ctx which not belong to $$default module', } type GetFnCtxCommit<ModuleState> = <PS extends Partial<ModuleState>>(partialState: PS) => void; type GetFnCtxCommitCu<ModuleComputed> = <PC extends Partial<ModuleComputed>>(partialComputed: PC) => void; // to constrain IFnCtx interface series shape interface _IFnCtx<FullState extends IAnyObj = IAnyObj> { // 方便 ctx.computed({....}) 定义计算描述体时,可以正确赋值fnCtx类型 retKey: string; callInfo: ICallInfo, /** * is cb been called first time */ isFirstCall: boolean; setted: string[]; changed: string[]; stateModule: string; refModule: string; oldState: FullState; committedState: IAnyObj; deltaCommittedState: IAnyObj; cuVal: IAnyObj; refCtx: ICtxBase; setInitialVal: (initialVal: any) => void; commit: GetFnCtxCommit<FullState>; commitCu: GetFnCtxCommitCu<any>; /** * 总是优化考虑使用 dispatch 替代 dispatchImmediate,确保执行的目标函数里拿到的 moduleState 是落地后的结果 */ dispatch: typeof refCtxDispatch; dispatchImmediate: typeof refCtxDispatch; } export interface IFnCtxBase extends _IFnCtx { refCtx: ICtxBase; } // M, means need module associate generic type export interface IFnCtx<RefCtx extends ICtxBase = ICtxBase, FullState = {}, Computed = {}> extends IFnCtxBase { commit: GetFnCtxCommit<FullState>;// for module computed or watch definition, FullState equivalent ModuleState, Computed equivalent ModuleComputed commitCu: GetFnCtxCommitCu<Computed>; committedState: Partial<FullState>; cuVal: Computed; oldState: FullState; refCtx: RefCtx; // __forCheckRefCtxAndCu__?: RefCtx['moduleComputed'] extends {} ? ( // Computed extends {} ? true : never // ) : ( // Computed extends RefCtx['moduleComputed'] ? true : never // ); } declare class ConcentComponent<P> extends Component { ctx: ICtxBase; constructor(props: Readonly<P>); constructor(props: P, context?: any); } interface IRegBase<P extends IAnyObj, ICtx extends ICtxBase> { module?: PropKey; props?: P; state?: IAnyFnReturnObj | IAnyObj; extra?: any, // assign to ctx.extra in every render period for useConcent , but only time for register staticExtra?: any, // assign to ctx.staticExtra only one time for useConcent and register both watchedKeys?: string[] | TStar | TAuto; storedKeys?: string[]; connect?: any; tag?: string; persistStoredKeys?: boolean; lite?: 1 | 2 | 3 | 4; layoutEffect?: boolean; // work for useConcent only isPropsProxy?: boolean; // work for register only, default false bindCtxToMethod?: boolean; // default false renderKeyClasses?: string[]; compareProps?: boolean; // default true setup?: (refCtx: EnsureEmptySettings<ICtx>) => IAnyObj | void; cuDesc?: MultiComputed | MultiComputedFn | null; // render?: (ctxOrMapped: any) => ReactNode; // work for useConcent, registerHookComp, registerDumb only } // 不把render写在IRegBase里,会导致registerHookComp接口里的联合类型render函数类型失效 // 所以这里单独为CcFrag单独写一个接口 interface IRegBaseFrag<P extends IAnyObj, ICtx extends ICtxBase> extends IRegBase<P, ICtx> { render?: (ctxOrMapped: any) => ReactNode; // work for useConcent, registerHookComp, registerDumb only } interface IRegBaseSt<P extends IAnyObj, ICtx extends ICtxBase, FnState = {}> extends IRegBase<P, ICtx> { state: FnState; // state required } // 加readonly 修饰是为了支持声明connect时用 as const后缀 // @see https://codesandbox.io/s/concent-guide-ts-zrxd5?file=/src/pages/CtxMConn/index.tsx type ConnectSpec<RootState extends IRootBase> = (keyof RootState)[] | readonly (keyof RootState)[] | // !!! currently I do not know how to pass ${moduleName} to evaluate target type in object value // something like (keyof RootState[moduleName] )[] but it is wrong writing { [moduleName in (keyof RootState)]?: TStar | TAuto | string[] }; type TargetKeysInFn<PrivState extends IAnyFnReturnObj> = Exclude<keyof ReturnType<PrivState>, (number | symbol)>; type TargetKeysInObj<PrivState extends IAnyObj> = Exclude<keyof PrivState, (number | symbol)>; // setup 里的 ctx.settings 在初次拿到时是一个空map,此处需要用Omit剔除掉透传的settings来确保类型安全 type EnsureEmptySettings<ICtx extends ICtxBase> = Omit<ICtx, 'settings'> & { settings: {} }; export interface RegisterOptions< P extends IAnyObj, RootState extends IRootBase, ModuleName extends keyof RootState, PrivState extends FnState, ICtx extends ICtxBase = ICtxBase > extends IRegBase<P, ICtx> { module?: ModuleName, state?: PrivState, watchedKeys?: (Extract<keyof RootState[ModuleName], string>)[] | TStar | TAuto; storedKeys?: PrivState extends IAnyFn ? (TargetKeysInFn<PrivState>)[] : (TargetKeysInObj<PrivState>)[] connect?: ConnectSpec<RootState>, setup?: (refCtx: EnsureEmptySettings<ICtx>) => IAnyObj | void; } // only state required interface RegisterOptionsSt< P extends IAnyObj, RootState extends IRootBase, ModuleName extends keyof RootState, PrivState extends FnState, ICtx extends ICtxBase = ICtxBase > extends RegisterOptions<P, RootState, ModuleName, PrivState, ICtx> { state: PrivState; } // only module required interface RegisterOptionsMo< P extends IAnyObj, RootState extends IRootBase, ModuleName extends keyof RootState, PrivState extends FnState, ICtx extends ICtxBase = ICtxBase > extends RegisterOptions<P, RootState, ModuleName, PrivState, ICtx> { module: ModuleName, } // both module、state required interface RegisterOptionsMoSt< P extends IAnyObj, RootState extends IRootBase, ModuleName extends keyof RootState, PrivState extends FnState, ICtx extends ICtxBase = ICtxBase > extends RegisterOptions<P, RootState, ModuleName, PrivState, ICtx> { module: ModuleName, state: PrivState; } type WatchFn<F extends IFnCtxBase = IFnCtxBase, S extends any = any> = (newState: S, oldState: S, fnCtx: F) => void; // declare function watchFn<IFnCtx extends IFnCtxBase>(oldVal: any, newVal: any, fnCtx: IFnCtx): void; type WatchFnDesc<Fn extends WatchFn = WatchFn> = { fn: Fn, compare?: boolean,// default is runtimeVar.watchCompare immediate?: boolean,// default is runtimeVar.watchImmediate depKeys?: DepKeysOfWatch,// default is '-' retKeyDep?: boolean,// default is true } type TypeDesc = { module?: string; type: string; cb?: Function; }; declare function init<T extends IAnyObj = IAnyObj>(moduleState: T): Partial<T>; declare function init<T extends IAnyObj = IAnyObj>(moduleState: T): Promise<Partial<T>>; /** default is true */ export type TriggerOnce = boolean | void; export type ModuleTemplate<S extends IAnyObj = any> = { state: S | (() => S); reducer?: ModuleReducerDef<S>; ghosts?: string[] | readonly string[]; computed?: ModuleComputedDef<S>; watch?: ModuleWatchDef<S>; lifecycle?: ModuleLifeCycleDef<S>; } // for legacy export type ModuleConfig<S extends IAnyObj = any> = ModuleTemplate<S>; export interface ConfOptions { /** 慎用此选项 */ allowDup: boolean; } // returned by createModule api export type RegisteredModule = { /** concent will also keep a symbol('__regModule__') for prevent user creating a fake RegisteredModule */ __regModule__: string; } & ModuleConfig; export interface StoreConfig { [moduleName: string]: ModuleConfig; } export type MidCtx = { calledBy: CalledBy, type: string, payload: any, renderKey: Array<string | number>[], delay: number, ccKey: string, ccUniqueKey: string, committedState: object, sharedState: object | null, refModule: string, module: string, fnName: string, modState: (key: string, value: any) => void, }; export type SigFnData = { sig: SigFn, payload: { isSourceCall: boolean, calledBy: CalledBy, module: string, chainId: number, fn: Function, /** * 可以等同于方法名 */ type: string, } }; export type SigModuleConfiguredData = { sig: SigModuleConfigured, payload: string,//配置了新模块 }; export type SigStateChangedData = { sig: SigStateChanged, payload: { calledBy: CalledBy, type: string, payload: any, committedState: IAnyObj, sharedState: IAnyObj | null, module: string, ccUniqueKey: string, stateSnapshot: IAnyObj, renderKey: Array<string | number>[], } }; export interface PluginOn { (sig: SigFn | SigFn[], callback: (data: SigFnData) => void): void; (sig: SigModuleConfigured, callback: (data: SigModuleConfiguredData) => void): void; (sig: SigStateChanged, callback: (data: SigStateChangedData) => void): void; (sig: string | string[], callback: (data: { sig: string, payload: any }) => void): void; } type PluginName = string; export interface Plugin { install: (on: PluginOn) => { name: PluginName }; } export interface RunOptions { middlewares?: ((midCtx: MidCtx, next: Function) => void)[]; plugins?: Plugin[]; // default is false isHot?: boolean; // default is false isStrict?: boolean; /** * default is false * 是否转发 reducer 错误到 errorHandler 里, * 强烈不建议用户配置 unsafe_moveReducerErrToErrorHandler 为 true,否则reducer错误会被静默掉 * 保留这个参数是为了让老版本的concent工程能够正常工作, */ unsafe_moveReducerErrToErrorHandler?: boolean; log?: boolean; // if print error message with console.error or not, default is true logVersion?: boolean; // if print concent version or not, default is true act?: IAnyFn; // should pass act avoid warning if in test mode, see https://reactjs.org/docs/test-utils.html#act errorHandler?: (err: Error) => void; /** * this kind of error will not lead to app crash, but should let developer know it */ warningHandler?: (err: Error) => void; bindCtxToMethod?: boolean; // default is false /** * default is true * it means no matter state changed or not, if a ref call setState or mr.{method} * it will always been rendered */ alwaysRenderCaller?: boolean; computedCompare?: boolean; // default is false, trigger computed if set watchCompare?: boolean; // default is false, trigger watch if set watchImmediate?: boolean; // default is false reComputed?: boolean; // default is true extractModuleChangedState?: boolean; // default is true extractRefChangedState?: boolean; // default is false /** * default is false * when extractRefChangedState is true, objectValueCompare will effect * -------------------------------------------------------------------- * when objectValueCompare is false, concent treat object value as new value when user set it * * const { obj } = ctx.state; * obj.foo = 'new'; * ctx.setState({obj}); // trigger re-render * * // but if you set objectValueCompare true, you need write immutable style code to trigger re-render * ctx.setState({obj}); // no trigger re-render * ctx.setState({obj:{...obj}}); // trigger re-render */ objectValueCompare?: boolean; nonObjectValueCompare?: boolean; // default is true localStorage?: Record<string, any>; // localStorage lib, in browser it will be window.localStorage by default, in rn, user should pass one /** * currently an async cu fun will be computed to below template in babel: * function asyncFn(_x, _x2, _x3) { * return _asyncFn.apply(this, arguments); * } * so if you want your async cu fn work well after compiled, you must specify async-cu-keys */ asyncCuKeys?: string[], /** * pass immer or limu */ immutLib?: any, } export interface ICallInfo { renderKey: Array<string | number>[]; delay: number; fnName: string; type: string; calledBy: CalledBy; keys: string[]; keyPath: string; } export interface IActionCtxBase<RefState extends any = any> { callInfo: ICallInfo; callerModule: string; module: PropKey; committedStateMap: IAnyObj, committedState: IAnyObj, invoke: typeof refCtxInvoke; lazyInvoke: typeof refCtxInvoke; dispatch: typeof refCtxDispatch; lazyDispatch: typeof refCtxDispatch; rootState: IAnyObj; globalState: any; moduleState: IAnyObj; moduleComputed: IAnyObj; setState: (obj: any, renderKey?: RenderKey, delay?: number) => Promise<any>; refCtx: IAnyObj; refState: RefState; } // constraint RefCtx must be an implement of ICtxBase export interface IActionCtx< RootState extends IRootBase = IRootBase, RootCu extends IRootBase = IRootBase, ModuleName extends keyof RootState = MODULE_VOID, RefCtx extends ICtxBase = ICtxBase, FullState extends IAnyObj = RootState[ModuleName] > extends IActionCtxBase { module: ModuleName; moduleState: RootState[ModuleName]; moduleComputed: ModuleName extends keyof RootCu ? RootCu[ModuleName] : {}; rootState: RootState; globalState: RootState[MODULE_GLOBAL]; setState: <T extends Partial<FullState>>(obj: T, renderKey?: RenderKey, delay?: number) => Promise<T>; refCtx: RefCtx; } // 适用于标记属于default模块的invokeFn的第三位ac参数 export interface IActionCtxDe< RefState extends IAnyObj = IAnyObj > extends IActionCtxBase { setState: <T extends Partial<RefState>>(obj: T, renderKey?: RenderKey, delay?: number) => Promise<T>; refState: RefState; } // 直接传入模块描述体来推导 actionCtx 类型 export interface IActionCtxMod< RootInfo extends IAnyObj, Mod extends ModuleDesc, RefCtx extends ICtxBase = ICtxBase, > extends IActionCtxBase { moduleState: StateType<Mod['state']>; moduleComputed: GetSubCuType<Mod>; rootState: GetSubType<RootInfo, 'state'>; globalState: GetSubType<GetSubType<RootInfo, 'state'>, MODULE_GLOBAL>; setState: <T extends Partial<StateType<Mod['state']>>>(obj: T, renderKey?: RenderKey, delay?: number) => Promise<T>; refCtx: RefCtx; } // IModActionCtx仅为了兼容旧的类型声明,(推荐优先考虑 IActionCtxMod,这样 IActionCtx 前缀能够形成统一词语前缀) export type IModActionCtx< RootInfo extends IAnyObj, Mod extends ModuleDesc, RefCtx extends ICtxBase = ICtxBase, > = IActionCtxMod<RootInfo, Mod, RefCtx>; ////////////////////////////////////////// // exposed top api ////////////////////////////////////////// /** * * @param clearAll default false * @param warningErrForClearAll */ export function clearContextIfHot(clearAll?: boolean, warningErrForClearAll?: string): void; export function run(storeConfig?: StoreConfig | null, runOptions?: RunOptions): void; // register 用于class组件注册,因只有setup在class组件的reg参数里是有意义的,而setup在类组件里使用场景不多 // 所以setup的ctx参数类型不再有泛型方法列表里传入,由用户自己标记,如果不标记则默认为ICtxBase,以便减少register函数的泛型列表长度 export function register( registerOptions: string, ccClassKey?: string, ): (ReactComp: IAnyClass) => IAnyClass; export function register< Props extends IAnyObj, RootState extends IRootBase = IRootBase, ModuleName extends keyof RootState = MODULE_DEFAULT, PrivState extends FnState | NoPrivState = NoPrivState >( registerOptions: PrivState extends NoPrivState ? (ModuleName extends MODULE_DEFAULT ? RegisterOptions<Props, RootState, ModuleName, {}> : RegisterOptionsMo<Props, RootState, ModuleName, {}>) : (ModuleName extends MODULE_DEFAULT ? RegisterOptionsSt<Props, RootState, ModuleName, Exclude<PrivState, NoPrivState>> : RegisterOptionsMoSt<Props, RootState, ModuleName, Exclude<PrivState, NoPrivState>>), ccClassKey?: string, ): (ReactComp: IAnyClass) => IAnyClass; export function connect< Props extends IAnyObj = {}, RootState extends IRootBase = IRootBase, >( connectSpec: ConnectSpec<RootState>, ccClassKey?: string, ): (ReactComp: typeof Component) => ComponentClass<Props>; export type NoMap = 'NoMap'; // no mapProps passed type NoPrivState = 'NoPrivState'; type TMap = IAnyObj | NoMap; export function registerHookComp<Props extends IAnyObj, RefCtx extends ICtxBase = ICtxBase>( registerOptions?: string, ccClassKey?: string, ): (renderFn: (props: RefCtx) => ReactNode) => FC<Props>; // ********* registerOptions 【包含】render时,直接返回组件 ********* /** ====== 无指定所属模块,仅自定义自己的管理状态时 ======*/ export function registerHookComp< Props extends IAnyObj, RefCtx extends ICtxDefault = ICtxDefault, T extends TMap = NoMap, PrivState extends FnState | NoPrivState = NoPrivState >( // 用IRegBaseSt来约束只有state无module传入 registerOptions: (PrivState extends NoPrivState ? IRegBase<Props, RefCtx> : IRegBaseSt<Props, RefCtx, Exclude<PrivState, NoPrivState>>) & (T extends NoMap ? {} : { mapProps: (refCtx: RefCtx) => T; }) & { render: (props: T extends NoMap ? RefCtx : T) => ReactNode }, ccClassKey?: string, ): FC<Props>; export function registerHookComp< Props extends IAnyObj, RefCtx extends ICtxBase, T extends TMap, RootState extends IRootBase, ModuleName extends keyof RootState, PrivState extends FnState | NoPrivState = NoPrivState >( registerOptions: // 约束state,module是否必需传入 (PrivState extends NoPrivState ? (ModuleName extends MODULE_DEFAULT ? RegisterOptions<Props, RootState, ModuleName, {}, RefCtx> : RegisterOptionsMo<Props, RootState, ModuleName, {}, RefCtx>) : (ModuleName extends MODULE_DEFAULT ? RegisterOptionsSt<Props, RootState, ModuleName, Exclude<PrivState, NoPrivState>, RefCtx> : RegisterOptionsMoSt<Props, RootState, ModuleName, Exclude<PrivState, NoPrivState>, RefCtx>) ) & (T extends NoMap ? {} : { mapProps: (refCtx: RefCtx) => T; }) & { render: (props: T extends NoMap ? RefCtx : T) => ReactNode }, ccClassKey?: string, ): FC<Props>; // ----------------------------------------------------------------------------------------------------------------------------------------- // ********* registerOptions 【不包含】render时,返回一个接收render函数作为参数的函数,由函数返回组件 ********* /** ====== 无指定所属模块,仅自定义自己的自己管理状态时 ======*/ export function registerHookComp< Props extends IAnyObj, RefCtx extends ICtxDefault = ICtxDefault, // RefCtx约束为ICtxDefault T extends TMap = NoMap, PrivState extends FnState | NoPrivState = NoPrivState >( // 用IRegBaseSt来约束只有state无module传入 registerOptions: (PrivState extends NoPrivState ? IRegBase<Props, RefCtx> : IRegBaseSt<Props, RefCtx, Exclude<PrivState, NoPrivState>>) & (T extends NoMap ? {} : { mapProps: (refCtx: RefCtx) => T; }), ccClassKey?: string, ): (render: (props: T extends NoMap ? RefCtx : T) => ReactNode) => FC<Props>;//有mapProp时,render函数的参数类型就是mapProps返回类型 export function registerHookComp< Props extends IAnyObj, RefCtx extends ICtxBase, T extends TMap, RootState extends IRootBase, ModuleName extends keyof RootState, PrivState extends FnState | NoPrivState = NoPrivState >( registerOptions: // 约束state,module是否必需传入 (PrivState extends NoPrivState ? (ModuleName extends MODULE_DEFAULT ? RegisterOptions<Props, RootState, ModuleName, {}, RefCtx> : RegisterOptionsMo<Props, RootState, ModuleName, {}, RefCtx>) : (ModuleName extends MODULE_DEFAULT ? RegisterOptionsSt<Props, RootState, ModuleName, Exclude<PrivState, NoPrivState>, RefCtx> : RegisterOptionsMoSt<Props, RootState, ModuleName, Exclude<PrivState, NoPrivState>, RefCtx>) ) & (T extends NoMap ? {} : { mapProps: (refCtx: RefCtx) => T; }), ccClassKey?: string, ): (render: (props: T extends NoMap ? RefCtx : T) => ReactNode) => FC<Props>; // 除了返回组件是ClassComponent,registerDumb效果和registerHookComp一样 export function registerDumb<Props extends IAnyObj = {}, RefCtx extends ICtxBase = ICtxBase>( registerOptions?: string, ccClassKey?: string, ): (renderFn: (props: RefCtx) => ReactNode) => ComponentClass<Props>; // ********* registerOptions 【包含】render时,直接返回组件 ********* /** ====== 无指定所属模块,仅自定义自己的自己管理状态时 ======*/ export function registerDumb< Props extends IAnyObj, RefCtx extends ICtxDefault = ICtxDefault, // RefCtx约束为ICtxDefault T extends TMap = NoMap, PrivState extends FnState | NoPrivState = NoPrivState >( // 用IRegBaseSt来约束只有state无module传入 registerOptions: (PrivState extends NoPrivState ? IRegBase<Props, RefCtx> : IRegBaseSt<Props, RefCtx, Exclude<PrivState, NoPrivState>>) & (T extends NoMap ? {} : { mapProps: (refCtx: RefCtx) => T; }) & { render: (props: T extends NoMap ? RefCtx : T) => ReactNode }, ccClassKey?: string, ): ComponentClass<Props>; export function registerDumb< Props extends IAnyObj, RefCtx extends ICtxBase, T extends TMap, RootState extends IRootBase, ModuleName extends keyof RootState, PrivState extends FnState | NoPrivState = NoPrivState >( registerOptions: // 约束state,module是否必需传入 (PrivState extends NoPrivState ? (ModuleName extends MODULE_DEFAULT ? RegisterOptions<Props, RootState, ModuleName, {}, RefCtx> : RegisterOptionsMo<Props, RootState, ModuleName, {}, RefCtx>) : (ModuleName extends MODULE_DEFAULT ? RegisterOptionsSt<Props, RootState, ModuleName, Exclude<PrivState, NoPrivState>, RefCtx> : RegisterOptionsMoSt<Props, RootState, ModuleName, Exclude<PrivState, NoPrivState>, RefCtx>) ) & (T extends NoMap ? {} : { mapProps: (refCtx: RefCtx) => T; }) & { render: (props: T extends NoMap ? RefCtx : T) => ReactNode }, ccClassKey?: string, ): ComponentClass<Props>; // ----------------------------------------------------------------------------------------------------------------------------------------- // ********* registerOptions 【不包含】render时,返回一个接收render函数作为参数的函数,由函数返回组件 ********* /** ====== 无指定所属模块,仅自定义自己的自己管理状态时 ======*/ export function registerDumb< Props extends IAnyObj, RefCtx extends ICtxDefault = ICtxDefault, // RefCtx约束为ICtxDefault T extends TMap = NoMap, PrivState extends FnState | NoPrivState = NoPrivState >( // 用IRegBaseSt来约束只有state无module传入 registerOptions: (PrivState extends NoPrivState ? IRegBase<Props, RefCtx> : IRegBaseSt<Props, RefCtx, Exclude<PrivState, NoPrivState>>) & (T extends NoMap ? {} : { mapProps: (refCtx: RefCtx) => T; }), ccClassKey?: string, ): (render: (props: T extends NoMap ? RefCtx : T) => ReactNode) => ComponentClass<Props>;//有mapProp时,render函数的参数类型就是mapProps返回类型 export function registerDumb< Props extends IAnyObj, RefCtx extends ICtxBase, T extends TMap, RootState extends IRootBase, ModuleName extends keyof RootState, PrivState extends FnState | NoPrivState = NoPrivState >( registerOptions: // 约束state,module是否必需传入 (PrivState extends NoPrivState ? (ModuleName extends MODULE_DEFAULT ? RegisterOptions<Props, RootState, ModuleName, {}, RefCtx> : RegisterOptionsMo<Props, RootState, ModuleName, {}, RefCtx>) : (ModuleName extends MODULE_DEFAULT ? RegisterOptionsSt<Props, RootState, ModuleName, Exclude<PrivState, NoPrivState>, RefCtx> : RegisterOptionsMoSt<Props, RootState, ModuleName, Exclude<PrivState, NoPrivState>, RefCtx>) ) & (T extends NoMap ? {} : { mapProps: (refCtx: RefCtx) => T; }), ccClassKey?: string, ): (render: (props: T extends NoMap ? RefCtx : T) => ReactNode) => ComponentClass<Props>; export function connectDumb<Props extends IAnyObj = {}, RootState extends IRootBase = IRootBase, RefCtx extends ICtxBase = ICtxBase>( connectSpec: ConnectSpec<RootState>, ccClassKey: string, ): (render: (props: RefCtx) => ReactNode) => ComponentClass<Props>; // user decide RefCtx type is which one of RefCtx series, default is ICtxBase export function useConcent<Props extends IAnyObj = IAnyObj, RefCtx extends ICtxBase = ICtxBaseP<Props>>( registerOptions?: string, ccClassKey?: string, ): RefCtx; export function useConcent< Props extends IAnyObj, RefCtx extends ICtxBase, T extends IAnyObj | NoMap = NoMap, PrivState extends FnState | NoPrivState = NoPrivState >( registerOptions: (PrivState extends NoPrivState ? IRegBase<Props, RefCtx> : IRegBaseSt<Props, RefCtx, Exclude<PrivState, NoPrivState>>) & (T extends NoMap ? {} : { mapProps: (refCtx: RefCtx) => T }), ccClassKey?: string, ): RefCtx; export function useConcent< Props extends IAnyObj, RefCtx extends ICtxBase, T extends IAnyObj | NoMap, RootState extends IRootBase, ModuleName extends keyof RootState, PrivState extends FnState | NoPrivState = NoPrivState >( registerOptions: // 约束state,module是否必需传入 (PrivState extends NoPrivState ? (ModuleName extends MODULE_DEFAULT ? RegisterOptions<Props, RootState, ModuleName, {}, RefCtx> : RegisterOptionsMo<Props, RootState, ModuleName, {}, RefCtx>) : (ModuleName extends MODULE_DEFAULT ? RegisterOptionsSt<Props, RootState, ModuleName, Exclude<PrivState, NoPrivState>, RefCtx> : RegisterOptionsMoSt<Props, RootState, ModuleName, Exclude<PrivState, NoPrivState>, RefCtx>) // 下面写法是不对的,需要如上使用Exclude排除掉 // (ModuleName extends MODULE_DEFAULT ? RegisterOptionsSt<Props, RootState, ModuleName, PrivState, RefCtx> : RegisterOptionsMoSt<Props, RootState, ModuleName, PrivState, RefCtx>) ) & (T extends NoMap ? {} : { mapProps: (refCtx: RefCtx) => T }), ccClassKey?: string, ): RefCtx; /** * 配置模块到concent模块池,区别于 run 接口集中式的配置,configureModule可以在 run 之前或之后新增模块到concent模块池 * @param moduleName * @param moduleConfig */ declare function configureModule(moduleName: string, moduleConfig: ModuleConfig): void; declare function configureModule(storeConfig: StoreConfig, confOptions?: ConfOptions): void; /** 用于辅助 defineModule 方法推导出类型 */ interface ModuleConfigDef< S extends IAnyObj = IAnyObj, Rd extends ModuleReducerDef<S> = ModuleReducerDef<S>, Cu extends ModuleComputedDef<S> = ModuleComputedDef<S>, Wa extends ModuleWatchDef<S> = ModuleWatchDef<S>, Li extends ModuleLifeCycleDef<S> = ModuleLifeCycleDef<S>, Go extends string[] = string[] > { state: S | (() => S); reducer?: Rd; computed?: Cu; watch?: Wa; lifecycle?: Li; ghosts?: Go; } export type ModuleReducerDef<S extends IState = IState> = { [key: string]: IReducerFn<S> }; export type ModuleComputedDef<S extends IState = IState> = { [key: string]: ComputedFn<IFnCtxBase, S> | IComputedFnDesc<ComputedFn<IFnCtxBase, S>> }; export type ModuleWatchDef<S extends IState = IState> = { [retKey: string]: WatchFn<IFnCtxBase, S> | WatchFnDesc<WatchFn<IFnCtxBase, S>> }; export type ModuleLifeCycleDef<S extends IState = IState> = { initState?: typeof init; // legency for ModuleConfig.init initStateDone?: (dispatch: IDispatch, moduleState: S) => any; // legency for ModuleConfig.initPost // insteand of initState and initStateDone, using bellow methods is better way // because you can put the logic to reducer loaded?: (dispatch: IDispatch, moduleState: S) => void; // return triggerOnce, default is true, // that means mounted will only been called one time if match the condition mounted?: (dispatch: IDispatch, moduleState: S) => TriggerOnce; willUnmount?: (dispatch: IDispatch, moduleState: S) => TriggerOnce; }; /** * 定义模块配置,此函数仅用于辅助单文件定义model时,方便向对象体注入类型 * defineModule 返回的对象依然需要交给run函数执行后才能够被使用 * * ```js * import { defineModule } from 'concent'; * const modelDef = defineModule({ * state: { a:1, b:2 }; * reducer: { * // 此处 moduleState actionCtx 将获得类型 * xxAction(payload, moduleState, actionCtx){} * } * computed: { * // 此处 newState oldState fnCtx 将获得类型 * xxAction(newState, oldState, fnCtx){} * } * watch: { * // 此处 newState oldState fnCtx 将获得类型 * xxChanged(newState, oldState, fnCtx){} * } * lifecycle: { * willUnmount(dispatch, moduleState){} * }; // lifecycle 下的所有方法获得类型 * ghosts: []; // 将被约束为 reducer keys * }); * ``` * @param moduleConfig * @return moduleDef */ export declare function defineModule< // 此处不约束 S 为 IState,否则会导致调用 defineModule 传入真正的state泛型类型时 ts报错 Type 'YourRealState' does not satisfy the constraint 'IState' S extends IAnyObj = any, Rd extends ModuleReducerDef<S> = ModuleReducerDef<S>, Cu extends ModuleComputedDef<S> = ModuleComputedDef<S>, Wa extends ModuleWatchDef<S> = ModuleWatchDef<S>, Li extends ModuleLifeCycleDef<S> = ModuleLifeCycleDef<S>, Go extends Array<Exclude<keyof Rd, number | symbol>> = Array<any>, > (moduleConfig: ModuleConfigDef<S, Rd, Cu, Wa, Li, Go>): { state: S; reducer: 'reducer' extends keyof ModuleConfigDef ? Rd : {}; /** * alias of reducer,方便书写 dispatch 调用 * * @example * ```js * const m = defineModule({ * state: { a:1, b:2 }; * reducer: { * xxAction(payload, moduleState, ac){ * // 等同于 ac.dispatch(m.reducer.anotherAction); * await ac.dispatch(m.r.anotherAction); * }, * anotherAction(payload, moduleState, ac){ * ac.dispatch(m.r.); * }, * } * }); *``` */ r: 'reducer' extends keyof ModuleConfigDef ? Rd : {}; computed: 'computed' extends keyof ModuleConfigDef ? Cu : {}; watch: 'watch' extends keyof ModuleConfigDef ? Wa : {}; lifecycle: 'lifecycle' extends keyof ModuleConfigDef ? Li : {}; ghosts: 'ghosts' extends keyof ModuleConfigDef ? Go : []; }; export const configure: typeof configureModule; export function cloneModule(newModule: string, existingModule: string, overwriteModuleConfig?: ModuleConfig): void; export function setState<RootState, ModuleState>(moduleName: keyof RootState, state: Partial<ModuleState>, renderKey?: RenderKey, delay?: number): void; export function setGlobalState<GlobalState>(state: Partial<GlobalState>): void; export function getGlobalState<RootState extends IRootBase = IRootBase>(): RootState['$$global']; // 放弃这种写法,拆为下面两个,方便外界调用时可直接通过泛型参数数量来确定返回类型 // export function getState<RootState extends IAnyObj = IRootBase, M extends StrKeys<RootState> = undefined> // (moduleName?: M): M extends undefined ? RootState : RootState[M]; export function getState<RootState extends IRootBase = IRootBase, M extends StrKeys<RootState> | Empty = undefined> (moduleName: M): (M extends StrKeys<RootState> ? RootState[M] : RootState); /** * 适用于不需要感知 RootState 类型,直接返回用户的定义模块状态的场景 * @param moduleName */ export function getState<State extends IAnyObj = IAnyObj>(moduleName: string): State; export function getState<RootState extends IRootBase = IRootBase>(): RootState; export function getComputed<RootCu extends IAnyObj, M extends StrKeys<RootCu>>(moduleName: M): RootCu[M]; /** * 适用于不需要感知 RootCu 类型,直接返回用户的定义模块计算结果的场景 * @param moduleName */ export function getComputed<Cu>(moduleName: string): Cu; /** * 不传递模块名,直接返回整个 RootCu */ export function getComputed<RootCu extends IRootBase = IRootBase>(): RootCu; /** * for printing cu object in console as plain json object */ export function debugComputed<T>(moduleName?: string): T; export function getGlobalComputed<T>(): T; export function set(keyPath: string, value: any, renderKey?: RenderKey, delay?: number): void; // only work for top api cc.dispatch interface IDispatchExtra { ccClassKey?: string; ccKey?: string; throwError?: boolean; refModule?: string; } type GetDispatchRetType<T> = T extends IAnyFn ? GetPromiseT<T> : any; type GetDispatchPayloadType<T> = T extends IAnyFn ? Parameters<T>[0] : any; declare function ccDispatch<T extends string | IAnyFn | TypeDesc, P extends GetDispatchPayloadType<T>>( type: T, payload?: P, renderKey?: RenderKey | IDispatchOptions, delay?: number, extra?: IDispatchExtra ): Promise<GetDispatchRetType<T>>; export type IDispatch = typeof ccDispatch; export declare const dispatch: IDispatch; export declare const emit: typeof refCtxEmit; export declare const off: typeof refCtxOff; export function execute(ccClassKey: string, ...args: any): void; export function executeAll(...args: any): void; export function appendState(moduleName: string, state: IAnyObj): void; type DefOptions = { depKeys?: DepKeys, compare?: boolean, lazy?: boolean, sort?: number, retKeyDep?: boolean }; export function defComputedVal<CuRet>(ret: CuRet): IComputedFnDesc<GetComputedFn<CuRet>>; export function defComputed<V extends IAnyObj, CuRet, F extends IFnCtxBase = IFnCtxBase> (fn: (newState: V, oldState: V, fnCtx: F) => CuRet, defOptions?: DepKeys | DefOptions): IComputedFnDesc<GetComputedFn<CuRet>>; export function defComputed<CuRet> (fn: (newState: IAnyObj, oldState: IAnyObj, fnCtx: IFnCtxBase) => CuRet, defOptions?: DepKeys | DefOptions): IComputedFnDesc<GetComputedFn<CuRet>>; type DefLazyOptions = { depKeys?: DepKeys, compare?: boolean, sort?: number, retKeyDep?: boolean }; export function defLazyComputed<V extends IAnyObj, CuRet, F extends IFnCtxBase = IFnCtxBase> (fn: (newState: V, oldState: V, fnCtx: F) => CuRet, defOptions?: DepKeys | DefLazyOptions): IComputedFnDesc<GetComputedFn<CuRet>>; export function defLazyComputed<CuRet> (fn: (newState: IAnyObj, oldState: IAnyObj, fnCtx: IFnCtxBase) => CuRet, defOptions?: DepKeys | DefLazyOptions): IComputedFnDesc<GetComputedFn<CuRet>>; export function defWatch<V extends IAnyObj = {}, F extends IFnCtxBase = IFnCtxBase> (fn: (newState: V, oldState: V, fnCtx: F) => void | boolean, defOptions?: DepKeysOfWatch<V> | WatchCbOptions<V>): WatchFnDesc; export declare const cst: CcCst; export class CcFragment<P extends IAnyObj, Ctx extends ICtxBase> extends Component<{ register: IRegBaseFrag<P, Ctx>, ccKey?: string, ccClassKey?: string, ccOption?: { storedKeys?: string[], renderKey?: string | number, persistStoredKeys?: boolean, tag?: string } }, any> { } /** * [state, computed, reducers] * reducers:{ mr: IAnyFnInObj, cr: IAnyFnInObj, r: IAnyFnInObj } */ type ObRenderFn = (obTuple: [IAnyObj, IAnyObj, { mr: IAnyFnInObj, cr: IAnyFnInObj, r: IAnyFnInObj }]) => React.ReactElement; export function Ob(props: { classKey?: string, module?: string, connect?: string | string[], render: ObRenderFn, children?: ObRenderFn }): React.FC; /** * user specify detail type when use * * import {reducer} from 'concent'; * import { RootReducer } from 'types'; * * const typedReducer = reducer as RootReducer; */ export declare const reducer: IAnyFnInObj; export interface RefFilters { /** * find refs that mountStatus is belong (NOT_MOUNT, MOUNTED) or (MOUNTED) * default is false, means only find out MOUNTED refs */ includeNotMount?: boolean; tag?: string; ccClassKey?: string; moduleName?: string; } type ccClassKey = string; export function getRefs<Ctx extends ICtxBase>(filters?: RefFilters | ccClassKey): { ctx: Ctx }[]; export function getRef<Ctx extends ICtxBase>(filters?: RefFilters | ccClassKey): ({ ctx: Ctx } | undefined); /** * * @param newModuleName * @param existingModuleName * @param overwriteModuleConfig overwriteModuleConfig will been merged to existingModuleConfig */ export function cloneModule(newModuleName: string, existingModuleName: string, overwriteModuleConfig?: ModuleConfig): void; export type Empty = void | null | undefined; export type MouseEv = React.MouseEvent<HTMLElement>; export type VoidPayload = Empty | MouseEv; interface FnPayload { /** * 【重载1】如果 fn 的第一位参数不是 VoidPayload,则会进入 unknown 逻辑导致类型推导出错 * 以便让用户必须传递具体的 payload 参数,让ts进入其他重载,便有机会检查 传递的payload类型是否符合定义的payload类型 */ <F extends IReducerFn>(fn: F): Parameters<F>[0] extends VoidPayload ? [F] : unknown; /** * 【重载2】 */ <F extends IReducerFn, P extends Parameters<F>[0]>(fn: F, payload: P): [F, P]; <F extends IReducerFn, P extends Parameters<F>[0]>(fn: F, payload: P, renderKey: RenderKeyOrOpts): [F, P, RenderKeyOrOpts]; <F extends IReducerFn, P extends Parameters<F>[0]>(fn: F, payload: P, renderKey: RenderKeyOrOpts, delay: number): [F, P, RenderKeyOrOpts, number]; } /** * 辅助检查 fn 类型和 payload 类型是否相匹配 */ export const fnPayload: FnPayload; ////////////////////////////////////////////////// // type helper ////////////////////////////////////////////////// export type IncludeModelKey<Models, ModelKey> = ModelKey extends keyof Models ? true : false; export type GetRootState<Models extends { [key: string]: ModuleConfig<any> }> = { [key in keyof Models]: StateType<Models[key]['state']> } & { [cst.MODULE_VOID]: {} } & (IncludeModelKey<Models, MODULE_DEFAULT> extends true ? {} : { [cst.MODULE_DEFAULT]: {} }) & (IncludeModelKey<Models, MODULE_GLOBAL> extends true ? {} : { [cst.MODULE_GLOBAL]: {} }); export type GetRootReducer<Models extends { [key: string]: ModuleConfig<any> }> = { [key in keyof Models]: 'reducer' extends keyof Models[key] ? (Models[key]['reducer'] extends IAnyObj ? ReducerType<StateType<Models[key]['state']>, Models[key]['reducer']> : {}) : {}; } & { [cst.MODULE_VOID]: {} } & (IncludeModelKey<Models, MODULE_DEFAULT> extends true ? {} : { [cst.MODULE_DEFAULT]: {} }) & (IncludeModelKey<Models, MODULE_GLOBAL> extends true ? {} : { [cst.MODULE_GLOBAL]: {} }); export type GetRootReducerCaller<Models extends { [key: string]: ModuleConfig<any> }> = { [key in keyof Models]: 'reducer' extends keyof Models[key] ? (Models[key]['reducer'] extends IAnyObj ? ReducerCallerType<Models[key]['reducer']> : {}) : {}; } & { [cst.MODULE_VOID]: {} } & (IncludeModelKey<Models, MODULE_DEFAULT> extends true ? {} : { [cst.MODULE_DEFAULT]: {} }) & (IncludeModelKey<Models, MODULE_GLOBAL> extends true ? {} : { [cst.MODULE_GLOBAL]: {} }); export type GetRootReducerGhost<Models extends { [key: string]: ModuleConfig<any> }, RootReducer extends { [K in keyof Models]: any }> = { [key in keyof Models]: 'ghosts' extends keyof Models[key] ? (Models[key]['ghosts'] extends string[] ? { [ghostKey in ArrItemsType<Models[key]['ghosts']>]: RootReducer[key] } : {}) : {}; } & { [cst.MODULE_VOID]: {} } & (IncludeModelKey<Models, MODULE_DEFAULT> extends true ? {} : { [cst.MODULE_DEFAULT]: {} }) & (IncludeModelKey<Models, MODULE_GLOBAL> extends true ? {} : { [cst.MODULE_GLOBAL]: {} }); export type GetRootComputed<Models extends { [key: string]: ModuleConfig<any> }> = { [key in keyof Models]: 'computed' extends keyof Models[key] ? (Models[key]['computed'] extends IAnyObj ? ComputedValType<Models[key]['computed']> : {}) : {}; } & { [cst.MODULE_VOID]: {} } & (IncludeModelKey<Models, MODULE_DEFAULT> extends true ? {} : { [cst.MODULE_DEFAULT]: {} }) & (IncludeModelKey<Models, MODULE_GLOBAL> extends true ? {} : { [cst.MODULE_GLOBAL]: {} }); type AnyOrEmpty = any | void | undefined | null; export type CallTargetParams = ReducerCallerParams | [reducerFn: IAnyFn] | [reducerFn: IAnyFn, payload: AnyOrEmpty] | [reducerFn: IAnyFn, payload: AnyOrEmpty, renderKeyOrOpts: RenderKeyOrOpts] | [reducerFn: IAnyFn, payload: AnyOrEmpty, renderKeyOrOpts: RenderKeyOrOpts, delay: number]; export declare function bindCcToMcc(key: string): void; export declare function bindCcToWindow(custPrefix: string): void; declare type DefaultExport = { bindCcToMcc: typeof bindCcToMcc, bindCcToWindow: typeof bindCcToWindow, ccContext: any, clearContextIfHot: typeof clearContextIfHot, run: typeof run, register: typeof register, connect: typeof connect, registerDumb: typeof registerDumb, connectDumb: typeof connectDumb, registerHookComp: typeof registerHookComp, useConcent: typeof useConcent, configure: typeof configureModule, defineModule: typeof defineModule, cloneModule: typeof cloneModule, set: typeof set, setState: typeof setState, setGlobalState: typeof setGlobalState, getState: typeof getState, getGlobalState: typeof getGlobalState, getComputed: typeof getComputed, debugComputed: typeof debugComputed, getGlobalComputed: typeof getGlobalComputed, getRefs: typeof getRefs, getRef: typeof getRef, dispatch: typeof dispatch, reducer: typeof reducer, emit: typeof refCtxEmit, off: typeof refCtxOff, execute: typeof execute, executeAll: typeof executeAll, appendState: typeof appendState, defComputed: typeof defComputed, defLazyComputed: typeof defLazyComputed, defComputedVal: typeof defComputedVal, defWatch: typeof defWatch, fnPayload: FnPayload, cst: typeof cst, CcFragment: typeof CcFragment, Ob: typeof Ob, } declare let defaultExport: DefaultExport; export default defaultExport; export as namespace cc;
the_stack
import { base64, str2buf, buf2str } from './utils'; export interface AccessToken { expires?: number; access_token?: string; } export interface GoogleDriveUserAccount extends AccessToken { type: 'authorized_user'; // User Credential fields // (These typically come from gcloud auth.) client_id: string; client_secret: string; refresh_token: string; } export interface GoogleDriveServiceAccount extends AccessToken { type: 'service_account'; // Service Account fields client_email: string; private_key_id: string; private_key: string; token_uri: string; project_id: string; } export type GoogleDriveAccount = GoogleDriveUserAccount | GoogleDriveServiceAccount; export interface GoogleDriveConfig { // secure random string that provides app-level security secret: string; accountRotation: number; accountCandidates: number; accounts: (GoogleDriveAccount | string)[]; userURL: (user: string) => Promise<string>; static: (pathname: string) => Promise<string>; } interface TokenResponse { access_token: string; token_type: string; refresh_token: string; expires_in: number; } interface GDFileList { nextPageToken?: string; files?: any; drives?: any; } export interface SearchOptions { query: string; drives?: string[]; encrypted_page_token?: string | null; } export interface User { name: string; pass: string; drives_white_list?: string[]; drives_black_list?: string[]; } export class GoogleDrive { constructor(private config: GoogleDriveConfig) {} async getUser(user: string): Promise<User> { return JSON.parse( buf2str(await this.decrypt('user', await (await fetch(await this.config.userURL(user))).arrayBuffer())), ); } async download(account: GoogleDriveAccount | null, id: string, range = ''): Promise<Response> { const url = new URL(`https://www.googleapis.com/drive/v3/files/${id}?alt=media`); if (account == null) { account = await this.pickAccount(); } return fetch(url.toString(), { headers: { Range: range, Authorization: `Bearer ${await this.accessToken(account)}`, }, }); } async file(account: GoogleDriveAccount | null, id: string): Promise<any> { if (account == null) { account = await this.pickAccount(); } const token = await this.accessToken(account); const [file, drive] = await Promise.all([ (async () => { const url = new URL(`https://www.googleapis.com/drive/v3/files/${id}`); url.searchParams.set('supportsAllDrives', 'true'); url.searchParams.set('fields', 'id,name,kind,mimeType,size,modifiedTime,parents,md5Checksum'); return ( await fetch(url.toString(), { headers: { Authorization: `Bearer ${token}`, }, }) ).json(); })(), (async () => { const url = new URL(`https://www.googleapis.com/drive/v3/drives/${id}`); url.searchParams.set('fields', 'id,name,kind'); return ( await fetch(url.toString(), { headers: { Authorization: `Bearer ${token}`, }, }) ).json(); })(), ]); if (!drive.error) { file.kind = drive.kind; file.name = drive.name; } return file; } async search(account: GoogleDriveAccount | null, options: SearchOptions): Promise<GDFileList | null> { let pageTokenMap: Record<string, string> = {}; let { query, drives, encrypted_page_token } = options; if (account == null && typeof encrypted_page_token === 'string' && encrypted_page_token !== '') { const data = JSON.parse( buf2str(await this.decrypt('pageToken', base64.RAWURL.decode(encrypted_page_token))), ); account = data.account; pageTokenMap = data.pageTokenMap; } if (account == null) { account = await this.pickAccount(); } const url = new URL('https://www.googleapis.com/drive/v3/files'); url.searchParams.set('includeItemsFromAllDrives', 'true'); url.searchParams.set('supportsAllDrives', 'true'); url.searchParams.set('fields', 'nextPageToken,files(id,name,mimeType,size,modifiedTime,parents)'); url.searchParams.set('pageSize', '100'); const clauses: string[] = []; query .replace(/\\/, '\\\\') .replace(/'/, "\\'") .split(/\s+/) .forEach((term) => term !== '' && clauses.push(`fullText contains '${term}'`)); clauses.push('trashed = false'); url.searchParams.set('q', clauses.join(' and ')); const searchInDrive = async (drive?: string) => { const _url = new URL(url.toString()); if (drive) { _url.searchParams.set('driveId', drive); _url.searchParams.set('corpora', 'drive'); if (pageTokenMap[drive]) { _url.searchParams.set('pageToken', pageTokenMap[drive]); } } else { _url.searchParams.set('corpora', 'allDrives'); if (pageTokenMap['global']) { _url.searchParams.set('pageToken', pageTokenMap['global']); } } const response = await ( await fetch(_url.toString(), { headers: { Authorization: `Bearer ${await this.accessToken(account as GoogleDriveAccount)}`, }, }) ).json(); if (response.nextPageToken) { if (drive) { pageTokenMap[drive] = response.nextPageToken; } else { pageTokenMap['global'] = response.nextPageToken; } } else { if (drive) { delete pageTokenMap[drive]; } else if (pageTokenMap['global']) { delete pageTokenMap['global']; } } console.log('url = ', _url.toString()); console.log('token = ', await this.accessToken(account as GoogleDriveAccount)); console.log('drive = ', drive, response); if (!response.files) { response.files = []; } return response; }; const promises: Promise<any>[] = []; if (drives && drives.length > 0) { for (const drive of drives) { promises.push(searchInDrive(drive)); } } else { promises.push(searchInDrive()); } const responses = await Promise.all(promises); let nextPageToken: string | undefined; if (Object.keys(pageTokenMap).length > 0) { nextPageToken = base64.RAWURL.encode( await this.encrypt('pageToken', JSON.stringify({ account, pageTokenMap })), ); } let files: any[] = []; for (const response of responses) { files = [...files, ...response.files]; } return { nextPageToken, files }; } async ls( account?: GoogleDriveAccount | null, parent?: string | null, orderBy?: string | null, encrypted_page_token?: string | null, ): Promise<GDFileList | null> { let pageToken: string | undefined; if (account == null && typeof encrypted_page_token === 'string' && encrypted_page_token !== '') { const data = JSON.parse( buf2str(await this.decrypt('pageToken', base64.RAWURL.decode(encrypted_page_token))), ); account = data.account; pageToken = data.pageToken; } if (account == null) { account = await this.pickAccount(); } let url: URL; if (parent) { url = new URL('https://www.googleapis.com/drive/v3/files'); url.searchParams.set('includeItemsFromAllDrives', 'true'); url.searchParams.set('supportsAllDrives', 'true'); url.searchParams.set('q', `'${parent}' in parents and trashed = false`); url.searchParams.set('fields', 'nextPageToken,files(id,name,mimeType,size,modifiedTime,parents)'); url.searchParams.set('pageSize', '100'); if (orderBy) { url.searchParams.set('orderBy', orderBy); } else { url.searchParams.set('orderBy', 'folder,name,modifiedTime desc'); } } else { url = new URL('https://www.googleapis.com/drive/v3/drives'); url.searchParams.set('pageSize', '100'); } if (pageToken) { url.searchParams.set('pageToken', pageToken); } const response = await ( await fetch(url.toString(), { headers: { Authorization: `Bearer ${await this.accessToken(account)}`, }, }) ).json(); let nextPageToken: string | undefined; if (response.nextPageToken) { nextPageToken = base64.RAWURL.encode( await this.encrypt( 'pageToken', JSON.stringify({ account, pageToken: response.nextPageToken, }), ), ); } return { nextPageToken, files: response.files, drives: response.drives, }; } async copyFileInit(account: GoogleDriveAccount | null, src: string, dst: string): Promise<Response> { if (account == null) { account = await this.pickAccount(); } const file = await this.file(account, src); const url = new URL('https://www.googleapis.com/upload/drive/v3/files'); url.searchParams.set('uploadType', 'resumable'); url.searchParams.set('supportsAllDrives', 'true'); const response = await fetch(url.toString(), { method: 'POST', headers: { Authorization: `Bearer ${await this.accessToken(account)}`, 'Content-Type': 'application/json; charset=UTF-8', 'X-Upload-Content-Type': `${file.mimeType}`, 'X-Upload-Content-Length': `${file.size}`, }, body: JSON.stringify({ name: file.name, parents: [dst], }), }); const location = new URL(response.headers.get('Location') as string); console.log(location.toString()); return new Response(JSON.stringify({ ...file, token: location.searchParams.get('upload_id') as string })); } async copyFileExec(account: GoogleDriveAccount | null, src: string, token: string): Promise<Response> { if (account == null) { account = await this.pickAccount(); } const location = `https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true&upload_id=${token}`; const data = await this.download(account, src); return fetch(location, { method: 'PUT', headers: { 'Content-Length': data.headers.get('Content-Length') as string, 'Content-Type': data.headers.get('Content-Type') as string, }, body: data.body, }); } async copyFileStat(account: GoogleDriveAccount | null, token: string): Promise<Response> { const location = `https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true&upload_id=${token}`; const response = await fetch(location, { method: 'PUT', headers: { 'Content-Range': 'bytes */*', }, }); if (response.status === 200) { const file = await response.json(); return new Response(JSON.stringify({ ...file, status: 'uploaded' })); } if (response.status === 404) { return new Response(JSON.stringify({ status: 'expired' })); } if (response.status === 308) { const range = response.headers.get('Range'); let uploaded = 0; if (range) { const m = range.match(/bytes=0-(\d+)/); if (m) { uploaded = parseInt(m[1]); } } return new Response(JSON.stringify({ status: 'uploading', uploaded })); } return new Response( JSON.stringify({ status: 'error', message: `unexpected API response status: ${response.status}` }), ); } async secretKey(namespace: string): Promise<CryptoKey> { const { config: { secret }, } = this; return crypto.subtle.importKey( 'raw', await crypto.subtle.digest('SHA-256', str2buf(secret + ':' + namespace)), 'AES-GCM', true, ['encrypt', 'decrypt'], ); } async encrypt(namespace: string, data: string | ArrayBufferLike): Promise<ArrayBuffer> { const iv = crypto.getRandomValues(new Uint8Array(12)); const ciphertext = new Uint8Array( await crypto.subtle.encrypt( { name: 'AES-GCM', iv }, await this.secretKey(namespace), typeof data === 'string' ? str2buf(data) : new Uint8Array(data), ), ); const packed = new Uint8Array(12 + ciphertext.byteLength); packed.set(iv); packed.set(ciphertext, 12); return packed; } async decrypt(namespace: string, data: string | ArrayBufferLike): Promise<ArrayBuffer> { if (typeof data === 'string') { data = base64.decode(data); } if (!(data instanceof Uint8Array)) { data = new Uint8Array(data); } const iv = new Uint8Array((data as Uint8Array).buffer, 0, 12); const ciphertext = new Uint8Array((data as Uint8Array).buffer, 12); return crypto.subtle.decrypt({ name: 'AES-GCM', iv }, await this.secretKey(namespace), ciphertext); } async pickAccount(): Promise<GoogleDriveAccount> { const { config: { secret, accounts, accountRotation, accountCandidates }, } = this; const candidates: typeof accounts = []; if (accounts.length <= accountCandidates) { candidates.push(...accounts); } else { // new seed for every accountRotation seconds const seed = secret + Math.floor(Date.now() / 1000 / accountRotation).toString(); // generate a random value from seed const rand = new Uint32Array(await crypto.subtle.digest('SHA-256', str2buf(seed)))[0]; // use the seeded random value as starting point, select accountCandidates consecutive accounts for (let i = rand % accounts.length, j = 0; j < accountCandidates; i = (i + 1) % accounts.length, ++j) { candidates.push(accounts[i]); } } // choose randomly without seed, an item from the candidates const account = candidates[Math.floor(Math.random() * candidates.length)]; if (typeof account === 'string') { const ciphertext = await (await fetch(account)).arrayBuffer(); const plaintext = buf2str(await this.decrypt('account', ciphertext)); return JSON.parse(plaintext); } else { return account; } } async accessToken(account: GoogleDriveAccount): Promise<string> { if (account.expires == undefined || account.expires < Date.now()) { let token: TokenResponse; if (account.type == 'authorized_user') { token = await this.fetchOauth2Token(account); } else { token = await this.fetchJwtToken(account); } if (token.access_token != undefined) { account.access_token = token.access_token; account.expires = Date.now() + Math.max(0, token.expires_in - 100) * 1000; } } return account.access_token as string; } async fetchOauth2Token(account: GoogleDriveUserAccount): Promise<TokenResponse> { const url = new URL('https://oauth2.googleapis.com/token'); const form = new URLSearchParams(); form.set('client_id', account.client_id); form.set('client_secret', account.client_secret); form.set('refresh_token', account.refresh_token); form.set('grant_type', 'refresh_token'); return ( await fetch(url.toString(), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: form.toString(), }) ).json(); } async fetchJwtToken(account: GoogleDriveServiceAccount): Promise<TokenResponse> { const headers = { alg: 'RS256', typ: 'JWT', kid: account.private_key_id, }; const now = Math.floor(Date.now() / 1000) - 10; const claimSet = { iat: now, exp: now + 3600, iss: account.client_email, aud: account.token_uri, scope: 'https://www.googleapis.com/auth/drive', }; const body = base64.RAWURL.encodeString(JSON.stringify(headers)) + '.' + base64.RAWURL.encodeString(JSON.stringify(claimSet)); const privateKey = await this.importRSAPEMPrivateKey(account.private_key); const sig = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', privateKey, str2buf(body)); const jws = body + '.' + base64.encode(sig); const url = new URL('https://oauth2.googleapis.com/token'); const form = new URLSearchParams(); form.set('assertion', jws); form.set('grant_type', 'urn:ietf:params:oauth:grant-type:jwt-bearer'); return ( await fetch(url.toString(), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: form.toString(), }) ).json(); } async importRSAPEMPrivateKey(pem: string): Promise<CryptoKey> { // fetch the part of the PEM string between header and footer const pemHeader = '-----BEGIN PRIVATE KEY-----'; const pemFooter = '-----END PRIVATE KEY-----'; const lines = pem.split(/[\r\n]+/); let pemContent = ''; let inContent = false; for (let line of lines) { line = line.trim(); if (inContent) { if (line === pemFooter) { break; } pemContent += line; } else if (line === pemHeader) { inContent = true; } } const binaryDer = base64.decode(pemContent); return crypto.subtle.importKey( 'pkcs8', binaryDer, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256', }, true, ['sign'], ); } }
the_stack
import { ComponentFixture, inject, TestBed, waitForAsync, } from "@angular/core/testing"; import { Component, Inject, InjectionToken, NgModule, Optional, ViewChild, ViewContainerRef, } from "@angular/core"; import { By } from "@angular/platform-browser"; import { MdlDialogModule, MdlDialogReference } from "./mdl-dialog.module"; import { MdlDialogService } from "./mdl-dialog.service"; import { MdlDialogHostComponent } from "./mdl-dialog-host.component"; import { MdlSimpleDialogComponent } from "./mdl-simple-dialog.component"; import { IOpenCloseRect } from "./mdl-dialog-configuration"; import { MdlDialogOutletModule } from "../dialog-outlet/mdl-dialog-outlet.module"; import { MdlDialogOutletService } from "../dialog-outlet/mdl-dialog-outlet.service"; import { MdlButtonComponent } from "../button/mdl-button.component"; import { MdlButtonModule } from "../button/mdl-button.module"; import { DOCUMENT } from "@angular/common"; import { MdlBackdropOverlayComponent } from "./../dialog-outlet/mdl-backdrop-overlay.component"; const TEST = new InjectionToken<string>("test"); // https://github.com/angular/angular/issues/36623 // https://angular.io/api/core/global/ngGetComponent declare const ng: { getComponent<T>(element: Element): T | null; }; const getComponent = <T>( fixture: ComponentFixture<unknown>, cssQuery: string ): T => { const componentElement = getNativeElement(fixture, cssQuery); return ng.getComponent(componentElement); }; const getNativeElement = ( fixture: ComponentFixture<unknown>, cssQuery: string ): HTMLElement => { return fixture.nativeElement.querySelector(cssQuery); }; @Component({ // eslint-disable-next-line selector: "test-view", template: ` <div></div> <button mdl-button #targetBtn></button> <button mdl-button #btn></button> <dialog-outlet></dialog-outlet> `, }) class MdlTestViewComponent { @ViewChild("btn", { static: true }) button: MdlButtonComponent; @ViewChild("targetBtn", { static: true }) targetBtn: MdlButtonComponent; public getFakeMouseEvent() { const mouseEvent = new MouseEvent("click"); // eslint-disable-next-line (mouseEvent as any).testtarget = this.targetBtn.elementRef.nativeElement; return mouseEvent; } } @Component({ // eslint-disable-next-line selector: "test-dialog-component", template: "<div>TestCustomDialog</div>", }) class TestCustomDialogComponent { constructor( private viewRef: ViewContainerRef, private dialog: MdlDialogReference, @Optional() @Inject(TEST) public test: string ) {} close(data?: unknown): void { this.dialog.hide(data); } } @Component({ // eslint-disable-next-line selector: "test-fail-dialog-component", template: "<div>TestFalCustomDialog</div>", }) class TestFailCustomDialogComponent {} @NgModule({ imports: [], exports: [TestCustomDialogComponent], declarations: [TestCustomDialogComponent, TestFailCustomDialogComponent], providers: [], entryComponents: [TestCustomDialogComponent, TestFailCustomDialogComponent], }) class TestDialogModul {} describe("Service: MdlDialog", () => { let mdlDialogService: MdlDialogService; let mdlDialogOutletService: MdlDialogOutletService; let doc: HTMLDocument; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [MdlTestViewComponent], imports: [ MdlDialogModule.forRoot(), MdlDialogOutletModule, TestDialogModul, MdlButtonModule.forRoot(), ], }); }) ); beforeEach( waitForAsync( inject( [MdlDialogService, MdlDialogOutletService, DOCUMENT], ( service: MdlDialogService, dialogOutletService: MdlDialogOutletService, document ) => { mdlDialogService = service; mdlDialogOutletService = dialogOutletService; doc = document; } ) ) ); it("should show an alert", (done) => { const title = "Alert"; const fixture = TestBed.createComponent(MdlTestViewComponent); const result = mdlDialogService.alert(title); result.subscribe(() => done()); fixture.detectChanges(); const dialogHostComponent: MdlDialogHostComponent = getComponent( fixture, "mdl-dialog-host-component" ); expect(dialogHostComponent.zIndex).toBe( 100001, "the zIndex should be 100001" ); // the backdrop shoud be visible and have an zIndex of 100000 const backdrop: MdlBackdropOverlayComponent = getComponent( fixture, "mdl-backdrop-overlay" ); expect(backdrop.zIndex).toBe( 100000, "the zIndex of the background should be 100000" ); const titleDiv = getNativeElement(fixture, ".mdl-dialog__content"); expect(titleDiv.textContent).toBe(title); // close the dialog by clicking the ok button const buttonEl = getNativeElement(fixture, ".mdl-button--primary"); buttonEl.click(); }); it("should show a confirm dialog which is modal and can be closed with click on confirm", (done) => { const fixture = TestBed.createComponent(MdlTestViewComponent); const result = mdlDialogService.confirm("?", "no", "yes"); result.subscribe(() => { done(); }); fixture.detectChanges(); const ne: HTMLElement = fixture.debugElement.nativeElement; // the yes button const buttonDebugElements = ne.querySelectorAll( "mdl-dialog-component .mdl-button" ); const buttonEl: HTMLButtonElement = buttonDebugElements[0] as HTMLButtonElement; buttonEl.click(); }); it("should show a confirm dialog which is modal and can be closed esc", (done) => { const fixture = TestBed.createComponent(MdlTestViewComponent); const result = mdlDialogService.confirm("?", "no", "yes"); result.subscribe( // eslint-disable-next-line @typescript-eslint/no-empty-function () => {}, () => { done(); } ); fixture.detectChanges(); const dialog: MdlSimpleDialogComponent = getComponent( fixture, "mdl-dialog-component" ); // sending an keybord event to the dialog would be better dialog.onEsc(); }); it("should be possible to open a custom dialog", (done) => { const fixture = TestBed.createComponent(MdlTestViewComponent); const p = mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, providers: [{ provide: TEST, useValue: "test" }], }); p.subscribe((dialogRef) => { dialogRef.onHide().subscribe(() => { done(); }); const customDialogComponent: TestCustomDialogComponent = getComponent( fixture, "test-dialog-component" ); // value should be jnjected expect(customDialogComponent.test).toBe("test"); // call close by calling hide on the dialog reference customDialogComponent.close(); }); fixture.detectChanges(); }); it("should be able to pass data when hiding a custom dialog", (done) => { const fixture = TestBed.createComponent(MdlTestViewComponent); const p = mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, }); p.subscribe((dialogRef) => { dialogRef.onHide().subscribe((data) => { // async makes sure this is called expect(data).toEqual("teststring"); done(); }); const customDialogComponent: TestCustomDialogComponent = getComponent( fixture, "test-dialog-component" ); // call close by calling hide on the dialog reference customDialogComponent.close("teststring"); }); fixture.detectChanges(); }); it( "should stop propagaton on overlay clicks", waitForAsync(() => { const fixture = TestBed.createComponent(MdlTestViewComponent); fixture.detectChanges(); mdlDialogService.alert("Alert"); const backdrop = doc.querySelector(".dialog-backdrop") as HTMLDivElement; const event = new MouseEvent("click", {}); spyOn(event, "stopPropagation"); backdrop.dispatchEvent(event); expect(event.stopPropagation).toHaveBeenCalled(); }) ); it( "should not be possible to create a simple dialog without actions", waitForAsync(() => { expect(() => { mdlDialogService.showDialog({ message: "x", actions: [], }); }).toThrow(); }) ); it("should not hide the dialog on esc key if there is no closing action", (done) => { const fixture = TestBed.createComponent(MdlTestViewComponent); const pDialogRef = mdlDialogService.showDialog({ message: "m", actions: [ { // eslint-disable-next-line @typescript-eslint/no-empty-function handler: () => {}, text: "ok", }, ], }); pDialogRef.subscribe((dialogRef: MdlDialogReference) => { spyOn(dialogRef, "hide"); const dialog = fixture.debugElement.query( By.directive(MdlSimpleDialogComponent) ).componentInstance; // sending an keybord event to the dialog would be better dialog.onEsc(); expect(dialogRef.hide).not.toHaveBeenCalled(); done(); }); fixture.detectChanges(); }); it( "should throw if no viewContainerRef is provided", waitForAsync(() => { mdlDialogOutletService.setDefaultViewContainerRef(null); expect(() => { mdlDialogService.alert("m"); }).toThrow(); }) ); it( "should close the dialog on click on the backdrop if clickOutsideToClose true", waitForAsync(() => { const fixture = TestBed.createComponent(MdlTestViewComponent); fixture.detectChanges(); const p = mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, isModal: true, clickOutsideToClose: true, }); p.subscribe((dialogRef) => { dialogRef.onHide().subscribe(() => { // async -> this have to been called to fullfill all open obseravbles }); const backdrop = doc.querySelector( ".dialog-backdrop" ) as HTMLDivElement; const event = new MouseEvent("click", {}); backdrop.dispatchEvent(event); }); }) ); it( "should not close the dialog on click on the backdrop if clickOutsideToClose true", waitForAsync(() => { const fixture = TestBed.createComponent(MdlTestViewComponent); fixture.detectChanges(); const p = mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, isModal: true, clickOutsideToClose: false, }); p.subscribe(() => { const backdrop = doc.querySelector( ".dialog-backdrop" ) as HTMLDivElement; expect(backdrop).toBeDefined("dialog-backdrop should be present"); const event = new MouseEvent("click", {}); backdrop.dispatchEvent(event); fixture.detectChanges(); fixture.whenStable().then(() => { const dialogHost = fixture.debugElement.query( By.directive(MdlDialogHostComponent) ); expect(dialogHost).toBeDefined( "dialog host should not be null - because it is not closed." ); }); }); }) ); it( "should disable animations if animate is false", waitForAsync(() => { const fixture = TestBed.createComponent(MdlTestViewComponent); fixture.detectChanges(); mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, animate: false, }); fixture.detectChanges(); fixture.whenStable().then(() => { const dialogHost = fixture.debugElement.query( By.directive(MdlDialogHostComponent) ); expect(dialogHost.componentInstance.isAnimateEnabled()).toBe( false, "animate should be false" ); }); }) ); it("should add additional classes and styles to the dialog host", async () => { const fixture = TestBed.createComponent(MdlTestViewComponent); fixture.detectChanges(); mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, styles: { width: "350px" }, classes: "a b", }); fixture.detectChanges(); await fixture.whenStable(); const ne: HTMLElement = fixture.debugElement.nativeElement; const dialogHost: HTMLElement = ne.querySelector( "mdl-dialog-host-component" ); expect(dialogHost.style.width).toBe("350px"); expect(dialogHost.classList.contains("a")).toBe( true, "should contian class a" ); expect(dialogHost.classList.contains("b")).toBe( true, "should contian class b" ); }); it( "should open a dialog if openForm is specified", waitForAsync(() => { const fixture = TestBed.createComponent(MdlTestViewComponent); fixture.detectChanges(); const p = mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, styles: { width: "350px" }, classes: "a b", openFrom: fixture.componentInstance.button, }); p.subscribe((dialogRef) => { dialogRef.hide(); }); }) ); it( "should open a dialog if animation is false", waitForAsync(() => { const fixture = TestBed.createComponent(MdlTestViewComponent); fixture.detectChanges(); const p = mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, animate: false, }); p.subscribe((dialogRef) => { dialogRef.hide(); }); }) ); it( "should open a dialog from a button and close to a mouse event position", waitForAsync(() => { const fixture = TestBed.createComponent(MdlTestViewComponent); fixture.detectChanges(); const p = mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, styles: { width: "350px" }, classes: "a b", openFrom: fixture.componentInstance.button, closeTo: fixture.componentInstance.getFakeMouseEvent(), }); p.subscribe((dialogRef) => { dialogRef.hide(); }); }) ); it( "should open a dialog from a OpenCloseRect ", waitForAsync(() => { const fixture = TestBed.createComponent(MdlTestViewComponent); fixture.detectChanges(); const p = mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, styles: { width: "350px" }, classes: "a b", openFrom: { height: 10, left: 0, top: 0, width: 0 } as IOpenCloseRect, }); p.subscribe((dialogRef) => { dialogRef.hide(); }); }) ); it( "should emit an event when the first dialog instance is opened", waitForAsync(() => { const fixture = TestBed.createComponent(MdlTestViewComponent); fixture.detectChanges(); const spy = spyOn(mdlDialogService.onDialogsOpenChanged, "emit"); mdlDialogService.onDialogsOpenChanged.subscribe((dialogsOpen) => { expect(dialogsOpen).toBe(true); }); mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, providers: [{ provide: TEST, useValue: "test" }], }); mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, providers: [{ provide: TEST, useValue: "test 2" }], }); expect(spy.calls.count()).toEqual(1); }) ); it( "should emit an event when the last dialog instance is closed", waitForAsync(() => { const fixture = TestBed.createComponent(MdlTestViewComponent); fixture.detectChanges(); const spy = spyOn(mdlDialogService.onDialogsOpenChanged, "emit"); const p = mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, providers: [{ provide: TEST, useValue: "test 1" }], }); const p2 = mdlDialogService.showCustomDialog({ component: TestCustomDialogComponent, providers: [{ provide: TEST, useValue: "test 2" }], }); mdlDialogService.onDialogsOpenChanged.subscribe((dialogsOpen) => { expect(dialogsOpen).toBe(false); }); p.subscribe((dialogRef) => { dialogRef.hide(); p2.subscribe((dialogRef2) => { dialogRef2.hide(); expect(spy.calls.count()).toEqual(2); // 1 open, 1 close. }); }); }) ); });
the_stack
import { Component, Inject, OnInit } from '@angular/core'; import { Subscription } from "rxjs"; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { MatSnackBar } from '@angular/material/snack-bar'; import { MatTableDataSource } from '@angular/material/table'; import { DialogService, SnackBarComponent } from 'serendipity-components-lib'; import { LoggerService } from 'utils-lib'; import { ContactsService } from '../../../services/contacts/contacts.service'; import { LookupAccountDialogComponent } from "../lookup-account-dialog/lookup-account-dialog.component"; import { DialogResult } from "../../../models/dialog"; import { PartyType } from '../../../types/party-type'; import { Role } from '../../../models/role'; interface RoleClassificationScheme { role: string; partyType: string; relationship: string; reciprocalRole: string; reciprocalPartyType: string; } const DEFAULT_FOOTER_COL_SPAN = 5; const RELATIONSHIP_LIST_COLUMNS = [ 'partyName', 'role', 'relationship', 'reciprocalRole', 'reciprocalPartyName' ]; @Component({ selector: 'party-add-relationship-dialog', template: ` <h2 mat-dialog-title>Add relationship</h2> <mat-dialog-content class="mat-typography"> <!-- <div class="lookup-list-container"> --> <div> <table mat-table [hidden]="!items" [dataSource]="dataSource" matSort matSortStart="desc" matSortDisableClear> <!-- Name Column --> <ng-container matColumnDef="partyName"> <!-- See: .scss for mat-column styles --> <th mat-header-cell *matHeaderCellDef> NAME </th> <td mat-cell *matCellDef="let element"> {{ element.partyName }} </td> </ng-container> <!-- Role Column --> <ng-container matColumnDef="role"> <!-- See: .scss for mat-column styles --> <th mat-header-cell *matHeaderCellDef> ROLE </th> <td mat-cell *matCellDef="let element"> <mat-select [(value)]="role" (selectionChange)="onSelectionChange()" > <mat-option *ngFor="let element of scheme" [value]="element.role"> {{ element.role }} </mat-option> </mat-select> </td> </ng-container> <ng-container matColumnDef="relationship"> <!-- See: .scss for mat-column styles --> <th mat-header-cell *matHeaderCellDef> RELATIONSHIP </th> <td mat-cell *matCellDef="let element"> {{ element.relationship }} </td> </ng-container> <ng-container matColumnDef="reciprocalRole"> <!-- See: .scss for mat-column styles --> <th mat-header-cell *matHeaderCellDef> RECIPROCAL ROLE </th> <td mat-cell *matCellDef="let element"> {{ element.reciprocalRole }} </td> </ng-container> <ng-container matColumnDef="reciprocalPartyName"> <!-- See: .scss for mat-column styles --> <th mat-header-cell *matHeaderCellDef> NAME </th> <td mat-cell *matCellDef="let element"> <div class="md-input"> <div class="md-input-trigger"> <div class="md-input-value"> <span class="md-input-value-text"> {{ element.reciprocalPartyName }} </span> </div> <div class="md-input-search-icon-wrapper"> <mat-icon matSuffix svgIcon="search" class="md-input-search-icon" (click)="reciprocalPartyNameClickHandler()"> </mat-icon> </div> </div> </div> </td> </ng-container> <!-- Footer --> <ng-container matColumnDef="footer"> <td mat-footer-cell *matFooterCellDef [attr.colspan]="footerColSpan"> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> <tr mat-footer-row *matFooterRowDef="['footer']; sticky: true"></tr> </table> </div> </mat-dialog-content> <mat-dialog-actions align="end"> <button mat-raised-button color="accent" #okButton [disabled]="disableOkButton" (keydown.arrowright)="cancelButton.focus()" (click)="onOk()"> {{ okButtonLabel }} </button> <button mat-raised-button cdkFocusInitial #cancelButton (keydown.arrowleft)="okButton.focus()" (click)="onCancel()"> {{ cancelButtonLabel }} </button> </mat-dialog-actions> `, styleUrls: ['add-relationship-dialog.component.scss'] }) export class AddRelationshipDialogComponent implements OnInit { public item!: any; // Contact or Account public reciprocalParty!: any; // Contact or Account public items!: Array<Role>; public dataSource!: MatTableDataSource<Role>; public displayedColumns = RELATIONSHIP_LIST_COLUMNS; public footerColSpan = DEFAULT_FOOTER_COL_SPAN; public scheme!: RoleClassificationScheme[]; public role!: string; public cancelButtonLabel = 'CANCEL'; public okButtonLabel = 'OK'; public disableOkButton = true; constructor(@Inject(MAT_DIALOG_DATA) public data: {item: any}, private dialogRef: MatDialogRef<AddRelationshipDialogComponent>, private dialogService: DialogService, private entityService: ContactsService, private snackBar: MatSnackBar, private logger: LoggerService) { this.logger.info('AddRelationshipDialogComponent: constructor()'); this.logger.info('data: ' + JSON.stringify(data, null, 2) + '\n'); this.item = data.item; } public ngOnInit() { this.logger.info('AddRelationshipDialogComponent: ngOnInit()'); // this.logger.info('currentUser: ' + JSON.stringify(this.currentUser, null, 2)); if (this.item.party.type === PartyType.INDIVIDUAL) { this.scheme = [ { role: 'Member', partyType: PartyType.INDIVIDUAL, relationship: 'Membership', reciprocalRole: 'Political Party', reciprocalPartyType: PartyType.ORGANISATION }, { role: 'Investor', partyType: PartyType.INDIVIDUAL, relationship: 'Investment Management', reciprocalRole: 'Advisor', reciprocalPartyType: PartyType.INDIVIDUAL } ]; this.role = this.scheme[0].role; } else { // PartyType.ORGANISATION this.scheme = [ { role: 'Public Officer', partyType: PartyType.ORGANISATION, relationship: 'Office Holder', reciprocalRole: 'Authorised Contact', reciprocalPartyType: PartyType.INDIVIDUAL }, { role: 'Employer', partyType: PartyType.ORGANISATION, relationship: 'Employment', reciprocalRole: 'Employee', reciprocalPartyType: PartyType.INDIVIDUAL } ]; this.role = this.scheme[0].role; } this.items = []; this.items.push(new Role( this.role, this.item.party.id, this.item.party.type, this.item.party.displayName, this.item.email, this.item.phoneNumber, this.scheme[0].relationship, this.scheme[0].reciprocalRole )); this.dataSource = new MatTableDataSource(this.items); this.dataSource.data = this.items; } // // Dynamic Form events // public onSelectionChange(): void { this.logger.info('AddRelationshipDialogComponent: onSelectionChange()'); this.logger.info('role: ' + this.role); this.scheme.every((element, index) => { if (element.role === this.role) { this.logger.info('item.role === this.role'); this.items[0].relationship = this.scheme[index].relationship; this.items[0].reciprocalRole = this.scheme[index].reciprocalRole; this.reciprocalParty = null; this.items[0].reciprocalPartyId = ''; this.items[0].reciprocalPartyType = ''; this.items[0].reciprocalPartyName = ''; this.items[0].reciprocalPartyEmail = ''; this.items[0].reciprocalPartyPhoneNumber = ''; this.disableOkButton = true; return false; } return true; }); } public reciprocalPartyNameClickHandler(): void { this.logger.info('AddRelationshipDialogComponent: reciprocalPartyNameClickHandler()'); if (this.items[0].reciprocalRole === PartyType.INDIVIDUAL) { this.logger.info('this.items[0].reciprocalRole === PartyType.INDIVIDUAL'); } else { this.logger.info('this.items[0].reciprocalRole === PartyType.ORGANISATION'); this.openLookupAccountDialog(); } } private openLookupAccountDialog() { this.logger.info('AddRelationshipDialogComponent: openLookupAccountDialog()'); let config = { disableRemoveButton: true, hideRemoveButton: true, addButtonLabel: 'OK' }; const lookupAccountDialogRef = this.dialogService.open(LookupAccountDialogComponent, { data: config }); lookupAccountDialogRef.afterClosed().subscribe((response: DialogResult) => { this.logger.info('response: ' + JSON.stringify(response, null, 2) + '\n'); if (!response.result) { return; } switch (response.action) { case 'ok': this.reciprocalParty = response.record; this.items[0].reciprocalPartyId = this.reciprocalParty.party.id; this.items[0].reciprocalPartyType = this.reciprocalParty.party.type; this.items[0].reciprocalPartyName = this.reciprocalParty.party.displayName; this.items[0].reciprocalPartyEmail = this.reciprocalParty.email; this.items[0].reciprocalPartyPhoneNumber = this.reciprocalParty.phoneNumber; this.disableOkButton = false; break; default: this.logger.error('openLookupAccountDialog() -> default'); break; } }); } // // Action Bar events // public onCancel(): void { this.dialogRef.close({ result: false }); } public onOk(): void { this.logger.info('AddRelationshipDialogComponent: onOk()'); const subscription: Subscription = this.entityService.createRole(this.item.party.id, this.items[0]).subscribe(() => { subscription.unsubscribe(); }); this.dialogRef.close({ result: true, action: 'ok' }); } // // Misc // private openSnackBar(message: string) { this.snackBar.openFromComponent(SnackBarComponent, { data: { message: message }, duration: 500, panelClass: 'md-snack-bar' }); } // https://stackoverflow.com/questions/48891174/angular-material-2-datatable-sorting-with-nested-objects public getProperty = (obj: any, path: any) => ( path.split('.').reduce((o: any, p: any) => o && o[p], obj) ) }
the_stack
import { Component, ViewChild, AfterViewInit, ElementRef, ChangeDetectorRef, ViewChildren, QueryList } from '@angular/core'; import { IgxGridComponent, IDropBaseEventArgs, IgxDialogComponent, IDropDroppedEventArgs, GridSelectionMode} from 'igniteui-angular'; interface ColumnConfig { key: string; width: string; colStart: number; rowStart: number; colSpan: number; rowSpan: number; selected: boolean; hovered: boolean; } @Component({ selector: 'app-grid-mrl-config-sample', templateUrl: 'grid-mrl-config.sample.html', styleUrls: ['grid-mrl-config.sample.css'] }) export class GridMRLConfigSampleComponent implements AfterViewInit { @ViewChild('jsonDialog', { read: IgxDialogComponent, static: true }) public jsonDialog: IgxDialogComponent; @ViewChild('textArea', { read: ElementRef, static: true }) public textArea: ElementRef; @ViewChild('grid', { read: IgxGridComponent }) public grid: IgxGridComponent; @ViewChildren('gridCell', { read: ElementRef }) public gridCells: QueryList<ElementRef>; @ViewChild('resizeIndicator', { read: ElementRef, static: true }) public resizeIndicator: ElementRef; public rowsCount = 3; public colsCount = 6; public rowsHeight = '32px'; public colsWidth = '136px'; public collection: ColumnConfig[][] = []; public gridCollection = []; public renderGrid = false; public jsonCollection = ''; public cellSelected; public dragStarted = false; public dragStartX; public dragStartY; public curResizedCell; public colSpanIncrease = 0; public rowSpanIncrease = 0; public resizeVisible = false; public resizeTop; public resizeLeft; public resizeRight; public resizeInitialWidth = 0; public resizeInitialHeight = 0; public resizeWidth = 0; public resizeHeight = 0; public selectionMode; public columnsList: {key: string; field: string; hide?: boolean} [] = [ { key: 'ContactName', field: 'Contact name'}, { key: 'ContactTitle', field: 'Contact title'}, { key: 'CompanyName', field: 'Company name'}, { key: 'Country', field: 'Country'}, { key: 'Phone', field: 'Phone'}, { key: 'City', field: 'City'}, { key: 'Address', field: 'Address'} ]; public columnsConfiguration; public data = [ /* eslint-disable max-len */ { ID: 'ALFKI', CompanyName: 'Alfreds Futterkiste', ContactName: 'Maria Anders', ContactTitle: 'Sales Representative', Address: 'Obere Str. 57', City: 'Berlin', Region: null, PostalCode: '12209', Country: 'Germany', Phone: '030-0074321', Fax: '030-0076545' }, { ID: 'ANATR', CompanyName: 'Ana Trujillo Emparedados y helados', ContactName: 'Ana Trujillo', ContactTitle: 'Owner', Address: 'Avda. de la Constitución 2222', City: 'México D.F.', Region: null, PostalCode: '05021', Country: 'Mexico', Phone: '(5) 555-4729', Fax: '(5) 555-3745' }, { ID: 'ANTON', CompanyName: 'Antonio Moreno Taquería', ContactName: 'Antonio Moreno', ContactTitle: 'Owner', Address: 'Mataderos 2312', City: 'México D.F.', Region: null, PostalCode: '05023', Country: 'Mexico', Phone: '(5) 555-3932', Fax: null }, { ID: 'AROUT', CompanyName: 'Around the Horn', ContactName: 'Thomas Hardy', ContactTitle: 'Sales Representative', Address: '120 Hanover Sq.', City: 'London', Region: null, PostalCode: 'WA1 1DP', Country: 'UK', Phone: '(171) 555-7788', Fax: '(171) 555-6750' }, { ID: 'BERGS', CompanyName: 'Berglunds snabbköp', ContactName: 'Christina Berglund', ContactTitle: 'Order Administrator', Address: 'Berguvsvägen 8', City: 'Luleå', Region: null, PostalCode: 'S-958 22', Country: 'Sweden', Phone: '0921-12 34 65', Fax: '0921-12 34 67' }, { ID: 'BLAUS', CompanyName: 'Blauer See Delikatessen', ContactName: 'Hanna Moos', ContactTitle: 'Sales Representative', Address: 'Forsterstr. 57', City: 'Mannheim', Region: null, PostalCode: '68306', Country: 'Germany', Phone: '0621-08460', Fax: '0621-08924' }, { ID: 'BLONP', CompanyName: 'Blondesddsl père et fils', ContactName: 'Frédérique Citeaux', ContactTitle: 'Marketing Manager', Address: '24, place Kléber', City: 'Strasbourg', Region: null, PostalCode: '67000', Country: 'France', Phone: '88.60.15.31', Fax: '88.60.15.32' }, { ID: 'BOLID', CompanyName: 'Bólido Comidas preparadas', ContactName: 'Martín Sommer', ContactTitle: 'Owner', Address: 'C/ Araquil, 67', City: 'Madrid', Region: null, PostalCode: '28023', Country: 'Spain', Phone: '(91) 555 22 82', Fax: '(91) 555 91 99' }, { ID: 'BONAP', CompanyName: 'Bon app\'', ContactName: 'Laurence Lebihan', ContactTitle: 'Owner', Address: '12, rue des Bouchers', City: 'Marseille', Region: null, PostalCode: '13008', Country: 'France', Phone: '91.24.45.40', Fax: '91.24.45.41' }, { ID: 'BOTTM', CompanyName: 'Bottom-Dollar Markets', ContactName: 'Elizabeth Lincoln', ContactTitle: 'Accounting Manager', Address: '23 Tsawassen Blvd.', City: 'Tsawassen', Region: 'BC', PostalCode: 'T2F 8M4', Country: 'Canada', Phone: '(604) 555-4729', Fax: '(604) 555-3745' }, { ID: 'BSBEV', CompanyName: 'B\'s Beverages', ContactName: 'Victoria Ashworth', ContactTitle: 'Sales Representative', Address: 'Fauntleroy Circus', City: 'London', Region: null, PostalCode: 'EC2 5NT', Country: 'UK', Phone: '(171) 555-1212', Fax: null }, { ID: 'CACTU', CompanyName: 'Cactus Comidas para llevar', ContactName: 'Patricio Simpson', ContactTitle: 'Sales Agent', Address: 'Cerrito 333', City: 'Buenos Aires', Region: null, PostalCode: '1010', Country: 'Argentina', Phone: '(1) 135-5555', Fax: '(1) 135-4892' }, { ID: 'CENTC', CompanyName: 'Centro comercial Moctezuma', ContactName: 'Francisco Chang', ContactTitle: 'Marketing Manager', Address: 'Sierras de Granada 9993', City: 'México D.F.', Region: null, PostalCode: '05022', Country: 'Mexico', Phone: '(5) 555-3392', Fax: '(5) 555-7293' }, { ID: 'CHOPS', CompanyName: 'Chop-suey Chinese', ContactName: 'Yang Wang', ContactTitle: 'Owner', Address: 'Hauptstr. 29', City: 'Bern', Region: null, PostalCode: '3012', Country: 'Switzerland', Phone: '0452-076545', Fax: null }, { ID: 'COMMI', CompanyName: 'Comércio Mineiro', ContactName: 'Pedro Afonso', ContactTitle: 'Sales Associate', Address: 'Av. dos Lusíadas, 23', City: 'Sao Paulo', Region: 'SP', PostalCode: '05432-043', Country: 'Brazil', Phone: '(11) 555-7647', Fax: null }, { ID: 'CONSH', CompanyName: 'Consolidated Holdings', ContactName: 'Elizabeth Brown', ContactTitle: 'Sales Representative', Address: 'Berkeley Gardens 12 Brewery', City: 'London', Region: null, PostalCode: 'WX1 6LT', Country: 'UK', Phone: '(171) 555-2282', Fax: '(171) 555-9199' }, { ID: 'DRACD', CompanyName: 'Drachenblut Delikatessen', ContactName: 'Sven Ottlieb', ContactTitle: 'Order Administrator', Address: 'Walserweg 21', City: 'Aachen', Region: null, PostalCode: '52066', Country: 'Germany', Phone: '0241-039123', Fax: '0241-059428' }, { ID: 'DUMON', CompanyName: 'Du monde entier', ContactName: 'Janine Labrune', ContactTitle: 'Owner', Address: '67, rue des Cinquante Otages', City: 'Nantes', Region: null, PostalCode: '44000', Country: 'France', Phone: '40.67.88.88', Fax: '40.67.89.89' }, { ID: 'EASTC', CompanyName: 'Eastern Connection', ContactName: 'Ann Devon', ContactTitle: 'Sales Agent', Address: '35 King George', City: 'London', Region: null, PostalCode: 'WX3 6FW', Country: 'UK', Phone: '(171) 555-0297', Fax: '(171) 555-3373' }, { ID: 'ERNSH', CompanyName: 'Ernst Handel', ContactName: 'Roland Mendel', ContactTitle: 'Sales Manager', Address: 'Kirchgasse 6', City: 'Graz', Region: null, PostalCode: '8010', Country: 'Austria', Phone: '7675-3425', Fax: '7675-3426' }, { ID: 'FAMIA', CompanyName: 'Familia Arquibaldo', ContactName: 'Aria Cruz', ContactTitle: 'Marketing Assistant', Address: 'Rua Orós, 92', City: 'Sao Paulo', Region: 'SP', PostalCode: '05442-030', Country: 'Brazil', Phone: '(11) 555-9857', Fax: null }, { ID: 'FISSA', CompanyName: 'FISSA Fabrica Inter. Salchichas S.A.', ContactName: 'Diego Roel', ContactTitle: 'Accounting Manager', Address: 'C/ Moralzarzal, 86', City: 'Madrid', Region: null, PostalCode: '28034', Country: 'Spain', Phone: '(91) 555 94 44', Fax: '(91) 555 55 93' }, { ID: 'FOLIG', CompanyName: 'Folies gourmandes', ContactName: 'Martine Rancé', ContactTitle: 'Assistant Sales Agent', Address: '184, chaussée de Tournai', City: 'Lille', Region: null, PostalCode: '59000', Country: 'France', Phone: '20.16.10.16', Fax: '20.16.10.17' }, { ID: 'FOLKO', CompanyName: 'Folk och fä HB', ContactName: 'Maria Larsson', ContactTitle: 'Owner', Address: 'Åkergatan 24', City: 'Bräcke', Region: null, PostalCode: 'S-844 67', Country: 'Sweden', Phone: '0695-34 67 21', Fax: null }, { ID: 'FRANK', CompanyName: 'Frankenversand', ContactName: 'Peter Franken', ContactTitle: 'Marketing Manager', Address: 'Berliner Platz 43', City: 'München', Region: null, PostalCode: '80805', Country: 'Germany', Phone: '089-0877310', Fax: '089-0877451' }, { ID: 'FRANR', CompanyName: 'France restauration', ContactName: 'Carine Schmitt', ContactTitle: 'Marketing Manager', Address: '54, rue Royale', City: 'Nantes', Region: null, PostalCode: '44000', Country: 'France', Phone: '40.32.21.21', Fax: '40.32.21.20' }, { ID: 'FRANS', CompanyName: 'Franchi S.p.A.', ContactName: 'Paolo Accorti', ContactTitle: 'Sales Representative', Address: 'Via Monte Bianco 34', City: 'Torino', Region: null, PostalCode: '10100', Country: 'Italy', Phone: '011-4988260', Fax: '011-4988261' } ]; /* eslint-enable max-len */ constructor(public cdr: ChangeDetectorRef) { this.updateCollectionSize(); this.selectionMode = GridSelectionMode.none; } public ngAfterViewInit() { // this.grid.groupBy({ fieldName: 'Country', dir: 1, ignoreCase: false }); } public get layoutRowStyle() { let style = ''; this.collection.forEach(() => { if (this.rowsHeight.indexOf('px') !== -1 || this.rowsHeight.indexOf('%') !== -1 || isNaN(parseInt(this.rowsHeight, 10))) { style += ' ' + this.rowsHeight; } else { style += ' ' + parseInt(this.rowsHeight, 10) + 'px'; } }); return style; } public get layoutColsStyle() { let style = ''; this.collection[0].forEach((col) => { for (let i = 0; i < col.colSpan; i++) { if (this.colsWidth.indexOf('px') !== -1 || this.colsWidth.indexOf('%') !== -1 || isNaN(parseInt(this.colsWidth, 10))) { style += ' ' + this.colsWidth; } else { style += ' ' + parseInt(this.colsWidth, 10) + 'px'; } } }); return style; } public updateCollectionSize() { const newCollection = []; for (let rowIndex = 0; rowIndex < this.rowsCount; rowIndex++) { const row = []; for (let colIndex = 0; colIndex < this.colsCount; colIndex++) { if (this.collection[rowIndex] && this.collection[rowIndex][colIndex]) { row.push(this.collection[rowIndex][colIndex]); } else { row.push({ key: '', width: '', rowStart: rowIndex + 1, colStart: colIndex + 1, colSpan: 1, rowSpan: 1 }); } } newCollection.push(row); } this.collection = newCollection; } public updateCollectionLayout() { // eslint-disable-next-line @typescript-eslint/prefer-for-of for (let rowIndex = 0; rowIndex < this.collection.length; rowIndex++) { let column = this.collection[rowIndex][0]; for (let colIndex = 1; colIndex < this.collection[rowIndex].length; colIndex++) { if (this.collection[rowIndex][colIndex].key === column.key && this.collection[rowIndex][colIndex].key !== '') { column.colSpan += this.collection[rowIndex][colIndex].colSpan; this.collection[rowIndex].splice(colIndex, 1); colIndex--; } else { column = this.collection[rowIndex][colIndex]; } } } } public rowCountChanged(event) { this.rowsCount = parseInt(event.target.value, 10); this.updateCollectionSize(); } public rowHeightChanged(event) { this.rowsHeight = event.target.value; this.cdr.detectChanges(); } public colCountChanged(event) { this.colsCount = parseInt(event.target.value, 10); this.updateCollectionSize(); } public colWidthChanged(event) { this.colsWidth = event.target.value; } public onColEnter(event: IDropBaseEventArgs, rowIndex, colIndex) { this.collection[rowIndex][colIndex].hovered = true; } public onColLeave(event: IDropBaseEventArgs, rowIndex, colIndex) { this.collection[rowIndex][colIndex].hovered = false; } public onColDropped(event: IDropDroppedEventArgs, rowIndex, colIndex) { event.cancel = true; this.collection[rowIndex][colIndex].key = event.drag.data.key; this.updateCollectionLayout(); } public flattenCollection() { const result = []; this.collection.forEach((row) => { row.forEach((col) => { const newCol = { ...col }; delete newCol.width; delete newCol.hovered; delete newCol.selected; result.push(newCol); }); }); return result; } public rerenderGrid() { this.renderGrid = false; // Flatten the current collection for the grid. this.gridCollection = this.flattenCollection(); setTimeout(() => { this.renderGrid = true; }, 200); } public renderJson() { const flatCollection = this.flattenCollection(); this.jsonCollection = JSON.stringify(flatCollection); this.jsonDialog.open(); } public copyToClipboard() { this.textArea.nativeElement.select(); document.execCommand('copy'); } public clickCell(cellRef, rowIndex, colIndex) { this.cellSelected = this.collection[rowIndex][colIndex]; this.cellSelected.selected = true; this.resizeTop = cellRef.offsetTop; this.resizeLeft = cellRef.offsetLeft; this.resizeHeight = cellRef.offsetHeight; this.resizeWidth = cellRef.offsetWidth; this.resizeInitialHeight = this.resizeHeight; this.resizeInitialWidth = this.resizeWidth; this.resizeVisible = true; } public onBlur(event, rowIndex, colIndex) { this.cellSelected = null; this.collection[rowIndex][colIndex].selected = false; this.resizeVisible = false; } public pointerDownResize(event, rowIndex, colIndex) { this.dragStarted = true; this.dragStartX = event.pageX; this.dragStartY = event.pageY; this.curResizedCell = this.collection[rowIndex][colIndex]; event.target.setPointerCapture(event.pointerId); } public pointerMoveResizeLeft(event, cellRef, rowIndex, colIndex) { if (this.dragStarted) { const curDistance = this.dragStartX - event.pageX; const minIncrease = -this.curResizedCell.colSpan; const maxIncrease = colIndex; this.colSpanIncrease = Math.min(Math.round(curDistance / 136), maxIncrease); this.colSpanIncrease = Math.max(this.colSpanIncrease, minIncrease); this.resizeWidth = this.resizeInitialWidth + this.colSpanIncrease * 136; this.resizeLeft = cellRef.offsetLeft - this.colSpanIncrease * 136; } } public pointerMoveResizeRight(event, cellRef, rowIndex, colIndex) { if (this.dragStarted) { const curDistance = event.pageX - this.dragStartX; const maxIncrease = this.colsCount - (colIndex + this.curResizedCell.colSpan); this.colSpanIncrease = Math.min(Math.round(curDistance / 136), maxIncrease); this.resizeWidth = this.resizeInitialWidth + this.colSpanIncrease * 136; } } public pointerUpResizeRight(event, cellRef, rowIndex, colIndex) { this.dragStarted = false; this.resizeVisible = false; if (this.colSpanIncrease > 0) { for (let i = 0; i < this.colSpanIncrease; i++) { const nextCell = this.collection[rowIndex][colIndex + 1]; if (this.curResizedCell.colStart + this.curResizedCell.colSpan + i !== nextCell.colStart || nextCell.rowSpan > 1) { this.colSpanIncrease = i; break; } if (this.collection[rowIndex][colIndex + 1].colSpan > 1) { this.collection[rowIndex][colIndex + 1].colStart++; this.collection[rowIndex][colIndex + 1].colSpan--; } else { this.collection[rowIndex].splice(colIndex + 1, 1); } } if (this.curResizedCell.rowSpan > 1) { for (let row = this.curResizedCell.rowStart; row < this.curResizedCell.rowStart - 1 + this.curResizedCell.rowSpan; row++) { for (let spanIndex = 0; spanIndex < this.colSpanIncrease; spanIndex++) { let borderCellIndex = 0; const borderCell = this.collection[row].find((cell, index) => { borderCellIndex = index; return cell.colStart === this.curResizedCell.colStart + this.curResizedCell.colSpan + spanIndex; }); if (borderCell) { if (borderCell.colSpan > 1) { borderCell.colStart++; borderCell.colSpan--; } else { this.collection[row].splice(borderCellIndex, 1); } } } } } this.curResizedCell.colSpan += this.colSpanIncrease; } else if (this.colSpanIncrease < 0) { this.colSpanIncrease = -1 * Math.min(-1 * this.colSpanIncrease, this.curResizedCell.colSpan); const rowEndIndex = this.curResizedCell.rowStart - 1 + this.curResizedCell.rowSpan; for (let rowUpdateIndex = rowIndex; rowUpdateIndex < rowEndIndex; rowUpdateIndex++) { const firstHalf = []; for (const layout of this.collection[rowUpdateIndex]) { if (layout.colStart < this.curResizedCell.colStart + this.curResizedCell.colSpan) { firstHalf.push(layout); } else { break; } } const secondHalf = this.collection[rowUpdateIndex].slice(firstHalf.length); for (let i = 0; i < -1 * this.colSpanIncrease; i++) { secondHalf.unshift({ key: '', width: '', rowStart: rowUpdateIndex + 1, colStart: this.curResizedCell.colStart + this.curResizedCell.colSpan - i - 1, colSpan: 1, rowSpan: 1, selected: false, hovered: false }); } this.collection[rowUpdateIndex] = firstHalf.concat(secondHalf); } this.curResizedCell.colSpan -= -1 * this.colSpanIncrease; if (this.curResizedCell.colSpan === 0) { this.collection[rowIndex].splice(colIndex + this.curResizedCell.colSpan, 1); } } this.colSpanIncrease = 0; } public pointerUpResizeLeft(event, cellRef, targetRowIndex, targetColIndex) { this.dragStarted = false; this.resizeVisible = false; const curIndexFromEnd = this.collection[targetRowIndex].length - targetColIndex - 1; if (this.colSpanIncrease > 0) { // Handle first row for (let i = 0; i < this.colSpanIncrease; i++) { const curIndexFromStart = this.collection[targetRowIndex].length - curIndexFromEnd - 1; const prevCell = this.collection[targetRowIndex][curIndexFromStart - 1]; if (prevCell.colStart + prevCell.colSpan + i !== this.collection[targetRowIndex][curIndexFromStart].colStart || prevCell.rowSpan > 1) { this.colSpanIncrease = i; break; } if (prevCell.colSpan > 1) { prevCell.colSpan--; } else { this.collection[targetRowIndex].splice(curIndexFromStart - 1, 1); } } // Handle the rest if it spans more than one row if (this.curResizedCell.rowSpan > 1) { for (let rowIndex = this.curResizedCell.rowStart; rowIndex < this.curResizedCell.rowStart - 1 + this.curResizedCell.rowSpan; rowIndex++) { let leftSibling; let leftSiblingIndex = 0; for (let m = 0; m < this.collection[rowIndex].length; m++) { if (this.collection[rowIndex][m].colStart >= this.curResizedCell.colStart + this.curResizedCell.colSpan) { break; } leftSiblingIndex = m; leftSibling = this.collection[rowIndex][m]; } for (let spanIndex = 0; spanIndex < this.colSpanIncrease; spanIndex++) { if (leftSibling.colSpan > 1) { leftSibling.colSpan--; } else { this.collection[rowIndex].splice(leftSiblingIndex - spanIndex, 1); } leftSibling = this.collection[rowIndex][leftSiblingIndex - spanIndex - 1]; } } } this.curResizedCell.colStart -= this.colSpanIncrease; this.curResizedCell.colSpan += this.colSpanIncrease; } else if (this.colSpanIncrease < 0) { this.colSpanIncrease = -1 * Math.min(-1 * this.colSpanIncrease, this.curResizedCell.colSpan); const rowEndIndex = this.curResizedCell.rowStart - 1 + this.curResizedCell.rowSpan; for (let rowUpdateIndex = targetRowIndex; rowUpdateIndex < rowEndIndex; rowUpdateIndex++) { const firstHalf = []; for (const layout of this.collection[rowUpdateIndex]) { if (layout.colStart < this.curResizedCell.colStart) { firstHalf.push(layout); } else { break; } } const secondHalf = this.collection[rowUpdateIndex].slice(firstHalf.length); for (let i = 0; i < -1 * this.colSpanIncrease; i++) { firstHalf.push({ key: '', width: '', rowStart: rowUpdateIndex + 1, colStart: this.curResizedCell.colStart + i, colSpan: 1, rowSpan: 1, selected: false }); } if (rowUpdateIndex === targetRowIndex && this.curResizedCell.colSpan === 0) { secondHalf.shift(); } this.collection[rowUpdateIndex] = firstHalf.concat(secondHalf); } this.curResizedCell.colSpan -= -1 * this.colSpanIncrease; this.curResizedCell.colStart += -1 * this.colSpanIncrease; } this.colSpanIncrease = 0; } public pointerMoveResizeBottom(event, rowIndex) { if (this.dragStarted) { const curDistance = event.pageY - this.dragStartY; const maxIncrease = this.rowsCount - rowIndex - this.curResizedCell.rowSpan; this.rowSpanIncrease = Math.min(Math.round(curDistance / 32), maxIncrease); this.resizeHeight = this.resizeInitialHeight + this.rowSpanIncrease * 32; } } public pointerUpResizeBottom(rowIndex) { this.dragStarted = false; this.resizeVisible = false; if (this.rowSpanIncrease > 0) { for (let increaseIndex = 1; increaseIndex <= this.rowSpanIncrease; increaseIndex++) { // Cycle how many rows should the size of the cell increase, and edit them accordingly. const curRowIndex = rowIndex + (this.curResizedCell.rowSpan - 1) + increaseIndex; for (let j = this.collection[curRowIndex].length - 1; j >= 0 ; j--) { // Cycle all cells backwards because when cell spans in the way it should be cut and cells on the right should be added. const curCell = this.collection[curRowIndex][j]; const curCellStart = curCell.colStart; let curCellEnd = curCell.colStart + curCell.colSpan; const resizedCellStart = this.curResizedCell.colStart ; const resizedCellEnd = this.curResizedCell.colStart + this.curResizedCell.colSpan; if (curCellStart < resizedCellEnd && curCellEnd > resizedCellEnd && curCell.rowSpan === 1) { // If current cell spans the way of the resized down cell and the end is spanning more to the right, // cut the current cell and add the needed cells after the resized cell ends. const numNewCells = curCellEnd - resizedCellEnd; for (let i = 0; i < numNewCells; i++) { curCell.colSpan--; curCellEnd--; this.collection[curRowIndex].splice(j + 1, 0, { key: '', width: '', rowStart: curRowIndex + 1, colStart: curCellEnd, colSpan: 1, rowSpan: 1, selected: false, hovered: false }); } } else if (curCellStart < resizedCellEnd && curCellEnd > resizedCellEnd && curCell.rowSpan > 1) { // We only need to check the rowSpan because we start from top to bottom and top cells have the rowSpan this.curResizedCell.rowSpan += increaseIndex - 1; this.rowSpanIncrease = 0; return; } if (curCellStart <= resizedCellEnd && curCellEnd >= resizedCellStart && curCellEnd <= resizedCellEnd) { // If current cell is in the way of resized down cell decrease the size of the current cell. curCell.colSpan -= (curCellEnd) - this.curResizedCell.colStart; } if (curCell.colSpan <= 0) { // If the current cell span is <= 0 it should be removed. this.collection[curRowIndex].splice(j, 1); } } } this.curResizedCell.rowSpan += this.rowSpanIncrease; } else if (this.rowSpanIncrease < 0) { this.rowSpanIncrease = -1 * Math.min(-1 * this.rowSpanIncrease, this.curResizedCell.rowSpan); const startIndex = this.curResizedCell.rowStart + this.curResizedCell.rowSpan - 2; for (let i = startIndex; i > startIndex + this.rowSpanIncrease; i--) { let startCellIndex = 0; // Get first cell after current resized multirow cell for (let j = 0; j < this.collection[i].length; j++) { if (this.collection[i][j].colStart > this.curResizedCell.colStart) { startCellIndex = j - 1; break; } } for (let j = 0; j < this.curResizedCell.colSpan; j++) { this.collection[i].splice(startCellIndex + 1 + j, 0, { key: '', width: '', rowStart: i + 1, colStart: this.curResizedCell.colStart + j, colSpan: 1, rowSpan: 1, selected: false, hovered: false }); } } this.curResizedCell.rowSpan += this.rowSpanIncrease; if (this.curResizedCell.rowSpan === 0) { this.collection[rowIndex].splice(this.curResizedCell.colStart - 1 + this.curResizedCell.colSpan, 1); } } this.rowSpanIncrease = 0; } public onCellKey(event, rowIndex) { if (event.key === 'Delete') { for (let i = rowIndex; i < rowIndex + this.cellSelected.rowSpan; i++) { const rowFirstHalf = []; for (const layout of this.collection[i]) { if (layout.colStart < this.cellSelected.colStart) { rowFirstHalf.push(layout); } else { break; } } const rowSecondHalf = this.collection[i].slice(rowFirstHalf.length + (i === rowIndex ? 1 : 0)); for (let j = 0; j < this.cellSelected.colSpan; j++) { rowFirstHalf.push({ key: '', width: '', rowStart: i + 1, colStart: this.cellSelected.colStart + j, colSpan: 1, rowSpan: 1, selected: false }); } this.collection[i] = rowFirstHalf.concat(rowSecondHalf); } this.cellSelected = null; this.resizeVisible = false; } } }
the_stack
import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core'; import { FormControl } from '@angular/forms'; import { DYNAMIC_FORM_CONTROL_TYPE_DATEPICKER, DynamicDateControlModel, DynamicDatePickerModel, DynamicFormArrayGroupModel, DynamicFormArrayModel, DynamicFormControlEvent, DynamicFormControlModel, DynamicFormGroupModel, DynamicSelectModel, MATCH_ENABLED, OR_OPERATOR } from '@ng-dynamic-forms/core'; import { WorkspaceitemSectionUploadFileObject } from '../../../../../core/submission/models/workspaceitem-section-upload-file.model'; import { FormBuilderService } from '../../../../../shared/form/builder/form-builder.service'; import { BITSTREAM_ACCESS_CONDITION_GROUP_CONFIG, BITSTREAM_ACCESS_CONDITION_GROUP_LAYOUT, BITSTREAM_ACCESS_CONDITIONS_FORM_ARRAY_CONFIG, BITSTREAM_ACCESS_CONDITIONS_FORM_ARRAY_LAYOUT, BITSTREAM_FORM_ACCESS_CONDITION_END_DATE_CONFIG, BITSTREAM_FORM_ACCESS_CONDITION_END_DATE_LAYOUT, BITSTREAM_FORM_ACCESS_CONDITION_START_DATE_CONFIG, BITSTREAM_FORM_ACCESS_CONDITION_START_DATE_LAYOUT, BITSTREAM_FORM_ACCESS_CONDITION_TYPE_CONFIG, BITSTREAM_FORM_ACCESS_CONDITION_TYPE_LAYOUT, BITSTREAM_METADATA_FORM_GROUP_CONFIG, BITSTREAM_METADATA_FORM_GROUP_LAYOUT } from './section-upload-file-edit.model'; import { POLICY_DEFAULT_WITH_LIST } from '../../section-upload.component'; import { hasNoValue, hasValue, isNotEmpty, isNotNull } from '../../../../../shared/empty.util'; import { SubmissionFormsModel } from '../../../../../core/config/models/config-submission-forms.model'; import { FormFieldModel } from '../../../../../shared/form/builder/models/form-field.model'; import { AccessConditionOption } from '../../../../../core/config/models/config-access-condition-option.model'; import { SubmissionService } from '../../../../submission.service'; import { FormService } from '../../../../../shared/form/form.service'; import { FormComponent } from '../../../../../shared/form/form.component'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { filter, mergeMap, take } from 'rxjs/operators'; import { dateToISOFormat } from '../../../../../shared/date.util'; import { SubmissionObject } from '../../../../../core/submission/models/submission-object.model'; import { WorkspaceitemSectionUploadObject } from '../../../../../core/submission/models/workspaceitem-section-upload.model'; import { JsonPatchOperationsBuilder } from '../../../../../core/json-patch/builder/json-patch-operations-builder'; import { SubmissionJsonPatchOperationsService } from '../../../../../core/submission/submission-json-patch-operations.service'; import { JsonPatchOperationPathCombiner } from '../../../../../core/json-patch/builder/json-patch-operation-path-combiner'; import { SectionUploadService } from '../../section-upload.service'; import { Subscription } from 'rxjs'; /** * This component represents the edit form for bitstream */ @Component({ selector: 'ds-submission-section-upload-file-edit', styleUrls: ['./section-upload-file-edit.component.scss'], templateUrl: './section-upload-file-edit.component.html', }) export class SubmissionSectionUploadFileEditComponent implements OnInit { /** * The FormComponent reference */ @ViewChild('formRef') public formRef: FormComponent; /** * The list of available access condition * @type {Array} */ public availableAccessConditionOptions: any[]; /** * The submission id * @type {string} */ public collectionId: string; /** * Define if collection access conditions policy type : * POLICY_DEFAULT_NO_LIST : is not possible to define additional access group/s for the single file * POLICY_DEFAULT_WITH_LIST : is possible to define additional access group/s for the single file * @type {number} */ public collectionPolicyType: number; /** * The configuration for the bitstream's metadata form * @type {SubmissionFormsModel} */ public configMetadataForm: SubmissionFormsModel; /** * The bitstream's metadata data * @type {WorkspaceitemSectionUploadFileObject} */ public fileData: WorkspaceitemSectionUploadFileObject; /** * The bitstream id * @type {string} */ public fileId: string; /** * The bitstream array key * @type {string} */ public fileIndex: string; /** * The form id * @type {string} */ public formId: string; /** * The section id * @type {string} */ public sectionId: string; /** * The submission id * @type {string} */ public submissionId: string; /** * The list of all available metadata */ formMetadata: string[] = []; /** * The form model * @type {DynamicFormControlModel[]} */ formModel: DynamicFormControlModel[]; /** * When `true` form controls are deactivated */ isSaving = false; /** * The [JsonPatchOperationPathCombiner] object * @type {JsonPatchOperationPathCombiner} */ protected pathCombiner: JsonPatchOperationPathCombiner; protected subscriptions: Subscription[] = []; /** * Initialize instance variables * * @param activeModal * @param {ChangeDetectorRef} cdr * @param {FormBuilderService} formBuilderService * @param {FormService} formService * @param {SubmissionService} submissionService * @param {JsonPatchOperationsBuilder} operationsBuilder * @param {SubmissionJsonPatchOperationsService} operationsService * @param {SectionUploadService} uploadService */ constructor( protected activeModal: NgbActiveModal, private cdr: ChangeDetectorRef, private formBuilderService: FormBuilderService, private formService: FormService, private submissionService: SubmissionService, private operationsBuilder: JsonPatchOperationsBuilder, private operationsService: SubmissionJsonPatchOperationsService, private uploadService: SectionUploadService, ) { } /** * Initialize form model values * * @param formModel * The form model */ public initModelData(formModel: DynamicFormControlModel[]) { this.fileData.accessConditions.forEach((accessCondition, index) => { Array.of('name', 'startDate', 'endDate') .filter((key) => accessCondition.hasOwnProperty(key) && isNotEmpty(accessCondition[key])) .forEach((key) => { const metadataModel: any = this.formBuilderService.findById(key, formModel, index); if (metadataModel) { if (metadataModel.type === DYNAMIC_FORM_CONTROL_TYPE_DATEPICKER) { const date = new Date(accessCondition[key]); metadataModel.value = { year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate() }; } else { metadataModel.value = accessCondition[key]; } } }); }); } /** * Dispatch form model update when changing an access condition * * @param event * The event emitted */ onChange(event: DynamicFormControlEvent) { if (event.model.id === 'name') { this.setOptions(event.model, event.control); } } onModalClose() { this.activeModal.dismiss(); } onSubmit() { this.isSaving = true; this.saveBitstreamData(); } /** * Update `startDate`, 'groupUUID' and 'endDate' model * * @param model * The [[DynamicFormControlModel]] object * @param control * The [[FormControl]] object */ public setOptions(model: DynamicFormControlModel, control: FormControl) { let accessCondition: AccessConditionOption = null; this.availableAccessConditionOptions.filter((element) => element.name === control.value) .forEach((element) => accessCondition = element ); if (isNotEmpty(accessCondition)) { const showGroups: boolean = accessCondition.hasStartDate === true || accessCondition.hasEndDate === true; const startDateControl: FormControl = control.parent.get('startDate') as FormControl; const endDateControl: FormControl = control.parent.get('endDate') as FormControl; // Clear previous state startDateControl?.markAsUntouched(); endDateControl?.markAsUntouched(); startDateControl?.setValue(null); control.parent.markAsDirty(); endDateControl?.setValue(null); if (showGroups) { if (accessCondition.hasStartDate) { const startDateModel = this.formBuilderService.findById( 'startDate', (model.parent as DynamicFormArrayGroupModel).group) as DynamicDateControlModel; const min = new Date(accessCondition.maxStartDate); startDateModel.max = { year: min.getUTCFullYear(), month: min.getUTCMonth() + 1, day: min.getUTCDate() }; } if (accessCondition.hasEndDate) { const endDateModel = this.formBuilderService.findById( 'endDate', (model.parent as DynamicFormArrayGroupModel).group) as DynamicDateControlModel; const max = new Date(accessCondition.maxEndDate); endDateModel.max = { year: max.getUTCFullYear(), month: max.getUTCMonth() + 1, day: max.getUTCDate() }; } } } } /** * Dispatch form model init */ ngOnInit() { if (this.fileData && this.formId) { this.formModel = this.buildFileEditForm(); this.cdr.detectChanges(); } } ngOnDestroy(): void { this.unsubscribeAll(); } protected retrieveValueFromField(field: any) { const temp = Array.isArray(field) ? field[0] : field; return (temp) ? temp.value : undefined; } /** * Initialize form model */ protected buildFileEditForm() { const configDescr: FormFieldModel = Object.assign({}, this.configMetadataForm.rows[0].fields[0]); configDescr.repeatable = false; const configForm = Object.assign({}, this.configMetadataForm, { fields: Object.assign([], this.configMetadataForm.rows[0].fields[0], [ this.configMetadataForm.rows[0].fields[0], configDescr ]) }); const formModel: DynamicFormControlModel[] = []; const metadataGroupModelConfig = Object.assign({}, BITSTREAM_METADATA_FORM_GROUP_CONFIG); metadataGroupModelConfig.group = this.formBuilderService.modelFromConfiguration( this.submissionId, configForm, this.collectionId, this.fileData.metadata, this.submissionService.getSubmissionScope() ); formModel.push(new DynamicFormGroupModel(metadataGroupModelConfig, BITSTREAM_METADATA_FORM_GROUP_LAYOUT)); const accessConditionTypeModelConfig = Object.assign({}, BITSTREAM_FORM_ACCESS_CONDITION_TYPE_CONFIG); const accessConditionsArrayConfig = Object.assign({}, BITSTREAM_ACCESS_CONDITIONS_FORM_ARRAY_CONFIG); const accessConditionTypeOptions = []; if (this.collectionPolicyType === POLICY_DEFAULT_WITH_LIST) { for (const accessCondition of this.availableAccessConditionOptions) { accessConditionTypeOptions.push( { label: accessCondition.name, value: accessCondition.name } ); } accessConditionTypeModelConfig.options = accessConditionTypeOptions; // Dynamically assign of relation in config. For startdate, endDate, groups. const hasStart = []; const hasEnd = []; const hasGroups = []; this.availableAccessConditionOptions.forEach((condition) => { const showStart: boolean = condition.hasStartDate === true; const showEnd: boolean = condition.hasEndDate === true; const showGroups: boolean = showStart || showEnd; if (showStart) { hasStart.push({id: 'name', value: condition.name}); } if (showEnd) { hasEnd.push({id: 'name', value: condition.name}); } if (showGroups) { hasGroups.push({id: 'name', value: condition.name}); } }); const confStart = {relations: [{match: MATCH_ENABLED, operator: OR_OPERATOR, when: hasStart}]}; const confEnd = {relations: [{match: MATCH_ENABLED, operator: OR_OPERATOR, when: hasEnd}]}; accessConditionsArrayConfig.groupFactory = () => { const type = new DynamicSelectModel(accessConditionTypeModelConfig, BITSTREAM_FORM_ACCESS_CONDITION_TYPE_LAYOUT); const startDateConfig = Object.assign({}, BITSTREAM_FORM_ACCESS_CONDITION_START_DATE_CONFIG, confStart); const endDateConfig = Object.assign({}, BITSTREAM_FORM_ACCESS_CONDITION_END_DATE_CONFIG, confEnd); const startDate = new DynamicDatePickerModel(startDateConfig, BITSTREAM_FORM_ACCESS_CONDITION_START_DATE_LAYOUT); const endDate = new DynamicDatePickerModel(endDateConfig, BITSTREAM_FORM_ACCESS_CONDITION_END_DATE_LAYOUT); const accessConditionGroupConfig = Object.assign({}, BITSTREAM_ACCESS_CONDITION_GROUP_CONFIG); accessConditionGroupConfig.group = [type]; if (hasStart.length > 0) { accessConditionGroupConfig.group.push(startDate); } if (hasEnd.length > 0) { accessConditionGroupConfig.group.push(endDate); } return [new DynamicFormGroupModel(accessConditionGroupConfig, BITSTREAM_ACCESS_CONDITION_GROUP_LAYOUT)]; }; // Number of access conditions blocks in form accessConditionsArrayConfig.initialCount = isNotEmpty(this.fileData.accessConditions) ? this.fileData.accessConditions.length : 1; formModel.push( new DynamicFormArrayModel(accessConditionsArrayConfig, BITSTREAM_ACCESS_CONDITIONS_FORM_ARRAY_LAYOUT) ); } this.initModelData(formModel); return formModel; } /** * Save bitstream metadata */ saveBitstreamData() { // validate form this.formService.validateAllFormFields(this.formRef.formGroup); const saveBitstreamDataSubscription = this.formService.isValid(this.formId).pipe( take(1), filter((isValid) => isValid), mergeMap(() => this.formService.getFormData(this.formId)), take(1), mergeMap((formData: any) => { // collect bitstream metadata Object.keys((formData.metadata)) .filter((key) => isNotEmpty(formData.metadata[key])) .forEach((key) => { const metadataKey = key.replace(/_/g, '.'); const path = `metadata/${metadataKey}`; this.operationsBuilder.add(this.pathCombiner.getPath(path), formData.metadata[key], true); }); Object.keys((this.fileData.metadata)) .filter((key) => isNotEmpty(this.fileData.metadata[key])) .filter((key) => hasNoValue(formData.metadata[key])) .filter((key) => this.formMetadata.includes(key)) .forEach((key) => { const metadataKey = key.replace(/_/g, '.'); const path = `metadata/${metadataKey}`; this.operationsBuilder.remove(this.pathCombiner.getPath(path)); }); const accessConditionsToSave = []; formData.accessConditions .map((accessConditions) => accessConditions.accessConditionGroup) .filter((accessCondition) => isNotEmpty(accessCondition)) .forEach((accessCondition) => { let accessConditionOpt; this.availableAccessConditionOptions .filter((element) => isNotNull(accessCondition.name) && element.name === accessCondition.name[0].value) .forEach((element) => accessConditionOpt = element); if (accessConditionOpt) { const currentAccessCondition = Object.assign({}, accessCondition); currentAccessCondition.name = this.retrieveValueFromField(accessCondition.name); /* When start and end date fields are deactivated, their values may be still present in formData, therefore it is necessary to delete them if they're not allowed by the current access condition option. */ if (!accessConditionOpt.hasStartDate) { delete currentAccessCondition.startDate; } else if (accessCondition.startDate) { const startDate = this.retrieveValueFromField(accessCondition.startDate); currentAccessCondition.startDate = dateToISOFormat(startDate); } if (!accessConditionOpt.hasEndDate) { delete currentAccessCondition.endDate; } else if (accessCondition.endDate) { const endDate = this.retrieveValueFromField(accessCondition.endDate); currentAccessCondition.endDate = dateToISOFormat(endDate); } accessConditionsToSave.push(currentAccessCondition); } }); if (isNotEmpty(accessConditionsToSave)) { this.operationsBuilder.add(this.pathCombiner.getPath('accessConditions'), accessConditionsToSave, true); } // dispatch a PATCH request to save metadata return this.operationsService.jsonPatchByResourceID( this.submissionService.getSubmissionObjectLinkName(), this.submissionId, this.pathCombiner.rootElement, this.pathCombiner.subRootElement); }) ).subscribe((result: SubmissionObject[]) => { if (result[0].sections[this.sectionId]) { const uploadSection = (result[0].sections[this.sectionId] as WorkspaceitemSectionUploadObject); Object.keys(uploadSection.files) .filter((key) => uploadSection.files[key].uuid === this.fileId) .forEach((key) => this.uploadService.updateFileData( this.submissionId, this.sectionId, this.fileId, uploadSection.files[key]) ); } this.isSaving = false; this.activeModal.close(); }); this.subscriptions.push(saveBitstreamDataSubscription); } private unsubscribeAll() { this.subscriptions.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe()); } }
the_stack
import shortcut from './vendor/shortcut' import scrollStop from './vendor/scrollStop' import Overlay from './overlay' import Color from './Color.d' import Rect from './rect' var EDROPPER_VERSION = 12 var CANVAS_MAX_SIZE = 32767 - 20 var page = { width: 0, height: 0, screenWidth: 0, screenHeight: 0, xOffset: 0, yOffset: 0, overlay: null as Overlay, options: { cursor: 'default', enableColorToolbox: true, enableColorTooltip: true, enableRightClickDeactivate: true, }, canvas: null, canvasData: null, canvasContext: null, canvasBorders: 20, imageData: null, resetCanvas: true, rects: [] as Array<Rect>, screenshoting: false, dropperActivated: false, // function to set defaults - used during init and later for reset defaults: function () { page.screenWidth = window.innerWidth page.screenHeight = window.innerHeight page.canvas = document.createElement('canvas') page.resetCanvas = true page.rects = [] page.screenshoting = false page.width = Math.round(document.documentElement.scrollWidth) page.height = Math.round(document.documentElement.scrollHeight) // TODO: check if this is needed if (page.width > CANVAS_MAX_SIZE) { page.width = CANVAS_MAX_SIZE console.warn('Page width is larger then maximum Canvas width.') } if (page.height > CANVAS_MAX_SIZE) { page.height = CANVAS_MAX_SIZE console.warn('Page height is larger then maximum Canvas height.') } }, // --------------------------------- // MESSAGING // --------------------------------- messageListener: function () { // Listen for pickup activate console.log('dropper: page activated') console.log(`dropper: debug page at ${chrome.runtime.getURL('debug-tab.html')}`) chrome.runtime.onMessage.addListener(function (req, _sender, sendResponse) { switch (req.type) { case 'edropper-version': sendResponse({ version: EDROPPER_VERSION, tabid: req.tabid, }) break case 'pickup-activate': page.options = req.options page.dropperActivate() break case 'pickup-deactivate': page.dropperDeactivate() break case 'update-image': console.log('dropper: background send me updated screenshot') page.imageData = req.data page.capture() break } }) }, sendMessage: function (message: any) { chrome.runtime.connect().postMessage(message) }, // --------------------------------- // DROPPER CONTROL // --------------------------------- dropperActivate: function () { if (page.dropperActivated) return console.log('dropper: activating page dropper') page.defaults() page.overlay = new Overlay({ width: page.width, height: page.height, enableToolbox: page.options.enableColorToolbox, enableTooltip: page.options.enableColorTooltip, cursor: page.options.cursor, }) page.dropperActivated = true page.screenChanged() // set listeners scrollStop(page.onScrollStop) document.addEventListener('mousemove', page.onMouseMove, false) document.addEventListener('click', page.onMouseClick, false) if (page.options.enableRightClickDeactivate === true) { document.addEventListener('contextmenu', page.onContextMenu, false) } // enable keyboard shortcuts page.shortcuts(true) }, dropperDeactivate: function () { if (!page.dropperActivated) return // disable keyboard shortcuts page.shortcuts(false) page.dropperActivated = false console.log('dropper: deactivating page dropper') document.removeEventListener('mousemove', page.onMouseMove, false) document.removeEventListener('click', page.onMouseClick, false) if (page.options.enableRightClickDeactivate === true) { document.removeEventListener('contextmenu', page.onContextMenu, false) } scrollStop(page.onScrollStop, 'stop') page.overlay.deactivate() }, // --------------------------------- // EVENT HANDLING // --------------------------------- onMouseMove: function (e: MouseEvent) { if (!page.dropperActivated) return page.tooltip(e) }, onMouseClick: function (e: MouseEvent) { console.log('dropper: mouse click') console.dir(e) if (!page.dropperActivated) return e.preventDefault() page.dropperDeactivate() const x = e.pageX const y = e.pageY const color = page.pickColor(x, y) console.log(`dropper: click: ${x},${y}. Color: ${color.rgbhex}`) page.sendMessage({ type: 'set-color', color, }) }, onScrollStop: function () { if (!page.dropperActivated) return console.log('dropper: scroll stopped') page.screenChanged() }, onScrollStart: function () { if (!page.dropperActivated) return }, // keyboard shortcuts // enable with argument as true, disable with false shortcuts: function (start: boolean) { // enable shortcuts if (start == true) { shortcut.add('Esc', function (_evt: KeyboardEvent) { page.dropperDeactivate() }) shortcut.add('U', function (_evt: KeyboardEvent) { page.screenChanged(true) }) // disable shortcuts } else { shortcut.remove('U') shortcut.remove('Esc') } }, // right click onContextMenu: function (e: MouseEvent) { if (!page.dropperActivated) return e.preventDefault() page.dropperDeactivate() }, // window is resized onWindowResize: function () { if (!page.dropperActivated) return console.log('dropper: window resized or pixelRatio changed') // set defaults page.defaults() // call screen chaned page.screenChanged() page.overlay.resized({ width: page.width, height: page.height }) }, // --------------------------------- // MISC // --------------------------------- tooltip: function (e: MouseEvent) { if (!page.dropperActivated || page.screenshoting) return const x = e.pageX const y = e.pageY const color = page.pickColor(x, y) console.log(`dropper: move: ${x},${y}. Color: ${color.rgbhex}`) page.overlay.tooltip({ screenWidth: page.screenWidth, screenHeight: page.screenHeight, x, y, color, }) }, // --------------------------------- // COLORS // --------------------------------- pickColor: function (x_coord: number, y_coord: number) { const x = Math.round(x_coord) const y = Math.round(y_coord) if (page.canvasData === null) return const redIndex = y * page.canvas.width * 4 + x * 4 let color: Color = { r: page.canvasData[redIndex], g: page.canvasData[redIndex + 1], b: page.canvasData[redIndex + 2], alpha: page.canvasData[redIndex + 3], } color.rgbhex = page.rgbToHex(color.r, color.g, color.b) color.opposite = page.rgbToHex(255 - color.r, 255 - color.g, 255 - color.b) return color }, // i: color channel value, integer 0-255 // returns two character string hex representation of a color channel (00-FF) toHex: function (i: number) { // TODO this shouldn't happen; looks like offset/x/y might be off by one if (i === undefined) { console.error(`Wrong color channel value: ${i}. Can't convert to hex.`) return 'ff' } var str = i.toString(16) while (str.length < 2) { str = '0' + str } return str }, // r,g,b: color channel value, integer 0-255 // returns six character string hex representation of a color rgbToHex: function (r: number, g: number, b: number) { return `${page.toHex(r)}${page.toHex(g)}${page.toHex(b)}` }, // --------------------------------- // UPDATING SCREEN // --------------------------------- checkCanvas: function () { const scale = window.devicePixelRatio // we have to create new canvas element if ( page.resetCanvas || page.canvas.width != page.width || page.canvas.height != page.height ) { page.canvas = document.createElement('canvas') page.canvas.width = page.width page.canvas.height = page.height console.log( `dropper: creating new canvas ${page.canvas.width}x${page.canvas.height}. Pixel Ratio: ${window.devicePixelRatio}. Page dimension: ${page.width}x${page.height}`, ) page.canvasContext = page.canvas.getContext('2d') page.canvasContext.scale(1 / scale, 1 / scale) page.rects = [] page.resetCanvas = false } }, setScreenshoting: function (state: boolean) { if (page.screenshoting && state) { return } page.screenshoting = state page.overlay.screenshoting(state) }, screenChanged: function (force = false) { if (!page.dropperActivated) return console.log('dropper: screenChanged') page.yOffset = Math.round(document.documentElement.scrollTop) page.xOffset = Math.round(document.documentElement.scrollLeft) const rect = new Rect(page.xOffset, page.yOffset, page.screenWidth, page.screenHeight) console.group(`comparing rect ${rect} with [ ${page.rects.join(', ')} ]`) // don't screenshot if we already have this one if (!force && page.rects.length > 0) { for (let r of page.rects) { if (r.contains(rect)) { console.log('dropper: already shoted, skipping') console.groupEnd() return } } } console.groupEnd() page.setScreenshoting(true) setTimeout(function () { page.sendMessage({ type: 'screenshot', }) }, 50) }, updateRects: function (rect: Rect) { console.group('updateRects') if (page.rects.length === 0) { page.rects.push(rect) console.log('no rects yet, pushing first') console.groupEnd() return } let merged = false page.rects.forEach((r, i) => { console.group(`Trying merge ${rect} with ${r}`) let t = rect.merge(r) if (t !== null) { console.log('merged') merged = true page.rects.splice(i, 1) page.updateRects(t) } console.groupEnd() }) if (!merged) { console.log('dropper: pushing merged to rects') page.rects.push(rect) } console.groupEnd() }, // capture actual Screenshot capture: function () { console.group('capture') page.checkCanvas() console.log('dropper: creating image element and waiting on load') var image = document.createElement('img') image.onload = function () { console.log(`dropper: got new screenshot ${image.width}x${image.height}`) const rect = new Rect( page.xOffset, page.yOffset, Math.round(image.width / window.devicePixelRatio), Math.round(image.height / window.devicePixelRatio), ) page.updateRects(rect) // we changed scale of canvasContext and image data are parsed accroding to this // but unfortunately not sx,sy dimensions so we need to adjust them const scale = window.devicePixelRatio const sx = page.xOffset * scale const sy = page.yOffset * scale console.log( `dropper: drawing image at ${page.xOffset},${page.yOffset} and internally at ${sx},${sy}`, ) page.canvasContext.drawImage(image, sx, sy) // get whole canvas data page.canvasData = page.canvasContext.getImageData( 0, 0, page.canvas.width, page.canvas.height, ).data page.setScreenshoting(false) if (DEV_MODE) { page.sendMessage({ type: 'debug-tab', image: page.canvas.toDataURL() }) } } if (page.imageData) { image.src = page.imageData } else { console.error('ed: no imageData') } console.groupEnd() }, init: function () { page.messageListener() window.onresize = function () { page.onWindowResize() } // FIXME: implement device pixel ration changes same as scrollstop // with some timeout so it works ok during zoom change i.e. const mqString = `(resolution: ${window.devicePixelRatio}dppx)` matchMedia(mqString).addListener(page.onWindowResize) }, } page.init()
the_stack
import { expect } from 'chai'; import { lorem, random } from 'faker'; import sinon from 'sinon'; import { Platform } from '../src/enums'; import { $configuration, CastedObject } from '../src/configuration'; import { SentrySocket } from '../src/socket'; const { word } = lorem; const { boolean } = random; const sandbox = sinon.createSandbox(); describe('Configuration', () => { beforeEach(() => { $configuration.clearInstance(); }); afterEach(() => { sandbox.restore(); }); it('setup should create instance', async () => { // Arrange const storefrontName = 'tr'; const envVar = word(); process.env.envVar = envVar; sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); // Act await $configuration.setup(Platform.Storefront, storefrontName); //Assert expect($configuration.getInstance()).to.be.instanceof($configuration); }); it('setup should create instance and not check if sentry is connected', async () => { // Arrange const storefrontName = 'tr'; const envVar = word(); process.env.envVar = envVar; sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); // Act await $configuration.setup(Platform.Storefront, storefrontName, false); //Assert expect($configuration.getInstance()).to.be.instanceof($configuration); }); it('setup should create instance once', async () => { // Arrange const storefrontName = 'tr'; const envVar = word(); process.env.envVar = envVar; sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); // Act await $configuration.setup(Platform.Storefront, storefrontName); await $configuration.setup(Platform.Gateway, word()); //Assert expect($configuration.getInstance()).to.be.instanceof($configuration); expect($configuration.getName()).to.be.eq(storefrontName); expect($configuration.getPlatform()).to.be.eq(Platform.Storefront); }); it('should throw Error when get is called without setup', () => { // Assert expect($configuration.get).to.throw(); }); describe('when value does not exist in sentry configuration', () => { it('should return value from process environment', async () => { // Arrange const storefrontName = 'tr'; process.env.CUSTOM_ENV_VAR = word(); sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); // Act await $configuration.setup(Platform.Storefront, storefrontName); const envVar = $configuration.get('CUSTOM_ENV_VAR'); // Assert expect(envVar.string).to.be.eq(process.env.CUSTOM_ENV_VAR); }); }); describe('when value exists in sentry configuration', () => { it('should return value when value is boolean', async () => { // Arrange const storefrontName = 'tr'; const envKey = word(); const envValue = boolean(); sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); // Act await $configuration.setup(Platform.Storefront, storefrontName); ($configuration as any).instance.sentryEnv = new Map([[envKey, new CastedObject(envValue)]]); const envVar = $configuration.get(envKey); // Assert expect(envVar.boolean).to.be.eq(envValue); }); it('should return value when envValue is 1', async () => { // Arrange const storefrontName = 'tr'; const envKey = word(); const envValue = 1; sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); // Act await $configuration.setup(Platform.Storefront, storefrontName); ($configuration as any).instance.sentryEnv = new Map([[envKey, new CastedObject(envValue)]]); const envVar = $configuration.get(envKey); // Assert expect(envVar.boolean).to.be.eq(true); expect(envVar.string).to.be.eq('1'); expect(envVar.number).to.be.eq(1); }); it('should return value when envValue is 0', async () => { // Arrange const storefrontName = 'tr'; const envKey = word(); const envValue = 0; sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); // Act await $configuration.setup(Platform.Storefront, storefrontName); ($configuration as any).instance.sentryEnv = new Map([[envKey, new CastedObject(envValue)]]); const envVar = $configuration.get(envKey); // Assert expect(envVar.boolean).to.be.eq(false); expect(envVar.string).to.be.eq('0'); expect(envVar.number).to.be.eq(0); }); it('should return value when envValue is word', async () => { // Arrange const storefrontName = 'tr'; const envKey = word(); const envValue = word(); sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); // Act await $configuration.setup(Platform.Storefront, storefrontName); ($configuration as any).instance.sentryEnv = new Map([[envKey, new CastedObject(envValue)]]); const envVar = $configuration.get(envKey); // Assert expect(envVar.boolean).to.be.eq(Boolean(envValue)); expect(envVar.string).to.be.eq(envValue); }); it('should return value when envValue is string false', async () => { // Arrange const storefrontName = 'tr'; const envKey = word(); const envValue = 'false'; sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); // Act await $configuration.setup(Platform.Storefront, storefrontName); ($configuration as any).instance.sentryEnv = new Map([[envKey, new CastedObject(envValue)]]); const envVar = $configuration.get(envKey); // Assert expect(envVar.boolean).to.be.eq(false); expect(envVar.string).to.be.eq(envValue); }); }); it('shoud return CastedObject with undefined values', async () => { // Arrange const storefrontName = 'tr'; sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); // Act await $configuration.setup(Platform.Storefront, storefrontName); const envVar = $configuration.get(word()); // Assert expect(envVar.boolean).to.be.eq(undefined); expect(envVar.string).to.be.eq(undefined); expect(envVar.number).to.be.eq(undefined); }); it('should update sentryMap', async () => { // Arrange const storefrontName = 'tr'; const updateObject = { key1: word(), key2: word() }; sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); // Act await $configuration.setup(Platform.Storefront, storefrontName); ($configuration.getInstance() as any).updateSentryMap(updateObject); // Assert expect(($configuration.getInstance() as any).sentryEnv).to.be.deep.eq(CastedObject.toMap(updateObject)); }); it('should subscribe for sentry config update ', async () => { // Arrange const gatewayName = 'Browsing'; sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); const callbackData = { key1: word(), key2: word(), }; const onStub = sandbox.stub(); const updateSentryMapStub = sandbox.stub(); // Act await $configuration.setup(Platform.Gateway, gatewayName); ($configuration.getInstance() as any).sentrySocket = { client: { on: onStub.yields(callbackData) } }; ($configuration.getInstance() as any).updateSentryMap = updateSentryMapStub; ($configuration.getInstance() as any).subscribeForSentryConfigUpdate(); // Assert expect(onStub.called).to.be.eq(true); expect(updateSentryMapStub.calledWith(callbackData)).to.be.eq(true); }); it('should not subscribe for sentry config update when received data is not an object ', async () => { // Arrange const gatewayName = 'Browsing'; sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); const callbackData = boolean(); const onStub = sandbox.stub(); const updateSentryMapStub = sandbox.stub(); // Act await $configuration.setup(Platform.Gateway, gatewayName); ($configuration.getInstance() as any).sentrySocket = { client: { on: onStub.yields(callbackData) } }; ($configuration.getInstance() as any).updateSentryMap = updateSentryMapStub; ($configuration.getInstance() as any).subscribeForSentryConfigUpdate(); // Assert expect(onStub.calledWith(`configurations.${Platform.Gateway}.${gatewayName}.update`)).to.be.eq(true); expect(updateSentryMapStub.calledWith(callbackData)).to.be.eq(false); }); it('should get sentry data, and then update sentry map with the data, and then subscribe for sentry config update', async () => { // Arrange const gatewayName = 'Browsing'; sandbox.stub(SentrySocket.prototype, 'connect').callsArgWith(0, true); const getSentryStub = sandbox.stub($configuration.prototype as any, 'getSentryData').callsArg(0); const callbackData = { key1: word(), key2: word(), }; const onStub = sandbox.stub(); const emitStub = sandbox.stub(); const updateSentryMapStub = sandbox.stub(); const resolveStub = sandbox.stub(); const rejectStub = sandbox.stub(); // Act await $configuration.setup(Platform.Gateway, gatewayName); getSentryStub.restore(); ($configuration.getInstance() as any).sentrySocket = { client: { on: onStub.yields(callbackData), emit: emitStub } }; ($configuration.getInstance() as any).updateSentryMap = updateSentryMapStub; ($configuration.getInstance() as any).getSentryData(resolveStub, rejectStub); // Assert expect(onStub.calledWith(`configurations.${Platform.Gateway}.${gatewayName}`)).to.be.eq(true); expect(resolveStub.called).to.be.eq(true); expect(rejectStub.called).to.be.eq(false); expect(updateSentryMapStub.calledWith(callbackData)).to.be.eq(true); expect(emitStub.calledWith(`configurations.${Platform.Gateway}.get`, { name: gatewayName })).to.be.eq(true); }); });
the_stack
import {unzipSync, strFromU8, Unzipped} from 'fflate'; import {JsFilesManifest, SelfContainedFileName} from './Common'; import {ViewerDataByElement} from '../../poly/Common'; import {ModuleName} from '../../poly/registers/modules/Common'; import {DomEffects} from '../../../core/DomEffects'; import {PolyEngine} from '../../Poly'; import {createObjectURL} from '../../../core/BlobUtils'; declare global { interface Window { __POLYGONJS_SELF_CONTAINED___MARK_AS_LOADED_CALLBACK__: () => void; __POLYGONJS_SELF_CONTAINED___POLY__: PolyEngine; } } const url = new URL(window.location.href); const DEBUG = url.searchParams.get('POLY_DEBUG') == '1'; enum LoadingMode { LAZY = 'lazy', EAGER = 'eager', } export class SelfContainedSceneImporter { private _viewerDataByElement: ViewerDataByElement = new Map(); private _firstPolygonjsVersionFound: string | undefined; async load() { window.__POLYGONJS_SELF_CONTAINED___MARK_AS_LOADED_CALLBACK__ = this.markPolygonjsAsLoaded.bind(this); const elements = document.getElementsByTagName('polygonjs-viewer'); // 1 - ensure that all scenes need the same polygonjs engine. // 2 - only display a warning if not // 3 - accumulate list of unzipped content // 4 - load polygonjs // 5 - when polygonjs is loaded, load them one by one for (let i = 0; i < elements.length; i++) { const element = elements[i]; await this._prepareElement(element as HTMLElement); } let firstUnzippedData: Unzipped | undefined; const requiredModules: Set<ModuleName> = new Set(); for (let i = 0; i < elements.length; i++) { const element = elements[i] as HTMLElement; const loadingMode = this._loadingMode(element); switch (loadingMode) { case LoadingMode.EAGER: { // we need await here, to make sure that we only create one script tag at a time // to load polygonjs const unzippedData = await this._getElementViewerData(element as HTMLElement, requiredModules); if (!firstUnzippedData && unzippedData) { firstUnzippedData = unzippedData; } break; } case LoadingMode.LAZY: { const onInteraction = async () => { const unzippedData = await this._getElementViewerData(element as HTMLElement, requiredModules); if (unzippedData) { await this.loadPolygonjs(unzippedData, requiredModules); } element.removeEventListener('click', onInteraction); }; element.addEventListener('click', onInteraction); } } } if (firstUnzippedData) { await this.loadPolygonjs(firstUnzippedData, requiredModules); } } private _loadingMode(element: HTMLElement) { let loadingMode = element.getAttribute('loading') as LoadingMode | null; loadingMode = loadingMode || LoadingMode.EAGER; return loadingMode; } private _prepareElement(element: HTMLElement) { this._setupPoster(element); } private async _getElementViewerData(element: HTMLElement, requiredModules: Set<ModuleName>) { const src = element.getAttribute('src'); if (!src) { console.error('polygonjs-viewer element has no src attribute', element); return; } const response = await fetch(src); const {progressBarContainer, progressBar} = this._addProgressBar(element); // const buffer = await reponse.arrayBuffer(); // const massiveFile = new Uint8Array(buffer); const massiveFile = await this._fetchZipWithProgress(response, (progress, receivedLength, contentLength) => { this._updateProgressBar(progressBar, progress); }); this._fadeOutProgressBar(progressBarContainer); if (!massiveFile) { return; } const unzippedData = unzipSync(massiveFile); const sceneData = JSON.parse(strFromU8(unzippedData[SelfContainedFileName.CODE])); const assetsManifest = JSON.parse(strFromU8(unzippedData[SelfContainedFileName.ASSETS])); const jsFilesManifest: JsFilesManifest = JSON.parse(strFromU8(unzippedData[SelfContainedFileName.JS_FILES])); if (DEBUG) { console.log(unzippedData); console.log(assetsManifest); console.log(jsFilesManifest); } const polygonjsVersion = sceneData.properties?.versions?.polygonjs; if (!polygonjsVersion) { console.error('no engine version found in scene data'); return; } if (this._firstPolygonjsVersionFound) { if (this._firstPolygonjsVersionFound != polygonjsVersion) { console.warn( `WARNING: different versions of polygonjs are requested by different scenes (${polygonjsVersion} and ${this._firstPolygonjsVersionFound})` ); } } else { this._firstPolygonjsVersionFound = polygonjsVersion; } for (let moduleName of jsFilesManifest.modules) { requiredModules.add(moduleName); } this._viewerDataByElement.set(element, { sceneData, assetsManifest, unzippedData, }); return unzippedData; } private _POLYGONJS_LOADED = false; markPolygonjsAsLoaded() { this._POLYGONJS_LOADED = true; window.__POLYGONJS_SELF_CONTAINED___POLY__.selfContainedScenesLoader.load(this._viewerDataByElement); } private async loadPolygonjs(unzippedData: Unzipped, requiredModuleNames: Set<ModuleName>) { if (this._POLYGONJS_LOADED) { window.__POLYGONJS_SELF_CONTAINED___POLY__.selfContainedScenesLoader.load(this._viewerDataByElement); return; } const polygonjsVersion = this._firstPolygonjsVersionFound; if (!polygonjsVersion) { console.warn('no version found, polygonjs will not be loaded'); return; } if (DEBUG) { console.log('loading polygonjsVersion version:', polygonjsVersion); } const polygonjsUrl = this._createJsBlob(unzippedData[SelfContainedFileName.POLYGONJS], 'polygonjs'); if (DEBUG) { console.log('loading polygonjsUrl', polygonjsUrl); } const elementId = `polygonjs-module-viewer-script`; let script = document.getElementById(elementId); const lines: string[] = []; lines.push(`import {Poly, SceneJsonImporter} from '${polygonjsUrl}';`); requiredModuleNames.forEach((moduleName) => { const moduleUrl = this._createJsBlob(unzippedData[`js/modules/${moduleName}.js`], moduleName); lines.push(`import {${moduleName}} from '${moduleUrl}';`); lines.push(`Poly.modulesRegister.register('${moduleName}', ${moduleName});`); }); // lines.push(`Poly.selfContainedScenesLoader.load(window.__POLYGONJS_VIEWER_LOAD_DATA__, SceneJsonImporter);`); lines.push(`window.__POLYGONJS_SELF_CONTAINED___POLY__ = Poly;`); lines.push( `Poly.selfContainedScenesLoader.markAsLoaded(window.__POLYGONJS_SELF_CONTAINED___MARK_AS_LOADED_CALLBACK__, SceneJsonImporter)` ); if (!script) { script = document.createElement('script') as HTMLScriptElement; script.setAttribute('type', 'module'); (script as any).text = lines.join('\n'); document.body.append(script); } } // from https://javascript.info/fetch-progress private async _fetchZipWithProgress( response: Response, progressCallback: (progress: number, receivedLength: number, contentLength: number) => void ) { const body = response.body; const headers = response.headers; if (!body) { console.error('no body in the response'); return; } if (!headers) { console.error('no headers in the response'); return; } const reader = body.getReader(); // Step 2: get total length const contentLength = parseInt(headers.get('Content-Length') || '0'); // Step 3: read the data let receivedLength = 0; // received that many bytes at the moment let chunks: Uint8Array[] = []; // array of received binary chunks (comprises the body) while (true) { const {done, value} = await reader.read(); if (done) { break; } if (value) { chunks.push(value); receivedLength += value.length; } const progress = receivedLength / contentLength; progressCallback(progress, receivedLength, contentLength); } // Step 4: concatenate chunks into single Uint8Array let chunksAll = new Uint8Array(receivedLength); // (4.1) let position = 0; for (let chunk of chunks) { chunksAll.set(chunk, position); // (4.2) position += chunk.length; } return chunksAll; } private _addProgressBar(element: HTMLElement) { const progressBarContainer = document.createElement('div'); const progressBar = document.createElement('div'); element.append(progressBarContainer); progressBarContainer.append(progressBar); progressBarContainer.style.position = 'absolute'; progressBarContainer.style.left = '0px'; progressBarContainer.style.top = '0px'; progressBarContainer.style.width = '100%'; progressBarContainer.style.height = '4px'; progressBar.style.position = 'relative'; progressBar.style.width = '35%'; progressBar.style.height = '100%'; progressBar.style.backgroundColor = 'blue'; return {progressBarContainer, progressBar}; } private _updateProgressBar(progressBar: HTMLElement, progress: number) { const percent = Math.floor(progress * 100); progressBar.style.width = `${percent}%`; if (percent >= 100) { } } private _removeProgressBar(progressBarContainer: HTMLElement) { progressBarContainer.parentElement?.removeChild(progressBarContainer); } private _fadeOutProgressBar(progressBarContainer: HTMLElement) { DomEffects.fadeOut(progressBarContainer).then(() => { this._removeProgressBar(progressBarContainer); }); } private _createJsBlob(array: Uint8Array, filename: string) { const blob = new Blob([array]); const file = new File([blob], `${filename}.js`, {type: 'application/javascript'}); return createObjectURL(file); } private _setupPoster(element: HTMLElement) { const posterUrl = element.getAttribute('poster'); if (!posterUrl) { return; } const posterElement = document.createElement('div'); element.append(posterElement); const loadingMode = this._loadingMode(element); posterElement.setAttribute('data-polygonjs-poster', 'true'); const style = posterElement.style; if (loadingMode == LoadingMode.LAZY) { style.cursor = 'pointer'; } style.position = 'absolute'; style.top = '0px'; style.left = '0px'; style.height = '100%'; style.width = '100%'; style.backgroundImage = `url('${posterUrl}')`; style.backgroundSize = 'cover'; style.backgroundPosition = 'center center'; } }
the_stack
module BABYLON { export class WireFrame2DRenderCache extends ModelRenderCache { effectsReady: boolean = false; vb: WebGLBuffer = null; vtxCount = 0; instancingAttributes: InstancingAttributeInfo[] = null; effect: Effect = null; effectInstanced: Effect = null; render(instanceInfo: GroupInstanceInfo, context: Render2DContext): boolean { // Do nothing if the shader is still loading/preparing if (!this.effectsReady) { if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) { return false; } this.effectsReady = true; } // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data let canvas = instanceInfo.owner.owner; var engine = canvas.engine; var cur = engine.getAlphaMode(); let effect = context.useInstancing ? this.effectInstanced : this.effect; engine.enableEffect(effect); engine.bindBuffersDirectly(this.vb, null, [2, 4], 24, effect); if (context.renderMode !== Render2DContext.RenderModeOpaque) { engine.setAlphaMode(Engine.ALPHA_COMBINE, true); } let pid = context.groupInfoPartData[0]; if (context.useInstancing) { if (!this.instancingAttributes) { this.instancingAttributes = this.loadInstancingAttributes(WireFrame2D.WIREFRAME2D_MAINPARTID, effect); } let glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer; let count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount; canvas._addDrawCallCount(1, context.renderMode); engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes); engine.drawUnIndexed(false, 0, this.vtxCount, count); // engine.draw(true, 0, 6, count); engine.unbindInstanceAttributes(); } else { canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode); for (let i = context.partDataStartIndex; i < context.partDataEndIndex; i++) { this.setupUniforms(effect, 0, pid._partData, i); engine.drawUnIndexed(false, 0, this.vtxCount); // engine.draw(true, 0, 6); } } engine.setAlphaMode(cur, true); return true; } public updateModelRenderCache(prim: Prim2DBase): boolean { let w = prim as WireFrame2D; w._updateVertexBuffer(this); return true; } public dispose(): boolean { if (!super.dispose()) { return false; } if (this.vb) { this._engine._releaseBuffer(this.vb); this.vb = null; } this.effect = null; this.effectInstanced = null; return true; } } @className("WireFrameVertex2D", "BABYLON") export class WireFrameVertex2D { x: number; y: number; r: number; g: number; b: number; a: number; constructor(p: Vector2, c: Color4=null) { this.fromVector2(p); if (c != null) { this.fromColor4(c); } else { this.r = this.g = this.b = this.a = 1; } } fromVector2(p: Vector2) { this.x = p.x; this.y = p.y; } fromColor3(c: Color3) { this.r = c.r; this.g = c.g; this.b = c.b; this.a = 1; } fromColor4(c: Color4) { this.r = c.r; this.g = c.g; this.b = c.b; this.a = c.a; } } @className("WireFrameGroup2D", "BABYLON") /** * A WireFrameGroup2D has a unique id (among the WireFrame2D primitive) and a collection of WireFrameVertex2D which form a Line list. * A Line is defined by two vertices, the storage of vertices doesn't follow the Line Strip convention, so to create consecutive lines the intermediate vertex must be doubled. The best way to build a Line Strip is to use the startLineStrip, pushVertex and endLineStrip methods. * You can manually add vertices using the pushVertex method, but mind that the vertices array must be a multiple of 2 as each line are defined with TWO SEPARATED vertices. I hope this is clear enough. */ export class WireFrameGroup2D { /** * Construct a WireFrameGroup2D object * @param id a unique ID among the Groups added to a given WireFrame2D primitive, if you don't specify an id, a random one will be generated. The id is immutable. * @param defaultColor specify the default color that will be used when a vertex is pushed, white will be used if not specified. */ constructor(id: string=null, defaultColor: Color4=null) { this._id = (id == null) ? Tools.RandomId() : id; this._uid = Tools.RandomId(); this._defaultColor = (defaultColor == null) ? new Color4(1,1,1,1) : defaultColor; this._buildingStrip = false; this._vertices = new Array<WireFrameVertex2D>(); } public get uid() { return this._uid; } /** * Retrieve the ID of the group */ public get id(): string { return this._id; } /** * Push a vertex in the array of vertices. * If you're previously called startLineStrip, the vertex will be pushed twice in order to describe the end of a line and the start of a new one. * @param p Position of the vertex * @param c Color of the vertex, if null the default color of the group will be used */ public pushVertex(p: Vector2, c: Color4=null) { let v = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c); this._vertices.push(v); if (this._buildingStrip) { let v2 = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c); this._vertices.push(v2); } } /** * Start to store a Line Strip. The given vertex will be pushed in the array. The you have to call pushVertex to add subsequent vertices describing the strip and don't forget to call endLineStrip to close the strip!!! * @param p Position of the vertex * @param c Color of the vertex, if null the default color of the group will be used */ public startLineStrip(p: Vector2, c: Color4=null) { this.pushVertex(p, (c == null) ? this._defaultColor : c); this._buildingStrip = true; } /** * Close the Strip by storing a last vertex * @param p Position of the vertex * @param c Color of the vertex, if null the default color of the group will be used */ public endLineStrip(p: Vector2, c: Color4=null) { this._buildingStrip = false; this.pushVertex(p, (c == null) ? this._defaultColor : c); } /** * Access to the array of Vertices, you can manipulate its content but BEWARE of what you're doing! */ public get vertices(): Array<WireFrameVertex2D> { return this._vertices; } private _uid: string; private _id: string; private _defaultColor: Color4; private _vertices: Array<WireFrameVertex2D>; private _buildingStrip: boolean; } @className("WireFrame2D", "BABYLON") /** * Primitive that displays a WireFrame */ export class WireFrame2D extends RenderablePrim2D { static WIREFRAME2D_MAINPARTID = 1; public static wireFrameGroupsProperty: Prim2DPropInfo; @modelLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, pi => WireFrame2D.wireFrameGroupsProperty = pi) /** * Get/set the texture that contains the sprite to display */ public get wireFrameGroups(): StringDictionary<WireFrameGroup2D> { return this._wireFrameGroups; } /** * If you change the content of the wireFrameGroups you MUST call this method for the changes to be reflected during rendering */ public wireFrameGroupsDirty() { this._setFlags(SmartPropertyPrim.flagModelUpdate); this.onPrimBecomesDirty(); } public get size(): Size { if (this._size == null) { this._computeMinMaxTrans(); } return this._size; } public set size(value: Size) { this.internalSetSize(value); } protected updateLevelBoundingInfo(): boolean { let v = this._computeMinMaxTrans(); BoundingInfo2D.CreateFromMinMaxToRef(v.x, v.z, v.y, v.w, this._levelBoundingInfo); return true; } protected levelIntersect(intersectInfo: IntersectInfo2D): boolean { // TODO ! return true; } /** * Create an WireFrame 2D primitive * @param wireFrameGroups an array of WireFrameGroup. * @param settings a combination of settings, possible ones are * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting) * - children: an array of direct children * - id a text identifier, for information purpose * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0] * - rotation: the initial rotation (in radian) of the primitive. default is 0 * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent. * - zOrder: override the zOrder with the specified value * - origin: define the normalized origin point location, default [0.5;0.5] * - alignToPixel: the rendered lines will be aligned to the rendering device' pixels * - isVisible: true if the sprite must be visible, false for hidden. Default is true. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED! * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision). * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString) * - marginHAlignment: one value of the PrimitiveAlignment type's static properties * - marginVAlignment: one value of the PrimitiveAlignment type's static properties * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString) */ constructor(wireFrameGroups: Array<WireFrameGroup2D>, settings?: { parent ?: Prim2DBase, children ?: Array<Prim2DBase>, id ?: string, position ?: Vector2, x ?: number, y ?: number, rotation ?: number, size ?: Size, scale ?: number, scaleX ?: number, scaleY ?: number, dontInheritParentScale?: boolean, opacity ?: number, zOrder ?: number, origin ?: Vector2, alignToPixel ?: boolean, isVisible ?: boolean, isPickable ?: boolean, isContainer ?: boolean, childrenFlatZOrder ?: boolean, levelCollision ?: boolean, deepCollision ?: boolean, layoutData ?: ILayoutData, marginTop ?: number | string, marginLeft ?: number | string, marginRight ?: number | string, marginBottom ?: number | string, margin ?: number | string, marginHAlignment ?: number, marginVAlignment ?: number, marginAlignment ?: string, paddingTop ?: number | string, paddingLeft ?: number | string, paddingRight ?: number | string, paddingBottom ?: number | string, padding ?: number | string, }) { if (!settings) { settings = {}; } super(settings); this._wireFrameGroups = new StringDictionary<WireFrameGroup2D>(); for (let wfg of wireFrameGroups) { this._wireFrameGroups.add(wfg.id, wfg); } this._vtxTransparent = false; if (settings.size != null) { this.size = settings.size; } this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel; } /** * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not */ public get alignToPixel(): boolean { return this._alignToPixel; } public set alignToPixel(value: boolean) { this._alignToPixel = value; } protected createModelRenderCache(modelKey: string): ModelRenderCache { let renderCache = new WireFrame2DRenderCache(this.owner.engine, modelKey); return renderCache; } protected setupModelRenderCache(modelRenderCache: ModelRenderCache) { let renderCache = <WireFrame2DRenderCache>modelRenderCache; let engine = this.owner.engine; // Create the VertexBuffer this._updateVertexBuffer(renderCache); // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one let ei = this.getDataPartEffectInfo(WireFrame2D.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], true); if (ei) { renderCache.effectInstanced = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null); } ei = this.getDataPartEffectInfo(WireFrame2D.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], false); renderCache.effect = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null); return renderCache; } public _updateVertexBuffer(mrc: WireFrame2DRenderCache) { let engine = this.owner.engine; if (mrc.vb != null) { engine._releaseBuffer(mrc.vb); } let vtxCount = 0; this._wireFrameGroups.forEach((k, v) => vtxCount += v.vertices.length); let vb = new Float32Array(vtxCount * 6); let i = 0; this._wireFrameGroups.forEach((k, v) => { for (let vtx of v.vertices) { vb[i++] = vtx.x; vb[i++] = vtx.y; vb[i++] = vtx.r; vb[i++] = vtx.g; vb[i++] = vtx.b; vb[i++] = vtx.a; } }); mrc.vb = engine.createVertexBuffer(vb); mrc.vtxCount = vtxCount; } protected refreshInstanceDataPart(part: InstanceDataBase): boolean { if (!super.refreshInstanceDataPart(part)) { return false; } return true; } private _computeMinMaxTrans(): Vector4 { let xmin = Number.MAX_VALUE; let xmax = Number.MIN_VALUE; let ymin = Number.MAX_VALUE; let ymax = Number.MIN_VALUE; let transparent = false; this._wireFrameGroups.forEach((k, v) => { for (let vtx of v.vertices) { xmin = Math.min(xmin, vtx.x); xmax = Math.max(xmax, vtx.x); ymin = Math.min(ymin, vtx.y); ymax = Math.max(ymax, vtx.y); if (vtx.a < 1) { transparent = true; } } }); this._vtxTransparent = transparent; this._size = new Size(xmax - xmin, ymax - ymin); return new Vector4(xmin, ymin, xmax, ymax); } protected createInstanceDataParts(): InstanceDataBase[] { return [new WireFrame2DInstanceData(WireFrame2D.WIREFRAME2D_MAINPARTID)]; } private _vtxTransparent: boolean; private _wireFrameGroups: StringDictionary<WireFrameGroup2D>; private _alignToPixel: boolean; } export class WireFrame2DInstanceData extends InstanceDataBase { constructor(partId: number) { super(partId, 1); } } }
the_stack
import DocPage from '../../components/DocPage' import DocSection from '../../components/DocSection' import Code from '../../components/Code' export default function Tutorials() { return ( <DocPage name="js-quickstart" title="Tutorials" colour="primary"> Clone it like above. Ensure you can build it. Open <span className="_code"> Logary.sln </span>. Make a change, send a PR towards master. To balance the app.config files, try <span className="_code"> mono tools/paket.exe install --redirects --clean-redirects --createnewbindingfiles</span> <DocSection title='File guidelines – module vs static method' id='file-guidelines'> <p>Declare your interfaces in a <span className="_code"> MyIf.fs </span> and its module in <span className="_code"> MyIfModule.fs </span> with a ([CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)])).</p> <p>Place these files as high as possible. Place the module as close to and below the non-module file as possible.</p> <p>If it's plausible that one would like to use point-free programming with your functions, place them in a module. (E.g. Message versus MessageModule)</p> <p>Factory methods go on the types for value types. For stateful objects they go on the module, named <span className="_code"> create </span> which may or may not return a <span className="_code"> Job[] </span> of some public state type with a private/internal constructor. (E.g. PointName versus Engine)</p> </DocSection> <DocSection title='File guidelines – plural vs singular' id='file-guidelines-plural'> <p>All implementations go in a plural namespace. E.g. <span className="_code"> Logary.Metrics.Ticked </span> has:</p> <ul> <li><span className="_code">Logary</span> – core namespace</li> <li><span className="_code">Metrics</span> – namespace for all metrics implementations</li> <li><span className="_code">Ticked</span> – a module and/or type that implements Logary-based ticking/ scheduling.</li> </ul> <p>Another example: <span className="_code"> Logary.Target </span>, which is a module that implements logic about the life-cycle of target instances. It's used to start/stop/pause and shutdown targets. It's singular.</p> </DocSection> <DocSection title='Namespace guidelines' id='namespaces'> <p>– <span className="_code">Logary.Internals</span> or not</p> <p>Things that end-users of the library are not likely to configure should go in <span className="_code">Logary.Internals</span> . Examples include <span className="_code"> Logary.Internals.Globals </span> and <span className="_code"> Logary.Internals.RuntimeInfo </span> (which is configured with the config API instead).</p> </DocSection> <DocSection title='RuntimeInfo &amp; internal logging' id='ri-and-internal-logging'> <p>The <span className="_code"> RuntimeInfo </span> and internal <span className="_code"> Logger </span> should be propagated to the modules and objects that you build your solution out of. This guideline is mostly about the registry's implementation and its interaction with config and services.</p> </DocSection> <DocSection title='A new function?' id='functions'> <p>Generally, keep your functions to a single responsibility and compose functions instead of extending existing functions. Composition happens through currying and partial application of 'state' or 'always-this-value' values. For state it can both go through the Services abstraction (start/pause/stop/etc) or by closing over the state with a function.</p> <p>If you find that your functions are getting larger than 3 lines of code, you should probably extract part of the function. By 'default' it's better to be 1% less performant but 5% more readable, after this list of priorities:</p> <ol type="1"> <li>Correct</li> <li>CReadable/SRPorrect</li> <li>Fast/efficient/performant</li> </ol> </DocSection> <DocSection title='Opening namespaces' id='opening-namespaces'> <p>Prefer to open a namespace over fully qualifying a type.</p> <p>Prefer to open fully qualified over partial.</p> <Code language="fsharp" value="open Logary.Internals open Logary.Internals.Supervisor" /> <p>Instead of</p> <Code language="fsharp" value="open Logary.Internals open Supervisor" /> </DocSection> <DocSection title='Starting Hopac Jobs' id='hopac-jobs'> <p>A module function like <span className="_code"> MyModule.create: Conf -&gt; Job[T] </span> should not start the server loop. Instead, just return a cold job (that can be started multiple time) and let the composition "root", such as the <span className="_code"> Registry </span>, perform the composition and lifetime handling.</p> </DocSection> <DocSection title='Writing a new target' id='new-target'> <p>Are you thinking of creating a new Target for Logary? It's a good idea if you can't find the right Target for your use case. It can also be useful if you have an internal metrics or log message engine in your company you wish to ship to.</p> <ol type="1"> <li>Create a new .net 4.5.1 class library in F#, under target and add that to Logary.sln.</li> <li>Copy the code from Logary's Targets/Noop.fs, which contains the basic structure. There are more docs in this file, to a file named MyTarget.fs in your new project.</li> <li>Add a nuget reference (or project reference if you're intending to send a PR) to Logary</li> <li>Write your Target and your Target's tests to ensure that it works</li> </ol> <ul> <li>Remember to test when the call to your server throws exceptions or fails</li> <li>You should use <a href="https://github.com/haf/Http.fs"> Http.fs </a> as the HTTP client if it's a HTTP target</li> </ul> <h5>Target guidelines</h5> <p>When writing the Target, it's useful to keep these guidelines in mind.</p> <ul> <li>It should be able to handle shutdown messages from the shutdown channel</li> <li>It should not handle 'unexpected' exceptions, like network loss or a full disk by itself, but instead crash with an exception – the Logary supervisor will restart it after a short duration.</li> <li>Things that are part of the target API, like different response status codes of a REST API should be handled inside the Target.</li> <li>Don't do blocking calls; <ul> <li>Convert <code>Task&lt;_&gt;</code> and <code>Async&lt;_&gt;</code> to <code>Job&lt;_&gt;</code> by using the Hopac <a href="https://hopac.github.io/Hopac/Hopac.html#def:val%20Hopac.Job.fromAsync" rel="nofollow">conversion methods</a></li> <li>If you need to block, use <a href="https://hopac.github.io/Hopac/Hopac.html#def:val%20Hopac.Job.Scheduler.isolate" rel="nofollow">Scheduler.isolate</a> so that your blocking call doesn't stop all Targets.</li> </ul> </li> <li>Choose whether to create a target that can re-send crashing messages by choosing between <code>TargetUtils.[willAwareNamedTarget, stdNamedTarget]</code></li> <li>You can choose between consuming Messages one-by-one through <a href="https://github.com/logary/RingBuffer"><code>RingBuffer.take</code></a> or in batches with <code>RingBuffer.takeBatch</code></li> <li>If you take a batch and the network call to send it off fails, consider sending the batch to the <code>willChannel</code> and throw an exception. Your target will be re-instantiated with the batch and you can now send the messages one-by-one to your target, throwing away poison messages (things that always crash).</li> <li>If your target throws an exception, the batch of Messages or the Message you've taken from the <code>RingBuffer</code> will be gone, unless you send it to the <em>will</em> channel.</li> <li>Exiting the loop will cause your Target to shut down. So don't catch <em>all</em> exceptions without recursing afterwards. The supervisor does <em>not</em> restart targets that exit on their own.</li> <li>If your target can understand a service name, then you should always add the service name from <code>RuntimeInfo.serviceName</code> as passed to your loop function.</li> <li>The <code>RuntimeInfo</code> contains a simple internal logger that you can assume always will accept your Messages. It allows you to debug and log exceptions from your target. By default it will write output to the STDOUT stream.</li> <li>If you don't implement the last-will functionality, a caller that awaits the Promise in <code>Alt&lt;Promise&lt;unit&gt;&gt;</code> as returned from <code>logWithAck</code>, will block forever if your target ever crashes.</li> <li>If you need to do JSON serialisation, consider using <code>Logary.Utils.Chiron</code> and <code>Logary.Utils.Aether</code>, which are vendored copies of <a href="https://github.com/xyncro/chiron">Chiron</a> and <a href="https://github.com/xyncro/aether">Aether</a>. Have a look at the <a href="https://github.com/logary/logary/blob/master/src/targets/Logary.Targets.Logstash/Targets_Logstash.fs">Logstash Target</a> for an example.</li> </ul> <h5>Publishing your target</h5> <p>When your Target is finished, either ping <a href="https://github.com/haf">@haf</a> on github, <a href="https://twitter.com/henrikfeldt" rel="nofollow">@henrikfeldt</a> on twitter, or send a PR to this README with your implementation documented. I can assist in proof-reading your code, to ensure that it follows the empirical lessons learnt operating huge systems with Logary.</p> </DocSection> </DocPage> ) }
the_stack
interface IPhpDebugBarWidget { className?:string; $el?:JQuery; tagName?: string; defaults ?: {}; render?: () => void; initialize? : (options:{}) => void; set?: (attr:string|{}, value:{}) => void; has?: (attr:string) => boolean; get?: (attr:string) => any; bindAttr?: (attr:string, cb:Function) => void; extend ?: (prop:{}) => IPhpDebugBarWidget; } interface IPhpDebugBarDebugBar extends IPhpDebugBarWidget { controls ?: {}; dataMap ?: {}; datasets ?: {}; firstTabName ?: string; activePanelName ?: string; datesetTitleFormater ?: any; /** * Register resize event, for resize debugbar with reponsive css. * * @this {DebugBar} */ registerResizeHandler ?: () => void; /** * Resizes the debugbar to fit the current browser window */ resize ?: () => void; /** * Initialiazes the UI * * @this {DebugBar} */ render ?: () => void; /** * Sets the height of the debugbar body section * Forces the height to lie within a reasonable range * Stores the height in local storage so it can be restored * Resets the document body bottom offset * * @this {DebugBar} */ setHeight ?: (height) => void; /** * Restores the state of the DebugBar using localStorage * This is not called by default in the constructor and * needs to be called by subclasses in their init() method * * @this {DebugBar} */ restoreState ?: () => void; /** * Creates and adds a new tab * * @this {DebugBar} * @param {String} name Internal name * @param {Object} widget A widget object with an element property * @param {String} title The text in the tab, if not specified, name will be used * @return {Item} */ createTab ?: (name, widget, title) => void; /** * Adds a new tab * * @this {DebugBar} * @param {String} name Internal name * @param {Item} tab Tab object * @return {Item} */ addTab ?: (name, tab) => void; /** * Creates and adds an indicator * * @this {DebugBar} * @param {String} name Internal name * @param {String} icon * @param {String} tooltip * @param {String} position "right" or "left", default is "right" * @return {Indicator} */ createIndicator ?: (name, icon, tooltip, position) => void; /** * Adds an indicator * * @this {DebugBar} * @param {String} name Internal name * @param {Indicator} indicator Indicator object * @return {Indicator} */ addIndicator ?: (name, indicator, position) => void; /** * Returns a control * * @param {String} name * @return {Object} */ getControl ?: (name) => void; /** * Checks if there's a control under the specified name * * @this {DebugBar} * @param {String} name * @return {Boolean} */ isControl ?: (name) => void; /** * Checks if a tab with the specified name exists * * @this {DebugBar} * @param {String} name * @return {Boolean} */ isTab ?: (name) => void; /** * Checks if an indicator with the specified name exists * * @this {DebugBar} * @param {String} name * @return {Boolean} */ isIndicator ?: (name) => void; /** * Removes all tabs and indicators from the debug bar and hides it * * @this {DebugBar} */ reset ?: () => void; /** * Open the debug bar and display the specified tab * * @this {DebugBar} * @param {String} name If not specified, display the first tab */ showTab ?: (name) => void; /** * Hide panels and minimize the debug bar * * @this {DebugBar} */ minimize ?: () => void; /** * Checks if the panel is minimized * * @return {Boolean} */ isMinimized ?: () => void; /** * Close the debug bar * * @this {DebugBar} */ close ?: () => void; /** * Restore the debug bar * * @this {DebugBar} */ restore ?: () => void; /** * Recomputes the padding-bottom css property of the body so * that the debug bar never hides any content */ recomputeBottomOffset ?: () => void; /** * Sets the data map used by dataChangeHandler to populate * indicators and widgets * * A data map is an object where properties are control names. * The value of each property should be an array where the first * item is the name of a property from the data object (nested properties * can be specified) and the second item the default value. * * Example: * {"memory": ["memory.peak_usage_str", "0B"]} * * @this {DebugBar} * @param {Object} map */ setDataMap ?: (map) => void; /** * Same as setDataMap() but appends to the existing map * rather than replacing it * * @this {DebugBar} * @param {Object} map */ addDataMap ?: (map) => void; /** * Resets datasets and add one set of data * * For this method to be usefull, you need to specify * a dataMap using setDataMap() * * @this {DebugBar} * @param {Object} data * @return {String} Dataset's id */ setData ?: (data) => void; /** * Adds a dataset * * If more than one dataset are added, the dataset selector * will be displayed. * * For this method to be usefull, you need to specify * a dataMap using setDataMap() * * @this {DebugBar} * @param {Object} data * @param {String} id The name of this set, optional * @param {String} suffix * @return {String} Dataset's id */ addDataSet ?: (data, id, suffix) => void; /** * Loads a dataset using the open handler * * @param {String} id */ loadDataSet ?: (id, suffix, callback) => void; /** * Returns the data from a dataset * * @this {DebugBar} * @param {String} id * @return {Object} */ getDataSet ?: (id) => void; /** * Switch the currently displayed dataset * * @this {DebugBar} * @param {String} id */ showDataSet ?: (id) => void; /** * Called when the current dataset is modified. * * @this {DebugBar} * @param {Object} data */ dataChangeHandler ?: (data) => void; /** * Sets the handler to open past dataset * * @this {DebugBar} * @param {object} handler */ setOpenHandler ?: (handler) => void; /** * Returns the handler to open past dataset * * @this {DebugBar} * @return {object} */ getOpenHandler: () => {}; } interface IPhpDebugBarAjaxHandler extends IPhpDebugBarWidget { /** * Handles an XMLHttpRequest * * @this {IPhpDebugBarAjaxHandler} * @param {XMLHttpRequest} xhr * @return {Bool} */ handle?: (xhr:XMLHttpRequest) => boolean; /** * Checks if the HEADER-id exists and loads the dataset using the open handler * * @param {XMLHttpRequest} xhr * @return {Bool} */ loadFromId?: (xhr:XMLHttpRequest) => boolean; /** * Extracts the id from the HEADER-id * * @param {XMLHttpRequest} xhr * @return {String} */ extractIdFromHeaders?: (xhr:XMLHttpRequest) => string; /** * Checks if the HEADER exists and loads the dataset * * @param {XMLHttpRequest} xhr * @return {Bool} */ loadFromData?: (xhr:XMLHttpRequest) => boolean; /** * Extract the data as a string from headers of an XMLHttpRequest * * @this {IPhpDebugBarAjaxHandler} * @param {XMLHttpRequest} xhr * @return {string} */ extractDataFromHeaders?: (xhr:XMLHttpRequest) => string; /** * Parses the string data into an object * * @this {IPhpDebugBarAjaxHandler} * @param {string} data * @return {string} */ parseHeaders?: (data:string) => string; /** * Attaches an event listener to jQuery.ajaxComplete() * * @this {IPhpDebugBarAjaxHandler} * @param {jQuery} jq Optional */ bindToJquery?: (jq:JQuery) => void; /** * Attaches an event listener to XMLHttpRequest * * @this {IPhpDebugBarAjaxHandler} */ bindToXHR?: () => void; } interface IPhpDebugBarOpenHandler extends IPhpDebugBarWidget { refresh ?: () => void; addSearch?: () => void; handleFind?: (data:any) => void; show?: (callback:any) => void; hide?: () => void; find?: (filters:any, offset:any, callback:any) => void; load?: (id:any, callback:any) => void; clear?: (callback:any) => void; ajax ?: (data:any, callback:any) => void; } interface IPhpDebugBarWidgets { [key: string]: any ListWidget?:IPhpDebugBarWidget; CodexWidget?:any; KVListWidget?:IPhpDebugBarWidget; VariableListWidget?:IPhpDebugBarWidget; IFrameWidget?:IPhpDebugBarWidget; MessagesWidget?:IPhpDebugBarWidget; TimelineWidget?:IPhpDebugBarWidget; ExceptionsWidget?:IPhpDebugBarWidget; htmlize?:(text:string) =>string; renderValue?: (value:any, prettify?:boolean) => string; highlight?:(code:string, lang?:string)=>string; createCodeBlock?:(code:string, lang?:string)=>string; } interface IPhpDebugBarUtils { getDictValue ?: (dict, key, default_value) => any; getObjectSize?:(obj:any)=>number; csscls?:(cls:string, prefix:string) => string; makecsscls?: (prefix:string) => (name:string) => string; } //declare var PhpDebugBar:IPhpDebugBar; declare module phpDebugBar { export class Widget implements IPhpDebugBarWidget { public static extend(props:any); } export class OpenHandler implements IPhpDebugBarOpenHandler { } export class AjaxHandler implements IPhpDebugBarAjaxHandler { } } interface IPhpDebugBar { $?:JQueryStatic, Widgets?:IPhpDebugBarWidgets; Widget?:typeof phpDebugBar.Widget; utils?:IPhpDebugBarUtils; DebugBar?:IPhpDebugBarDebugBar; AjaxHandler:typeof phpDebugBar.AjaxHandler; OpenHandler:typeof phpDebugBar.OpenHandler; } declare var PhpDebugBar:IPhpDebugBar;
the_stack
"use strict"; import * as fs from "fs"; import * as mkdirp from "mkdirp"; import * as _path from "path"; import * as rimraf from "rimraf"; import * as fsgit from "fs-git"; import * as pmb from "packagemanager-backend"; import * as m from "./model"; import * as utils from "./utils"; import Tracker from "./tracker"; export function createManager(options: m.Options = {}): Promise<Manager> { "use strict"; return new Manager(options)._setupBackend(); } export default class Manager { static defaultConfigFile = process.cwd() + "/dtsm.json"; static defaultRootDir = "~/.dtsm"; static defaultRepo = "https://github.com/DefinitelyTyped/DefinitelyTyped.git"; static defaultRef = "master"; static defaultPath = "typings"; static defaultBundleFile = "bundle.d.ts"; configPath = Manager.defaultConfigFile; offline = false; rootDir = Manager.defaultRootDir; repos: pmb.RepositorySpec[] = []; path = Manager.defaultPath; bundle = this.path + "/" + Manager.defaultBundleFile; backend: pmb.Manager<m.GlobalConfig>; tracker: Tracker; savedRecipe: m.Recipe; constructor(options: m.Options = {}) { options = utils.deepClone(options); this.configPath = options.configPath || this.configPath; this.repos = options.repos || this.repos; this.repos = this.repos.map(repo => repo); // copy if (this.repos.length === 0) { this.repos.push({ url: Manager.defaultRepo, ref: Manager.defaultRef }); } if (!this.repos[0].url) { this.repos[0].url = Manager.defaultRepo; } this.offline = options.offline || this.offline; this.tracker = new Tracker(); if (typeof options.insightOptout !== "undefined") { this.tracker.optOut = options.insightOptout; } if (this.tracker.optOut === false) { this.tracker.track(); } this.savedRecipe = this._load(); if (this.savedRecipe) { // for backward compatible let _recipe: any = this.savedRecipe; if (_recipe.baseRepo) { let baseRepo: string = _recipe.baseRepo; let baseRef: string = _recipe.baseRef; delete _recipe.baseRepo; delete _recipe.baseRef; this.savedRecipe.repos = this.savedRecipe.repos || []; this.savedRecipe.repos.unshift({ url: baseRepo, ref: baseRef }); } // for options if (this.repos.length === 0) { this.repos = this.savedRecipe.repos; } else if (options.repos && options.repos.length === 0) { this.repos = this.savedRecipe.repos; } this.rootDir = this.savedRecipe.rootDir || this.rootDir; this.path = this.savedRecipe.path || this.path; } } /** @internal */ _setupBackend(): Promise<Manager> { return pmb.Manager .createManager<m.GlobalConfig>({ rootDir: this.rootDir, repos: this.repos }) .then(backend => { this.backend = backend; return this; }); } /** @internal */ _setupDefaultRecipe() { this.savedRecipe = this.savedRecipe || <any>{}; this.savedRecipe.repos = this.savedRecipe.repos || this.repos; this.savedRecipe.path = this.savedRecipe.path || this.path; this.savedRecipe.bundle = typeof this.savedRecipe.bundle !== "undefined" ? this.savedRecipe.bundle : this.bundle; // for this.recipe.bundle === null this.savedRecipe.link = this.savedRecipe.link || {}; this.savedRecipe.link["npm"] = this.savedRecipe.link["npm"] || { include: true }; this.savedRecipe.dependencies = this.savedRecipe.dependencies || {}; } init(path: string = this.configPath): string { this.tracker.track("init"); this._setupDefaultRecipe(); return this._save(path); } /** @internal */ _load(path: string = this.configPath): m.Recipe { if (fs.existsSync(path)) { let recipe: m.Recipe = JSON.parse(fs.readFileSync(path, "utf8")); // backward compatible if (!recipe.repos || recipe.repos.length === 0) { recipe.repos = [{ url: (<any>recipe).baseRepo, ref: (<any>recipe).baseRef }]; } delete (<any>recipe).baseRepo; delete (<any>recipe).baseRef; return recipe; } else { return null; } } /** @internal */ _save(path: string = this.configPath, recipe: m.Recipe = this.savedRecipe): string { let jsonContent = JSON.stringify(recipe, null, 2); mkdirp.sync(_path.resolve(path, "../")); fs.writeFileSync(path, jsonContent); return jsonContent; } search(phrase: string): Promise<pmb.SearchResult[]> { this.tracker.track("search", phrase); let promises: Promise<any>[]; if (this.offline) { promises = [Promise.resolve(null)]; } else { promises = this.backend.repos.map(repo => { return this._fetchIfOutdated(repo); }); } return Promise.all(promises) .then(() => { return this.backend .search({ globPatterns: [ "**/*.d.ts", "!_infrastructure/**/*" ] }); }) .then((resultList: pmb.SearchResult[]) => resultList.filter(result => result.fileInfo.path.indexOf(phrase) !== -1)) .then((resultList: pmb.SearchResult[]) => this._addWeightingAndSort(phrase, resultList, v => v.fileInfo.path).map(data => data.result)); } install(opts: { save: boolean; dryRun: boolean; }, phrases: string[]): Promise<pmb.Result> { if (phrases) { phrases.forEach(phrase => { this.tracker.track("install", phrase); }); } if (!this.configPath) { return Promise.reject<pmb.Result>("configPath is required"); } if (!fs.existsSync(this.configPath) && opts.save) { return Promise.reject<pmb.Result>(this.configPath + " is not exists"); } this._setupDefaultRecipe(); let promises = phrases.map(phrase => { return this.search(phrase).then(resultList => { if (resultList.length === 1) { return Promise.resolve(resultList[0]); } else if (resultList.length === 0) { return Promise.reject<pmb.SearchResult>(phrase + " is not found"); } else { let fileInfoWithWeight = this._addWeightingAndSort(phrase, resultList, v => v.fileInfo.path)[0]; if (fileInfoWithWeight && fileInfoWithWeight.weight === 1) { return Promise.resolve(fileInfoWithWeight.result); } else { return Promise.reject<pmb.SearchResult>(phrase + " could not be identified. found: " + resultList.length); } } }); }); return Promise.all<pmb.SearchResult>(promises) .then((resultList: pmb.SearchResult[]) => { if (!opts.save || opts.dryRun) { return resultList; } resultList.forEach(result => { let depName = result.fileInfo.path; if (this.savedRecipe.dependencies[depName]) { return; } this.savedRecipe.dependencies[depName] = { repo: result.repo.spec.url, ref: result.fileInfo.ref }; if (this.savedRecipe) { if (this.savedRecipe.repos && this.savedRecipe.repos[0].url === this.savedRecipe.dependencies[depName].repo) { delete this.savedRecipe.dependencies[depName].repo; } } }); this._save(); return resultList; }) .then((resultList: pmb.SearchResult[]) => { let diff: m.Recipe = { repos: this.savedRecipe.repos, path: this.savedRecipe.path, bundle: this.savedRecipe.bundle, dependencies: {} }; resultList.forEach(result => { let depName = result.fileInfo.path; diff.dependencies[depName] = this.savedRecipe.dependencies[depName] || { repo: result.repo.spec.url, ref: result.fileInfo.ref }; }); return this._installFromOptions(diff, opts); }); } installFromFile(opts: { dryRun?: boolean; } = {}, retryWithFetch = true): Promise<pmb.Result> { if (retryWithFetch) { // installFromFile exec recursive, call tracker only once. this.tracker.track("installFromFile"); } if (!this.configPath) { return Promise.reject<pmb.Result>("configPath is required"); } let content = this._load(); if (!content) { return Promise.reject<pmb.Result>(this.configPath + " is not exists"); } return this._installFromOptions(content, opts) .catch(err => { // error raised when specified ref is not fetched yet. if (retryWithFetch) { return this.fetch().then(() => this.installFromFile(opts, false)); } else { return Promise.reject<pmb.Result>(err); } }); } /** @internal */ _installFromOptions(recipe: m.Recipe, opts: { dryRun?: boolean; } = {}): Promise<pmb.Result> { let baseRepo = recipe && recipe.repos && recipe.repos[0] || this.repos[0]; return this.backend .getByRecipe({ baseRepo: baseRepo.url, baseRef: baseRepo.ref, path: recipe.path, dependencies: recipe.dependencies, postProcessForDependency: (result: pmb.Result, depResult: pmb.ResolvedDependency, content: any) => { let dependencies = utils.extractDependencies(content.toString("utf8")); dependencies.forEach(detected => { let obj = result.toDepNameAndPath(detected); result.pushAdditionalDependency(obj.depName, { repo: depResult.repo, ref: depResult.ref, path: obj.path }); }); }, resolveMissingDependency: (result: pmb.Result, missing: pmb.ResolvedDependency): Promise<pmb.Dependency> => { if (missing.depth === 1) { return null; } // first, from current process let newDep: pmb.Dependency = result.dependencies[missing.depName]; if (newDep) { return Promise.resolve(newDep); } // second, from dtsm.json. can't use this.repos in `dtsm --remote .... install ....` context. if (this.savedRecipe) { newDep = this.savedRecipe.dependencies[missing.depName]; let repo = this.savedRecipe.repos[0]; if (newDep && repo) { newDep.repo = newDep.repo || repo.url || Manager.defaultRepo; newDep.ref = newDep.ref || repo.ref || Manager.defaultRef; } return Promise.resolve(newDep); } return Promise.resolve(null); } }).then((result: pmb.Result) => { let errors = result.dependenciesList.filter(depResult => !!depResult.error); if (errors.length !== 0) { // TODO toString return Promise.reject<pmb.Result>(errors); } if (opts.dryRun) { return result; } // create definition files and bundle file result.dependenciesList.forEach(depResult => { this._writeDefinitionFile(recipe, depResult); if (!recipe.bundle) { return; } let depPath = _path.join(_path.dirname(this.configPath), this.path, depResult.depName); this._addReferenceToBundle(recipe, depPath); }); return result; }); } /** @internal */ _addWeightingAndSort<T>(phrase: string, list: T[], getPath: (val: T) => string): { weight: number; result: T; }[] { // TODO add something awesome weighing algorithm. return list .map(value => { let path = getPath(value); // exact match if (path === phrase) { return { weight: 1, result: value }; } // library name match if (path === phrase + "/" + phrase + ".d.ts") { return { weight: 1, result: value }; } // .d.t.s file match if (path.indexOf("/" + phrase + ".d.ts") !== -1) { return { weight: 0.9, result: value }; } // directory name match if (path.indexOf(phrase + "/") === 0) { return { weight: 0.8, result: value }; } // junk return { weight: 0.0, result: value }; }) .sort((a, b) => b.weight - a.weight); } update(opts: { save?: boolean; dryRun?: boolean }): Promise<pmb.Result> { this.tracker.track("update"); if (!this.configPath) { return Promise.reject<pmb.Result>("configPath is required"); } this._setupDefaultRecipe(); // reset ref settings Object.keys(this.savedRecipe.dependencies).map(depName => { this.savedRecipe.dependencies[depName].ref = null; }); return this._installFromOptions(this.savedRecipe, opts) .then(result => { if (opts.dryRun) { return result; } Object.keys(result.dependencies).forEach(depName => { let depResult = result.dependencies[depName]; this._writeDefinitionFile(this.savedRecipe, depResult); if (this.savedRecipe.dependencies[depName]) { this.savedRecipe.dependencies[depName].ref = depResult.fileInfo.ref; } }); if (opts.save) { this._save(); } return result; }); } uninstall(opts: { save?: boolean; dryRun?: boolean }, phrases: string[]): Promise<pmb.ResolvedDependency[]> { this.tracker.track("uninstall"); return this.installFromFile({ dryRun: true }, false) .then(result => { let topLevelDeps = Object.keys(result.dependencies).map(depName => result.dependencies[depName]); if (topLevelDeps.length === 0) { return Promise.reject<pmb.ResolvedDependency[]>("this project doesn't have a dependency tree."); } let promises = phrases.map(phrase => { let weights = this._addWeightingAndSort(phrase, topLevelDeps, dep => dep.depName); weights = weights.filter(w => w.weight !== 0); if (weights.length === 0) { return Promise.reject<pmb.ResolvedDependency>(phrase + " is not found in config file"); } if (weights[0].weight !== 1) { return Promise.reject<pmb.ResolvedDependency>(phrase + " could not be identified. found: " + weights.length); } return Promise.resolve(weights[0].result); }); return Promise.all<pmb.ResolvedDependency>(promises) .then((depList: pmb.ResolvedDependency[]) => { let removeList: pmb.ResolvedDependency[] = []; let addToRemoveList = (dep: pmb.ResolvedDependency) => { if (!dep) { return; } if (removeList.filter(rmDep => rmDep.depName === dep.depName).length !== 0) { return; } removeList.push(dep); if (!dep.dependencies) { return; } Object.keys(dep.dependencies).forEach(depName => { addToRemoveList(dep.dependencies[depName]); }); }; depList.forEach(dep => { // always remove from top level. delete this.savedRecipe.dependencies[dep.depName]; delete result.dependencies[dep.depName]; addToRemoveList(dep); }); if (opts.dryRun) { return depList; } removeList.forEach(dep => { let unused = result.dependenciesList.every(exDep => exDep.depName !== dep.depName); if (unused) { this._removeDefinitionFile(this.savedRecipe, dep); if (!this.savedRecipe.bundle) { return; } let depPath = _path.join(_path.dirname(this.configPath), this.path, dep.depName); this._removeReferenceFromBundle(this.savedRecipe, depPath); } }); if (!opts.save) { return depList; } this._save(); return depList; }); }); } link(opts: { save?: boolean; dryRun?: boolean }): Promise<m.LinkResult[]> { this.tracker.track("link"); if (!this.configPath) { return Promise.reject<m.LinkResult[]>("configPath is required"); } this._setupDefaultRecipe(); if (!this.savedRecipe.bundle) { return Promise.reject<m.LinkResult[]>("bundle is required"); } let linkInfo = this.savedRecipe.link || {}; let resultList: m.LinkResult[] = []; { let depInfo = this._processLink(linkInfo["npm"], "npm", "package.json", "node_modules"); linkInfo["npm"] = depInfo.link; if (!opts || !opts.dryRun) { depInfo.results.forEach(r => { r.files.forEach(filePath => { this._addReferenceToBundle(this.savedRecipe, filePath); }); }); } resultList = resultList.concat(depInfo.results); } { let depInfo = this._processLink(linkInfo["bower"], "bower", "bower.json", "bower_components"); linkInfo["bower"] = depInfo.link; if (!opts || !opts.dryRun) { depInfo.results.forEach(r => { r.files.forEach(filePath => { this._addReferenceToBundle(this.savedRecipe, filePath); }); }); } resultList = resultList.concat(depInfo.results); } this.savedRecipe.link = linkInfo; if (opts && opts.save) { this._save(); } return Promise.resolve(resultList); } /** @internal */ _processLink(linkInfo: m.Link, managerName: string, configFileName: string, moduleDir: string): { link: m.Link; results: m.LinkResult[]; } { if (linkInfo == null) { // continue } else if (!linkInfo.include) { return { link: linkInfo, results: [] }; } linkInfo = linkInfo || { include: true }; let definitionList: m.LinkResult[] = []; let configPath = _path.join(_path.dirname(this.configPath), linkInfo.configPath || configFileName); if (!fs.existsSync(configPath)) { return { link: linkInfo, results: [] }; } let configData = JSON.parse(fs.readFileSync(configPath, { encoding: "utf8" })); ["dependencies", "devDependencies"].forEach(propName => { Object.keys(configData[propName] || {}).forEach(depName => { let depConfigPath = _path.join(_path.dirname(configPath), moduleDir, depName, configFileName); if (!fs.existsSync(depConfigPath)) { return; } let depConfig = JSON.parse(fs.readFileSync(depConfigPath, { encoding: "utf8" })); let definitionInfo = depConfig["typescript"]; if (!definitionInfo) { return; } let resultList: string[] = []; ["definition", "definitions"].forEach(propName => { if (typeof definitionInfo[propName] === "string") { resultList.push(definitionInfo[propName]); } else if (Array.isArray(definitionInfo[propName])) { resultList = resultList.concat(definitionInfo[propName]); } }); definitionList.push({ managerName: managerName, depName: depName, files: resultList.map(filePath => _path.join(_path.dirname(configPath), moduleDir, depName, filePath)) }); }); }); return { link: linkInfo, results: definitionList }; } /** @internal */ _writeDefinitionFile(recipe: m.Recipe, depResult: pmb.ResolvedDependency) { let path = _path.resolve(_path.dirname(this.configPath), recipe.path, depResult.depName); mkdirp.sync(_path.resolve(path, "../")); fs.writeFileSync(path, depResult.content.toString("utf8")); } /** @internal */ _removeDefinitionFile(recipe: m.Recipe, depResult: pmb.ResolvedDependency) { let path = _path.resolve(_path.dirname(this.configPath), recipe.path, depResult.depName); try { fs.unlinkSync(path); let contents = fs.readdirSync(_path.dirname(path)); if (contents.length === 0) { rimraf.sync(_path.dirname(path)); } } catch (e) { // suppress error when path is already removed. } } /** @internal */ _createReferenceComment(bundlePath: string, pathFromCwd: string) { let referencePath = _path.relative(_path.dirname(bundlePath), pathFromCwd); if (_path.posix) { // for windows referencePath = referencePath.replace(new RegExp("\\" + _path.win32.sep, "g"), _path.posix.sep); } return `/// <reference path="${referencePath}" />` + "\n"; } /** @internal */ _addReferenceToBundle(recipe: m.Recipe, pathFromCwd: string) { let bundleContent = ""; let bundlePath = _path.join(_path.dirname(this.configPath), recipe.bundle); if (fs.existsSync(bundlePath)) { bundleContent = fs.readFileSync(bundlePath, "utf8"); } else { mkdirp.sync(_path.dirname(bundlePath)); } let referenceComment = this._createReferenceComment(bundlePath, pathFromCwd); if (bundleContent.indexOf(referenceComment) === -1) { fs.appendFileSync(bundlePath, referenceComment, { encoding: "utf8" }); } } /** @internal */ _removeReferenceFromBundle(recipe: m.Recipe, pathFromCwd: string) { let bundleContent = ""; let bundlePath = _path.join(_path.dirname(this.configPath), recipe.bundle); if (!fs.existsSync(bundlePath)) { return; } bundleContent = fs.readFileSync(bundlePath, "utf8"); let referenceComment = this._createReferenceComment(bundlePath, pathFromCwd); if (bundleContent.indexOf(referenceComment) !== -1) { fs.writeFileSync(bundlePath, bundleContent.replace(referenceComment, ''), { encoding: "utf8" }); } } refs(): Promise<fsgit.RefInfo[]> { let promises: Promise<any>[]; if (this.offline) { promises = [Promise.resolve(null)]; } else { promises = this.backend.repos.map(repo => { return this._fetchIfOutdated(repo); }); } return Promise.all(promises) .then(() => { let repo: pmb.Repo = this.backend.repos[0]; return repo.open().then(fs => fs.showRef()); }); } fetch(): Promise<void> { this.tracker.track("fetch"); let promises = this.backend.repos.map(repo => { return this._fetchRepo(repo); }); return Promise.all(promises).then(() => <any>null); } /** @internal */ _fetchIfOutdated(repo: pmb.Repo): Promise<pmb.Repo> { if (this._checkOutdated(repo.spec.url)) { return this._fetchRepo(repo); } else { return Promise.resolve(repo); } } /** @internal */ _fetchRepo(repo: pmb.Repo): Promise<pmb.Repo> { console.log("fetching " + repo.spec.url); return Promise .resolve(null) .then(() => repo.fetchAll()) .then(() => { this._setLastFetchAt(repo.spec.url); return repo; }); } /** @internal */ _checkOutdated(repoUrl: string): boolean { let fetchAt = this._getLastFetchAt(repoUrl); // 15min return fetchAt + 15 * 60 * 1000 < Date.now(); } /** @internal */ _getLastFetchAt(repoID: string): number { let config: m.GlobalConfig = this.backend.loadConfig() || <any>{}; config.repositories = config.repositories || {}; let repo = config.repositories[repoID] || { fetchAt: null }; return repo.fetchAt; } /** @internal */ _setLastFetchAt(repoID: string, fetchAt: number = Date.now()): void { let config: m.GlobalConfig = this.backend.loadConfig() || <any>{}; config.repositories = config.repositories || {}; config.repositories[repoID] = { fetchAt: fetchAt }; this.backend.saveConfig(config); } }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type ArtworkTestsQueryVariables = {}; export type ArtworkTestsQueryResponse = { readonly artwork: { readonly " $fragmentRefs": FragmentRefs<"Artwork_artworkAboveTheFold">; } | null; }; export type ArtworkTestsQuery = { readonly response: ArtworkTestsQueryResponse; readonly variables: ArtworkTestsQueryVariables; }; /* query ArtworkTestsQuery { artwork(id: "doesn't matter") { ...Artwork_artworkAboveTheFold id } } fragment Artwork_artworkAboveTheFold on Artwork { ...ArtworkHeader_artwork ...CommercialInformation_artwork slug internalID id is_acquireable: isAcquireable is_offerable: isOfferable is_biddable: isBiddable is_inquireable: isInquireable availability } fragment ArtworkHeader_artwork on Artwork { ...ArtworkActions_artwork ...ArtworkTombstone_artwork images { ...ImageCarousel_images } } fragment CommercialInformation_artwork on Artwork { isAcquireable isOfferable isInquireable isInAuction availability saleMessage isForSale artists { isConsignable id } editionSets { id } sale { isClosed isAuction isLiveOpen isPreview liveStartAt endAt startAt id } ...CommercialButtons_artwork ...CommercialPartnerInformation_artwork ...CommercialEditionSetInformation_artwork ...ArtworkExtraLinks_artwork ...AuctionPrice_artwork } fragment CommercialButtons_artwork on Artwork { slug isAcquireable isOfferable isInquireable isInAuction isBuyNowable isForSale editionSets { id } sale { isClosed id } ...BuyNowButton_artwork ...BidButton_artwork ...MakeOfferButton_artwork } fragment CommercialPartnerInformation_artwork on Artwork { availability isAcquireable isForSale isOfferable shippingOrigin shippingInfo priceIncludesTaxDisplay partner { name id } } fragment CommercialEditionSetInformation_artwork on Artwork { editionSets { id internalID saleMessage editionOf dimensions { in cm } } ...CommercialPartnerInformation_artwork } fragment ArtworkExtraLinks_artwork on Artwork { isAcquireable isInAuction isOfferable title isForSale sale { isClosed isBenefit partner { name id } id } artists { isConsignable name id } artist { name id } } fragment AuctionPrice_artwork on Artwork { sale { internalID isWithBuyersPremium isClosed isLiveOpen id } saleArtwork { reserveMessage currentBid { display } counts { bidderPositions } id } myLotStanding(live: true) { activeBid { isWinning id } mostRecentBid { maxBid { display } id } } } fragment BuyNowButton_artwork on Artwork { internalID saleMessage } fragment BidButton_artwork on Artwork { slug sale { slug registrationStatus { qualifiedForBidding id } isPreview isLiveOpen isClosed isRegistrationClosed id } myLotStanding(live: true) { mostRecentBid { maxBid { cents } id } } saleArtwork { increments { cents } id } } fragment MakeOfferButton_artwork on Artwork { internalID } fragment ArtworkActions_artwork on Artwork { id internalID slug title href is_saved: isSaved is_hangable: isHangable artists { name id } image { url } sale { isAuction isClosed id } widthCm heightCm } fragment ArtworkTombstone_artwork on Artwork { title isInAuction medium date cultural_maker: culturalMaker saleArtwork { lotLabel estimate id } partner { name id } sale { isClosed id } artists { name href ...FollowArtistButton_artist id } dimensions { in cm } edition_of: editionOf attribution_class: attributionClass { shortDescription id } } fragment ImageCarousel_images on Image { url: imageURL width height imageVersions deepZoom { image: Image { tileSize: TileSize url: Url format: Format size: Size { width: Width height: Height } } } } fragment FollowArtistButton_artist on Artist { id slug internalID is_followed: isFollowed } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "doesn't matter" } ], v1 = { "kind": "ScalarField", "alias": null, "name": "id", "args": null, "storageKey": null }, v2 = { "kind": "ScalarField", "alias": null, "name": "internalID", "args": null, "storageKey": null }, v3 = { "kind": "ScalarField", "alias": null, "name": "slug", "args": null, "storageKey": null }, v4 = { "kind": "ScalarField", "alias": null, "name": "href", "args": null, "storageKey": null }, v5 = { "kind": "ScalarField", "alias": null, "name": "name", "args": null, "storageKey": null }, v6 = [ (v5/*: any*/), (v1/*: any*/) ], v7 = { "kind": "LinkedField", "alias": null, "name": "partner", "storageKey": null, "args": null, "concreteType": "Partner", "plural": false, "selections": (v6/*: any*/) }, v8 = { "kind": "ScalarField", "alias": null, "name": "cents", "args": null, "storageKey": null }, v9 = { "kind": "ScalarField", "alias": null, "name": "display", "args": null, "storageKey": null }, v10 = { "kind": "LinkedField", "alias": null, "name": "dimensions", "storageKey": null, "args": null, "concreteType": "dimensions", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "in", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "cm", "args": null, "storageKey": null } ] }, v11 = { "kind": "ScalarField", "alias": null, "name": "saleMessage", "args": null, "storageKey": null }, v12 = { "type": "ID", "enumValues": null, "plural": false, "nullable": false }, v13 = { "type": "Boolean", "enumValues": null, "plural": false, "nullable": true }, v14 = { "type": "String", "enumValues": null, "plural": false, "nullable": true }, v15 = { "type": "Float", "enumValues": null, "plural": false, "nullable": true }, v16 = { "type": "Partner", "enumValues": null, "plural": false, "nullable": true }, v17 = { "type": "dimensions", "enumValues": null, "plural": false, "nullable": true }, v18 = { "type": "ID", "enumValues": null, "plural": false, "nullable": true }, v19 = { "type": "Int", "enumValues": null, "plural": false, "nullable": true }, v20 = { "type": "BidderPosition", "enumValues": null, "plural": false, "nullable": true }; return { "kind": "Request", "fragment": { "kind": "Fragment", "name": "ArtworkTestsQuery", "type": "Query", "metadata": null, "argumentDefinitions": [], "selections": [ { "kind": "LinkedField", "alias": null, "name": "artwork", "storageKey": "artwork(id:\"doesn't matter\")", "args": (v0/*: any*/), "concreteType": "Artwork", "plural": false, "selections": [ { "kind": "FragmentSpread", "name": "Artwork_artworkAboveTheFold", "args": null } ] } ] }, "operation": { "kind": "Operation", "name": "ArtworkTestsQuery", "argumentDefinitions": [], "selections": [ { "kind": "LinkedField", "alias": null, "name": "artwork", "storageKey": "artwork(id:\"doesn't matter\")", "args": (v0/*: any*/), "concreteType": "Artwork", "plural": false, "selections": [ (v1/*: any*/), (v2/*: any*/), (v3/*: any*/), { "kind": "ScalarField", "alias": null, "name": "title", "args": null, "storageKey": null }, (v4/*: any*/), { "kind": "ScalarField", "alias": "is_saved", "name": "isSaved", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "is_hangable", "name": "isHangable", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "artists", "storageKey": null, "args": null, "concreteType": "Artist", "plural": true, "selections": [ (v5/*: any*/), (v1/*: any*/), (v4/*: any*/), (v3/*: any*/), (v2/*: any*/), { "kind": "ScalarField", "alias": "is_followed", "name": "isFollowed", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "isConsignable", "args": null, "storageKey": null } ] }, { "kind": "LinkedField", "alias": null, "name": "image", "storageKey": null, "args": null, "concreteType": "Image", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "url", "args": null, "storageKey": null } ] }, { "kind": "LinkedField", "alias": null, "name": "sale", "storageKey": null, "args": null, "concreteType": "Sale", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "isAuction", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "isClosed", "args": null, "storageKey": null }, (v1/*: any*/), { "kind": "ScalarField", "alias": null, "name": "isLiveOpen", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "isPreview", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "liveStartAt", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "endAt", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "startAt", "args": null, "storageKey": null }, (v3/*: any*/), { "kind": "LinkedField", "alias": null, "name": "registrationStatus", "storageKey": null, "args": null, "concreteType": "Bidder", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "qualifiedForBidding", "args": null, "storageKey": null }, (v1/*: any*/) ] }, { "kind": "ScalarField", "alias": null, "name": "isRegistrationClosed", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "isBenefit", "args": null, "storageKey": null }, (v7/*: any*/), (v2/*: any*/), { "kind": "ScalarField", "alias": null, "name": "isWithBuyersPremium", "args": null, "storageKey": null } ] }, { "kind": "ScalarField", "alias": null, "name": "widthCm", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "heightCm", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "isInAuction", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "medium", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "date", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "cultural_maker", "name": "culturalMaker", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "saleArtwork", "storageKey": null, "args": null, "concreteType": "SaleArtwork", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "lotLabel", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "estimate", "args": null, "storageKey": null }, (v1/*: any*/), { "kind": "LinkedField", "alias": null, "name": "increments", "storageKey": null, "args": null, "concreteType": "BidIncrementsFormatted", "plural": true, "selections": [ (v8/*: any*/) ] }, { "kind": "ScalarField", "alias": null, "name": "reserveMessage", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "currentBid", "storageKey": null, "args": null, "concreteType": "SaleArtworkCurrentBid", "plural": false, "selections": [ (v9/*: any*/) ] }, { "kind": "LinkedField", "alias": null, "name": "counts", "storageKey": null, "args": null, "concreteType": "SaleArtworkCounts", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "bidderPositions", "args": null, "storageKey": null } ] } ] }, (v7/*: any*/), (v10/*: any*/), { "kind": "ScalarField", "alias": "edition_of", "name": "editionOf", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": "attribution_class", "name": "attributionClass", "storageKey": null, "args": null, "concreteType": "AttributionClass", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "shortDescription", "args": null, "storageKey": null }, (v1/*: any*/) ] }, { "kind": "LinkedField", "alias": null, "name": "images", "storageKey": null, "args": null, "concreteType": "Image", "plural": true, "selections": [ { "kind": "ScalarField", "alias": "url", "name": "imageURL", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "width", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "height", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "imageVersions", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "deepZoom", "storageKey": null, "args": null, "concreteType": "DeepZoom", "plural": false, "selections": [ { "kind": "LinkedField", "alias": "image", "name": "Image", "storageKey": null, "args": null, "concreteType": "DeepZoomImage", "plural": false, "selections": [ { "kind": "ScalarField", "alias": "tileSize", "name": "TileSize", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "url", "name": "Url", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "format", "name": "Format", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": "size", "name": "Size", "storageKey": null, "args": null, "concreteType": "DeepZoomImageSize", "plural": false, "selections": [ { "kind": "ScalarField", "alias": "width", "name": "Width", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "height", "name": "Height", "args": null, "storageKey": null } ] } ] } ] } ] }, { "kind": "ScalarField", "alias": null, "name": "isAcquireable", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "isOfferable", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "isInquireable", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "availability", "args": null, "storageKey": null }, (v11/*: any*/), { "kind": "ScalarField", "alias": null, "name": "isForSale", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "editionSets", "storageKey": null, "args": null, "concreteType": "EditionSet", "plural": true, "selections": [ (v1/*: any*/), (v2/*: any*/), (v11/*: any*/), { "kind": "ScalarField", "alias": null, "name": "editionOf", "args": null, "storageKey": null }, (v10/*: any*/) ] }, { "kind": "ScalarField", "alias": null, "name": "isBuyNowable", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "myLotStanding", "storageKey": "myLotStanding(live:true)", "args": [ { "kind": "Literal", "name": "live", "value": true } ], "concreteType": "LotStanding", "plural": true, "selections": [ { "kind": "LinkedField", "alias": null, "name": "mostRecentBid", "storageKey": null, "args": null, "concreteType": "BidderPosition", "plural": false, "selections": [ { "kind": "LinkedField", "alias": null, "name": "maxBid", "storageKey": null, "args": null, "concreteType": "BidderPositionMaxBid", "plural": false, "selections": [ (v8/*: any*/), (v9/*: any*/) ] }, (v1/*: any*/) ] }, { "kind": "LinkedField", "alias": null, "name": "activeBid", "storageKey": null, "args": null, "concreteType": "BidderPosition", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "isWinning", "args": null, "storageKey": null }, (v1/*: any*/) ] } ] }, { "kind": "ScalarField", "alias": null, "name": "shippingOrigin", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "shippingInfo", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "priceIncludesTaxDisplay", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "artist", "storageKey": null, "args": null, "concreteType": "Artist", "plural": false, "selections": (v6/*: any*/) }, { "kind": "ScalarField", "alias": "is_acquireable", "name": "isAcquireable", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "is_offerable", "name": "isOfferable", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "is_biddable", "name": "isBiddable", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "is_inquireable", "name": "isInquireable", "args": null, "storageKey": null } ] } ] }, "params": { "operationKind": "query", "name": "ArtworkTestsQuery", "id": "067decf76d93b36b49b506f8c4438362", "text": null, "metadata": { "relayTestingSelectionTypeInfo": { "artwork": { "type": "Artwork", "enumValues": null, "plural": false, "nullable": true }, "artwork.id": (v12/*: any*/), "artwork.slug": (v12/*: any*/), "artwork.internalID": (v12/*: any*/), "artwork.is_acquireable": (v13/*: any*/), "artwork.is_offerable": (v13/*: any*/), "artwork.is_biddable": (v13/*: any*/), "artwork.is_inquireable": (v13/*: any*/), "artwork.availability": (v14/*: any*/), "artwork.images": { "type": "Image", "enumValues": null, "plural": true, "nullable": true }, "artwork.isAcquireable": (v13/*: any*/), "artwork.isOfferable": (v13/*: any*/), "artwork.isInquireable": (v13/*: any*/), "artwork.isInAuction": (v13/*: any*/), "artwork.saleMessage": (v14/*: any*/), "artwork.isForSale": (v13/*: any*/), "artwork.artists": { "type": "Artist", "enumValues": null, "plural": true, "nullable": true }, "artwork.editionSets": { "type": "EditionSet", "enumValues": null, "plural": true, "nullable": true }, "artwork.sale": { "type": "Sale", "enumValues": null, "plural": false, "nullable": true }, "artwork.title": (v14/*: any*/), "artwork.href": (v14/*: any*/), "artwork.is_saved": (v13/*: any*/), "artwork.is_hangable": (v13/*: any*/), "artwork.image": { "type": "Image", "enumValues": null, "plural": false, "nullable": true }, "artwork.widthCm": (v15/*: any*/), "artwork.heightCm": (v15/*: any*/), "artwork.medium": (v14/*: any*/), "artwork.date": (v14/*: any*/), "artwork.cultural_maker": (v14/*: any*/), "artwork.saleArtwork": { "type": "SaleArtwork", "enumValues": null, "plural": false, "nullable": true }, "artwork.partner": (v16/*: any*/), "artwork.dimensions": (v17/*: any*/), "artwork.edition_of": (v14/*: any*/), "artwork.attribution_class": { "type": "AttributionClass", "enumValues": null, "plural": false, "nullable": true }, "artwork.artists.isConsignable": (v13/*: any*/), "artwork.artists.id": (v12/*: any*/), "artwork.editionSets.id": (v12/*: any*/), "artwork.sale.isClosed": (v13/*: any*/), "artwork.sale.isAuction": (v13/*: any*/), "artwork.sale.isLiveOpen": (v13/*: any*/), "artwork.sale.isPreview": (v13/*: any*/), "artwork.sale.liveStartAt": (v14/*: any*/), "artwork.sale.endAt": (v14/*: any*/), "artwork.sale.startAt": (v14/*: any*/), "artwork.sale.id": (v18/*: any*/), "artwork.isBuyNowable": (v13/*: any*/), "artwork.shippingOrigin": (v14/*: any*/), "artwork.shippingInfo": (v14/*: any*/), "artwork.priceIncludesTaxDisplay": (v14/*: any*/), "artwork.artist": { "type": "Artist", "enumValues": null, "plural": false, "nullable": true }, "artwork.myLotStanding": { "type": "LotStanding", "enumValues": null, "plural": true, "nullable": true }, "artwork.artists.name": (v14/*: any*/), "artwork.image.url": (v14/*: any*/), "artwork.saleArtwork.lotLabel": (v14/*: any*/), "artwork.saleArtwork.estimate": (v14/*: any*/), "artwork.saleArtwork.id": (v18/*: any*/), "artwork.partner.name": (v14/*: any*/), "artwork.partner.id": (v18/*: any*/), "artwork.artists.href": (v14/*: any*/), "artwork.dimensions.in": (v14/*: any*/), "artwork.dimensions.cm": (v14/*: any*/), "artwork.attribution_class.shortDescription": (v14/*: any*/), "artwork.attribution_class.id": (v18/*: any*/), "artwork.images.url": (v14/*: any*/), "artwork.images.width": (v19/*: any*/), "artwork.images.height": (v19/*: any*/), "artwork.images.imageVersions": { "type": "String", "enumValues": null, "plural": true, "nullable": true }, "artwork.images.deepZoom": { "type": "DeepZoom", "enumValues": null, "plural": false, "nullable": true }, "artwork.editionSets.internalID": (v12/*: any*/), "artwork.editionSets.saleMessage": (v14/*: any*/), "artwork.editionSets.editionOf": (v14/*: any*/), "artwork.editionSets.dimensions": (v17/*: any*/), "artwork.sale.isBenefit": (v13/*: any*/), "artwork.sale.partner": (v16/*: any*/), "artwork.artist.name": (v14/*: any*/), "artwork.artist.id": (v18/*: any*/), "artwork.sale.internalID": (v12/*: any*/), "artwork.sale.isWithBuyersPremium": (v13/*: any*/), "artwork.saleArtwork.reserveMessage": (v14/*: any*/), "artwork.saleArtwork.currentBid": { "type": "SaleArtworkCurrentBid", "enumValues": null, "plural": false, "nullable": true }, "artwork.saleArtwork.counts": { "type": "SaleArtworkCounts", "enumValues": null, "plural": false, "nullable": true }, "artwork.myLotStanding.activeBid": (v20/*: any*/), "artwork.myLotStanding.mostRecentBid": (v20/*: any*/), "artwork.artists.slug": (v12/*: any*/), "artwork.artists.internalID": (v12/*: any*/), "artwork.artists.is_followed": (v13/*: any*/), "artwork.images.deepZoom.image": { "type": "DeepZoomImage", "enumValues": null, "plural": false, "nullable": true }, "artwork.sale.slug": (v12/*: any*/), "artwork.sale.registrationStatus": { "type": "Bidder", "enumValues": null, "plural": false, "nullable": true }, "artwork.sale.isRegistrationClosed": (v13/*: any*/), "artwork.saleArtwork.increments": { "type": "BidIncrementsFormatted", "enumValues": null, "plural": true, "nullable": true }, "artwork.editionSets.dimensions.in": (v14/*: any*/), "artwork.editionSets.dimensions.cm": (v14/*: any*/), "artwork.sale.partner.name": (v14/*: any*/), "artwork.sale.partner.id": (v18/*: any*/), "artwork.saleArtwork.currentBid.display": (v14/*: any*/), "artwork.saleArtwork.counts.bidderPositions": { "type": "FormattedNumber", "enumValues": null, "plural": false, "nullable": true }, "artwork.myLotStanding.activeBid.isWinning": (v13/*: any*/), "artwork.myLotStanding.activeBid.id": (v18/*: any*/), "artwork.myLotStanding.mostRecentBid.maxBid": { "type": "BidderPositionMaxBid", "enumValues": null, "plural": false, "nullable": true }, "artwork.myLotStanding.mostRecentBid.id": (v18/*: any*/), "artwork.images.deepZoom.image.tileSize": (v19/*: any*/), "artwork.images.deepZoom.image.url": (v14/*: any*/), "artwork.images.deepZoom.image.format": (v14/*: any*/), "artwork.images.deepZoom.image.size": { "type": "DeepZoomImageSize", "enumValues": null, "plural": false, "nullable": true }, "artwork.sale.registrationStatus.qualifiedForBidding": (v13/*: any*/), "artwork.sale.registrationStatus.id": (v18/*: any*/), "artwork.saleArtwork.increments.cents": (v15/*: any*/), "artwork.myLotStanding.mostRecentBid.maxBid.display": (v14/*: any*/), "artwork.images.deepZoom.image.size.width": (v19/*: any*/), "artwork.images.deepZoom.image.size.height": (v19/*: any*/), "artwork.myLotStanding.mostRecentBid.maxBid.cents": (v15/*: any*/) } } } }; })(); (node as any).hash = 'd067b32ad76e98e236f5c6c651e5323b'; export default node;
the_stack
import json from '@rollup/plugin-json' import type { BuildOptions as ESBuildOptions } from 'esbuild' import * as FS from 'fs' import * as Path from 'path' import type { OutputOptions, Plugin, RollupOptions } from 'rollup' import dts from 'rollup-plugin-dts' import { TopologicalSort } from 'topological-sort' import type { CompilerOptions, ModuleKind, parseJsonSourceFileConfigFileContent, readJsonConfigFile, sys, } from 'typescript' import { inspect } from 'util' import { esbuild } from './rollup-plugin-esbuild' import glob from 'fast-glob' export type BuildKind = 'dts' | 'bundle' export type ExtendedOutputOptions = ( | OutputOptions | ({ format: 'dts' } & Omit<OutputOptions, 'format'>) ) & { bundle?: boolean | ESBuildOptions } export interface BuildConfig { useMain: boolean sources: Record<string, ExtendedOutputOptions[]> external: string[] } export interface PackageJson { name?: string version?: string main?: string module?: string unpkg?: string types?: string dependencies: Record<string, string> devDependencies: Record<string, string> peerDependencies: Record<string, string> buildConfig: BuildConfig publishConfig: Partial<{ main: string module: string types: string unpkg: string }> } export interface PackageInfo { packageRoot: string packageJson: PackageJson tsconfig?: { configFile: string configOptions: CompilerOptions } rollupOptions: RollupOptions & { input: string output: OutputOptions[] external: string[] plugins: Plugin[] } } export interface GenerateOptions { rootDir?: string dirPatterns?: string[] extend(kind: BuildKind, info: PackageInfo): RollupOptions | RollupOptions[] } export function generateRollupOptions( options: GenerateOptions, ): RollupOptions[] { const typeConfigs: RollupOptions[] = [] const configs: RollupOptions[] = [] const packagesDir = options.rootDir != null ? Path.isAbsolute(options.rootDir) ? options.rootDir : Path.resolve(process.cwd(), options.rootDir) : process.cwd() const { packageNames, resolvedPackages } = getPackages( packagesDir, options.dirPatterns ?? ['**'], ) const filterByFormat = createFilter<ExtendedOutputOptions>( process.env['BUILD_FORMATS'], (value) => [value.format], ) const filterBySource = createFilter<string>( process.env['BUILD_SOURCES'], (value) => [value], ) const filterByPackageName = createFilter<string>( process.env['BUILD_PACKAGES'], (value) => [resolvedPackages.get(value)?.name, value], ) packageNames.filter(filterByPackageName).forEach((packageName) => { const project = (...segments: string[]): string => { return Path.resolve(packagesDir, packageName, ...segments) } const projectIf = (...segments: string[]): string | undefined => { const fileName = project(...segments) if (FS.existsSync(fileName)) return fileName else return undefined } const packageJson = resolvedPackages.get(packageName) if (packageJson == null) return // should never happen. const external = [ ...Object.keys(packageJson.dependencies), ...Object.keys(packageJson.peerDependencies), ...(packageJson.buildConfig.external ?? []), ] const sources: BuildConfig['sources'] = { ...packageJson.buildConfig.sources, } if (packageJson.buildConfig.useMain) { const key = packageJson.main?.endsWith('.ts') === true ? packageJson.main : 'src/index.ts' const outputs = Object.entries({ ...packageJson, ...packageJson.publishConfig, }) .map(([key, value]) => ({ key, value })) .filter((item): item is { key: 'main' | 'module' | 'types' | 'unpkg' value: string } => /^(main|module|unpkg|types)$/.test(item.key)) .map<ExtendedOutputOptions>(({ key: type, value: file }) => ({ file: file, format: type === 'main' ? 'commonjs' : type === 'unpkg' ? 'iife' : type === 'types' ? 'dts' : 'module', })) if (key in sources) { sources[key] = [...outputs, ...(sources[key] ?? [])] } else { sources[key] = outputs } } let tsconfig: PackageInfo['tsconfig'] const configFile = projectIf('tsconfig.json') if (configFile != null) { tsconfig = { configFile, configOptions: getTSConfig(configFile), } } Object.entries(sources) .filter(([input]) => filterBySource(input)) .forEach(([input, outputs]) => { const types = Array.from(outputs) .filter(filterByFormat) .filter((output) => output.format === 'dts') .map<OutputOptions>(({ bundle, ...output }) => ({ sourcemap: false, ...output, file: output.file != null ? project(output.file) : output.file, format: 'module', })) const bundles = Array.from(outputs) .filter(filterByFormat) .filter( ( output, ): output is OutputOptions & { bundle?: boolean | ESBuildOptions } => output.format !== 'dts', ) .map<OutputOptions>(({ bundle, ...output }) => ({ sourcemap: true, preferConst: true, exports: 'auto', ...output, file: output.file != null ? project(output.file) : output.file, plugins: bundle != null && bundle !== false ? [ esbuild(bundle, () => { // TODO: Get final external option. return external }), ] : [], })) const relInput = Path.relative(process.cwd(), project(input)) const packageRoot = project('.') if (types.length > 0) { const config = options.extend('dts', { packageRoot, packageJson, tsconfig, rollupOptions: { input: relInput, output: types, external: external.slice(), plugins: [ json(), dts({ respectExternal: true, compilerOptions: tsconfig?.configOptions, }), ], }, }) typeConfigs.push(...(Array.isArray(config) ? config : [config])) } if (bundles.length > 0) { const config = options.extend('bundle', { packageRoot, packageJson, tsconfig, rollupOptions: { input: relInput, output: bundles, external: external.slice(), plugins: [], }, }) configs.push(...(Array.isArray(config) ? config : [config])) } }) }) // FIXME: Disable eslint rule as it conflicts with typescript config. // eslint-disable-next-line @typescript-eslint/dot-notation if (process.env['DEBUG'] === 'rollup-monorepo-utils') { console.log('Generated rollup configs:', inspect(configs, false, 4)) } return [...typeConfigs, ...configs] } export function getPackages( rootDir: string, patterns: string[] = ['**'], ): { packageNames: string[] fullPackageNames: string[] resolvedPackages: Map<string, PackageJson> } { const packageJsonFiles = glob.sync( patterns.map((pattern) => `${pattern.replace(/\/$/, '')}/package.json`), { cwd: rootDir, onlyFiles: true, ignore: ['**/node_modules/**'], }, ) const resolvedPackages = new Map<string, PackageJson>() const nodes = new Map<string, string>() packageJsonFiles.forEach((packageJsonFile) => { const packageRelativePath = Path.dirname(packageJsonFile) const packageFile = Path.resolve(rootDir, packageJsonFile) if (FS.existsSync(packageFile)) { const rawPackageJson = JSON.parse( FS.readFileSync(packageFile, 'utf-8'), ) as Partial<PackageJson> const packageJson: PackageJson = { dependencies: {}, devDependencies: {}, peerDependencies: {}, publishConfig: {}, ...rawPackageJson, buildConfig: { useMain: true, sources: {}, external: [], ...rawPackageJson.buildConfig, }, } resolvedPackages.set(packageRelativePath, packageJson) nodes.set(packageJson.name ?? packageRelativePath, packageRelativePath) } }) const sortOp = new TopologicalSort(nodes) resolvedPackages.forEach((packageJson, packageName) => { new Set([ ...Object.keys(packageJson.dependencies), ...Object.keys(packageJson.devDependencies), ]).forEach((dependencyName) => { if (nodes.has(dependencyName)) { sortOp.addEdge(dependencyName, packageJson.name ?? packageName) } }) }) const sortedPackageNames = Array.from(sortOp.sort().keys()) const packageDirNames = sortedPackageNames.map((key) => nodes.get(key) ?? key) return { packageNames: packageDirNames, fullPackageNames: sortedPackageNames, resolvedPackages, } } const TS_CONFIG_CACHE = new Map<string, CompilerOptions>() function getTSConfig(configFile: string): CompilerOptions { if (TS_CONFIG_CACHE.has(configFile)) return TS_CONFIG_CACHE.get(configFile) ?? {} // Load typescript package from current working directory. // eslint-disable-next-line @typescript-eslint/no-var-requires const ts = require('typescript') as { parseJsonSourceFileConfigFileContent: typeof parseJsonSourceFileConfigFileContent readJsonConfigFile: typeof readJsonConfigFile ModuleKind: typeof ModuleKind sys: typeof sys } const configSource = ts.readJsonConfigFile(configFile, ts.sys.readFile) const parsed = ts.parseJsonSourceFileConfigFileContent( configSource, ts.sys, Path.dirname(configFile), ) return parsed.options } function createFilter<T>( matchRE: string | undefined, getter: (value: T) => Array<string | undefined>, ): (value: T) => boolean { if (matchRE == null) return () => true const RE = matchRE.startsWith('/') ? new RegExp(matchRE.substring(1, matchRE.lastIndexOf('/'))) : new RegExp(matchRE, 'i') return (value) => getter(value) .filter((id): id is string => id != null) .some((id) => RE.test(id)) }
the_stack
import { createMemoryHistory } from "history" import React from "react" import { findRenderedComponentWithType } from "react-dom/test-utils" import ReactModal from "react-modal" import { MemoryRouter } from "react-router" import HUD, { mergeAppUpdate } from "./HUD" import LogStore from "./LogStore" import { SocketBarRoot } from "./SocketBar" import { renderTestComponent } from "./test-helpers" import { logList, nButtonView, nResourceView, oneResourceView, twoResourceView, } from "./testdata" import { SocketState } from "./types" // Note: `body` is used as the app element _only_ in a test env // since the app root element isn't available; in prod, it should // be set as the app root so that accessibility features are set correctly ReactModal.setAppElement(document.body) const fakeHistory = createMemoryHistory() const interfaceVersion = { isNewDefault: () => false, toggleDefault: () => {} } const emptyHUD = () => { return ( <MemoryRouter initialEntries={["/"]}> <HUD history={fakeHistory} interfaceVersion={interfaceVersion} /> </MemoryRouter> ) } beforeEach(() => { Date.now = jest.fn(() => 1482363367071) }) it("renders reconnecting bar", async () => { const { rootTree, container } = renderTestComponent<HUD>(emptyHUD()) expect(container.textContent).toEqual(expect.stringContaining("Loading")) const hud = findRenderedComponentWithType(rootTree, HUD) hud.setState({ view: oneResourceView(), socketState: SocketState.Reconnecting, }) let socketBar = Array.from(container.querySelectorAll(SocketBarRoot)) expect(socketBar).toHaveLength(1) expect(socketBar[0].textContent).toEqual( expect.stringContaining("reconnecting") ) }) it("loads logs incrementally", async () => { const { rootTree } = renderTestComponent<HUD>(emptyHUD()) const hud = findRenderedComponentWithType(rootTree, HUD) let now = new Date().toString() let resourceView = oneResourceView() resourceView.logList = { spans: { "": {}, }, segments: [ { text: "line1\n", time: now }, { text: "line2\n", time: now }, ], fromCheckpoint: 0, toCheckpoint: 2, } hud.onAppChange({ view: resourceView }) let resourceView2 = oneResourceView() resourceView2.logList = { spans: { "": {}, }, segments: [ { text: "line3\n", time: now }, { text: "line4\n", time: now }, ], fromCheckpoint: 2, toCheckpoint: 4, } hud.onAppChange({ view: resourceView2 }) let snapshot = hud.snapshotFromState(hud.state) expect(snapshot.view?.logList).toEqual({ spans: { _: { manifestName: "" }, }, segments: [ { text: "line1\n", time: now, spanId: "_" }, { text: "line2\n", time: now, spanId: "_" }, { text: "line3\n", time: now, spanId: "_" }, { text: "line4\n", time: now, spanId: "_" }, ], }) }) it("renders logs to snapshot", async () => { const { rootTree } = renderTestComponent<HUD>(emptyHUD()) const hud = findRenderedComponentWithType(rootTree, HUD) let now = new Date().toString() let resourceView = oneResourceView() resourceView.logList = { spans: { "": {}, }, segments: [ { text: "line1\n", time: now, level: "WARN" }, { text: "line2\n", time: now, fields: { buildEvent: "1" } }, ], fromCheckpoint: 0, toCheckpoint: 2, } hud.onAppChange({ view: resourceView }) let snapshot = hud.snapshotFromState(hud.state) expect(snapshot.view?.logList).toEqual({ spans: { _: { manifestName: "" }, }, segments: [ { text: "line1\n", time: now, spanId: "_", level: "WARN" }, { text: "line2\n", time: now, spanId: "_", fields: { buildEvent: "1" } }, ], }) }) describe("mergeAppUpdates", () => { // It's important to maintain reference equality when nothing changes. it("handles no view update", () => { let resourceView = oneResourceView() let prevState = { view: resourceView } let result = mergeAppUpdate(prevState as any, {}) as any expect(result).toBe(null) }) it("handles empty view update", () => { let resourceView = oneResourceView() let prevState = { view: resourceView } let result = mergeAppUpdate(prevState as any, { view: {} }) expect(result).toBe(null) }) it("handles replace view update", () => { let prevState = { view: oneResourceView() } let update = { view: oneResourceView() } let result = mergeAppUpdate(prevState as any, update) expect(result!.view).not.toBe(update.view) expect(result!.view).not.toBe(prevState.view) expect(result!.view.uiSession).toBe(update.view.uiSession) }) it("handles add resource", () => { let prevState = { view: oneResourceView() } let update = { view: { uiResources: [twoResourceView().uiResources[1]] } } let result = mergeAppUpdate(prevState as any, update) expect(result!.view).not.toBe(prevState.view) expect(result!.view.uiSession).toBe(prevState.view.uiSession) expect(result!.view.uiResources!.length).toEqual(2) expect(result!.view.uiResources![0].metadata!.name).toEqual("vigoda") expect(result!.view.uiResources![1].metadata!.name).toEqual("snack") }) it("handles add resource out of order", () => { let prevState = { view: nResourceView(10) } let addedResources = prevState.view.uiResources.splice(3, 1) let update = { view: { uiResources: addedResources } } let result = mergeAppUpdate(prevState as any, update) expect(result!.view).not.toBe(prevState.view) expect(result!.view.uiSession).toBe(prevState.view.uiSession) expect(result!.view.uiResources).toEqual(nResourceView(10).uiResources) }) it("handles add button out of order", () => { let prevState = { view: nButtonView(9) } let addedButtons = prevState.view.uiButtons.splice(3, 1) let update = { view: { uiButtons: addedButtons } } let result = mergeAppUpdate(prevState as any, update) expect(result!.view).not.toBe(prevState.view) expect(result!.view.uiSession).toBe(prevState.view.uiSession) expect(result!.view.uiButtons).toEqual(nButtonView(9).uiButtons) }) it("handles delete resource", () => { let prevState = { view: twoResourceView() } let update = { view: { uiResources: [ { metadata: { name: "vigoda", deletionTimestamp: new Date().toString(), }, }, ], }, } let result = mergeAppUpdate(prevState as any, update) expect(result!.view).not.toBe(prevState.view) expect(result!.view.uiResources!.length).toEqual(1) expect(result!.view.uiResources![0].metadata!.name).toEqual("snack") }) it("handles replace resource", () => { let prevState = { view: twoResourceView() } let update = { view: { uiResources: [{ metadata: { name: "vigoda" } }] } } let result = mergeAppUpdate(prevState as any, update) expect(result!.view).not.toBe(prevState.view) expect(result!.view.uiResources!.length).toEqual(2) expect(result!.view.uiResources![0]).toBe(update.view.uiResources[0]) expect(result!.view.uiResources![1]).toBe(prevState.view.uiResources[1]) }) it("handles add button", () => { let prevState = { view: nButtonView(1) } let update = { view: { uiButtons: [nButtonView(2).uiButtons[1]] } } let result = mergeAppUpdate(prevState as any, update) expect(result!.view).not.toBe(prevState.view) expect(result!.view.uiSession).toBe(prevState.view.uiSession) expect(result!.view.uiResources).toBe(prevState.view.uiResources) expect(result!.view.uiButtons!.length).toEqual(2) expect(result!.view.uiButtons![0].metadata!.name).toEqual("button1") expect(result!.view.uiButtons![1].metadata!.name).toEqual("button2") }) it("handles delete button", () => { let prevState = { view: nButtonView(2) } let update = { view: { uiButtons: [ { metadata: { name: "button1", deletionTimestamp: new Date().toString(), }, }, ], }, } let result = mergeAppUpdate(prevState as any, update) expect(result!.view).not.toBe(prevState.view) expect(result!.view.uiResources).toBe(prevState.view.uiResources) expect(result!.view.uiButtons!.length).toEqual(1) expect(result!.view.uiButtons![0].metadata!.name).toEqual("button2") }) it("handles replace button", () => { let prevState = { view: nButtonView(2) } let update = { view: { uiButtons: [{ metadata: { name: "button1" } }] } } let result = mergeAppUpdate(prevState as any, update) expect(result!.view).not.toBe(prevState.view) expect(result!.view.uiResources).toBe(prevState.view.uiResources) expect(result!.view.uiButtons!.length).toEqual(2) expect(result!.view.uiButtons![0]).toBe(update.view.uiButtons[0]) expect(result!.view.uiButtons![1]).toBe(prevState.view.uiButtons[1]) }) it("handles socket state", () => { let prevState = { view: twoResourceView(), socketState: SocketState.Active } let update = { socketState: SocketState.Reconnecting } let result = mergeAppUpdate(prevState as any, update) as any expect(result!.view).toBe(prevState.view) expect(result!.socketState).toBe(SocketState.Reconnecting) }) it("handles complete view", () => { let prevLogStore = new LogStore() let prevState = { view: twoResourceView(), logStore: prevLogStore } let update = { view: { uiResources: [{ metadata: { name: "b" } }, { metadata: { name: "a" } }], uiButtons: [{ metadata: { name: "z" } }, { metadata: { name: "y" } }], logList: logList(["line1", "line2"]), isComplete: true, }, } let result = mergeAppUpdate<"view" | "logStore">(prevState as any, update) expect(result!.view).toBe(update.view) expect(result!.logStore).not.toBe(prevState.logStore) expect(result!.logStore?.allLog().map((ll) => ll.text)).toEqual([ "line1", "line2", ]) const expectedResourceOrder = ["a", "b"] expect(result!.view.uiResources?.map((r) => r.metadata!.name)).toEqual( expectedResourceOrder ) const expectedButtonOrder = ["y", "z"] expect(result!.view.uiButtons?.map((r) => r.metadata!.name)).toEqual( expectedButtonOrder ) }) it("handles log only update", () => { let prevLogStore = new LogStore() let prevState = { view: twoResourceView(), logStore: prevLogStore } let update = { view: { logList: logList(["line1", "line2"]), }, } let result = mergeAppUpdate<"view" | "logStore">(prevState as any, update) expect(result).toBe(null) }) })
the_stack